id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
24,300
google/closure-compiler
src/com/google/javascript/jscomp/NodeUtil.java
NodeUtil.getInvocationArgsCount
static int getInvocationArgsCount(Node invocation) { if (invocation.isTaggedTemplateLit()) { Iterable<Node> args = new TemplateArgsIterable(invocation.getLastChild()); return Iterables.size(args) + 1; } else { return invocation.getChildCount() - 1; } }
java
static int getInvocationArgsCount(Node invocation) { if (invocation.isTaggedTemplateLit()) { Iterable<Node> args = new TemplateArgsIterable(invocation.getLastChild()); return Iterables.size(args) + 1; } else { return invocation.getChildCount() - 1; } }
[ "static", "int", "getInvocationArgsCount", "(", "Node", "invocation", ")", "{", "if", "(", "invocation", ".", "isTaggedTemplateLit", "(", ")", ")", "{", "Iterable", "<", "Node", ">", "args", "=", "new", "TemplateArgsIterable", "(", "invocation", ".", "getLastChild", "(", ")", ")", ";", "return", "Iterables", ".", "size", "(", "args", ")", "+", "1", ";", "}", "else", "{", "return", "invocation", ".", "getChildCount", "(", ")", "-", "1", ";", "}", "}" ]
Returns the number of arguments in this invocation. For template literals it takes into account the implicit first argument of ITemplateArray
[ "Returns", "the", "number", "of", "arguments", "in", "this", "invocation", ".", "For", "template", "literals", "it", "takes", "into", "account", "the", "implicit", "first", "argument", "of", "ITemplateArray" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L5883-L5890
24,301
google/closure-compiler
src/com/google/javascript/jscomp/NodeUtil.java
NodeUtil.getAllVarsDeclaredInFunction
static void getAllVarsDeclaredInFunction( final Map<String, Var> nameVarMap, final List<Var> orderedVars, AbstractCompiler compiler, ScopeCreator scopeCreator, final Scope scope) { checkState(nameVarMap.isEmpty()); checkState(orderedVars.isEmpty()); checkState(scope.isFunctionScope(), scope); ScopedCallback finder = new ScopedCallback() { @Override public void enterScope(NodeTraversal t) { Scope currentScope = t.getScope(); for (Var v : currentScope.getVarIterable()) { nameVarMap.put(v.getName(), v); orderedVars.add(v); } } @Override public void exitScope(NodeTraversal t) {} @Override public final boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { // Don't enter any new functions return !n.isFunction() || n == scope.getRootNode(); } @Override public void visit(NodeTraversal t, Node n, Node parent) {} }; NodeTraversal t = new NodeTraversal(compiler, finder, scopeCreator); t.traverseAtScope(scope); }
java
static void getAllVarsDeclaredInFunction( final Map<String, Var> nameVarMap, final List<Var> orderedVars, AbstractCompiler compiler, ScopeCreator scopeCreator, final Scope scope) { checkState(nameVarMap.isEmpty()); checkState(orderedVars.isEmpty()); checkState(scope.isFunctionScope(), scope); ScopedCallback finder = new ScopedCallback() { @Override public void enterScope(NodeTraversal t) { Scope currentScope = t.getScope(); for (Var v : currentScope.getVarIterable()) { nameVarMap.put(v.getName(), v); orderedVars.add(v); } } @Override public void exitScope(NodeTraversal t) {} @Override public final boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { // Don't enter any new functions return !n.isFunction() || n == scope.getRootNode(); } @Override public void visit(NodeTraversal t, Node n, Node parent) {} }; NodeTraversal t = new NodeTraversal(compiler, finder, scopeCreator); t.traverseAtScope(scope); }
[ "static", "void", "getAllVarsDeclaredInFunction", "(", "final", "Map", "<", "String", ",", "Var", ">", "nameVarMap", ",", "final", "List", "<", "Var", ">", "orderedVars", ",", "AbstractCompiler", "compiler", ",", "ScopeCreator", "scopeCreator", ",", "final", "Scope", "scope", ")", "{", "checkState", "(", "nameVarMap", ".", "isEmpty", "(", ")", ")", ";", "checkState", "(", "orderedVars", ".", "isEmpty", "(", ")", ")", ";", "checkState", "(", "scope", ".", "isFunctionScope", "(", ")", ",", "scope", ")", ";", "ScopedCallback", "finder", "=", "new", "ScopedCallback", "(", ")", "{", "@", "Override", "public", "void", "enterScope", "(", "NodeTraversal", "t", ")", "{", "Scope", "currentScope", "=", "t", ".", "getScope", "(", ")", ";", "for", "(", "Var", "v", ":", "currentScope", ".", "getVarIterable", "(", ")", ")", "{", "nameVarMap", ".", "put", "(", "v", ".", "getName", "(", ")", ",", "v", ")", ";", "orderedVars", ".", "add", "(", "v", ")", ";", "}", "}", "@", "Override", "public", "void", "exitScope", "(", "NodeTraversal", "t", ")", "{", "}", "@", "Override", "public", "final", "boolean", "shouldTraverse", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "parent", ")", "{", "// Don't enter any new functions", "return", "!", "n", ".", "isFunction", "(", ")", "||", "n", "==", "scope", ".", "getRootNode", "(", ")", ";", "}", "@", "Override", "public", "void", "visit", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "parent", ")", "{", "}", "}", ";", "NodeTraversal", "t", "=", "new", "NodeTraversal", "(", "compiler", ",", "finder", ",", "scopeCreator", ")", ";", "t", ".", "traverseAtScope", "(", "scope", ")", ";", "}" ]
Records a mapping of names to vars of everything reachable in a function. Should only be called with a function scope. Does not enter new control flow areas aka embedded functions. @param nameVarMap an empty map that gets populated with the keys being variable names and values being variable objects @param orderedVars an empty list that gets populated with variable objects in the order that they appear in the fn
[ "Records", "a", "mapping", "of", "names", "to", "vars", "of", "everything", "reachable", "in", "a", "function", ".", "Should", "only", "be", "called", "with", "a", "function", "scope", ".", "Does", "not", "enter", "new", "control", "flow", "areas", "aka", "embedded", "functions", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L5935-L5972
24,302
google/closure-compiler
src/com/google/javascript/jscomp/NodeUtil.java
NodeUtil.isObjLitProperty
public static boolean isObjLitProperty(Node node) { return node.isStringKey() || node.isGetterDef() || node.isSetterDef() || node.isMemberFunctionDef() || node.isComputedProp(); }
java
public static boolean isObjLitProperty(Node node) { return node.isStringKey() || node.isGetterDef() || node.isSetterDef() || node.isMemberFunctionDef() || node.isComputedProp(); }
[ "public", "static", "boolean", "isObjLitProperty", "(", "Node", "node", ")", "{", "return", "node", ".", "isStringKey", "(", ")", "||", "node", ".", "isGetterDef", "(", ")", "||", "node", ".", "isSetterDef", "(", ")", "||", "node", ".", "isMemberFunctionDef", "(", ")", "||", "node", ".", "isComputedProp", "(", ")", ";", "}" ]
Returns true if the node is a property of an object literal.
[ "Returns", "true", "if", "the", "node", "is", "a", "property", "of", "an", "object", "literal", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L5975-L5981
24,303
google/closure-compiler
src/com/google/javascript/jscomp/NodeUtil.java
NodeUtil.addFeatureToScript
static void addFeatureToScript(Node scriptNode, Feature feature) { checkState(scriptNode.isScript(), scriptNode); FeatureSet currentFeatures = getFeatureSetOfScript(scriptNode); FeatureSet newFeatures = currentFeatures != null ? currentFeatures.with(feature) : FeatureSet.BARE_MINIMUM.with(feature); scriptNode.putProp(Node.FEATURE_SET, newFeatures); }
java
static void addFeatureToScript(Node scriptNode, Feature feature) { checkState(scriptNode.isScript(), scriptNode); FeatureSet currentFeatures = getFeatureSetOfScript(scriptNode); FeatureSet newFeatures = currentFeatures != null ? currentFeatures.with(feature) : FeatureSet.BARE_MINIMUM.with(feature); scriptNode.putProp(Node.FEATURE_SET, newFeatures); }
[ "static", "void", "addFeatureToScript", "(", "Node", "scriptNode", ",", "Feature", "feature", ")", "{", "checkState", "(", "scriptNode", ".", "isScript", "(", ")", ",", "scriptNode", ")", ";", "FeatureSet", "currentFeatures", "=", "getFeatureSetOfScript", "(", "scriptNode", ")", ";", "FeatureSet", "newFeatures", "=", "currentFeatures", "!=", "null", "?", "currentFeatures", ".", "with", "(", "feature", ")", ":", "FeatureSet", ".", "BARE_MINIMUM", ".", "with", "(", "feature", ")", ";", "scriptNode", ".", "putProp", "(", "Node", ".", "FEATURE_SET", ",", "newFeatures", ")", ";", "}" ]
Adds the given features to a SCRIPT node's FeatureSet property.
[ "Adds", "the", "given", "features", "to", "a", "SCRIPT", "node", "s", "FeatureSet", "property", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L6003-L6011
24,304
google/closure-compiler
src/com/google/javascript/jscomp/DestructuredTarget.java
DestructuredTarget.inferType
JSType inferType() { JSType inferredType = inferTypeWithoutUsingDefaultValue(); if (!inferredType.isUnknownType() && hasDefaultValue()) { JSType defaultValueType = getDefaultValue().getJSType(); if (defaultValueType == null) { defaultValueType = registry.getNativeType(JSTypeNative.UNKNOWN_TYPE); } // We effectively replace '|undefined" with '|typeOfDefaultValue' return registry.createUnionType(inferredType.restrictByNotUndefined(), defaultValueType); } else { return inferredType; } }
java
JSType inferType() { JSType inferredType = inferTypeWithoutUsingDefaultValue(); if (!inferredType.isUnknownType() && hasDefaultValue()) { JSType defaultValueType = getDefaultValue().getJSType(); if (defaultValueType == null) { defaultValueType = registry.getNativeType(JSTypeNative.UNKNOWN_TYPE); } // We effectively replace '|undefined" with '|typeOfDefaultValue' return registry.createUnionType(inferredType.restrictByNotUndefined(), defaultValueType); } else { return inferredType; } }
[ "JSType", "inferType", "(", ")", "{", "JSType", "inferredType", "=", "inferTypeWithoutUsingDefaultValue", "(", ")", ";", "if", "(", "!", "inferredType", ".", "isUnknownType", "(", ")", "&&", "hasDefaultValue", "(", ")", ")", "{", "JSType", "defaultValueType", "=", "getDefaultValue", "(", ")", ".", "getJSType", "(", ")", ";", "if", "(", "defaultValueType", "==", "null", ")", "{", "defaultValueType", "=", "registry", ".", "getNativeType", "(", "JSTypeNative", ".", "UNKNOWN_TYPE", ")", ";", "}", "// We effectively replace '|undefined\" with '|typeOfDefaultValue'", "return", "registry", ".", "createUnionType", "(", "inferredType", ".", "restrictByNotUndefined", "(", ")", ",", "defaultValueType", ")", ";", "}", "else", "{", "return", "inferredType", ";", "}", "}" ]
Infers the type of this target <p>e.g. given `a` in const {a = 3} = {}; returns `number`
[ "Infers", "the", "type", "of", "this", "target" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DestructuredTarget.java#L282-L294
24,305
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.process
@Override public void process(Node externs, Node root) { checkState(compiler.getLifeCycleStage().isNormalized()); if (!allowRemovalOfExternProperties) { referencedPropertyNames.addAll(compiler.getExternProperties()); } traverseAndRemoveUnusedReferences(root); // This pass may remove definitions of getter or setter properties. GatherGettersAndSetterProperties.update(compiler, externs, root); }
java
@Override public void process(Node externs, Node root) { checkState(compiler.getLifeCycleStage().isNormalized()); if (!allowRemovalOfExternProperties) { referencedPropertyNames.addAll(compiler.getExternProperties()); } traverseAndRemoveUnusedReferences(root); // This pass may remove definitions of getter or setter properties. GatherGettersAndSetterProperties.update(compiler, externs, root); }
[ "@", "Override", "public", "void", "process", "(", "Node", "externs", ",", "Node", "root", ")", "{", "checkState", "(", "compiler", ".", "getLifeCycleStage", "(", ")", ".", "isNormalized", "(", ")", ")", ";", "if", "(", "!", "allowRemovalOfExternProperties", ")", "{", "referencedPropertyNames", ".", "addAll", "(", "compiler", ".", "getExternProperties", "(", ")", ")", ";", "}", "traverseAndRemoveUnusedReferences", "(", "root", ")", ";", "// This pass may remove definitions of getter or setter properties.", "GatherGettersAndSetterProperties", ".", "update", "(", "compiler", ",", "externs", ",", "root", ")", ";", "}" ]
Traverses the root, removing all unused variables. Multiple traversals may occur to ensure all unused variables are removed.
[ "Traverses", "the", "root", "removing", "all", "unused", "variables", ".", "Multiple", "traversals", "may", "occur", "to", "ensure", "all", "unused", "variables", "are", "removed", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L242-L251
24,306
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.traverseAndRemoveUnusedReferences
private void traverseAndRemoveUnusedReferences(Node root) { // Create scope from parent of root node, which also has externs as a child, so we'll // have extern definitions in scope. Scope scope = scopeCreator.createScope(root.getParent(), null); if (!scope.hasSlot(NodeUtil.JSC_PROPERTY_NAME_FN)) { // TODO(b/70730762): Passes that add references to this should ensure it is declared. // NOTE: null input makes this an extern var. scope.declare( NodeUtil.JSC_PROPERTY_NAME_FN, /* no declaration node */ null, /* no input */ null); } worklist.add(new Continuation(root, scope)); while (!worklist.isEmpty()) { Continuation continuation = worklist.remove(); continuation.apply(); } removeUnreferencedVarsAndPolyfills(); removeIndependentlyRemovableProperties(); for (Scope fparamScope : allFunctionParamScopes) { removeUnreferencedFunctionArgs(fparamScope); } }
java
private void traverseAndRemoveUnusedReferences(Node root) { // Create scope from parent of root node, which also has externs as a child, so we'll // have extern definitions in scope. Scope scope = scopeCreator.createScope(root.getParent(), null); if (!scope.hasSlot(NodeUtil.JSC_PROPERTY_NAME_FN)) { // TODO(b/70730762): Passes that add references to this should ensure it is declared. // NOTE: null input makes this an extern var. scope.declare( NodeUtil.JSC_PROPERTY_NAME_FN, /* no declaration node */ null, /* no input */ null); } worklist.add(new Continuation(root, scope)); while (!worklist.isEmpty()) { Continuation continuation = worklist.remove(); continuation.apply(); } removeUnreferencedVarsAndPolyfills(); removeIndependentlyRemovableProperties(); for (Scope fparamScope : allFunctionParamScopes) { removeUnreferencedFunctionArgs(fparamScope); } }
[ "private", "void", "traverseAndRemoveUnusedReferences", "(", "Node", "root", ")", "{", "// Create scope from parent of root node, which also has externs as a child, so we'll", "// have extern definitions in scope.", "Scope", "scope", "=", "scopeCreator", ".", "createScope", "(", "root", ".", "getParent", "(", ")", ",", "null", ")", ";", "if", "(", "!", "scope", ".", "hasSlot", "(", "NodeUtil", ".", "JSC_PROPERTY_NAME_FN", ")", ")", "{", "// TODO(b/70730762): Passes that add references to this should ensure it is declared.", "// NOTE: null input makes this an extern var.", "scope", ".", "declare", "(", "NodeUtil", ".", "JSC_PROPERTY_NAME_FN", ",", "/* no declaration node */", "null", ",", "/* no input */", "null", ")", ";", "}", "worklist", ".", "add", "(", "new", "Continuation", "(", "root", ",", "scope", ")", ")", ";", "while", "(", "!", "worklist", ".", "isEmpty", "(", ")", ")", "{", "Continuation", "continuation", "=", "worklist", ".", "remove", "(", ")", ";", "continuation", ".", "apply", "(", ")", ";", "}", "removeUnreferencedVarsAndPolyfills", "(", ")", ";", "removeIndependentlyRemovableProperties", "(", ")", ";", "for", "(", "Scope", "fparamScope", ":", "allFunctionParamScopes", ")", "{", "removeUnreferencedFunctionArgs", "(", "fparamScope", ")", ";", "}", "}" ]
Traverses a node recursively. Call this once per pass.
[ "Traverses", "a", "node", "recursively", ".", "Call", "this", "once", "per", "pass", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L256-L277
24,307
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.traverseClass
private void traverseClass(Node classNode, Scope scope) { checkArgument(classNode.isClass()); if (NodeUtil.isClassDeclaration(classNode)) { traverseClassDeclaration(classNode, scope); } else { traverseClassExpression(classNode, scope); } }
java
private void traverseClass(Node classNode, Scope scope) { checkArgument(classNode.isClass()); if (NodeUtil.isClassDeclaration(classNode)) { traverseClassDeclaration(classNode, scope); } else { traverseClassExpression(classNode, scope); } }
[ "private", "void", "traverseClass", "(", "Node", "classNode", ",", "Scope", "scope", ")", "{", "checkArgument", "(", "classNode", ".", "isClass", "(", ")", ")", ";", "if", "(", "NodeUtil", ".", "isClassDeclaration", "(", "classNode", ")", ")", "{", "traverseClassDeclaration", "(", "classNode", ",", "scope", ")", ";", "}", "else", "{", "traverseClassExpression", "(", "classNode", ",", "scope", ")", ";", "}", "}" ]
Handle a class that is not the RHS child of an assignment or a variable declaration initializer. <p>For @param classNode @param scope
[ "Handle", "a", "class", "that", "is", "not", "the", "RHS", "child", "of", "an", "assignment", "or", "a", "variable", "declaration", "initializer", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L1198-L1205
24,308
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.traverseFunction
private void traverseFunction(Node function, Scope parentScope) { checkState(function.getChildCount() == 3, function); checkState(function.isFunction(), function); final Node paramlist = NodeUtil.getFunctionParameters(function); final Node body = function.getLastChild(); checkState(body.getNext() == null && body.isBlock(), body); // Checking the parameters Scope fparamScope = scopeCreator.createScope(function, parentScope); // Checking the function body Scope fbodyScope = scopeCreator.createScope(body, fparamScope); Node nameNode = function.getFirstChild(); if (!nameNode.getString().isEmpty()) { // var x = function funcName() {}; // make sure funcName gets into the varInfoMap so it will be considered for removal. VarInfo varInfo = traverseNameNode(nameNode, fparamScope); if (NodeUtil.isExpressionResultUsed(function)) { // var f = function g() {}; // The f is an alias for g, so g escapes from the scope where it is defined. varInfo.hasNonLocalOrNonLiteralValue = true; } } traverseChildren(paramlist, fparamScope); traverseChildren(body, fbodyScope); allFunctionParamScopes.add(fparamScope); }
java
private void traverseFunction(Node function, Scope parentScope) { checkState(function.getChildCount() == 3, function); checkState(function.isFunction(), function); final Node paramlist = NodeUtil.getFunctionParameters(function); final Node body = function.getLastChild(); checkState(body.getNext() == null && body.isBlock(), body); // Checking the parameters Scope fparamScope = scopeCreator.createScope(function, parentScope); // Checking the function body Scope fbodyScope = scopeCreator.createScope(body, fparamScope); Node nameNode = function.getFirstChild(); if (!nameNode.getString().isEmpty()) { // var x = function funcName() {}; // make sure funcName gets into the varInfoMap so it will be considered for removal. VarInfo varInfo = traverseNameNode(nameNode, fparamScope); if (NodeUtil.isExpressionResultUsed(function)) { // var f = function g() {}; // The f is an alias for g, so g escapes from the scope where it is defined. varInfo.hasNonLocalOrNonLiteralValue = true; } } traverseChildren(paramlist, fparamScope); traverseChildren(body, fbodyScope); allFunctionParamScopes.add(fparamScope); }
[ "private", "void", "traverseFunction", "(", "Node", "function", ",", "Scope", "parentScope", ")", "{", "checkState", "(", "function", ".", "getChildCount", "(", ")", "==", "3", ",", "function", ")", ";", "checkState", "(", "function", ".", "isFunction", "(", ")", ",", "function", ")", ";", "final", "Node", "paramlist", "=", "NodeUtil", ".", "getFunctionParameters", "(", "function", ")", ";", "final", "Node", "body", "=", "function", ".", "getLastChild", "(", ")", ";", "checkState", "(", "body", ".", "getNext", "(", ")", "==", "null", "&&", "body", ".", "isBlock", "(", ")", ",", "body", ")", ";", "// Checking the parameters", "Scope", "fparamScope", "=", "scopeCreator", ".", "createScope", "(", "function", ",", "parentScope", ")", ";", "// Checking the function body", "Scope", "fbodyScope", "=", "scopeCreator", ".", "createScope", "(", "body", ",", "fparamScope", ")", ";", "Node", "nameNode", "=", "function", ".", "getFirstChild", "(", ")", ";", "if", "(", "!", "nameNode", ".", "getString", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "// var x = function funcName() {};", "// make sure funcName gets into the varInfoMap so it will be considered for removal.", "VarInfo", "varInfo", "=", "traverseNameNode", "(", "nameNode", ",", "fparamScope", ")", ";", "if", "(", "NodeUtil", ".", "isExpressionResultUsed", "(", "function", ")", ")", "{", "// var f = function g() {};", "// The f is an alias for g, so g escapes from the scope where it is defined.", "varInfo", ".", "hasNonLocalOrNonLiteralValue", "=", "true", ";", "}", "}", "traverseChildren", "(", "paramlist", ",", "fparamScope", ")", ";", "traverseChildren", "(", "body", ",", "fbodyScope", ")", ";", "allFunctionParamScopes", ".", "add", "(", "fparamScope", ")", ";", "}" ]
Traverses a function ES6 scopes of a function include the parameter scope and the body scope of the function. Note that CATCH blocks also create a new scope, but only for the catch variable. Declarations within the block actually belong to the enclosing scope. Because we don't remove catch variables, there's no need to treat CATCH blocks differently like we do functions.
[ "Traverses", "a", "function" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L1295-L1325
24,309
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.removeUnreferencedFunctionArgs
private void removeUnreferencedFunctionArgs(Scope fparamScope) { // Notice that removing unreferenced function args breaks // Function.prototype.length. In advanced mode, we don't really care // about this: we consider "length" the equivalent of reflecting on // the function's lexical source. // // Rather than create a new option for this, we assume that if the user // is removing globals, then it's OK to remove unused function args. // // See http://blickly.github.io/closure-compiler-issues/#253 if (!removeGlobals) { return; } Node function = fparamScope.getRootNode(); checkState(function.isFunction()); if (NodeUtil.isGetOrSetKey(function.getParent())) { // The parameters object literal setters can not be removed. return; } Node argList = NodeUtil.getFunctionParameters(function); // Strip as many unreferenced args off the end of the function declaration as possible. maybeRemoveUnusedTrailingParameters(argList, fparamScope); // Mark any remaining unused parameters are unused to OptimizeParameters can try to remove // them. markUnusedParameters(argList, fparamScope); }
java
private void removeUnreferencedFunctionArgs(Scope fparamScope) { // Notice that removing unreferenced function args breaks // Function.prototype.length. In advanced mode, we don't really care // about this: we consider "length" the equivalent of reflecting on // the function's lexical source. // // Rather than create a new option for this, we assume that if the user // is removing globals, then it's OK to remove unused function args. // // See http://blickly.github.io/closure-compiler-issues/#253 if (!removeGlobals) { return; } Node function = fparamScope.getRootNode(); checkState(function.isFunction()); if (NodeUtil.isGetOrSetKey(function.getParent())) { // The parameters object literal setters can not be removed. return; } Node argList = NodeUtil.getFunctionParameters(function); // Strip as many unreferenced args off the end of the function declaration as possible. maybeRemoveUnusedTrailingParameters(argList, fparamScope); // Mark any remaining unused parameters are unused to OptimizeParameters can try to remove // them. markUnusedParameters(argList, fparamScope); }
[ "private", "void", "removeUnreferencedFunctionArgs", "(", "Scope", "fparamScope", ")", "{", "// Notice that removing unreferenced function args breaks", "// Function.prototype.length. In advanced mode, we don't really care", "// about this: we consider \"length\" the equivalent of reflecting on", "// the function's lexical source.", "//", "// Rather than create a new option for this, we assume that if the user", "// is removing globals, then it's OK to remove unused function args.", "//", "// See http://blickly.github.io/closure-compiler-issues/#253", "if", "(", "!", "removeGlobals", ")", "{", "return", ";", "}", "Node", "function", "=", "fparamScope", ".", "getRootNode", "(", ")", ";", "checkState", "(", "function", ".", "isFunction", "(", ")", ")", ";", "if", "(", "NodeUtil", ".", "isGetOrSetKey", "(", "function", ".", "getParent", "(", ")", ")", ")", "{", "// The parameters object literal setters can not be removed.", "return", ";", "}", "Node", "argList", "=", "NodeUtil", ".", "getFunctionParameters", "(", "function", ")", ";", "// Strip as many unreferenced args off the end of the function declaration as possible.", "maybeRemoveUnusedTrailingParameters", "(", "argList", ",", "fparamScope", ")", ";", "// Mark any remaining unused parameters are unused to OptimizeParameters can try to remove", "// them.", "markUnusedParameters", "(", "argList", ",", "fparamScope", ")", ";", "}" ]
Removes unreferenced arguments from a function declaration and when possible the function's callSites. @param fparamScope The function parameter
[ "Removes", "unreferenced", "arguments", "from", "a", "function", "declaration", "and", "when", "possible", "the", "function", "s", "callSites", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L1339-L1367
24,310
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.markUnusedParameters
private void markUnusedParameters(Node paramList, Scope fparamScope) { for (Node param = paramList.getFirstChild(); param != null; param = param.getNext()) { if (param.isUnusedParameter()) { continue; } Node lValue = nameOfParam(param); if (lValue == null) { continue; } VarInfo varInfo = traverseNameNode(lValue, fparamScope); if (varInfo.isRemovable()) { param.setUnusedParameter(true); compiler.reportChangeToEnclosingScope(paramList); } } }
java
private void markUnusedParameters(Node paramList, Scope fparamScope) { for (Node param = paramList.getFirstChild(); param != null; param = param.getNext()) { if (param.isUnusedParameter()) { continue; } Node lValue = nameOfParam(param); if (lValue == null) { continue; } VarInfo varInfo = traverseNameNode(lValue, fparamScope); if (varInfo.isRemovable()) { param.setUnusedParameter(true); compiler.reportChangeToEnclosingScope(paramList); } } }
[ "private", "void", "markUnusedParameters", "(", "Node", "paramList", ",", "Scope", "fparamScope", ")", "{", "for", "(", "Node", "param", "=", "paramList", ".", "getFirstChild", "(", ")", ";", "param", "!=", "null", ";", "param", "=", "param", ".", "getNext", "(", ")", ")", "{", "if", "(", "param", ".", "isUnusedParameter", "(", ")", ")", "{", "continue", ";", "}", "Node", "lValue", "=", "nameOfParam", "(", "param", ")", ";", "if", "(", "lValue", "==", "null", ")", "{", "continue", ";", "}", "VarInfo", "varInfo", "=", "traverseNameNode", "(", "lValue", ",", "fparamScope", ")", ";", "if", "(", "varInfo", ".", "isRemovable", "(", ")", ")", "{", "param", ".", "setUnusedParameter", "(", "true", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "paramList", ")", ";", "}", "}", "}" ]
Mark any remaining unused parameters as being unused so it can be used elsewhere. @param paramList list of function's parameters @param fparamScope
[ "Mark", "any", "remaining", "unused", "parameters", "as", "being", "unused", "so", "it", "can", "be", "used", "elsewhere", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L1415-L1432
24,311
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.maybeRemoveUnusedTrailingParameters
private void maybeRemoveUnusedTrailingParameters(Node argList, Scope fparamScope) { Node lastArg; while ((lastArg = argList.getLastChild()) != null) { Node lValue = lastArg; if (lastArg.isDefaultValue()) { lValue = lastArg.getFirstChild(); if (NodeUtil.mayHaveSideEffects(lastArg.getLastChild(), compiler)) { break; } } if (lValue.isRest()) { lValue = lValue.getFirstChild(); } if (lValue.isDestructuringPattern()) { if (lValue.hasChildren()) { // TODO(johnlenz): handle the case where there are no assignments. break; } else { // Remove empty destructuring patterns and their associated object literal assignment // if it exists and if the right hand side does not have side effects. Note, a // destructuring pattern with a "leftover" property key as in {a:{}} is not considered // empty in this case! NodeUtil.deleteNode(lastArg, compiler); continue; } } VarInfo varInfo = getVarInfo(getVarForNameNode(lValue, fparamScope)); if (varInfo.isRemovable()) { NodeUtil.deleteNode(lastArg, compiler); } else { break; } } }
java
private void maybeRemoveUnusedTrailingParameters(Node argList, Scope fparamScope) { Node lastArg; while ((lastArg = argList.getLastChild()) != null) { Node lValue = lastArg; if (lastArg.isDefaultValue()) { lValue = lastArg.getFirstChild(); if (NodeUtil.mayHaveSideEffects(lastArg.getLastChild(), compiler)) { break; } } if (lValue.isRest()) { lValue = lValue.getFirstChild(); } if (lValue.isDestructuringPattern()) { if (lValue.hasChildren()) { // TODO(johnlenz): handle the case where there are no assignments. break; } else { // Remove empty destructuring patterns and their associated object literal assignment // if it exists and if the right hand side does not have side effects. Note, a // destructuring pattern with a "leftover" property key as in {a:{}} is not considered // empty in this case! NodeUtil.deleteNode(lastArg, compiler); continue; } } VarInfo varInfo = getVarInfo(getVarForNameNode(lValue, fparamScope)); if (varInfo.isRemovable()) { NodeUtil.deleteNode(lastArg, compiler); } else { break; } } }
[ "private", "void", "maybeRemoveUnusedTrailingParameters", "(", "Node", "argList", ",", "Scope", "fparamScope", ")", "{", "Node", "lastArg", ";", "while", "(", "(", "lastArg", "=", "argList", ".", "getLastChild", "(", ")", ")", "!=", "null", ")", "{", "Node", "lValue", "=", "lastArg", ";", "if", "(", "lastArg", ".", "isDefaultValue", "(", ")", ")", "{", "lValue", "=", "lastArg", ".", "getFirstChild", "(", ")", ";", "if", "(", "NodeUtil", ".", "mayHaveSideEffects", "(", "lastArg", ".", "getLastChild", "(", ")", ",", "compiler", ")", ")", "{", "break", ";", "}", "}", "if", "(", "lValue", ".", "isRest", "(", ")", ")", "{", "lValue", "=", "lValue", ".", "getFirstChild", "(", ")", ";", "}", "if", "(", "lValue", ".", "isDestructuringPattern", "(", ")", ")", "{", "if", "(", "lValue", ".", "hasChildren", "(", ")", ")", "{", "// TODO(johnlenz): handle the case where there are no assignments.", "break", ";", "}", "else", "{", "// Remove empty destructuring patterns and their associated object literal assignment", "// if it exists and if the right hand side does not have side effects. Note, a", "// destructuring pattern with a \"leftover\" property key as in {a:{}} is not considered", "// empty in this case!", "NodeUtil", ".", "deleteNode", "(", "lastArg", ",", "compiler", ")", ";", "continue", ";", "}", "}", "VarInfo", "varInfo", "=", "getVarInfo", "(", "getVarForNameNode", "(", "lValue", ",", "fparamScope", ")", ")", ";", "if", "(", "varInfo", ".", "isRemovable", "(", ")", ")", "{", "NodeUtil", ".", "deleteNode", "(", "lastArg", ",", "compiler", ")", ";", "}", "else", "{", "break", ";", "}", "}", "}" ]
Strip as many unreferenced args off the end of the function declaration as possible. We start from the end of the function declaration because removing parameters from the middle of the param list could mess up the interpretation of parameters being sent over by any function calls. @param argList list of function's arguments @param fparamScope
[ "Strip", "as", "many", "unreferenced", "args", "off", "the", "end", "of", "the", "function", "declaration", "as", "possible", ".", "We", "start", "from", "the", "end", "of", "the", "function", "declaration", "because", "removing", "parameters", "from", "the", "middle", "of", "the", "param", "list", "could", "mess", "up", "the", "interpretation", "of", "parameters", "being", "sent", "over", "by", "any", "function", "calls", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L1443-L1479
24,312
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.removeUnreferencedVarsAndPolyfills
private void removeUnreferencedVarsAndPolyfills() { for (Entry<Var, VarInfo> entry : varInfoMap.entrySet()) { Var var = entry.getKey(); VarInfo varInfo = entry.getValue(); if (!varInfo.isRemovable()) { continue; } // Regardless of what happens to the original declaration, // we need to remove all assigns, because they may contain references // to other unreferenced variables. varInfo.removeAllRemovables(); Node nameNode = var.nameNode; Node toRemove = nameNode.getParent(); if (toRemove == null || alreadyRemoved(toRemove)) { // assignedVarInfo.removeAllRemovables () already removed it } else if (NodeUtil.isFunctionExpression(toRemove)) { // TODO(bradfordcsmith): Add a Removable for this case. if (!preserveFunctionExpressionNames) { Node fnNameNode = toRemove.getFirstChild(); compiler.reportChangeToEnclosingScope(fnNameNode); fnNameNode.setString(""); } } else { // Removables are not created for theses cases. // function foo(unused1 = someSideEffectingValue, ...unused2) {} // removeUnreferencedFunctionArgs() is responsible for removing these. // TODO(bradfordcsmith): handle parameter declarations with removables checkState( toRemove.isParamList() || (toRemove.getParent().isParamList() && (toRemove.isDefaultValue() || toRemove.isRest())), "unremoved code: %s", toRemove); } } Iterator<PolyfillInfo> iter = polyfills.values().iterator(); while (iter.hasNext()) { PolyfillInfo polyfill = iter.next(); if (polyfill.isRemovable) { polyfill.removable.remove(compiler); iter.remove(); } } }
java
private void removeUnreferencedVarsAndPolyfills() { for (Entry<Var, VarInfo> entry : varInfoMap.entrySet()) { Var var = entry.getKey(); VarInfo varInfo = entry.getValue(); if (!varInfo.isRemovable()) { continue; } // Regardless of what happens to the original declaration, // we need to remove all assigns, because they may contain references // to other unreferenced variables. varInfo.removeAllRemovables(); Node nameNode = var.nameNode; Node toRemove = nameNode.getParent(); if (toRemove == null || alreadyRemoved(toRemove)) { // assignedVarInfo.removeAllRemovables () already removed it } else if (NodeUtil.isFunctionExpression(toRemove)) { // TODO(bradfordcsmith): Add a Removable for this case. if (!preserveFunctionExpressionNames) { Node fnNameNode = toRemove.getFirstChild(); compiler.reportChangeToEnclosingScope(fnNameNode); fnNameNode.setString(""); } } else { // Removables are not created for theses cases. // function foo(unused1 = someSideEffectingValue, ...unused2) {} // removeUnreferencedFunctionArgs() is responsible for removing these. // TODO(bradfordcsmith): handle parameter declarations with removables checkState( toRemove.isParamList() || (toRemove.getParent().isParamList() && (toRemove.isDefaultValue() || toRemove.isRest())), "unremoved code: %s", toRemove); } } Iterator<PolyfillInfo> iter = polyfills.values().iterator(); while (iter.hasNext()) { PolyfillInfo polyfill = iter.next(); if (polyfill.isRemovable) { polyfill.removable.remove(compiler); iter.remove(); } } }
[ "private", "void", "removeUnreferencedVarsAndPolyfills", "(", ")", "{", "for", "(", "Entry", "<", "Var", ",", "VarInfo", ">", "entry", ":", "varInfoMap", ".", "entrySet", "(", ")", ")", "{", "Var", "var", "=", "entry", ".", "getKey", "(", ")", ";", "VarInfo", "varInfo", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "!", "varInfo", ".", "isRemovable", "(", ")", ")", "{", "continue", ";", "}", "// Regardless of what happens to the original declaration,", "// we need to remove all assigns, because they may contain references", "// to other unreferenced variables.", "varInfo", ".", "removeAllRemovables", "(", ")", ";", "Node", "nameNode", "=", "var", ".", "nameNode", ";", "Node", "toRemove", "=", "nameNode", ".", "getParent", "(", ")", ";", "if", "(", "toRemove", "==", "null", "||", "alreadyRemoved", "(", "toRemove", ")", ")", "{", "// assignedVarInfo.removeAllRemovables () already removed it", "}", "else", "if", "(", "NodeUtil", ".", "isFunctionExpression", "(", "toRemove", ")", ")", "{", "// TODO(bradfordcsmith): Add a Removable for this case.", "if", "(", "!", "preserveFunctionExpressionNames", ")", "{", "Node", "fnNameNode", "=", "toRemove", ".", "getFirstChild", "(", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "fnNameNode", ")", ";", "fnNameNode", ".", "setString", "(", "\"\"", ")", ";", "}", "}", "else", "{", "// Removables are not created for theses cases.", "// function foo(unused1 = someSideEffectingValue, ...unused2) {}", "// removeUnreferencedFunctionArgs() is responsible for removing these.", "// TODO(bradfordcsmith): handle parameter declarations with removables", "checkState", "(", "toRemove", ".", "isParamList", "(", ")", "||", "(", "toRemove", ".", "getParent", "(", ")", ".", "isParamList", "(", ")", "&&", "(", "toRemove", ".", "isDefaultValue", "(", ")", "||", "toRemove", ".", "isRest", "(", ")", ")", ")", ",", "\"unremoved code: %s\"", ",", "toRemove", ")", ";", "}", "}", "Iterator", "<", "PolyfillInfo", ">", "iter", "=", "polyfills", ".", "values", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "PolyfillInfo", "polyfill", "=", "iter", ".", "next", "(", ")", ";", "if", "(", "polyfill", ".", "isRemovable", ")", "{", "polyfill", ".", "removable", ".", "remove", "(", "compiler", ")", ";", "iter", ".", "remove", "(", ")", ";", "}", "}", "}" ]
Removes any vars in the scope that were not referenced. Removes any assignments to those variables as well.
[ "Removes", "any", "vars", "in", "the", "scope", "that", "were", "not", "referenced", ".", "Removes", "any", "assignments", "to", "those", "variables", "as", "well", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L1568-L1615
24,313
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.isLocalDefaultValueAssignment
private static boolean isLocalDefaultValueAssignment(Node targetNode, Node valueNode) { return valueNode.isOr() && targetNode.isQualifiedName() && valueNode.getFirstChild().isEquivalentTo(targetNode) && NodeUtil.evaluatesToLocalValue(valueNode.getLastChild()); }
java
private static boolean isLocalDefaultValueAssignment(Node targetNode, Node valueNode) { return valueNode.isOr() && targetNode.isQualifiedName() && valueNode.getFirstChild().isEquivalentTo(targetNode) && NodeUtil.evaluatesToLocalValue(valueNode.getLastChild()); }
[ "private", "static", "boolean", "isLocalDefaultValueAssignment", "(", "Node", "targetNode", ",", "Node", "valueNode", ")", "{", "return", "valueNode", ".", "isOr", "(", ")", "&&", "targetNode", ".", "isQualifiedName", "(", ")", "&&", "valueNode", ".", "getFirstChild", "(", ")", ".", "isEquivalentTo", "(", "targetNode", ")", "&&", "NodeUtil", ".", "evaluatesToLocalValue", "(", "valueNode", ".", "getLastChild", "(", ")", ")", ";", "}" ]
True if targetNode is a qualified name and the valueNode is of the form `targetQualifiedName || localValue`.
[ "True", "if", "targetNode", "is", "a", "qualified", "name", "and", "the", "valueNode", "is", "of", "the", "form", "targetQualifiedName", "||", "localValue", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L2292-L2297
24,314
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.createPolyfillInfo
private PolyfillInfo createPolyfillInfo(Node call, Scope scope, String name) { checkState(scope.isGlobal()); checkState(call.getParent().isExprResult()); // Make the removable and polyfill info. Add continuations for all arguments. RemovableBuilder builder = new RemovableBuilder(); for (Node n = call.getFirstChild().getNext(); n != null; n = n.getNext()) { builder.addContinuation(new Continuation(n, scope)); } Polyfill removable = builder.buildPolyfill(call.getParent()); int lastDot = name.lastIndexOf("."); if (lastDot < 0) { return new GlobalPolyfillInfo(removable, name); } String owner = name.substring(0, lastDot); String prop = name.substring(lastDot + 1); boolean typed = call.getJSType() != null; if (owner.endsWith(DOT_PROTOTYPE)) { owner = owner.substring(0, owner.length() - DOT_PROTOTYPE.length()); return new PrototypePropertyPolyfillInfo( removable, prop, typed ? compiler.getTypeRegistry().getType(scope, owner) : null); } ObjectType ownerInstanceType = typed ? ObjectType.cast(compiler.getTypeRegistry().getType(scope, owner)) : null; JSType ownerCtorType = ownerInstanceType != null ? ownerInstanceType.getConstructor() : null; return new StaticPropertyPolyfillInfo(removable, prop, ownerCtorType, owner); }
java
private PolyfillInfo createPolyfillInfo(Node call, Scope scope, String name) { checkState(scope.isGlobal()); checkState(call.getParent().isExprResult()); // Make the removable and polyfill info. Add continuations for all arguments. RemovableBuilder builder = new RemovableBuilder(); for (Node n = call.getFirstChild().getNext(); n != null; n = n.getNext()) { builder.addContinuation(new Continuation(n, scope)); } Polyfill removable = builder.buildPolyfill(call.getParent()); int lastDot = name.lastIndexOf("."); if (lastDot < 0) { return new GlobalPolyfillInfo(removable, name); } String owner = name.substring(0, lastDot); String prop = name.substring(lastDot + 1); boolean typed = call.getJSType() != null; if (owner.endsWith(DOT_PROTOTYPE)) { owner = owner.substring(0, owner.length() - DOT_PROTOTYPE.length()); return new PrototypePropertyPolyfillInfo( removable, prop, typed ? compiler.getTypeRegistry().getType(scope, owner) : null); } ObjectType ownerInstanceType = typed ? ObjectType.cast(compiler.getTypeRegistry().getType(scope, owner)) : null; JSType ownerCtorType = ownerInstanceType != null ? ownerInstanceType.getConstructor() : null; return new StaticPropertyPolyfillInfo(removable, prop, ownerCtorType, owner); }
[ "private", "PolyfillInfo", "createPolyfillInfo", "(", "Node", "call", ",", "Scope", "scope", ",", "String", "name", ")", "{", "checkState", "(", "scope", ".", "isGlobal", "(", ")", ")", ";", "checkState", "(", "call", ".", "getParent", "(", ")", ".", "isExprResult", "(", ")", ")", ";", "// Make the removable and polyfill info. Add continuations for all arguments.", "RemovableBuilder", "builder", "=", "new", "RemovableBuilder", "(", ")", ";", "for", "(", "Node", "n", "=", "call", ".", "getFirstChild", "(", ")", ".", "getNext", "(", ")", ";", "n", "!=", "null", ";", "n", "=", "n", ".", "getNext", "(", ")", ")", "{", "builder", ".", "addContinuation", "(", "new", "Continuation", "(", "n", ",", "scope", ")", ")", ";", "}", "Polyfill", "removable", "=", "builder", ".", "buildPolyfill", "(", "call", ".", "getParent", "(", ")", ")", ";", "int", "lastDot", "=", "name", ".", "lastIndexOf", "(", "\".\"", ")", ";", "if", "(", "lastDot", "<", "0", ")", "{", "return", "new", "GlobalPolyfillInfo", "(", "removable", ",", "name", ")", ";", "}", "String", "owner", "=", "name", ".", "substring", "(", "0", ",", "lastDot", ")", ";", "String", "prop", "=", "name", ".", "substring", "(", "lastDot", "+", "1", ")", ";", "boolean", "typed", "=", "call", ".", "getJSType", "(", ")", "!=", "null", ";", "if", "(", "owner", ".", "endsWith", "(", "DOT_PROTOTYPE", ")", ")", "{", "owner", "=", "owner", ".", "substring", "(", "0", ",", "owner", ".", "length", "(", ")", "-", "DOT_PROTOTYPE", ".", "length", "(", ")", ")", ";", "return", "new", "PrototypePropertyPolyfillInfo", "(", "removable", ",", "prop", ",", "typed", "?", "compiler", ".", "getTypeRegistry", "(", ")", ".", "getType", "(", "scope", ",", "owner", ")", ":", "null", ")", ";", "}", "ObjectType", "ownerInstanceType", "=", "typed", "?", "ObjectType", ".", "cast", "(", "compiler", ".", "getTypeRegistry", "(", ")", ".", "getType", "(", "scope", ",", "owner", ")", ")", ":", "null", ";", "JSType", "ownerCtorType", "=", "ownerInstanceType", "!=", "null", "?", "ownerInstanceType", ".", "getConstructor", "(", ")", ":", "null", ";", "return", "new", "StaticPropertyPolyfillInfo", "(", "removable", ",", "prop", ",", "ownerCtorType", ",", "owner", ")", ";", "}" ]
Makes a new PolyfillInfo, including the correct Removable. Parses the name to determine whether this is a global, static, or prototype polyfill.
[ "Makes", "a", "new", "PolyfillInfo", "including", "the", "correct", "Removable", ".", "Parses", "the", "name", "to", "determine", "whether", "this", "is", "a", "global", "static", "or", "prototype", "polyfill", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L2625-L2650
24,315
google/closure-compiler
src/com/google/javascript/jscomp/gwt/client/JsfileParser.java
JsfileParser.assoc
private static Set<JsArray<String>> assoc() { return new TreeSet<>(Ordering.<String>natural().lexicographical().onResultOf(JsArray::asList)); }
java
private static Set<JsArray<String>> assoc() { return new TreeSet<>(Ordering.<String>natural().lexicographical().onResultOf(JsArray::asList)); }
[ "private", "static", "Set", "<", "JsArray", "<", "String", ">", ">", "assoc", "(", ")", "{", "return", "new", "TreeSet", "<>", "(", "Ordering", ".", "<", "String", ">", "natural", "(", ")", ".", "lexicographical", "(", ")", ".", "onResultOf", "(", "JsArray", "::", "asList", ")", ")", ";", "}" ]
Returns an associative multimap.
[ "Returns", "an", "associative", "multimap", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/gwt/client/JsfileParser.java#L406-L408
24,316
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.isNominalConstructor
public final boolean isNominalConstructor() { if (isConstructor() || isInterface()) { FunctionType fn = toMaybeFunctionType(); if (fn == null) { return false; } // Programmer-defined constructors will have a link // back to the original function in the source tree. // Structural constructors will not. if (fn.getSource() != null) { return true; } // Native constructors are always nominal. return fn.isNativeObjectType(); } return false; }
java
public final boolean isNominalConstructor() { if (isConstructor() || isInterface()) { FunctionType fn = toMaybeFunctionType(); if (fn == null) { return false; } // Programmer-defined constructors will have a link // back to the original function in the source tree. // Structural constructors will not. if (fn.getSource() != null) { return true; } // Native constructors are always nominal. return fn.isNativeObjectType(); } return false; }
[ "public", "final", "boolean", "isNominalConstructor", "(", ")", "{", "if", "(", "isConstructor", "(", ")", "||", "isInterface", "(", ")", ")", "{", "FunctionType", "fn", "=", "toMaybeFunctionType", "(", ")", ";", "if", "(", "fn", "==", "null", ")", "{", "return", "false", ";", "}", "// Programmer-defined constructors will have a link", "// back to the original function in the source tree.", "// Structural constructors will not.", "if", "(", "fn", ".", "getSource", "(", ")", "!=", "null", ")", "{", "return", "true", ";", "}", "// Native constructors are always nominal.", "return", "fn", ".", "isNativeObjectType", "(", ")", ";", "}", "return", "false", ";", "}" ]
Whether this type is the original constructor of a nominal type. Does not include structural constructors.
[ "Whether", "this", "type", "is", "the", "original", "constructor", "of", "a", "nominal", "type", ".", "Does", "not", "include", "structural", "constructors", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L598-L616
24,317
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.deepestResolvedTypeNameOf
@Nullable private String deepestResolvedTypeNameOf(ObjectType objType) { if (!objType.isResolved() || !(objType instanceof ProxyObjectType)) { return objType.getReferenceName(); } ObjectType internal = ((ProxyObjectType) objType).getReferencedObjTypeInternal(); return (internal != null && internal.isNominalType()) ? deepestResolvedTypeNameOf(internal) : null; }
java
@Nullable private String deepestResolvedTypeNameOf(ObjectType objType) { if (!objType.isResolved() || !(objType instanceof ProxyObjectType)) { return objType.getReferenceName(); } ObjectType internal = ((ProxyObjectType) objType).getReferencedObjTypeInternal(); return (internal != null && internal.isNominalType()) ? deepestResolvedTypeNameOf(internal) : null; }
[ "@", "Nullable", "private", "String", "deepestResolvedTypeNameOf", "(", "ObjectType", "objType", ")", "{", "if", "(", "!", "objType", ".", "isResolved", "(", ")", "||", "!", "(", "objType", "instanceof", "ProxyObjectType", ")", ")", "{", "return", "objType", ".", "getReferenceName", "(", ")", ";", "}", "ObjectType", "internal", "=", "(", "(", "ProxyObjectType", ")", "objType", ")", ".", "getReferencedObjTypeInternal", "(", ")", ";", "return", "(", "internal", "!=", "null", "&&", "internal", ".", "isNominalType", "(", ")", ")", "?", "deepestResolvedTypeNameOf", "(", "internal", ")", ":", "null", ";", "}" ]
Named types may be proxies of concrete types.
[ "Named", "types", "may", "be", "proxies", "of", "concrete", "types", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L792-L802
24,318
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.findPropertyTypeWithoutConsideringTemplateTypes
@ForOverride @Nullable protected JSType findPropertyTypeWithoutConsideringTemplateTypes(String propertyName) { ObjectType autoboxObjType = ObjectType.cast(autoboxesTo()); if (autoboxObjType != null) { return autoboxObjType.findPropertyType(propertyName); } return null; }
java
@ForOverride @Nullable protected JSType findPropertyTypeWithoutConsideringTemplateTypes(String propertyName) { ObjectType autoboxObjType = ObjectType.cast(autoboxesTo()); if (autoboxObjType != null) { return autoboxObjType.findPropertyType(propertyName); } return null; }
[ "@", "ForOverride", "@", "Nullable", "protected", "JSType", "findPropertyTypeWithoutConsideringTemplateTypes", "(", "String", "propertyName", ")", "{", "ObjectType", "autoboxObjType", "=", "ObjectType", ".", "cast", "(", "autoboxesTo", "(", ")", ")", ";", "if", "(", "autoboxObjType", "!=", "null", ")", "{", "return", "autoboxObjType", ".", "findPropertyType", "(", "propertyName", ")", ";", "}", "return", "null", ";", "}" ]
Looks up a property on this type, but without properly replacing any templates in the result. <p>Subclasses can override this if they need more complicated logic for property lookup than just autoboxing to an object. <p>This is only for use by {@code findPropertyType(JSType)}. Call that method instead if you need to lookup a property on a random JSType
[ "Looks", "up", "a", "property", "on", "this", "type", "but", "without", "properly", "replacing", "any", "templates", "in", "the", "result", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L910-L918
24,319
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.autobox
public JSType autobox() { JSType restricted = restrictByNotNullOrUndefined(); JSType autobox = restricted.autoboxesTo(); return autobox == null ? restricted : autobox; }
java
public JSType autobox() { JSType restricted = restrictByNotNullOrUndefined(); JSType autobox = restricted.autoboxesTo(); return autobox == null ? restricted : autobox; }
[ "public", "JSType", "autobox", "(", ")", "{", "JSType", "restricted", "=", "restrictByNotNullOrUndefined", "(", ")", ";", "JSType", "autobox", "=", "restricted", ".", "autoboxesTo", "(", ")", ";", "return", "autobox", "==", "null", "?", "restricted", ":", "autobox", ";", "}" ]
Dereferences a type for property access. Filters null/undefined and autoboxes the resulting type. Never returns null.
[ "Dereferences", "a", "type", "for", "property", "access", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L980-L984
24,320
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.getLeastSupertype
@SuppressWarnings("AmbiguousMethodReference") static JSType getLeastSupertype(JSType thisType, JSType thatType) { boolean areEquivalent = thisType.isEquivalentTo(thatType); return areEquivalent ? thisType : filterNoResolvedType( thisType.registry.createUnionType(thisType, thatType)); }
java
@SuppressWarnings("AmbiguousMethodReference") static JSType getLeastSupertype(JSType thisType, JSType thatType) { boolean areEquivalent = thisType.isEquivalentTo(thatType); return areEquivalent ? thisType : filterNoResolvedType( thisType.registry.createUnionType(thisType, thatType)); }
[ "@", "SuppressWarnings", "(", "\"AmbiguousMethodReference\"", ")", "static", "JSType", "getLeastSupertype", "(", "JSType", "thisType", ",", "JSType", "thatType", ")", "{", "boolean", "areEquivalent", "=", "thisType", ".", "isEquivalentTo", "(", "thatType", ")", ";", "return", "areEquivalent", "?", "thisType", ":", "filterNoResolvedType", "(", "thisType", ".", "registry", ".", "createUnionType", "(", "thisType", ",", "thatType", ")", ")", ";", "}" ]
A generic implementation meant to be used as a helper for common getLeastSupertype implementations.
[ "A", "generic", "implementation", "meant", "to", "be", "used", "as", "a", "helper", "for", "common", "getLeastSupertype", "implementations", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L1168-L1174
24,321
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.isSubtypeHelper
static boolean isSubtypeHelper(JSType thisType, JSType thatType, ImplCache implicitImplCache, SubtypingMode subtypingMode) { checkNotNull(thisType); // unknown if (thatType.isUnknownType()) { return true; } // all type if (thatType.isAllType()) { return true; } // equality if (thisType.isEquivalentTo(thatType, implicitImplCache.isStructuralTyping())) { return true; } // unions if (thatType.isUnionType()) { UnionType union = thatType.toMaybeUnionType(); // use an indexed for-loop to avoid allocations ImmutableList<JSType> alternates = union.getAlternates(); for (int i = 0; i < alternates.size(); i++) { JSType element = alternates.get(i); if (thisType.isSubtype(element, implicitImplCache, subtypingMode)) { return true; } } return false; } if (subtypingMode == SubtypingMode.IGNORE_NULL_UNDEFINED && (thisType.isNullType() || thisType.isVoidType())) { return true; } // TemplateTypeMaps. This check only returns false if the TemplateTypeMaps // are not equivalent. TemplateTypeMap thisTypeParams = thisType.getTemplateTypeMap(); TemplateTypeMap thatTypeParams = thatType.getTemplateTypeMap(); boolean templateMatch = true; if (isBivariantType(thatType)) { // Array and Object are exempt from template type invariance; their // template types maps are bivariant. That is they are considered // a match if either ObjectElementKey values are subtypes of the // other. TemplateType key = thisType.registry.getObjectElementKey(); JSType thisElement = thisTypeParams.getResolvedTemplateType(key); JSType thatElement = thatTypeParams.getResolvedTemplateType(key); templateMatch = thisElement.isSubtype(thatElement, implicitImplCache, subtypingMode) || thatElement.isSubtype(thisElement, implicitImplCache, subtypingMode); } else if (isIThenableSubtype(thatType)) { // NOTE: special case IThenable subclass (Promise, etc). These classes are expected to be // covariant. // Also note that this ignores any additional template type arguments that might be defined // on subtypes. If we expand this to other types, a more correct solution will be needed. TemplateType key = thisType.registry.getThenableValueKey(); JSType thisElement = thisTypeParams.getResolvedTemplateType(key); JSType thatElement = thatTypeParams.getResolvedTemplateType(key); templateMatch = thisElement.isSubtype(thatElement, implicitImplCache, subtypingMode); } else { templateMatch = thisTypeParams.checkEquivalenceHelper( thatTypeParams, EquivalenceMethod.INVARIANT, subtypingMode); } if (!templateMatch) { return false; } // If the super type is a structural type, then we can't safely remove a templatized type // (since it might affect the types of the properties) if (implicitImplCache.shouldMatchStructurally(thisType, thatType)) { return thisType .toMaybeObjectType() .isStructuralSubtype(thatType.toMaybeObjectType(), implicitImplCache, subtypingMode); } // Templatized types. For nominal types, the above check guarantees TemplateTypeMap // equivalence; check if the base type is a subtype. if (thisType.isTemplatizedType()) { return thisType .toMaybeTemplatizedType() .getReferencedType() .isSubtype(thatType, implicitImplCache, subtypingMode); } // proxy types if (thatType instanceof ProxyObjectType) { return thisType.isSubtype( ((ProxyObjectType) thatType).getReferencedTypeInternal(), implicitImplCache, subtypingMode); } return false; }
java
static boolean isSubtypeHelper(JSType thisType, JSType thatType, ImplCache implicitImplCache, SubtypingMode subtypingMode) { checkNotNull(thisType); // unknown if (thatType.isUnknownType()) { return true; } // all type if (thatType.isAllType()) { return true; } // equality if (thisType.isEquivalentTo(thatType, implicitImplCache.isStructuralTyping())) { return true; } // unions if (thatType.isUnionType()) { UnionType union = thatType.toMaybeUnionType(); // use an indexed for-loop to avoid allocations ImmutableList<JSType> alternates = union.getAlternates(); for (int i = 0; i < alternates.size(); i++) { JSType element = alternates.get(i); if (thisType.isSubtype(element, implicitImplCache, subtypingMode)) { return true; } } return false; } if (subtypingMode == SubtypingMode.IGNORE_NULL_UNDEFINED && (thisType.isNullType() || thisType.isVoidType())) { return true; } // TemplateTypeMaps. This check only returns false if the TemplateTypeMaps // are not equivalent. TemplateTypeMap thisTypeParams = thisType.getTemplateTypeMap(); TemplateTypeMap thatTypeParams = thatType.getTemplateTypeMap(); boolean templateMatch = true; if (isBivariantType(thatType)) { // Array and Object are exempt from template type invariance; their // template types maps are bivariant. That is they are considered // a match if either ObjectElementKey values are subtypes of the // other. TemplateType key = thisType.registry.getObjectElementKey(); JSType thisElement = thisTypeParams.getResolvedTemplateType(key); JSType thatElement = thatTypeParams.getResolvedTemplateType(key); templateMatch = thisElement.isSubtype(thatElement, implicitImplCache, subtypingMode) || thatElement.isSubtype(thisElement, implicitImplCache, subtypingMode); } else if (isIThenableSubtype(thatType)) { // NOTE: special case IThenable subclass (Promise, etc). These classes are expected to be // covariant. // Also note that this ignores any additional template type arguments that might be defined // on subtypes. If we expand this to other types, a more correct solution will be needed. TemplateType key = thisType.registry.getThenableValueKey(); JSType thisElement = thisTypeParams.getResolvedTemplateType(key); JSType thatElement = thatTypeParams.getResolvedTemplateType(key); templateMatch = thisElement.isSubtype(thatElement, implicitImplCache, subtypingMode); } else { templateMatch = thisTypeParams.checkEquivalenceHelper( thatTypeParams, EquivalenceMethod.INVARIANT, subtypingMode); } if (!templateMatch) { return false; } // If the super type is a structural type, then we can't safely remove a templatized type // (since it might affect the types of the properties) if (implicitImplCache.shouldMatchStructurally(thisType, thatType)) { return thisType .toMaybeObjectType() .isStructuralSubtype(thatType.toMaybeObjectType(), implicitImplCache, subtypingMode); } // Templatized types. For nominal types, the above check guarantees TemplateTypeMap // equivalence; check if the base type is a subtype. if (thisType.isTemplatizedType()) { return thisType .toMaybeTemplatizedType() .getReferencedType() .isSubtype(thatType, implicitImplCache, subtypingMode); } // proxy types if (thatType instanceof ProxyObjectType) { return thisType.isSubtype( ((ProxyObjectType) thatType).getReferencedTypeInternal(), implicitImplCache, subtypingMode); } return false; }
[ "static", "boolean", "isSubtypeHelper", "(", "JSType", "thisType", ",", "JSType", "thatType", ",", "ImplCache", "implicitImplCache", ",", "SubtypingMode", "subtypingMode", ")", "{", "checkNotNull", "(", "thisType", ")", ";", "// unknown", "if", "(", "thatType", ".", "isUnknownType", "(", ")", ")", "{", "return", "true", ";", "}", "// all type", "if", "(", "thatType", ".", "isAllType", "(", ")", ")", "{", "return", "true", ";", "}", "// equality", "if", "(", "thisType", ".", "isEquivalentTo", "(", "thatType", ",", "implicitImplCache", ".", "isStructuralTyping", "(", ")", ")", ")", "{", "return", "true", ";", "}", "// unions", "if", "(", "thatType", ".", "isUnionType", "(", ")", ")", "{", "UnionType", "union", "=", "thatType", ".", "toMaybeUnionType", "(", ")", ";", "// use an indexed for-loop to avoid allocations", "ImmutableList", "<", "JSType", ">", "alternates", "=", "union", ".", "getAlternates", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "alternates", ".", "size", "(", ")", ";", "i", "++", ")", "{", "JSType", "element", "=", "alternates", ".", "get", "(", "i", ")", ";", "if", "(", "thisType", ".", "isSubtype", "(", "element", ",", "implicitImplCache", ",", "subtypingMode", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "if", "(", "subtypingMode", "==", "SubtypingMode", ".", "IGNORE_NULL_UNDEFINED", "&&", "(", "thisType", ".", "isNullType", "(", ")", "||", "thisType", ".", "isVoidType", "(", ")", ")", ")", "{", "return", "true", ";", "}", "// TemplateTypeMaps. This check only returns false if the TemplateTypeMaps", "// are not equivalent.", "TemplateTypeMap", "thisTypeParams", "=", "thisType", ".", "getTemplateTypeMap", "(", ")", ";", "TemplateTypeMap", "thatTypeParams", "=", "thatType", ".", "getTemplateTypeMap", "(", ")", ";", "boolean", "templateMatch", "=", "true", ";", "if", "(", "isBivariantType", "(", "thatType", ")", ")", "{", "// Array and Object are exempt from template type invariance; their", "// template types maps are bivariant. That is they are considered", "// a match if either ObjectElementKey values are subtypes of the", "// other.", "TemplateType", "key", "=", "thisType", ".", "registry", ".", "getObjectElementKey", "(", ")", ";", "JSType", "thisElement", "=", "thisTypeParams", ".", "getResolvedTemplateType", "(", "key", ")", ";", "JSType", "thatElement", "=", "thatTypeParams", ".", "getResolvedTemplateType", "(", "key", ")", ";", "templateMatch", "=", "thisElement", ".", "isSubtype", "(", "thatElement", ",", "implicitImplCache", ",", "subtypingMode", ")", "||", "thatElement", ".", "isSubtype", "(", "thisElement", ",", "implicitImplCache", ",", "subtypingMode", ")", ";", "}", "else", "if", "(", "isIThenableSubtype", "(", "thatType", ")", ")", "{", "// NOTE: special case IThenable subclass (Promise, etc). These classes are expected to be", "// covariant.", "// Also note that this ignores any additional template type arguments that might be defined", "// on subtypes. If we expand this to other types, a more correct solution will be needed.", "TemplateType", "key", "=", "thisType", ".", "registry", ".", "getThenableValueKey", "(", ")", ";", "JSType", "thisElement", "=", "thisTypeParams", ".", "getResolvedTemplateType", "(", "key", ")", ";", "JSType", "thatElement", "=", "thatTypeParams", ".", "getResolvedTemplateType", "(", "key", ")", ";", "templateMatch", "=", "thisElement", ".", "isSubtype", "(", "thatElement", ",", "implicitImplCache", ",", "subtypingMode", ")", ";", "}", "else", "{", "templateMatch", "=", "thisTypeParams", ".", "checkEquivalenceHelper", "(", "thatTypeParams", ",", "EquivalenceMethod", ".", "INVARIANT", ",", "subtypingMode", ")", ";", "}", "if", "(", "!", "templateMatch", ")", "{", "return", "false", ";", "}", "// If the super type is a structural type, then we can't safely remove a templatized type", "// (since it might affect the types of the properties)", "if", "(", "implicitImplCache", ".", "shouldMatchStructurally", "(", "thisType", ",", "thatType", ")", ")", "{", "return", "thisType", ".", "toMaybeObjectType", "(", ")", ".", "isStructuralSubtype", "(", "thatType", ".", "toMaybeObjectType", "(", ")", ",", "implicitImplCache", ",", "subtypingMode", ")", ";", "}", "// Templatized types. For nominal types, the above check guarantees TemplateTypeMap", "// equivalence; check if the base type is a subtype.", "if", "(", "thisType", ".", "isTemplatizedType", "(", ")", ")", "{", "return", "thisType", ".", "toMaybeTemplatizedType", "(", ")", ".", "getReferencedType", "(", ")", ".", "isSubtype", "(", "thatType", ",", "implicitImplCache", ",", "subtypingMode", ")", ";", "}", "// proxy types", "if", "(", "thatType", "instanceof", "ProxyObjectType", ")", "{", "return", "thisType", ".", "isSubtype", "(", "(", "(", "ProxyObjectType", ")", "thatType", ")", ".", "getReferencedTypeInternal", "(", ")", ",", "implicitImplCache", ",", "subtypingMode", ")", ";", "}", "return", "false", ";", "}" ]
if implicitImplCache is null, there is no structural interface matching
[ "if", "implicitImplCache", "is", "null", "there", "is", "no", "structural", "interface", "matching" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L1540-L1632
24,322
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.isBivariantType
static boolean isBivariantType(JSType type) { ObjectType objType = type.toObjectType(); return objType != null // && objType.isNativeObjectType() && BIVARIANT_TYPES.contains(objType.getReferenceName()); }
java
static boolean isBivariantType(JSType type) { ObjectType objType = type.toObjectType(); return objType != null // && objType.isNativeObjectType() && BIVARIANT_TYPES.contains(objType.getReferenceName()); }
[ "static", "boolean", "isBivariantType", "(", "JSType", "type", ")", "{", "ObjectType", "objType", "=", "type", ".", "toObjectType", "(", ")", ";", "return", "objType", "!=", "null", "// && objType.isNativeObjectType()", "&&", "BIVARIANT_TYPES", ".", "contains", "(", "objType", ".", "getReferenceName", "(", ")", ")", ";", "}" ]
Determines if the supplied type should be checked as a bivariant templatized type rather the standard invariant templatized type rules.
[ "Determines", "if", "the", "supplied", "type", "should", "be", "checked", "as", "a", "bivariant", "templatized", "type", "rather", "the", "standard", "invariant", "templatized", "type", "rules", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L1639-L1644
24,323
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.isIThenableSubtype
static boolean isIThenableSubtype(JSType type) { if (type.isTemplatizedType()) { TemplatizedType ttype = type.toMaybeTemplatizedType(); return ttype.getTemplateTypeMap().hasTemplateKey(ttype.registry.getThenableValueKey()); } return false; }
java
static boolean isIThenableSubtype(JSType type) { if (type.isTemplatizedType()) { TemplatizedType ttype = type.toMaybeTemplatizedType(); return ttype.getTemplateTypeMap().hasTemplateKey(ttype.registry.getThenableValueKey()); } return false; }
[ "static", "boolean", "isIThenableSubtype", "(", "JSType", "type", ")", "{", "if", "(", "type", ".", "isTemplatizedType", "(", ")", ")", "{", "TemplatizedType", "ttype", "=", "type", ".", "toMaybeTemplatizedType", "(", ")", ";", "return", "ttype", ".", "getTemplateTypeMap", "(", ")", ".", "hasTemplateKey", "(", "ttype", ".", "registry", ".", "getThenableValueKey", "(", ")", ")", ";", "}", "return", "false", ";", "}" ]
Determines if the specified type is exempt from standard invariant templatized typing rules.
[ "Determines", "if", "the", "specified", "type", "is", "exempt", "from", "standard", "invariant", "templatized", "typing", "rules", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L1649-L1655
24,324
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.resolve
public final JSType resolve(ErrorReporter reporter) { if (resolved) { if (resolveResult == null) { // If there is a circular definition, keep the NamedType around. This is not ideal, // but is still a better type than unknown. return this; } return resolveResult; } resolved = true; resolveResult = resolveInternal(reporter); resolveResult.setResolvedTypeInternal(resolveResult); return resolveResult; }
java
public final JSType resolve(ErrorReporter reporter) { if (resolved) { if (resolveResult == null) { // If there is a circular definition, keep the NamedType around. This is not ideal, // but is still a better type than unknown. return this; } return resolveResult; } resolved = true; resolveResult = resolveInternal(reporter); resolveResult.setResolvedTypeInternal(resolveResult); return resolveResult; }
[ "public", "final", "JSType", "resolve", "(", "ErrorReporter", "reporter", ")", "{", "if", "(", "resolved", ")", "{", "if", "(", "resolveResult", "==", "null", ")", "{", "// If there is a circular definition, keep the NamedType around. This is not ideal,", "// but is still a better type than unknown.", "return", "this", ";", "}", "return", "resolveResult", ";", "}", "resolved", "=", "true", ";", "resolveResult", "=", "resolveInternal", "(", "reporter", ")", ";", "resolveResult", ".", "setResolvedTypeInternal", "(", "resolveResult", ")", ";", "return", "resolveResult", ";", "}" ]
Resolve this type in the given scope. The returned value must be equal to {@code this}, as defined by {@link #isEquivalentTo}. It may or may not be the same object. This method may modify the internal state of {@code this}, as long as it does so in a way that preserves Object equality. For efficiency, we should only resolve a type once per compilation job. For incremental compilations, one compilation job may need the artifacts from a previous generation, so we will eventually need a generational flag instead of a boolean one.
[ "Resolve", "this", "type", "in", "the", "given", "scope", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L1684-L1697
24,325
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.safeResolve
static final JSType safeResolve( JSType type, ErrorReporter reporter) { return type == null ? null : type.resolve(reporter); }
java
static final JSType safeResolve( JSType type, ErrorReporter reporter) { return type == null ? null : type.resolve(reporter); }
[ "static", "final", "JSType", "safeResolve", "(", "JSType", "type", ",", "ErrorReporter", "reporter", ")", "{", "return", "type", "==", "null", "?", "null", ":", "type", ".", "resolve", "(", "reporter", ")", ";", "}" ]
A null-safe resolve. @see #resolve
[ "A", "null", "-", "safe", "resolve", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L1733-L1736
24,326
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.toAnnotationString
public final String toAnnotationString(Nullability nullability) { return nullability == Nullability.EXPLICIT ? appendAsNonNull(new StringBuilder(), true).toString() : appendTo(new StringBuilder(), true).toString(); }
java
public final String toAnnotationString(Nullability nullability) { return nullability == Nullability.EXPLICIT ? appendAsNonNull(new StringBuilder(), true).toString() : appendTo(new StringBuilder(), true).toString(); }
[ "public", "final", "String", "toAnnotationString", "(", "Nullability", "nullability", ")", "{", "return", "nullability", "==", "Nullability", ".", "EXPLICIT", "?", "appendAsNonNull", "(", "new", "StringBuilder", "(", ")", ",", "true", ")", ".", "toString", "(", ")", ":", "appendTo", "(", "new", "StringBuilder", "(", ")", ",", "true", ")", ".", "toString", "(", ")", ";", "}" ]
Don't call from this package; use appendAsNonNull instead.
[ "Don", "t", "call", "from", "this", "package", ";", "use", "appendAsNonNull", "instead", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L1779-L1783
24,327
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.getInstantiatedTypeArgument
public JSType getInstantiatedTypeArgument(JSType supertype) { TemplateType templateType = Iterables.getOnlyElement(supertype.getTemplateTypeMap().getTemplateKeys()); return getTemplateTypeMap().getResolvedTemplateType(templateType); }
java
public JSType getInstantiatedTypeArgument(JSType supertype) { TemplateType templateType = Iterables.getOnlyElement(supertype.getTemplateTypeMap().getTemplateKeys()); return getTemplateTypeMap().getResolvedTemplateType(templateType); }
[ "public", "JSType", "getInstantiatedTypeArgument", "(", "JSType", "supertype", ")", "{", "TemplateType", "templateType", "=", "Iterables", ".", "getOnlyElement", "(", "supertype", ".", "getTemplateTypeMap", "(", ")", ".", "getTemplateKeys", "(", ")", ")", ";", "return", "getTemplateTypeMap", "(", ")", ".", "getResolvedTemplateType", "(", "templateType", ")", ";", "}" ]
Returns the template type argument in this type's map corresponding to the supertype's template parameter, or the UNKNOWN_TYPE if the supertype template key is not present. <p>Note: this only supports arguments that have a singleton list of template keys, and will throw an exception for arguments with zero or multiple or template keys.
[ "Returns", "the", "template", "type", "argument", "in", "this", "type", "s", "map", "corresponding", "to", "the", "supertype", "s", "template", "parameter", "or", "the", "UNKNOWN_TYPE", "if", "the", "supertype", "template", "key", "is", "not", "present", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L2108-L2112
24,328
google/closure-compiler
src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java
AnalyzePrototypeProperties.getAllNameInfo
public Collection<NameInfo> getAllNameInfo() { List<NameInfo> result = new ArrayList<>(propertyNameInfo.values()); result.addAll(varNameInfo.values()); return result; }
java
public Collection<NameInfo> getAllNameInfo() { List<NameInfo> result = new ArrayList<>(propertyNameInfo.values()); result.addAll(varNameInfo.values()); return result; }
[ "public", "Collection", "<", "NameInfo", ">", "getAllNameInfo", "(", ")", "{", "List", "<", "NameInfo", ">", "result", "=", "new", "ArrayList", "<>", "(", "propertyNameInfo", ".", "values", "(", ")", ")", ";", "result", ".", "addAll", "(", "varNameInfo", ".", "values", "(", ")", ")", ";", "return", "result", ";", "}" ]
Returns information on all prototype properties.
[ "Returns", "information", "on", "all", "prototype", "properties", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java#L162-L166
24,329
google/closure-compiler
src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java
AnalyzePrototypeProperties.getNameInfoForName
private NameInfo getNameInfoForName(String name, SymbolType type) { Map<String, NameInfo> map = type == PROPERTY ? propertyNameInfo : varNameInfo; if (map.containsKey(name)) { return map.get(name); } else { NameInfo nameInfo = new NameInfo(name); map.put(name, nameInfo); symbolGraph.createNode(nameInfo); return nameInfo; } }
java
private NameInfo getNameInfoForName(String name, SymbolType type) { Map<String, NameInfo> map = type == PROPERTY ? propertyNameInfo : varNameInfo; if (map.containsKey(name)) { return map.get(name); } else { NameInfo nameInfo = new NameInfo(name); map.put(name, nameInfo); symbolGraph.createNode(nameInfo); return nameInfo; } }
[ "private", "NameInfo", "getNameInfoForName", "(", "String", "name", ",", "SymbolType", "type", ")", "{", "Map", "<", "String", ",", "NameInfo", ">", "map", "=", "type", "==", "PROPERTY", "?", "propertyNameInfo", ":", "varNameInfo", ";", "if", "(", "map", ".", "containsKey", "(", "name", ")", ")", "{", "return", "map", ".", "get", "(", "name", ")", ";", "}", "else", "{", "NameInfo", "nameInfo", "=", "new", "NameInfo", "(", "name", ")", ";", "map", ".", "put", "(", "name", ",", "nameInfo", ")", ";", "symbolGraph", ".", "createNode", "(", "nameInfo", ")", ";", "return", "nameInfo", ";", "}", "}" ]
Gets the name info for the property or variable of a given name, and creates a new one if necessary. @param name The name of the symbol. @param type The type of symbol.
[ "Gets", "the", "name", "info", "for", "the", "property", "or", "variable", "of", "a", "given", "name", "and", "creates", "a", "new", "one", "if", "necessary", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java#L175-L185
24,330
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.trackMessage
private void trackMessage( NodeTraversal t, JsMessage message, String msgName, Node msgNode, boolean isUnnamedMessage) { if (!isUnnamedMessage) { MessageLocation location = new MessageLocation(message, msgNode); messageNames.put(msgName, location); } else { Var var = t.getScope().getVar(msgName); if (var != null) { unnamedMessages.put(var, message); } } }
java
private void trackMessage( NodeTraversal t, JsMessage message, String msgName, Node msgNode, boolean isUnnamedMessage) { if (!isUnnamedMessage) { MessageLocation location = new MessageLocation(message, msgNode); messageNames.put(msgName, location); } else { Var var = t.getScope().getVar(msgName); if (var != null) { unnamedMessages.put(var, message); } } }
[ "private", "void", "trackMessage", "(", "NodeTraversal", "t", ",", "JsMessage", "message", ",", "String", "msgName", ",", "Node", "msgNode", ",", "boolean", "isUnnamedMessage", ")", "{", "if", "(", "!", "isUnnamedMessage", ")", "{", "MessageLocation", "location", "=", "new", "MessageLocation", "(", "message", ",", "msgNode", ")", ";", "messageNames", ".", "put", "(", "msgName", ",", "location", ")", ";", "}", "else", "{", "Var", "var", "=", "t", ".", "getScope", "(", ")", ".", "getVar", "(", "msgName", ")", ";", "if", "(", "var", "!=", "null", ")", "{", "unnamedMessages", ".", "put", "(", "var", ",", "message", ")", ";", "}", "}", "}" ]
Track a message for later retrieval. This is used for tracking duplicates, and for figuring out message fallback. Not all message types are trackable, because that would require a more sophisticated analysis. e.g., function f(s) { s.MSG_UNNAMED_X = 'Some untrackable message'; }
[ "Track", "a", "message", "for", "later", "retrieval", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L346-L358
24,331
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.isLegalMessageVarAlias
private static boolean isLegalMessageVarAlias(Node msgNode, String msgKey) { if (msgNode.isGetProp() && msgNode.isQualifiedName() && msgNode.getLastChild().getString().equals(msgKey)) { // Case: `foo.Thing.MSG_EXAMPLE = bar.OtherThing.MSG_EXAMPLE;` // // This kind of construct is created by Es6ToEs3ClassSideInheritance. Just ignore it; the // message will have already been extracted from the base class. return true; } if (msgNode.getGrandparent().isObjectPattern() && msgNode.isName()) { // Case: `var {MSG_HELLO} = x; // // It's a destructuring import. Ignore it if the name is the same. We compare against the // original name if possible because in modules, the NAME node will be rewritten with a // module-qualified name (e.g. `var {MSG_HELLO: goog$module$my$module_MSG_HELLO} = x;`). String aliasName = (msgNode.getOriginalName() != null) ? msgNode.getOriginalName() : msgNode.getString(); if (aliasName.equals(msgKey)) { return true; } } // TODO(nickreid): Should `var MSG_HELLO = x.MSG_HELLO;` also be allowed? return false; }
java
private static boolean isLegalMessageVarAlias(Node msgNode, String msgKey) { if (msgNode.isGetProp() && msgNode.isQualifiedName() && msgNode.getLastChild().getString().equals(msgKey)) { // Case: `foo.Thing.MSG_EXAMPLE = bar.OtherThing.MSG_EXAMPLE;` // // This kind of construct is created by Es6ToEs3ClassSideInheritance. Just ignore it; the // message will have already been extracted from the base class. return true; } if (msgNode.getGrandparent().isObjectPattern() && msgNode.isName()) { // Case: `var {MSG_HELLO} = x; // // It's a destructuring import. Ignore it if the name is the same. We compare against the // original name if possible because in modules, the NAME node will be rewritten with a // module-qualified name (e.g. `var {MSG_HELLO: goog$module$my$module_MSG_HELLO} = x;`). String aliasName = (msgNode.getOriginalName() != null) ? msgNode.getOriginalName() : msgNode.getString(); if (aliasName.equals(msgKey)) { return true; } } // TODO(nickreid): Should `var MSG_HELLO = x.MSG_HELLO;` also be allowed? return false; }
[ "private", "static", "boolean", "isLegalMessageVarAlias", "(", "Node", "msgNode", ",", "String", "msgKey", ")", "{", "if", "(", "msgNode", ".", "isGetProp", "(", ")", "&&", "msgNode", ".", "isQualifiedName", "(", ")", "&&", "msgNode", ".", "getLastChild", "(", ")", ".", "getString", "(", ")", ".", "equals", "(", "msgKey", ")", ")", "{", "// Case: `foo.Thing.MSG_EXAMPLE = bar.OtherThing.MSG_EXAMPLE;`", "//", "// This kind of construct is created by Es6ToEs3ClassSideInheritance. Just ignore it; the", "// message will have already been extracted from the base class.", "return", "true", ";", "}", "if", "(", "msgNode", ".", "getGrandparent", "(", ")", ".", "isObjectPattern", "(", ")", "&&", "msgNode", ".", "isName", "(", ")", ")", "{", "// Case: `var {MSG_HELLO} = x;", "//", "// It's a destructuring import. Ignore it if the name is the same. We compare against the", "// original name if possible because in modules, the NAME node will be rewritten with a", "// module-qualified name (e.g. `var {MSG_HELLO: goog$module$my$module_MSG_HELLO} = x;`).", "String", "aliasName", "=", "(", "msgNode", ".", "getOriginalName", "(", ")", "!=", "null", ")", "?", "msgNode", ".", "getOriginalName", "(", ")", ":", "msgNode", ".", "getString", "(", ")", ";", "if", "(", "aliasName", ".", "equals", "(", "msgKey", ")", ")", "{", "return", "true", ";", "}", "}", "// TODO(nickreid): Should `var MSG_HELLO = x.MSG_HELLO;` also be allowed?", "return", "false", ";", "}" ]
Defines any special cases that are exceptions to what would otherwise be illegal message assignments. <p>These exceptions are generally due to the pass being designed before new syntax was introduced.
[ "Defines", "any", "special", "cases", "that", "are", "exceptions", "to", "what", "would", "otherwise", "be", "illegal", "message", "assignments", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L367-L394
24,332
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.getTrackedMessage
private JsMessage getTrackedMessage(NodeTraversal t, String msgName) { boolean isUnnamedMessage = isUnnamedMessageName(msgName); if (!isUnnamedMessage) { MessageLocation location = messageNames.get(msgName); return location == null ? null : location.message; } else { Var var = t.getScope().getVar(msgName); if (var != null) { return unnamedMessages.get(var); } } return null; }
java
private JsMessage getTrackedMessage(NodeTraversal t, String msgName) { boolean isUnnamedMessage = isUnnamedMessageName(msgName); if (!isUnnamedMessage) { MessageLocation location = messageNames.get(msgName); return location == null ? null : location.message; } else { Var var = t.getScope().getVar(msgName); if (var != null) { return unnamedMessages.get(var); } } return null; }
[ "private", "JsMessage", "getTrackedMessage", "(", "NodeTraversal", "t", ",", "String", "msgName", ")", "{", "boolean", "isUnnamedMessage", "=", "isUnnamedMessageName", "(", "msgName", ")", ";", "if", "(", "!", "isUnnamedMessage", ")", "{", "MessageLocation", "location", "=", "messageNames", ".", "get", "(", "msgName", ")", ";", "return", "location", "==", "null", "?", "null", ":", "location", ".", "message", ";", "}", "else", "{", "Var", "var", "=", "t", ".", "getScope", "(", ")", ".", "getVar", "(", "msgName", ")", ";", "if", "(", "var", "!=", "null", ")", "{", "return", "unnamedMessages", ".", "get", "(", "var", ")", ";", "}", "}", "return", "null", ";", "}" ]
Get a previously tracked message.
[ "Get", "a", "previously", "tracked", "message", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L397-L409
24,333
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.checkIfMessageDuplicated
private void checkIfMessageDuplicated(String msgName, Node msgNode) { if (messageNames.containsKey(msgName)) { MessageLocation location = messageNames.get(msgName); compiler.report(JSError.make(msgNode, MESSAGE_DUPLICATE_KEY, msgName, location.messageNode.getSourceFileName(), Integer.toString(location.messageNode.getLineno()))); } }
java
private void checkIfMessageDuplicated(String msgName, Node msgNode) { if (messageNames.containsKey(msgName)) { MessageLocation location = messageNames.get(msgName); compiler.report(JSError.make(msgNode, MESSAGE_DUPLICATE_KEY, msgName, location.messageNode.getSourceFileName(), Integer.toString(location.messageNode.getLineno()))); } }
[ "private", "void", "checkIfMessageDuplicated", "(", "String", "msgName", ",", "Node", "msgNode", ")", "{", "if", "(", "messageNames", ".", "containsKey", "(", "msgName", ")", ")", "{", "MessageLocation", "location", "=", "messageNames", ".", "get", "(", "msgName", ")", ";", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "msgNode", ",", "MESSAGE_DUPLICATE_KEY", ",", "msgName", ",", "location", ".", "messageNode", ".", "getSourceFileName", "(", ")", ",", "Integer", ".", "toString", "(", "location", ".", "messageNode", ".", "getLineno", "(", ")", ")", ")", ")", ";", "}", "}" ]
Checks if message already processed. If so - it generates 'message duplicated' compiler error. @param msgName the name of the message @param msgNode the node that represents JS message
[ "Checks", "if", "message", "already", "processed", ".", "If", "so", "-", "it", "generates", "message", "duplicated", "compiler", "error", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L418-L425
24,334
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.maybeInitMetaDataFromJsDoc
private static boolean maybeInitMetaDataFromJsDoc(Builder builder, Node node) { boolean messageHasDesc = false; JSDocInfo info = node.getJSDocInfo(); if (info != null) { String desc = info.getDescription(); if (desc != null) { builder.setDesc(desc); messageHasDesc = true; } if (info.isHidden()) { builder.setIsHidden(true); } if (info.getMeaning() != null) { builder.setMeaning(info.getMeaning()); } } return messageHasDesc; }
java
private static boolean maybeInitMetaDataFromJsDoc(Builder builder, Node node) { boolean messageHasDesc = false; JSDocInfo info = node.getJSDocInfo(); if (info != null) { String desc = info.getDescription(); if (desc != null) { builder.setDesc(desc); messageHasDesc = true; } if (info.isHidden()) { builder.setIsHidden(true); } if (info.getMeaning() != null) { builder.setMeaning(info.getMeaning()); } } return messageHasDesc; }
[ "private", "static", "boolean", "maybeInitMetaDataFromJsDoc", "(", "Builder", "builder", ",", "Node", "node", ")", "{", "boolean", "messageHasDesc", "=", "false", ";", "JSDocInfo", "info", "=", "node", ".", "getJSDocInfo", "(", ")", ";", "if", "(", "info", "!=", "null", ")", "{", "String", "desc", "=", "info", ".", "getDescription", "(", ")", ";", "if", "(", "desc", "!=", "null", ")", "{", "builder", ".", "setDesc", "(", "desc", ")", ";", "messageHasDesc", "=", "true", ";", "}", "if", "(", "info", ".", "isHidden", "(", ")", ")", "{", "builder", ".", "setIsHidden", "(", "true", ")", ";", "}", "if", "(", "info", ".", "getMeaning", "(", ")", "!=", "null", ")", "{", "builder", ".", "setMeaning", "(", "info", ".", "getMeaning", "(", ")", ")", ";", "}", "}", "return", "messageHasDesc", ";", "}" ]
Initializes the meta data in a message builder given a node that may contain JsDoc properties. @param builder the message builder whose meta data will be initialized @param node the node with the message's JSDoc properties @return true if message has JsDoc with valid description in @desc annotation
[ "Initializes", "the", "meta", "data", "in", "a", "message", "builder", "given", "a", "node", "that", "may", "contain", "JsDoc", "properties", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L550-L568
24,335
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.extractFromReturnDescendant
private static void extractFromReturnDescendant(Builder builder, Node node) throws MalformedException { switch (node.getToken()) { case STRING: builder.appendStringPart(node.getString()); break; case NAME: builder.appendPlaceholderReference(node.getString()); break; case ADD: for (Node child : node.children()) { extractFromReturnDescendant(builder, child); } break; default: throw new MalformedException( "STRING, NAME, or ADD node expected; found: " + node.getToken(), node); } }
java
private static void extractFromReturnDescendant(Builder builder, Node node) throws MalformedException { switch (node.getToken()) { case STRING: builder.appendStringPart(node.getString()); break; case NAME: builder.appendPlaceholderReference(node.getString()); break; case ADD: for (Node child : node.children()) { extractFromReturnDescendant(builder, child); } break; default: throw new MalformedException( "STRING, NAME, or ADD node expected; found: " + node.getToken(), node); } }
[ "private", "static", "void", "extractFromReturnDescendant", "(", "Builder", "builder", ",", "Node", "node", ")", "throws", "MalformedException", "{", "switch", "(", "node", ".", "getToken", "(", ")", ")", "{", "case", "STRING", ":", "builder", ".", "appendStringPart", "(", "node", ".", "getString", "(", ")", ")", ";", "break", ";", "case", "NAME", ":", "builder", ".", "appendPlaceholderReference", "(", "node", ".", "getString", "(", ")", ")", ";", "break", ";", "case", "ADD", ":", "for", "(", "Node", "child", ":", "node", ".", "children", "(", ")", ")", "{", "extractFromReturnDescendant", "(", "builder", ",", "child", ")", ";", "}", "break", ";", "default", ":", "throw", "new", "MalformedException", "(", "\"STRING, NAME, or ADD node expected; found: \"", "+", "node", ".", "getToken", "(", ")", ",", "node", ")", ";", "}", "}" ]
Appends value parts to the message builder by traversing the descendants of the given RETURN node. @param builder the message builder @param node the node from where we extract a message @throws MalformedException if the parsed message is invalid
[ "Appends", "value", "parts", "to", "the", "message", "builder", "by", "traversing", "the", "descendants", "of", "the", "given", "RETURN", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L688-L707
24,336
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.parseMessageTextNode
private static void parseMessageTextNode(Builder builder, Node node) throws MalformedException { String value = extractStringFromStringExprNode(node); while (true) { int phBegin = value.indexOf(PH_JS_PREFIX); if (phBegin < 0) { // Just a string literal builder.appendStringPart(value); return; } else { if (phBegin > 0) { // A string literal followed by a placeholder builder.appendStringPart(value.substring(0, phBegin)); } // A placeholder. Find where it ends int phEnd = value.indexOf(PH_JS_SUFFIX, phBegin); if (phEnd < 0) { throw new MalformedException( "Placeholder incorrectly formatted in: " + builder.getKey(), node); } String phName = value.substring(phBegin + PH_JS_PREFIX.length(), phEnd); builder.appendPlaceholderReference(phName); int nextPos = phEnd + PH_JS_SUFFIX.length(); if (nextPos < value.length()) { // Iterate on the rest of the message value value = value.substring(nextPos); } else { // The message is parsed return; } } } }
java
private static void parseMessageTextNode(Builder builder, Node node) throws MalformedException { String value = extractStringFromStringExprNode(node); while (true) { int phBegin = value.indexOf(PH_JS_PREFIX); if (phBegin < 0) { // Just a string literal builder.appendStringPart(value); return; } else { if (phBegin > 0) { // A string literal followed by a placeholder builder.appendStringPart(value.substring(0, phBegin)); } // A placeholder. Find where it ends int phEnd = value.indexOf(PH_JS_SUFFIX, phBegin); if (phEnd < 0) { throw new MalformedException( "Placeholder incorrectly formatted in: " + builder.getKey(), node); } String phName = value.substring(phBegin + PH_JS_PREFIX.length(), phEnd); builder.appendPlaceholderReference(phName); int nextPos = phEnd + PH_JS_SUFFIX.length(); if (nextPos < value.length()) { // Iterate on the rest of the message value value = value.substring(nextPos); } else { // The message is parsed return; } } } }
[ "private", "static", "void", "parseMessageTextNode", "(", "Builder", "builder", ",", "Node", "node", ")", "throws", "MalformedException", "{", "String", "value", "=", "extractStringFromStringExprNode", "(", "node", ")", ";", "while", "(", "true", ")", "{", "int", "phBegin", "=", "value", ".", "indexOf", "(", "PH_JS_PREFIX", ")", ";", "if", "(", "phBegin", "<", "0", ")", "{", "// Just a string literal", "builder", ".", "appendStringPart", "(", "value", ")", ";", "return", ";", "}", "else", "{", "if", "(", "phBegin", ">", "0", ")", "{", "// A string literal followed by a placeholder", "builder", ".", "appendStringPart", "(", "value", ".", "substring", "(", "0", ",", "phBegin", ")", ")", ";", "}", "// A placeholder. Find where it ends", "int", "phEnd", "=", "value", ".", "indexOf", "(", "PH_JS_SUFFIX", ",", "phBegin", ")", ";", "if", "(", "phEnd", "<", "0", ")", "{", "throw", "new", "MalformedException", "(", "\"Placeholder incorrectly formatted in: \"", "+", "builder", ".", "getKey", "(", ")", ",", "node", ")", ";", "}", "String", "phName", "=", "value", ".", "substring", "(", "phBegin", "+", "PH_JS_PREFIX", ".", "length", "(", ")", ",", "phEnd", ")", ";", "builder", ".", "appendPlaceholderReference", "(", "phName", ")", ";", "int", "nextPos", "=", "phEnd", "+", "PH_JS_SUFFIX", ".", "length", "(", ")", ";", "if", "(", "nextPos", "<", "value", ".", "length", "(", ")", ")", "{", "// Iterate on the rest of the message value", "value", "=", "value", ".", "substring", "(", "nextPos", ")", ";", "}", "else", "{", "// The message is parsed", "return", ";", "}", "}", "}", "}" ]
Appends the message parts in a JS message value extracted from the given text node. @param builder the JS message builder to append parts to @param node the node with string literal that contains the message text @throws MalformedException if {@code value} contains a reference to an unregistered placeholder
[ "Appends", "the", "message", "parts", "in", "a", "JS", "message", "value", "extracted", "from", "the", "given", "text", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L817-L854
24,337
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.visitFallbackFunctionCall
private void visitFallbackFunctionCall(NodeTraversal t, Node call) { // Check to make sure the function call looks like: // goog.getMsgWithFallback(MSG_1, MSG_2); if (call.getChildCount() != 3 || !call.getSecondChild().isName() || !call.getLastChild().isName()) { compiler.report(JSError.make(call, BAD_FALLBACK_SYNTAX)); return; } Node firstArg = call.getSecondChild(); String name = firstArg.getOriginalName(); if (name == null) { name = firstArg.getString(); } JsMessage firstMessage = getTrackedMessage(t, name); if (firstMessage == null) { compiler.report(JSError.make(firstArg, FALLBACK_ARG_ERROR, name)); return; } Node secondArg = firstArg.getNext(); name = secondArg.getOriginalName(); if (name == null) { name = secondArg.getString(); } JsMessage secondMessage = getTrackedMessage(t, name); if (secondMessage == null) { compiler.report(JSError.make(secondArg, FALLBACK_ARG_ERROR, name)); return; } processMessageFallback(call, firstMessage, secondMessage); }
java
private void visitFallbackFunctionCall(NodeTraversal t, Node call) { // Check to make sure the function call looks like: // goog.getMsgWithFallback(MSG_1, MSG_2); if (call.getChildCount() != 3 || !call.getSecondChild().isName() || !call.getLastChild().isName()) { compiler.report(JSError.make(call, BAD_FALLBACK_SYNTAX)); return; } Node firstArg = call.getSecondChild(); String name = firstArg.getOriginalName(); if (name == null) { name = firstArg.getString(); } JsMessage firstMessage = getTrackedMessage(t, name); if (firstMessage == null) { compiler.report(JSError.make(firstArg, FALLBACK_ARG_ERROR, name)); return; } Node secondArg = firstArg.getNext(); name = secondArg.getOriginalName(); if (name == null) { name = secondArg.getString(); } JsMessage secondMessage = getTrackedMessage(t, name); if (secondMessage == null) { compiler.report(JSError.make(secondArg, FALLBACK_ARG_ERROR, name)); return; } processMessageFallback(call, firstMessage, secondMessage); }
[ "private", "void", "visitFallbackFunctionCall", "(", "NodeTraversal", "t", ",", "Node", "call", ")", "{", "// Check to make sure the function call looks like:", "// goog.getMsgWithFallback(MSG_1, MSG_2);", "if", "(", "call", ".", "getChildCount", "(", ")", "!=", "3", "||", "!", "call", ".", "getSecondChild", "(", ")", ".", "isName", "(", ")", "||", "!", "call", ".", "getLastChild", "(", ")", ".", "isName", "(", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "call", ",", "BAD_FALLBACK_SYNTAX", ")", ")", ";", "return", ";", "}", "Node", "firstArg", "=", "call", ".", "getSecondChild", "(", ")", ";", "String", "name", "=", "firstArg", ".", "getOriginalName", "(", ")", ";", "if", "(", "name", "==", "null", ")", "{", "name", "=", "firstArg", ".", "getString", "(", ")", ";", "}", "JsMessage", "firstMessage", "=", "getTrackedMessage", "(", "t", ",", "name", ")", ";", "if", "(", "firstMessage", "==", "null", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "firstArg", ",", "FALLBACK_ARG_ERROR", ",", "name", ")", ")", ";", "return", ";", "}", "Node", "secondArg", "=", "firstArg", ".", "getNext", "(", ")", ";", "name", "=", "secondArg", ".", "getOriginalName", "(", ")", ";", "if", "(", "name", "==", "null", ")", "{", "name", "=", "secondArg", ".", "getString", "(", ")", ";", "}", "JsMessage", "secondMessage", "=", "getTrackedMessage", "(", "t", ",", "name", ")", ";", "if", "(", "secondMessage", "==", "null", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "secondArg", ",", "FALLBACK_ARG_ERROR", ",", "name", ")", ")", ";", "return", ";", "}", "processMessageFallback", "(", "call", ",", "firstMessage", ",", "secondMessage", ")", ";", "}" ]
Visit a call to goog.getMsgWithFallback.
[ "Visit", "a", "call", "to", "goog", ".", "getMsgWithFallback", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L857-L890
24,338
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.isMessageName
boolean isMessageName(String identifier, boolean isNewStyleMessage) { return identifier.startsWith(MSG_PREFIX) && (style == JsMessage.Style.CLOSURE || isNewStyleMessage || !identifier.endsWith(DESC_SUFFIX)); }
java
boolean isMessageName(String identifier, boolean isNewStyleMessage) { return identifier.startsWith(MSG_PREFIX) && (style == JsMessage.Style.CLOSURE || isNewStyleMessage || !identifier.endsWith(DESC_SUFFIX)); }
[ "boolean", "isMessageName", "(", "String", "identifier", ",", "boolean", "isNewStyleMessage", ")", "{", "return", "identifier", ".", "startsWith", "(", "MSG_PREFIX", ")", "&&", "(", "style", "==", "JsMessage", ".", "Style", ".", "CLOSURE", "||", "isNewStyleMessage", "||", "!", "identifier", ".", "endsWith", "(", "DESC_SUFFIX", ")", ")", ";", "}" ]
Returns whether the given JS identifier is a valid JS message name.
[ "Returns", "whether", "the", "given", "JS", "identifier", "is", "a", "valid", "JS", "message", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L922-L926
24,339
google/closure-compiler
src/com/google/javascript/jscomp/DiagnosticGroup.java
DiagnosticGroup.forType
public static synchronized DiagnosticGroup forType(DiagnosticType type) { singletons.computeIfAbsent(type, DiagnosticGroup::new); return singletons.get(type); }
java
public static synchronized DiagnosticGroup forType(DiagnosticType type) { singletons.computeIfAbsent(type, DiagnosticGroup::new); return singletons.get(type); }
[ "public", "static", "synchronized", "DiagnosticGroup", "forType", "(", "DiagnosticType", "type", ")", "{", "singletons", ".", "computeIfAbsent", "(", "type", ",", "DiagnosticGroup", "::", "new", ")", ";", "return", "singletons", ".", "get", "(", "type", ")", ";", "}" ]
Create a diagnostic group that matches only the given type.
[ "Create", "a", "diagnostic", "group", "that", "matches", "only", "the", "given", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DiagnosticGroup.java#L84-L87
24,340
google/closure-compiler
src/com/google/javascript/jscomp/DiagnosticGroup.java
DiagnosticGroup.isSubGroup
boolean isSubGroup(DiagnosticGroup group) { for (DiagnosticType type : group.types) { if (!matches(type)) { return false; } } return true; }
java
boolean isSubGroup(DiagnosticGroup group) { for (DiagnosticType type : group.types) { if (!matches(type)) { return false; } } return true; }
[ "boolean", "isSubGroup", "(", "DiagnosticGroup", "group", ")", "{", "for", "(", "DiagnosticType", "type", ":", "group", ".", "types", ")", "{", "if", "(", "!", "matches", "(", "type", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns whether all of the types in the given group are in this group.
[ "Returns", "whether", "all", "of", "the", "types", "in", "the", "given", "group", "are", "in", "this", "group", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DiagnosticGroup.java#L107-L114
24,341
google/closure-compiler
src/com/google/javascript/jscomp/StrictModeCheck.java
StrictModeCheck.checkWith
private static void checkWith(NodeTraversal t, Node n) { JSDocInfo info = n.getJSDocInfo(); boolean allowWith = info != null && info.getSuppressions().contains("with"); if (!allowWith) { t.report(n, USE_OF_WITH); } }
java
private static void checkWith(NodeTraversal t, Node n) { JSDocInfo info = n.getJSDocInfo(); boolean allowWith = info != null && info.getSuppressions().contains("with"); if (!allowWith) { t.report(n, USE_OF_WITH); } }
[ "private", "static", "void", "checkWith", "(", "NodeTraversal", "t", ",", "Node", "n", ")", "{", "JSDocInfo", "info", "=", "n", ".", "getJSDocInfo", "(", ")", ";", "boolean", "allowWith", "=", "info", "!=", "null", "&&", "info", ".", "getSuppressions", "(", ")", ".", "contains", "(", "\"with\"", ")", ";", "if", "(", "!", "allowWith", ")", "{", "t", ".", "report", "(", "n", ",", "USE_OF_WITH", ")", ";", "}", "}" ]
Reports a warning for with statements.
[ "Reports", "a", "warning", "for", "with", "statements", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/StrictModeCheck.java#L120-L127
24,342
google/closure-compiler
src/com/google/javascript/jscomp/StrictModeCheck.java
StrictModeCheck.isDeclaration
private static boolean isDeclaration(Node n) { switch (n.getParent().getToken()) { case LET: case CONST: case VAR: case CATCH: return true; case FUNCTION: return n == n.getParent().getFirstChild(); case PARAM_LIST: return n.getGrandparent().isFunction(); default: return false; } }
java
private static boolean isDeclaration(Node n) { switch (n.getParent().getToken()) { case LET: case CONST: case VAR: case CATCH: return true; case FUNCTION: return n == n.getParent().getFirstChild(); case PARAM_LIST: return n.getGrandparent().isFunction(); default: return false; } }
[ "private", "static", "boolean", "isDeclaration", "(", "Node", "n", ")", "{", "switch", "(", "n", ".", "getParent", "(", ")", ".", "getToken", "(", ")", ")", "{", "case", "LET", ":", "case", "CONST", ":", "case", "VAR", ":", "case", "CATCH", ":", "return", "true", ";", "case", "FUNCTION", ":", "return", "n", "==", "n", ".", "getParent", "(", ")", ".", "getFirstChild", "(", ")", ";", "case", "PARAM_LIST", ":", "return", "n", ".", "getGrandparent", "(", ")", ".", "isFunction", "(", ")", ";", "default", ":", "return", "false", ";", "}", "}" ]
Determines if the given name is a declaration, which can be a declaration of a variable, function, or argument.
[ "Determines", "if", "the", "given", "name", "is", "a", "declaration", "which", "can", "be", "a", "declaration", "of", "a", "variable", "function", "or", "argument", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/StrictModeCheck.java#L133-L149
24,343
google/closure-compiler
src/com/google/javascript/jscomp/StrictModeCheck.java
StrictModeCheck.checkAssignment
private static void checkAssignment(NodeTraversal t, Node n) { if (n.getFirstChild().isName()) { if ("arguments".equals(n.getFirstChild().getString())) { t.report(n, ARGUMENTS_ASSIGNMENT); } else if ("eval".equals(n.getFirstChild().getString())) { // Note that assignment to eval is already illegal because any use of // that name is illegal. t.report(n, EVAL_ASSIGNMENT); } } }
java
private static void checkAssignment(NodeTraversal t, Node n) { if (n.getFirstChild().isName()) { if ("arguments".equals(n.getFirstChild().getString())) { t.report(n, ARGUMENTS_ASSIGNMENT); } else if ("eval".equals(n.getFirstChild().getString())) { // Note that assignment to eval is already illegal because any use of // that name is illegal. t.report(n, EVAL_ASSIGNMENT); } } }
[ "private", "static", "void", "checkAssignment", "(", "NodeTraversal", "t", ",", "Node", "n", ")", "{", "if", "(", "n", ".", "getFirstChild", "(", ")", ".", "isName", "(", ")", ")", "{", "if", "(", "\"arguments\"", ".", "equals", "(", "n", ".", "getFirstChild", "(", ")", ".", "getString", "(", ")", ")", ")", "{", "t", ".", "report", "(", "n", ",", "ARGUMENTS_ASSIGNMENT", ")", ";", "}", "else", "if", "(", "\"eval\"", ".", "equals", "(", "n", ".", "getFirstChild", "(", ")", ".", "getString", "(", ")", ")", ")", "{", "// Note that assignment to eval is already illegal because any use of", "// that name is illegal.", "t", ".", "report", "(", "n", ",", "EVAL_ASSIGNMENT", ")", ";", "}", "}", "}" ]
Checks that an assignment is not to the "arguments" object.
[ "Checks", "that", "an", "assignment", "is", "not", "to", "the", "arguments", "object", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/StrictModeCheck.java#L152-L162
24,344
google/closure-compiler
src/com/google/javascript/jscomp/StrictModeCheck.java
StrictModeCheck.checkDelete
private static void checkDelete(NodeTraversal t, Node n) { if (n.getFirstChild().isName()) { Var v = t.getScope().getVar(n.getFirstChild().getString()); if (v != null) { t.report(n, DELETE_VARIABLE); } } }
java
private static void checkDelete(NodeTraversal t, Node n) { if (n.getFirstChild().isName()) { Var v = t.getScope().getVar(n.getFirstChild().getString()); if (v != null) { t.report(n, DELETE_VARIABLE); } } }
[ "private", "static", "void", "checkDelete", "(", "NodeTraversal", "t", ",", "Node", "n", ")", "{", "if", "(", "n", ".", "getFirstChild", "(", ")", ".", "isName", "(", ")", ")", "{", "Var", "v", "=", "t", ".", "getScope", "(", ")", ".", "getVar", "(", "n", ".", "getFirstChild", "(", ")", ".", "getString", "(", ")", ")", ";", "if", "(", "v", "!=", "null", ")", "{", "t", ".", "report", "(", "n", ",", "DELETE_VARIABLE", ")", ";", "}", "}", "}" ]
Checks that variables, functions, and arguments are not deleted.
[ "Checks", "that", "variables", "functions", "and", "arguments", "are", "not", "deleted", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/StrictModeCheck.java#L165-L172
24,345
google/closure-compiler
src/com/google/javascript/jscomp/StrictModeCheck.java
StrictModeCheck.checkObjectLiteralOrClass
private static void checkObjectLiteralOrClass(NodeTraversal t, Node n) { Set<String> getters = new HashSet<>(); Set<String> setters = new HashSet<>(); Set<String> staticGetters = new HashSet<>(); Set<String> staticSetters = new HashSet<>(); for (Node key = n.getFirstChild(); key != null; key = key.getNext()) { if (key.isEmpty() || key.isComputedProp()) { continue; } if (key.isSpread()) { continue; } String keyName = key.getString(); if (!key.isSetterDef()) { // normal property and getter cases Set<String> set = key.isStaticMember() ? staticGetters : getters; if (!set.add(keyName)) { if (n.isClassMembers()) { t.report(key, DUPLICATE_CLASS_METHODS, keyName); } else { t.report(key, DUPLICATE_OBJECT_KEY, keyName); } } } if (!key.isGetterDef()) { // normal property and setter cases Set<String> set = key.isStaticMember() ? staticSetters : setters; if (!set.add(keyName)) { if (n.isClassMembers()) { t.report(key, DUPLICATE_CLASS_METHODS, keyName); } else { t.report(key, DUPLICATE_OBJECT_KEY, keyName); } } } } }
java
private static void checkObjectLiteralOrClass(NodeTraversal t, Node n) { Set<String> getters = new HashSet<>(); Set<String> setters = new HashSet<>(); Set<String> staticGetters = new HashSet<>(); Set<String> staticSetters = new HashSet<>(); for (Node key = n.getFirstChild(); key != null; key = key.getNext()) { if (key.isEmpty() || key.isComputedProp()) { continue; } if (key.isSpread()) { continue; } String keyName = key.getString(); if (!key.isSetterDef()) { // normal property and getter cases Set<String> set = key.isStaticMember() ? staticGetters : getters; if (!set.add(keyName)) { if (n.isClassMembers()) { t.report(key, DUPLICATE_CLASS_METHODS, keyName); } else { t.report(key, DUPLICATE_OBJECT_KEY, keyName); } } } if (!key.isGetterDef()) { // normal property and setter cases Set<String> set = key.isStaticMember() ? staticSetters : setters; if (!set.add(keyName)) { if (n.isClassMembers()) { t.report(key, DUPLICATE_CLASS_METHODS, keyName); } else { t.report(key, DUPLICATE_OBJECT_KEY, keyName); } } } } }
[ "private", "static", "void", "checkObjectLiteralOrClass", "(", "NodeTraversal", "t", ",", "Node", "n", ")", "{", "Set", "<", "String", ">", "getters", "=", "new", "HashSet", "<>", "(", ")", ";", "Set", "<", "String", ">", "setters", "=", "new", "HashSet", "<>", "(", ")", ";", "Set", "<", "String", ">", "staticGetters", "=", "new", "HashSet", "<>", "(", ")", ";", "Set", "<", "String", ">", "staticSetters", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "Node", "key", "=", "n", ".", "getFirstChild", "(", ")", ";", "key", "!=", "null", ";", "key", "=", "key", ".", "getNext", "(", ")", ")", "{", "if", "(", "key", ".", "isEmpty", "(", ")", "||", "key", ".", "isComputedProp", "(", ")", ")", "{", "continue", ";", "}", "if", "(", "key", ".", "isSpread", "(", ")", ")", "{", "continue", ";", "}", "String", "keyName", "=", "key", ".", "getString", "(", ")", ";", "if", "(", "!", "key", ".", "isSetterDef", "(", ")", ")", "{", "// normal property and getter cases", "Set", "<", "String", ">", "set", "=", "key", ".", "isStaticMember", "(", ")", "?", "staticGetters", ":", "getters", ";", "if", "(", "!", "set", ".", "add", "(", "keyName", ")", ")", "{", "if", "(", "n", ".", "isClassMembers", "(", ")", ")", "{", "t", ".", "report", "(", "key", ",", "DUPLICATE_CLASS_METHODS", ",", "keyName", ")", ";", "}", "else", "{", "t", ".", "report", "(", "key", ",", "DUPLICATE_OBJECT_KEY", ",", "keyName", ")", ";", "}", "}", "}", "if", "(", "!", "key", ".", "isGetterDef", "(", ")", ")", "{", "// normal property and setter cases", "Set", "<", "String", ">", "set", "=", "key", ".", "isStaticMember", "(", ")", "?", "staticSetters", ":", "setters", ";", "if", "(", "!", "set", ".", "add", "(", "keyName", ")", ")", "{", "if", "(", "n", ".", "isClassMembers", "(", ")", ")", "{", "t", ".", "report", "(", "key", ",", "DUPLICATE_CLASS_METHODS", ",", "keyName", ")", ";", "}", "else", "{", "t", ".", "report", "(", "key", ",", "DUPLICATE_OBJECT_KEY", ",", "keyName", ")", ";", "}", "}", "}", "}", "}" ]
Checks that object literal keys or class method names are valid.
[ "Checks", "that", "object", "literal", "keys", "or", "class", "method", "names", "are", "valid", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/StrictModeCheck.java#L175-L213
24,346
google/closure-compiler
src/com/google/javascript/jscomp/GenerateExports.java
GenerateExports.addExportMethod
private void addExportMethod(Map<String, Node> exports, String export, Node context) { // We can export as a property if any of the following conditions holds: // a) ES6 class members, which the above `addExportForEs6Method` handles // b) this is a property on a name which is also being exported // c) this is a prototype property String methodOwnerName = null; // the object this method is on, null for exported names. boolean isEs5StylePrototypeAssignment = false; // If this is a prototype property String propertyName = null; if (context.getFirstChild().isGetProp()) { // e.g. `/** @export */ a.prototype.b = obj;` Node node = context.getFirstChild(); // e.g. get `a.prototype.b` Node ownerNode = node.getFirstChild(); // e.g. get `a.prototype` methodOwnerName = ownerNode.getQualifiedName(); // e.g. get the string "a.prototype" if (ownerNode.isGetProp() && ownerNode.getLastChild().getString().equals(PROTOTYPE_PROPERTY)) { // e.g. true if ownerNode is `a.prototype` // false if this export were `/** @export */ a.b = obj;` instead isEs5StylePrototypeAssignment = true; } propertyName = node.getSecondChild().getString(); } boolean useExportSymbol = true; if (isEs5StylePrototypeAssignment) { useExportSymbol = false; } else if (methodOwnerName != null && exports.containsKey(methodOwnerName)) { useExportSymbol = false; } if (useExportSymbol) { addExportSymbolCall(export, context); } else { addExportPropertyCall(methodOwnerName, context, export, propertyName); } }
java
private void addExportMethod(Map<String, Node> exports, String export, Node context) { // We can export as a property if any of the following conditions holds: // a) ES6 class members, which the above `addExportForEs6Method` handles // b) this is a property on a name which is also being exported // c) this is a prototype property String methodOwnerName = null; // the object this method is on, null for exported names. boolean isEs5StylePrototypeAssignment = false; // If this is a prototype property String propertyName = null; if (context.getFirstChild().isGetProp()) { // e.g. `/** @export */ a.prototype.b = obj;` Node node = context.getFirstChild(); // e.g. get `a.prototype.b` Node ownerNode = node.getFirstChild(); // e.g. get `a.prototype` methodOwnerName = ownerNode.getQualifiedName(); // e.g. get the string "a.prototype" if (ownerNode.isGetProp() && ownerNode.getLastChild().getString().equals(PROTOTYPE_PROPERTY)) { // e.g. true if ownerNode is `a.prototype` // false if this export were `/** @export */ a.b = obj;` instead isEs5StylePrototypeAssignment = true; } propertyName = node.getSecondChild().getString(); } boolean useExportSymbol = true; if (isEs5StylePrototypeAssignment) { useExportSymbol = false; } else if (methodOwnerName != null && exports.containsKey(methodOwnerName)) { useExportSymbol = false; } if (useExportSymbol) { addExportSymbolCall(export, context); } else { addExportPropertyCall(methodOwnerName, context, export, propertyName); } }
[ "private", "void", "addExportMethod", "(", "Map", "<", "String", ",", "Node", ">", "exports", ",", "String", "export", ",", "Node", "context", ")", "{", "// We can export as a property if any of the following conditions holds:", "// a) ES6 class members, which the above `addExportForEs6Method` handles", "// b) this is a property on a name which is also being exported", "// c) this is a prototype property", "String", "methodOwnerName", "=", "null", ";", "// the object this method is on, null for exported names.", "boolean", "isEs5StylePrototypeAssignment", "=", "false", ";", "// If this is a prototype property", "String", "propertyName", "=", "null", ";", "if", "(", "context", ".", "getFirstChild", "(", ")", ".", "isGetProp", "(", ")", ")", "{", "// e.g. `/** @export */ a.prototype.b = obj;`", "Node", "node", "=", "context", ".", "getFirstChild", "(", ")", ";", "// e.g. get `a.prototype.b`", "Node", "ownerNode", "=", "node", ".", "getFirstChild", "(", ")", ";", "// e.g. get `a.prototype`", "methodOwnerName", "=", "ownerNode", ".", "getQualifiedName", "(", ")", ";", "// e.g. get the string \"a.prototype\"", "if", "(", "ownerNode", ".", "isGetProp", "(", ")", "&&", "ownerNode", ".", "getLastChild", "(", ")", ".", "getString", "(", ")", ".", "equals", "(", "PROTOTYPE_PROPERTY", ")", ")", "{", "// e.g. true if ownerNode is `a.prototype`", "// false if this export were `/** @export */ a.b = obj;` instead", "isEs5StylePrototypeAssignment", "=", "true", ";", "}", "propertyName", "=", "node", ".", "getSecondChild", "(", ")", ".", "getString", "(", ")", ";", "}", "boolean", "useExportSymbol", "=", "true", ";", "if", "(", "isEs5StylePrototypeAssignment", ")", "{", "useExportSymbol", "=", "false", ";", "}", "else", "if", "(", "methodOwnerName", "!=", "null", "&&", "exports", ".", "containsKey", "(", "methodOwnerName", ")", ")", "{", "useExportSymbol", "=", "false", ";", "}", "if", "(", "useExportSymbol", ")", "{", "addExportSymbolCall", "(", "export", ",", "context", ")", ";", "}", "else", "{", "addExportPropertyCall", "(", "methodOwnerName", ",", "context", ",", "export", ",", "propertyName", ")", ";", "}", "}" ]
Emits a call to either goog.exportProperty or goog.exportSymbol. <p>Attempts to optimize by creating a property export instead of a symbol export, because property exports are significantly simpler/faster. @param export The fully qualified name of the object we want to export @param context The node on which the @export annotation was found
[ "Emits", "a", "call", "to", "either", "goog", ".", "exportProperty", "or", "goog", ".", "exportSymbol", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/GenerateExports.java#L135-L169
24,347
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java
PeepholeReplaceKnownMethods.jsSplitMatch
private static int jsSplitMatch(String stringValue, int startIndex, String separator) { if (startIndex + separator.length() > stringValue.length()) { return -1; } int matchIndex = stringValue.indexOf(separator, startIndex); if (matchIndex < 0) { return -1; } return matchIndex; }
java
private static int jsSplitMatch(String stringValue, int startIndex, String separator) { if (startIndex + separator.length() > stringValue.length()) { return -1; } int matchIndex = stringValue.indexOf(separator, startIndex); if (matchIndex < 0) { return -1; } return matchIndex; }
[ "private", "static", "int", "jsSplitMatch", "(", "String", "stringValue", ",", "int", "startIndex", ",", "String", "separator", ")", "{", "if", "(", "startIndex", "+", "separator", ".", "length", "(", ")", ">", "stringValue", ".", "length", "(", ")", ")", "{", "return", "-", "1", ";", "}", "int", "matchIndex", "=", "stringValue", ".", "indexOf", "(", "separator", ",", "startIndex", ")", ";", "if", "(", "matchIndex", "<", "0", ")", "{", "return", "-", "1", ";", "}", "return", "matchIndex", ";", "}" ]
Support function for jsSplit, find the first occurrence of separator within stringValue starting at startIndex.
[ "Support", "function", "for", "jsSplit", "find", "the", "first", "occurrence", "of", "separator", "within", "stringValue", "starting", "at", "startIndex", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java#L843-L857
24,348
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java
PeepholeReplaceKnownMethods.jsSplit
private String[] jsSplit(String stringValue, String separator, int limit) { checkArgument(limit >= 0); checkArgument(stringValue != null); // For limits of 0, return an empty array if (limit == 0) { return new String[0]; } // If a separator is not specified, return the entire string as // the only element of an array. if (separator == null) { return new String[] {stringValue}; } List<String> splitStrings = new ArrayList<>(); // If an empty string is specified for the separator, split apart each // character of the string. if (separator.isEmpty()) { for (int i = 0; i < stringValue.length() && i < limit; i++) { splitStrings.add(stringValue.substring(i, i + 1)); } } else { int startIndex = 0; int matchIndex; while ((matchIndex = jsSplitMatch(stringValue, startIndex, separator)) >= 0 && splitStrings.size() < limit) { splitStrings.add(stringValue.substring(startIndex, matchIndex)); startIndex = matchIndex + separator.length(); } if (splitStrings.size() < limit) { if (startIndex < stringValue.length()) { splitStrings.add(stringValue.substring(startIndex)); } else { splitStrings.add(""); } } } return splitStrings.toArray(new String[0]); }
java
private String[] jsSplit(String stringValue, String separator, int limit) { checkArgument(limit >= 0); checkArgument(stringValue != null); // For limits of 0, return an empty array if (limit == 0) { return new String[0]; } // If a separator is not specified, return the entire string as // the only element of an array. if (separator == null) { return new String[] {stringValue}; } List<String> splitStrings = new ArrayList<>(); // If an empty string is specified for the separator, split apart each // character of the string. if (separator.isEmpty()) { for (int i = 0; i < stringValue.length() && i < limit; i++) { splitStrings.add(stringValue.substring(i, i + 1)); } } else { int startIndex = 0; int matchIndex; while ((matchIndex = jsSplitMatch(stringValue, startIndex, separator)) >= 0 && splitStrings.size() < limit) { splitStrings.add(stringValue.substring(startIndex, matchIndex)); startIndex = matchIndex + separator.length(); } if (splitStrings.size() < limit) { if (startIndex < stringValue.length()) { splitStrings.add(stringValue.substring(startIndex)); } else { splitStrings.add(""); } } } return splitStrings.toArray(new String[0]); }
[ "private", "String", "[", "]", "jsSplit", "(", "String", "stringValue", ",", "String", "separator", ",", "int", "limit", ")", "{", "checkArgument", "(", "limit", ">=", "0", ")", ";", "checkArgument", "(", "stringValue", "!=", "null", ")", ";", "// For limits of 0, return an empty array", "if", "(", "limit", "==", "0", ")", "{", "return", "new", "String", "[", "0", "]", ";", "}", "// If a separator is not specified, return the entire string as", "// the only element of an array.", "if", "(", "separator", "==", "null", ")", "{", "return", "new", "String", "[", "]", "{", "stringValue", "}", ";", "}", "List", "<", "String", ">", "splitStrings", "=", "new", "ArrayList", "<>", "(", ")", ";", "// If an empty string is specified for the separator, split apart each", "// character of the string.", "if", "(", "separator", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "stringValue", ".", "length", "(", ")", "&&", "i", "<", "limit", ";", "i", "++", ")", "{", "splitStrings", ".", "add", "(", "stringValue", ".", "substring", "(", "i", ",", "i", "+", "1", ")", ")", ";", "}", "}", "else", "{", "int", "startIndex", "=", "0", ";", "int", "matchIndex", ";", "while", "(", "(", "matchIndex", "=", "jsSplitMatch", "(", "stringValue", ",", "startIndex", ",", "separator", ")", ")", ">=", "0", "&&", "splitStrings", ".", "size", "(", ")", "<", "limit", ")", "{", "splitStrings", ".", "add", "(", "stringValue", ".", "substring", "(", "startIndex", ",", "matchIndex", ")", ")", ";", "startIndex", "=", "matchIndex", "+", "separator", ".", "length", "(", ")", ";", "}", "if", "(", "splitStrings", ".", "size", "(", ")", "<", "limit", ")", "{", "if", "(", "startIndex", "<", "stringValue", ".", "length", "(", ")", ")", "{", "splitStrings", ".", "add", "(", "stringValue", ".", "substring", "(", "startIndex", ")", ")", ";", "}", "else", "{", "splitStrings", ".", "add", "(", "\"\"", ")", ";", "}", "}", "}", "return", "splitStrings", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ";", "}" ]
Implement the JS String.split method using a string separator.
[ "Implement", "the", "JS", "String", ".", "split", "method", "using", "a", "string", "separator", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java#L862-L906
24,349
google/closure-compiler
src/com/google/javascript/jscomp/AbstractCompiler.java
AbstractCompiler.getPropertyAccessKind
final PropertyAccessKind getPropertyAccessKind(String property) { return getExternGetterAndSetterProperties() .getOrDefault(property, PropertyAccessKind.NORMAL) .unionWith( getSourceGetterAndSetterProperties().getOrDefault(property, PropertyAccessKind.NORMAL)); }
java
final PropertyAccessKind getPropertyAccessKind(String property) { return getExternGetterAndSetterProperties() .getOrDefault(property, PropertyAccessKind.NORMAL) .unionWith( getSourceGetterAndSetterProperties().getOrDefault(property, PropertyAccessKind.NORMAL)); }
[ "final", "PropertyAccessKind", "getPropertyAccessKind", "(", "String", "property", ")", "{", "return", "getExternGetterAndSetterProperties", "(", ")", ".", "getOrDefault", "(", "property", ",", "PropertyAccessKind", ".", "NORMAL", ")", ".", "unionWith", "(", "getSourceGetterAndSetterProperties", "(", ")", ".", "getOrDefault", "(", "property", ",", "PropertyAccessKind", ".", "NORMAL", ")", ")", ";", "}" ]
Returns any property seen in the externs or source with the given name was a getter, setter, or both. <p>This defaults to {@link PropertyAccessKind#NORMAL} for any property not known to have a getter or setter, even for property names that do not exist in the given program.
[ "Returns", "any", "property", "seen", "in", "the", "externs", "or", "source", "with", "the", "given", "name", "was", "a", "getter", "setter", "or", "both", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AbstractCompiler.java#L650-L655
24,350
google/closure-compiler
src/com/google/javascript/jscomp/AbstractCompiler.java
AbstractCompiler.setAnnotation
void setAnnotation(String key, Object object) { checkArgument(object != null, "The stored annotation value cannot be null."); Preconditions.checkArgument( !annotationMap.containsKey(key), "Cannot overwrite the existing annotation '%s'.", key); annotationMap.put(key, object); }
java
void setAnnotation(String key, Object object) { checkArgument(object != null, "The stored annotation value cannot be null."); Preconditions.checkArgument( !annotationMap.containsKey(key), "Cannot overwrite the existing annotation '%s'.", key); annotationMap.put(key, object); }
[ "void", "setAnnotation", "(", "String", "key", ",", "Object", "object", ")", "{", "checkArgument", "(", "object", "!=", "null", ",", "\"The stored annotation value cannot be null.\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "!", "annotationMap", ".", "containsKey", "(", "key", ")", ",", "\"Cannot overwrite the existing annotation '%s'.\"", ",", "key", ")", ";", "annotationMap", ".", "put", "(", "key", ",", "object", ")", ";", "}" ]
Sets an annotation for the given key. @param key the annotation key @param object the object to store as the annotation
[ "Sets", "an", "annotation", "for", "the", "given", "key", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AbstractCompiler.java#L688-L693
24,351
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeFoldConstants.java
PeepholeFoldConstants.tryFoldAddConstantString
private Node tryFoldAddConstantString(Node n, Node left, Node right) { if (left.isString() || right.isString() || left.isArrayLit() || right.isArrayLit()) { // Add strings. String leftString = NodeUtil.getStringValue(left); String rightString = NodeUtil.getStringValue(right); if (leftString != null && rightString != null) { Node newStringNode = IR.string(leftString + rightString); n.replaceWith(newStringNode); reportChangeToEnclosingScope(newStringNode); return newStringNode; } } return n; }
java
private Node tryFoldAddConstantString(Node n, Node left, Node right) { if (left.isString() || right.isString() || left.isArrayLit() || right.isArrayLit()) { // Add strings. String leftString = NodeUtil.getStringValue(left); String rightString = NodeUtil.getStringValue(right); if (leftString != null && rightString != null) { Node newStringNode = IR.string(leftString + rightString); n.replaceWith(newStringNode); reportChangeToEnclosingScope(newStringNode); return newStringNode; } } return n; }
[ "private", "Node", "tryFoldAddConstantString", "(", "Node", "n", ",", "Node", "left", ",", "Node", "right", ")", "{", "if", "(", "left", ".", "isString", "(", ")", "||", "right", ".", "isString", "(", ")", "||", "left", ".", "isArrayLit", "(", ")", "||", "right", ".", "isArrayLit", "(", ")", ")", "{", "// Add strings.", "String", "leftString", "=", "NodeUtil", ".", "getStringValue", "(", "left", ")", ";", "String", "rightString", "=", "NodeUtil", ".", "getStringValue", "(", "right", ")", ";", "if", "(", "leftString", "!=", "null", "&&", "rightString", "!=", "null", ")", "{", "Node", "newStringNode", "=", "IR", ".", "string", "(", "leftString", "+", "rightString", ")", ";", "n", ".", "replaceWith", "(", "newStringNode", ")", ";", "reportChangeToEnclosingScope", "(", "newStringNode", ")", ";", "return", "newStringNode", ";", "}", "}", "return", "n", ";", "}" ]
Try to fold an ADD node with constant operands
[ "Try", "to", "fold", "an", "ADD", "node", "with", "constant", "operands" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeFoldConstants.java#L704-L719
24,352
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeFoldConstants.java
PeepholeFoldConstants.tryFoldShift
private Node tryFoldShift(Node n, Node left, Node right) { if (left.isNumber() && right.isNumber()) { double result; double lval = left.getDouble(); double rval = right.getDouble(); // only the lower 5 bits are used when shifting, so don't do anything // if the shift amount is outside [0,32) if (!(rval >= 0 && rval < 32)) { return n; } int rvalInt = (int) rval; if (rvalInt != rval) { report(FRACTIONAL_BITWISE_OPERAND, right); return n; } if (Math.floor(lval) != lval) { report(FRACTIONAL_BITWISE_OPERAND, left); return n; } int bits = jsConvertDoubleToBits(lval); switch (n.getToken()) { case LSH: result = bits << rvalInt; break; case RSH: result = bits >> rvalInt; break; case URSH: // JavaScript always treats the result of >>> as unsigned. // We must force Java to do the same here. result = 0xffffffffL & (bits >>> rvalInt); break; default: throw new AssertionError("Unknown shift operator: " + n.getToken()); } Node newNumber = IR.number(result); reportChangeToEnclosingScope(n); n.replaceWith(newNumber); return newNumber; } return n; }
java
private Node tryFoldShift(Node n, Node left, Node right) { if (left.isNumber() && right.isNumber()) { double result; double lval = left.getDouble(); double rval = right.getDouble(); // only the lower 5 bits are used when shifting, so don't do anything // if the shift amount is outside [0,32) if (!(rval >= 0 && rval < 32)) { return n; } int rvalInt = (int) rval; if (rvalInt != rval) { report(FRACTIONAL_BITWISE_OPERAND, right); return n; } if (Math.floor(lval) != lval) { report(FRACTIONAL_BITWISE_OPERAND, left); return n; } int bits = jsConvertDoubleToBits(lval); switch (n.getToken()) { case LSH: result = bits << rvalInt; break; case RSH: result = bits >> rvalInt; break; case URSH: // JavaScript always treats the result of >>> as unsigned. // We must force Java to do the same here. result = 0xffffffffL & (bits >>> rvalInt); break; default: throw new AssertionError("Unknown shift operator: " + n.getToken()); } Node newNumber = IR.number(result); reportChangeToEnclosingScope(n); n.replaceWith(newNumber); return newNumber; } return n; }
[ "private", "Node", "tryFoldShift", "(", "Node", "n", ",", "Node", "left", ",", "Node", "right", ")", "{", "if", "(", "left", ".", "isNumber", "(", ")", "&&", "right", ".", "isNumber", "(", ")", ")", "{", "double", "result", ";", "double", "lval", "=", "left", ".", "getDouble", "(", ")", ";", "double", "rval", "=", "right", ".", "getDouble", "(", ")", ";", "// only the lower 5 bits are used when shifting, so don't do anything", "// if the shift amount is outside [0,32)", "if", "(", "!", "(", "rval", ">=", "0", "&&", "rval", "<", "32", ")", ")", "{", "return", "n", ";", "}", "int", "rvalInt", "=", "(", "int", ")", "rval", ";", "if", "(", "rvalInt", "!=", "rval", ")", "{", "report", "(", "FRACTIONAL_BITWISE_OPERAND", ",", "right", ")", ";", "return", "n", ";", "}", "if", "(", "Math", ".", "floor", "(", "lval", ")", "!=", "lval", ")", "{", "report", "(", "FRACTIONAL_BITWISE_OPERAND", ",", "left", ")", ";", "return", "n", ";", "}", "int", "bits", "=", "jsConvertDoubleToBits", "(", "lval", ")", ";", "switch", "(", "n", ".", "getToken", "(", ")", ")", "{", "case", "LSH", ":", "result", "=", "bits", "<<", "rvalInt", ";", "break", ";", "case", "RSH", ":", "result", "=", "bits", ">>", "rvalInt", ";", "break", ";", "case", "URSH", ":", "// JavaScript always treats the result of >>> as unsigned.", "// We must force Java to do the same here.", "result", "=", "0xffffffff", "L", "&", "(", "bits", ">>>", "rvalInt", ")", ";", "break", ";", "default", ":", "throw", "new", "AssertionError", "(", "\"Unknown shift operator: \"", "+", "n", ".", "getToken", "(", ")", ")", ";", "}", "Node", "newNumber", "=", "IR", ".", "number", "(", "result", ")", ";", "reportChangeToEnclosingScope", "(", "n", ")", ";", "n", ".", "replaceWith", "(", "newNumber", ")", ";", "return", "newNumber", ";", "}", "return", "n", ";", "}" ]
Try to fold shift operations
[ "Try", "to", "fold", "shift", "operations" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeFoldConstants.java#L961-L1012
24,353
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeFoldConstants.java
PeepholeFoldConstants.inForcedStringContext
private static boolean inForcedStringContext(Node n) { if (n.getParent().isGetElem() && n.getParent().getLastChild() == n) { return true; } // we can fold in the case "" + new String("") return n.getParent().isAdd(); }
java
private static boolean inForcedStringContext(Node n) { if (n.getParent().isGetElem() && n.getParent().getLastChild() == n) { return true; } // we can fold in the case "" + new String("") return n.getParent().isAdd(); }
[ "private", "static", "boolean", "inForcedStringContext", "(", "Node", "n", ")", "{", "if", "(", "n", ".", "getParent", "(", ")", ".", "isGetElem", "(", ")", "&&", "n", ".", "getParent", "(", ")", ".", "getLastChild", "(", ")", "==", "n", ")", "{", "return", "true", ";", "}", "// we can fold in the case \"\" + new String(\"\")", "return", "n", ".", "getParent", "(", ")", ".", "isAdd", "(", ")", ";", "}" ]
Returns whether this node must be coerced to a string.
[ "Returns", "whether", "this", "node", "must", "be", "coerced", "to", "a", "string", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeFoldConstants.java#L1250-L1258
24,354
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeFoldConstants.java
PeepholeFoldConstants.tryFlattenArrayOrObjectLit
private Node tryFlattenArrayOrObjectLit(Node parentLit) { for (Node child = parentLit.getFirstChild(); child != null; ) { // We have to store the next element here because nodes may be inserted below. Node spread = child; child = child.getNext(); if (!spread.isSpread()) { continue; } Node innerLit = spread.getOnlyChild(); if (!parentLit.getToken().equals(innerLit.getToken())) { continue; // We only want to inline arrays into arrays and objects into objects. } parentLit.addChildrenAfter(innerLit.removeChildren(), spread); spread.detach(); reportChangeToEnclosingScope(parentLit); } return parentLit; }
java
private Node tryFlattenArrayOrObjectLit(Node parentLit) { for (Node child = parentLit.getFirstChild(); child != null; ) { // We have to store the next element here because nodes may be inserted below. Node spread = child; child = child.getNext(); if (!spread.isSpread()) { continue; } Node innerLit = spread.getOnlyChild(); if (!parentLit.getToken().equals(innerLit.getToken())) { continue; // We only want to inline arrays into arrays and objects into objects. } parentLit.addChildrenAfter(innerLit.removeChildren(), spread); spread.detach(); reportChangeToEnclosingScope(parentLit); } return parentLit; }
[ "private", "Node", "tryFlattenArrayOrObjectLit", "(", "Node", "parentLit", ")", "{", "for", "(", "Node", "child", "=", "parentLit", ".", "getFirstChild", "(", ")", ";", "child", "!=", "null", ";", ")", "{", "// We have to store the next element here because nodes may be inserted below.", "Node", "spread", "=", "child", ";", "child", "=", "child", ".", "getNext", "(", ")", ";", "if", "(", "!", "spread", ".", "isSpread", "(", ")", ")", "{", "continue", ";", "}", "Node", "innerLit", "=", "spread", ".", "getOnlyChild", "(", ")", ";", "if", "(", "!", "parentLit", ".", "getToken", "(", ")", ".", "equals", "(", "innerLit", ".", "getToken", "(", ")", ")", ")", "{", "continue", ";", "// We only want to inline arrays into arrays and objects into objects.", "}", "parentLit", ".", "addChildrenAfter", "(", "innerLit", ".", "removeChildren", "(", ")", ",", "spread", ")", ";", "spread", ".", "detach", "(", ")", ";", "reportChangeToEnclosingScope", "(", "parentLit", ")", ";", "}", "return", "parentLit", ";", "}" ]
Flattens array- or object-literals that contain spreads of other literals. <p>Does not recurse into nested spreads because this method is already called as part of a postorder traversal and nested spreads will already have been flattened. <p>Example: `[0, ...[1, 2, 3], 4, ...[5]]` => `[0, 1, 2, 3, 4, 5]`
[ "Flattens", "array", "-", "or", "object", "-", "literals", "that", "contain", "spreads", "of", "other", "literals", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeFoldConstants.java#L1428-L1448
24,355
google/closure-compiler
src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java
SourceMapGeneratorV3.setWrapperPrefix
@Override public void setWrapperPrefix(String prefix) { // Determine the current line and character position. int prefixLine = 0; int prefixIndex = 0; for (int i = 0; i < prefix.length(); ++i) { if (prefix.charAt(i) == '\n') { prefixLine++; prefixIndex = 0; } else { prefixIndex++; } } prefixPosition = new FilePosition(prefixLine, prefixIndex); }
java
@Override public void setWrapperPrefix(String prefix) { // Determine the current line and character position. int prefixLine = 0; int prefixIndex = 0; for (int i = 0; i < prefix.length(); ++i) { if (prefix.charAt(i) == '\n') { prefixLine++; prefixIndex = 0; } else { prefixIndex++; } } prefixPosition = new FilePosition(prefixLine, prefixIndex); }
[ "@", "Override", "public", "void", "setWrapperPrefix", "(", "String", "prefix", ")", "{", "// Determine the current line and character position.", "int", "prefixLine", "=", "0", ";", "int", "prefixIndex", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "prefix", ".", "length", "(", ")", ";", "++", "i", ")", "{", "if", "(", "prefix", ".", "charAt", "(", "i", ")", "==", "'", "'", ")", "{", "prefixLine", "++", ";", "prefixIndex", "=", "0", ";", "}", "else", "{", "prefixIndex", "++", ";", "}", "}", "prefixPosition", "=", "new", "FilePosition", "(", "prefixLine", ",", "prefixIndex", ")", ";", "}" ]
Sets the prefix used for wrapping the generated source file before it is written. This ensures that the source map is adjusted for the change in character offsets. @param prefix The prefix that is added before the generated source code.
[ "Sets", "the", "prefix", "used", "for", "wrapping", "the", "generated", "source", "file", "before", "it", "is", "written", ".", "This", "ensures", "that", "the", "source", "map", "is", "adjusted", "for", "the", "change", "in", "character", "offsets", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java#L166-L182
24,356
google/closure-compiler
src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java
SourceMapGeneratorV3.setStartingPosition
@Override public void setStartingPosition(int offsetLine, int offsetIndex) { checkState(offsetLine >= 0); checkState(offsetIndex >= 0); offsetPosition = new FilePosition(offsetLine, offsetIndex); }
java
@Override public void setStartingPosition(int offsetLine, int offsetIndex) { checkState(offsetLine >= 0); checkState(offsetIndex >= 0); offsetPosition = new FilePosition(offsetLine, offsetIndex); }
[ "@", "Override", "public", "void", "setStartingPosition", "(", "int", "offsetLine", ",", "int", "offsetIndex", ")", "{", "checkState", "(", "offsetLine", ">=", "0", ")", ";", "checkState", "(", "offsetIndex", ">=", "0", ")", ";", "offsetPosition", "=", "new", "FilePosition", "(", "offsetLine", ",", "offsetIndex", ")", ";", "}" ]
Sets the source code that exists in the buffer for which the generated code is being generated. This ensures that the source map accurately reflects the fact that the source is being appended to an existing buffer and as such, does not start at line 0, position 0 but rather some other line and position. @param offsetLine The index of the current line being printed. @param offsetIndex The column index of the current character being printed.
[ "Sets", "the", "source", "code", "that", "exists", "in", "the", "buffer", "for", "which", "the", "generated", "code", "is", "being", "generated", ".", "This", "ensures", "that", "the", "source", "map", "accurately", "reflects", "the", "fact", "that", "the", "source", "is", "being", "appended", "to", "an", "existing", "buffer", "and", "as", "such", "does", "not", "start", "at", "line", "0", "position", "0", "but", "rather", "some", "other", "line", "and", "position", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java#L194-L199
24,357
google/closure-compiler
src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java
SourceMapGeneratorV3.addExtension
public void addExtension(String name, Object object) throws SourceMapParseException{ if (!name.startsWith("x_")){ throw new SourceMapParseException("Extension '" + name + "' must start with 'x_'"); } this.extensions.put(name, object); }
java
public void addExtension(String name, Object object) throws SourceMapParseException{ if (!name.startsWith("x_")){ throw new SourceMapParseException("Extension '" + name + "' must start with 'x_'"); } this.extensions.put(name, object); }
[ "public", "void", "addExtension", "(", "String", "name", ",", "Object", "object", ")", "throws", "SourceMapParseException", "{", "if", "(", "!", "name", ".", "startsWith", "(", "\"x_\"", ")", ")", "{", "throw", "new", "SourceMapParseException", "(", "\"Extension '\"", "+", "name", "+", "\"' must start with 'x_'\"", ")", ";", "}", "this", ".", "extensions", ".", "put", "(", "name", ",", "object", ")", ";", "}" ]
Adds field extensions to the json source map. The value is allowed to be any value accepted by json, eg. string, JsonObject, JsonArray, etc. Extensions must follow the format x_orgranization_field (based on V3 proposal), otherwise a {@code SourceMapParseExtension} will be thrown. @param name The name of the extension with format organization_field @param object The value of the extension as a valid json value @throws SourceMapParseException if extension name is malformed
[ "Adds", "field", "extensions", "to", "the", "json", "source", "map", ".", "The", "value", "is", "allowed", "to", "be", "any", "value", "accepted", "by", "json", "eg", ".", "string", "JsonObject", "JsonArray", "etc", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java#L448-L455
24,358
google/closure-compiler
src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java
SourceMapGeneratorV3.appendFirstField
private static void appendFirstField( Appendable out, String name, CharSequence value) throws IOException { appendFieldStart(out, name, true); out.append(value); }
java
private static void appendFirstField( Appendable out, String name, CharSequence value) throws IOException { appendFieldStart(out, name, true); out.append(value); }
[ "private", "static", "void", "appendFirstField", "(", "Appendable", "out", ",", "String", "name", ",", "CharSequence", "value", ")", "throws", "IOException", "{", "appendFieldStart", "(", "out", ",", "name", ",", "true", ")", ";", "out", ".", "append", "(", "value", ")", ";", "}" ]
Source map field helpers.
[ "Source", "map", "field", "helpers", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java#L553-L558
24,359
google/closure-compiler
src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java
SourceMapGeneratorV3.prepMappings
private int prepMappings() throws IOException { // Mark any unused mappings. (new MappingTraversal()).traverse(new UsedMappingCheck()); // Renumber used mappings and keep track of the last line. int id = 0; int maxLine = 0; for (Mapping m : mappings) { if (m.used) { m.id = id++; int endPositionLine = m.endPosition.getLine(); maxLine = Math.max(maxLine, endPositionLine); } } // Adjust for the prefix. return maxLine + prefixPosition.getLine(); }
java
private int prepMappings() throws IOException { // Mark any unused mappings. (new MappingTraversal()).traverse(new UsedMappingCheck()); // Renumber used mappings and keep track of the last line. int id = 0; int maxLine = 0; for (Mapping m : mappings) { if (m.used) { m.id = id++; int endPositionLine = m.endPosition.getLine(); maxLine = Math.max(maxLine, endPositionLine); } } // Adjust for the prefix. return maxLine + prefixPosition.getLine(); }
[ "private", "int", "prepMappings", "(", ")", "throws", "IOException", "{", "// Mark any unused mappings.", "(", "new", "MappingTraversal", "(", ")", ")", ".", "traverse", "(", "new", "UsedMappingCheck", "(", ")", ")", ";", "// Renumber used mappings and keep track of the last line.", "int", "id", "=", "0", ";", "int", "maxLine", "=", "0", ";", "for", "(", "Mapping", "m", ":", "mappings", ")", "{", "if", "(", "m", ".", "used", ")", "{", "m", ".", "id", "=", "id", "++", ";", "int", "endPositionLine", "=", "m", ".", "endPosition", ".", "getLine", "(", ")", ";", "maxLine", "=", "Math", ".", "max", "(", "maxLine", ",", "endPositionLine", ")", ";", "}", "}", "// Adjust for the prefix.", "return", "maxLine", "+", "prefixPosition", ".", "getLine", "(", ")", ";", "}" ]
Assigns sequential ids to used mappings, and returns the last line mapped.
[ "Assigns", "sequential", "ids", "to", "used", "mappings", "and", "returns", "the", "last", "line", "mapped", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java#L591-L608
24,360
google/closure-compiler
src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java
SourceMapGeneratorV3.appendIndexMapTo
@Override public void appendIndexMapTo( Appendable out, String name, List<SourceMapSection> sections) throws IOException { // Add the header fields. out.append("{\n"); appendFirstField(out, "version", "3"); appendField(out, "file", escapeString(name)); // Add the line character maps. appendFieldStart(out, "sections"); out.append("[\n"); boolean first = true; for (SourceMapSection section : sections) { if (first) { first = false; } else { out.append(",\n"); } out.append("{\n"); appendFieldStart(out, "offset", true); appendOffsetValue(out, section.getLine(), section.getColumn()); if (section.getSectionType() == SourceMapSection.SectionType.URL) { appendField(out, "url", escapeString(section.getSectionValue())); } else if (section.getSectionType() == SourceMapSection.SectionType.MAP) { appendField(out, "map", section.getSectionValue()); } else { throw new IOException("Unexpected section type"); } out.append("\n}"); } out.append("\n]"); appendFieldEnd(out); out.append("\n}\n"); }
java
@Override public void appendIndexMapTo( Appendable out, String name, List<SourceMapSection> sections) throws IOException { // Add the header fields. out.append("{\n"); appendFirstField(out, "version", "3"); appendField(out, "file", escapeString(name)); // Add the line character maps. appendFieldStart(out, "sections"); out.append("[\n"); boolean first = true; for (SourceMapSection section : sections) { if (first) { first = false; } else { out.append(",\n"); } out.append("{\n"); appendFieldStart(out, "offset", true); appendOffsetValue(out, section.getLine(), section.getColumn()); if (section.getSectionType() == SourceMapSection.SectionType.URL) { appendField(out, "url", escapeString(section.getSectionValue())); } else if (section.getSectionType() == SourceMapSection.SectionType.MAP) { appendField(out, "map", section.getSectionValue()); } else { throw new IOException("Unexpected section type"); } out.append("\n}"); } out.append("\n]"); appendFieldEnd(out); out.append("\n}\n"); }
[ "@", "Override", "public", "void", "appendIndexMapTo", "(", "Appendable", "out", ",", "String", "name", ",", "List", "<", "SourceMapSection", ">", "sections", ")", "throws", "IOException", "{", "// Add the header fields.", "out", ".", "append", "(", "\"{\\n\"", ")", ";", "appendFirstField", "(", "out", ",", "\"version\"", ",", "\"3\"", ")", ";", "appendField", "(", "out", ",", "\"file\"", ",", "escapeString", "(", "name", ")", ")", ";", "// Add the line character maps.", "appendFieldStart", "(", "out", ",", "\"sections\"", ")", ";", "out", ".", "append", "(", "\"[\\n\"", ")", ";", "boolean", "first", "=", "true", ";", "for", "(", "SourceMapSection", "section", ":", "sections", ")", "{", "if", "(", "first", ")", "{", "first", "=", "false", ";", "}", "else", "{", "out", ".", "append", "(", "\",\\n\"", ")", ";", "}", "out", ".", "append", "(", "\"{\\n\"", ")", ";", "appendFieldStart", "(", "out", ",", "\"offset\"", ",", "true", ")", ";", "appendOffsetValue", "(", "out", ",", "section", ".", "getLine", "(", ")", ",", "section", ".", "getColumn", "(", ")", ")", ";", "if", "(", "section", ".", "getSectionType", "(", ")", "==", "SourceMapSection", ".", "SectionType", ".", "URL", ")", "{", "appendField", "(", "out", ",", "\"url\"", ",", "escapeString", "(", "section", ".", "getSectionValue", "(", ")", ")", ")", ";", "}", "else", "if", "(", "section", ".", "getSectionType", "(", ")", "==", "SourceMapSection", ".", "SectionType", ".", "MAP", ")", "{", "appendField", "(", "out", ",", "\"map\"", ",", "section", ".", "getSectionValue", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "IOException", "(", "\"Unexpected section type\"", ")", ";", "}", "out", ".", "append", "(", "\"\\n}\"", ")", ";", "}", "out", ".", "append", "(", "\"\\n]\"", ")", ";", "appendFieldEnd", "(", "out", ")", ";", "out", ".", "append", "(", "\"\\n}\\n\"", ")", ";", "}" ]
Appends the index source map to the given buffer. @param out The stream to which the map will be appended. @param name The name of the generated source file that this source map represents. @param sections An ordered list of map sections to include in the index. @throws IOException
[ "Appends", "the", "index", "source", "map", "to", "the", "given", "buffer", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java#L820-L856
24,361
google/closure-compiler
src/com/google/javascript/jscomp/webservice/common/Protocol.java
Protocol.resetMaximumInputSize
public static final void resetMaximumInputSize() { String maxInputSizeStr = System.getProperty(Protocol.MAX_INPUT_SIZE_KEY); if (maxInputSizeStr == null) { maxInputSize = Protocol.FALLBACK_MAX_INPUT_SIZE; } else { maxInputSize = Integer.parseInt(maxInputSizeStr); } }
java
public static final void resetMaximumInputSize() { String maxInputSizeStr = System.getProperty(Protocol.MAX_INPUT_SIZE_KEY); if (maxInputSizeStr == null) { maxInputSize = Protocol.FALLBACK_MAX_INPUT_SIZE; } else { maxInputSize = Integer.parseInt(maxInputSizeStr); } }
[ "public", "static", "final", "void", "resetMaximumInputSize", "(", ")", "{", "String", "maxInputSizeStr", "=", "System", ".", "getProperty", "(", "Protocol", ".", "MAX_INPUT_SIZE_KEY", ")", ";", "if", "(", "maxInputSizeStr", "==", "null", ")", "{", "maxInputSize", "=", "Protocol", ".", "FALLBACK_MAX_INPUT_SIZE", ";", "}", "else", "{", "maxInputSize", "=", "Integer", ".", "parseInt", "(", "maxInputSizeStr", ")", ";", "}", "}" ]
Reset the maximum input size so that the property key is rechecked. This is needed for testing code because we are caching the maximum input size value.
[ "Reset", "the", "maximum", "input", "size", "so", "that", "the", "property", "key", "is", "rechecked", ".", "This", "is", "needed", "for", "testing", "code", "because", "we", "are", "caching", "the", "maximum", "input", "size", "value", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/webservice/common/Protocol.java#L355-L363
24,362
google/closure-compiler
src/com/google/javascript/jscomp/graph/LinkedDirectedGraph.java
LinkedDirectedGraph.isConnectedInDirection
public boolean isConnectedInDirection( DiGraphNode<N, E> dNode1, Predicate<E> edgeMatcher, DiGraphNode<N, E> dNode2) { // Verify the nodes. List<DiGraphEdge<N, E>> outEdges = dNode1.getOutEdges(); int outEdgesLen = outEdges.size(); List<DiGraphEdge<N, E>> inEdges = dNode2.getInEdges(); int inEdgesLen = inEdges.size(); // It is possible that there is a large assymmetry between the nodes, so pick the direction // to search based on the shorter list since the edge lists should be symmetric. if (outEdgesLen < inEdgesLen) { for (int i = 0; i < outEdgesLen; i++) { DiGraphEdge<N, E> outEdge = outEdges.get(i); if (outEdge.getDestination() == dNode2 && edgeMatcher.apply(outEdge.getValue())) { return true; } } } else { for (int i = 0; i < inEdgesLen; i++) { DiGraphEdge<N, E> inEdge = inEdges.get(i); if (inEdge.getSource() == dNode1 && edgeMatcher.apply(inEdge.getValue())) { return true; } } } return false; }
java
public boolean isConnectedInDirection( DiGraphNode<N, E> dNode1, Predicate<E> edgeMatcher, DiGraphNode<N, E> dNode2) { // Verify the nodes. List<DiGraphEdge<N, E>> outEdges = dNode1.getOutEdges(); int outEdgesLen = outEdges.size(); List<DiGraphEdge<N, E>> inEdges = dNode2.getInEdges(); int inEdgesLen = inEdges.size(); // It is possible that there is a large assymmetry between the nodes, so pick the direction // to search based on the shorter list since the edge lists should be symmetric. if (outEdgesLen < inEdgesLen) { for (int i = 0; i < outEdgesLen; i++) { DiGraphEdge<N, E> outEdge = outEdges.get(i); if (outEdge.getDestination() == dNode2 && edgeMatcher.apply(outEdge.getValue())) { return true; } } } else { for (int i = 0; i < inEdgesLen; i++) { DiGraphEdge<N, E> inEdge = inEdges.get(i); if (inEdge.getSource() == dNode1 && edgeMatcher.apply(inEdge.getValue())) { return true; } } } return false; }
[ "public", "boolean", "isConnectedInDirection", "(", "DiGraphNode", "<", "N", ",", "E", ">", "dNode1", ",", "Predicate", "<", "E", ">", "edgeMatcher", ",", "DiGraphNode", "<", "N", ",", "E", ">", "dNode2", ")", "{", "// Verify the nodes.", "List", "<", "DiGraphEdge", "<", "N", ",", "E", ">", ">", "outEdges", "=", "dNode1", ".", "getOutEdges", "(", ")", ";", "int", "outEdgesLen", "=", "outEdges", ".", "size", "(", ")", ";", "List", "<", "DiGraphEdge", "<", "N", ",", "E", ">", ">", "inEdges", "=", "dNode2", ".", "getInEdges", "(", ")", ";", "int", "inEdgesLen", "=", "inEdges", ".", "size", "(", ")", ";", "// It is possible that there is a large assymmetry between the nodes, so pick the direction", "// to search based on the shorter list since the edge lists should be symmetric.", "if", "(", "outEdgesLen", "<", "inEdgesLen", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "outEdgesLen", ";", "i", "++", ")", "{", "DiGraphEdge", "<", "N", ",", "E", ">", "outEdge", "=", "outEdges", ".", "get", "(", "i", ")", ";", "if", "(", "outEdge", ".", "getDestination", "(", ")", "==", "dNode2", "&&", "edgeMatcher", ".", "apply", "(", "outEdge", ".", "getValue", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "}", "else", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "inEdgesLen", ";", "i", "++", ")", "{", "DiGraphEdge", "<", "N", ",", "E", ">", "inEdge", "=", "inEdges", ".", "get", "(", "i", ")", ";", "if", "(", "inEdge", ".", "getSource", "(", ")", "==", "dNode1", "&&", "edgeMatcher", ".", "apply", "(", "inEdge", ".", "getValue", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
DiGraphNode look ups can be expensive for a large graph operation, prefer this method if you have the DiGraphNodes available.
[ "DiGraphNode", "look", "ups", "can", "be", "expensive", "for", "a", "large", "graph", "operation", "prefer", "this", "method", "if", "you", "have", "the", "DiGraphNodes", "available", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/graph/LinkedDirectedGraph.java#L244-L274
24,363
google/closure-compiler
src/com/google/javascript/jscomp/CheckMissingGetCssName.java
CheckMissingGetCssName.insideGetCssNameCall
private static boolean insideGetCssNameCall(Node n) { Node parent = n.getParent(); return parent.isCall() && parent.getFirstChild().matchesQualifiedName(GET_CSS_NAME_FUNCTION); }
java
private static boolean insideGetCssNameCall(Node n) { Node parent = n.getParent(); return parent.isCall() && parent.getFirstChild().matchesQualifiedName(GET_CSS_NAME_FUNCTION); }
[ "private", "static", "boolean", "insideGetCssNameCall", "(", "Node", "n", ")", "{", "Node", "parent", "=", "n", ".", "getParent", "(", ")", ";", "return", "parent", ".", "isCall", "(", ")", "&&", "parent", ".", "getFirstChild", "(", ")", ".", "matchesQualifiedName", "(", "GET_CSS_NAME_FUNCTION", ")", ";", "}" ]
Returns whether the node is an argument of a goog.getCssName call.
[ "Returns", "whether", "the", "node", "is", "an", "argument", "of", "a", "goog", ".", "getCssName", "call", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckMissingGetCssName.java#L87-L91
24,364
google/closure-compiler
src/com/google/javascript/jscomp/ReferenceCollection.java
ReferenceCollection.isWellDefined
protected boolean isWellDefined() { int size = references.size(); if (size == 0) { return false; } // If this is a declaration that does not instantiate the variable, // it's not well-defined. Reference init = getInitializingReference(); if (init == null) { return false; } checkState(references.get(0).isDeclaration()); BasicBlock initBlock = init.getBasicBlock(); for (int i = 1; i < size; i++) { if (!initBlock.provablyExecutesBefore(references.get(i).getBasicBlock())) { return false; } } return true; }
java
protected boolean isWellDefined() { int size = references.size(); if (size == 0) { return false; } // If this is a declaration that does not instantiate the variable, // it's not well-defined. Reference init = getInitializingReference(); if (init == null) { return false; } checkState(references.get(0).isDeclaration()); BasicBlock initBlock = init.getBasicBlock(); for (int i = 1; i < size; i++) { if (!initBlock.provablyExecutesBefore(references.get(i).getBasicBlock())) { return false; } } return true; }
[ "protected", "boolean", "isWellDefined", "(", ")", "{", "int", "size", "=", "references", ".", "size", "(", ")", ";", "if", "(", "size", "==", "0", ")", "{", "return", "false", ";", "}", "// If this is a declaration that does not instantiate the variable,", "// it's not well-defined.", "Reference", "init", "=", "getInitializingReference", "(", ")", ";", "if", "(", "init", "==", "null", ")", "{", "return", "false", ";", "}", "checkState", "(", "references", ".", "get", "(", "0", ")", ".", "isDeclaration", "(", ")", ")", ";", "BasicBlock", "initBlock", "=", "init", ".", "getBasicBlock", "(", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "size", ";", "i", "++", ")", "{", "if", "(", "!", "initBlock", ".", "provablyExecutesBefore", "(", "references", ".", "get", "(", "i", ")", ".", "getBasicBlock", "(", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Determines if the variable for this reference collection is "well-defined." A variable is well-defined if we can prove at compile-time that it's assigned a value before it's used. <p>Notice that if this function returns false, this doesn't imply that the variable is used before it's assigned. It just means that we don't have enough information to make a definitive judgment.
[ "Determines", "if", "the", "variable", "for", "this", "reference", "collection", "is", "well", "-", "defined", ".", "A", "variable", "is", "well", "-", "defined", "if", "we", "can", "prove", "at", "compile", "-", "time", "that", "it", "s", "assigned", "a", "value", "before", "it", "s", "used", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ReferenceCollection.java#L53-L75
24,365
google/closure-compiler
src/com/google/javascript/jscomp/ReferenceCollection.java
ReferenceCollection.isEscaped
boolean isEscaped() { Scope hoistScope = null; for (Reference ref : references) { if (hoistScope == null) { hoistScope = ref.getScope().getClosestHoistScope(); } else if (hoistScope != ref.getScope().getClosestHoistScope()) { return true; } } return false; }
java
boolean isEscaped() { Scope hoistScope = null; for (Reference ref : references) { if (hoistScope == null) { hoistScope = ref.getScope().getClosestHoistScope(); } else if (hoistScope != ref.getScope().getClosestHoistScope()) { return true; } } return false; }
[ "boolean", "isEscaped", "(", ")", "{", "Scope", "hoistScope", "=", "null", ";", "for", "(", "Reference", "ref", ":", "references", ")", "{", "if", "(", "hoistScope", "==", "null", ")", "{", "hoistScope", "=", "ref", ".", "getScope", "(", ")", ".", "getClosestHoistScope", "(", ")", ";", "}", "else", "if", "(", "hoistScope", "!=", "ref", ".", "getScope", "(", ")", ".", "getClosestHoistScope", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Whether the variable is escaped into an inner function.
[ "Whether", "the", "variable", "is", "escaped", "into", "an", "inner", "function", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ReferenceCollection.java#L78-L88
24,366
google/closure-compiler
src/com/google/javascript/jscomp/ReferenceCollection.java
ReferenceCollection.getInitializingReferenceForConstants
Reference getInitializingReferenceForConstants() { int size = references.size(); for (int i = 0; i < size; i++) { if (isInitializingDeclarationAt(i) || isInitializingAssignmentAt(i)) { return references.get(i); } } return null; }
java
Reference getInitializingReferenceForConstants() { int size = references.size(); for (int i = 0; i < size; i++) { if (isInitializingDeclarationAt(i) || isInitializingAssignmentAt(i)) { return references.get(i); } } return null; }
[ "Reference", "getInitializingReferenceForConstants", "(", ")", "{", "int", "size", "=", "references", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "if", "(", "isInitializingDeclarationAt", "(", "i", ")", "||", "isInitializingAssignmentAt", "(", "i", ")", ")", "{", "return", "references", ".", "get", "(", "i", ")", ";", "}", "}", "return", "null", ";", "}" ]
Constants are allowed to be defined after their first use.
[ "Constants", "are", "allowed", "to", "be", "defined", "after", "their", "first", "use", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ReferenceCollection.java#L141-L149
24,367
google/closure-compiler
src/com/google/javascript/jscomp/CheckSideEffects.java
CheckSideEffects.protectSideEffects
private void protectSideEffects() { if (!problemNodes.isEmpty()) { if (!preserveFunctionInjected) { addExtern(compiler); } for (Node n : problemNodes) { Node name = IR.name(PROTECTOR_FN).srcref(n); name.putBooleanProp(Node.IS_CONSTANT_NAME, true); Node replacement = IR.call(name).srcref(n); replacement.putBooleanProp(Node.FREE_CALL, true); n.replaceWith(replacement); replacement.addChildToBack(n); compiler.reportChangeToEnclosingScope(replacement); } } }
java
private void protectSideEffects() { if (!problemNodes.isEmpty()) { if (!preserveFunctionInjected) { addExtern(compiler); } for (Node n : problemNodes) { Node name = IR.name(PROTECTOR_FN).srcref(n); name.putBooleanProp(Node.IS_CONSTANT_NAME, true); Node replacement = IR.call(name).srcref(n); replacement.putBooleanProp(Node.FREE_CALL, true); n.replaceWith(replacement); replacement.addChildToBack(n); compiler.reportChangeToEnclosingScope(replacement); } } }
[ "private", "void", "protectSideEffects", "(", ")", "{", "if", "(", "!", "problemNodes", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "!", "preserveFunctionInjected", ")", "{", "addExtern", "(", "compiler", ")", ";", "}", "for", "(", "Node", "n", ":", "problemNodes", ")", "{", "Node", "name", "=", "IR", ".", "name", "(", "PROTECTOR_FN", ")", ".", "srcref", "(", "n", ")", ";", "name", ".", "putBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ",", "true", ")", ";", "Node", "replacement", "=", "IR", ".", "call", "(", "name", ")", ".", "srcref", "(", "n", ")", ";", "replacement", ".", "putBooleanProp", "(", "Node", ".", "FREE_CALL", ",", "true", ")", ";", "n", ".", "replaceWith", "(", "replacement", ")", ";", "replacement", ".", "addChildToBack", "(", "n", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "replacement", ")", ";", "}", "}", "}" ]
Protect side-effect free nodes by making them parameters to a extern function call. This call will be removed after all the optimizations passes have run.
[ "Protect", "side", "-", "effect", "free", "nodes", "by", "making", "them", "parameters", "to", "a", "extern", "function", "call", ".", "This", "call", "will", "be", "removed", "after", "all", "the", "optimizations", "passes", "have", "run", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckSideEffects.java#L174-L189
24,368
google/closure-compiler
src/com/google/javascript/jscomp/CheckSideEffects.java
CheckSideEffects.addExtern
static void addExtern(AbstractCompiler compiler) { Node name = IR.name(PROTECTOR_FN); name.putBooleanProp(Node.IS_CONSTANT_NAME, true); Node var = IR.var(name); JSDocInfoBuilder builder = new JSDocInfoBuilder(false); var.setJSDocInfo(builder.build()); CompilerInput input = compiler.getSynthesizedExternsInput(); Node root = input.getAstRoot(compiler); name.setStaticSourceFileFrom(root); var.setStaticSourceFileFrom(root); root.addChildToBack(var); compiler.reportChangeToEnclosingScope(var); }
java
static void addExtern(AbstractCompiler compiler) { Node name = IR.name(PROTECTOR_FN); name.putBooleanProp(Node.IS_CONSTANT_NAME, true); Node var = IR.var(name); JSDocInfoBuilder builder = new JSDocInfoBuilder(false); var.setJSDocInfo(builder.build()); CompilerInput input = compiler.getSynthesizedExternsInput(); Node root = input.getAstRoot(compiler); name.setStaticSourceFileFrom(root); var.setStaticSourceFileFrom(root); root.addChildToBack(var); compiler.reportChangeToEnclosingScope(var); }
[ "static", "void", "addExtern", "(", "AbstractCompiler", "compiler", ")", "{", "Node", "name", "=", "IR", ".", "name", "(", "PROTECTOR_FN", ")", ";", "name", ".", "putBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ",", "true", ")", ";", "Node", "var", "=", "IR", ".", "var", "(", "name", ")", ";", "JSDocInfoBuilder", "builder", "=", "new", "JSDocInfoBuilder", "(", "false", ")", ";", "var", ".", "setJSDocInfo", "(", "builder", ".", "build", "(", ")", ")", ";", "CompilerInput", "input", "=", "compiler", ".", "getSynthesizedExternsInput", "(", ")", ";", "Node", "root", "=", "input", ".", "getAstRoot", "(", "compiler", ")", ";", "name", ".", "setStaticSourceFileFrom", "(", "root", ")", ";", "var", ".", "setStaticSourceFileFrom", "(", "root", ")", ";", "root", ".", "addChildToBack", "(", "var", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "var", ")", ";", "}" ]
Injects JSCOMPILER_PRESEVE into the synthetic externs
[ "Injects", "JSCOMPILER_PRESEVE", "into", "the", "synthetic", "externs" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckSideEffects.java#L192-L204
24,369
google/closure-compiler
src/com/google/javascript/jscomp/CodeGenerator.java
CodeGenerator.unrollBinaryOperator
private void unrollBinaryOperator( Node n, Token op, String opStr, Context context, Context rhsContext, int leftPrecedence, int rightPrecedence) { Node firstNonOperator = n.getFirstChild(); while (firstNonOperator.getToken() == op) { firstNonOperator = firstNonOperator.getFirstChild(); } addExpr(firstNonOperator, leftPrecedence, context); Node current = firstNonOperator; do { current = current.getParent(); cc.addOp(opStr, true); addExpr(current.getSecondChild(), rightPrecedence, rhsContext); } while (current != n); }
java
private void unrollBinaryOperator( Node n, Token op, String opStr, Context context, Context rhsContext, int leftPrecedence, int rightPrecedence) { Node firstNonOperator = n.getFirstChild(); while (firstNonOperator.getToken() == op) { firstNonOperator = firstNonOperator.getFirstChild(); } addExpr(firstNonOperator, leftPrecedence, context); Node current = firstNonOperator; do { current = current.getParent(); cc.addOp(opStr, true); addExpr(current.getSecondChild(), rightPrecedence, rhsContext); } while (current != n); }
[ "private", "void", "unrollBinaryOperator", "(", "Node", "n", ",", "Token", "op", ",", "String", "opStr", ",", "Context", "context", ",", "Context", "rhsContext", ",", "int", "leftPrecedence", ",", "int", "rightPrecedence", ")", "{", "Node", "firstNonOperator", "=", "n", ".", "getFirstChild", "(", ")", ";", "while", "(", "firstNonOperator", ".", "getToken", "(", ")", "==", "op", ")", "{", "firstNonOperator", "=", "firstNonOperator", ".", "getFirstChild", "(", ")", ";", "}", "addExpr", "(", "firstNonOperator", ",", "leftPrecedence", ",", "context", ")", ";", "Node", "current", "=", "firstNonOperator", ";", "do", "{", "current", "=", "current", ".", "getParent", "(", ")", ";", "cc", ".", "addOp", "(", "opStr", ",", "true", ")", ";", "addExpr", "(", "current", ".", "getSecondChild", "(", ")", ",", "rightPrecedence", ",", "rhsContext", ")", ";", "}", "while", "(", "current", "!=", "n", ")", ";", "}" ]
We could use addList recursively here, but sometimes we produce very deeply nested operators and run out of stack space, so we just unroll the recursion when possible. We assume nodes are left-recursive.
[ "We", "could", "use", "addList", "recursively", "here", "but", "sometimes", "we", "produce", "very", "deeply", "nested", "operators", "and", "run", "out", "of", "stack", "space", "so", "we", "just", "unroll", "the", "recursion", "when", "possible", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CodeGenerator.java#L1460-L1476
24,370
google/closure-compiler
src/com/google/javascript/jscomp/CodeGenerator.java
CodeGenerator.addArrayList
void addArrayList(Node firstInList) { boolean lastWasEmpty = false; for (Node n = firstInList; n != null; n = n.getNext()) { if (n != firstInList) { cc.listSeparator(); } addExpr(n, 1, Context.OTHER); lastWasEmpty = n.isEmpty(); } if (lastWasEmpty) { cc.listSeparator(); } }
java
void addArrayList(Node firstInList) { boolean lastWasEmpty = false; for (Node n = firstInList; n != null; n = n.getNext()) { if (n != firstInList) { cc.listSeparator(); } addExpr(n, 1, Context.OTHER); lastWasEmpty = n.isEmpty(); } if (lastWasEmpty) { cc.listSeparator(); } }
[ "void", "addArrayList", "(", "Node", "firstInList", ")", "{", "boolean", "lastWasEmpty", "=", "false", ";", "for", "(", "Node", "n", "=", "firstInList", ";", "n", "!=", "null", ";", "n", "=", "n", ".", "getNext", "(", ")", ")", "{", "if", "(", "n", "!=", "firstInList", ")", "{", "cc", ".", "listSeparator", "(", ")", ";", "}", "addExpr", "(", "n", ",", "1", ",", "Context", ".", "OTHER", ")", ";", "lastWasEmpty", "=", "n", ".", "isEmpty", "(", ")", ";", "}", "if", "(", "lastWasEmpty", ")", "{", "cc", ".", "listSeparator", "(", ")", ";", "}", "}" ]
This function adds a comma-separated list as is specified by an ARRAYLIT node with the associated skipIndexes array. This is a space optimization since we avoid creating a whole Node object for each empty array literal slot. @param firstInList The first in the node list (chained through the next property).
[ "This", "function", "adds", "a", "comma", "-", "separated", "list", "as", "is", "specified", "by", "an", "ARRAYLIT", "node", "with", "the", "associated", "skipIndexes", "array", ".", "This", "is", "a", "space", "optimization", "since", "we", "avoid", "creating", "a", "whole", "Node", "object", "for", "each", "empty", "array", "literal", "slot", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CodeGenerator.java#L1712-L1725
24,371
google/closure-compiler
src/com/google/javascript/jscomp/CodeGenerator.java
CodeGenerator.escapeUnrecognizedCharacters
private String escapeUnrecognizedCharacters(String s) { // TODO(yitingwang) Move this method to a suitable place StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { // From the SingleEscapeCharacter grammar production. case '\b': case '\f': case '\n': case '\r': case '\t': case '\\': case '\"': case '\'': case '$': case '`': case '\u2028': case '\u2029': sb.append(c); break; default: if ((outputCharsetEncoder != null && outputCharsetEncoder.canEncode(c)) || (c > 0x1f && c < 0x7f)) { // If we're given an outputCharsetEncoder, then check if the character can be // represented in this character set. If no charsetEncoder provided - pass straight // Latin characters through, and escape the rest. Doing the explicit character check is // measurably faster than using the CharsetEncoder. sb.append(c); } else { // Other characters can be misinterpreted by some JS parsers, // or perhaps mangled by proxies along the way, // so we play it safe and Unicode escape them. Util.appendHexJavaScriptRepresentation(sb, c); } } } return sb.toString(); }
java
private String escapeUnrecognizedCharacters(String s) { // TODO(yitingwang) Move this method to a suitable place StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { // From the SingleEscapeCharacter grammar production. case '\b': case '\f': case '\n': case '\r': case '\t': case '\\': case '\"': case '\'': case '$': case '`': case '\u2028': case '\u2029': sb.append(c); break; default: if ((outputCharsetEncoder != null && outputCharsetEncoder.canEncode(c)) || (c > 0x1f && c < 0x7f)) { // If we're given an outputCharsetEncoder, then check if the character can be // represented in this character set. If no charsetEncoder provided - pass straight // Latin characters through, and escape the rest. Doing the explicit character check is // measurably faster than using the CharsetEncoder. sb.append(c); } else { // Other characters can be misinterpreted by some JS parsers, // or perhaps mangled by proxies along the way, // so we play it safe and Unicode escape them. Util.appendHexJavaScriptRepresentation(sb, c); } } } return sb.toString(); }
[ "private", "String", "escapeUnrecognizedCharacters", "(", "String", "s", ")", "{", "// TODO(yitingwang) Move this method to a suitable place", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", "(", ")", ";", "i", "++", ")", "{", "char", "c", "=", "s", ".", "charAt", "(", "i", ")", ";", "switch", "(", "c", ")", "{", "// From the SingleEscapeCharacter grammar production.", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "sb", ".", "append", "(", "c", ")", ";", "break", ";", "default", ":", "if", "(", "(", "outputCharsetEncoder", "!=", "null", "&&", "outputCharsetEncoder", ".", "canEncode", "(", "c", ")", ")", "||", "(", "c", ">", "0x1f", "&&", "c", "<", "0x7f", ")", ")", "{", "// If we're given an outputCharsetEncoder, then check if the character can be", "// represented in this character set. If no charsetEncoder provided - pass straight", "// Latin characters through, and escape the rest. Doing the explicit character check is", "// measurably faster than using the CharsetEncoder.", "sb", ".", "append", "(", "c", ")", ";", "}", "else", "{", "// Other characters can be misinterpreted by some JS parsers,", "// or perhaps mangled by proxies along the way,", "// so we play it safe and Unicode escape them.", "Util", ".", "appendHexJavaScriptRepresentation", "(", "sb", ",", "c", ")", ";", "}", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Helper to escape the characters that might be misinterpreted @param s the string to modify @return the string with unrecognizable characters escaped.
[ "Helper", "to", "escape", "the", "characters", "that", "might", "be", "misinterpreted" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CodeGenerator.java#L1927-L1965
24,372
google/closure-compiler
src/com/google/javascript/jscomp/CodeGenerator.java
CodeGenerator.getFirstNonEmptyChild
private static Node getFirstNonEmptyChild(Node n) { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.isBlock()) { Node result = getFirstNonEmptyChild(c); if (result != null) { return result; } } else if (!c.isEmpty()) { return c; } } return null; }
java
private static Node getFirstNonEmptyChild(Node n) { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.isBlock()) { Node result = getFirstNonEmptyChild(c); if (result != null) { return result; } } else if (!c.isEmpty()) { return c; } } return null; }
[ "private", "static", "Node", "getFirstNonEmptyChild", "(", "Node", "n", ")", "{", "for", "(", "Node", "c", "=", "n", ".", "getFirstChild", "(", ")", ";", "c", "!=", "null", ";", "c", "=", "c", ".", "getNext", "(", ")", ")", "{", "if", "(", "c", ".", "isBlock", "(", ")", ")", "{", "Node", "result", "=", "getFirstNonEmptyChild", "(", "c", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "}", "else", "if", "(", "!", "c", ".", "isEmpty", "(", ")", ")", "{", "return", "c", ";", "}", "}", "return", "null", ";", "}" ]
Gets the first non-empty child of the given node.
[ "Gets", "the", "first", "non", "-", "empty", "child", "of", "the", "given", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CodeGenerator.java#L2007-L2019
24,373
google/closure-compiler
src/com/google/javascript/jscomp/CodeGenerator.java
CodeGenerator.getContextForArrowFunctionBody
private static Context getContextForArrowFunctionBody(Context context) { return context.inForInInitClause() ? Context.START_OF_ARROW_FN_IN_FOR_INIT : Context.START_OF_ARROW_FN_BODY; }
java
private static Context getContextForArrowFunctionBody(Context context) { return context.inForInInitClause() ? Context.START_OF_ARROW_FN_IN_FOR_INIT : Context.START_OF_ARROW_FN_BODY; }
[ "private", "static", "Context", "getContextForArrowFunctionBody", "(", "Context", "context", ")", "{", "return", "context", ".", "inForInInitClause", "(", ")", "?", "Context", ".", "START_OF_ARROW_FN_IN_FOR_INIT", ":", "Context", ".", "START_OF_ARROW_FN_BODY", ";", "}" ]
If we're at the start of an arrow function body, we need parentheses around object literals and object patterns. We also must also pass the IN_FOR_INIT_CLAUSE flag into subexpressions.
[ "If", "we", "re", "at", "the", "start", "of", "an", "arrow", "function", "body", "we", "need", "parentheses", "around", "object", "literals", "and", "object", "patterns", ".", "We", "also", "must", "also", "pass", "the", "IN_FOR_INIT_CLAUSE", "flag", "into", "subexpressions", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CodeGenerator.java#L2093-L2097
24,374
google/closure-compiler
src/com/google/javascript/jscomp/ProcessDefines.java
ProcessDefines.isValidDefineType
private boolean isValidDefineType(JSTypeExpression expression) { JSTypeRegistry registry = compiler.getTypeRegistry(); JSType type = registry.evaluateTypeExpressionInGlobalScope(expression); return !type.isUnknownType() && type.isSubtypeOf(registry.getNativeType(NUMBER_STRING_BOOLEAN)); }
java
private boolean isValidDefineType(JSTypeExpression expression) { JSTypeRegistry registry = compiler.getTypeRegistry(); JSType type = registry.evaluateTypeExpressionInGlobalScope(expression); return !type.isUnknownType() && type.isSubtypeOf(registry.getNativeType(NUMBER_STRING_BOOLEAN)); }
[ "private", "boolean", "isValidDefineType", "(", "JSTypeExpression", "expression", ")", "{", "JSTypeRegistry", "registry", "=", "compiler", ".", "getTypeRegistry", "(", ")", ";", "JSType", "type", "=", "registry", ".", "evaluateTypeExpressionInGlobalScope", "(", "expression", ")", ";", "return", "!", "type", ".", "isUnknownType", "(", ")", "&&", "type", ".", "isSubtypeOf", "(", "registry", ".", "getNativeType", "(", "NUMBER_STRING_BOOLEAN", ")", ")", ";", "}" ]
Only defines of literal number, string, or boolean are supported.
[ "Only", "defines", "of", "literal", "number", "string", "or", "boolean", "are", "supported", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessDefines.java#L192-L197
24,375
google/closure-compiler
src/com/google/javascript/jscomp/ProcessDefines.java
ProcessDefines.getConstantDeclValue
private static Node getConstantDeclValue(Node name) { Node parent = name.getParent(); if (parent == null) { return null; } if (name.isName()) { if (parent.isConst()) { return name.getFirstChild(); } else if (!parent.isVar()) { return null; } JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(name); return jsdoc != null && jsdoc.isConstant() ? name.getFirstChild() : null; } else if (name.isGetProp() && parent.isAssign()) { JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(name); return jsdoc != null && jsdoc.isConstant() ? name.getNext() : null; } return null; }
java
private static Node getConstantDeclValue(Node name) { Node parent = name.getParent(); if (parent == null) { return null; } if (name.isName()) { if (parent.isConst()) { return name.getFirstChild(); } else if (!parent.isVar()) { return null; } JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(name); return jsdoc != null && jsdoc.isConstant() ? name.getFirstChild() : null; } else if (name.isGetProp() && parent.isAssign()) { JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(name); return jsdoc != null && jsdoc.isConstant() ? name.getNext() : null; } return null; }
[ "private", "static", "Node", "getConstantDeclValue", "(", "Node", "name", ")", "{", "Node", "parent", "=", "name", ".", "getParent", "(", ")", ";", "if", "(", "parent", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "name", ".", "isName", "(", ")", ")", "{", "if", "(", "parent", ".", "isConst", "(", ")", ")", "{", "return", "name", ".", "getFirstChild", "(", ")", ";", "}", "else", "if", "(", "!", "parent", ".", "isVar", "(", ")", ")", "{", "return", "null", ";", "}", "JSDocInfo", "jsdoc", "=", "NodeUtil", ".", "getBestJSDocInfo", "(", "name", ")", ";", "return", "jsdoc", "!=", "null", "&&", "jsdoc", ".", "isConstant", "(", ")", "?", "name", ".", "getFirstChild", "(", ")", ":", "null", ";", "}", "else", "if", "(", "name", ".", "isGetProp", "(", ")", "&&", "parent", ".", "isAssign", "(", ")", ")", "{", "JSDocInfo", "jsdoc", "=", "NodeUtil", ".", "getBestJSDocInfo", "(", "name", ")", ";", "return", "jsdoc", "!=", "null", "&&", "jsdoc", ".", "isConstant", "(", ")", "?", "name", ".", "getNext", "(", ")", ":", "null", ";", "}", "return", "null", ";", "}" ]
Checks whether the NAME node is inside either a CONST or a @const VAR. Returns the RHS node if so, otherwise returns null.
[ "Checks", "whether", "the", "NAME", "node", "is", "inside", "either", "a", "CONST", "or", "a" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessDefines.java#L612-L630
24,376
google/closure-compiler
src/com/google/javascript/jscomp/ProcessDefines.java
ProcessDefines.setDefineInfoNotAssignable
private static void setDefineInfoNotAssignable(DefineInfo info, NodeTraversal t) { info.setNotAssignable( format(REASON_DEFINE_NOT_ASSIGNABLE, t.getLineNumber(), t.getSourceName())); }
java
private static void setDefineInfoNotAssignable(DefineInfo info, NodeTraversal t) { info.setNotAssignable( format(REASON_DEFINE_NOT_ASSIGNABLE, t.getLineNumber(), t.getSourceName())); }
[ "private", "static", "void", "setDefineInfoNotAssignable", "(", "DefineInfo", "info", ",", "NodeTraversal", "t", ")", "{", "info", ".", "setNotAssignable", "(", "format", "(", "REASON_DEFINE_NOT_ASSIGNABLE", ",", "t", ".", "getLineNumber", "(", ")", ",", "t", ".", "getSourceName", "(", ")", ")", ")", ";", "}" ]
Records the fact that because of the current node in the node traversal, the define can't ever be assigned again. @param info Represents the define variable. @param t The current traversal.
[ "Records", "the", "fact", "that", "because", "of", "the", "current", "node", "in", "the", "node", "traversal", "the", "define", "can", "t", "ever", "be", "assigned", "again", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessDefines.java#L639-L642
24,377
google/closure-compiler
src/com/google/javascript/jscomp/ExternExportsPass.java
ExternExportsPass.computePathPrefixes
private static ImmutableList<String> computePathPrefixes(String path) { List<String> pieces = Q_NAME_SPLITTER.splitToList(path); ImmutableList.Builder<String> pathPrefixes = ImmutableList.builder(); String partial = pieces.get(0); // There will always be at least 1. pathPrefixes.add(partial); for (int i = 1; i < pieces.size(); i++) { partial = Q_NAME_JOINER.join(partial, pieces.get(i)); pathPrefixes.add(partial); } return pathPrefixes.build(); }
java
private static ImmutableList<String> computePathPrefixes(String path) { List<String> pieces = Q_NAME_SPLITTER.splitToList(path); ImmutableList.Builder<String> pathPrefixes = ImmutableList.builder(); String partial = pieces.get(0); // There will always be at least 1. pathPrefixes.add(partial); for (int i = 1; i < pieces.size(); i++) { partial = Q_NAME_JOINER.join(partial, pieces.get(i)); pathPrefixes.add(partial); } return pathPrefixes.build(); }
[ "private", "static", "ImmutableList", "<", "String", ">", "computePathPrefixes", "(", "String", "path", ")", "{", "List", "<", "String", ">", "pieces", "=", "Q_NAME_SPLITTER", ".", "splitToList", "(", "path", ")", ";", "ImmutableList", ".", "Builder", "<", "String", ">", "pathPrefixes", "=", "ImmutableList", ".", "builder", "(", ")", ";", "String", "partial", "=", "pieces", ".", "get", "(", "0", ")", ";", "// There will always be at least 1.", "pathPrefixes", ".", "add", "(", "partial", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "pieces", ".", "size", "(", ")", ";", "i", "++", ")", "{", "partial", "=", "Q_NAME_JOINER", ".", "join", "(", "partial", ",", "pieces", ".", "get", "(", "i", ")", ")", ";", "pathPrefixes", ".", "add", "(", "partial", ")", ";", "}", "return", "pathPrefixes", ".", "build", "(", ")", ";", "}" ]
Computes a list of the path prefixes constructed from the components of the path. <pre> E.g., if the path is: "a.b.c" then then path prefixes will be ["a","a.b","a.b.c"]: </pre>
[ "Computes", "a", "list", "of", "the", "path", "prefixes", "constructed", "from", "the", "components", "of", "the", "path", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExternExportsPass.java#L477-L489
24,378
google/closure-compiler
src/com/google/javascript/jscomp/ClosureCheckModule.java
ClosureCheckModule.isExportLhs
private boolean isExportLhs(Node lhs) { if (!lhs.isQualifiedName()) { return false; } return lhs.matchesQualifiedName("exports") || (lhs.isGetProp() && lhs.getFirstChild().matchesQualifiedName("exports")); }
java
private boolean isExportLhs(Node lhs) { if (!lhs.isQualifiedName()) { return false; } return lhs.matchesQualifiedName("exports") || (lhs.isGetProp() && lhs.getFirstChild().matchesQualifiedName("exports")); }
[ "private", "boolean", "isExportLhs", "(", "Node", "lhs", ")", "{", "if", "(", "!", "lhs", ".", "isQualifiedName", "(", ")", ")", "{", "return", "false", ";", "}", "return", "lhs", ".", "matchesQualifiedName", "(", "\"exports\"", ")", "||", "(", "lhs", ".", "isGetProp", "(", ")", "&&", "lhs", ".", "getFirstChild", "(", ")", ".", "matchesQualifiedName", "(", "\"exports\"", ")", ")", ";", "}" ]
Is this the LHS of a goog.module export? i.e. Either "exports" or "exports.name"
[ "Is", "this", "the", "LHS", "of", "a", "goog", ".", "module", "export?", "i", ".", "e", ".", "Either", "exports", "or", "exports", ".", "name" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ClosureCheckModule.java#L367-L373
24,379
google/closure-compiler
src/com/google/javascript/jscomp/deps/DefaultDependencyResolver.java
DefaultDependencyResolver.getDependencies
@Override public List<String> getDependencies(String code) throws ServiceException { return getDependencies(parseRequires(code, true)); }
java
@Override public List<String> getDependencies(String code) throws ServiceException { return getDependencies(parseRequires(code, true)); }
[ "@", "Override", "public", "List", "<", "String", ">", "getDependencies", "(", "String", "code", ")", "throws", "ServiceException", "{", "return", "getDependencies", "(", "parseRequires", "(", "code", ",", "true", ")", ")", ";", "}" ]
Gets a list of dependencies for the provided code.
[ "Gets", "a", "list", "of", "dependencies", "for", "the", "provided", "code", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DefaultDependencyResolver.java#L71-L75
24,380
google/closure-compiler
src/com/google/javascript/jscomp/deps/DefaultDependencyResolver.java
DefaultDependencyResolver.getDependencies
@Override public List<String> getDependencies(Collection<String> symbols) throws ServiceException { return getDependencies(symbols, new HashSet<String>()); }
java
@Override public List<String> getDependencies(Collection<String> symbols) throws ServiceException { return getDependencies(symbols, new HashSet<String>()); }
[ "@", "Override", "public", "List", "<", "String", ">", "getDependencies", "(", "Collection", "<", "String", ">", "symbols", ")", "throws", "ServiceException", "{", "return", "getDependencies", "(", "symbols", ",", "new", "HashSet", "<", "String", ">", "(", ")", ")", ";", "}" ]
Gets a list of dependencies for the provided list of symbols.
[ "Gets", "a", "list", "of", "dependencies", "for", "the", "provided", "list", "of", "symbols", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DefaultDependencyResolver.java#L78-L82
24,381
google/closure-compiler
src/com/google/javascript/jscomp/deps/DefaultDependencyResolver.java
DefaultDependencyResolver.parseRequires
private static Collection<String> parseRequires(String code, boolean addClosureBase) { ErrorManager errorManager = new LoggerErrorManager(logger); JsFileParser parser = new JsFileParser(errorManager); DependencyInfo deps = parser.parseFile("<unknown path>", "<unknown path>", code); List<String> requires = new ArrayList<>(); if (addClosureBase) { requires.add(CLOSURE_BASE_PROVIDE); } requires.addAll(deps.getRequiredSymbols()); errorManager.generateReport(); return requires; }
java
private static Collection<String> parseRequires(String code, boolean addClosureBase) { ErrorManager errorManager = new LoggerErrorManager(logger); JsFileParser parser = new JsFileParser(errorManager); DependencyInfo deps = parser.parseFile("<unknown path>", "<unknown path>", code); List<String> requires = new ArrayList<>(); if (addClosureBase) { requires.add(CLOSURE_BASE_PROVIDE); } requires.addAll(deps.getRequiredSymbols()); errorManager.generateReport(); return requires; }
[ "private", "static", "Collection", "<", "String", ">", "parseRequires", "(", "String", "code", ",", "boolean", "addClosureBase", ")", "{", "ErrorManager", "errorManager", "=", "new", "LoggerErrorManager", "(", "logger", ")", ";", "JsFileParser", "parser", "=", "new", "JsFileParser", "(", "errorManager", ")", ";", "DependencyInfo", "deps", "=", "parser", ".", "parseFile", "(", "\"<unknown path>\"", ",", "\"<unknown path>\"", ",", "code", ")", ";", "List", "<", "String", ">", "requires", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "addClosureBase", ")", "{", "requires", ".", "add", "(", "CLOSURE_BASE_PROVIDE", ")", ";", "}", "requires", ".", "addAll", "(", "deps", ".", "getRequiredSymbols", "(", ")", ")", ";", "errorManager", ".", "generateReport", "(", ")", ";", "return", "requires", ";", "}" ]
Parses a block of code for goog.require statements and extracts the required symbols.
[ "Parses", "a", "block", "of", "code", "for", "goog", ".", "require", "statements", "and", "extracts", "the", "required", "symbols", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DefaultDependencyResolver.java#L142-L154
24,382
google/closure-compiler
src/com/google/javascript/jscomp/deps/DefaultDependencyResolver.java
DefaultDependencyResolver.getDependencyInfo
private DependencyInfo getDependencyInfo(String symbol) { for (DependencyFile depsFile : depsFiles) { DependencyInfo di = depsFile.getDependencyInfo(symbol); if (di != null) { return di; } } return null; }
java
private DependencyInfo getDependencyInfo(String symbol) { for (DependencyFile depsFile : depsFiles) { DependencyInfo di = depsFile.getDependencyInfo(symbol); if (di != null) { return di; } } return null; }
[ "private", "DependencyInfo", "getDependencyInfo", "(", "String", "symbol", ")", "{", "for", "(", "DependencyFile", "depsFile", ":", "depsFiles", ")", "{", "DependencyInfo", "di", "=", "depsFile", ".", "getDependencyInfo", "(", "symbol", ")", ";", "if", "(", "di", "!=", "null", ")", "{", "return", "di", ";", "}", "}", "return", "null", ";", "}" ]
Looks at each of the dependency files for dependency information.
[ "Looks", "at", "each", "of", "the", "dependency", "files", "for", "dependency", "information", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DefaultDependencyResolver.java#L157-L165
24,383
google/closure-compiler
src/com/google/javascript/rhino/jstype/NamedType.java
NamedType.resolveViaRegistry
private boolean resolveViaRegistry(ErrorReporter reporter) { JSType type = registry.getType(resolutionScope, reference); if (type != null) { setReferencedAndResolvedType(type, reporter); return true; } return false; }
java
private boolean resolveViaRegistry(ErrorReporter reporter) { JSType type = registry.getType(resolutionScope, reference); if (type != null) { setReferencedAndResolvedType(type, reporter); return true; } return false; }
[ "private", "boolean", "resolveViaRegistry", "(", "ErrorReporter", "reporter", ")", "{", "JSType", "type", "=", "registry", ".", "getType", "(", "resolutionScope", ",", "reference", ")", ";", "if", "(", "type", "!=", "null", ")", "{", "setReferencedAndResolvedType", "(", "type", ",", "reporter", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Resolves a named type by looking it up in the registry. @return True if we resolved successfully.
[ "Resolves", "a", "named", "type", "by", "looking", "it", "up", "in", "the", "registry", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/NamedType.java#L274-L281
24,384
google/closure-compiler
src/com/google/javascript/rhino/jstype/NamedType.java
NamedType.resolveViaProperties
private void resolveViaProperties(ErrorReporter reporter) { String[] componentNames = reference.split("\\.", -1); if (componentNames[0].length() == 0) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); return; } StaticTypedSlot slot = resolutionScope.getSlot(componentNames[0]); if (slot == null) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); return; } // If the first component has a type of 'Unknown', then any type // names using it should be regarded as silently 'Unknown' rather than be // noisy about it. JSType slotType = slot.getType(); if (slotType == null || slotType.isAllType() || slotType.isNoType()) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); return; } // resolving component by component for (int i = 1; i < componentNames.length; i++) { ObjectType parentObj = ObjectType.cast(slotType); if (parentObj == null || componentNames[i].length() == 0) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); return; } if (i == componentNames.length - 1) { // Look for a typedefTypeProp on the definition node of the last component. Node def = parentObj.getPropertyDefSite(componentNames[i]); JSType typedefType = def != null ? def.getTypedefTypeProp() : null; if (typedefType != null) { setReferencedAndResolvedType(typedefType, reporter); return; } } slotType = parentObj.getPropertyType(componentNames[i]); } // Translate "constructor" types to "instance" types. if (slotType == null) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); } else if (slotType.isFunctionType() && (slotType.isConstructor() || slotType.isInterface())) { setReferencedAndResolvedType(slotType.toMaybeFunctionType().getInstanceType(), reporter); } else if (slotType.isNoObjectType()) { setReferencedAndResolvedType( registry.getNativeObjectType(JSTypeNative.NO_OBJECT_TYPE), reporter); } else if (slotType instanceof EnumType) { setReferencedAndResolvedType(((EnumType) slotType).getElementsType(), reporter); } else { // We've been running into issues where people forward-declare // non-named types. (This is legitimate...our dependency management // code doubles as our forward-declaration code.) // // So if the type does resolve to an actual value, but it's not named, // then don't respect the forward declaration. handleUnresolvedType(reporter, slotType.isUnknownType()); } }
java
private void resolveViaProperties(ErrorReporter reporter) { String[] componentNames = reference.split("\\.", -1); if (componentNames[0].length() == 0) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); return; } StaticTypedSlot slot = resolutionScope.getSlot(componentNames[0]); if (slot == null) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); return; } // If the first component has a type of 'Unknown', then any type // names using it should be regarded as silently 'Unknown' rather than be // noisy about it. JSType slotType = slot.getType(); if (slotType == null || slotType.isAllType() || slotType.isNoType()) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); return; } // resolving component by component for (int i = 1; i < componentNames.length; i++) { ObjectType parentObj = ObjectType.cast(slotType); if (parentObj == null || componentNames[i].length() == 0) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); return; } if (i == componentNames.length - 1) { // Look for a typedefTypeProp on the definition node of the last component. Node def = parentObj.getPropertyDefSite(componentNames[i]); JSType typedefType = def != null ? def.getTypedefTypeProp() : null; if (typedefType != null) { setReferencedAndResolvedType(typedefType, reporter); return; } } slotType = parentObj.getPropertyType(componentNames[i]); } // Translate "constructor" types to "instance" types. if (slotType == null) { handleUnresolvedType(reporter, /* ignoreForwardReferencedTypes= */ true); } else if (slotType.isFunctionType() && (slotType.isConstructor() || slotType.isInterface())) { setReferencedAndResolvedType(slotType.toMaybeFunctionType().getInstanceType(), reporter); } else if (slotType.isNoObjectType()) { setReferencedAndResolvedType( registry.getNativeObjectType(JSTypeNative.NO_OBJECT_TYPE), reporter); } else if (slotType instanceof EnumType) { setReferencedAndResolvedType(((EnumType) slotType).getElementsType(), reporter); } else { // We've been running into issues where people forward-declare // non-named types. (This is legitimate...our dependency management // code doubles as our forward-declaration code.) // // So if the type does resolve to an actual value, but it's not named, // then don't respect the forward declaration. handleUnresolvedType(reporter, slotType.isUnknownType()); } }
[ "private", "void", "resolveViaProperties", "(", "ErrorReporter", "reporter", ")", "{", "String", "[", "]", "componentNames", "=", "reference", ".", "split", "(", "\"\\\\.\"", ",", "-", "1", ")", ";", "if", "(", "componentNames", "[", "0", "]", ".", "length", "(", ")", "==", "0", ")", "{", "handleUnresolvedType", "(", "reporter", ",", "/* ignoreForwardReferencedTypes= */", "true", ")", ";", "return", ";", "}", "StaticTypedSlot", "slot", "=", "resolutionScope", ".", "getSlot", "(", "componentNames", "[", "0", "]", ")", ";", "if", "(", "slot", "==", "null", ")", "{", "handleUnresolvedType", "(", "reporter", ",", "/* ignoreForwardReferencedTypes= */", "true", ")", ";", "return", ";", "}", "// If the first component has a type of 'Unknown', then any type", "// names using it should be regarded as silently 'Unknown' rather than be", "// noisy about it.", "JSType", "slotType", "=", "slot", ".", "getType", "(", ")", ";", "if", "(", "slotType", "==", "null", "||", "slotType", ".", "isAllType", "(", ")", "||", "slotType", ".", "isNoType", "(", ")", ")", "{", "handleUnresolvedType", "(", "reporter", ",", "/* ignoreForwardReferencedTypes= */", "true", ")", ";", "return", ";", "}", "// resolving component by component", "for", "(", "int", "i", "=", "1", ";", "i", "<", "componentNames", ".", "length", ";", "i", "++", ")", "{", "ObjectType", "parentObj", "=", "ObjectType", ".", "cast", "(", "slotType", ")", ";", "if", "(", "parentObj", "==", "null", "||", "componentNames", "[", "i", "]", ".", "length", "(", ")", "==", "0", ")", "{", "handleUnresolvedType", "(", "reporter", ",", "/* ignoreForwardReferencedTypes= */", "true", ")", ";", "return", ";", "}", "if", "(", "i", "==", "componentNames", ".", "length", "-", "1", ")", "{", "// Look for a typedefTypeProp on the definition node of the last component.", "Node", "def", "=", "parentObj", ".", "getPropertyDefSite", "(", "componentNames", "[", "i", "]", ")", ";", "JSType", "typedefType", "=", "def", "!=", "null", "?", "def", ".", "getTypedefTypeProp", "(", ")", ":", "null", ";", "if", "(", "typedefType", "!=", "null", ")", "{", "setReferencedAndResolvedType", "(", "typedefType", ",", "reporter", ")", ";", "return", ";", "}", "}", "slotType", "=", "parentObj", ".", "getPropertyType", "(", "componentNames", "[", "i", "]", ")", ";", "}", "// Translate \"constructor\" types to \"instance\" types.", "if", "(", "slotType", "==", "null", ")", "{", "handleUnresolvedType", "(", "reporter", ",", "/* ignoreForwardReferencedTypes= */", "true", ")", ";", "}", "else", "if", "(", "slotType", ".", "isFunctionType", "(", ")", "&&", "(", "slotType", ".", "isConstructor", "(", ")", "||", "slotType", ".", "isInterface", "(", ")", ")", ")", "{", "setReferencedAndResolvedType", "(", "slotType", ".", "toMaybeFunctionType", "(", ")", ".", "getInstanceType", "(", ")", ",", "reporter", ")", ";", "}", "else", "if", "(", "slotType", ".", "isNoObjectType", "(", ")", ")", "{", "setReferencedAndResolvedType", "(", "registry", ".", "getNativeObjectType", "(", "JSTypeNative", ".", "NO_OBJECT_TYPE", ")", ",", "reporter", ")", ";", "}", "else", "if", "(", "slotType", "instanceof", "EnumType", ")", "{", "setReferencedAndResolvedType", "(", "(", "(", "EnumType", ")", "slotType", ")", ".", "getElementsType", "(", ")", ",", "reporter", ")", ";", "}", "else", "{", "// We've been running into issues where people forward-declare", "// non-named types. (This is legitimate...our dependency management", "// code doubles as our forward-declaration code.)", "//", "// So if the type does resolve to an actual value, but it's not named,", "// then don't respect the forward declaration.", "handleUnresolvedType", "(", "reporter", ",", "slotType", ".", "isUnknownType", "(", ")", ")", ";", "}", "}" ]
Resolves a named type by looking up its first component in the scope, and subsequent components as properties. The scope must have been fully parsed and a symbol table constructed.
[ "Resolves", "a", "named", "type", "by", "looking", "up", "its", "first", "component", "in", "the", "scope", "and", "subsequent", "components", "as", "properties", ".", "The", "scope", "must", "have", "been", "fully", "parsed", "and", "a", "symbol", "table", "constructed", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/NamedType.java#L287-L347
24,385
google/closure-compiler
src/com/google/javascript/rhino/jstype/NamedType.java
NamedType.handleUnresolvedType
private void handleUnresolvedType( ErrorReporter reporter, boolean ignoreForwardReferencedTypes) { boolean isForwardDeclared = ignoreForwardReferencedTypes && registry.isForwardDeclaredType(reference); if (!isForwardDeclared) { String msg = "Bad type annotation. Unknown type " + reference; warning(reporter, msg); } else { setReferencedType(new NoResolvedType(registry, getReferenceName(), getTemplateTypes())); if (validator != null) { validator.apply(getReferencedType()); } } setResolvedTypeInternal(getReferencedType()); }
java
private void handleUnresolvedType( ErrorReporter reporter, boolean ignoreForwardReferencedTypes) { boolean isForwardDeclared = ignoreForwardReferencedTypes && registry.isForwardDeclaredType(reference); if (!isForwardDeclared) { String msg = "Bad type annotation. Unknown type " + reference; warning(reporter, msg); } else { setReferencedType(new NoResolvedType(registry, getReferenceName(), getTemplateTypes())); if (validator != null) { validator.apply(getReferencedType()); } } setResolvedTypeInternal(getReferencedType()); }
[ "private", "void", "handleUnresolvedType", "(", "ErrorReporter", "reporter", ",", "boolean", "ignoreForwardReferencedTypes", ")", "{", "boolean", "isForwardDeclared", "=", "ignoreForwardReferencedTypes", "&&", "registry", ".", "isForwardDeclaredType", "(", "reference", ")", ";", "if", "(", "!", "isForwardDeclared", ")", "{", "String", "msg", "=", "\"Bad type annotation. Unknown type \"", "+", "reference", ";", "warning", "(", "reporter", ",", "msg", ")", ";", "}", "else", "{", "setReferencedType", "(", "new", "NoResolvedType", "(", "registry", ",", "getReferenceName", "(", ")", ",", "getTemplateTypes", "(", ")", ")", ")", ";", "if", "(", "validator", "!=", "null", ")", "{", "validator", ".", "apply", "(", "getReferencedType", "(", ")", ")", ";", "}", "}", "setResolvedTypeInternal", "(", "getReferencedType", "(", ")", ")", ";", "}" ]
type name.
[ "type", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/NamedType.java#L384-L399
24,386
google/closure-compiler
src/com/google/javascript/jscomp/CoalesceVariableNames.java
CoalesceVariableNames.computeVariableNamesInterferenceGraph
private UndiGraph<Var, Void> computeVariableNamesInterferenceGraph( ControlFlowGraph<Node> cfg, Set<? extends Var> escaped) { UndiGraph<Var, Void> interferenceGraph = LinkedUndirectedGraph.create(); // First create a node for each non-escaped variable. We add these nodes in the order in which // they appear in the code because we want the names that appear earlier in the code to be used // when coalescing to variables that appear later in the code. List<Var> orderedVariables = liveness.getAllVariablesInOrder(); for (Var v : orderedVariables) { if (escaped.contains(v)) { continue; } // NOTE(user): In theory, we CAN coalesce function names just like any variables. Our // Liveness analysis captures this just like it as described in the specification. However, we // saw some zipped and unzipped size increase after this. We are not totally sure why // that is but, for now, we will respect the dead functions and not play around with it if (v.getParentNode().isFunction()) { continue; } // NOTE: we skip class declarations for a combination of two reasons: // 1. they are block-scoped, so we would need to rewrite them as class expressions // e.g. `class C {}` -> `var C = class {}` to avoid incorrect semantics // (see testDontCoalesceClassDeclarationsWithDestructuringDeclaration). // This is possible but increases pre-gzip code size and complexity. // 2. since function declaration coalescing seems to cause a size regression (as discussed // above) we assume that coalescing class names may cause a similar size regression. if (v.getParentNode().isClass()) { continue; } // Skip lets and consts that have multiple variables declared in them, otherwise this produces // incorrect semantics. See test case "testCapture". // Skipping vars technically isn't needed for correct semantics, but works around a Safari // bug for var redeclarations (https://github.com/google/closure-compiler/issues/3164) if (isInMultipleLvalueDecl(v)) { continue; } interferenceGraph.createNode(v); } // Go through each variable and try to connect them. int v1Index = -1; for (Var v1 : orderedVariables) { v1Index++; int v2Index = -1; NEXT_VAR_PAIR: for (Var v2 : orderedVariables) { v2Index++; // Skip duplicate pairs. if (v1Index > v2Index) { continue; } if (!interferenceGraph.hasNode(v1) || !interferenceGraph.hasNode(v2)) { // Skip nodes that were not added. They are globals and escaped // locals. Also avoid merging a variable with itself. continue NEXT_VAR_PAIR; } if (v1.isParam() && v2.isParam()) { interferenceGraph.connectIfNotFound(v1, null, v2); continue NEXT_VAR_PAIR; } // Go through every CFG node in the program and look at // this variable pair. If they are both live at the same // time, add an edge between them and continue to the next pair. NEXT_CROSS_CFG_NODE: for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) { if (cfg.isImplicitReturn(cfgNode)) { continue NEXT_CROSS_CFG_NODE; } FlowState<LiveVariableLattice> state = cfgNode.getAnnotation(); // Check the live states and add edge when possible. if ((state.getIn().isLive(v1Index) && state.getIn().isLive(v2Index)) || (state.getOut().isLive(v1Index) && state.getOut().isLive(v2Index))) { interferenceGraph.connectIfNotFound(v1, null, v2); continue NEXT_VAR_PAIR; } } // v1 and v2 might not have an edge between them! woohoo. there's // one last sanity check that we have to do: we have to check // if there's a collision *within* the cfg node. NEXT_INTRA_CFG_NODE: for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) { if (cfg.isImplicitReturn(cfgNode)) { continue NEXT_INTRA_CFG_NODE; } FlowState<LiveVariableLattice> state = cfgNode.getAnnotation(); boolean v1OutLive = state.getOut().isLive(v1Index); boolean v2OutLive = state.getOut().isLive(v2Index); CombinedLiveRangeChecker checker = new CombinedLiveRangeChecker( cfgNode.getValue(), new LiveRangeChecker(v1, v2OutLive ? null : v2), new LiveRangeChecker(v2, v1OutLive ? null : v1)); checker.check(cfgNode.getValue()); if (checker.connectIfCrossed(interferenceGraph)) { continue NEXT_VAR_PAIR; } } } } return interferenceGraph; }
java
private UndiGraph<Var, Void> computeVariableNamesInterferenceGraph( ControlFlowGraph<Node> cfg, Set<? extends Var> escaped) { UndiGraph<Var, Void> interferenceGraph = LinkedUndirectedGraph.create(); // First create a node for each non-escaped variable. We add these nodes in the order in which // they appear in the code because we want the names that appear earlier in the code to be used // when coalescing to variables that appear later in the code. List<Var> orderedVariables = liveness.getAllVariablesInOrder(); for (Var v : orderedVariables) { if (escaped.contains(v)) { continue; } // NOTE(user): In theory, we CAN coalesce function names just like any variables. Our // Liveness analysis captures this just like it as described in the specification. However, we // saw some zipped and unzipped size increase after this. We are not totally sure why // that is but, for now, we will respect the dead functions and not play around with it if (v.getParentNode().isFunction()) { continue; } // NOTE: we skip class declarations for a combination of two reasons: // 1. they are block-scoped, so we would need to rewrite them as class expressions // e.g. `class C {}` -> `var C = class {}` to avoid incorrect semantics // (see testDontCoalesceClassDeclarationsWithDestructuringDeclaration). // This is possible but increases pre-gzip code size and complexity. // 2. since function declaration coalescing seems to cause a size regression (as discussed // above) we assume that coalescing class names may cause a similar size regression. if (v.getParentNode().isClass()) { continue; } // Skip lets and consts that have multiple variables declared in them, otherwise this produces // incorrect semantics. See test case "testCapture". // Skipping vars technically isn't needed for correct semantics, but works around a Safari // bug for var redeclarations (https://github.com/google/closure-compiler/issues/3164) if (isInMultipleLvalueDecl(v)) { continue; } interferenceGraph.createNode(v); } // Go through each variable and try to connect them. int v1Index = -1; for (Var v1 : orderedVariables) { v1Index++; int v2Index = -1; NEXT_VAR_PAIR: for (Var v2 : orderedVariables) { v2Index++; // Skip duplicate pairs. if (v1Index > v2Index) { continue; } if (!interferenceGraph.hasNode(v1) || !interferenceGraph.hasNode(v2)) { // Skip nodes that were not added. They are globals and escaped // locals. Also avoid merging a variable with itself. continue NEXT_VAR_PAIR; } if (v1.isParam() && v2.isParam()) { interferenceGraph.connectIfNotFound(v1, null, v2); continue NEXT_VAR_PAIR; } // Go through every CFG node in the program and look at // this variable pair. If they are both live at the same // time, add an edge between them and continue to the next pair. NEXT_CROSS_CFG_NODE: for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) { if (cfg.isImplicitReturn(cfgNode)) { continue NEXT_CROSS_CFG_NODE; } FlowState<LiveVariableLattice> state = cfgNode.getAnnotation(); // Check the live states and add edge when possible. if ((state.getIn().isLive(v1Index) && state.getIn().isLive(v2Index)) || (state.getOut().isLive(v1Index) && state.getOut().isLive(v2Index))) { interferenceGraph.connectIfNotFound(v1, null, v2); continue NEXT_VAR_PAIR; } } // v1 and v2 might not have an edge between them! woohoo. there's // one last sanity check that we have to do: we have to check // if there's a collision *within* the cfg node. NEXT_INTRA_CFG_NODE: for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) { if (cfg.isImplicitReturn(cfgNode)) { continue NEXT_INTRA_CFG_NODE; } FlowState<LiveVariableLattice> state = cfgNode.getAnnotation(); boolean v1OutLive = state.getOut().isLive(v1Index); boolean v2OutLive = state.getOut().isLive(v2Index); CombinedLiveRangeChecker checker = new CombinedLiveRangeChecker( cfgNode.getValue(), new LiveRangeChecker(v1, v2OutLive ? null : v2), new LiveRangeChecker(v2, v1OutLive ? null : v1)); checker.check(cfgNode.getValue()); if (checker.connectIfCrossed(interferenceGraph)) { continue NEXT_VAR_PAIR; } } } } return interferenceGraph; }
[ "private", "UndiGraph", "<", "Var", ",", "Void", ">", "computeVariableNamesInterferenceGraph", "(", "ControlFlowGraph", "<", "Node", ">", "cfg", ",", "Set", "<", "?", "extends", "Var", ">", "escaped", ")", "{", "UndiGraph", "<", "Var", ",", "Void", ">", "interferenceGraph", "=", "LinkedUndirectedGraph", ".", "create", "(", ")", ";", "// First create a node for each non-escaped variable. We add these nodes in the order in which", "// they appear in the code because we want the names that appear earlier in the code to be used", "// when coalescing to variables that appear later in the code.", "List", "<", "Var", ">", "orderedVariables", "=", "liveness", ".", "getAllVariablesInOrder", "(", ")", ";", "for", "(", "Var", "v", ":", "orderedVariables", ")", "{", "if", "(", "escaped", ".", "contains", "(", "v", ")", ")", "{", "continue", ";", "}", "// NOTE(user): In theory, we CAN coalesce function names just like any variables. Our", "// Liveness analysis captures this just like it as described in the specification. However, we", "// saw some zipped and unzipped size increase after this. We are not totally sure why", "// that is but, for now, we will respect the dead functions and not play around with it", "if", "(", "v", ".", "getParentNode", "(", ")", ".", "isFunction", "(", ")", ")", "{", "continue", ";", "}", "// NOTE: we skip class declarations for a combination of two reasons:", "// 1. they are block-scoped, so we would need to rewrite them as class expressions", "// e.g. `class C {}` -> `var C = class {}` to avoid incorrect semantics", "// (see testDontCoalesceClassDeclarationsWithDestructuringDeclaration).", "// This is possible but increases pre-gzip code size and complexity.", "// 2. since function declaration coalescing seems to cause a size regression (as discussed", "// above) we assume that coalescing class names may cause a similar size regression.", "if", "(", "v", ".", "getParentNode", "(", ")", ".", "isClass", "(", ")", ")", "{", "continue", ";", "}", "// Skip lets and consts that have multiple variables declared in them, otherwise this produces", "// incorrect semantics. See test case \"testCapture\".", "// Skipping vars technically isn't needed for correct semantics, but works around a Safari", "// bug for var redeclarations (https://github.com/google/closure-compiler/issues/3164)", "if", "(", "isInMultipleLvalueDecl", "(", "v", ")", ")", "{", "continue", ";", "}", "interferenceGraph", ".", "createNode", "(", "v", ")", ";", "}", "// Go through each variable and try to connect them.", "int", "v1Index", "=", "-", "1", ";", "for", "(", "Var", "v1", ":", "orderedVariables", ")", "{", "v1Index", "++", ";", "int", "v2Index", "=", "-", "1", ";", "NEXT_VAR_PAIR", ":", "for", "(", "Var", "v2", ":", "orderedVariables", ")", "{", "v2Index", "++", ";", "// Skip duplicate pairs.", "if", "(", "v1Index", ">", "v2Index", ")", "{", "continue", ";", "}", "if", "(", "!", "interferenceGraph", ".", "hasNode", "(", "v1", ")", "||", "!", "interferenceGraph", ".", "hasNode", "(", "v2", ")", ")", "{", "// Skip nodes that were not added. They are globals and escaped", "// locals. Also avoid merging a variable with itself.", "continue", "NEXT_VAR_PAIR", ";", "}", "if", "(", "v1", ".", "isParam", "(", ")", "&&", "v2", ".", "isParam", "(", ")", ")", "{", "interferenceGraph", ".", "connectIfNotFound", "(", "v1", ",", "null", ",", "v2", ")", ";", "continue", "NEXT_VAR_PAIR", ";", "}", "// Go through every CFG node in the program and look at", "// this variable pair. If they are both live at the same", "// time, add an edge between them and continue to the next pair.", "NEXT_CROSS_CFG_NODE", ":", "for", "(", "DiGraphNode", "<", "Node", ",", "Branch", ">", "cfgNode", ":", "cfg", ".", "getDirectedGraphNodes", "(", ")", ")", "{", "if", "(", "cfg", ".", "isImplicitReturn", "(", "cfgNode", ")", ")", "{", "continue", "NEXT_CROSS_CFG_NODE", ";", "}", "FlowState", "<", "LiveVariableLattice", ">", "state", "=", "cfgNode", ".", "getAnnotation", "(", ")", ";", "// Check the live states and add edge when possible.", "if", "(", "(", "state", ".", "getIn", "(", ")", ".", "isLive", "(", "v1Index", ")", "&&", "state", ".", "getIn", "(", ")", ".", "isLive", "(", "v2Index", ")", ")", "||", "(", "state", ".", "getOut", "(", ")", ".", "isLive", "(", "v1Index", ")", "&&", "state", ".", "getOut", "(", ")", ".", "isLive", "(", "v2Index", ")", ")", ")", "{", "interferenceGraph", ".", "connectIfNotFound", "(", "v1", ",", "null", ",", "v2", ")", ";", "continue", "NEXT_VAR_PAIR", ";", "}", "}", "// v1 and v2 might not have an edge between them! woohoo. there's", "// one last sanity check that we have to do: we have to check", "// if there's a collision *within* the cfg node.", "NEXT_INTRA_CFG_NODE", ":", "for", "(", "DiGraphNode", "<", "Node", ",", "Branch", ">", "cfgNode", ":", "cfg", ".", "getDirectedGraphNodes", "(", ")", ")", "{", "if", "(", "cfg", ".", "isImplicitReturn", "(", "cfgNode", ")", ")", "{", "continue", "NEXT_INTRA_CFG_NODE", ";", "}", "FlowState", "<", "LiveVariableLattice", ">", "state", "=", "cfgNode", ".", "getAnnotation", "(", ")", ";", "boolean", "v1OutLive", "=", "state", ".", "getOut", "(", ")", ".", "isLive", "(", "v1Index", ")", ";", "boolean", "v2OutLive", "=", "state", ".", "getOut", "(", ")", ".", "isLive", "(", "v2Index", ")", ";", "CombinedLiveRangeChecker", "checker", "=", "new", "CombinedLiveRangeChecker", "(", "cfgNode", ".", "getValue", "(", ")", ",", "new", "LiveRangeChecker", "(", "v1", ",", "v2OutLive", "?", "null", ":", "v2", ")", ",", "new", "LiveRangeChecker", "(", "v2", ",", "v1OutLive", "?", "null", ":", "v1", ")", ")", ";", "checker", ".", "check", "(", "cfgNode", ".", "getValue", "(", ")", ")", ";", "if", "(", "checker", ".", "connectIfCrossed", "(", "interferenceGraph", ")", ")", "{", "continue", "NEXT_VAR_PAIR", ";", "}", "}", "}", "}", "return", "interferenceGraph", ";", "}" ]
In order to determine when it is appropriate to coalesce two variables, we use a live variables analysis to make sure they are not alive at the same time. We take every pairing of variables and for every CFG node, determine whether the two variables are alive at the same time. If two variables are alive at the same time, we create an edge between them in the interference graph. The interference graph is the input to a graph coloring algorithm that ensures any interfering variables are marked in different color groups, while variables that can safely be coalesced are assigned the same color group. @param cfg @param escaped we don't want to coalesce any escaped variables @return graph with variable nodes and edges representing variable interference
[ "In", "order", "to", "determine", "when", "it", "is", "appropriate", "to", "coalesce", "two", "variables", "we", "use", "a", "live", "variables", "analysis", "to", "make", "sure", "they", "are", "not", "alive", "at", "the", "same", "time", ".", "We", "take", "every", "pairing", "of", "variables", "and", "for", "every", "CFG", "node", "determine", "whether", "the", "two", "variables", "are", "alive", "at", "the", "same", "time", ".", "If", "two", "variables", "are", "alive", "at", "the", "same", "time", "we", "create", "an", "edge", "between", "them", "in", "the", "interference", "graph", ".", "The", "interference", "graph", "is", "the", "input", "to", "a", "graph", "coloring", "algorithm", "that", "ensures", "any", "interfering", "variables", "are", "marked", "in", "different", "color", "groups", "while", "variables", "that", "can", "safely", "be", "coalesced", "are", "assigned", "the", "same", "color", "group", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CoalesceVariableNames.java#L263-L376
24,387
google/closure-compiler
src/com/google/javascript/jscomp/CoalesceVariableNames.java
CoalesceVariableNames.isInMultipleLvalueDecl
private boolean isInMultipleLvalueDecl(Var v) { Token declarationType = v.declarationType(); switch (declarationType) { case LET: case CONST: case VAR: Node nameDecl = NodeUtil.getEnclosingNode(v.getNode(), NodeUtil::isNameDeclaration); return NodeUtil.findLhsNodesInNode(nameDecl).size() > 1; default: return false; } }
java
private boolean isInMultipleLvalueDecl(Var v) { Token declarationType = v.declarationType(); switch (declarationType) { case LET: case CONST: case VAR: Node nameDecl = NodeUtil.getEnclosingNode(v.getNode(), NodeUtil::isNameDeclaration); return NodeUtil.findLhsNodesInNode(nameDecl).size() > 1; default: return false; } }
[ "private", "boolean", "isInMultipleLvalueDecl", "(", "Var", "v", ")", "{", "Token", "declarationType", "=", "v", ".", "declarationType", "(", ")", ";", "switch", "(", "declarationType", ")", "{", "case", "LET", ":", "case", "CONST", ":", "case", "VAR", ":", "Node", "nameDecl", "=", "NodeUtil", ".", "getEnclosingNode", "(", "v", ".", "getNode", "(", ")", ",", "NodeUtil", "::", "isNameDeclaration", ")", ";", "return", "NodeUtil", ".", "findLhsNodesInNode", "(", "nameDecl", ")", ".", "size", "(", ")", ">", "1", ";", "default", ":", "return", "false", ";", "}", "}" ]
Returns whether this variable's declaration also declares other names. <p>For example, this would return true for `x` in `let [x, y, z] = []`;
[ "Returns", "whether", "this", "variable", "s", "declaration", "also", "declares", "other", "names", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CoalesceVariableNames.java#L383-L394
24,388
google/closure-compiler
src/com/google/javascript/jscomp/CoalesceVariableNames.java
CoalesceVariableNames.removeVarDeclaration
private static void removeVarDeclaration(Node name) { Node var = NodeUtil.getEnclosingNode(name, NodeUtil::isNameDeclaration); Node parent = var.getParent(); if (var.getFirstChild().isDestructuringLhs()) { // convert `const [x] = arr` to `[x] = arr` // a precondition for this method is that `x` is the only lvalue in the destructuring pattern Node destructuringLhs = var.getFirstChild(); Node pattern = destructuringLhs.getFirstChild().detach(); if (NodeUtil.isEnhancedFor(parent)) { var.replaceWith(pattern); } else { Node rvalue = var.getFirstFirstChild().detach(); var.replaceWith(NodeUtil.newExpr(IR.assign(pattern, rvalue).srcref(var))); } } else if (NodeUtil.isEnhancedFor(parent)) { // convert `for (let x of ...` to `for (x of ...` parent.replaceChild(var, name.detach()); } else { // either `var x = 0;` or `var x;` checkState(var.hasOneChild() && var.getFirstChild() == name, var); if (name.hasChildren()) { // convert `let x = 0;` to `x = 0;` Node value = name.removeFirstChild(); var.removeChild(name); Node assign = IR.assign(name, value).srcref(name); // We don't need to wrapped it with EXPR node if it is within a FOR. if (!parent.isVanillaFor()) { assign = NodeUtil.newExpr(assign); } parent.replaceChild(var, assign); } else { // convert `let x;` to `` // and `for (let x;;) {}` to `for (;;) {}` NodeUtil.removeChild(parent, var); } } }
java
private static void removeVarDeclaration(Node name) { Node var = NodeUtil.getEnclosingNode(name, NodeUtil::isNameDeclaration); Node parent = var.getParent(); if (var.getFirstChild().isDestructuringLhs()) { // convert `const [x] = arr` to `[x] = arr` // a precondition for this method is that `x` is the only lvalue in the destructuring pattern Node destructuringLhs = var.getFirstChild(); Node pattern = destructuringLhs.getFirstChild().detach(); if (NodeUtil.isEnhancedFor(parent)) { var.replaceWith(pattern); } else { Node rvalue = var.getFirstFirstChild().detach(); var.replaceWith(NodeUtil.newExpr(IR.assign(pattern, rvalue).srcref(var))); } } else if (NodeUtil.isEnhancedFor(parent)) { // convert `for (let x of ...` to `for (x of ...` parent.replaceChild(var, name.detach()); } else { // either `var x = 0;` or `var x;` checkState(var.hasOneChild() && var.getFirstChild() == name, var); if (name.hasChildren()) { // convert `let x = 0;` to `x = 0;` Node value = name.removeFirstChild(); var.removeChild(name); Node assign = IR.assign(name, value).srcref(name); // We don't need to wrapped it with EXPR node if it is within a FOR. if (!parent.isVanillaFor()) { assign = NodeUtil.newExpr(assign); } parent.replaceChild(var, assign); } else { // convert `let x;` to `` // and `for (let x;;) {}` to `for (;;) {}` NodeUtil.removeChild(parent, var); } } }
[ "private", "static", "void", "removeVarDeclaration", "(", "Node", "name", ")", "{", "Node", "var", "=", "NodeUtil", ".", "getEnclosingNode", "(", "name", ",", "NodeUtil", "::", "isNameDeclaration", ")", ";", "Node", "parent", "=", "var", ".", "getParent", "(", ")", ";", "if", "(", "var", ".", "getFirstChild", "(", ")", ".", "isDestructuringLhs", "(", ")", ")", "{", "// convert `const [x] = arr` to `[x] = arr`", "// a precondition for this method is that `x` is the only lvalue in the destructuring pattern", "Node", "destructuringLhs", "=", "var", ".", "getFirstChild", "(", ")", ";", "Node", "pattern", "=", "destructuringLhs", ".", "getFirstChild", "(", ")", ".", "detach", "(", ")", ";", "if", "(", "NodeUtil", ".", "isEnhancedFor", "(", "parent", ")", ")", "{", "var", ".", "replaceWith", "(", "pattern", ")", ";", "}", "else", "{", "Node", "rvalue", "=", "var", ".", "getFirstFirstChild", "(", ")", ".", "detach", "(", ")", ";", "var", ".", "replaceWith", "(", "NodeUtil", ".", "newExpr", "(", "IR", ".", "assign", "(", "pattern", ",", "rvalue", ")", ".", "srcref", "(", "var", ")", ")", ")", ";", "}", "}", "else", "if", "(", "NodeUtil", ".", "isEnhancedFor", "(", "parent", ")", ")", "{", "// convert `for (let x of ...` to `for (x of ...`", "parent", ".", "replaceChild", "(", "var", ",", "name", ".", "detach", "(", ")", ")", ";", "}", "else", "{", "// either `var x = 0;` or `var x;`", "checkState", "(", "var", ".", "hasOneChild", "(", ")", "&&", "var", ".", "getFirstChild", "(", ")", "==", "name", ",", "var", ")", ";", "if", "(", "name", ".", "hasChildren", "(", ")", ")", "{", "// convert `let x = 0;` to `x = 0;`", "Node", "value", "=", "name", ".", "removeFirstChild", "(", ")", ";", "var", ".", "removeChild", "(", "name", ")", ";", "Node", "assign", "=", "IR", ".", "assign", "(", "name", ",", "value", ")", ".", "srcref", "(", "name", ")", ";", "// We don't need to wrapped it with EXPR node if it is within a FOR.", "if", "(", "!", "parent", ".", "isVanillaFor", "(", ")", ")", "{", "assign", "=", "NodeUtil", ".", "newExpr", "(", "assign", ")", ";", "}", "parent", ".", "replaceChild", "(", "var", ",", "assign", ")", ";", "}", "else", "{", "// convert `let x;` to ``", "// and `for (let x;;) {}` to `for (;;) {}`", "NodeUtil", ".", "removeChild", "(", "parent", ",", "var", ")", ";", "}", "}", "}" ]
Remove variable declaration if the variable has been coalesced with another variable that has already been declared. <p>A precondition is that if the variable has already been declared, it must be the only lvalue in said declaration. For example, this method will not accept `var x = 1, y = 2`. In theory we could leave in the `var` declaration, but var shadowing of params triggers a Safari bug: https://bugs.webkit.org/show_bug.cgi?id=182414 Another @param name name node of the variable being coalesced
[ "Remove", "variable", "declaration", "if", "the", "variable", "has", "been", "coalesced", "with", "another", "variable", "that", "has", "already", "been", "declared", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CoalesceVariableNames.java#L462-L501
24,389
google/closure-compiler
src/com/google/javascript/jscomp/CoalesceVariableNames.java
CoalesceVariableNames.makeDeclarationVar
private static void makeDeclarationVar(Var coalescedName) { if (coalescedName.isLet() || coalescedName.isConst()) { Node declNode = NodeUtil.getEnclosingNode(coalescedName.getParentNode(), NodeUtil::isNameDeclaration); declNode.setToken(Token.VAR); } }
java
private static void makeDeclarationVar(Var coalescedName) { if (coalescedName.isLet() || coalescedName.isConst()) { Node declNode = NodeUtil.getEnclosingNode(coalescedName.getParentNode(), NodeUtil::isNameDeclaration); declNode.setToken(Token.VAR); } }
[ "private", "static", "void", "makeDeclarationVar", "(", "Var", "coalescedName", ")", "{", "if", "(", "coalescedName", ".", "isLet", "(", ")", "||", "coalescedName", ".", "isConst", "(", ")", ")", "{", "Node", "declNode", "=", "NodeUtil", ".", "getEnclosingNode", "(", "coalescedName", ".", "getParentNode", "(", ")", ",", "NodeUtil", "::", "isNameDeclaration", ")", ";", "declNode", ".", "setToken", "(", "Token", ".", "VAR", ")", ";", "}", "}" ]
Because the code has already been normalized by the time this pass runs, we can safely redeclare any let and const coalesced variables as vars
[ "Because", "the", "code", "has", "already", "been", "normalized", "by", "the", "time", "this", "pass", "runs", "we", "can", "safely", "redeclare", "any", "let", "and", "const", "coalesced", "variables", "as", "vars" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CoalesceVariableNames.java#L507-L513
24,390
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteClass.java
Es6RewriteClass.visitMethod
private void visitMethod(Node member, ClassDeclarationMetadata metadata) { Node qualifiedMemberAccess = getQualifiedMemberAccess(member, metadata); Node method = member.getLastChild().detach(); // Use the source info from the method (a FUNCTION) not the MEMBER_FUNCTION_DEF // because the MEMBER_FUNCTION_DEf source info only corresponds to the identifier Node assign = astFactory.createAssign(qualifiedMemberAccess, method).useSourceInfoIfMissingFrom(method); JSDocInfo info = member.getJSDocInfo(); if (member.isStaticMember() && NodeUtil.referencesThis(assign.getLastChild())) { JSDocInfoBuilder memberDoc = JSDocInfoBuilder.maybeCopyFrom(info); memberDoc.recordThisType( new JSTypeExpression(new Node(Token.BANG, new Node(Token.QMARK)), member.getSourceFileName())); info = memberDoc.build(); } if (info != null) { assign.setJSDocInfo(info); } Node newNode = NodeUtil.newExpr(assign); metadata.insertNodeAndAdvance(newNode); }
java
private void visitMethod(Node member, ClassDeclarationMetadata metadata) { Node qualifiedMemberAccess = getQualifiedMemberAccess(member, metadata); Node method = member.getLastChild().detach(); // Use the source info from the method (a FUNCTION) not the MEMBER_FUNCTION_DEF // because the MEMBER_FUNCTION_DEf source info only corresponds to the identifier Node assign = astFactory.createAssign(qualifiedMemberAccess, method).useSourceInfoIfMissingFrom(method); JSDocInfo info = member.getJSDocInfo(); if (member.isStaticMember() && NodeUtil.referencesThis(assign.getLastChild())) { JSDocInfoBuilder memberDoc = JSDocInfoBuilder.maybeCopyFrom(info); memberDoc.recordThisType( new JSTypeExpression(new Node(Token.BANG, new Node(Token.QMARK)), member.getSourceFileName())); info = memberDoc.build(); } if (info != null) { assign.setJSDocInfo(info); } Node newNode = NodeUtil.newExpr(assign); metadata.insertNodeAndAdvance(newNode); }
[ "private", "void", "visitMethod", "(", "Node", "member", ",", "ClassDeclarationMetadata", "metadata", ")", "{", "Node", "qualifiedMemberAccess", "=", "getQualifiedMemberAccess", "(", "member", ",", "metadata", ")", ";", "Node", "method", "=", "member", ".", "getLastChild", "(", ")", ".", "detach", "(", ")", ";", "// Use the source info from the method (a FUNCTION) not the MEMBER_FUNCTION_DEF", "// because the MEMBER_FUNCTION_DEf source info only corresponds to the identifier", "Node", "assign", "=", "astFactory", ".", "createAssign", "(", "qualifiedMemberAccess", ",", "method", ")", ".", "useSourceInfoIfMissingFrom", "(", "method", ")", ";", "JSDocInfo", "info", "=", "member", ".", "getJSDocInfo", "(", ")", ";", "if", "(", "member", ".", "isStaticMember", "(", ")", "&&", "NodeUtil", ".", "referencesThis", "(", "assign", ".", "getLastChild", "(", ")", ")", ")", "{", "JSDocInfoBuilder", "memberDoc", "=", "JSDocInfoBuilder", ".", "maybeCopyFrom", "(", "info", ")", ";", "memberDoc", ".", "recordThisType", "(", "new", "JSTypeExpression", "(", "new", "Node", "(", "Token", ".", "BANG", ",", "new", "Node", "(", "Token", ".", "QMARK", ")", ")", ",", "member", ".", "getSourceFileName", "(", ")", ")", ")", ";", "info", "=", "memberDoc", ".", "build", "(", ")", ";", "}", "if", "(", "info", "!=", "null", ")", "{", "assign", ".", "setJSDocInfo", "(", "info", ")", ";", "}", "Node", "newNode", "=", "NodeUtil", ".", "newExpr", "(", "assign", ")", ";", "metadata", ".", "insertNodeAndAdvance", "(", "newNode", ")", ";", "}" ]
Handles transpilation of a standard class member function. Getters, setters, and the constructor are not handled here.
[ "Handles", "transpilation", "of", "a", "standard", "class", "member", "function", ".", "Getters", "setters", "and", "the", "constructor", "are", "not", "handled", "here", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteClass.java#L500-L523
24,391
google/closure-compiler
src/com/google/javascript/jscomp/modules/ResolveExportResult.java
ResolveExportResult.copy
ResolveExportResult copy(Node sourceNode, Binding.CreatedBy createdBy) { checkNotNull(sourceNode); if (binding == null) { return this; } return new ResolveExportResult(binding.copy(sourceNode, createdBy), state); }
java
ResolveExportResult copy(Node sourceNode, Binding.CreatedBy createdBy) { checkNotNull(sourceNode); if (binding == null) { return this; } return new ResolveExportResult(binding.copy(sourceNode, createdBy), state); }
[ "ResolveExportResult", "copy", "(", "Node", "sourceNode", ",", "Binding", ".", "CreatedBy", "createdBy", ")", "{", "checkNotNull", "(", "sourceNode", ")", ";", "if", "(", "binding", "==", "null", ")", "{", "return", "this", ";", "}", "return", "new", "ResolveExportResult", "(", "binding", ".", "copy", "(", "sourceNode", ",", "createdBy", ")", ",", "state", ")", ";", "}" ]
Creates a new result that has the given node for the source of the binding and given type of binding.
[ "Creates", "a", "new", "result", "that", "has", "the", "given", "node", "for", "the", "source", "of", "the", "binding", "and", "given", "type", "of", "binding", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/modules/ResolveExportResult.java#L47-L55
24,392
google/closure-compiler
src/com/google/debugging/sourcemap/Util.java
Util.appendHexJavaScriptRepresentation
private static void appendHexJavaScriptRepresentation( int codePoint, Appendable out) throws IOException { if (Character.isSupplementaryCodePoint(codePoint)) { // Handle supplementary Unicode values which are not representable in // JavaScript. We deal with these by escaping them as two 4B sequences // so that they will round-trip properly when sent from Java to JavaScript // and back. char[] surrogates = Character.toChars(codePoint); appendHexJavaScriptRepresentation(surrogates[0], out); appendHexJavaScriptRepresentation(surrogates[1], out); return; } out.append("\\u") .append(HEX_CHARS[(codePoint >>> 12) & 0xf]) .append(HEX_CHARS[(codePoint >>> 8) & 0xf]) .append(HEX_CHARS[(codePoint >>> 4) & 0xf]) .append(HEX_CHARS[codePoint & 0xf]); }
java
private static void appendHexJavaScriptRepresentation( int codePoint, Appendable out) throws IOException { if (Character.isSupplementaryCodePoint(codePoint)) { // Handle supplementary Unicode values which are not representable in // JavaScript. We deal with these by escaping them as two 4B sequences // so that they will round-trip properly when sent from Java to JavaScript // and back. char[] surrogates = Character.toChars(codePoint); appendHexJavaScriptRepresentation(surrogates[0], out); appendHexJavaScriptRepresentation(surrogates[1], out); return; } out.append("\\u") .append(HEX_CHARS[(codePoint >>> 12) & 0xf]) .append(HEX_CHARS[(codePoint >>> 8) & 0xf]) .append(HEX_CHARS[(codePoint >>> 4) & 0xf]) .append(HEX_CHARS[codePoint & 0xf]); }
[ "private", "static", "void", "appendHexJavaScriptRepresentation", "(", "int", "codePoint", ",", "Appendable", "out", ")", "throws", "IOException", "{", "if", "(", "Character", ".", "isSupplementaryCodePoint", "(", "codePoint", ")", ")", "{", "// Handle supplementary Unicode values which are not representable in", "// JavaScript. We deal with these by escaping them as two 4B sequences", "// so that they will round-trip properly when sent from Java to JavaScript", "// and back.", "char", "[", "]", "surrogates", "=", "Character", ".", "toChars", "(", "codePoint", ")", ";", "appendHexJavaScriptRepresentation", "(", "surrogates", "[", "0", "]", ",", "out", ")", ";", "appendHexJavaScriptRepresentation", "(", "surrogates", "[", "1", "]", ",", "out", ")", ";", "return", ";", "}", "out", ".", "append", "(", "\"\\\\u\"", ")", ".", "append", "(", "HEX_CHARS", "[", "(", "codePoint", ">>>", "12", ")", "&", "0xf", "]", ")", ".", "append", "(", "HEX_CHARS", "[", "(", "codePoint", ">>>", "8", ")", "&", "0xf", "]", ")", ".", "append", "(", "HEX_CHARS", "[", "(", "codePoint", ">>>", "4", ")", "&", "0xf", "]", ")", ".", "append", "(", "HEX_CHARS", "[", "codePoint", "&", "0xf", "]", ")", ";", "}" ]
Returns a JavaScript representation of the character in a hex escaped format. @param codePoint The code point to append. @param out The buffer to which the hex representation should be appended.
[ "Returns", "a", "JavaScript", "representation", "of", "the", "character", "in", "a", "hex", "escaped", "format", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/Util.java#L111-L129
24,393
google/closure-compiler
src/com/google/javascript/jscomp/DisambiguateProperties.java
DisambiguateProperties.getProperty
protected Property getProperty(String name) { if (!properties.containsKey(name)) { properties.put(name, new Property(name)); } return properties.get(name); }
java
protected Property getProperty(String name) { if (!properties.containsKey(name)) { properties.put(name, new Property(name)); } return properties.get(name); }
[ "protected", "Property", "getProperty", "(", "String", "name", ")", "{", "if", "(", "!", "properties", ".", "containsKey", "(", "name", ")", ")", "{", "properties", ".", "put", "(", "name", ",", "new", "Property", "(", "name", ")", ")", ";", "}", "return", "properties", ".", "get", "(", "name", ")", ";", "}" ]
Returns the property for the given name, creating it if necessary.
[ "Returns", "the", "property", "for", "the", "given", "name", "creating", "it", "if", "necessary", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DisambiguateProperties.java#L407-L412
24,394
google/closure-compiler
src/com/google/javascript/jscomp/DisambiguateProperties.java
DisambiguateProperties.renameProperties
void renameProperties() { int propsRenamed = 0; int propsSkipped = 0; int instancesRenamed = 0; int instancesSkipped = 0; int singleTypeProps = 0; Set<String> reported = new HashSet<>(); for (Property prop : properties.values()) { if (prop.shouldRename()) { UnionFind<JSType> pTypes = prop.getTypes(); Map<JSType, String> propNames = buildPropNames(prop); ++propsRenamed; prop.expandTypesToSkip(); // This loop has poor locality, because instead of walking the AST, // we iterate over all accesses of a property, which can be in very // different places in the code. for (Map.Entry<Node, JSType> entry : prop.rootTypesByNode.entrySet()) { Node node = entry.getKey(); JSType rootType = entry.getValue(); if (prop.shouldRename(rootType)) { String newName = propNames.get(pTypes.find(rootType)); node.setString(newName); compiler.reportChangeToEnclosingScope(node); ++instancesRenamed; } else { ++instancesSkipped; CheckLevel checkLevelForProp = propertiesToErrorFor.get(prop.name); if (checkLevelForProp != null && checkLevelForProp != CheckLevel.OFF && !reported.contains(prop.name)) { reported.add(prop.name); compiler.report(JSError.make( node, checkLevelForProp, Warnings.INVALIDATION_ON_TYPE, prop.name, rootType.toString(), "")); } } } } else { if (prop.skipRenaming) { ++propsSkipped; } else { ++singleTypeProps; } } } if (logger.isLoggable(Level.FINE)) { logger.fine("Renamed " + instancesRenamed + " instances of " + propsRenamed + " properties."); logger.fine("Skipped renaming " + instancesSkipped + " invalidated " + "properties, " + propsSkipped + " instances of properties " + "that were skipped for specific types and " + singleTypeProps + " properties that were referenced from only one type."); } }
java
void renameProperties() { int propsRenamed = 0; int propsSkipped = 0; int instancesRenamed = 0; int instancesSkipped = 0; int singleTypeProps = 0; Set<String> reported = new HashSet<>(); for (Property prop : properties.values()) { if (prop.shouldRename()) { UnionFind<JSType> pTypes = prop.getTypes(); Map<JSType, String> propNames = buildPropNames(prop); ++propsRenamed; prop.expandTypesToSkip(); // This loop has poor locality, because instead of walking the AST, // we iterate over all accesses of a property, which can be in very // different places in the code. for (Map.Entry<Node, JSType> entry : prop.rootTypesByNode.entrySet()) { Node node = entry.getKey(); JSType rootType = entry.getValue(); if (prop.shouldRename(rootType)) { String newName = propNames.get(pTypes.find(rootType)); node.setString(newName); compiler.reportChangeToEnclosingScope(node); ++instancesRenamed; } else { ++instancesSkipped; CheckLevel checkLevelForProp = propertiesToErrorFor.get(prop.name); if (checkLevelForProp != null && checkLevelForProp != CheckLevel.OFF && !reported.contains(prop.name)) { reported.add(prop.name); compiler.report(JSError.make( node, checkLevelForProp, Warnings.INVALIDATION_ON_TYPE, prop.name, rootType.toString(), "")); } } } } else { if (prop.skipRenaming) { ++propsSkipped; } else { ++singleTypeProps; } } } if (logger.isLoggable(Level.FINE)) { logger.fine("Renamed " + instancesRenamed + " instances of " + propsRenamed + " properties."); logger.fine("Skipped renaming " + instancesSkipped + " invalidated " + "properties, " + propsSkipped + " instances of properties " + "that were skipped for specific types and " + singleTypeProps + " properties that were referenced from only one type."); } }
[ "void", "renameProperties", "(", ")", "{", "int", "propsRenamed", "=", "0", ";", "int", "propsSkipped", "=", "0", ";", "int", "instancesRenamed", "=", "0", ";", "int", "instancesSkipped", "=", "0", ";", "int", "singleTypeProps", "=", "0", ";", "Set", "<", "String", ">", "reported", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "Property", "prop", ":", "properties", ".", "values", "(", ")", ")", "{", "if", "(", "prop", ".", "shouldRename", "(", ")", ")", "{", "UnionFind", "<", "JSType", ">", "pTypes", "=", "prop", ".", "getTypes", "(", ")", ";", "Map", "<", "JSType", ",", "String", ">", "propNames", "=", "buildPropNames", "(", "prop", ")", ";", "++", "propsRenamed", ";", "prop", ".", "expandTypesToSkip", "(", ")", ";", "// This loop has poor locality, because instead of walking the AST,", "// we iterate over all accesses of a property, which can be in very", "// different places in the code.", "for", "(", "Map", ".", "Entry", "<", "Node", ",", "JSType", ">", "entry", ":", "prop", ".", "rootTypesByNode", ".", "entrySet", "(", ")", ")", "{", "Node", "node", "=", "entry", ".", "getKey", "(", ")", ";", "JSType", "rootType", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "prop", ".", "shouldRename", "(", "rootType", ")", ")", "{", "String", "newName", "=", "propNames", ".", "get", "(", "pTypes", ".", "find", "(", "rootType", ")", ")", ";", "node", ".", "setString", "(", "newName", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "node", ")", ";", "++", "instancesRenamed", ";", "}", "else", "{", "++", "instancesSkipped", ";", "CheckLevel", "checkLevelForProp", "=", "propertiesToErrorFor", ".", "get", "(", "prop", ".", "name", ")", ";", "if", "(", "checkLevelForProp", "!=", "null", "&&", "checkLevelForProp", "!=", "CheckLevel", ".", "OFF", "&&", "!", "reported", ".", "contains", "(", "prop", ".", "name", ")", ")", "{", "reported", ".", "add", "(", "prop", ".", "name", ")", ";", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "node", ",", "checkLevelForProp", ",", "Warnings", ".", "INVALIDATION_ON_TYPE", ",", "prop", ".", "name", ",", "rootType", ".", "toString", "(", ")", ",", "\"\"", ")", ")", ";", "}", "}", "}", "}", "else", "{", "if", "(", "prop", ".", "skipRenaming", ")", "{", "++", "propsSkipped", ";", "}", "else", "{", "++", "singleTypeProps", ";", "}", "}", "}", "if", "(", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "logger", ".", "fine", "(", "\"Renamed \"", "+", "instancesRenamed", "+", "\" instances of \"", "+", "propsRenamed", "+", "\" properties.\"", ")", ";", "logger", ".", "fine", "(", "\"Skipped renaming \"", "+", "instancesSkipped", "+", "\" invalidated \"", "+", "\"properties, \"", "+", "propsSkipped", "+", "\" instances of properties \"", "+", "\"that were skipped for specific types and \"", "+", "singleTypeProps", "+", "\" properties that were referenced from only one type.\"", ")", ";", "}", "}" ]
Renames all properties with references on more than one type.
[ "Renames", "all", "properties", "with", "references", "on", "more", "than", "one", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DisambiguateProperties.java#L800-L858
24,395
google/closure-compiler
src/com/google/javascript/jscomp/DisambiguateProperties.java
DisambiguateProperties.buildPropNames
private Map<JSType, String> buildPropNames(Property prop) { UnionFind<JSType> pTypes = prop.getTypes(); String pname = prop.name; Map<JSType, String> names = new HashMap<>(); for (Set<JSType> set : pTypes.allEquivalenceClasses()) { checkState(!set.isEmpty()); JSType representative = pTypes.find(set.iterator().next()); String typeName = null; for (JSType type : set) { String typeString = type.toString(); if (typeName == null || typeString.compareTo(typeName) < 0) { typeName = typeString; } } String newName; if ("{...}".equals(typeName)) { newName = pname; } else { newName = NONWORD_PATTERN.matcher(typeName).replaceAll("_") + '$' + pname; } names.put(representative, newName); } return names; }
java
private Map<JSType, String> buildPropNames(Property prop) { UnionFind<JSType> pTypes = prop.getTypes(); String pname = prop.name; Map<JSType, String> names = new HashMap<>(); for (Set<JSType> set : pTypes.allEquivalenceClasses()) { checkState(!set.isEmpty()); JSType representative = pTypes.find(set.iterator().next()); String typeName = null; for (JSType type : set) { String typeString = type.toString(); if (typeName == null || typeString.compareTo(typeName) < 0) { typeName = typeString; } } String newName; if ("{...}".equals(typeName)) { newName = pname; } else { newName = NONWORD_PATTERN.matcher(typeName).replaceAll("_") + '$' + pname; } names.put(representative, newName); } return names; }
[ "private", "Map", "<", "JSType", ",", "String", ">", "buildPropNames", "(", "Property", "prop", ")", "{", "UnionFind", "<", "JSType", ">", "pTypes", "=", "prop", ".", "getTypes", "(", ")", ";", "String", "pname", "=", "prop", ".", "name", ";", "Map", "<", "JSType", ",", "String", ">", "names", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Set", "<", "JSType", ">", "set", ":", "pTypes", ".", "allEquivalenceClasses", "(", ")", ")", "{", "checkState", "(", "!", "set", ".", "isEmpty", "(", ")", ")", ";", "JSType", "representative", "=", "pTypes", ".", "find", "(", "set", ".", "iterator", "(", ")", ".", "next", "(", ")", ")", ";", "String", "typeName", "=", "null", ";", "for", "(", "JSType", "type", ":", "set", ")", "{", "String", "typeString", "=", "type", ".", "toString", "(", ")", ";", "if", "(", "typeName", "==", "null", "||", "typeString", ".", "compareTo", "(", "typeName", ")", "<", "0", ")", "{", "typeName", "=", "typeString", ";", "}", "}", "String", "newName", ";", "if", "(", "\"{...}\"", ".", "equals", "(", "typeName", ")", ")", "{", "newName", "=", "pname", ";", "}", "else", "{", "newName", "=", "NONWORD_PATTERN", ".", "matcher", "(", "typeName", ")", ".", "replaceAll", "(", "\"_\"", ")", "+", "'", "'", "+", "pname", ";", "}", "names", ".", "put", "(", "representative", ",", "newName", ")", ";", "}", "return", "names", ";", "}" ]
Chooses a name to use for renaming in each equivalence class and maps the representative type of that class to that name.
[ "Chooses", "a", "name", "to", "use", "for", "renaming", "in", "each", "equivalence", "class", "and", "maps", "the", "representative", "type", "of", "that", "class", "to", "that", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DisambiguateProperties.java#L864-L887
24,396
google/closure-compiler
src/com/google/javascript/jscomp/DisambiguateProperties.java
DisambiguateProperties.getTypesToSkipForType
private ImmutableSet<JSType> getTypesToSkipForType(JSType type) { type = type.restrictByNotNullOrUndefined(); if (type.isUnionType()) { ImmutableSet.Builder<JSType> types = ImmutableSet.builder(); types.add(type); for (JSType alt : type.getUnionMembers()) { types.addAll(getTypesToSkipForTypeNonUnion(alt)); } return types.build(); } else if (type.isEnumElementType()) { return getTypesToSkipForType(type.getEnumeratedTypeOfEnumElement()); } return ImmutableSet.copyOf(getTypesToSkipForTypeNonUnion(type)); }
java
private ImmutableSet<JSType> getTypesToSkipForType(JSType type) { type = type.restrictByNotNullOrUndefined(); if (type.isUnionType()) { ImmutableSet.Builder<JSType> types = ImmutableSet.builder(); types.add(type); for (JSType alt : type.getUnionMembers()) { types.addAll(getTypesToSkipForTypeNonUnion(alt)); } return types.build(); } else if (type.isEnumElementType()) { return getTypesToSkipForType(type.getEnumeratedTypeOfEnumElement()); } return ImmutableSet.copyOf(getTypesToSkipForTypeNonUnion(type)); }
[ "private", "ImmutableSet", "<", "JSType", ">", "getTypesToSkipForType", "(", "JSType", "type", ")", "{", "type", "=", "type", ".", "restrictByNotNullOrUndefined", "(", ")", ";", "if", "(", "type", ".", "isUnionType", "(", ")", ")", "{", "ImmutableSet", ".", "Builder", "<", "JSType", ">", "types", "=", "ImmutableSet", ".", "builder", "(", ")", ";", "types", ".", "add", "(", "type", ")", ";", "for", "(", "JSType", "alt", ":", "type", ".", "getUnionMembers", "(", ")", ")", "{", "types", ".", "addAll", "(", "getTypesToSkipForTypeNonUnion", "(", "alt", ")", ")", ";", "}", "return", "types", ".", "build", "(", ")", ";", "}", "else", "if", "(", "type", ".", "isEnumElementType", "(", ")", ")", "{", "return", "getTypesToSkipForType", "(", "type", ".", "getEnumeratedTypeOfEnumElement", "(", ")", ")", ";", "}", "return", "ImmutableSet", ".", "copyOf", "(", "getTypesToSkipForTypeNonUnion", "(", "type", ")", ")", ";", "}" ]
Returns a set of types that should be skipped given the given type. This is necessary for interfaces, as all super interfaces must also be skipped.
[ "Returns", "a", "set", "of", "types", "that", "should", "be", "skipped", "given", "the", "given", "type", ".", "This", "is", "necessary", "for", "interfaces", "as", "all", "super", "interfaces", "must", "also", "be", "skipped", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DisambiguateProperties.java#L917-L930
24,397
google/closure-compiler
src/com/google/javascript/jscomp/DisambiguateProperties.java
DisambiguateProperties.getTypeAlternatives
private Iterable<? extends JSType> getTypeAlternatives(JSType type) { if (type.isUnionType()) { return type.getUnionMembers(); } else { ObjectType objType = type.toMaybeObjectType(); FunctionType constructor = objType != null ? objType.getConstructor() : null; if (constructor != null && constructor.isInterface()) { List<JSType> list = new ArrayList<>(); for (FunctionType impl : constructor.getDirectSubTypes()) { list.add(impl.getInstanceType()); } return list.isEmpty() ? null : list; } else { return null; } } }
java
private Iterable<? extends JSType> getTypeAlternatives(JSType type) { if (type.isUnionType()) { return type.getUnionMembers(); } else { ObjectType objType = type.toMaybeObjectType(); FunctionType constructor = objType != null ? objType.getConstructor() : null; if (constructor != null && constructor.isInterface()) { List<JSType> list = new ArrayList<>(); for (FunctionType impl : constructor.getDirectSubTypes()) { list.add(impl.getInstanceType()); } return list.isEmpty() ? null : list; } else { return null; } } }
[ "private", "Iterable", "<", "?", "extends", "JSType", ">", "getTypeAlternatives", "(", "JSType", "type", ")", "{", "if", "(", "type", ".", "isUnionType", "(", ")", ")", "{", "return", "type", ".", "getUnionMembers", "(", ")", ";", "}", "else", "{", "ObjectType", "objType", "=", "type", ".", "toMaybeObjectType", "(", ")", ";", "FunctionType", "constructor", "=", "objType", "!=", "null", "?", "objType", ".", "getConstructor", "(", ")", ":", "null", ";", "if", "(", "constructor", "!=", "null", "&&", "constructor", ".", "isInterface", "(", ")", ")", "{", "List", "<", "JSType", ">", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "FunctionType", "impl", ":", "constructor", ".", "getDirectSubTypes", "(", ")", ")", "{", "list", ".", "add", "(", "impl", ".", "getInstanceType", "(", ")", ")", ";", "}", "return", "list", ".", "isEmpty", "(", ")", "?", "null", ":", "list", ";", "}", "else", "{", "return", "null", ";", "}", "}", "}" ]
Returns the alternatives if this is a type that represents multiple types, and null if not. Union and interface types can correspond to multiple other types.
[ "Returns", "the", "alternatives", "if", "this", "is", "a", "type", "that", "represents", "multiple", "types", "and", "null", "if", "not", ".", "Union", "and", "interface", "types", "can", "correspond", "to", "multiple", "other", "types", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DisambiguateProperties.java#L960-L976
24,398
google/closure-compiler
src/com/google/javascript/jscomp/DisambiguateProperties.java
DisambiguateProperties.getTypeWithProperty
private ObjectType getTypeWithProperty(String field, JSType type) { if (type == null) { return null; } ObjectType foundType = gtwpCacheGet(field, type); if (foundType != null) { return foundType.equals(bottomObjectType) ? null : foundType; } if (type.isEnumElementType()) { foundType = getTypeWithProperty(field, type.getEnumeratedTypeOfEnumElement()); gtwpCachePut(field, type, foundType == null ? bottomObjectType : foundType); return foundType; } if (!type.isObjectType()) { if (type.isBoxableScalar()) { foundType = getTypeWithProperty(field, type.autobox()); gtwpCachePut(field, type, foundType == null ? bottomObjectType : foundType); return foundType; } else { gtwpCachePut(field, type, bottomObjectType); return null; } } // Ignore the prototype itself at all times. if ("prototype".equals(field)) { gtwpCachePut(field, type, bottomObjectType); return null; } // We look up the prototype chain to find the highest place (if any) that // this appears. This will make references to overridden properties look // like references to the initial property, so they are renamed alike. ObjectType objType = type.toMaybeObjectType(); if (objType != null && objType.getConstructor() != null && objType.getConstructor().isInterface()) { ObjectType topInterface = objType.getTopDefiningInterface(field); if (topInterface != null && topInterface.getConstructor() != null) { foundType = topInterface.getImplicitPrototype(); } } else { while (objType != null && !Objects.equals(objType.getImplicitPrototype(), objType)) { if (objType.hasOwnProperty(field)) { foundType = objType; } objType = objType.getImplicitPrototype(); } } // If the property does not exist on the referenced type but the original // type is an object type, see if any subtype has the property. if (foundType == null) { JSType subtypeWithProp = type.getGreatestSubtypeWithProperty(field); ObjectType maybeType = subtypeWithProp == null ? null : subtypeWithProp.toMaybeObjectType(); // getGreatestSubtypeWithProperty does not guarantee that the property // is defined on the returned type, it just indicates that it might be, // so we have to double check. if (maybeType != null && maybeType.hasOwnProperty(field)) { foundType = maybeType; } } // Unwrap templatized types, they are not unique at runtime. if (foundType != null && foundType.isGenericObjectType()) { foundType = foundType.getRawType(); } // Since disambiguation just looks at names, we must return a uniquely named type rather // than an "equivalent" type. In particular, we must manually unwrap named types // so that the returned type has the correct name. if (foundType != null && foundType.isNamedType()) { foundType = foundType.toMaybeNamedType().getReferencedType().toMaybeObjectType(); } gtwpCachePut(field, type, foundType == null ? bottomObjectType : foundType); return foundType; }
java
private ObjectType getTypeWithProperty(String field, JSType type) { if (type == null) { return null; } ObjectType foundType = gtwpCacheGet(field, type); if (foundType != null) { return foundType.equals(bottomObjectType) ? null : foundType; } if (type.isEnumElementType()) { foundType = getTypeWithProperty(field, type.getEnumeratedTypeOfEnumElement()); gtwpCachePut(field, type, foundType == null ? bottomObjectType : foundType); return foundType; } if (!type.isObjectType()) { if (type.isBoxableScalar()) { foundType = getTypeWithProperty(field, type.autobox()); gtwpCachePut(field, type, foundType == null ? bottomObjectType : foundType); return foundType; } else { gtwpCachePut(field, type, bottomObjectType); return null; } } // Ignore the prototype itself at all times. if ("prototype".equals(field)) { gtwpCachePut(field, type, bottomObjectType); return null; } // We look up the prototype chain to find the highest place (if any) that // this appears. This will make references to overridden properties look // like references to the initial property, so they are renamed alike. ObjectType objType = type.toMaybeObjectType(); if (objType != null && objType.getConstructor() != null && objType.getConstructor().isInterface()) { ObjectType topInterface = objType.getTopDefiningInterface(field); if (topInterface != null && topInterface.getConstructor() != null) { foundType = topInterface.getImplicitPrototype(); } } else { while (objType != null && !Objects.equals(objType.getImplicitPrototype(), objType)) { if (objType.hasOwnProperty(field)) { foundType = objType; } objType = objType.getImplicitPrototype(); } } // If the property does not exist on the referenced type but the original // type is an object type, see if any subtype has the property. if (foundType == null) { JSType subtypeWithProp = type.getGreatestSubtypeWithProperty(field); ObjectType maybeType = subtypeWithProp == null ? null : subtypeWithProp.toMaybeObjectType(); // getGreatestSubtypeWithProperty does not guarantee that the property // is defined on the returned type, it just indicates that it might be, // so we have to double check. if (maybeType != null && maybeType.hasOwnProperty(field)) { foundType = maybeType; } } // Unwrap templatized types, they are not unique at runtime. if (foundType != null && foundType.isGenericObjectType()) { foundType = foundType.getRawType(); } // Since disambiguation just looks at names, we must return a uniquely named type rather // than an "equivalent" type. In particular, we must manually unwrap named types // so that the returned type has the correct name. if (foundType != null && foundType.isNamedType()) { foundType = foundType.toMaybeNamedType().getReferencedType().toMaybeObjectType(); } gtwpCachePut(field, type, foundType == null ? bottomObjectType : foundType); return foundType; }
[ "private", "ObjectType", "getTypeWithProperty", "(", "String", "field", ",", "JSType", "type", ")", "{", "if", "(", "type", "==", "null", ")", "{", "return", "null", ";", "}", "ObjectType", "foundType", "=", "gtwpCacheGet", "(", "field", ",", "type", ")", ";", "if", "(", "foundType", "!=", "null", ")", "{", "return", "foundType", ".", "equals", "(", "bottomObjectType", ")", "?", "null", ":", "foundType", ";", "}", "if", "(", "type", ".", "isEnumElementType", "(", ")", ")", "{", "foundType", "=", "getTypeWithProperty", "(", "field", ",", "type", ".", "getEnumeratedTypeOfEnumElement", "(", ")", ")", ";", "gtwpCachePut", "(", "field", ",", "type", ",", "foundType", "==", "null", "?", "bottomObjectType", ":", "foundType", ")", ";", "return", "foundType", ";", "}", "if", "(", "!", "type", ".", "isObjectType", "(", ")", ")", "{", "if", "(", "type", ".", "isBoxableScalar", "(", ")", ")", "{", "foundType", "=", "getTypeWithProperty", "(", "field", ",", "type", ".", "autobox", "(", ")", ")", ";", "gtwpCachePut", "(", "field", ",", "type", ",", "foundType", "==", "null", "?", "bottomObjectType", ":", "foundType", ")", ";", "return", "foundType", ";", "}", "else", "{", "gtwpCachePut", "(", "field", ",", "type", ",", "bottomObjectType", ")", ";", "return", "null", ";", "}", "}", "// Ignore the prototype itself at all times.", "if", "(", "\"prototype\"", ".", "equals", "(", "field", ")", ")", "{", "gtwpCachePut", "(", "field", ",", "type", ",", "bottomObjectType", ")", ";", "return", "null", ";", "}", "// We look up the prototype chain to find the highest place (if any) that", "// this appears. This will make references to overridden properties look", "// like references to the initial property, so they are renamed alike.", "ObjectType", "objType", "=", "type", ".", "toMaybeObjectType", "(", ")", ";", "if", "(", "objType", "!=", "null", "&&", "objType", ".", "getConstructor", "(", ")", "!=", "null", "&&", "objType", ".", "getConstructor", "(", ")", ".", "isInterface", "(", ")", ")", "{", "ObjectType", "topInterface", "=", "objType", ".", "getTopDefiningInterface", "(", "field", ")", ";", "if", "(", "topInterface", "!=", "null", "&&", "topInterface", ".", "getConstructor", "(", ")", "!=", "null", ")", "{", "foundType", "=", "topInterface", ".", "getImplicitPrototype", "(", ")", ";", "}", "}", "else", "{", "while", "(", "objType", "!=", "null", "&&", "!", "Objects", ".", "equals", "(", "objType", ".", "getImplicitPrototype", "(", ")", ",", "objType", ")", ")", "{", "if", "(", "objType", ".", "hasOwnProperty", "(", "field", ")", ")", "{", "foundType", "=", "objType", ";", "}", "objType", "=", "objType", ".", "getImplicitPrototype", "(", ")", ";", "}", "}", "// If the property does not exist on the referenced type but the original", "// type is an object type, see if any subtype has the property.", "if", "(", "foundType", "==", "null", ")", "{", "JSType", "subtypeWithProp", "=", "type", ".", "getGreatestSubtypeWithProperty", "(", "field", ")", ";", "ObjectType", "maybeType", "=", "subtypeWithProp", "==", "null", "?", "null", ":", "subtypeWithProp", ".", "toMaybeObjectType", "(", ")", ";", "// getGreatestSubtypeWithProperty does not guarantee that the property", "// is defined on the returned type, it just indicates that it might be,", "// so we have to double check.", "if", "(", "maybeType", "!=", "null", "&&", "maybeType", ".", "hasOwnProperty", "(", "field", ")", ")", "{", "foundType", "=", "maybeType", ";", "}", "}", "// Unwrap templatized types, they are not unique at runtime.", "if", "(", "foundType", "!=", "null", "&&", "foundType", ".", "isGenericObjectType", "(", ")", ")", "{", "foundType", "=", "foundType", ".", "getRawType", "(", ")", ";", "}", "// Since disambiguation just looks at names, we must return a uniquely named type rather", "// than an \"equivalent\" type. In particular, we must manually unwrap named types", "// so that the returned type has the correct name.", "if", "(", "foundType", "!=", "null", "&&", "foundType", ".", "isNamedType", "(", ")", ")", "{", "foundType", "=", "foundType", ".", "toMaybeNamedType", "(", ")", ".", "getReferencedType", "(", ")", ".", "toMaybeObjectType", "(", ")", ";", "}", "gtwpCachePut", "(", "field", ",", "type", ",", "foundType", "==", "null", "?", "bottomObjectType", ":", "foundType", ")", ";", "return", "foundType", ";", "}" ]
Returns the type in the chain from the given type that contains the given field or null if it is not found anywhere. Can return a subtype of the input type.
[ "Returns", "the", "type", "in", "the", "chain", "from", "the", "given", "type", "that", "contains", "the", "given", "field", "or", "null", "if", "it", "is", "not", "found", "anywhere", ".", "Can", "return", "a", "subtype", "of", "the", "input", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DisambiguateProperties.java#L983-L1062
24,399
google/closure-compiler
src/com/google/javascript/jscomp/DisambiguateProperties.java
DisambiguateProperties.getInstanceIfPrototype
@Nullable private static JSType getInstanceIfPrototype(JSType maybePrototype) { if (maybePrototype.isFunctionPrototypeType()) { FunctionType constructor = maybePrototype.toObjectType().getOwnerFunction(); if (constructor != null) { if (!constructor.hasInstanceType()) { // this can happen when adding to the prototype of a non-constructor function return null; } return constructor.getInstanceType(); } } return null; }
java
@Nullable private static JSType getInstanceIfPrototype(JSType maybePrototype) { if (maybePrototype.isFunctionPrototypeType()) { FunctionType constructor = maybePrototype.toObjectType().getOwnerFunction(); if (constructor != null) { if (!constructor.hasInstanceType()) { // this can happen when adding to the prototype of a non-constructor function return null; } return constructor.getInstanceType(); } } return null; }
[ "@", "Nullable", "private", "static", "JSType", "getInstanceIfPrototype", "(", "JSType", "maybePrototype", ")", "{", "if", "(", "maybePrototype", ".", "isFunctionPrototypeType", "(", ")", ")", "{", "FunctionType", "constructor", "=", "maybePrototype", ".", "toObjectType", "(", ")", ".", "getOwnerFunction", "(", ")", ";", "if", "(", "constructor", "!=", "null", ")", "{", "if", "(", "!", "constructor", ".", "hasInstanceType", "(", ")", ")", "{", "// this can happen when adding to the prototype of a non-constructor function", "return", "null", ";", "}", "return", "constructor", ".", "getInstanceType", "(", ")", ";", "}", "}", "return", "null", ";", "}" ]
Returns the corresponding instance if `maybePrototype` is a prototype of a constructor, otherwise null
[ "Returns", "the", "corresponding", "instance", "if", "maybePrototype", "is", "a", "prototype", "of", "a", "constructor", "otherwise", "null" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DisambiguateProperties.java#L1076-L1089