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,600
google/closure-compiler
src/com/google/javascript/rhino/jstype/TemplateTypeMap.java
TemplateTypeMap.concatImmutableLists
private static <T> ImmutableList<T> concatImmutableLists( ImmutableList<T> first, ImmutableList<T> second) { if (first.isEmpty()) { return second; } if (second.isEmpty()) { return first; } return ImmutableList.<T>builder().addAll(first).addAll(second).build(); }
java
private static <T> ImmutableList<T> concatImmutableLists( ImmutableList<T> first, ImmutableList<T> second) { if (first.isEmpty()) { return second; } if (second.isEmpty()) { return first; } return ImmutableList.<T>builder().addAll(first).addAll(second).build(); }
[ "private", "static", "<", "T", ">", "ImmutableList", "<", "T", ">", "concatImmutableLists", "(", "ImmutableList", "<", "T", ">", "first", ",", "ImmutableList", "<", "T", ">", "second", ")", "{", "if", "(", "first", ".", "isEmpty", "(", ")", ")", "{", "return", "second", ";", "}", "if", "(", "second", ".", "isEmpty", "(", ")", ")", "{", "return", "first", ";", "}", "return", "ImmutableList", ".", "<", "T", ">", "builder", "(", ")", ".", "addAll", "(", "first", ")", ".", "addAll", "(", "second", ")", ".", "build", "(", ")", ";", "}" ]
Concatenates two ImmutableList instances. If either input is empty, the other is returned; otherwise, a new ImmutableList instance is created that contains the contents of both arguments.
[ "Concatenates", "two", "ImmutableList", "instances", ".", "If", "either", "input", "is", "empty", "the", "other", "is", "returned", ";", "otherwise", "a", "new", "ImmutableList", "instance", "is", "created", "that", "contains", "the", "contents", "of", "both", "arguments", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMap.java#L382-L392
24,601
google/closure-compiler
src/com/google/javascript/jscomp/ModuleIdentifier.java
ModuleIdentifier.forClosure
public static ModuleIdentifier forClosure(String name) { String normalizedName = name; if (normalizedName.startsWith("goog:")) { normalizedName = normalizedName.substring("goog:".length()); } String namespace = normalizedName; String moduleName = normalizedName; int splitPoint = normalizedName.indexOf(':'); if (splitPoint != -1) { moduleName = normalizedName.substring(0, splitPoint); namespace = normalizedName.substring(Math.min(splitPoint + 1, normalizedName.length() - 1)); } return new AutoValue_ModuleIdentifier(normalizedName, namespace, moduleName); }
java
public static ModuleIdentifier forClosure(String name) { String normalizedName = name; if (normalizedName.startsWith("goog:")) { normalizedName = normalizedName.substring("goog:".length()); } String namespace = normalizedName; String moduleName = normalizedName; int splitPoint = normalizedName.indexOf(':'); if (splitPoint != -1) { moduleName = normalizedName.substring(0, splitPoint); namespace = normalizedName.substring(Math.min(splitPoint + 1, normalizedName.length() - 1)); } return new AutoValue_ModuleIdentifier(normalizedName, namespace, moduleName); }
[ "public", "static", "ModuleIdentifier", "forClosure", "(", "String", "name", ")", "{", "String", "normalizedName", "=", "name", ";", "if", "(", "normalizedName", ".", "startsWith", "(", "\"goog:\"", ")", ")", "{", "normalizedName", "=", "normalizedName", ".", "substring", "(", "\"goog:\"", ".", "length", "(", ")", ")", ";", "}", "String", "namespace", "=", "normalizedName", ";", "String", "moduleName", "=", "normalizedName", ";", "int", "splitPoint", "=", "normalizedName", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "splitPoint", "!=", "-", "1", ")", "{", "moduleName", "=", "normalizedName", ".", "substring", "(", "0", ",", "splitPoint", ")", ";", "namespace", "=", "normalizedName", ".", "substring", "(", "Math", ".", "min", "(", "splitPoint", "+", "1", ",", "normalizedName", ".", "length", "(", ")", "-", "1", ")", ")", ";", "}", "return", "new", "AutoValue_ModuleIdentifier", "(", "normalizedName", ",", "namespace", ",", "moduleName", ")", ";", "}" ]
Returns an identifier for a Closure namespace. @param name The Closure namespace. It may be in one of the formats `name.space`, `goog:name.space` or `goog:moduleName:name.space`, where the latter specifies that the module and namespace names are different.
[ "Returns", "an", "identifier", "for", "a", "Closure", "namespace", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ModuleIdentifier.java#L59-L74
24,602
google/closure-compiler
src/com/google/javascript/jscomp/ModuleIdentifier.java
ModuleIdentifier.forFile
public static ModuleIdentifier forFile(String filepath) { String normalizedName = ModuleNames.fileToModuleName(filepath); return new AutoValue_ModuleIdentifier(filepath, normalizedName, normalizedName); }
java
public static ModuleIdentifier forFile(String filepath) { String normalizedName = ModuleNames.fileToModuleName(filepath); return new AutoValue_ModuleIdentifier(filepath, normalizedName, normalizedName); }
[ "public", "static", "ModuleIdentifier", "forFile", "(", "String", "filepath", ")", "{", "String", "normalizedName", "=", "ModuleNames", ".", "fileToModuleName", "(", "filepath", ")", ";", "return", "new", "AutoValue_ModuleIdentifier", "(", "filepath", ",", "normalizedName", ",", "normalizedName", ")", ";", "}" ]
Returns an identifier for an ES or CommonJS module. @param filepath Path to the ES or CommonJS module.
[ "Returns", "an", "identifier", "for", "an", "ES", "or", "CommonJS", "module", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ModuleIdentifier.java#L81-L84
24,603
google/closure-compiler
src/com/google/javascript/jscomp/ValidityCheck.java
ValidityCheck.checkAst
private void checkAst(Node externs, Node root) { astValidator.validateCodeRoot(externs); astValidator.validateCodeRoot(root); }
java
private void checkAst(Node externs, Node root) { astValidator.validateCodeRoot(externs); astValidator.validateCodeRoot(root); }
[ "private", "void", "checkAst", "(", "Node", "externs", ",", "Node", "root", ")", "{", "astValidator", ".", "validateCodeRoot", "(", "externs", ")", ";", "astValidator", ".", "validateCodeRoot", "(", "root", ")", ";", "}" ]
Check that the AST is structurally accurate.
[ "Check", "that", "the", "AST", "is", "structurally", "accurate", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ValidityCheck.java#L66-L69
24,604
google/closure-compiler
src/com/google/javascript/jscomp/ValidityCheck.java
ValidityCheck.checkNormalization
private void checkNormalization(Node externs, Node root) { // Verify nothing has inappropriately denormalize the AST. CodeChangeHandler handler = new ForbiddenChange(); compiler.addChangeHandler(handler); // TODO(johnlenz): Change these normalization checks Preconditions and // Exceptions into Errors so that it is easier to find the root cause // when there are cascading issues. new PrepareAst(compiler, true).process(null, root); if (compiler.getLifeCycleStage().isNormalized()) { (new Normalize(compiler, true)).process(externs, root); if (compiler.getLifeCycleStage().isNormalizedUnobfuscated()) { boolean checkUserDeclarations = true; CompilerPass pass = new Normalize.VerifyConstants(compiler, checkUserDeclarations); pass.process(externs, root); } } compiler.removeChangeHandler(handler); }
java
private void checkNormalization(Node externs, Node root) { // Verify nothing has inappropriately denormalize the AST. CodeChangeHandler handler = new ForbiddenChange(); compiler.addChangeHandler(handler); // TODO(johnlenz): Change these normalization checks Preconditions and // Exceptions into Errors so that it is easier to find the root cause // when there are cascading issues. new PrepareAst(compiler, true).process(null, root); if (compiler.getLifeCycleStage().isNormalized()) { (new Normalize(compiler, true)).process(externs, root); if (compiler.getLifeCycleStage().isNormalizedUnobfuscated()) { boolean checkUserDeclarations = true; CompilerPass pass = new Normalize.VerifyConstants(compiler, checkUserDeclarations); pass.process(externs, root); } } compiler.removeChangeHandler(handler); }
[ "private", "void", "checkNormalization", "(", "Node", "externs", ",", "Node", "root", ")", "{", "// Verify nothing has inappropriately denormalize the AST.", "CodeChangeHandler", "handler", "=", "new", "ForbiddenChange", "(", ")", ";", "compiler", ".", "addChangeHandler", "(", "handler", ")", ";", "// TODO(johnlenz): Change these normalization checks Preconditions and", "// Exceptions into Errors so that it is easier to find the root cause", "// when there are cascading issues.", "new", "PrepareAst", "(", "compiler", ",", "true", ")", ".", "process", "(", "null", ",", "root", ")", ";", "if", "(", "compiler", ".", "getLifeCycleStage", "(", ")", ".", "isNormalized", "(", ")", ")", "{", "(", "new", "Normalize", "(", "compiler", ",", "true", ")", ")", ".", "process", "(", "externs", ",", "root", ")", ";", "if", "(", "compiler", ".", "getLifeCycleStage", "(", ")", ".", "isNormalizedUnobfuscated", "(", ")", ")", "{", "boolean", "checkUserDeclarations", "=", "true", ";", "CompilerPass", "pass", "=", "new", "Normalize", ".", "VerifyConstants", "(", "compiler", ",", "checkUserDeclarations", ")", ";", "pass", ".", "process", "(", "externs", ",", "root", ")", ";", "}", "}", "compiler", ".", "removeChangeHandler", "(", "handler", ")", ";", "}" ]
Verifies that the normalization pass does nothing on an already-normalized tree.
[ "Verifies", "that", "the", "normalization", "pass", "does", "nothing", "on", "an", "already", "-", "normalized", "tree", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ValidityCheck.java#L80-L100
24,605
google/closure-compiler
src/com/google/javascript/jscomp/CrossChunkMethodMotion.java
CrossChunkMethodMotion.moveMethods
private void moveMethods(Collection<NameInfo> allNameInfo) { boolean hasStubDeclaration = idGenerator.hasGeneratedAnyIds(); for (NameInfo nameInfo : allNameInfo) { if (!nameInfo.isReferenced()) { // The code below can't do anything with unreferenced name // infos. They should be skipped to avoid NPE since their // deepestCommonModuleRef is null. continue; } if (nameInfo.readsClosureVariables()) { continue; } JSModule deepestCommonModuleRef = nameInfo.getDeepestCommonModuleRef(); if (deepestCommonModuleRef == null) { compiler.report(JSError.make(NULL_COMMON_MODULE_ERROR)); continue; } Iterator<Symbol> declarations = nameInfo.getDeclarations().descendingIterator(); while (declarations.hasNext()) { Symbol symbol = declarations.next(); if (symbol instanceof PrototypeProperty) { tryToMovePrototypeMethod(nameInfo, deepestCommonModuleRef, (PrototypeProperty) symbol); } else if (symbol instanceof ClassMemberFunction) { tryToMoveMemberFunction(nameInfo, deepestCommonModuleRef, (ClassMemberFunction) symbol); } // else it's a variable definition, and we don't move those. } } if (!noStubFunctions && !hasStubDeclaration && idGenerator .hasGeneratedAnyIds()) { // Declare stub functions in the top-most chunk. Node declarations = compiler.parseSyntheticCode(STUB_DECLARATIONS); NodeUtil.markNewScopesChanged(declarations, compiler); Node firstScript = compiler.getNodeForCodeInsertion(null); firstScript.addChildrenToFront(declarations.removeChildren()); compiler.reportChangeToEnclosingScope(firstScript); } }
java
private void moveMethods(Collection<NameInfo> allNameInfo) { boolean hasStubDeclaration = idGenerator.hasGeneratedAnyIds(); for (NameInfo nameInfo : allNameInfo) { if (!nameInfo.isReferenced()) { // The code below can't do anything with unreferenced name // infos. They should be skipped to avoid NPE since their // deepestCommonModuleRef is null. continue; } if (nameInfo.readsClosureVariables()) { continue; } JSModule deepestCommonModuleRef = nameInfo.getDeepestCommonModuleRef(); if (deepestCommonModuleRef == null) { compiler.report(JSError.make(NULL_COMMON_MODULE_ERROR)); continue; } Iterator<Symbol> declarations = nameInfo.getDeclarations().descendingIterator(); while (declarations.hasNext()) { Symbol symbol = declarations.next(); if (symbol instanceof PrototypeProperty) { tryToMovePrototypeMethod(nameInfo, deepestCommonModuleRef, (PrototypeProperty) symbol); } else if (symbol instanceof ClassMemberFunction) { tryToMoveMemberFunction(nameInfo, deepestCommonModuleRef, (ClassMemberFunction) symbol); } // else it's a variable definition, and we don't move those. } } if (!noStubFunctions && !hasStubDeclaration && idGenerator .hasGeneratedAnyIds()) { // Declare stub functions in the top-most chunk. Node declarations = compiler.parseSyntheticCode(STUB_DECLARATIONS); NodeUtil.markNewScopesChanged(declarations, compiler); Node firstScript = compiler.getNodeForCodeInsertion(null); firstScript.addChildrenToFront(declarations.removeChildren()); compiler.reportChangeToEnclosingScope(firstScript); } }
[ "private", "void", "moveMethods", "(", "Collection", "<", "NameInfo", ">", "allNameInfo", ")", "{", "boolean", "hasStubDeclaration", "=", "idGenerator", ".", "hasGeneratedAnyIds", "(", ")", ";", "for", "(", "NameInfo", "nameInfo", ":", "allNameInfo", ")", "{", "if", "(", "!", "nameInfo", ".", "isReferenced", "(", ")", ")", "{", "// The code below can't do anything with unreferenced name", "// infos. They should be skipped to avoid NPE since their", "// deepestCommonModuleRef is null.", "continue", ";", "}", "if", "(", "nameInfo", ".", "readsClosureVariables", "(", ")", ")", "{", "continue", ";", "}", "JSModule", "deepestCommonModuleRef", "=", "nameInfo", ".", "getDeepestCommonModuleRef", "(", ")", ";", "if", "(", "deepestCommonModuleRef", "==", "null", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "NULL_COMMON_MODULE_ERROR", ")", ")", ";", "continue", ";", "}", "Iterator", "<", "Symbol", ">", "declarations", "=", "nameInfo", ".", "getDeclarations", "(", ")", ".", "descendingIterator", "(", ")", ";", "while", "(", "declarations", ".", "hasNext", "(", ")", ")", "{", "Symbol", "symbol", "=", "declarations", ".", "next", "(", ")", ";", "if", "(", "symbol", "instanceof", "PrototypeProperty", ")", "{", "tryToMovePrototypeMethod", "(", "nameInfo", ",", "deepestCommonModuleRef", ",", "(", "PrototypeProperty", ")", "symbol", ")", ";", "}", "else", "if", "(", "symbol", "instanceof", "ClassMemberFunction", ")", "{", "tryToMoveMemberFunction", "(", "nameInfo", ",", "deepestCommonModuleRef", ",", "(", "ClassMemberFunction", ")", "symbol", ")", ";", "}", "// else it's a variable definition, and we don't move those.", "}", "}", "if", "(", "!", "noStubFunctions", "&&", "!", "hasStubDeclaration", "&&", "idGenerator", ".", "hasGeneratedAnyIds", "(", ")", ")", "{", "// Declare stub functions in the top-most chunk.", "Node", "declarations", "=", "compiler", ".", "parseSyntheticCode", "(", "STUB_DECLARATIONS", ")", ";", "NodeUtil", ".", "markNewScopesChanged", "(", "declarations", ",", "compiler", ")", ";", "Node", "firstScript", "=", "compiler", ".", "getNodeForCodeInsertion", "(", "null", ")", ";", "firstScript", ".", "addChildrenToFront", "(", "declarations", ".", "removeChildren", "(", ")", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "firstScript", ")", ";", "}", "}" ]
Move methods deeper in the chunk graph when possible.
[ "Move", "methods", "deeper", "in", "the", "chunk", "graph", "when", "possible", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CrossChunkMethodMotion.java#L107-L148
24,606
google/closure-compiler
src/com/google/javascript/jscomp/CrossChunkMethodMotion.java
CrossChunkMethodMotion.tryToMoveMemberFunction
private void tryToMoveMemberFunction( NameInfo nameInfo, JSModule deepestCommonModuleRef, ClassMemberFunction classMemberFunction) { // We should only move a property across chunks if: // 1) We can move it deeper in the chunk graph, // 2) and it's a normal member function, and not a GETTER_DEF or a SETTER_DEF, // 3) and the class is available in the global scope. Var rootVar = classMemberFunction.getRootVar(); if (rootVar == null || !rootVar.isGlobal()) { return; } Node definitionNode = classMemberFunction.getDefinitionNode(); // Only attempt to move normal member functions. // A getter or setter cannot be as easily defined outside of the class to which it belongs. if (!definitionNode.isMemberFunctionDef()) { return; } if (moduleGraph.dependsOn(deepestCommonModuleRef, classMemberFunction.getModule())) { if (hasUnmovableRedeclaration(nameInfo, classMemberFunction)) { // If it has been redeclared on the same object, skip it. return; } Node destinationParent = compiler.getNodeForCodeInsertion(deepestCommonModuleRef); String className = rootVar.getName(); if (noStubFunctions) { moveClassInstanceMethodWithoutStub(className, definitionNode, destinationParent); } else { moveClassInstanceMethodWithStub(className, definitionNode, destinationParent); } } }
java
private void tryToMoveMemberFunction( NameInfo nameInfo, JSModule deepestCommonModuleRef, ClassMemberFunction classMemberFunction) { // We should only move a property across chunks if: // 1) We can move it deeper in the chunk graph, // 2) and it's a normal member function, and not a GETTER_DEF or a SETTER_DEF, // 3) and the class is available in the global scope. Var rootVar = classMemberFunction.getRootVar(); if (rootVar == null || !rootVar.isGlobal()) { return; } Node definitionNode = classMemberFunction.getDefinitionNode(); // Only attempt to move normal member functions. // A getter or setter cannot be as easily defined outside of the class to which it belongs. if (!definitionNode.isMemberFunctionDef()) { return; } if (moduleGraph.dependsOn(deepestCommonModuleRef, classMemberFunction.getModule())) { if (hasUnmovableRedeclaration(nameInfo, classMemberFunction)) { // If it has been redeclared on the same object, skip it. return; } Node destinationParent = compiler.getNodeForCodeInsertion(deepestCommonModuleRef); String className = rootVar.getName(); if (noStubFunctions) { moveClassInstanceMethodWithoutStub(className, definitionNode, destinationParent); } else { moveClassInstanceMethodWithStub(className, definitionNode, destinationParent); } } }
[ "private", "void", "tryToMoveMemberFunction", "(", "NameInfo", "nameInfo", ",", "JSModule", "deepestCommonModuleRef", ",", "ClassMemberFunction", "classMemberFunction", ")", "{", "// We should only move a property across chunks if:", "// 1) We can move it deeper in the chunk graph,", "// 2) and it's a normal member function, and not a GETTER_DEF or a SETTER_DEF,", "// 3) and the class is available in the global scope.", "Var", "rootVar", "=", "classMemberFunction", ".", "getRootVar", "(", ")", ";", "if", "(", "rootVar", "==", "null", "||", "!", "rootVar", ".", "isGlobal", "(", ")", ")", "{", "return", ";", "}", "Node", "definitionNode", "=", "classMemberFunction", ".", "getDefinitionNode", "(", ")", ";", "// Only attempt to move normal member functions.", "// A getter or setter cannot be as easily defined outside of the class to which it belongs.", "if", "(", "!", "definitionNode", ".", "isMemberFunctionDef", "(", ")", ")", "{", "return", ";", "}", "if", "(", "moduleGraph", ".", "dependsOn", "(", "deepestCommonModuleRef", ",", "classMemberFunction", ".", "getModule", "(", ")", ")", ")", "{", "if", "(", "hasUnmovableRedeclaration", "(", "nameInfo", ",", "classMemberFunction", ")", ")", "{", "// If it has been redeclared on the same object, skip it.", "return", ";", "}", "Node", "destinationParent", "=", "compiler", ".", "getNodeForCodeInsertion", "(", "deepestCommonModuleRef", ")", ";", "String", "className", "=", "rootVar", ".", "getName", "(", ")", ";", "if", "(", "noStubFunctions", ")", "{", "moveClassInstanceMethodWithoutStub", "(", "className", ",", "definitionNode", ",", "destinationParent", ")", ";", "}", "else", "{", "moveClassInstanceMethodWithStub", "(", "className", ",", "definitionNode", ",", "destinationParent", ")", ";", "}", "}", "}" ]
If possible, move a class instance member function definition to the deepest chunk common to all uses of the method. @param nameInfo information about all definitions of the given property name @param deepestCommonModuleRef all uses of the method are either in this chunk or in chunks that depend on it @param classMemberFunction definition of the method within its class body
[ "If", "possible", "move", "a", "class", "instance", "member", "function", "definition", "to", "the", "deepest", "chunk", "common", "to", "all", "uses", "of", "the", "method", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CrossChunkMethodMotion.java#L419-L453
24,607
google/closure-compiler
src/com/google/javascript/jscomp/AccessControlUtils.java
AccessControlUtils.getOverriddenPropertyVisibility
static Visibility getOverriddenPropertyVisibility(ObjectType objectType, String propertyName) { return objectType != null ? objectType.getOwnPropertyJSDocInfo(propertyName).getVisibility() : Visibility.INHERITED; }
java
static Visibility getOverriddenPropertyVisibility(ObjectType objectType, String propertyName) { return objectType != null ? objectType.getOwnPropertyJSDocInfo(propertyName).getVisibility() : Visibility.INHERITED; }
[ "static", "Visibility", "getOverriddenPropertyVisibility", "(", "ObjectType", "objectType", ",", "String", "propertyName", ")", "{", "return", "objectType", "!=", "null", "?", "objectType", ".", "getOwnPropertyJSDocInfo", "(", "propertyName", ")", ".", "getVisibility", "(", ")", ":", "Visibility", ".", "INHERITED", ";", "}" ]
Returns the original visibility of an overridden property.
[ "Returns", "the", "original", "visibility", "of", "an", "overridden", "property", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AccessControlUtils.java#L157-L161
24,608
google/closure-compiler
src/com/google/javascript/rhino/jstype/EnumType.java
EnumType.defineElement
public boolean defineElement(String name, Node definingNode) { elements.add(name); return defineDeclaredProperty(name, elementsType, definingNode); }
java
public boolean defineElement(String name, Node definingNode) { elements.add(name); return defineDeclaredProperty(name, elementsType, definingNode); }
[ "public", "boolean", "defineElement", "(", "String", "name", ",", "Node", "definingNode", ")", "{", "elements", ".", "add", "(", "name", ")", ";", "return", "defineDeclaredProperty", "(", "name", ",", "elementsType", ",", "definingNode", ")", ";", "}" ]
Defines a new element on this enum. @param name the name of the new element @param definingNode the {@code Node} that defines this new element @return true iff the new element is added successfully
[ "Defines", "a", "new", "element", "on", "this", "enum", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/EnumType.java#L100-L103
24,609
google/closure-compiler
src/com/google/javascript/jscomp/deps/JsFileLineParser.java
JsFileLineParser.parseJsString
String parseJsString(String jsStringLiteral) throws ParseException { valueMatcher.reset(jsStringLiteral); if (!valueMatcher.matches()) { throw new ParseException("Syntax error in JS String literal", true /* fatal */); } return valueMatcher.group(1) != null ? valueMatcher.group(1) : valueMatcher.group(2); }
java
String parseJsString(String jsStringLiteral) throws ParseException { valueMatcher.reset(jsStringLiteral); if (!valueMatcher.matches()) { throw new ParseException("Syntax error in JS String literal", true /* fatal */); } return valueMatcher.group(1) != null ? valueMatcher.group(1) : valueMatcher.group(2); }
[ "String", "parseJsString", "(", "String", "jsStringLiteral", ")", "throws", "ParseException", "{", "valueMatcher", ".", "reset", "(", "jsStringLiteral", ")", ";", "if", "(", "!", "valueMatcher", ".", "matches", "(", ")", ")", "{", "throw", "new", "ParseException", "(", "\"Syntax error in JS String literal\"", ",", "true", "/* fatal */", ")", ";", "}", "return", "valueMatcher", ".", "group", "(", "1", ")", "!=", "null", "?", "valueMatcher", ".", "group", "(", "1", ")", ":", "valueMatcher", ".", "group", "(", "2", ")", ";", "}" ]
Parses a JS string literal. @param jsStringLiteral The literal. Must look like "asdf" or 'asdf' @throws ParseException Thrown if there is a string literal that cannot be parsed.
[ "Parses", "a", "JS", "string", "literal", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/JsFileLineParser.java#L297-L303
24,610
google/closure-compiler
src/com/google/javascript/rhino/jstype/PropertyMap.java
PropertyMap.getPrimaryParent
PropertyMap getPrimaryParent() { if (parentSource == null) { return null; } ObjectType iProto = parentSource.getImplicitPrototype(); return iProto == null ? null : iProto.getPropertyMap(); }
java
PropertyMap getPrimaryParent() { if (parentSource == null) { return null; } ObjectType iProto = parentSource.getImplicitPrototype(); return iProto == null ? null : iProto.getPropertyMap(); }
[ "PropertyMap", "getPrimaryParent", "(", ")", "{", "if", "(", "parentSource", "==", "null", ")", "{", "return", "null", ";", "}", "ObjectType", "iProto", "=", "parentSource", ".", "getImplicitPrototype", "(", ")", ";", "return", "iProto", "==", "null", "?", "null", ":", "iProto", ".", "getPropertyMap", "(", ")", ";", "}" ]
Returns the direct parent of this property map.
[ "Returns", "the", "direct", "parent", "of", "this", "property", "map", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/PropertyMap.java#L90-L96
24,611
google/closure-compiler
src/com/google/javascript/rhino/jstype/PropertyMap.java
PropertyMap.collectPropertyNamesHelper
private void collectPropertyNamesHelper( Set<String> props, Set<PropertyMap> cache) { if (!cache.add(this)) { return; } props.addAll(properties.keySet()); PropertyMap primaryParent = getPrimaryParent(); if (primaryParent != null) { primaryParent.collectPropertyNamesHelper(props, cache); } for (ObjectType o : getSecondaryParentObjects()) { PropertyMap p = o.getPropertyMap(); if (p != null) { p.collectPropertyNamesHelper(props, cache); } } }
java
private void collectPropertyNamesHelper( Set<String> props, Set<PropertyMap> cache) { if (!cache.add(this)) { return; } props.addAll(properties.keySet()); PropertyMap primaryParent = getPrimaryParent(); if (primaryParent != null) { primaryParent.collectPropertyNamesHelper(props, cache); } for (ObjectType o : getSecondaryParentObjects()) { PropertyMap p = o.getPropertyMap(); if (p != null) { p.collectPropertyNamesHelper(props, cache); } } }
[ "private", "void", "collectPropertyNamesHelper", "(", "Set", "<", "String", ">", "props", ",", "Set", "<", "PropertyMap", ">", "cache", ")", "{", "if", "(", "!", "cache", ".", "add", "(", "this", ")", ")", "{", "return", ";", "}", "props", ".", "addAll", "(", "properties", ".", "keySet", "(", ")", ")", ";", "PropertyMap", "primaryParent", "=", "getPrimaryParent", "(", ")", ";", "if", "(", "primaryParent", "!=", "null", ")", "{", "primaryParent", ".", "collectPropertyNamesHelper", "(", "props", ",", "cache", ")", ";", "}", "for", "(", "ObjectType", "o", ":", "getSecondaryParentObjects", "(", ")", ")", "{", "PropertyMap", "p", "=", "o", ".", "getPropertyMap", "(", ")", ";", "if", "(", "p", "!=", "null", ")", "{", "p", ".", "collectPropertyNamesHelper", "(", "props", ",", "cache", ")", ";", "}", "}", "}" ]
Use cache to avoid stack overflow.
[ "Use", "cache", "to", "avoid", "stack", "overflow", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/PropertyMap.java#L158-L174
24,612
google/closure-compiler
src/com/google/javascript/jscomp/VarCheck.java
VarCheck.createSynthesizedExternVar
static void createSynthesizedExternVar(AbstractCompiler compiler, String varName) { Node nameNode = IR.name(varName); // Mark the variable as constant if it matches the coding convention // for constant vars. // NOTE(nicksantos): honestly, I'm not sure how much this matters. // AFAIK, all people who use the CONST coding convention also // compile with undeclaredVars as errors. We have some test // cases for this configuration though, and it makes them happier. if (compiler.getCodingConvention().isConstant(varName)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); } Node syntheticExternVar = IR.var(nameNode); getSynthesizedExternsRoot(compiler).addChildToBack(syntheticExternVar); compiler.reportChangeToEnclosingScope(syntheticExternVar); }
java
static void createSynthesizedExternVar(AbstractCompiler compiler, String varName) { Node nameNode = IR.name(varName); // Mark the variable as constant if it matches the coding convention // for constant vars. // NOTE(nicksantos): honestly, I'm not sure how much this matters. // AFAIK, all people who use the CONST coding convention also // compile with undeclaredVars as errors. We have some test // cases for this configuration though, and it makes them happier. if (compiler.getCodingConvention().isConstant(varName)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); } Node syntheticExternVar = IR.var(nameNode); getSynthesizedExternsRoot(compiler).addChildToBack(syntheticExternVar); compiler.reportChangeToEnclosingScope(syntheticExternVar); }
[ "static", "void", "createSynthesizedExternVar", "(", "AbstractCompiler", "compiler", ",", "String", "varName", ")", "{", "Node", "nameNode", "=", "IR", ".", "name", "(", "varName", ")", ";", "// Mark the variable as constant if it matches the coding convention", "// for constant vars.", "// NOTE(nicksantos): honestly, I'm not sure how much this matters.", "// AFAIK, all people who use the CONST coding convention also", "// compile with undeclaredVars as errors. We have some test", "// cases for this configuration though, and it makes them happier.", "if", "(", "compiler", ".", "getCodingConvention", "(", ")", ".", "isConstant", "(", "varName", ")", ")", "{", "nameNode", ".", "putBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ",", "true", ")", ";", "}", "Node", "syntheticExternVar", "=", "IR", ".", "var", "(", "nameNode", ")", ";", "getSynthesizedExternsRoot", "(", "compiler", ")", ".", "addChildToBack", "(", "syntheticExternVar", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "syntheticExternVar", ")", ";", "}" ]
Create a new variable in a synthetic script. This will prevent subsequent compiler passes from crashing.
[ "Create", "a", "new", "variable", "in", "a", "synthetic", "script", ".", "This", "will", "prevent", "subsequent", "compiler", "passes", "from", "crashing", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/VarCheck.java#L328-L344
24,613
google/closure-compiler
src/com/google/javascript/jscomp/VarCheck.java
VarCheck.hasDuplicateDeclarationSuppression
static boolean hasDuplicateDeclarationSuppression( AbstractCompiler compiler, Node n, Node origVar) { // For VarCheck and VariableReferenceCheck, variables in externs do not generate duplicate // warnings. if (isExternNamespace(n)) { return true; } return TypeValidator.hasDuplicateDeclarationSuppression(compiler, origVar); }
java
static boolean hasDuplicateDeclarationSuppression( AbstractCompiler compiler, Node n, Node origVar) { // For VarCheck and VariableReferenceCheck, variables in externs do not generate duplicate // warnings. if (isExternNamespace(n)) { return true; } return TypeValidator.hasDuplicateDeclarationSuppression(compiler, origVar); }
[ "static", "boolean", "hasDuplicateDeclarationSuppression", "(", "AbstractCompiler", "compiler", ",", "Node", "n", ",", "Node", "origVar", ")", "{", "// For VarCheck and VariableReferenceCheck, variables in externs do not generate duplicate", "// warnings.", "if", "(", "isExternNamespace", "(", "n", ")", ")", "{", "return", "true", ";", "}", "return", "TypeValidator", ".", "hasDuplicateDeclarationSuppression", "(", "compiler", ",", "origVar", ")", ";", "}" ]
Returns true if duplication warnings are suppressed on either n or origVar.
[ "Returns", "true", "if", "duplication", "warnings", "are", "suppressed", "on", "either", "n", "or", "origVar", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/VarCheck.java#L434-L442
24,614
google/closure-compiler
src/com/google/javascript/jscomp/VarCheck.java
VarCheck.isExternNamespace
static boolean isExternNamespace(Node n) { return n.getParent().isVar() && n.isFromExterns() && NodeUtil.isNamespaceDecl(n); }
java
static boolean isExternNamespace(Node n) { return n.getParent().isVar() && n.isFromExterns() && NodeUtil.isNamespaceDecl(n); }
[ "static", "boolean", "isExternNamespace", "(", "Node", "n", ")", "{", "return", "n", ".", "getParent", "(", ")", ".", "isVar", "(", ")", "&&", "n", ".", "isFromExterns", "(", ")", "&&", "NodeUtil", ".", "isNamespaceDecl", "(", "n", ")", ";", "}" ]
Returns true if n is the name of a variable that declares a namespace in an externs file.
[ "Returns", "true", "if", "n", "is", "the", "name", "of", "a", "variable", "that", "declares", "a", "namespace", "in", "an", "externs", "file", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/VarCheck.java#L445-L447
24,615
google/closure-compiler
src/com/google/javascript/jscomp/lint/CheckJSDocStyle.java
CheckJSDocStyle.isFunctionThatShouldHaveJsDoc
private boolean isFunctionThatShouldHaveJsDoc(NodeTraversal t, Node function) { if (!(t.inGlobalHoistScope() || t.inModuleScope())) { // TODO(b/233631820): this should check for the module hoist scope instead return false; } if (NodeUtil.isFunctionDeclaration(function)) { return true; } if (NodeUtil.isNameDeclaration(function.getGrandparent()) || function.getParent().isAssign()) { return true; } if (function.getParent().isExport()) { return true; } if (function.getGrandparent().isClassMembers()) { Node memberNode = function.getParent(); if (memberNode.isMemberFunctionDef()) { // A constructor with no parameters doesn't need JSDoc, // but all other member functions do. return !isConstructorWithoutParameters(function); } else if (memberNode.isGetterDef() || memberNode.isSetterDef()) { return true; } } if (function.getGrandparent().isObjectLit() && NodeUtil.isCallTo(function.getGrandparent().getParent(), "Polymer")) { return true; } return false; }
java
private boolean isFunctionThatShouldHaveJsDoc(NodeTraversal t, Node function) { if (!(t.inGlobalHoistScope() || t.inModuleScope())) { // TODO(b/233631820): this should check for the module hoist scope instead return false; } if (NodeUtil.isFunctionDeclaration(function)) { return true; } if (NodeUtil.isNameDeclaration(function.getGrandparent()) || function.getParent().isAssign()) { return true; } if (function.getParent().isExport()) { return true; } if (function.getGrandparent().isClassMembers()) { Node memberNode = function.getParent(); if (memberNode.isMemberFunctionDef()) { // A constructor with no parameters doesn't need JSDoc, // but all other member functions do. return !isConstructorWithoutParameters(function); } else if (memberNode.isGetterDef() || memberNode.isSetterDef()) { return true; } } if (function.getGrandparent().isObjectLit() && NodeUtil.isCallTo(function.getGrandparent().getParent(), "Polymer")) { return true; } return false; }
[ "private", "boolean", "isFunctionThatShouldHaveJsDoc", "(", "NodeTraversal", "t", ",", "Node", "function", ")", "{", "if", "(", "!", "(", "t", ".", "inGlobalHoistScope", "(", ")", "||", "t", ".", "inModuleScope", "(", ")", ")", ")", "{", "// TODO(b/233631820): this should check for the module hoist scope instead", "return", "false", ";", "}", "if", "(", "NodeUtil", ".", "isFunctionDeclaration", "(", "function", ")", ")", "{", "return", "true", ";", "}", "if", "(", "NodeUtil", ".", "isNameDeclaration", "(", "function", ".", "getGrandparent", "(", ")", ")", "||", "function", ".", "getParent", "(", ")", ".", "isAssign", "(", ")", ")", "{", "return", "true", ";", "}", "if", "(", "function", ".", "getParent", "(", ")", ".", "isExport", "(", ")", ")", "{", "return", "true", ";", "}", "if", "(", "function", ".", "getGrandparent", "(", ")", ".", "isClassMembers", "(", ")", ")", "{", "Node", "memberNode", "=", "function", ".", "getParent", "(", ")", ";", "if", "(", "memberNode", ".", "isMemberFunctionDef", "(", ")", ")", "{", "// A constructor with no parameters doesn't need JSDoc,", "// but all other member functions do.", "return", "!", "isConstructorWithoutParameters", "(", "function", ")", ";", "}", "else", "if", "(", "memberNode", ".", "isGetterDef", "(", ")", "||", "memberNode", ".", "isSetterDef", "(", ")", ")", "{", "return", "true", ";", "}", "}", "if", "(", "function", ".", "getGrandparent", "(", ")", ".", "isObjectLit", "(", ")", "&&", "NodeUtil", ".", "isCallTo", "(", "function", ".", "getGrandparent", "(", ")", ".", "getParent", "(", ")", ",", "\"Polymer\"", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Whether the given function should have JSDoc. True if it's a function declared in the global scope, or a method on a class which is declared in the global scope.
[ "Whether", "the", "given", "function", "should", "have", "JSDoc", ".", "True", "if", "it", "s", "a", "function", "declared", "in", "the", "global", "scope", "or", "a", "method", "on", "a", "class", "which", "is", "declared", "in", "the", "global", "scope", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/lint/CheckJSDocStyle.java#L242-L274
24,616
google/closure-compiler
src/com/google/javascript/jscomp/lint/CheckJSDocStyle.java
CheckJSDocStyle.checkInlineParams
private void checkInlineParams(NodeTraversal t, Node function) { Node paramList = NodeUtil.getFunctionParameters(function); for (Node param : paramList.children()) { JSDocInfo jsDoc = param.getJSDocInfo(); if (jsDoc == null) { t.report(param, MISSING_PARAMETER_JSDOC); return; } else { JSTypeExpression paramType = jsDoc.getType(); checkNotNull(paramType, "Inline JSDoc info should always have a type"); checkParam(t, param, null, paramType); } } }
java
private void checkInlineParams(NodeTraversal t, Node function) { Node paramList = NodeUtil.getFunctionParameters(function); for (Node param : paramList.children()) { JSDocInfo jsDoc = param.getJSDocInfo(); if (jsDoc == null) { t.report(param, MISSING_PARAMETER_JSDOC); return; } else { JSTypeExpression paramType = jsDoc.getType(); checkNotNull(paramType, "Inline JSDoc info should always have a type"); checkParam(t, param, null, paramType); } } }
[ "private", "void", "checkInlineParams", "(", "NodeTraversal", "t", ",", "Node", "function", ")", "{", "Node", "paramList", "=", "NodeUtil", ".", "getFunctionParameters", "(", "function", ")", ";", "for", "(", "Node", "param", ":", "paramList", ".", "children", "(", ")", ")", "{", "JSDocInfo", "jsDoc", "=", "param", ".", "getJSDocInfo", "(", ")", ";", "if", "(", "jsDoc", "==", "null", ")", "{", "t", ".", "report", "(", "param", ",", "MISSING_PARAMETER_JSDOC", ")", ";", "return", ";", "}", "else", "{", "JSTypeExpression", "paramType", "=", "jsDoc", ".", "getType", "(", ")", ";", "checkNotNull", "(", "paramType", ",", "\"Inline JSDoc info should always have a type\"", ")", ";", "checkParam", "(", "t", ",", "param", ",", "null", ",", "paramType", ")", ";", "}", "}", "}" ]
Checks that the inline type annotations are correct.
[ "Checks", "that", "the", "inline", "type", "annotations", "are", "correct", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/lint/CheckJSDocStyle.java#L332-L346
24,617
google/closure-compiler
src/com/google/javascript/jscomp/parsing/IRFactory.java
IRFactory.transformNodeWithInlineJsDoc
Node transformNodeWithInlineJsDoc(ParseTree node) { JSDocInfo info = handleInlineJsDoc(node); Node irNode = transformDispatcher.process(node); if (info != null) { irNode.setJSDocInfo(info); } setSourceInfo(irNode, node); return irNode; }
java
Node transformNodeWithInlineJsDoc(ParseTree node) { JSDocInfo info = handleInlineJsDoc(node); Node irNode = transformDispatcher.process(node); if (info != null) { irNode.setJSDocInfo(info); } setSourceInfo(irNode, node); return irNode; }
[ "Node", "transformNodeWithInlineJsDoc", "(", "ParseTree", "node", ")", "{", "JSDocInfo", "info", "=", "handleInlineJsDoc", "(", "node", ")", ";", "Node", "irNode", "=", "transformDispatcher", ".", "process", "(", "node", ")", ";", "if", "(", "info", "!=", "null", ")", "{", "irNode", ".", "setJSDocInfo", "(", "info", ")", ";", "}", "setSourceInfo", "(", "irNode", ",", "node", ")", ";", "return", "irNode", ";", "}" ]
Names and destructuring patterns, in parameters or variable declarations are special, because they can have inline type docs attached. <pre>function f(/** string &#42;/ x) {}</pre> annotates 'x' as a string. @see <a href="http://code.google.com/p/jsdoc-toolkit/wiki/InlineDocs"> Using Inline Doc Comments</a>
[ "Names", "and", "destructuring", "patterns", "in", "parameters", "or", "variable", "declarations", "are", "special", "because", "they", "can", "have", "inline", "type", "docs", "attached", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/IRFactory.java#L752-L760
24,618
google/closure-compiler
src/com/google/javascript/jscomp/parsing/IRFactory.java
IRFactory.createJsDocInfoParser
private JsDocInfoParser createJsDocInfoParser(Comment node) { String comment = node.value; int lineno = lineno(node.location.start); int charno = charno(node.location.start); int position = node.location.start.offset; // The JsDocInfoParser expects the comment without the initial '/**'. int numOpeningChars = 3; JsDocInfoParser jsdocParser = new JsDocInfoParser( new JsDocTokenStream(comment.substring(numOpeningChars), lineno, charno + numOpeningChars), comment, position, templateNode, config, errorReporter); jsdocParser.setFileLevelJsDocBuilder(fileLevelJsDocBuilder); jsdocParser.setFileOverviewJSDocInfo(fileOverviewInfo); if (node.type == Comment.Type.IMPORTANT && node.value.length() > 0) { jsdocParser.parseImportantComment(); } else { jsdocParser.parse(); } return jsdocParser; }
java
private JsDocInfoParser createJsDocInfoParser(Comment node) { String comment = node.value; int lineno = lineno(node.location.start); int charno = charno(node.location.start); int position = node.location.start.offset; // The JsDocInfoParser expects the comment without the initial '/**'. int numOpeningChars = 3; JsDocInfoParser jsdocParser = new JsDocInfoParser( new JsDocTokenStream(comment.substring(numOpeningChars), lineno, charno + numOpeningChars), comment, position, templateNode, config, errorReporter); jsdocParser.setFileLevelJsDocBuilder(fileLevelJsDocBuilder); jsdocParser.setFileOverviewJSDocInfo(fileOverviewInfo); if (node.type == Comment.Type.IMPORTANT && node.value.length() > 0) { jsdocParser.parseImportantComment(); } else { jsdocParser.parse(); } return jsdocParser; }
[ "private", "JsDocInfoParser", "createJsDocInfoParser", "(", "Comment", "node", ")", "{", "String", "comment", "=", "node", ".", "value", ";", "int", "lineno", "=", "lineno", "(", "node", ".", "location", ".", "start", ")", ";", "int", "charno", "=", "charno", "(", "node", ".", "location", ".", "start", ")", ";", "int", "position", "=", "node", ".", "location", ".", "start", ".", "offset", ";", "// The JsDocInfoParser expects the comment without the initial '/**'.", "int", "numOpeningChars", "=", "3", ";", "JsDocInfoParser", "jsdocParser", "=", "new", "JsDocInfoParser", "(", "new", "JsDocTokenStream", "(", "comment", ".", "substring", "(", "numOpeningChars", ")", ",", "lineno", ",", "charno", "+", "numOpeningChars", ")", ",", "comment", ",", "position", ",", "templateNode", ",", "config", ",", "errorReporter", ")", ";", "jsdocParser", ".", "setFileLevelJsDocBuilder", "(", "fileLevelJsDocBuilder", ")", ";", "jsdocParser", ".", "setFileOverviewJSDocInfo", "(", "fileOverviewInfo", ")", ";", "if", "(", "node", ".", "type", "==", "Comment", ".", "Type", ".", "IMPORTANT", "&&", "node", ".", "value", ".", "length", "(", ")", ">", "0", ")", "{", "jsdocParser", ".", "parseImportantComment", "(", ")", ";", "}", "else", "{", "jsdocParser", ".", "parse", "(", ")", ";", "}", "return", "jsdocParser", ";", "}" ]
Creates a JsDocInfoParser and parses the JsDoc string. Used both for handling individual JSDoc comments and for handling file-level JSDoc comments (@fileoverview and @license). @param node The JsDoc Comment node to parse. @return A JsDocInfoParser. Will contain either fileoverview JsDoc, or normal JsDoc, or no JsDoc (if the method parses to the wrong level).
[ "Creates", "a", "JsDocInfoParser", "and", "parses", "the", "JsDoc", "string", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/IRFactory.java#L901-L928
24,619
google/closure-compiler
src/com/google/javascript/jscomp/parsing/IRFactory.java
IRFactory.parseInlineTypeDoc
private JSDocInfo parseInlineTypeDoc(Comment node) { String comment = node.value; int lineno = lineno(node.location.start); int charno = charno(node.location.start); // The JsDocInfoParser expects the comment without the initial '/**'. int numOpeningChars = 3; JsDocInfoParser parser = new JsDocInfoParser( new JsDocTokenStream(comment.substring(numOpeningChars), lineno, charno + numOpeningChars), comment, node.location.start.offset, templateNode, config, errorReporter); return parser.parseInlineTypeDoc(); }
java
private JSDocInfo parseInlineTypeDoc(Comment node) { String comment = node.value; int lineno = lineno(node.location.start); int charno = charno(node.location.start); // The JsDocInfoParser expects the comment without the initial '/**'. int numOpeningChars = 3; JsDocInfoParser parser = new JsDocInfoParser( new JsDocTokenStream(comment.substring(numOpeningChars), lineno, charno + numOpeningChars), comment, node.location.start.offset, templateNode, config, errorReporter); return parser.parseInlineTypeDoc(); }
[ "private", "JSDocInfo", "parseInlineTypeDoc", "(", "Comment", "node", ")", "{", "String", "comment", "=", "node", ".", "value", ";", "int", "lineno", "=", "lineno", "(", "node", ".", "location", ".", "start", ")", ";", "int", "charno", "=", "charno", "(", "node", ".", "location", ".", "start", ")", ";", "// The JsDocInfoParser expects the comment without the initial '/**'.", "int", "numOpeningChars", "=", "3", ";", "JsDocInfoParser", "parser", "=", "new", "JsDocInfoParser", "(", "new", "JsDocTokenStream", "(", "comment", ".", "substring", "(", "numOpeningChars", ")", ",", "lineno", ",", "charno", "+", "numOpeningChars", ")", ",", "comment", ",", "node", ".", "location", ".", "start", ".", "offset", ",", "templateNode", ",", "config", ",", "errorReporter", ")", ";", "return", "parser", ".", "parseInlineTypeDoc", "(", ")", ";", "}" ]
Parses inline type info.
[ "Parses", "inline", "type", "info", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/IRFactory.java#L933-L951
24,620
google/closure-compiler
src/com/google/javascript/jscomp/parsing/IRFactory.java
IRFactory.setLength
void setLength( Node node, SourcePosition start, SourcePosition end) { node.setLength(end.offset - start.offset); }
java
void setLength( Node node, SourcePosition start, SourcePosition end) { node.setLength(end.offset - start.offset); }
[ "void", "setLength", "(", "Node", "node", ",", "SourcePosition", "start", ",", "SourcePosition", "end", ")", "{", "node", ".", "setLength", "(", "end", ".", "offset", "-", "start", ".", "offset", ")", ";", "}" ]
Set the length on the node if we're in IDE mode.
[ "Set", "the", "length", "on", "the", "node", "if", "we", "re", "in", "IDE", "mode", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/IRFactory.java#L954-L957
24,621
google/closure-compiler
src/com/google/javascript/jscomp/parsing/IRFactory.java
IRFactory.cloneProps
Node cloneProps(Node n) { if (!n.hasProps()) { n.clonePropsFrom(templateNode); } for (Node child : n.children()) { cloneProps(child); } return n; }
java
Node cloneProps(Node n) { if (!n.hasProps()) { n.clonePropsFrom(templateNode); } for (Node child : n.children()) { cloneProps(child); } return n; }
[ "Node", "cloneProps", "(", "Node", "n", ")", "{", "if", "(", "!", "n", ".", "hasProps", "(", ")", ")", "{", "n", ".", "clonePropsFrom", "(", "templateNode", ")", ";", "}", "for", "(", "Node", "child", ":", "n", ".", "children", "(", ")", ")", "{", "cloneProps", "(", "child", ")", ";", "}", "return", "n", ";", "}" ]
Clone the properties from the template node recursively, skips nodes that have properties already.
[ "Clone", "the", "properties", "from", "the", "template", "node", "recursively", "skips", "nodes", "that", "have", "properties", "already", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/IRFactory.java#L3673-L3681
24,622
google/closure-compiler
src/com/google/javascript/jscomp/gwt/client/GwtRunner.java
GwtRunner.getDefaultFlags
private static Flags getDefaultFlags() { if (defaultFlags != null) { return defaultFlags; } defaultFlags = new Flags(); defaultFlags.angularPass = false; defaultFlags.applyInputSourceMaps = true; defaultFlags.assumeFunctionWrapper = false; defaultFlags.checksOnly = false; defaultFlags.chunk = null; defaultFlags.chunkWrapper = null; defaultFlags.chunkOutputPathPrefix = "./"; defaultFlags.compilationLevel = "SIMPLE"; defaultFlags.createSourceMap = true; defaultFlags.dartPass = false; defaultFlags.debug = false; defaultFlags.define = null; defaultFlags.defines = null; defaultFlags.dependencyMode = null; defaultFlags.entryPoint = null; defaultFlags.env = "BROWSER"; defaultFlags.exportLocalPropertyDefinitions = false; defaultFlags.extraAnnotationName = null; defaultFlags.externs = null; defaultFlags.forceInjectLibraries = null; defaultFlags.formatting = null; defaultFlags.generateExports = false; defaultFlags.hideWarningsFor = null; defaultFlags.injectLibraries = true; defaultFlags.js = null; defaultFlags.jsCode = null; defaultFlags.jscompError = null; defaultFlags.jscompOff = null; defaultFlags.jscompWarning = null; defaultFlags.jsModuleRoot = null; defaultFlags.jsOutputFile = "compiled.js"; defaultFlags.languageIn = "ECMASCRIPT_2017"; defaultFlags.languageOut = "ECMASCRIPT5"; defaultFlags.moduleResolution = "BROWSER"; defaultFlags.newTypeInf = false; defaultFlags.isolationMode = "NONE"; defaultFlags.outputWrapper = null; defaultFlags.packageJsonEntryNames = null; defaultFlags.parseInlineSourceMaps = true; defaultFlags.polymerPass = false; defaultFlags.polymerVersion = null; defaultFlags.preserveTypeAnnotations = false; defaultFlags.processClosurePrimitives = true; defaultFlags.processCommonJsModules = false; defaultFlags.renamePrefixNamespace = null; defaultFlags.renameVariablePrefix = null; defaultFlags.renaming = true; defaultFlags.rewritePolyfills = true; defaultFlags.sourceMapIncludeContent = false; defaultFlags.strictModeInput = true; defaultFlags.tracerMode = "OFF"; defaultFlags.warningLevel = "DEFAULT"; defaultFlags.useTypesForOptimization = true; return defaultFlags; }
java
private static Flags getDefaultFlags() { if (defaultFlags != null) { return defaultFlags; } defaultFlags = new Flags(); defaultFlags.angularPass = false; defaultFlags.applyInputSourceMaps = true; defaultFlags.assumeFunctionWrapper = false; defaultFlags.checksOnly = false; defaultFlags.chunk = null; defaultFlags.chunkWrapper = null; defaultFlags.chunkOutputPathPrefix = "./"; defaultFlags.compilationLevel = "SIMPLE"; defaultFlags.createSourceMap = true; defaultFlags.dartPass = false; defaultFlags.debug = false; defaultFlags.define = null; defaultFlags.defines = null; defaultFlags.dependencyMode = null; defaultFlags.entryPoint = null; defaultFlags.env = "BROWSER"; defaultFlags.exportLocalPropertyDefinitions = false; defaultFlags.extraAnnotationName = null; defaultFlags.externs = null; defaultFlags.forceInjectLibraries = null; defaultFlags.formatting = null; defaultFlags.generateExports = false; defaultFlags.hideWarningsFor = null; defaultFlags.injectLibraries = true; defaultFlags.js = null; defaultFlags.jsCode = null; defaultFlags.jscompError = null; defaultFlags.jscompOff = null; defaultFlags.jscompWarning = null; defaultFlags.jsModuleRoot = null; defaultFlags.jsOutputFile = "compiled.js"; defaultFlags.languageIn = "ECMASCRIPT_2017"; defaultFlags.languageOut = "ECMASCRIPT5"; defaultFlags.moduleResolution = "BROWSER"; defaultFlags.newTypeInf = false; defaultFlags.isolationMode = "NONE"; defaultFlags.outputWrapper = null; defaultFlags.packageJsonEntryNames = null; defaultFlags.parseInlineSourceMaps = true; defaultFlags.polymerPass = false; defaultFlags.polymerVersion = null; defaultFlags.preserveTypeAnnotations = false; defaultFlags.processClosurePrimitives = true; defaultFlags.processCommonJsModules = false; defaultFlags.renamePrefixNamespace = null; defaultFlags.renameVariablePrefix = null; defaultFlags.renaming = true; defaultFlags.rewritePolyfills = true; defaultFlags.sourceMapIncludeContent = false; defaultFlags.strictModeInput = true; defaultFlags.tracerMode = "OFF"; defaultFlags.warningLevel = "DEFAULT"; defaultFlags.useTypesForOptimization = true; return defaultFlags; }
[ "private", "static", "Flags", "getDefaultFlags", "(", ")", "{", "if", "(", "defaultFlags", "!=", "null", ")", "{", "return", "defaultFlags", ";", "}", "defaultFlags", "=", "new", "Flags", "(", ")", ";", "defaultFlags", ".", "angularPass", "=", "false", ";", "defaultFlags", ".", "applyInputSourceMaps", "=", "true", ";", "defaultFlags", ".", "assumeFunctionWrapper", "=", "false", ";", "defaultFlags", ".", "checksOnly", "=", "false", ";", "defaultFlags", ".", "chunk", "=", "null", ";", "defaultFlags", ".", "chunkWrapper", "=", "null", ";", "defaultFlags", ".", "chunkOutputPathPrefix", "=", "\"./\"", ";", "defaultFlags", ".", "compilationLevel", "=", "\"SIMPLE\"", ";", "defaultFlags", ".", "createSourceMap", "=", "true", ";", "defaultFlags", ".", "dartPass", "=", "false", ";", "defaultFlags", ".", "debug", "=", "false", ";", "defaultFlags", ".", "define", "=", "null", ";", "defaultFlags", ".", "defines", "=", "null", ";", "defaultFlags", ".", "dependencyMode", "=", "null", ";", "defaultFlags", ".", "entryPoint", "=", "null", ";", "defaultFlags", ".", "env", "=", "\"BROWSER\"", ";", "defaultFlags", ".", "exportLocalPropertyDefinitions", "=", "false", ";", "defaultFlags", ".", "extraAnnotationName", "=", "null", ";", "defaultFlags", ".", "externs", "=", "null", ";", "defaultFlags", ".", "forceInjectLibraries", "=", "null", ";", "defaultFlags", ".", "formatting", "=", "null", ";", "defaultFlags", ".", "generateExports", "=", "false", ";", "defaultFlags", ".", "hideWarningsFor", "=", "null", ";", "defaultFlags", ".", "injectLibraries", "=", "true", ";", "defaultFlags", ".", "js", "=", "null", ";", "defaultFlags", ".", "jsCode", "=", "null", ";", "defaultFlags", ".", "jscompError", "=", "null", ";", "defaultFlags", ".", "jscompOff", "=", "null", ";", "defaultFlags", ".", "jscompWarning", "=", "null", ";", "defaultFlags", ".", "jsModuleRoot", "=", "null", ";", "defaultFlags", ".", "jsOutputFile", "=", "\"compiled.js\"", ";", "defaultFlags", ".", "languageIn", "=", "\"ECMASCRIPT_2017\"", ";", "defaultFlags", ".", "languageOut", "=", "\"ECMASCRIPT5\"", ";", "defaultFlags", ".", "moduleResolution", "=", "\"BROWSER\"", ";", "defaultFlags", ".", "newTypeInf", "=", "false", ";", "defaultFlags", ".", "isolationMode", "=", "\"NONE\"", ";", "defaultFlags", ".", "outputWrapper", "=", "null", ";", "defaultFlags", ".", "packageJsonEntryNames", "=", "null", ";", "defaultFlags", ".", "parseInlineSourceMaps", "=", "true", ";", "defaultFlags", ".", "polymerPass", "=", "false", ";", "defaultFlags", ".", "polymerVersion", "=", "null", ";", "defaultFlags", ".", "preserveTypeAnnotations", "=", "false", ";", "defaultFlags", ".", "processClosurePrimitives", "=", "true", ";", "defaultFlags", ".", "processCommonJsModules", "=", "false", ";", "defaultFlags", ".", "renamePrefixNamespace", "=", "null", ";", "defaultFlags", ".", "renameVariablePrefix", "=", "null", ";", "defaultFlags", ".", "renaming", "=", "true", ";", "defaultFlags", ".", "rewritePolyfills", "=", "true", ";", "defaultFlags", ".", "sourceMapIncludeContent", "=", "false", ";", "defaultFlags", ".", "strictModeInput", "=", "true", ";", "defaultFlags", ".", "tracerMode", "=", "\"OFF\"", ";", "defaultFlags", ".", "warningLevel", "=", "\"DEFAULT\"", ";", "defaultFlags", ".", "useTypesForOptimization", "=", "true", ";", "return", "defaultFlags", ";", "}" ]
Lazy initialize due to GWT. If things are exported then Object is not available when the static initialization runs.
[ "Lazy", "initialize", "due", "to", "GWT", ".", "If", "things", "are", "exported", "then", "Object", "is", "not", "available", "when", "the", "static", "initialization", "runs", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/gwt/client/GwtRunner.java#L161-L221
24,623
google/closure-compiler
src/com/google/javascript/jscomp/PassFactory.java
PassFactory.createEmptyPass
public static PassFactory createEmptyPass(String name) { return new PassFactory(name, true) { @Override protected CompilerPass create(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) {} }; } @Override protected FeatureSet featureSet() { return FeatureSet.latest(); } }; }
java
public static PassFactory createEmptyPass(String name) { return new PassFactory(name, true) { @Override protected CompilerPass create(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) {} }; } @Override protected FeatureSet featureSet() { return FeatureSet.latest(); } }; }
[ "public", "static", "PassFactory", "createEmptyPass", "(", "String", "name", ")", "{", "return", "new", "PassFactory", "(", "name", ",", "true", ")", "{", "@", "Override", "protected", "CompilerPass", "create", "(", "final", "AbstractCompiler", "compiler", ")", "{", "return", "new", "CompilerPass", "(", ")", "{", "@", "Override", "public", "void", "process", "(", "Node", "externs", ",", "Node", "root", ")", "{", "}", "}", ";", "}", "@", "Override", "protected", "FeatureSet", "featureSet", "(", ")", "{", "return", "FeatureSet", ".", "latest", "(", ")", ";", "}", "}", ";", "}" ]
Create a no-op pass that can only run once. Used to break up loops.
[ "Create", "a", "no", "-", "op", "pass", "that", "can", "only", "run", "once", ".", "Used", "to", "break", "up", "loops", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PassFactory.java#L93-L108
24,624
google/closure-compiler
src/com/google/javascript/jscomp/CheckMissingAndExtraRequires.java
CheckMissingAndExtraRequires.isClassOrConstantName
private static boolean isClassOrConstantName(String name) { return name != null && name.length() > 1 && Character.isUpperCase(name.charAt(0)); }
java
private static boolean isClassOrConstantName(String name) { return name != null && name.length() > 1 && Character.isUpperCase(name.charAt(0)); }
[ "private", "static", "boolean", "isClassOrConstantName", "(", "String", "name", ")", "{", "return", "name", "!=", "null", "&&", "name", ".", "length", "(", ")", ">", "1", "&&", "Character", ".", "isUpperCase", "(", "name", ".", "charAt", "(", "0", ")", ")", ";", "}" ]
Return true if the name looks like a class name or a constant name.
[ "Return", "true", "if", "the", "name", "looks", "like", "a", "class", "name", "or", "a", "constant", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckMissingAndExtraRequires.java#L138-L140
24,625
google/closure-compiler
src/com/google/javascript/jscomp/CheckMissingAndExtraRequires.java
CheckMissingAndExtraRequires.getClassNames
private static ImmutableList<String> getClassNames(String qualifiedName) { ImmutableList.Builder<String> classNames = ImmutableList.builder(); List<String> parts = DOT_SPLITTER.splitToList(qualifiedName); for (int i = 0; i < parts.size(); i++) { String part = parts.get(i); if (isClassOrConstantName(part)) { classNames.add(DOT_JOINER.join(parts.subList(0, i + 1))); } } return classNames.build(); }
java
private static ImmutableList<String> getClassNames(String qualifiedName) { ImmutableList.Builder<String> classNames = ImmutableList.builder(); List<String> parts = DOT_SPLITTER.splitToList(qualifiedName); for (int i = 0; i < parts.size(); i++) { String part = parts.get(i); if (isClassOrConstantName(part)) { classNames.add(DOT_JOINER.join(parts.subList(0, i + 1))); } } return classNames.build(); }
[ "private", "static", "ImmutableList", "<", "String", ">", "getClassNames", "(", "String", "qualifiedName", ")", "{", "ImmutableList", ".", "Builder", "<", "String", ">", "classNames", "=", "ImmutableList", ".", "builder", "(", ")", ";", "List", "<", "String", ">", "parts", "=", "DOT_SPLITTER", ".", "splitToList", "(", "qualifiedName", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parts", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "part", "=", "parts", ".", "get", "(", "i", ")", ";", "if", "(", "isClassOrConstantName", "(", "part", ")", ")", "{", "classNames", ".", "add", "(", "DOT_JOINER", ".", "join", "(", "parts", ".", "subList", "(", "0", ",", "i", "+", "1", ")", ")", ")", ";", "}", "}", "return", "classNames", ".", "build", "(", ")", ";", "}" ]
or null if no part refers to a class.
[ "or", "null", "if", "no", "part", "refers", "to", "a", "class", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckMissingAndExtraRequires.java#L144-L154
24,626
google/closure-compiler
src/com/google/javascript/jscomp/CheckMissingAndExtraRequires.java
CheckMissingAndExtraRequires.maybeAddGoogScopeUsage
private void maybeAddGoogScopeUsage(NodeTraversal t, Node n, Node parent) { checkState(NodeUtil.isNameDeclaration(n)); if (n.hasOneChild() && parent == googScopeBlock) { Node rhs = n.getFirstFirstChild(); if (rhs != null && rhs.isQualifiedName()) { Node root = NodeUtil.getRootOfQualifiedName(rhs); if (root.isName()) { Var var = t.getScope().getVar(root.getString()); if (var == null || (var.isGlobal() && !var.isExtern())) { usages.put(rhs.getQualifiedName(), rhs); } } } } }
java
private void maybeAddGoogScopeUsage(NodeTraversal t, Node n, Node parent) { checkState(NodeUtil.isNameDeclaration(n)); if (n.hasOneChild() && parent == googScopeBlock) { Node rhs = n.getFirstFirstChild(); if (rhs != null && rhs.isQualifiedName()) { Node root = NodeUtil.getRootOfQualifiedName(rhs); if (root.isName()) { Var var = t.getScope().getVar(root.getString()); if (var == null || (var.isGlobal() && !var.isExtern())) { usages.put(rhs.getQualifiedName(), rhs); } } } } }
[ "private", "void", "maybeAddGoogScopeUsage", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "parent", ")", "{", "checkState", "(", "NodeUtil", ".", "isNameDeclaration", "(", "n", ")", ")", ";", "if", "(", "n", ".", "hasOneChild", "(", ")", "&&", "parent", "==", "googScopeBlock", ")", "{", "Node", "rhs", "=", "n", ".", "getFirstFirstChild", "(", ")", ";", "if", "(", "rhs", "!=", "null", "&&", "rhs", ".", "isQualifiedName", "(", ")", ")", "{", "Node", "root", "=", "NodeUtil", ".", "getRootOfQualifiedName", "(", "rhs", ")", ";", "if", "(", "root", ".", "isName", "(", ")", ")", "{", "Var", "var", "=", "t", ".", "getScope", "(", ")", ".", "getVar", "(", "root", ".", "getString", "(", ")", ")", ";", "if", "(", "var", "==", "null", "||", "(", "var", ".", "isGlobal", "(", ")", "&&", "!", "var", ".", "isExtern", "(", ")", ")", ")", "{", "usages", ".", "put", "(", "rhs", ".", "getQualifiedName", "(", ")", ",", "rhs", ")", ";", "}", "}", "}", "}", "}" ]
"var Dog = some.cute.Dog;" counts as a usage of some.cute.Dog, if it's immediately inside a goog.scope function.
[ "var", "Dog", "=", "some", ".", "cute", ".", "Dog", ";", "counts", "as", "a", "usage", "of", "some", ".", "cute", ".", "Dog", "if", "it", "s", "immediately", "inside", "a", "goog", ".", "scope", "function", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckMissingAndExtraRequires.java#L633-L647
24,627
google/closure-compiler
src/com/google/javascript/jscomp/TranspilationPasses.java
TranspilationPasses.addPostCheckTranspilationPasses
public static void addPostCheckTranspilationPasses( List<PassFactory> passes, CompilerOptions options) { if (options.needsTranspilationFrom(FeatureSet.ES_NEXT)) { passes.add(rewriteCatchWithNoBinding); } if (options.needsTranspilationFrom(ES2018)) { passes.add(rewriteAsyncIteration); passes.add(rewriteObjectSpread); } if (options.needsTranspilationFrom(ES8)) { // Trailing commas in parameter lists are flagged as present by the parser, // but never actually represented in the AST. // The only thing we need to do is mark them as not present in the AST. passes.add( createFeatureRemovalPass( "markTrailingCommasInParameterListsRemoved", Feature.TRAILING_COMMA_IN_PARAM_LIST)); passes.add(rewriteAsyncFunctions); } if (options.needsTranspilationFrom(ES7)) { passes.add(rewriteExponentialOperator); } if (options.needsTranspilationFrom(ES6)) { // TODO(b/73387406): Move passes here as typechecking & other check passes are updated to cope // with the features they transpile and as the passes themselves are updated to propagate type // information to the transpiled code. // Binary and octal literals are effectively transpiled by the parser. // There's no transpilation we can do for the new regexp flags. passes.add( createFeatureRemovalPass( "markEs6FeaturesNotRequiringTranspilationAsRemoved", Feature.BINARY_LITERALS, Feature.OCTAL_LITERALS, Feature.REGEXP_FLAG_U, Feature.REGEXP_FLAG_Y)); passes.add(es6NormalizeShorthandProperties); passes.add(es6RewriteClassExtends); passes.add(es6ConvertSuper); passes.add(es6RenameVariablesInParamLists); passes.add(es6SplitVariableDeclarations); passes.add( getEs6RewriteDestructuring(ObjectDestructuringRewriteMode.REWRITE_ALL_OBJECT_PATTERNS)); passes.add(es6RewriteArrowFunction); passes.add(es6ExtractClasses); passes.add(es6RewriteClass); passes.add(es6RewriteRestAndSpread); passes.add(lateConvertEs6ToEs3); passes.add(es6ForOf); passes.add(rewriteBlockScopedFunctionDeclaration); passes.add(rewriteBlockScopedDeclaration); passes.add(rewriteGenerators); passes.add(es6ConvertSuperConstructorCalls); } else if (options.needsTranspilationOf(Feature.OBJECT_PATTERN_REST)) { passes.add(es6RenameVariablesInParamLists); passes.add(es6SplitVariableDeclarations); passes.add(getEs6RewriteDestructuring(ObjectDestructuringRewriteMode.REWRITE_OBJECT_REST)); } }
java
public static void addPostCheckTranspilationPasses( List<PassFactory> passes, CompilerOptions options) { if (options.needsTranspilationFrom(FeatureSet.ES_NEXT)) { passes.add(rewriteCatchWithNoBinding); } if (options.needsTranspilationFrom(ES2018)) { passes.add(rewriteAsyncIteration); passes.add(rewriteObjectSpread); } if (options.needsTranspilationFrom(ES8)) { // Trailing commas in parameter lists are flagged as present by the parser, // but never actually represented in the AST. // The only thing we need to do is mark them as not present in the AST. passes.add( createFeatureRemovalPass( "markTrailingCommasInParameterListsRemoved", Feature.TRAILING_COMMA_IN_PARAM_LIST)); passes.add(rewriteAsyncFunctions); } if (options.needsTranspilationFrom(ES7)) { passes.add(rewriteExponentialOperator); } if (options.needsTranspilationFrom(ES6)) { // TODO(b/73387406): Move passes here as typechecking & other check passes are updated to cope // with the features they transpile and as the passes themselves are updated to propagate type // information to the transpiled code. // Binary and octal literals are effectively transpiled by the parser. // There's no transpilation we can do for the new regexp flags. passes.add( createFeatureRemovalPass( "markEs6FeaturesNotRequiringTranspilationAsRemoved", Feature.BINARY_LITERALS, Feature.OCTAL_LITERALS, Feature.REGEXP_FLAG_U, Feature.REGEXP_FLAG_Y)); passes.add(es6NormalizeShorthandProperties); passes.add(es6RewriteClassExtends); passes.add(es6ConvertSuper); passes.add(es6RenameVariablesInParamLists); passes.add(es6SplitVariableDeclarations); passes.add( getEs6RewriteDestructuring(ObjectDestructuringRewriteMode.REWRITE_ALL_OBJECT_PATTERNS)); passes.add(es6RewriteArrowFunction); passes.add(es6ExtractClasses); passes.add(es6RewriteClass); passes.add(es6RewriteRestAndSpread); passes.add(lateConvertEs6ToEs3); passes.add(es6ForOf); passes.add(rewriteBlockScopedFunctionDeclaration); passes.add(rewriteBlockScopedDeclaration); passes.add(rewriteGenerators); passes.add(es6ConvertSuperConstructorCalls); } else if (options.needsTranspilationOf(Feature.OBJECT_PATTERN_REST)) { passes.add(es6RenameVariablesInParamLists); passes.add(es6SplitVariableDeclarations); passes.add(getEs6RewriteDestructuring(ObjectDestructuringRewriteMode.REWRITE_OBJECT_REST)); } }
[ "public", "static", "void", "addPostCheckTranspilationPasses", "(", "List", "<", "PassFactory", ">", "passes", ",", "CompilerOptions", "options", ")", "{", "if", "(", "options", ".", "needsTranspilationFrom", "(", "FeatureSet", ".", "ES_NEXT", ")", ")", "{", "passes", ".", "add", "(", "rewriteCatchWithNoBinding", ")", ";", "}", "if", "(", "options", ".", "needsTranspilationFrom", "(", "ES2018", ")", ")", "{", "passes", ".", "add", "(", "rewriteAsyncIteration", ")", ";", "passes", ".", "add", "(", "rewriteObjectSpread", ")", ";", "}", "if", "(", "options", ".", "needsTranspilationFrom", "(", "ES8", ")", ")", "{", "// Trailing commas in parameter lists are flagged as present by the parser,", "// but never actually represented in the AST.", "// The only thing we need to do is mark them as not present in the AST.", "passes", ".", "add", "(", "createFeatureRemovalPass", "(", "\"markTrailingCommasInParameterListsRemoved\"", ",", "Feature", ".", "TRAILING_COMMA_IN_PARAM_LIST", ")", ")", ";", "passes", ".", "add", "(", "rewriteAsyncFunctions", ")", ";", "}", "if", "(", "options", ".", "needsTranspilationFrom", "(", "ES7", ")", ")", "{", "passes", ".", "add", "(", "rewriteExponentialOperator", ")", ";", "}", "if", "(", "options", ".", "needsTranspilationFrom", "(", "ES6", ")", ")", "{", "// TODO(b/73387406): Move passes here as typechecking & other check passes are updated to cope", "// with the features they transpile and as the passes themselves are updated to propagate type", "// information to the transpiled code.", "// Binary and octal literals are effectively transpiled by the parser.", "// There's no transpilation we can do for the new regexp flags.", "passes", ".", "add", "(", "createFeatureRemovalPass", "(", "\"markEs6FeaturesNotRequiringTranspilationAsRemoved\"", ",", "Feature", ".", "BINARY_LITERALS", ",", "Feature", ".", "OCTAL_LITERALS", ",", "Feature", ".", "REGEXP_FLAG_U", ",", "Feature", ".", "REGEXP_FLAG_Y", ")", ")", ";", "passes", ".", "add", "(", "es6NormalizeShorthandProperties", ")", ";", "passes", ".", "add", "(", "es6RewriteClassExtends", ")", ";", "passes", ".", "add", "(", "es6ConvertSuper", ")", ";", "passes", ".", "add", "(", "es6RenameVariablesInParamLists", ")", ";", "passes", ".", "add", "(", "es6SplitVariableDeclarations", ")", ";", "passes", ".", "add", "(", "getEs6RewriteDestructuring", "(", "ObjectDestructuringRewriteMode", ".", "REWRITE_ALL_OBJECT_PATTERNS", ")", ")", ";", "passes", ".", "add", "(", "es6RewriteArrowFunction", ")", ";", "passes", ".", "add", "(", "es6ExtractClasses", ")", ";", "passes", ".", "add", "(", "es6RewriteClass", ")", ";", "passes", ".", "add", "(", "es6RewriteRestAndSpread", ")", ";", "passes", ".", "add", "(", "lateConvertEs6ToEs3", ")", ";", "passes", ".", "add", "(", "es6ForOf", ")", ";", "passes", ".", "add", "(", "rewriteBlockScopedFunctionDeclaration", ")", ";", "passes", ".", "add", "(", "rewriteBlockScopedDeclaration", ")", ";", "passes", ".", "add", "(", "rewriteGenerators", ")", ";", "passes", ".", "add", "(", "es6ConvertSuperConstructorCalls", ")", ";", "}", "else", "if", "(", "options", ".", "needsTranspilationOf", "(", "Feature", ".", "OBJECT_PATTERN_REST", ")", ")", "{", "passes", ".", "add", "(", "es6RenameVariablesInParamLists", ")", ";", "passes", ".", "add", "(", "es6SplitVariableDeclarations", ")", ";", "passes", ".", "add", "(", "getEs6RewriteDestructuring", "(", "ObjectDestructuringRewriteMode", ".", "REWRITE_OBJECT_REST", ")", ")", ";", "}", "}" ]
Adds transpilation passes that should run after all checks are done.
[ "Adds", "transpilation", "passes", "that", "should", "run", "after", "all", "checks", "are", "done", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TranspilationPasses.java#L79-L140
24,628
google/closure-compiler
src/com/google/javascript/jscomp/TranspilationPasses.java
TranspilationPasses.processTranspile
static void processTranspile( AbstractCompiler compiler, Node combinedRoot, FeatureSet featureSet, Callback... callbacks) { if (compiler.getOptions().needsTranspilationFrom(featureSet)) { FeatureSet languageOutFeatures = compiler.getOptions().getOutputFeatureSet(); for (Node singleRoot : combinedRoot.children()) { // Only run the transpilation if this file has features not in the compiler's target output // language. For example, if this file is purely ES6 and the output language is ES6, don't // run any transpilation passes on it. // TODO(lharker): We could save time by being more selective about what files we transpile. // e.g. if a file has async functions but not `**`, don't run `**` transpilation on it. // Right now we know what features were in a file at parse time, but not what features were // added to that file by other transpilation passes. if (doesScriptHaveUnsupportedFeatures(singleRoot, languageOutFeatures)) { for (Callback callback : callbacks) { singleRoot.putBooleanProp(Node.TRANSPILED, true); NodeTraversal.traverse(compiler, singleRoot, callback); } } } } }
java
static void processTranspile( AbstractCompiler compiler, Node combinedRoot, FeatureSet featureSet, Callback... callbacks) { if (compiler.getOptions().needsTranspilationFrom(featureSet)) { FeatureSet languageOutFeatures = compiler.getOptions().getOutputFeatureSet(); for (Node singleRoot : combinedRoot.children()) { // Only run the transpilation if this file has features not in the compiler's target output // language. For example, if this file is purely ES6 and the output language is ES6, don't // run any transpilation passes on it. // TODO(lharker): We could save time by being more selective about what files we transpile. // e.g. if a file has async functions but not `**`, don't run `**` transpilation on it. // Right now we know what features were in a file at parse time, but not what features were // added to that file by other transpilation passes. if (doesScriptHaveUnsupportedFeatures(singleRoot, languageOutFeatures)) { for (Callback callback : callbacks) { singleRoot.putBooleanProp(Node.TRANSPILED, true); NodeTraversal.traverse(compiler, singleRoot, callback); } } } } }
[ "static", "void", "processTranspile", "(", "AbstractCompiler", "compiler", ",", "Node", "combinedRoot", ",", "FeatureSet", "featureSet", ",", "Callback", "...", "callbacks", ")", "{", "if", "(", "compiler", ".", "getOptions", "(", ")", ".", "needsTranspilationFrom", "(", "featureSet", ")", ")", "{", "FeatureSet", "languageOutFeatures", "=", "compiler", ".", "getOptions", "(", ")", ".", "getOutputFeatureSet", "(", ")", ";", "for", "(", "Node", "singleRoot", ":", "combinedRoot", ".", "children", "(", ")", ")", "{", "// Only run the transpilation if this file has features not in the compiler's target output", "// language. For example, if this file is purely ES6 and the output language is ES6, don't", "// run any transpilation passes on it.", "// TODO(lharker): We could save time by being more selective about what files we transpile.", "// e.g. if a file has async functions but not `**`, don't run `**` transpilation on it.", "// Right now we know what features were in a file at parse time, but not what features were", "// added to that file by other transpilation passes.", "if", "(", "doesScriptHaveUnsupportedFeatures", "(", "singleRoot", ",", "languageOutFeatures", ")", ")", "{", "for", "(", "Callback", "callback", ":", "callbacks", ")", "{", "singleRoot", ".", "putBooleanProp", "(", "Node", ".", "TRANSPILED", ",", "true", ")", ";", "NodeTraversal", ".", "traverse", "(", "compiler", ",", "singleRoot", ",", "callback", ")", ";", "}", "}", "}", "}", "}" ]
Process transpilations if the input language needs transpilation from certain features, on any JS file that has features not present in the compiler's output language mode. @param compiler An AbstractCompiler @param combinedRoot The combined root for all JS files. @param featureSet The features which this pass helps transpile. @param callbacks The callbacks that should be invoked if a file has ES6 features.
[ "Process", "transpilations", "if", "the", "input", "language", "needs", "transpilation", "from", "certain", "features", "on", "any", "JS", "file", "that", "has", "features", "not", "present", "in", "the", "compiler", "s", "output", "language", "mode", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TranspilationPasses.java#L526-L547
24,629
google/closure-compiler
src/com/google/javascript/jscomp/TranspilationPasses.java
TranspilationPasses.hotSwapTranspile
static void hotSwapTranspile( AbstractCompiler compiler, Node scriptRoot, FeatureSet featureSet, Callback... callbacks) { if (compiler.getOptions().needsTranspilationFrom(featureSet)) { FeatureSet languageOutFeatures = compiler.getOptions().getOutputFeatureSet(); if (doesScriptHaveUnsupportedFeatures(scriptRoot, languageOutFeatures)) { for (Callback callback : callbacks) { scriptRoot.putBooleanProp(Node.TRANSPILED, true); NodeTraversal.traverse(compiler, scriptRoot, callback); } } } }
java
static void hotSwapTranspile( AbstractCompiler compiler, Node scriptRoot, FeatureSet featureSet, Callback... callbacks) { if (compiler.getOptions().needsTranspilationFrom(featureSet)) { FeatureSet languageOutFeatures = compiler.getOptions().getOutputFeatureSet(); if (doesScriptHaveUnsupportedFeatures(scriptRoot, languageOutFeatures)) { for (Callback callback : callbacks) { scriptRoot.putBooleanProp(Node.TRANSPILED, true); NodeTraversal.traverse(compiler, scriptRoot, callback); } } } }
[ "static", "void", "hotSwapTranspile", "(", "AbstractCompiler", "compiler", ",", "Node", "scriptRoot", ",", "FeatureSet", "featureSet", ",", "Callback", "...", "callbacks", ")", "{", "if", "(", "compiler", ".", "getOptions", "(", ")", ".", "needsTranspilationFrom", "(", "featureSet", ")", ")", "{", "FeatureSet", "languageOutFeatures", "=", "compiler", ".", "getOptions", "(", ")", ".", "getOutputFeatureSet", "(", ")", ";", "if", "(", "doesScriptHaveUnsupportedFeatures", "(", "scriptRoot", ",", "languageOutFeatures", ")", ")", "{", "for", "(", "Callback", "callback", ":", "callbacks", ")", "{", "scriptRoot", ".", "putBooleanProp", "(", "Node", ".", "TRANSPILED", ",", "true", ")", ";", "NodeTraversal", ".", "traverse", "(", "compiler", ",", "scriptRoot", ",", "callback", ")", ";", "}", "}", "}", "}" ]
Hot-swap ES6+ transpilations if the input language needs transpilation from certain features, on any JS file that has features not present in the compiler's output language mode. @param compiler An AbstractCompiler @param scriptRoot The SCRIPT root for the JS file. @param featureSet The features which this pass helps transpile. @param callbacks The callbacks that should be invoked if the file has ES6 features.
[ "Hot", "-", "swap", "ES6", "+", "transpilations", "if", "the", "input", "language", "needs", "transpilation", "from", "certain", "features", "on", "any", "JS", "file", "that", "has", "features", "not", "present", "in", "the", "compiler", "s", "output", "language", "mode", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TranspilationPasses.java#L558-L569
24,630
google/closure-compiler
src/com/google/javascript/jscomp/TranspilationPasses.java
TranspilationPasses.createFeatureRemovalPass
private static HotSwapPassFactory createFeatureRemovalPass( String passName, final Feature featureToRemove, final Feature... moreFeaturesToRemove) { return new HotSwapPassFactory(passName) { @Override protected HotSwapCompilerPass create(final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void hotSwapScript(Node scriptRoot, Node originalRoot) { maybeMarkFeaturesAsTranspiledAway(compiler, featureToRemove, moreFeaturesToRemove); } @Override public void process(Node externs, Node root) { maybeMarkFeaturesAsTranspiledAway(compiler, featureToRemove, moreFeaturesToRemove); } }; } @Override protected FeatureSet featureSet() { return FeatureSet.latest(); } }; }
java
private static HotSwapPassFactory createFeatureRemovalPass( String passName, final Feature featureToRemove, final Feature... moreFeaturesToRemove) { return new HotSwapPassFactory(passName) { @Override protected HotSwapCompilerPass create(final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void hotSwapScript(Node scriptRoot, Node originalRoot) { maybeMarkFeaturesAsTranspiledAway(compiler, featureToRemove, moreFeaturesToRemove); } @Override public void process(Node externs, Node root) { maybeMarkFeaturesAsTranspiledAway(compiler, featureToRemove, moreFeaturesToRemove); } }; } @Override protected FeatureSet featureSet() { return FeatureSet.latest(); } }; }
[ "private", "static", "HotSwapPassFactory", "createFeatureRemovalPass", "(", "String", "passName", ",", "final", "Feature", "featureToRemove", ",", "final", "Feature", "...", "moreFeaturesToRemove", ")", "{", "return", "new", "HotSwapPassFactory", "(", "passName", ")", "{", "@", "Override", "protected", "HotSwapCompilerPass", "create", "(", "final", "AbstractCompiler", "compiler", ")", "{", "return", "new", "HotSwapCompilerPass", "(", ")", "{", "@", "Override", "public", "void", "hotSwapScript", "(", "Node", "scriptRoot", ",", "Node", "originalRoot", ")", "{", "maybeMarkFeaturesAsTranspiledAway", "(", "compiler", ",", "featureToRemove", ",", "moreFeaturesToRemove", ")", ";", "}", "@", "Override", "public", "void", "process", "(", "Node", "externs", ",", "Node", "root", ")", "{", "maybeMarkFeaturesAsTranspiledAway", "(", "compiler", ",", "featureToRemove", ",", "moreFeaturesToRemove", ")", ";", "}", "}", ";", "}", "@", "Override", "protected", "FeatureSet", "featureSet", "(", ")", "{", "return", "FeatureSet", ".", "latest", "(", ")", ";", "}", "}", ";", "}" ]
Returns a pass that just removes features from the AST FeatureSet. <p>Doing this indicates that the AST no longer contains uses of the features, or that they are no longer of concern for some other reason.
[ "Returns", "a", "pass", "that", "just", "removes", "features", "from", "the", "AST", "FeatureSet", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TranspilationPasses.java#L594-L617
24,631
google/closure-compiler
src/com/google/javascript/jscomp/GlobalNamespace.java
GlobalNamespace.scanNewNodes
void scanNewNodes(Set<AstChange> newNodes) { BuildGlobalNamespace builder = new BuildGlobalNamespace(); for (AstChange info : newNodes) { if (!info.node.isQualifiedName() && !NodeUtil.mayBeObjectLitKey(info.node)) { continue; } scanFromNode(builder, info.module, info.scope, info.node); } }
java
void scanNewNodes(Set<AstChange> newNodes) { BuildGlobalNamespace builder = new BuildGlobalNamespace(); for (AstChange info : newNodes) { if (!info.node.isQualifiedName() && !NodeUtil.mayBeObjectLitKey(info.node)) { continue; } scanFromNode(builder, info.module, info.scope, info.node); } }
[ "void", "scanNewNodes", "(", "Set", "<", "AstChange", ">", "newNodes", ")", "{", "BuildGlobalNamespace", "builder", "=", "new", "BuildGlobalNamespace", "(", ")", ";", "for", "(", "AstChange", "info", ":", "newNodes", ")", "{", "if", "(", "!", "info", ".", "node", ".", "isQualifiedName", "(", ")", "&&", "!", "NodeUtil", ".", "mayBeObjectLitKey", "(", "info", ".", "node", ")", ")", "{", "continue", ";", "}", "scanFromNode", "(", "builder", ",", "info", ".", "module", ",", "info", ".", "scope", ",", "info", ".", "node", ")", ";", "}", "}" ]
If the client adds new nodes to the AST, scan these new nodes to see if they've added any references to the global namespace. @param newNodes New nodes to check.
[ "If", "the", "client", "adds", "new", "nodes", "to", "the", "AST", "scan", "these", "new", "nodes", "to", "see", "if", "they", "ve", "added", "any", "references", "to", "the", "global", "namespace", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/GlobalNamespace.java#L228-L237
24,632
google/closure-compiler
src/com/google/javascript/jscomp/GlobalNamespace.java
GlobalNamespace.process
private void process() { if (hasExternsRoot()) { sourceKind = SourceKind.EXTERN; NodeTraversal.traverse(compiler, externsRoot, new BuildGlobalNamespace()); } sourceKind = SourceKind.CODE; NodeTraversal.traverse(compiler, root, new BuildGlobalNamespace()); generated = true; externsScope = null; }
java
private void process() { if (hasExternsRoot()) { sourceKind = SourceKind.EXTERN; NodeTraversal.traverse(compiler, externsRoot, new BuildGlobalNamespace()); } sourceKind = SourceKind.CODE; NodeTraversal.traverse(compiler, root, new BuildGlobalNamespace()); generated = true; externsScope = null; }
[ "private", "void", "process", "(", ")", "{", "if", "(", "hasExternsRoot", "(", ")", ")", "{", "sourceKind", "=", "SourceKind", ".", "EXTERN", ";", "NodeTraversal", ".", "traverse", "(", "compiler", ",", "externsRoot", ",", "new", "BuildGlobalNamespace", "(", ")", ")", ";", "}", "sourceKind", "=", "SourceKind", ".", "CODE", ";", "NodeTraversal", ".", "traverse", "(", "compiler", ",", "root", ",", "new", "BuildGlobalNamespace", "(", ")", ")", ";", "generated", "=", "true", ";", "externsScope", "=", "null", ";", "}" ]
Builds the namespace lazily.
[ "Builds", "the", "namespace", "lazily", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/GlobalNamespace.java#L261-L271
24,633
google/closure-compiler
src/com/google/javascript/jscomp/GlobalNamespace.java
GlobalNamespace.isGlobalNameReference
private boolean isGlobalNameReference(String name, Scope s) { String topVarName = getTopVarName(name); return isGlobalVarReference(topVarName, s); }
java
private boolean isGlobalNameReference(String name, Scope s) { String topVarName = getTopVarName(name); return isGlobalVarReference(topVarName, s); }
[ "private", "boolean", "isGlobalNameReference", "(", "String", "name", ",", "Scope", "s", ")", "{", "String", "topVarName", "=", "getTopVarName", "(", "name", ")", ";", "return", "isGlobalVarReference", "(", "topVarName", ",", "s", ")", ";", "}" ]
Determines whether a name reference in a particular scope is a global name reference. @param name A variable or property name (e.g. "a" or "a.b.c.d") @param s The scope in which the name is referenced @return Whether the name reference is a global name reference
[ "Determines", "whether", "a", "name", "reference", "in", "a", "particular", "scope", "is", "a", "global", "name", "reference", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/GlobalNamespace.java#L280-L283
24,634
google/closure-compiler
src/com/google/javascript/jscomp/GlobalNamespace.java
GlobalNamespace.getTopVarName
private static String getTopVarName(String name) { int firstDotIndex = name.indexOf('.'); return firstDotIndex == -1 ? name : name.substring(0, firstDotIndex); }
java
private static String getTopVarName(String name) { int firstDotIndex = name.indexOf('.'); return firstDotIndex == -1 ? name : name.substring(0, firstDotIndex); }
[ "private", "static", "String", "getTopVarName", "(", "String", "name", ")", "{", "int", "firstDotIndex", "=", "name", ".", "indexOf", "(", "'", "'", ")", ";", "return", "firstDotIndex", "==", "-", "1", "?", "name", ":", "name", ".", "substring", "(", "0", ",", "firstDotIndex", ")", ";", "}" ]
Gets the top variable name from a possibly namespaced name. @param name A variable or qualified property name (e.g. "a" or "a.b.c.d") @return The top variable name (e.g. "a")
[ "Gets", "the", "top", "variable", "name", "from", "a", "possibly", "namespaced", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/GlobalNamespace.java#L291-L294
24,635
google/closure-compiler
src/com/google/javascript/jscomp/GlobalNamespace.java
GlobalNamespace.isGlobalVarReference
private boolean isGlobalVarReference(String name, Scope s) { Var v = s.getVar(name); if (v == null && externsScope != null) { v = externsScope.getVar(name); } return v != null && !v.isLocal(); }
java
private boolean isGlobalVarReference(String name, Scope s) { Var v = s.getVar(name); if (v == null && externsScope != null) { v = externsScope.getVar(name); } return v != null && !v.isLocal(); }
[ "private", "boolean", "isGlobalVarReference", "(", "String", "name", ",", "Scope", "s", ")", "{", "Var", "v", "=", "s", ".", "getVar", "(", "name", ")", ";", "if", "(", "v", "==", "null", "&&", "externsScope", "!=", "null", ")", "{", "v", "=", "externsScope", ".", "getVar", "(", "name", ")", ";", "}", "return", "v", "!=", "null", "&&", "!", "v", ".", "isLocal", "(", ")", ";", "}" ]
Determines whether a variable name reference in a particular scope is a global variable reference. @param name A variable name (e.g. "a") @param s The scope in which the name is referenced @return Whether the name reference is a global variable reference
[ "Determines", "whether", "a", "variable", "name", "reference", "in", "a", "particular", "scope", "is", "a", "global", "variable", "reference", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/GlobalNamespace.java#L304-L310
24,636
google/closure-compiler
src/com/google/javascript/jscomp/CodePrinter.java
CodePrinter.toSource
private static String toSource( Node root, Format outputFormat, CompilerOptions options, SourceMap sourceMap, boolean tagAsTypeSummary, boolean tagAsStrict, boolean lineBreak, CodeGeneratorFactory codeGeneratorFactory) { checkState(options.sourceMapDetailLevel != null); boolean createSourceMap = (sourceMap != null); MappedCodePrinter mcp = outputFormat == Format.COMPACT ? new CompactCodePrinter( lineBreak, options.preferLineBreakAtEndOfFile, options.lineLengthThreshold, createSourceMap, options.sourceMapDetailLevel) : new PrettyCodePrinter( options.lineLengthThreshold, createSourceMap, options.sourceMapDetailLevel); CodeGenerator cg = codeGeneratorFactory.getCodeGenerator(outputFormat, mcp); if (tagAsTypeSummary) { cg.tagAsTypeSummary(); } if (tagAsStrict) { cg.tagAsStrict(); } cg.add(root); mcp.endFile(); String code = mcp.getCode(); if (createSourceMap) { mcp.generateSourceMap(code, sourceMap); } return code; }
java
private static String toSource( Node root, Format outputFormat, CompilerOptions options, SourceMap sourceMap, boolean tagAsTypeSummary, boolean tagAsStrict, boolean lineBreak, CodeGeneratorFactory codeGeneratorFactory) { checkState(options.sourceMapDetailLevel != null); boolean createSourceMap = (sourceMap != null); MappedCodePrinter mcp = outputFormat == Format.COMPACT ? new CompactCodePrinter( lineBreak, options.preferLineBreakAtEndOfFile, options.lineLengthThreshold, createSourceMap, options.sourceMapDetailLevel) : new PrettyCodePrinter( options.lineLengthThreshold, createSourceMap, options.sourceMapDetailLevel); CodeGenerator cg = codeGeneratorFactory.getCodeGenerator(outputFormat, mcp); if (tagAsTypeSummary) { cg.tagAsTypeSummary(); } if (tagAsStrict) { cg.tagAsStrict(); } cg.add(root); mcp.endFile(); String code = mcp.getCode(); if (createSourceMap) { mcp.generateSourceMap(code, sourceMap); } return code; }
[ "private", "static", "String", "toSource", "(", "Node", "root", ",", "Format", "outputFormat", ",", "CompilerOptions", "options", ",", "SourceMap", "sourceMap", ",", "boolean", "tagAsTypeSummary", ",", "boolean", "tagAsStrict", ",", "boolean", "lineBreak", ",", "CodeGeneratorFactory", "codeGeneratorFactory", ")", "{", "checkState", "(", "options", ".", "sourceMapDetailLevel", "!=", "null", ")", ";", "boolean", "createSourceMap", "=", "(", "sourceMap", "!=", "null", ")", ";", "MappedCodePrinter", "mcp", "=", "outputFormat", "==", "Format", ".", "COMPACT", "?", "new", "CompactCodePrinter", "(", "lineBreak", ",", "options", ".", "preferLineBreakAtEndOfFile", ",", "options", ".", "lineLengthThreshold", ",", "createSourceMap", ",", "options", ".", "sourceMapDetailLevel", ")", ":", "new", "PrettyCodePrinter", "(", "options", ".", "lineLengthThreshold", ",", "createSourceMap", ",", "options", ".", "sourceMapDetailLevel", ")", ";", "CodeGenerator", "cg", "=", "codeGeneratorFactory", ".", "getCodeGenerator", "(", "outputFormat", ",", "mcp", ")", ";", "if", "(", "tagAsTypeSummary", ")", "{", "cg", ".", "tagAsTypeSummary", "(", ")", ";", "}", "if", "(", "tagAsStrict", ")", "{", "cg", ".", "tagAsStrict", "(", ")", ";", "}", "cg", ".", "add", "(", "root", ")", ";", "mcp", ".", "endFile", "(", ")", ";", "String", "code", "=", "mcp", ".", "getCode", "(", ")", ";", "if", "(", "createSourceMap", ")", "{", "mcp", ".", "generateSourceMap", "(", "code", ",", "sourceMap", ")", ";", "}", "return", "code", ";", "}" ]
Converts a tree to JS code
[ "Converts", "a", "tree", "to", "JS", "code" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CodePrinter.java#L845-L888
24,637
google/closure-compiler
src/com/google/javascript/jscomp/AstValidator.java
AstValidator.validateClassDeclaration
private void validateClassDeclaration(Node n, boolean isAmbient) { validateClassHelper(n, isAmbient); validateName(n.getFirstChild()); }
java
private void validateClassDeclaration(Node n, boolean isAmbient) { validateClassHelper(n, isAmbient); validateName(n.getFirstChild()); }
[ "private", "void", "validateClassDeclaration", "(", "Node", "n", ",", "boolean", "isAmbient", ")", "{", "validateClassHelper", "(", "n", ",", "isAmbient", ")", ";", "validateName", "(", "n", ".", "getFirstChild", "(", ")", ")", ";", "}" ]
In a class declaration, unlike a class expression, the class name is required.
[ "In", "a", "class", "declaration", "unlike", "a", "class", "expression", "the", "class", "name", "is", "required", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstValidator.java#L723-L726
24,638
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.removeChild
public final void removeChild(Node child) { checkState(child.parent == this, "%s is not the parent of %s", this, child); checkNotNull(child.previous); Node last = first.previous; Node prevSibling = child.previous; Node nextSibling = child.next; if (first == child) { first = nextSibling; if (nextSibling != null) { nextSibling.previous = last; } // last.next remains null } else if (child == last) { first.previous = prevSibling; prevSibling.next = null; } else { prevSibling.next = nextSibling; nextSibling.previous = prevSibling; } child.next = null; child.previous = null; child.parent = null; }
java
public final void removeChild(Node child) { checkState(child.parent == this, "%s is not the parent of %s", this, child); checkNotNull(child.previous); Node last = first.previous; Node prevSibling = child.previous; Node nextSibling = child.next; if (first == child) { first = nextSibling; if (nextSibling != null) { nextSibling.previous = last; } // last.next remains null } else if (child == last) { first.previous = prevSibling; prevSibling.next = null; } else { prevSibling.next = nextSibling; nextSibling.previous = prevSibling; } child.next = null; child.previous = null; child.parent = null; }
[ "public", "final", "void", "removeChild", "(", "Node", "child", ")", "{", "checkState", "(", "child", ".", "parent", "==", "this", ",", "\"%s is not the parent of %s\"", ",", "this", ",", "child", ")", ";", "checkNotNull", "(", "child", ".", "previous", ")", ";", "Node", "last", "=", "first", ".", "previous", ";", "Node", "prevSibling", "=", "child", ".", "previous", ";", "Node", "nextSibling", "=", "child", ".", "next", ";", "if", "(", "first", "==", "child", ")", "{", "first", "=", "nextSibling", ";", "if", "(", "nextSibling", "!=", "null", ")", "{", "nextSibling", ".", "previous", "=", "last", ";", "}", "// last.next remains null", "}", "else", "if", "(", "child", "==", "last", ")", "{", "first", ".", "previous", "=", "prevSibling", ";", "prevSibling", ".", "next", "=", "null", ";", "}", "else", "{", "prevSibling", ".", "next", "=", "nextSibling", ";", "nextSibling", ".", "previous", "=", "prevSibling", ";", "}", "child", ".", "next", "=", "null", ";", "child", ".", "previous", "=", "null", ";", "child", ".", "parent", "=", "null", ";", "}" ]
Detach a child from its parent and siblings.
[ "Detach", "a", "child", "from", "its", "parent", "and", "siblings", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L952-L976
24,639
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.replaceChild
public final void replaceChild(Node child, Node newChild) { checkArgument(newChild.next == null, "The new child node has next siblings."); checkArgument(newChild.previous == null, "The new child node has previous siblings."); checkArgument(newChild.parent == null, "The new child node already has a parent."); checkState(child.parent == this, "%s is not the parent of %s", this, child); // Copy over important information. newChild.useSourceInfoIfMissingFrom(child); newChild.parent = this; Node nextSibling = child.next; Node prevSibling = child.previous; Node last = first.previous; if (child == prevSibling) { // first and only child first = newChild; first.previous = newChild; } else { if (child == first) { first = newChild; // prevSibling == last, and last.next remains null } else { prevSibling.next = newChild; } if (child == last) { first.previous = newChild; } else { nextSibling.previous = newChild; } newChild.previous = prevSibling; } newChild.next = nextSibling; // maybe null child.next = null; child.previous = null; child.parent = null; }
java
public final void replaceChild(Node child, Node newChild) { checkArgument(newChild.next == null, "The new child node has next siblings."); checkArgument(newChild.previous == null, "The new child node has previous siblings."); checkArgument(newChild.parent == null, "The new child node already has a parent."); checkState(child.parent == this, "%s is not the parent of %s", this, child); // Copy over important information. newChild.useSourceInfoIfMissingFrom(child); newChild.parent = this; Node nextSibling = child.next; Node prevSibling = child.previous; Node last = first.previous; if (child == prevSibling) { // first and only child first = newChild; first.previous = newChild; } else { if (child == first) { first = newChild; // prevSibling == last, and last.next remains null } else { prevSibling.next = newChild; } if (child == last) { first.previous = newChild; } else { nextSibling.previous = newChild; } newChild.previous = prevSibling; } newChild.next = nextSibling; // maybe null child.next = null; child.previous = null; child.parent = null; }
[ "public", "final", "void", "replaceChild", "(", "Node", "child", ",", "Node", "newChild", ")", "{", "checkArgument", "(", "newChild", ".", "next", "==", "null", ",", "\"The new child node has next siblings.\"", ")", ";", "checkArgument", "(", "newChild", ".", "previous", "==", "null", ",", "\"The new child node has previous siblings.\"", ")", ";", "checkArgument", "(", "newChild", ".", "parent", "==", "null", ",", "\"The new child node already has a parent.\"", ")", ";", "checkState", "(", "child", ".", "parent", "==", "this", ",", "\"%s is not the parent of %s\"", ",", "this", ",", "child", ")", ";", "// Copy over important information.", "newChild", ".", "useSourceInfoIfMissingFrom", "(", "child", ")", ";", "newChild", ".", "parent", "=", "this", ";", "Node", "nextSibling", "=", "child", ".", "next", ";", "Node", "prevSibling", "=", "child", ".", "previous", ";", "Node", "last", "=", "first", ".", "previous", ";", "if", "(", "child", "==", "prevSibling", ")", "{", "// first and only child", "first", "=", "newChild", ";", "first", ".", "previous", "=", "newChild", ";", "}", "else", "{", "if", "(", "child", "==", "first", ")", "{", "first", "=", "newChild", ";", "// prevSibling == last, and last.next remains null", "}", "else", "{", "prevSibling", ".", "next", "=", "newChild", ";", "}", "if", "(", "child", "==", "last", ")", "{", "first", ".", "previous", "=", "newChild", ";", "}", "else", "{", "nextSibling", ".", "previous", "=", "newChild", ";", "}", "newChild", ".", "previous", "=", "prevSibling", ";", "}", "newChild", ".", "next", "=", "nextSibling", ";", "// maybe null", "child", ".", "next", "=", "null", ";", "child", ".", "previous", "=", "null", ";", "child", ".", "parent", "=", "null", ";", "}" ]
Detaches child from Node and replaces it with newChild.
[ "Detaches", "child", "from", "Node", "and", "replaces", "it", "with", "newChild", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L986-L1025
24,640
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.clonePropsFrom
public final Node clonePropsFrom(Node other) { checkState(this.propListHead == null, "Node has existing properties."); this.propListHead = other.propListHead; return this; }
java
public final Node clonePropsFrom(Node other) { checkState(this.propListHead == null, "Node has existing properties."); this.propListHead = other.propListHead; return this; }
[ "public", "final", "Node", "clonePropsFrom", "(", "Node", "other", ")", "{", "checkState", "(", "this", ".", "propListHead", "==", "null", ",", "\"Node has existing properties.\"", ")", ";", "this", ".", "propListHead", "=", "other", ".", "propListHead", ";", "return", "this", ";", "}" ]
Clone the properties from the provided node without copying the property object. The receiving node may not have any existing properties. @param other The node to clone properties from. @return this node.
[ "Clone", "the", "properties", "from", "the", "provided", "node", "without", "copying", "the", "property", "object", ".", "The", "receiving", "node", "may", "not", "have", "any", "existing", "properties", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L1057-L1061
24,641
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.getIntProp
public final int getIntProp(Prop propType) { PropListItem item = lookupProperty(propType); if (item == null) { return 0; } return item.getIntValue(); }
java
public final int getIntProp(Prop propType) { PropListItem item = lookupProperty(propType); if (item == null) { return 0; } return item.getIntValue(); }
[ "public", "final", "int", "getIntProp", "(", "Prop", "propType", ")", "{", "PropListItem", "item", "=", "lookupProperty", "(", "propType", ")", ";", "if", "(", "item", "==", "null", ")", "{", "return", "0", ";", "}", "return", "item", ".", "getIntValue", "(", ")", ";", "}" ]
Returns the integer value for the property, or 0 if the property is not defined.
[ "Returns", "the", "integer", "value", "for", "the", "property", "or", "0", "if", "the", "property", "is", "not", "defined", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L1112-L1118
24,642
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.getSortedPropTypes
private byte[] getSortedPropTypes() { int count = 0; for (PropListItem x = propListHead; x != null; x = x.next) { count++; } byte[] keys = new byte[count]; for (PropListItem x = propListHead; x != null; x = x.next) { count--; keys[count] = x.propType; } Arrays.sort(keys); return keys; }
java
private byte[] getSortedPropTypes() { int count = 0; for (PropListItem x = propListHead; x != null; x = x.next) { count++; } byte[] keys = new byte[count]; for (PropListItem x = propListHead; x != null; x = x.next) { count--; keys[count] = x.propType; } Arrays.sort(keys); return keys; }
[ "private", "byte", "[", "]", "getSortedPropTypes", "(", ")", "{", "int", "count", "=", "0", ";", "for", "(", "PropListItem", "x", "=", "propListHead", ";", "x", "!=", "null", ";", "x", "=", "x", ".", "next", ")", "{", "count", "++", ";", "}", "byte", "[", "]", "keys", "=", "new", "byte", "[", "count", "]", ";", "for", "(", "PropListItem", "x", "=", "propListHead", ";", "x", "!=", "null", ";", "x", "=", "x", ".", "next", ")", "{", "count", "--", ";", "keys", "[", "count", "]", "=", "x", ".", "propType", ";", "}", "Arrays", ".", "sort", "(", "keys", ")", ";", "return", "keys", ";", "}" ]
Gets all the property types, in sorted order.
[ "Gets", "all", "the", "property", "types", "in", "sorted", "order", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L1188-L1202
24,643
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.setString
public void setString(String value) { if (this.token == Token.STRING || this.token == Token.NAME) { throw new IllegalStateException( "String node not created with Node.newString"); } else { throw new UnsupportedOperationException(this + " is not a string node"); } }
java
public void setString(String value) { if (this.token == Token.STRING || this.token == Token.NAME) { throw new IllegalStateException( "String node not created with Node.newString"); } else { throw new UnsupportedOperationException(this + " is not a string node"); } }
[ "public", "void", "setString", "(", "String", "value", ")", "{", "if", "(", "this", ".", "token", "==", "Token", ".", "STRING", "||", "this", ".", "token", "==", "Token", ".", "NAME", ")", "{", "throw", "new", "IllegalStateException", "(", "\"String node not created with Node.newString\"", ")", ";", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", "this", "+", "\" is not a string node\"", ")", ";", "}", "}" ]
Can only be called for a Token.STRING or Token.NAME. @param value the value to set.
[ "Can", "only", "be", "called", "for", "a", "Token", ".", "STRING", "or", "Token", ".", "NAME", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L1243-L1250
24,644
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.setStaticSourceFileFrom
public final void setStaticSourceFileFrom(Node other) { // Make sure source file prop nodes are not duplicated. if (other.propListHead != null && (this.propListHead == null || (this.propListHead.propType == Prop.SOURCE_FILE.ordinal() && this.propListHead.next == null))) { // Either the node has only Prop.SOURCE_FILE as a property or has not properties. PropListItem tail = other.propListHead; while (tail.next != null) { tail = tail.next; } if (tail.propType == Prop.SOURCE_FILE.ordinal()) { propListHead = tail; return; } } setStaticSourceFile(other.getStaticSourceFile()); }
java
public final void setStaticSourceFileFrom(Node other) { // Make sure source file prop nodes are not duplicated. if (other.propListHead != null && (this.propListHead == null || (this.propListHead.propType == Prop.SOURCE_FILE.ordinal() && this.propListHead.next == null))) { // Either the node has only Prop.SOURCE_FILE as a property or has not properties. PropListItem tail = other.propListHead; while (tail.next != null) { tail = tail.next; } if (tail.propType == Prop.SOURCE_FILE.ordinal()) { propListHead = tail; return; } } setStaticSourceFile(other.getStaticSourceFile()); }
[ "public", "final", "void", "setStaticSourceFileFrom", "(", "Node", "other", ")", "{", "// Make sure source file prop nodes are not duplicated.", "if", "(", "other", ".", "propListHead", "!=", "null", "&&", "(", "this", ".", "propListHead", "==", "null", "||", "(", "this", ".", "propListHead", ".", "propType", "==", "Prop", ".", "SOURCE_FILE", ".", "ordinal", "(", ")", "&&", "this", ".", "propListHead", ".", "next", "==", "null", ")", ")", ")", "{", "// Either the node has only Prop.SOURCE_FILE as a property or has not properties.", "PropListItem", "tail", "=", "other", ".", "propListHead", ";", "while", "(", "tail", ".", "next", "!=", "null", ")", "{", "tail", "=", "tail", ".", "next", ";", "}", "if", "(", "tail", ".", "propType", "==", "Prop", ".", "SOURCE_FILE", ".", "ordinal", "(", ")", ")", "{", "propListHead", "=", "tail", ";", "return", ";", "}", "}", "setStaticSourceFile", "(", "other", ".", "getStaticSourceFile", "(", ")", ")", ";", "}" ]
Source position management
[ "Source", "position", "management" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L1431-L1448
24,645
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.setLengthForTree
public final void setLengthForTree(int length) { this.length = length; for (Node child = first; child != null; child = child.next) { child.setLengthForTree(length); } }
java
public final void setLengthForTree(int length) { this.length = length; for (Node child = first; child != null; child = child.next) { child.setLengthForTree(length); } }
[ "public", "final", "void", "setLengthForTree", "(", "int", "length", ")", "{", "this", ".", "length", "=", "length", ";", "for", "(", "Node", "child", "=", "first", ";", "child", "!=", "null", ";", "child", "=", "child", ".", "next", ")", "{", "child", ".", "setLengthForTree", "(", "length", ")", ";", "}", "}" ]
Useful to set length of a transpiled node tree to map back to the length of original node.
[ "Useful", "to", "set", "length", "of", "a", "transpiled", "node", "tree", "to", "map", "back", "to", "the", "length", "of", "original", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L1527-L1533
24,646
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.getAncestor
@Nullable public final Node getAncestor(int level) { checkArgument(level >= 0); Node node = this; while (node != null && level-- > 0) { node = node.getParent(); } return node; }
java
@Nullable public final Node getAncestor(int level) { checkArgument(level >= 0); Node node = this; while (node != null && level-- > 0) { node = node.getParent(); } return node; }
[ "@", "Nullable", "public", "final", "Node", "getAncestor", "(", "int", "level", ")", "{", "checkArgument", "(", "level", ">=", "0", ")", ";", "Node", "node", "=", "this", ";", "while", "(", "node", "!=", "null", "&&", "level", "--", ">", "0", ")", "{", "node", "=", "node", ".", "getParent", "(", ")", ";", "}", "return", "node", ";", "}" ]
Gets the ancestor node relative to this. @param level 0 = this, 1 = the parent, etc.
[ "Gets", "the", "ancestor", "node", "relative", "to", "this", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L1733-L1741
24,647
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.hasXChildren
public final boolean hasXChildren(int x) { int c = 0; for (Node n = first; n != null && c <= x; n = n.next) { c++; } return c == x; }
java
public final boolean hasXChildren(int x) { int c = 0; for (Node n = first; n != null && c <= x; n = n.next) { c++; } return c == x; }
[ "public", "final", "boolean", "hasXChildren", "(", "int", "x", ")", "{", "int", "c", "=", "0", ";", "for", "(", "Node", "n", "=", "first", ";", "n", "!=", "null", "&&", "c", "<=", "x", ";", "n", "=", "n", ".", "next", ")", "{", "c", "++", ";", "}", "return", "c", "==", "x", ";", "}" ]
Check for has exactly the number of specified children. @return Whether the node has exactly the number of children specified.
[ "Check", "for", "has", "exactly", "the", "number", "of", "specified", "children", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L1857-L1863
24,648
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.hasChild
public final boolean hasChild(Node child) { for (Node n = first; n != null; n = n.next) { if (child == n) { return true; } } return false; }
java
public final boolean hasChild(Node child) { for (Node n = first; n != null; n = n.next) { if (child == n) { return true; } } return false; }
[ "public", "final", "boolean", "hasChild", "(", "Node", "child", ")", "{", "for", "(", "Node", "n", "=", "first", ";", "n", "!=", "null", ";", "n", "=", "n", ".", "next", ")", "{", "if", "(", "child", "==", "n", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Intended for testing and verification only.
[ "Intended", "for", "testing", "and", "verification", "only", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L1874-L1881
24,649
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.getQualifiedName
@Nullable public final String getQualifiedName() { switch (token) { case NAME: String name = getString(); return name.isEmpty() ? null : name; case GETPROP: StringBuilder builder = getQualifiedNameForGetProp(0); return builder != null ? builder.toString() : null; case THIS: return "this"; case SUPER: return "super"; default: return null; } }
java
@Nullable public final String getQualifiedName() { switch (token) { case NAME: String name = getString(); return name.isEmpty() ? null : name; case GETPROP: StringBuilder builder = getQualifiedNameForGetProp(0); return builder != null ? builder.toString() : null; case THIS: return "this"; case SUPER: return "super"; default: return null; } }
[ "@", "Nullable", "public", "final", "String", "getQualifiedName", "(", ")", "{", "switch", "(", "token", ")", "{", "case", "NAME", ":", "String", "name", "=", "getString", "(", ")", ";", "return", "name", ".", "isEmpty", "(", ")", "?", "null", ":", "name", ";", "case", "GETPROP", ":", "StringBuilder", "builder", "=", "getQualifiedNameForGetProp", "(", "0", ")", ";", "return", "builder", "!=", "null", "?", "builder", ".", "toString", "(", ")", ":", "null", ";", "case", "THIS", ":", "return", "\"this\"", ";", "case", "SUPER", ":", "return", "\"super\"", ";", "default", ":", "return", "null", ";", "}", "}" ]
This function takes a set of GETPROP nodes and produces a string that is each property separated by dots. If the node ultimately under the left sub-tree is not a simple name, this is not a valid qualified name. @return a null if this is not a qualified name, or a dot-separated string of the name and properties.
[ "This", "function", "takes", "a", "set", "of", "GETPROP", "nodes", "and", "produces", "a", "string", "that", "is", "each", "property", "separated", "by", "dots", ".", "If", "the", "node", "ultimately", "under", "the", "left", "sub", "-", "tree", "is", "not", "a", "simple", "name", "this", "is", "not", "a", "valid", "qualified", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L2022-L2038
24,650
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.getOriginalQualifiedName
@Nullable public final String getOriginalQualifiedName() { if (token == Token.NAME || getBooleanProp(Prop.IS_MODULE_NAME)) { String name = getOriginalName(); if (name == null) { name = getString(); } return name.isEmpty() ? null : name; } else if (token == Token.GETPROP) { String left = getFirstChild().getOriginalQualifiedName(); if (left == null) { return null; } String right = getLastChild().getOriginalName(); if (right == null) { right = getLastChild().getString(); } return left + "." + right; } else if (token == Token.THIS) { return "this"; } else if (token == Token.SUPER) { return "super"; } else { return null; } }
java
@Nullable public final String getOriginalQualifiedName() { if (token == Token.NAME || getBooleanProp(Prop.IS_MODULE_NAME)) { String name = getOriginalName(); if (name == null) { name = getString(); } return name.isEmpty() ? null : name; } else if (token == Token.GETPROP) { String left = getFirstChild().getOriginalQualifiedName(); if (left == null) { return null; } String right = getLastChild().getOriginalName(); if (right == null) { right = getLastChild().getString(); } return left + "." + right; } else if (token == Token.THIS) { return "this"; } else if (token == Token.SUPER) { return "super"; } else { return null; } }
[ "@", "Nullable", "public", "final", "String", "getOriginalQualifiedName", "(", ")", "{", "if", "(", "token", "==", "Token", ".", "NAME", "||", "getBooleanProp", "(", "Prop", ".", "IS_MODULE_NAME", ")", ")", "{", "String", "name", "=", "getOriginalName", "(", ")", ";", "if", "(", "name", "==", "null", ")", "{", "name", "=", "getString", "(", ")", ";", "}", "return", "name", ".", "isEmpty", "(", ")", "?", "null", ":", "name", ";", "}", "else", "if", "(", "token", "==", "Token", ".", "GETPROP", ")", "{", "String", "left", "=", "getFirstChild", "(", ")", ".", "getOriginalQualifiedName", "(", ")", ";", "if", "(", "left", "==", "null", ")", "{", "return", "null", ";", "}", "String", "right", "=", "getLastChild", "(", ")", ".", "getOriginalName", "(", ")", ";", "if", "(", "right", "==", "null", ")", "{", "right", "=", "getLastChild", "(", ")", ".", "getString", "(", ")", ";", "}", "return", "left", "+", "\".\"", "+", "right", ";", "}", "else", "if", "(", "token", "==", "Token", ".", "THIS", ")", "{", "return", "\"this\"", ";", "}", "else", "if", "(", "token", "==", "Token", ".", "SUPER", ")", "{", "return", "\"super\"", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
This function takes a set of GETPROP nodes and produces a string that is each property separated by dots. If the node ultimately under the left sub-tree is not a simple name, this is not a valid qualified name. This method returns the original name of each segment rather than the renamed version. @return a null if this is not a qualified name, or a dot-separated string of the name and properties.
[ "This", "function", "takes", "a", "set", "of", "GETPROP", "nodes", "and", "produces", "a", "string", "that", "is", "each", "property", "separated", "by", "dots", ".", "If", "the", "node", "ultimately", "under", "the", "left", "sub", "-", "tree", "is", "not", "a", "simple", "name", "this", "is", "not", "a", "valid", "qualified", "name", ".", "This", "method", "returns", "the", "original", "name", "of", "each", "segment", "rather", "than", "the", "renamed", "version", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L2083-L2109
24,651
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.detachChildren
public final void detachChildren() { for (Node child = first; child != null;) { Node nextChild = child.next; child.parent = null; child.next = null; child.previous = null; child = nextChild; } first = null; }
java
public final void detachChildren() { for (Node child = first; child != null;) { Node nextChild = child.next; child.parent = null; child.next = null; child.previous = null; child = nextChild; } first = null; }
[ "public", "final", "void", "detachChildren", "(", ")", "{", "for", "(", "Node", "child", "=", "first", ";", "child", "!=", "null", ";", ")", "{", "Node", "nextChild", "=", "child", ".", "next", ";", "child", ".", "parent", "=", "null", ";", "child", ".", "next", "=", "null", ";", "child", ".", "previous", "=", "null", ";", "child", "=", "nextChild", ";", "}", "first", "=", "null", ";", "}" ]
Removes all children from this node and isolates the children from each other.
[ "Removes", "all", "children", "from", "this", "node", "and", "isolates", "the", "children", "from", "each", "other", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L2277-L2286
24,652
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.setIsSyntheticBlock
public final void setIsSyntheticBlock(boolean val) { checkState(token == Token.BLOCK); putBooleanProp(Prop.SYNTHETIC, val); }
java
public final void setIsSyntheticBlock(boolean val) { checkState(token == Token.BLOCK); putBooleanProp(Prop.SYNTHETIC, val); }
[ "public", "final", "void", "setIsSyntheticBlock", "(", "boolean", "val", ")", "{", "checkState", "(", "token", "==", "Token", ".", "BLOCK", ")", ";", "putBooleanProp", "(", "Prop", ".", "SYNTHETIC", ",", "val", ")", ";", "}" ]
Sets whether this is a synthetic block that should not be considered a real source block.
[ "Sets", "whether", "this", "is", "a", "synthetic", "block", "that", "should", "not", "be", "considered", "a", "real", "source", "block", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L2575-L2578
24,653
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.getDirectives
@SuppressWarnings("unchecked") @Nullable public final Set<String> getDirectives() { return (Set<String>) getProp(Prop.DIRECTIVES); }
java
@SuppressWarnings("unchecked") @Nullable public final Set<String> getDirectives() { return (Set<String>) getProp(Prop.DIRECTIVES); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Nullable", "public", "final", "Set", "<", "String", ">", "getDirectives", "(", ")", "{", "return", "(", "Set", "<", "String", ">", ")", "getProp", "(", "Prop", ".", "DIRECTIVES", ")", ";", "}" ]
Returns the set of ES5 directives for this node.
[ "Returns", "the", "set", "of", "ES5", "directives", "for", "this", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L2596-L2600
24,654
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.writeEncodedInt
@GwtIncompatible("ObjectOutput") private void writeEncodedInt(ObjectOutput out, int value) throws IOException { while (value > 0X7f || value < 0) { out.writeByte(((value & 0X7f) | 0x80)); value >>>= 7; } out.writeByte(value); }
java
@GwtIncompatible("ObjectOutput") private void writeEncodedInt(ObjectOutput out, int value) throws IOException { while (value > 0X7f || value < 0) { out.writeByte(((value & 0X7f) | 0x80)); value >>>= 7; } out.writeByte(value); }
[ "@", "GwtIncompatible", "(", "\"ObjectOutput\"", ")", "private", "void", "writeEncodedInt", "(", "ObjectOutput", "out", ",", "int", "value", ")", "throws", "IOException", "{", "while", "(", "value", ">", "0X7f", "||", "value", "<", "0", ")", "{", "out", ".", "writeByte", "(", "(", "(", "value", "&", "0X7f", ")", "|", "0x80", ")", ")", ";", "value", ">>>=", "7", ";", "}", "out", ".", "writeByte", "(", "value", ")", ";", "}" ]
Encode integers using variable length encoding. Encodes an integer as a sequence of 7-bit values with a continuation bit. For example the number 3912 (0111 0100 1000) is encoded in two bytes as follows 0xC80E (1100 1000 0000 1110), i.e. first byte will be the lower 7 bits with a continuation bit set and second byte will consist of the upper 7 bits with the continuation bit unset. This encoding aims to reduce the serialized footprint for the most common values, reducing the footprint for all positive values that are smaller than 2^21 (~2000000): 0 - 127 are encoded in one byte 128 - 16384 are encoded in two bytes 16385 - 2097152 are encoded in three bytes 2097153 - 268435456 are encoded in four bytes. values greater than 268435456 and negative values are encoded in 5 bytes. Most values for the length field will be encoded with one byte and most values for sourcePosition will be encoded with 2 or 3 bytes. (Value -1, which is used to mark absence will use 5 bytes, and could be accommodated in the present scheme by an offset of 1 if it leads to size improvements).
[ "Encode", "integers", "using", "variable", "length", "encoding", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L3504-L3511
24,655
google/closure-compiler
src/com/google/javascript/jscomp/DartSuperAccessorsPass.java
DartSuperAccessorsPass.normalizeAssignmentOp
private static Node normalizeAssignmentOp(Node n) { Node lhs = n.getFirstChild(); Node rhs = n.getLastChild(); Node newRhs = new Node(NodeUtil.getOpFromAssignmentOp(n), lhs.cloneTree(), rhs.cloneTree()).srcrefTree(n); return replace(n, IR.assign(lhs.cloneTree(), newRhs).srcrefTree(n)); }
java
private static Node normalizeAssignmentOp(Node n) { Node lhs = n.getFirstChild(); Node rhs = n.getLastChild(); Node newRhs = new Node(NodeUtil.getOpFromAssignmentOp(n), lhs.cloneTree(), rhs.cloneTree()).srcrefTree(n); return replace(n, IR.assign(lhs.cloneTree(), newRhs).srcrefTree(n)); }
[ "private", "static", "Node", "normalizeAssignmentOp", "(", "Node", "n", ")", "{", "Node", "lhs", "=", "n", ".", "getFirstChild", "(", ")", ";", "Node", "rhs", "=", "n", ".", "getLastChild", "(", ")", ";", "Node", "newRhs", "=", "new", "Node", "(", "NodeUtil", ".", "getOpFromAssignmentOp", "(", "n", ")", ",", "lhs", ".", "cloneTree", "(", ")", ",", "rhs", ".", "cloneTree", "(", ")", ")", ".", "srcrefTree", "(", "n", ")", ";", "return", "replace", "(", "n", ",", "IR", ".", "assign", "(", "lhs", ".", "cloneTree", "(", ")", ",", "newRhs", ")", ".", "srcrefTree", "(", "n", ")", ")", ";", "}" ]
Transforms `a += b` to `a = a + b`.
[ "Transforms", "a", "+", "=", "b", "to", "a", "=", "a", "+", "b", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DartSuperAccessorsPass.java#L89-L95
24,656
google/closure-compiler
src/com/google/javascript/jscomp/DartSuperAccessorsPass.java
DartSuperAccessorsPass.renameProperty
private Node renameProperty(Node propertyName) { checkArgument(propertyName.isString()); if (!renameProperties) { return propertyName; } Node call = IR.call( IR.name(NodeUtil.JSC_PROPERTY_NAME_FN).srcref(propertyName), propertyName); call.srcref(propertyName); call.putBooleanProp(Node.FREE_CALL, true); call.putBooleanProp(Node.IS_CONSTANT_NAME, true); return call; }
java
private Node renameProperty(Node propertyName) { checkArgument(propertyName.isString()); if (!renameProperties) { return propertyName; } Node call = IR.call( IR.name(NodeUtil.JSC_PROPERTY_NAME_FN).srcref(propertyName), propertyName); call.srcref(propertyName); call.putBooleanProp(Node.FREE_CALL, true); call.putBooleanProp(Node.IS_CONSTANT_NAME, true); return call; }
[ "private", "Node", "renameProperty", "(", "Node", "propertyName", ")", "{", "checkArgument", "(", "propertyName", ".", "isString", "(", ")", ")", ";", "if", "(", "!", "renameProperties", ")", "{", "return", "propertyName", ";", "}", "Node", "call", "=", "IR", ".", "call", "(", "IR", ".", "name", "(", "NodeUtil", ".", "JSC_PROPERTY_NAME_FN", ")", ".", "srcref", "(", "propertyName", ")", ",", "propertyName", ")", ";", "call", ".", "srcref", "(", "propertyName", ")", ";", "call", ".", "putBooleanProp", "(", "Node", ".", "FREE_CALL", ",", "true", ")", ";", "call", ".", "putBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ",", "true", ")", ";", "return", "call", ";", "}" ]
Wraps a property string in a JSCompiler_renameProperty call. <p>Should only be called in phases running before {@link RenameProperties}, if such a pass is even used (see {@link #renameProperties}).
[ "Wraps", "a", "property", "string", "in", "a", "JSCompiler_renameProperty", "call", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DartSuperAccessorsPass.java#L174-L186
24,657
google/closure-compiler
src/com/google/javascript/jscomp/ProcessTweaks.java
ProcessTweaks.replaceGetCompilerOverridesCalls
private void replaceGetCompilerOverridesCalls( List<TweakFunctionCall> calls) { for (TweakFunctionCall call : calls) { Node callNode = call.callNode; Node objNode = createCompilerDefaultValueOverridesVarNode(callNode); callNode.replaceWith(objNode); compiler.reportChangeToEnclosingScope(objNode); } }
java
private void replaceGetCompilerOverridesCalls( List<TweakFunctionCall> calls) { for (TweakFunctionCall call : calls) { Node callNode = call.callNode; Node objNode = createCompilerDefaultValueOverridesVarNode(callNode); callNode.replaceWith(objNode); compiler.reportChangeToEnclosingScope(objNode); } }
[ "private", "void", "replaceGetCompilerOverridesCalls", "(", "List", "<", "TweakFunctionCall", ">", "calls", ")", "{", "for", "(", "TweakFunctionCall", "call", ":", "calls", ")", "{", "Node", "callNode", "=", "call", ".", "callNode", ";", "Node", "objNode", "=", "createCompilerDefaultValueOverridesVarNode", "(", "callNode", ")", ";", "callNode", ".", "replaceWith", "(", "objNode", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "objNode", ")", ";", "}", "}" ]
Passes the compiler default value overrides to the JS by replacing calls to goog.tweak.getCompilerOverrids_ with a map of tweak ID->default value;
[ "Passes", "the", "compiler", "default", "value", "overrides", "to", "the", "JS", "by", "replacing", "calls", "to", "goog", ".", "tweak", ".", "getCompilerOverrids_", "with", "a", "map", "of", "tweak", "ID", "-", ">", "default", "value", ";" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessTweaks.java#L222-L230
24,658
google/closure-compiler
src/com/google/javascript/jscomp/ProcessTweaks.java
ProcessTweaks.stripAllCalls
private void stripAllCalls(Map<String, TweakInfo> tweakInfos) { for (TweakInfo tweakInfo : tweakInfos.values()) { boolean isRegistered = tweakInfo.isRegistered(); for (TweakFunctionCall functionCall : tweakInfo.functionCalls) { Node callNode = functionCall.callNode; Node parent = callNode.getParent(); if (functionCall.tweakFunc.isGetterFunction()) { Node newValue; if (isRegistered) { newValue = tweakInfo.getDefaultValueNode().cloneNode(); } else { // When we find a getter of an unregistered tweak, there has // already been a warning about it, so now just use a default // value when stripping. TweakFunction registerFunction = functionCall.tweakFunc.registerFunction; newValue = registerFunction.createDefaultValueNode(); } parent.replaceChild(callNode, newValue); compiler.reportChangeToEnclosingScope(parent); } else { Node voidZeroNode = IR.voidNode(IR.number(0).srcref(callNode)) .srcref(callNode); parent.replaceChild(callNode, voidZeroNode); compiler.reportChangeToEnclosingScope(parent); } } } }
java
private void stripAllCalls(Map<String, TweakInfo> tweakInfos) { for (TweakInfo tweakInfo : tweakInfos.values()) { boolean isRegistered = tweakInfo.isRegistered(); for (TweakFunctionCall functionCall : tweakInfo.functionCalls) { Node callNode = functionCall.callNode; Node parent = callNode.getParent(); if (functionCall.tweakFunc.isGetterFunction()) { Node newValue; if (isRegistered) { newValue = tweakInfo.getDefaultValueNode().cloneNode(); } else { // When we find a getter of an unregistered tweak, there has // already been a warning about it, so now just use a default // value when stripping. TweakFunction registerFunction = functionCall.tweakFunc.registerFunction; newValue = registerFunction.createDefaultValueNode(); } parent.replaceChild(callNode, newValue); compiler.reportChangeToEnclosingScope(parent); } else { Node voidZeroNode = IR.voidNode(IR.number(0).srcref(callNode)) .srcref(callNode); parent.replaceChild(callNode, voidZeroNode); compiler.reportChangeToEnclosingScope(parent); } } } }
[ "private", "void", "stripAllCalls", "(", "Map", "<", "String", ",", "TweakInfo", ">", "tweakInfos", ")", "{", "for", "(", "TweakInfo", "tweakInfo", ":", "tweakInfos", ".", "values", "(", ")", ")", "{", "boolean", "isRegistered", "=", "tweakInfo", ".", "isRegistered", "(", ")", ";", "for", "(", "TweakFunctionCall", "functionCall", ":", "tweakInfo", ".", "functionCalls", ")", "{", "Node", "callNode", "=", "functionCall", ".", "callNode", ";", "Node", "parent", "=", "callNode", ".", "getParent", "(", ")", ";", "if", "(", "functionCall", ".", "tweakFunc", ".", "isGetterFunction", "(", ")", ")", "{", "Node", "newValue", ";", "if", "(", "isRegistered", ")", "{", "newValue", "=", "tweakInfo", ".", "getDefaultValueNode", "(", ")", ".", "cloneNode", "(", ")", ";", "}", "else", "{", "// When we find a getter of an unregistered tweak, there has", "// already been a warning about it, so now just use a default", "// value when stripping.", "TweakFunction", "registerFunction", "=", "functionCall", ".", "tweakFunc", ".", "registerFunction", ";", "newValue", "=", "registerFunction", ".", "createDefaultValueNode", "(", ")", ";", "}", "parent", ".", "replaceChild", "(", "callNode", ",", "newValue", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "parent", ")", ";", "}", "else", "{", "Node", "voidZeroNode", "=", "IR", ".", "voidNode", "(", "IR", ".", "number", "(", "0", ")", ".", "srcref", "(", "callNode", ")", ")", ".", "srcref", "(", "callNode", ")", ";", "parent", ".", "replaceChild", "(", "callNode", ",", "voidZeroNode", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "parent", ")", ";", "}", "}", "}", "}" ]
Removes all CALL nodes in the given TweakInfos, replacing calls to getter functions with the tweak's default value.
[ "Removes", "all", "CALL", "nodes", "in", "the", "given", "TweakInfos", "replacing", "calls", "to", "getter", "functions", "with", "the", "tweak", "s", "default", "value", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessTweaks.java#L236-L264
24,659
google/closure-compiler
src/com/google/javascript/jscomp/ProcessTweaks.java
ProcessTweaks.createCompilerDefaultValueOverridesVarNode
private Node createCompilerDefaultValueOverridesVarNode( Node sourceInformationNode) { Node objNode = IR.objectlit().srcref(sourceInformationNode); for (Entry<String, Node> entry : compilerDefaultValueOverrides.entrySet()) { Node objKeyNode = IR.stringKey(entry.getKey()) .useSourceInfoIfMissingFrom(sourceInformationNode); Node objValueNode = entry.getValue().cloneNode() .useSourceInfoIfMissingFrom(sourceInformationNode); objKeyNode.addChildToBack(objValueNode); objNode.addChildToBack(objKeyNode); } return objNode; }
java
private Node createCompilerDefaultValueOverridesVarNode( Node sourceInformationNode) { Node objNode = IR.objectlit().srcref(sourceInformationNode); for (Entry<String, Node> entry : compilerDefaultValueOverrides.entrySet()) { Node objKeyNode = IR.stringKey(entry.getKey()) .useSourceInfoIfMissingFrom(sourceInformationNode); Node objValueNode = entry.getValue().cloneNode() .useSourceInfoIfMissingFrom(sourceInformationNode); objKeyNode.addChildToBack(objValueNode); objNode.addChildToBack(objKeyNode); } return objNode; }
[ "private", "Node", "createCompilerDefaultValueOverridesVarNode", "(", "Node", "sourceInformationNode", ")", "{", "Node", "objNode", "=", "IR", ".", "objectlit", "(", ")", ".", "srcref", "(", "sourceInformationNode", ")", ";", "for", "(", "Entry", "<", "String", ",", "Node", ">", "entry", ":", "compilerDefaultValueOverrides", ".", "entrySet", "(", ")", ")", "{", "Node", "objKeyNode", "=", "IR", ".", "stringKey", "(", "entry", ".", "getKey", "(", ")", ")", ".", "useSourceInfoIfMissingFrom", "(", "sourceInformationNode", ")", ";", "Node", "objValueNode", "=", "entry", ".", "getValue", "(", ")", ".", "cloneNode", "(", ")", ".", "useSourceInfoIfMissingFrom", "(", "sourceInformationNode", ")", ";", "objKeyNode", ".", "addChildToBack", "(", "objValueNode", ")", ";", "objNode", ".", "addChildToBack", "(", "objKeyNode", ")", ";", "}", "return", "objNode", ";", "}" ]
Creates a JS object that holds a map of tweakId -> default value override.
[ "Creates", "a", "JS", "object", "that", "holds", "a", "map", "of", "tweakId", "-", ">", "default", "value", "override", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessTweaks.java#L269-L281
24,660
google/closure-compiler
src/com/google/javascript/jscomp/ProcessTweaks.java
ProcessTweaks.applyCompilerDefaultValueOverrides
private void applyCompilerDefaultValueOverrides( Map<String, TweakInfo> tweakInfos) { for (Entry<String, Node> entry : compilerDefaultValueOverrides.entrySet()) { String tweakId = entry.getKey(); TweakInfo tweakInfo = tweakInfos.get(tweakId); if (tweakInfo == null) { compiler.report(JSError.make(UNKNOWN_TWEAK_WARNING, tweakId)); } else { TweakFunction registerFunc = tweakInfo.registerCall.tweakFunc; Node value = entry.getValue(); if (!registerFunc.isValidNodeType(value.getToken())) { compiler.report(JSError.make(INVALID_TWEAK_DEFAULT_VALUE_WARNING, tweakId, registerFunc.getName(), registerFunc.getExpectedTypeName())); } else { tweakInfo.defaultValueNode = value; } } } }
java
private void applyCompilerDefaultValueOverrides( Map<String, TweakInfo> tweakInfos) { for (Entry<String, Node> entry : compilerDefaultValueOverrides.entrySet()) { String tweakId = entry.getKey(); TweakInfo tweakInfo = tweakInfos.get(tweakId); if (tweakInfo == null) { compiler.report(JSError.make(UNKNOWN_TWEAK_WARNING, tweakId)); } else { TweakFunction registerFunc = tweakInfo.registerCall.tweakFunc; Node value = entry.getValue(); if (!registerFunc.isValidNodeType(value.getToken())) { compiler.report(JSError.make(INVALID_TWEAK_DEFAULT_VALUE_WARNING, tweakId, registerFunc.getName(), registerFunc.getExpectedTypeName())); } else { tweakInfo.defaultValueNode = value; } } } }
[ "private", "void", "applyCompilerDefaultValueOverrides", "(", "Map", "<", "String", ",", "TweakInfo", ">", "tweakInfos", ")", "{", "for", "(", "Entry", "<", "String", ",", "Node", ">", "entry", ":", "compilerDefaultValueOverrides", ".", "entrySet", "(", ")", ")", "{", "String", "tweakId", "=", "entry", ".", "getKey", "(", ")", ";", "TweakInfo", "tweakInfo", "=", "tweakInfos", ".", "get", "(", "tweakId", ")", ";", "if", "(", "tweakInfo", "==", "null", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "UNKNOWN_TWEAK_WARNING", ",", "tweakId", ")", ")", ";", "}", "else", "{", "TweakFunction", "registerFunc", "=", "tweakInfo", ".", "registerCall", ".", "tweakFunc", ";", "Node", "value", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "!", "registerFunc", ".", "isValidNodeType", "(", "value", ".", "getToken", "(", ")", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "INVALID_TWEAK_DEFAULT_VALUE_WARNING", ",", "tweakId", ",", "registerFunc", ".", "getName", "(", ")", ",", "registerFunc", ".", "getExpectedTypeName", "(", ")", ")", ")", ";", "}", "else", "{", "tweakInfo", ".", "defaultValueNode", "=", "value", ";", "}", "}", "}", "}" ]
Sets the default values of tweaks based on compiler options.
[ "Sets", "the", "default", "values", "of", "tweaks", "based", "on", "compiler", "options", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessTweaks.java#L284-L303
24,661
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryFoldTry
private Node tryFoldTry(Node n) { checkState(n.isTry(), n); Node body = n.getFirstChild(); Node catchBlock = body.getNext(); Node finallyBlock = catchBlock.getNext(); // Removes TRYs that had its CATCH removed and/or empty FINALLY. if (!catchBlock.hasChildren() && (finallyBlock == null || !finallyBlock.hasChildren())) { n.removeChild(body); n.replaceWith(body); reportChangeToEnclosingScope(body); return body; } // Only leave FINALLYs if TRYs are empty if (!body.hasChildren()) { NodeUtil.redeclareVarsInsideBranch(catchBlock); reportChangeToEnclosingScope(n); if (finallyBlock != null) { n.removeChild(finallyBlock); n.replaceWith(finallyBlock); } else { n.detach(); } return finallyBlock; } return n; }
java
private Node tryFoldTry(Node n) { checkState(n.isTry(), n); Node body = n.getFirstChild(); Node catchBlock = body.getNext(); Node finallyBlock = catchBlock.getNext(); // Removes TRYs that had its CATCH removed and/or empty FINALLY. if (!catchBlock.hasChildren() && (finallyBlock == null || !finallyBlock.hasChildren())) { n.removeChild(body); n.replaceWith(body); reportChangeToEnclosingScope(body); return body; } // Only leave FINALLYs if TRYs are empty if (!body.hasChildren()) { NodeUtil.redeclareVarsInsideBranch(catchBlock); reportChangeToEnclosingScope(n); if (finallyBlock != null) { n.removeChild(finallyBlock); n.replaceWith(finallyBlock); } else { n.detach(); } return finallyBlock; } return n; }
[ "private", "Node", "tryFoldTry", "(", "Node", "n", ")", "{", "checkState", "(", "n", ".", "isTry", "(", ")", ",", "n", ")", ";", "Node", "body", "=", "n", ".", "getFirstChild", "(", ")", ";", "Node", "catchBlock", "=", "body", ".", "getNext", "(", ")", ";", "Node", "finallyBlock", "=", "catchBlock", ".", "getNext", "(", ")", ";", "// Removes TRYs that had its CATCH removed and/or empty FINALLY.", "if", "(", "!", "catchBlock", ".", "hasChildren", "(", ")", "&&", "(", "finallyBlock", "==", "null", "||", "!", "finallyBlock", ".", "hasChildren", "(", ")", ")", ")", "{", "n", ".", "removeChild", "(", "body", ")", ";", "n", ".", "replaceWith", "(", "body", ")", ";", "reportChangeToEnclosingScope", "(", "body", ")", ";", "return", "body", ";", "}", "// Only leave FINALLYs if TRYs are empty", "if", "(", "!", "body", ".", "hasChildren", "(", ")", ")", "{", "NodeUtil", ".", "redeclareVarsInsideBranch", "(", "catchBlock", ")", ";", "reportChangeToEnclosingScope", "(", "n", ")", ";", "if", "(", "finallyBlock", "!=", "null", ")", "{", "n", ".", "removeChild", "(", "finallyBlock", ")", ";", "n", ".", "replaceWith", "(", "finallyBlock", ")", ";", "}", "else", "{", "n", ".", "detach", "(", ")", ";", "}", "return", "finallyBlock", ";", "}", "return", "n", ";", "}" ]
Remove try blocks without catch blocks and with empty or not existent finally blocks. Or, only leave the finally blocks if try body blocks are empty @return the replacement node, if changed, or the original if not
[ "Remove", "try", "blocks", "without", "catch", "blocks", "and", "with", "empty", "or", "not", "existent", "finally", "blocks", ".", "Or", "only", "leave", "the", "finally", "blocks", "if", "try", "body", "blocks", "are", "empty" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L181-L209
24,662
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryFoldExpr
private Node tryFoldExpr(Node subtree) { Node result = trySimplifyUnusedResult(subtree.getFirstChild()); if (result == null) { Node parent = subtree.getParent(); // If the EXPR_RESULT no longer has any children, remove it as well. if (parent.isLabel()) { Node replacement = IR.block().srcref(subtree); parent.replaceChild(subtree, replacement); subtree = replacement; } else { subtree.detach(); subtree = null; } } return subtree; }
java
private Node tryFoldExpr(Node subtree) { Node result = trySimplifyUnusedResult(subtree.getFirstChild()); if (result == null) { Node parent = subtree.getParent(); // If the EXPR_RESULT no longer has any children, remove it as well. if (parent.isLabel()) { Node replacement = IR.block().srcref(subtree); parent.replaceChild(subtree, replacement); subtree = replacement; } else { subtree.detach(); subtree = null; } } return subtree; }
[ "private", "Node", "tryFoldExpr", "(", "Node", "subtree", ")", "{", "Node", "result", "=", "trySimplifyUnusedResult", "(", "subtree", ".", "getFirstChild", "(", ")", ")", ";", "if", "(", "result", "==", "null", ")", "{", "Node", "parent", "=", "subtree", ".", "getParent", "(", ")", ";", "// If the EXPR_RESULT no longer has any children, remove it as well.", "if", "(", "parent", ".", "isLabel", "(", ")", ")", "{", "Node", "replacement", "=", "IR", ".", "block", "(", ")", ".", "srcref", "(", "subtree", ")", ";", "parent", ".", "replaceChild", "(", "subtree", ",", "replacement", ")", ";", "subtree", "=", "replacement", ";", "}", "else", "{", "subtree", ".", "detach", "(", ")", ";", "subtree", "=", "null", ";", "}", "}", "return", "subtree", ";", "}" ]
Try folding EXPR_RESULT nodes by removing useless Ops and expressions. @return the replacement node, if changed, or the original if not
[ "Try", "folding", "EXPR_RESULT", "nodes", "by", "removing", "useless", "Ops", "and", "expressions", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L262-L277
24,663
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryOptimizeSwitch
private Node tryOptimizeSwitch(Node n) { checkState(n.isSwitch(), n); Node defaultCase = tryOptimizeDefaultCase(n); // Generally, it is unsafe to remove other cases when the default case is not the last one. if (defaultCase == null || n.getLastChild().isDefaultCase()) { Node cond = n.getFirstChild(); Node prev = null; Node next = null; Node cur; for (cur = cond.getNext(); cur != null; cur = next) { next = cur.getNext(); if (!mayHaveSideEffects(cur.getFirstChild()) && isUselessCase(cur, prev, defaultCase)) { removeCase(n, cur); } else { prev = cur; } } // Optimize switches with constant condition if (NodeUtil.isLiteralValue(cond, false)) { Node caseLabel; TernaryValue caseMatches = TernaryValue.TRUE; // Remove cases until you find one that may match for (cur = cond.getNext(); cur != null; cur = next) { next = cur.getNext(); caseLabel = cur.getFirstChild(); caseMatches = PeepholeFoldConstants.evaluateComparison(this, Token.SHEQ, cond, caseLabel); if (caseMatches == TernaryValue.TRUE) { break; } else if (caseMatches == TernaryValue.UNKNOWN) { break; } else { removeCase(n, cur); } } if (cur != null && caseMatches == TernaryValue.TRUE) { // Skip cases until you find one whose last stm is a removable break Node matchingCase = cur; Node matchingCaseBlock = matchingCase.getLastChild(); while (cur != null) { Node block = cur.getLastChild(); Node lastStm = block.getLastChild(); boolean isLastStmRemovableBreak = false; if (lastStm != null && isExit(lastStm)) { removeIfUnnamedBreak(lastStm); isLastStmRemovableBreak = true; } next = cur.getNext(); // Remove the fallthrough case labels if (cur != matchingCase) { while (block.hasChildren()) { matchingCaseBlock.addChildToBack(block.getFirstChild().detach()); } reportChangeToEnclosingScope(cur); cur.detach(); } cur = next; if (isLastStmRemovableBreak) { break; } } // Remove any remaining cases for (; cur != null; cur = next) { next = cur.getNext(); removeCase(n, cur); } // If there is one case left, we may be able to fold it cur = cond.getNext(); if (cur != null && cur.getNext() == null) { return tryRemoveSwitchWithSingleCase(n, false); } } } } return tryRemoveSwitch(n); }
java
private Node tryOptimizeSwitch(Node n) { checkState(n.isSwitch(), n); Node defaultCase = tryOptimizeDefaultCase(n); // Generally, it is unsafe to remove other cases when the default case is not the last one. if (defaultCase == null || n.getLastChild().isDefaultCase()) { Node cond = n.getFirstChild(); Node prev = null; Node next = null; Node cur; for (cur = cond.getNext(); cur != null; cur = next) { next = cur.getNext(); if (!mayHaveSideEffects(cur.getFirstChild()) && isUselessCase(cur, prev, defaultCase)) { removeCase(n, cur); } else { prev = cur; } } // Optimize switches with constant condition if (NodeUtil.isLiteralValue(cond, false)) { Node caseLabel; TernaryValue caseMatches = TernaryValue.TRUE; // Remove cases until you find one that may match for (cur = cond.getNext(); cur != null; cur = next) { next = cur.getNext(); caseLabel = cur.getFirstChild(); caseMatches = PeepholeFoldConstants.evaluateComparison(this, Token.SHEQ, cond, caseLabel); if (caseMatches == TernaryValue.TRUE) { break; } else if (caseMatches == TernaryValue.UNKNOWN) { break; } else { removeCase(n, cur); } } if (cur != null && caseMatches == TernaryValue.TRUE) { // Skip cases until you find one whose last stm is a removable break Node matchingCase = cur; Node matchingCaseBlock = matchingCase.getLastChild(); while (cur != null) { Node block = cur.getLastChild(); Node lastStm = block.getLastChild(); boolean isLastStmRemovableBreak = false; if (lastStm != null && isExit(lastStm)) { removeIfUnnamedBreak(lastStm); isLastStmRemovableBreak = true; } next = cur.getNext(); // Remove the fallthrough case labels if (cur != matchingCase) { while (block.hasChildren()) { matchingCaseBlock.addChildToBack(block.getFirstChild().detach()); } reportChangeToEnclosingScope(cur); cur.detach(); } cur = next; if (isLastStmRemovableBreak) { break; } } // Remove any remaining cases for (; cur != null; cur = next) { next = cur.getNext(); removeCase(n, cur); } // If there is one case left, we may be able to fold it cur = cond.getNext(); if (cur != null && cur.getNext() == null) { return tryRemoveSwitchWithSingleCase(n, false); } } } } return tryRemoveSwitch(n); }
[ "private", "Node", "tryOptimizeSwitch", "(", "Node", "n", ")", "{", "checkState", "(", "n", ".", "isSwitch", "(", ")", ",", "n", ")", ";", "Node", "defaultCase", "=", "tryOptimizeDefaultCase", "(", "n", ")", ";", "// Generally, it is unsafe to remove other cases when the default case is not the last one.", "if", "(", "defaultCase", "==", "null", "||", "n", ".", "getLastChild", "(", ")", ".", "isDefaultCase", "(", ")", ")", "{", "Node", "cond", "=", "n", ".", "getFirstChild", "(", ")", ";", "Node", "prev", "=", "null", ";", "Node", "next", "=", "null", ";", "Node", "cur", ";", "for", "(", "cur", "=", "cond", ".", "getNext", "(", ")", ";", "cur", "!=", "null", ";", "cur", "=", "next", ")", "{", "next", "=", "cur", ".", "getNext", "(", ")", ";", "if", "(", "!", "mayHaveSideEffects", "(", "cur", ".", "getFirstChild", "(", ")", ")", "&&", "isUselessCase", "(", "cur", ",", "prev", ",", "defaultCase", ")", ")", "{", "removeCase", "(", "n", ",", "cur", ")", ";", "}", "else", "{", "prev", "=", "cur", ";", "}", "}", "// Optimize switches with constant condition", "if", "(", "NodeUtil", ".", "isLiteralValue", "(", "cond", ",", "false", ")", ")", "{", "Node", "caseLabel", ";", "TernaryValue", "caseMatches", "=", "TernaryValue", ".", "TRUE", ";", "// Remove cases until you find one that may match", "for", "(", "cur", "=", "cond", ".", "getNext", "(", ")", ";", "cur", "!=", "null", ";", "cur", "=", "next", ")", "{", "next", "=", "cur", ".", "getNext", "(", ")", ";", "caseLabel", "=", "cur", ".", "getFirstChild", "(", ")", ";", "caseMatches", "=", "PeepholeFoldConstants", ".", "evaluateComparison", "(", "this", ",", "Token", ".", "SHEQ", ",", "cond", ",", "caseLabel", ")", ";", "if", "(", "caseMatches", "==", "TernaryValue", ".", "TRUE", ")", "{", "break", ";", "}", "else", "if", "(", "caseMatches", "==", "TernaryValue", ".", "UNKNOWN", ")", "{", "break", ";", "}", "else", "{", "removeCase", "(", "n", ",", "cur", ")", ";", "}", "}", "if", "(", "cur", "!=", "null", "&&", "caseMatches", "==", "TernaryValue", ".", "TRUE", ")", "{", "// Skip cases until you find one whose last stm is a removable break", "Node", "matchingCase", "=", "cur", ";", "Node", "matchingCaseBlock", "=", "matchingCase", ".", "getLastChild", "(", ")", ";", "while", "(", "cur", "!=", "null", ")", "{", "Node", "block", "=", "cur", ".", "getLastChild", "(", ")", ";", "Node", "lastStm", "=", "block", ".", "getLastChild", "(", ")", ";", "boolean", "isLastStmRemovableBreak", "=", "false", ";", "if", "(", "lastStm", "!=", "null", "&&", "isExit", "(", "lastStm", ")", ")", "{", "removeIfUnnamedBreak", "(", "lastStm", ")", ";", "isLastStmRemovableBreak", "=", "true", ";", "}", "next", "=", "cur", ".", "getNext", "(", ")", ";", "// Remove the fallthrough case labels", "if", "(", "cur", "!=", "matchingCase", ")", "{", "while", "(", "block", ".", "hasChildren", "(", ")", ")", "{", "matchingCaseBlock", ".", "addChildToBack", "(", "block", ".", "getFirstChild", "(", ")", ".", "detach", "(", ")", ")", ";", "}", "reportChangeToEnclosingScope", "(", "cur", ")", ";", "cur", ".", "detach", "(", ")", ";", "}", "cur", "=", "next", ";", "if", "(", "isLastStmRemovableBreak", ")", "{", "break", ";", "}", "}", "// Remove any remaining cases", "for", "(", ";", "cur", "!=", "null", ";", "cur", "=", "next", ")", "{", "next", "=", "cur", ".", "getNext", "(", ")", ";", "removeCase", "(", "n", ",", "cur", ")", ";", "}", "// If there is one case left, we may be able to fold it", "cur", "=", "cond", ".", "getNext", "(", ")", ";", "if", "(", "cur", "!=", "null", "&&", "cur", ".", "getNext", "(", ")", "==", "null", ")", "{", "return", "tryRemoveSwitchWithSingleCase", "(", "n", ",", "false", ")", ";", "}", "}", "}", "}", "return", "tryRemoveSwitch", "(", "n", ")", ";", "}" ]
Remove useless switches and cases.
[ "Remove", "useless", "switches", "and", "cases", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L525-L605
24,664
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.removeCase
private void removeCase(Node switchNode, Node caseNode) { NodeUtil.redeclareVarsInsideBranch(caseNode); switchNode.removeChild(caseNode); reportChangeToEnclosingScope(switchNode); }
java
private void removeCase(Node switchNode, Node caseNode) { NodeUtil.redeclareVarsInsideBranch(caseNode); switchNode.removeChild(caseNode); reportChangeToEnclosingScope(switchNode); }
[ "private", "void", "removeCase", "(", "Node", "switchNode", ",", "Node", "caseNode", ")", "{", "NodeUtil", ".", "redeclareVarsInsideBranch", "(", "caseNode", ")", ";", "switchNode", ".", "removeChild", "(", "caseNode", ")", ";", "reportChangeToEnclosingScope", "(", "switchNode", ")", ";", "}" ]
Remove the case from the switch redeclaring any variables declared in it. @param caseNode The case to remove.
[ "Remove", "the", "case", "from", "the", "switch", "redeclaring", "any", "variables", "declared", "in", "it", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L651-L655
24,665
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryOptimizeBlock
Node tryOptimizeBlock(Node n) { // Remove any useless children for (Node c = n.getFirstChild(); c != null; ) { Node next = c.getNext(); // save c.next, since 'c' may be removed if (!isUnremovableNode(c) && !mayHaveSideEffects(c)) { checkNormalization(!NodeUtil.isFunctionDeclaration(n), "function declaration"); // TODO(johnlenz): determine what this is actually removing. Candidates // include: EMPTY nodes, control structures without children // (removing infinite loops), empty try blocks. What else? n.removeChild(c); reportChangeToEnclosingScope(n); markFunctionsDeleted(c); } else { tryOptimizeConditionalAfterAssign(c); } c = next; } if (n.isSyntheticBlock() || n.isScript() || n.getParent() == null) { return n; } // Try to remove the block. Node parent = n.getParent(); if (NodeUtil.tryMergeBlock(n, false)) { reportChangeToEnclosingScope(parent); return null; } return n; }
java
Node tryOptimizeBlock(Node n) { // Remove any useless children for (Node c = n.getFirstChild(); c != null; ) { Node next = c.getNext(); // save c.next, since 'c' may be removed if (!isUnremovableNode(c) && !mayHaveSideEffects(c)) { checkNormalization(!NodeUtil.isFunctionDeclaration(n), "function declaration"); // TODO(johnlenz): determine what this is actually removing. Candidates // include: EMPTY nodes, control structures without children // (removing infinite loops), empty try blocks. What else? n.removeChild(c); reportChangeToEnclosingScope(n); markFunctionsDeleted(c); } else { tryOptimizeConditionalAfterAssign(c); } c = next; } if (n.isSyntheticBlock() || n.isScript() || n.getParent() == null) { return n; } // Try to remove the block. Node parent = n.getParent(); if (NodeUtil.tryMergeBlock(n, false)) { reportChangeToEnclosingScope(parent); return null; } return n; }
[ "Node", "tryOptimizeBlock", "(", "Node", "n", ")", "{", "// Remove any useless children", "for", "(", "Node", "c", "=", "n", ".", "getFirstChild", "(", ")", ";", "c", "!=", "null", ";", ")", "{", "Node", "next", "=", "c", ".", "getNext", "(", ")", ";", "// save c.next, since 'c' may be removed", "if", "(", "!", "isUnremovableNode", "(", "c", ")", "&&", "!", "mayHaveSideEffects", "(", "c", ")", ")", "{", "checkNormalization", "(", "!", "NodeUtil", ".", "isFunctionDeclaration", "(", "n", ")", ",", "\"function declaration\"", ")", ";", "// TODO(johnlenz): determine what this is actually removing. Candidates", "// include: EMPTY nodes, control structures without children", "// (removing infinite loops), empty try blocks. What else?", "n", ".", "removeChild", "(", "c", ")", ";", "reportChangeToEnclosingScope", "(", "n", ")", ";", "markFunctionsDeleted", "(", "c", ")", ";", "}", "else", "{", "tryOptimizeConditionalAfterAssign", "(", "c", ")", ";", "}", "c", "=", "next", ";", "}", "if", "(", "n", ".", "isSyntheticBlock", "(", ")", "||", "n", ".", "isScript", "(", ")", "||", "n", ".", "getParent", "(", ")", "==", "null", ")", "{", "return", "n", ";", "}", "// Try to remove the block.", "Node", "parent", "=", "n", ".", "getParent", "(", ")", ";", "if", "(", "NodeUtil", ".", "tryMergeBlock", "(", "n", ",", "false", ")", ")", "{", "reportChangeToEnclosingScope", "(", "parent", ")", ";", "return", "null", ";", "}", "return", "n", ";", "}" ]
Try removing unneeded block nodes and their useless children
[ "Try", "removing", "unneeded", "block", "nodes", "and", "their", "useless", "children" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L753-L783
24,666
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryOptimizeConditionalAfterAssign
private void tryOptimizeConditionalAfterAssign(Node n) { Node next = n.getNext(); // Look for patterns like the following and replace the if-condition with // a constant value so it can later be folded: // var a = /a/; // if (a) {foo(a)} // or // a = 0; // a ? foo(a) : c; // or // a = 0; // a || foo(a); // or // a = 0; // a && foo(a) // // TODO(johnlenz): This would be better handled by control-flow sensitive // constant propagation. As the other case that I want to handle is: // i=0; for(;i<0;i++){} // as right now nothing facilitates removing a loop like that. // This is here simply to remove the cruft left behind goog.userAgent and // similar cases. if (isSimpleAssignment(n) && isConditionalStatement(next)) { Node lhsAssign = getSimpleAssignmentName(n); Node condition = getConditionalStatementCondition(next); if (lhsAssign.isName() && condition.isName() && lhsAssign.getString().equals(condition.getString())) { Node rhsAssign = getSimpleAssignmentValue(n); TernaryValue value = NodeUtil.getImpureBooleanValue(rhsAssign); if (value != TernaryValue.UNKNOWN) { Node replacementConditionNode = NodeUtil.booleanNode(value.toBoolean(true)); condition.replaceWith(replacementConditionNode); reportChangeToEnclosingScope(replacementConditionNode); } } } }
java
private void tryOptimizeConditionalAfterAssign(Node n) { Node next = n.getNext(); // Look for patterns like the following and replace the if-condition with // a constant value so it can later be folded: // var a = /a/; // if (a) {foo(a)} // or // a = 0; // a ? foo(a) : c; // or // a = 0; // a || foo(a); // or // a = 0; // a && foo(a) // // TODO(johnlenz): This would be better handled by control-flow sensitive // constant propagation. As the other case that I want to handle is: // i=0; for(;i<0;i++){} // as right now nothing facilitates removing a loop like that. // This is here simply to remove the cruft left behind goog.userAgent and // similar cases. if (isSimpleAssignment(n) && isConditionalStatement(next)) { Node lhsAssign = getSimpleAssignmentName(n); Node condition = getConditionalStatementCondition(next); if (lhsAssign.isName() && condition.isName() && lhsAssign.getString().equals(condition.getString())) { Node rhsAssign = getSimpleAssignmentValue(n); TernaryValue value = NodeUtil.getImpureBooleanValue(rhsAssign); if (value != TernaryValue.UNKNOWN) { Node replacementConditionNode = NodeUtil.booleanNode(value.toBoolean(true)); condition.replaceWith(replacementConditionNode); reportChangeToEnclosingScope(replacementConditionNode); } } } }
[ "private", "void", "tryOptimizeConditionalAfterAssign", "(", "Node", "n", ")", "{", "Node", "next", "=", "n", ".", "getNext", "(", ")", ";", "// Look for patterns like the following and replace the if-condition with", "// a constant value so it can later be folded:", "// var a = /a/;", "// if (a) {foo(a)}", "// or", "// a = 0;", "// a ? foo(a) : c;", "// or", "// a = 0;", "// a || foo(a);", "// or", "// a = 0;", "// a && foo(a)", "//", "// TODO(johnlenz): This would be better handled by control-flow sensitive", "// constant propagation. As the other case that I want to handle is:", "// i=0; for(;i<0;i++){}", "// as right now nothing facilitates removing a loop like that.", "// This is here simply to remove the cruft left behind goog.userAgent and", "// similar cases.", "if", "(", "isSimpleAssignment", "(", "n", ")", "&&", "isConditionalStatement", "(", "next", ")", ")", "{", "Node", "lhsAssign", "=", "getSimpleAssignmentName", "(", "n", ")", ";", "Node", "condition", "=", "getConditionalStatementCondition", "(", "next", ")", ";", "if", "(", "lhsAssign", ".", "isName", "(", ")", "&&", "condition", ".", "isName", "(", ")", "&&", "lhsAssign", ".", "getString", "(", ")", ".", "equals", "(", "condition", ".", "getString", "(", ")", ")", ")", "{", "Node", "rhsAssign", "=", "getSimpleAssignmentValue", "(", "n", ")", ";", "TernaryValue", "value", "=", "NodeUtil", ".", "getImpureBooleanValue", "(", "rhsAssign", ")", ";", "if", "(", "value", "!=", "TernaryValue", ".", "UNKNOWN", ")", "{", "Node", "replacementConditionNode", "=", "NodeUtil", ".", "booleanNode", "(", "value", ".", "toBoolean", "(", "true", ")", ")", ";", "condition", ".", "replaceWith", "(", "replacementConditionNode", ")", ";", "reportChangeToEnclosingScope", "(", "replacementConditionNode", ")", ";", "}", "}", "}", "}" ]
Attempt to replace the condition of if or hook immediately that is a reference to a name that is assigned immediately before.
[ "Attempt", "to", "replace", "the", "condition", "of", "if", "or", "hook", "immediately", "that", "is", "a", "reference", "to", "a", "name", "that", "is", "assigned", "immediately", "before", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L798-L838
24,667
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryFoldWhile
Node tryFoldWhile(Node n) { checkArgument(n.isWhile()); Node cond = NodeUtil.getConditionExpression(n); if (NodeUtil.getPureBooleanValue(cond) != TernaryValue.FALSE) { return n; } NodeUtil.redeclareVarsInsideBranch(n); reportChangeToEnclosingScope(n.getParent()); NodeUtil.removeChild(n.getParent(), n); return null; }
java
Node tryFoldWhile(Node n) { checkArgument(n.isWhile()); Node cond = NodeUtil.getConditionExpression(n); if (NodeUtil.getPureBooleanValue(cond) != TernaryValue.FALSE) { return n; } NodeUtil.redeclareVarsInsideBranch(n); reportChangeToEnclosingScope(n.getParent()); NodeUtil.removeChild(n.getParent(), n); return null; }
[ "Node", "tryFoldWhile", "(", "Node", "n", ")", "{", "checkArgument", "(", "n", ".", "isWhile", "(", ")", ")", ";", "Node", "cond", "=", "NodeUtil", ".", "getConditionExpression", "(", "n", ")", ";", "if", "(", "NodeUtil", ".", "getPureBooleanValue", "(", "cond", ")", "!=", "TernaryValue", ".", "FALSE", ")", "{", "return", "n", ";", "}", "NodeUtil", ".", "redeclareVarsInsideBranch", "(", "n", ")", ";", "reportChangeToEnclosingScope", "(", "n", ".", "getParent", "(", ")", ")", ";", "NodeUtil", ".", "removeChild", "(", "n", ".", "getParent", "(", ")", ",", "n", ")", ";", "return", "null", ";", "}" ]
Removes WHILEs that always evaluate to false.
[ "Removes", "WHILEs", "that", "always", "evaluate", "to", "false", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L1076-L1087
24,668
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryFoldFor
Node tryFoldFor(Node n) { checkArgument(n.isVanillaFor()); Node init = n.getFirstChild(); Node cond = init.getNext(); Node increment = cond.getNext(); if (!init.isEmpty() && !NodeUtil.isNameDeclaration(init)) { init = trySimplifyUnusedResult(init); if (init == null) { init = IR.empty().srcref(n); n.addChildToFront(init); } } if (!increment.isEmpty()) { increment = trySimplifyUnusedResult(increment); if (increment == null) { increment = IR.empty().srcref(n); n.addChildAfter(increment, cond); } } // There is an initializer skip it if (!n.getFirstChild().isEmpty()) { return n; } if (NodeUtil.getImpureBooleanValue(cond) != TernaryValue.FALSE) { return n; } Node parent = n.getParent(); NodeUtil.redeclareVarsInsideBranch(n); if (!mayHaveSideEffects(cond)) { NodeUtil.removeChild(parent, n); } else { Node statement = IR.exprResult(cond.detach()) .useSourceInfoIfMissingFrom(cond); if (parent.isLabel()) { Node block = IR.block(); block.useSourceInfoIfMissingFrom(statement); block.addChildToFront(statement); statement = block; } parent.replaceChild(n, statement); } reportChangeToEnclosingScope(parent); return null; }
java
Node tryFoldFor(Node n) { checkArgument(n.isVanillaFor()); Node init = n.getFirstChild(); Node cond = init.getNext(); Node increment = cond.getNext(); if (!init.isEmpty() && !NodeUtil.isNameDeclaration(init)) { init = trySimplifyUnusedResult(init); if (init == null) { init = IR.empty().srcref(n); n.addChildToFront(init); } } if (!increment.isEmpty()) { increment = trySimplifyUnusedResult(increment); if (increment == null) { increment = IR.empty().srcref(n); n.addChildAfter(increment, cond); } } // There is an initializer skip it if (!n.getFirstChild().isEmpty()) { return n; } if (NodeUtil.getImpureBooleanValue(cond) != TernaryValue.FALSE) { return n; } Node parent = n.getParent(); NodeUtil.redeclareVarsInsideBranch(n); if (!mayHaveSideEffects(cond)) { NodeUtil.removeChild(parent, n); } else { Node statement = IR.exprResult(cond.detach()) .useSourceInfoIfMissingFrom(cond); if (parent.isLabel()) { Node block = IR.block(); block.useSourceInfoIfMissingFrom(statement); block.addChildToFront(statement); statement = block; } parent.replaceChild(n, statement); } reportChangeToEnclosingScope(parent); return null; }
[ "Node", "tryFoldFor", "(", "Node", "n", ")", "{", "checkArgument", "(", "n", ".", "isVanillaFor", "(", ")", ")", ";", "Node", "init", "=", "n", ".", "getFirstChild", "(", ")", ";", "Node", "cond", "=", "init", ".", "getNext", "(", ")", ";", "Node", "increment", "=", "cond", ".", "getNext", "(", ")", ";", "if", "(", "!", "init", ".", "isEmpty", "(", ")", "&&", "!", "NodeUtil", ".", "isNameDeclaration", "(", "init", ")", ")", "{", "init", "=", "trySimplifyUnusedResult", "(", "init", ")", ";", "if", "(", "init", "==", "null", ")", "{", "init", "=", "IR", ".", "empty", "(", ")", ".", "srcref", "(", "n", ")", ";", "n", ".", "addChildToFront", "(", "init", ")", ";", "}", "}", "if", "(", "!", "increment", ".", "isEmpty", "(", ")", ")", "{", "increment", "=", "trySimplifyUnusedResult", "(", "increment", ")", ";", "if", "(", "increment", "==", "null", ")", "{", "increment", "=", "IR", ".", "empty", "(", ")", ".", "srcref", "(", "n", ")", ";", "n", ".", "addChildAfter", "(", "increment", ",", "cond", ")", ";", "}", "}", "// There is an initializer skip it", "if", "(", "!", "n", ".", "getFirstChild", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "n", ";", "}", "if", "(", "NodeUtil", ".", "getImpureBooleanValue", "(", "cond", ")", "!=", "TernaryValue", ".", "FALSE", ")", "{", "return", "n", ";", "}", "Node", "parent", "=", "n", ".", "getParent", "(", ")", ";", "NodeUtil", ".", "redeclareVarsInsideBranch", "(", "n", ")", ";", "if", "(", "!", "mayHaveSideEffects", "(", "cond", ")", ")", "{", "NodeUtil", ".", "removeChild", "(", "parent", ",", "n", ")", ";", "}", "else", "{", "Node", "statement", "=", "IR", ".", "exprResult", "(", "cond", ".", "detach", "(", ")", ")", ".", "useSourceInfoIfMissingFrom", "(", "cond", ")", ";", "if", "(", "parent", ".", "isLabel", "(", ")", ")", "{", "Node", "block", "=", "IR", ".", "block", "(", ")", ";", "block", ".", "useSourceInfoIfMissingFrom", "(", "statement", ")", ";", "block", ".", "addChildToFront", "(", "statement", ")", ";", "statement", "=", "block", ";", "}", "parent", ".", "replaceChild", "(", "n", ",", "statement", ")", ";", "}", "reportChangeToEnclosingScope", "(", "parent", ")", ";", "return", "null", ";", "}" ]
Removes FORs that always evaluate to false.
[ "Removes", "FORs", "that", "always", "evaluate", "to", "false", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L1092-L1141
24,669
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryFoldDoAway
Node tryFoldDoAway(Node n) { checkArgument(n.isDo()); Node cond = NodeUtil.getConditionExpression(n); if (NodeUtil.getImpureBooleanValue(cond) != TernaryValue.FALSE) { return n; } Node block = NodeUtil.getLoopCodeBlock(n); if (n.getParent().isLabel() || hasUnnamedBreakOrContinue(block)) { return n; } Node parent = n.getParent(); n.replaceWith(block.detach()); if (mayHaveSideEffects(cond)) { Node condStatement = IR.exprResult(cond.detach()).srcref(cond); parent.addChildAfter(condStatement, block); } reportChangeToEnclosingScope(parent); return block; }
java
Node tryFoldDoAway(Node n) { checkArgument(n.isDo()); Node cond = NodeUtil.getConditionExpression(n); if (NodeUtil.getImpureBooleanValue(cond) != TernaryValue.FALSE) { return n; } Node block = NodeUtil.getLoopCodeBlock(n); if (n.getParent().isLabel() || hasUnnamedBreakOrContinue(block)) { return n; } Node parent = n.getParent(); n.replaceWith(block.detach()); if (mayHaveSideEffects(cond)) { Node condStatement = IR.exprResult(cond.detach()).srcref(cond); parent.addChildAfter(condStatement, block); } reportChangeToEnclosingScope(parent); return block; }
[ "Node", "tryFoldDoAway", "(", "Node", "n", ")", "{", "checkArgument", "(", "n", ".", "isDo", "(", ")", ")", ";", "Node", "cond", "=", "NodeUtil", ".", "getConditionExpression", "(", "n", ")", ";", "if", "(", "NodeUtil", ".", "getImpureBooleanValue", "(", "cond", ")", "!=", "TernaryValue", ".", "FALSE", ")", "{", "return", "n", ";", "}", "Node", "block", "=", "NodeUtil", ".", "getLoopCodeBlock", "(", "n", ")", ";", "if", "(", "n", ".", "getParent", "(", ")", ".", "isLabel", "(", ")", "||", "hasUnnamedBreakOrContinue", "(", "block", ")", ")", "{", "return", "n", ";", "}", "Node", "parent", "=", "n", ".", "getParent", "(", ")", ";", "n", ".", "replaceWith", "(", "block", ".", "detach", "(", ")", ")", ";", "if", "(", "mayHaveSideEffects", "(", "cond", ")", ")", "{", "Node", "condStatement", "=", "IR", ".", "exprResult", "(", "cond", ".", "detach", "(", ")", ")", ".", "srcref", "(", "cond", ")", ";", "parent", ".", "addChildAfter", "(", "condStatement", ",", "block", ")", ";", "}", "reportChangeToEnclosingScope", "(", "parent", ")", ";", "return", "block", ";", "}" ]
Removes DOs that always evaluate to false. This leaves the statements that were in the loop in a BLOCK node. The block will be removed in a later pass, if possible.
[ "Removes", "DOs", "that", "always", "evaluate", "to", "false", ".", "This", "leaves", "the", "statements", "that", "were", "in", "the", "loop", "in", "a", "BLOCK", "node", ".", "The", "block", "will", "be", "removed", "in", "a", "later", "pass", "if", "possible", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L1148-L1170
24,670
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryFoldEmptyDo
Node tryFoldEmptyDo(Node n) { checkArgument(n.isDo()); Node body = NodeUtil.getLoopCodeBlock(n); if (body.isBlock() && !body.hasChildren()) { Node cond = NodeUtil.getConditionExpression(n); Node forNode = IR.forNode(IR.empty().srcref(n), cond.detach(), IR.empty().srcref(n), body.detach()); n.replaceWith(forNode); reportChangeToEnclosingScope(forNode); return forNode; } return n; }
java
Node tryFoldEmptyDo(Node n) { checkArgument(n.isDo()); Node body = NodeUtil.getLoopCodeBlock(n); if (body.isBlock() && !body.hasChildren()) { Node cond = NodeUtil.getConditionExpression(n); Node forNode = IR.forNode(IR.empty().srcref(n), cond.detach(), IR.empty().srcref(n), body.detach()); n.replaceWith(forNode); reportChangeToEnclosingScope(forNode); return forNode; } return n; }
[ "Node", "tryFoldEmptyDo", "(", "Node", "n", ")", "{", "checkArgument", "(", "n", ".", "isDo", "(", ")", ")", ";", "Node", "body", "=", "NodeUtil", ".", "getLoopCodeBlock", "(", "n", ")", ";", "if", "(", "body", ".", "isBlock", "(", ")", "&&", "!", "body", ".", "hasChildren", "(", ")", ")", "{", "Node", "cond", "=", "NodeUtil", ".", "getConditionExpression", "(", "n", ")", ";", "Node", "forNode", "=", "IR", ".", "forNode", "(", "IR", ".", "empty", "(", ")", ".", "srcref", "(", "n", ")", ",", "cond", ".", "detach", "(", ")", ",", "IR", ".", "empty", "(", ")", ".", "srcref", "(", "n", ")", ",", "body", ".", "detach", "(", ")", ")", ";", "n", ".", "replaceWith", "(", "forNode", ")", ";", "reportChangeToEnclosingScope", "(", "forNode", ")", ";", "return", "forNode", ";", "}", "return", "n", ";", "}" ]
Removes DOs that have empty bodies into FORs, which are much easier for the CFA to analyze.
[ "Removes", "DOs", "that", "have", "empty", "bodies", "into", "FORs", "which", "are", "much", "easier", "for", "the", "CFA", "to", "analyze", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L1176-L1192
24,671
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryOptimizeObjectPattern
Node tryOptimizeObjectPattern(Node pattern) { checkArgument(pattern.isObjectPattern(), pattern); if (pattern.hasChildren() && pattern.getLastChild().isRest()) { // don't remove any elements in `const {f: [], ...rest} = obj` because that affects what's // assigned to `rest`. only the last element can be object rest. return pattern; } // remove trailing EMPTY nodes and empty destructuring patterns for (Node child = pattern.getFirstChild(); child != null; ) { Node key = child; child = key.getNext(); // don't put this in the for loop since we might remove `child` if (!key.isStringKey()) { // don't try to remove rest or computed properties, since they might have side effects continue; } if (isRemovableDestructuringTarget(key.getOnlyChild())) { // e.g. `const {f: {}} = obj;` key.detach(); reportChangeToEnclosingScope(pattern); } } return pattern; }
java
Node tryOptimizeObjectPattern(Node pattern) { checkArgument(pattern.isObjectPattern(), pattern); if (pattern.hasChildren() && pattern.getLastChild().isRest()) { // don't remove any elements in `const {f: [], ...rest} = obj` because that affects what's // assigned to `rest`. only the last element can be object rest. return pattern; } // remove trailing EMPTY nodes and empty destructuring patterns for (Node child = pattern.getFirstChild(); child != null; ) { Node key = child; child = key.getNext(); // don't put this in the for loop since we might remove `child` if (!key.isStringKey()) { // don't try to remove rest or computed properties, since they might have side effects continue; } if (isRemovableDestructuringTarget(key.getOnlyChild())) { // e.g. `const {f: {}} = obj;` key.detach(); reportChangeToEnclosingScope(pattern); } } return pattern; }
[ "Node", "tryOptimizeObjectPattern", "(", "Node", "pattern", ")", "{", "checkArgument", "(", "pattern", ".", "isObjectPattern", "(", ")", ",", "pattern", ")", ";", "if", "(", "pattern", ".", "hasChildren", "(", ")", "&&", "pattern", ".", "getLastChild", "(", ")", ".", "isRest", "(", ")", ")", "{", "// don't remove any elements in `const {f: [], ...rest} = obj` because that affects what's", "// assigned to `rest`. only the last element can be object rest.", "return", "pattern", ";", "}", "// remove trailing EMPTY nodes and empty destructuring patterns", "for", "(", "Node", "child", "=", "pattern", ".", "getFirstChild", "(", ")", ";", "child", "!=", "null", ";", ")", "{", "Node", "key", "=", "child", ";", "child", "=", "key", ".", "getNext", "(", ")", ";", "// don't put this in the for loop since we might remove `child`", "if", "(", "!", "key", ".", "isStringKey", "(", ")", ")", "{", "// don't try to remove rest or computed properties, since they might have side effects", "continue", ";", "}", "if", "(", "isRemovableDestructuringTarget", "(", "key", ".", "getOnlyChild", "(", ")", ")", ")", "{", "// e.g. `const {f: {}} = obj;`", "key", ".", "detach", "(", ")", ";", "reportChangeToEnclosingScope", "(", "pattern", ")", ";", "}", "}", "return", "pattern", ";", "}" ]
Removes string keys with an empty pattern as their child
[ "Removes", "string", "keys", "with", "an", "empty", "pattern", "as", "their", "child" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L1195-L1220
24,672
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryOptimizeArrayPattern
Node tryOptimizeArrayPattern(Node pattern) { checkArgument(pattern.isArrayPattern(), pattern); for (Node lastChild = pattern.getLastChild(); lastChild != null; ) { if (lastChild.isEmpty() || isRemovableDestructuringTarget(lastChild)) { Node prev = lastChild.getPrevious(); pattern.removeChild(lastChild); lastChild = prev; reportChangeToEnclosingScope(pattern); } else { // don't remove any non-trailing empty nodes because that will change the ordering of the // other assignments // note that this case also covers array pattern rest, which must be the final element break; } } return pattern; }
java
Node tryOptimizeArrayPattern(Node pattern) { checkArgument(pattern.isArrayPattern(), pattern); for (Node lastChild = pattern.getLastChild(); lastChild != null; ) { if (lastChild.isEmpty() || isRemovableDestructuringTarget(lastChild)) { Node prev = lastChild.getPrevious(); pattern.removeChild(lastChild); lastChild = prev; reportChangeToEnclosingScope(pattern); } else { // don't remove any non-trailing empty nodes because that will change the ordering of the // other assignments // note that this case also covers array pattern rest, which must be the final element break; } } return pattern; }
[ "Node", "tryOptimizeArrayPattern", "(", "Node", "pattern", ")", "{", "checkArgument", "(", "pattern", ".", "isArrayPattern", "(", ")", ",", "pattern", ")", ";", "for", "(", "Node", "lastChild", "=", "pattern", ".", "getLastChild", "(", ")", ";", "lastChild", "!=", "null", ";", ")", "{", "if", "(", "lastChild", ".", "isEmpty", "(", ")", "||", "isRemovableDestructuringTarget", "(", "lastChild", ")", ")", "{", "Node", "prev", "=", "lastChild", ".", "getPrevious", "(", ")", ";", "pattern", ".", "removeChild", "(", "lastChild", ")", ";", "lastChild", "=", "prev", ";", "reportChangeToEnclosingScope", "(", "pattern", ")", ";", "}", "else", "{", "// don't remove any non-trailing empty nodes because that will change the ordering of the", "// other assignments", "// note that this case also covers array pattern rest, which must be the final element", "break", ";", "}", "}", "return", "pattern", ";", "}" ]
Removes trailing EMPTY nodes and empty array patterns
[ "Removes", "trailing", "EMPTY", "nodes", "and", "empty", "array", "patterns" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L1223-L1240
24,673
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.hasUnnamedBreakOrContinue
static boolean hasUnnamedBreakOrContinue(Node n) { return NodeUtil.has(n, IS_UNNAMED_BREAK_PREDICATE, CAN_CONTAIN_BREAK_PREDICATE) || NodeUtil.has(n, IS_UNNAMED_CONTINUE_PREDICATE, CAN_CONTAIN_CONTINUE_PREDICATE); }
java
static boolean hasUnnamedBreakOrContinue(Node n) { return NodeUtil.has(n, IS_UNNAMED_BREAK_PREDICATE, CAN_CONTAIN_BREAK_PREDICATE) || NodeUtil.has(n, IS_UNNAMED_CONTINUE_PREDICATE, CAN_CONTAIN_CONTINUE_PREDICATE); }
[ "static", "boolean", "hasUnnamedBreakOrContinue", "(", "Node", "n", ")", "{", "return", "NodeUtil", ".", "has", "(", "n", ",", "IS_UNNAMED_BREAK_PREDICATE", ",", "CAN_CONTAIN_BREAK_PREDICATE", ")", "||", "NodeUtil", ".", "has", "(", "n", ",", "IS_UNNAMED_CONTINUE_PREDICATE", ",", "CAN_CONTAIN_CONTINUE_PREDICATE", ")", ";", "}" ]
Returns whether a node has any unhandled breaks or continue.
[ "Returns", "whether", "a", "node", "has", "any", "unhandled", "breaks", "or", "continue", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L1259-L1262
24,674
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java
PeepholeRemoveDeadCode.tryFoldForCondition
private void tryFoldForCondition(Node forCondition) { if (NodeUtil.getPureBooleanValue(forCondition) == TernaryValue.TRUE) { reportChangeToEnclosingScope(forCondition); forCondition.replaceWith(IR.empty()); } }
java
private void tryFoldForCondition(Node forCondition) { if (NodeUtil.getPureBooleanValue(forCondition) == TernaryValue.TRUE) { reportChangeToEnclosingScope(forCondition); forCondition.replaceWith(IR.empty()); } }
[ "private", "void", "tryFoldForCondition", "(", "Node", "forCondition", ")", "{", "if", "(", "NodeUtil", ".", "getPureBooleanValue", "(", "forCondition", ")", "==", "TernaryValue", ".", "TRUE", ")", "{", "reportChangeToEnclosingScope", "(", "forCondition", ")", ";", "forCondition", ".", "replaceWith", "(", "IR", ".", "empty", "(", ")", ")", ";", "}", "}" ]
Remove always true loop conditions.
[ "Remove", "always", "true", "loop", "conditions", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeRemoveDeadCode.java#L1267-L1272
24,675
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java
Es6RewriteBlockScopedDeclaration.visitBlockScopedName
private void visitBlockScopedName(NodeTraversal t, Node decl, Node nameNode) { Scope scope = t.getScope(); Node parent = decl.getParent(); // Normalize "let x;" to "let x = undefined;" if in a loop, since we later convert x // to be $jscomp$loop$0.x and want to reset the property to undefined every loop iteration. if ((decl.isLet() || decl.isConst()) && !nameNode.hasChildren() && (parent == null || !parent.isForIn()) && inLoop(decl)) { Node undefined = createUndefinedNode().srcref(nameNode); nameNode.addChildToFront(undefined); compiler.reportChangeToEnclosingScope(undefined); } String oldName = nameNode.getString(); Scope hoistScope = scope.getClosestHoistScope(); if (scope != hoistScope) { String newName = oldName; if (hoistScope.hasSlot(oldName) || undeclaredNames.contains(oldName)) { do { newName = oldName + "$" + compiler.getUniqueNameIdSupplier().get(); } while (hoistScope.hasSlot(newName)); nameNode.setString(newName); compiler.reportChangeToEnclosingScope(nameNode); Node scopeRoot = scope.getRootNode(); renameTable.put(scopeRoot, oldName, newName); } Var oldVar = scope.getVar(oldName); scope.undeclare(oldVar); hoistScope.declare(newName, nameNode, oldVar.input); } }
java
private void visitBlockScopedName(NodeTraversal t, Node decl, Node nameNode) { Scope scope = t.getScope(); Node parent = decl.getParent(); // Normalize "let x;" to "let x = undefined;" if in a loop, since we later convert x // to be $jscomp$loop$0.x and want to reset the property to undefined every loop iteration. if ((decl.isLet() || decl.isConst()) && !nameNode.hasChildren() && (parent == null || !parent.isForIn()) && inLoop(decl)) { Node undefined = createUndefinedNode().srcref(nameNode); nameNode.addChildToFront(undefined); compiler.reportChangeToEnclosingScope(undefined); } String oldName = nameNode.getString(); Scope hoistScope = scope.getClosestHoistScope(); if (scope != hoistScope) { String newName = oldName; if (hoistScope.hasSlot(oldName) || undeclaredNames.contains(oldName)) { do { newName = oldName + "$" + compiler.getUniqueNameIdSupplier().get(); } while (hoistScope.hasSlot(newName)); nameNode.setString(newName); compiler.reportChangeToEnclosingScope(nameNode); Node scopeRoot = scope.getRootNode(); renameTable.put(scopeRoot, oldName, newName); } Var oldVar = scope.getVar(oldName); scope.undeclare(oldVar); hoistScope.declare(newName, nameNode, oldVar.input); } }
[ "private", "void", "visitBlockScopedName", "(", "NodeTraversal", "t", ",", "Node", "decl", ",", "Node", "nameNode", ")", "{", "Scope", "scope", "=", "t", ".", "getScope", "(", ")", ";", "Node", "parent", "=", "decl", ".", "getParent", "(", ")", ";", "// Normalize \"let x;\" to \"let x = undefined;\" if in a loop, since we later convert x", "// to be $jscomp$loop$0.x and want to reset the property to undefined every loop iteration.", "if", "(", "(", "decl", ".", "isLet", "(", ")", "||", "decl", ".", "isConst", "(", ")", ")", "&&", "!", "nameNode", ".", "hasChildren", "(", ")", "&&", "(", "parent", "==", "null", "||", "!", "parent", ".", "isForIn", "(", ")", ")", "&&", "inLoop", "(", "decl", ")", ")", "{", "Node", "undefined", "=", "createUndefinedNode", "(", ")", ".", "srcref", "(", "nameNode", ")", ";", "nameNode", ".", "addChildToFront", "(", "undefined", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "undefined", ")", ";", "}", "String", "oldName", "=", "nameNode", ".", "getString", "(", ")", ";", "Scope", "hoistScope", "=", "scope", ".", "getClosestHoistScope", "(", ")", ";", "if", "(", "scope", "!=", "hoistScope", ")", "{", "String", "newName", "=", "oldName", ";", "if", "(", "hoistScope", ".", "hasSlot", "(", "oldName", ")", "||", "undeclaredNames", ".", "contains", "(", "oldName", ")", ")", "{", "do", "{", "newName", "=", "oldName", "+", "\"$\"", "+", "compiler", ".", "getUniqueNameIdSupplier", "(", ")", ".", "get", "(", ")", ";", "}", "while", "(", "hoistScope", ".", "hasSlot", "(", "newName", ")", ")", ";", "nameNode", ".", "setString", "(", "newName", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "nameNode", ")", ";", "Node", "scopeRoot", "=", "scope", ".", "getRootNode", "(", ")", ";", "renameTable", ".", "put", "(", "scopeRoot", ",", "oldName", ",", "newName", ")", ";", "}", "Var", "oldVar", "=", "scope", ".", "getVar", "(", "oldName", ")", ";", "scope", ".", "undeclare", "(", "oldVar", ")", ";", "hoistScope", ".", "declare", "(", "newName", ",", "nameNode", ",", "oldVar", ".", "input", ")", ";", "}", "}" ]
Renames block-scoped declarations that shadow a variable in an outer scope <p>Also normalizes declarations with no initializer in a loop to be initialized to undefined.
[ "Renames", "block", "-", "scoped", "declarations", "that", "shadow", "a", "variable", "in", "an", "outer", "scope" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java#L141-L172
24,676
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java
Es6RewriteBlockScopedDeclaration.inLoop
private boolean inLoop(Node n) { Node enclosingNode = NodeUtil.getEnclosingNode(n, isLoopOrFunction); return enclosingNode != null && !enclosingNode.isFunction(); }
java
private boolean inLoop(Node n) { Node enclosingNode = NodeUtil.getEnclosingNode(n, isLoopOrFunction); return enclosingNode != null && !enclosingNode.isFunction(); }
[ "private", "boolean", "inLoop", "(", "Node", "n", ")", "{", "Node", "enclosingNode", "=", "NodeUtil", ".", "getEnclosingNode", "(", "n", ",", "isLoopOrFunction", ")", ";", "return", "enclosingNode", "!=", "null", "&&", "!", "enclosingNode", ".", "isFunction", "(", ")", ";", "}" ]
Whether n is inside a loop. If n is inside a function which is inside a loop, we do not consider it to be inside a loop.
[ "Whether", "n", "is", "inside", "a", "loop", ".", "If", "n", "is", "inside", "a", "function", "which", "is", "inside", "a", "loop", "we", "do", "not", "consider", "it", "to", "be", "inside", "a", "loop", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java#L178-L181
24,677
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java
Es6RewriteBlockScopedDeclaration.createAssignNode
private Node createAssignNode(Node lhs, Node rhs) { Node assignNode = IR.assign(lhs, rhs); if (shouldAddTypesOnNewAstNodes) { assignNode.setJSType(rhs.getJSType()); } return assignNode; }
java
private Node createAssignNode(Node lhs, Node rhs) { Node assignNode = IR.assign(lhs, rhs); if (shouldAddTypesOnNewAstNodes) { assignNode.setJSType(rhs.getJSType()); } return assignNode; }
[ "private", "Node", "createAssignNode", "(", "Node", "lhs", ",", "Node", "rhs", ")", "{", "Node", "assignNode", "=", "IR", ".", "assign", "(", "lhs", ",", "rhs", ")", ";", "if", "(", "shouldAddTypesOnNewAstNodes", ")", "{", "assignNode", ".", "setJSType", "(", "rhs", ".", "getJSType", "(", ")", ")", ";", "}", "return", "assignNode", ";", "}" ]
Creates an ASSIGN node with type information matching its RHS.
[ "Creates", "an", "ASSIGN", "node", "with", "type", "information", "matching", "its", "RHS", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java#L709-L715
24,678
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java
Es6RewriteBlockScopedDeclaration.createCommaNode
private Node createCommaNode(Node expr1, Node expr2) { Node commaNode = IR.comma(expr1, expr2); if (shouldAddTypesOnNewAstNodes) { commaNode.setJSType(expr2.getJSType()); } return commaNode; }
java
private Node createCommaNode(Node expr1, Node expr2) { Node commaNode = IR.comma(expr1, expr2); if (shouldAddTypesOnNewAstNodes) { commaNode.setJSType(expr2.getJSType()); } return commaNode; }
[ "private", "Node", "createCommaNode", "(", "Node", "expr1", ",", "Node", "expr2", ")", "{", "Node", "commaNode", "=", "IR", ".", "comma", "(", "expr1", ",", "expr2", ")", ";", "if", "(", "shouldAddTypesOnNewAstNodes", ")", "{", "commaNode", ".", "setJSType", "(", "expr2", ".", "getJSType", "(", ")", ")", ";", "}", "return", "commaNode", ";", "}" ]
Creates a COMMA node with type information matching its second argument.
[ "Creates", "a", "COMMA", "node", "with", "type", "information", "matching", "its", "second", "argument", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java#L718-L724
24,679
google/closure-compiler
src/com/google/javascript/jscomp/SourceFile.java
SourceFile.getLine
public String getLine(int lineNumber) { findLineOffsets(); if (lineNumber > lineOffsets.length) { return null; } if (lineNumber < 1) { lineNumber = 1; } int pos = lineOffsets[lineNumber - 1]; String js = ""; try { // NOTE(nicksantos): Right now, this is optimized for few warnings. // This is probably the right trade-off, but will be slow if there // are lots of warnings in one file. js = getCode(); } catch (IOException e) { return null; } if (js.indexOf('\n', pos) == -1) { // If next new line cannot be found, there are two cases // 1. pos already reaches the end of file, then null should be returned // 2. otherwise, return the contents between pos and the end of file. if (pos >= js.length()) { return null; } else { return js.substring(pos); } } else { return js.substring(pos, js.indexOf('\n', pos)); } }
java
public String getLine(int lineNumber) { findLineOffsets(); if (lineNumber > lineOffsets.length) { return null; } if (lineNumber < 1) { lineNumber = 1; } int pos = lineOffsets[lineNumber - 1]; String js = ""; try { // NOTE(nicksantos): Right now, this is optimized for few warnings. // This is probably the right trade-off, but will be slow if there // are lots of warnings in one file. js = getCode(); } catch (IOException e) { return null; } if (js.indexOf('\n', pos) == -1) { // If next new line cannot be found, there are two cases // 1. pos already reaches the end of file, then null should be returned // 2. otherwise, return the contents between pos and the end of file. if (pos >= js.length()) { return null; } else { return js.substring(pos); } } else { return js.substring(pos, js.indexOf('\n', pos)); } }
[ "public", "String", "getLine", "(", "int", "lineNumber", ")", "{", "findLineOffsets", "(", ")", ";", "if", "(", "lineNumber", ">", "lineOffsets", ".", "length", ")", "{", "return", "null", ";", "}", "if", "(", "lineNumber", "<", "1", ")", "{", "lineNumber", "=", "1", ";", "}", "int", "pos", "=", "lineOffsets", "[", "lineNumber", "-", "1", "]", ";", "String", "js", "=", "\"\"", ";", "try", "{", "// NOTE(nicksantos): Right now, this is optimized for few warnings.", "// This is probably the right trade-off, but will be slow if there", "// are lots of warnings in one file.", "js", "=", "getCode", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "null", ";", "}", "if", "(", "js", ".", "indexOf", "(", "'", "'", ",", "pos", ")", "==", "-", "1", ")", "{", "// If next new line cannot be found, there are two cases", "// 1. pos already reaches the end of file, then null should be returned", "// 2. otherwise, return the contents between pos and the end of file.", "if", "(", "pos", ">=", "js", ".", "length", "(", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "js", ".", "substring", "(", "pos", ")", ";", "}", "}", "else", "{", "return", "js", ".", "substring", "(", "pos", ",", "js", ".", "indexOf", "(", "'", "'", ",", "pos", ")", ")", ";", "}", "}" ]
Gets the source line for the indicated line number. @param lineNumber the line number, 1 being the first line of the file. @return The line indicated. Does not include the newline at the end of the file. Returns {@code null} if it does not exist, or if there was an IO exception.
[ "Gets", "the", "source", "line", "for", "the", "indicated", "line", "number", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SourceFile.java#L243-L276
24,680
google/closure-compiler
src/com/google/javascript/jscomp/SourceFile.java
SourceFile.getRegion
public Region getRegion(int lineNumber) { String js = ""; try { js = getCode(); } catch (IOException e) { return null; } int pos = 0; int startLine = Math.max(1, lineNumber - (SOURCE_EXCERPT_REGION_LENGTH + 1) / 2 + 1); for (int n = 1; n < startLine; n++) { int nextpos = js.indexOf('\n', pos); if (nextpos == -1) { break; } pos = nextpos + 1; } int end = pos; int endLine = startLine; for (int n = 0; n < SOURCE_EXCERPT_REGION_LENGTH; n++, endLine++) { end = js.indexOf('\n', end); if (end == -1) { break; } end++; } if (lineNumber >= endLine) { return null; } if (end == -1) { int last = js.length() - 1; if (js.charAt(last) == '\n') { return new SimpleRegion(startLine, endLine, js.substring(pos, last)); } else { return new SimpleRegion(startLine, endLine, js.substring(pos)); } } else { return new SimpleRegion(startLine, endLine, js.substring(pos, end)); } }
java
public Region getRegion(int lineNumber) { String js = ""; try { js = getCode(); } catch (IOException e) { return null; } int pos = 0; int startLine = Math.max(1, lineNumber - (SOURCE_EXCERPT_REGION_LENGTH + 1) / 2 + 1); for (int n = 1; n < startLine; n++) { int nextpos = js.indexOf('\n', pos); if (nextpos == -1) { break; } pos = nextpos + 1; } int end = pos; int endLine = startLine; for (int n = 0; n < SOURCE_EXCERPT_REGION_LENGTH; n++, endLine++) { end = js.indexOf('\n', end); if (end == -1) { break; } end++; } if (lineNumber >= endLine) { return null; } if (end == -1) { int last = js.length() - 1; if (js.charAt(last) == '\n') { return new SimpleRegion(startLine, endLine, js.substring(pos, last)); } else { return new SimpleRegion(startLine, endLine, js.substring(pos)); } } else { return new SimpleRegion(startLine, endLine, js.substring(pos, end)); } }
[ "public", "Region", "getRegion", "(", "int", "lineNumber", ")", "{", "String", "js", "=", "\"\"", ";", "try", "{", "js", "=", "getCode", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "null", ";", "}", "int", "pos", "=", "0", ";", "int", "startLine", "=", "Math", ".", "max", "(", "1", ",", "lineNumber", "-", "(", "SOURCE_EXCERPT_REGION_LENGTH", "+", "1", ")", "/", "2", "+", "1", ")", ";", "for", "(", "int", "n", "=", "1", ";", "n", "<", "startLine", ";", "n", "++", ")", "{", "int", "nextpos", "=", "js", ".", "indexOf", "(", "'", "'", ",", "pos", ")", ";", "if", "(", "nextpos", "==", "-", "1", ")", "{", "break", ";", "}", "pos", "=", "nextpos", "+", "1", ";", "}", "int", "end", "=", "pos", ";", "int", "endLine", "=", "startLine", ";", "for", "(", "int", "n", "=", "0", ";", "n", "<", "SOURCE_EXCERPT_REGION_LENGTH", ";", "n", "++", ",", "endLine", "++", ")", "{", "end", "=", "js", ".", "indexOf", "(", "'", "'", ",", "end", ")", ";", "if", "(", "end", "==", "-", "1", ")", "{", "break", ";", "}", "end", "++", ";", "}", "if", "(", "lineNumber", ">=", "endLine", ")", "{", "return", "null", ";", "}", "if", "(", "end", "==", "-", "1", ")", "{", "int", "last", "=", "js", ".", "length", "(", ")", "-", "1", ";", "if", "(", "js", ".", "charAt", "(", "last", ")", "==", "'", "'", ")", "{", "return", "new", "SimpleRegion", "(", "startLine", ",", "endLine", ",", "js", ".", "substring", "(", "pos", ",", "last", ")", ")", ";", "}", "else", "{", "return", "new", "SimpleRegion", "(", "startLine", ",", "endLine", ",", "js", ".", "substring", "(", "pos", ")", ")", ";", "}", "}", "else", "{", "return", "new", "SimpleRegion", "(", "startLine", ",", "endLine", ",", "js", ".", "substring", "(", "pos", ",", "end", ")", ")", ";", "}", "}" ]
Get a region around the indicated line number. The exact definition of a region is implementation specific, but it must contain the line indicated by the line number. A region must not start or end by a carriage return. @param lineNumber the line number, 1 being the first line of the file. @return The line indicated. Returns {@code null} if it does not exist, or if there was an IO exception.
[ "Get", "a", "region", "around", "the", "indicated", "line", "number", ".", "The", "exact", "definition", "of", "a", "region", "is", "implementation", "specific", "but", "it", "must", "contain", "the", "line", "indicated", "by", "the", "line", "number", ".", "A", "region", "must", "not", "start", "or", "end", "by", "a", "carriage", "return", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SourceFile.java#L287-L327
24,681
google/closure-compiler
src/com/google/javascript/jscomp/VariableMap.java
VariableMap.save
@GwtIncompatible("com.google.io.Files") public void save(String filename) throws IOException { Files.write(toBytes(), new File(filename)); }
java
@GwtIncompatible("com.google.io.Files") public void save(String filename) throws IOException { Files.write(toBytes(), new File(filename)); }
[ "@", "GwtIncompatible", "(", "\"com.google.io.Files\"", ")", "public", "void", "save", "(", "String", "filename", ")", "throws", "IOException", "{", "Files", ".", "write", "(", "toBytes", "(", ")", ",", "new", "File", "(", "filename", ")", ")", ";", "}" ]
Saves the variable map to a file.
[ "Saves", "the", "variable", "map", "to", "a", "file", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/VariableMap.java#L81-L84
24,682
google/closure-compiler
src/com/google/javascript/jscomp/VariableMap.java
VariableMap.toBytes
@GwtIncompatible("java.io.ByteArrayOutputStream") public byte[] toBytes() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(baos, UTF_8); try { // The output order should be stable. for (Map.Entry<String, String> entry : ImmutableSortedSet.copyOf(comparingByKey(), map.entrySet())) { writer.write(escape(entry.getKey())); writer.write(SEPARATOR); writer.write(escape(entry.getValue())); writer.write('\n'); } writer.close(); } catch (IOException e) { // Note: A ByteArrayOutputStream never throws IOException. This try/catch // is just here to appease the Java compiler. throw new RuntimeException(e); } return baos.toByteArray(); }
java
@GwtIncompatible("java.io.ByteArrayOutputStream") public byte[] toBytes() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(baos, UTF_8); try { // The output order should be stable. for (Map.Entry<String, String> entry : ImmutableSortedSet.copyOf(comparingByKey(), map.entrySet())) { writer.write(escape(entry.getKey())); writer.write(SEPARATOR); writer.write(escape(entry.getValue())); writer.write('\n'); } writer.close(); } catch (IOException e) { // Note: A ByteArrayOutputStream never throws IOException. This try/catch // is just here to appease the Java compiler. throw new RuntimeException(e); } return baos.toByteArray(); }
[ "@", "GwtIncompatible", "(", "\"java.io.ByteArrayOutputStream\"", ")", "public", "byte", "[", "]", "toBytes", "(", ")", "{", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "Writer", "writer", "=", "new", "OutputStreamWriter", "(", "baos", ",", "UTF_8", ")", ";", "try", "{", "// The output order should be stable.", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "ImmutableSortedSet", ".", "copyOf", "(", "comparingByKey", "(", ")", ",", "map", ".", "entrySet", "(", ")", ")", ")", "{", "writer", ".", "write", "(", "escape", "(", "entry", ".", "getKey", "(", ")", ")", ")", ";", "writer", ".", "write", "(", "SEPARATOR", ")", ";", "writer", ".", "write", "(", "escape", "(", "entry", ".", "getValue", "(", ")", ")", ")", ";", "writer", ".", "write", "(", "'", "'", ")", ";", "}", "writer", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// Note: A ByteArrayOutputStream never throws IOException. This try/catch", "// is just here to appease the Java compiler.", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "return", "baos", ".", "toByteArray", "(", ")", ";", "}" ]
Serializes the variable map to a byte array.
[ "Serializes", "the", "variable", "map", "to", "a", "byte", "array", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/VariableMap.java#L102-L122
24,683
google/closure-compiler
src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java
TypeTransformationParser.parseTypeTransformation
public boolean parseTypeTransformation() { Config config = Config.builder() .setLanguageMode(Config.LanguageMode.ECMASCRIPT6) .setStrictMode(Config.StrictMode.SLOPPY) .build(); // TODO(lpino): ParserRunner reports errors if the expression is not // ES6 valid. We need to abort the validation of the type transformation // whenever an error is reported. ParseResult result = ParserRunner.parse( sourceFile, typeTransformationString, config, errorReporter); Node ast = result.ast; // Check that the expression is a script with an expression result if (!ast.isScript() || !ast.getFirstChild().isExprResult()) { warnInvalidExpression("type transformation", ast); return false; } Node expr = ast.getFirstFirstChild(); // The AST of the type transformation must correspond to a valid expression if (!validTypeTransformationExpression(expr)) { // No need to add a new warning because the validation does it return false; } fixLineNumbers(expr); // Store the result if the AST is valid typeTransformationAst = expr; return true; }
java
public boolean parseTypeTransformation() { Config config = Config.builder() .setLanguageMode(Config.LanguageMode.ECMASCRIPT6) .setStrictMode(Config.StrictMode.SLOPPY) .build(); // TODO(lpino): ParserRunner reports errors if the expression is not // ES6 valid. We need to abort the validation of the type transformation // whenever an error is reported. ParseResult result = ParserRunner.parse( sourceFile, typeTransformationString, config, errorReporter); Node ast = result.ast; // Check that the expression is a script with an expression result if (!ast.isScript() || !ast.getFirstChild().isExprResult()) { warnInvalidExpression("type transformation", ast); return false; } Node expr = ast.getFirstFirstChild(); // The AST of the type transformation must correspond to a valid expression if (!validTypeTransformationExpression(expr)) { // No need to add a new warning because the validation does it return false; } fixLineNumbers(expr); // Store the result if the AST is valid typeTransformationAst = expr; return true; }
[ "public", "boolean", "parseTypeTransformation", "(", ")", "{", "Config", "config", "=", "Config", ".", "builder", "(", ")", ".", "setLanguageMode", "(", "Config", ".", "LanguageMode", ".", "ECMASCRIPT6", ")", ".", "setStrictMode", "(", "Config", ".", "StrictMode", ".", "SLOPPY", ")", ".", "build", "(", ")", ";", "// TODO(lpino): ParserRunner reports errors if the expression is not", "// ES6 valid. We need to abort the validation of the type transformation", "// whenever an error is reported.", "ParseResult", "result", "=", "ParserRunner", ".", "parse", "(", "sourceFile", ",", "typeTransformationString", ",", "config", ",", "errorReporter", ")", ";", "Node", "ast", "=", "result", ".", "ast", ";", "// Check that the expression is a script with an expression result", "if", "(", "!", "ast", ".", "isScript", "(", ")", "||", "!", "ast", ".", "getFirstChild", "(", ")", ".", "isExprResult", "(", ")", ")", "{", "warnInvalidExpression", "(", "\"type transformation\"", ",", "ast", ")", ";", "return", "false", ";", "}", "Node", "expr", "=", "ast", ".", "getFirstFirstChild", "(", ")", ";", "// The AST of the type transformation must correspond to a valid expression", "if", "(", "!", "validTypeTransformationExpression", "(", "expr", ")", ")", "{", "// No need to add a new warning because the validation does it", "return", "false", ";", "}", "fixLineNumbers", "(", "expr", ")", ";", "// Store the result if the AST is valid", "typeTransformationAst", "=", "expr", ";", "return", "true", ";", "}" ]
Takes a type transformation expression, transforms it to an AST using the ParserRunner of the JSCompiler and then verifies that it is a valid AST. @return true if the parsing was successful otherwise it returns false and at least one warning is reported
[ "Takes", "a", "type", "transformation", "expression", "transforms", "it", "to", "an", "AST", "using", "the", "ParserRunner", "of", "the", "JSCompiler", "and", "then", "verifies", "that", "it", "is", "a", "valid", "AST", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java#L250-L278
24,684
google/closure-compiler
src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java
TypeTransformationParser.validBooleanExpression
private boolean validBooleanExpression(Node expr) { if (isBooleanOperation(expr)) { return validBooleanOperation(expr); } if (!isOperation(expr)) { warnInvalidExpression("boolean", expr); return false; } if (!isValidPredicate(getCallName(expr))) { warnInvalid("boolean predicate", expr); return false; } Keywords keyword = nameToKeyword(getCallName(expr)); if (!checkParameterCount(expr, keyword)) { return false; } switch (keyword.kind) { case TYPE_PREDICATE: return validTypePredicate(expr, getCallParamCount(expr)); case STRING_PREDICATE: return validStringPredicate(expr, getCallParamCount(expr)); case TYPEVAR_PREDICATE: return validTypevarPredicate(expr, getCallParamCount(expr)); default: throw new IllegalStateException("Invalid boolean expression"); } }
java
private boolean validBooleanExpression(Node expr) { if (isBooleanOperation(expr)) { return validBooleanOperation(expr); } if (!isOperation(expr)) { warnInvalidExpression("boolean", expr); return false; } if (!isValidPredicate(getCallName(expr))) { warnInvalid("boolean predicate", expr); return false; } Keywords keyword = nameToKeyword(getCallName(expr)); if (!checkParameterCount(expr, keyword)) { return false; } switch (keyword.kind) { case TYPE_PREDICATE: return validTypePredicate(expr, getCallParamCount(expr)); case STRING_PREDICATE: return validStringPredicate(expr, getCallParamCount(expr)); case TYPEVAR_PREDICATE: return validTypevarPredicate(expr, getCallParamCount(expr)); default: throw new IllegalStateException("Invalid boolean expression"); } }
[ "private", "boolean", "validBooleanExpression", "(", "Node", "expr", ")", "{", "if", "(", "isBooleanOperation", "(", "expr", ")", ")", "{", "return", "validBooleanOperation", "(", "expr", ")", ";", "}", "if", "(", "!", "isOperation", "(", "expr", ")", ")", "{", "warnInvalidExpression", "(", "\"boolean\"", ",", "expr", ")", ";", "return", "false", ";", "}", "if", "(", "!", "isValidPredicate", "(", "getCallName", "(", "expr", ")", ")", ")", "{", "warnInvalid", "(", "\"boolean predicate\"", ",", "expr", ")", ";", "return", "false", ";", "}", "Keywords", "keyword", "=", "nameToKeyword", "(", "getCallName", "(", "expr", ")", ")", ";", "if", "(", "!", "checkParameterCount", "(", "expr", ",", "keyword", ")", ")", "{", "return", "false", ";", "}", "switch", "(", "keyword", ".", "kind", ")", "{", "case", "TYPE_PREDICATE", ":", "return", "validTypePredicate", "(", "expr", ",", "getCallParamCount", "(", "expr", ")", ")", ";", "case", "STRING_PREDICATE", ":", "return", "validStringPredicate", "(", "expr", ",", "getCallParamCount", "(", "expr", ")", ")", ";", "case", "TYPEVAR_PREDICATE", ":", "return", "validTypevarPredicate", "(", "expr", ",", "getCallParamCount", "(", "expr", ")", ")", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Invalid boolean expression\"", ")", ";", "}", "}" ]
A boolean expression must be a boolean predicate or a boolean type predicate
[ "A", "boolean", "expression", "must", "be", "a", "boolean", "predicate", "or", "a", "boolean", "type", "predicate" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java#L572-L599
24,685
google/closure-compiler
src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java
TypeTransformationParser.validOperationExpression
private boolean validOperationExpression(Node expr) { String name = getCallName(expr); Keywords keyword = nameToKeyword(name); switch (keyword) { case COND: return validConditionalExpression(expr); case MAPUNION: return validMapunionExpression(expr); case MAPRECORD: return validMaprecordExpression(expr); case TYPEOFVAR: return validTypeOfVarExpression(expr); case INSTANCEOF: return validInstanceOfExpression(expr); case PRINTTYPE: return validPrintTypeExpression(expr); case PROPTYPE: return validPropTypeExpression(expr); default: throw new IllegalStateException("Invalid type transformation operation"); } }
java
private boolean validOperationExpression(Node expr) { String name = getCallName(expr); Keywords keyword = nameToKeyword(name); switch (keyword) { case COND: return validConditionalExpression(expr); case MAPUNION: return validMapunionExpression(expr); case MAPRECORD: return validMaprecordExpression(expr); case TYPEOFVAR: return validTypeOfVarExpression(expr); case INSTANCEOF: return validInstanceOfExpression(expr); case PRINTTYPE: return validPrintTypeExpression(expr); case PROPTYPE: return validPropTypeExpression(expr); default: throw new IllegalStateException("Invalid type transformation operation"); } }
[ "private", "boolean", "validOperationExpression", "(", "Node", "expr", ")", "{", "String", "name", "=", "getCallName", "(", "expr", ")", ";", "Keywords", "keyword", "=", "nameToKeyword", "(", "name", ")", ";", "switch", "(", "keyword", ")", "{", "case", "COND", ":", "return", "validConditionalExpression", "(", "expr", ")", ";", "case", "MAPUNION", ":", "return", "validMapunionExpression", "(", "expr", ")", ";", "case", "MAPRECORD", ":", "return", "validMaprecordExpression", "(", "expr", ")", ";", "case", "TYPEOFVAR", ":", "return", "validTypeOfVarExpression", "(", "expr", ")", ";", "case", "INSTANCEOF", ":", "return", "validInstanceOfExpression", "(", "expr", ")", ";", "case", "PRINTTYPE", ":", "return", "validPrintTypeExpression", "(", "expr", ")", ";", "case", "PROPTYPE", ":", "return", "validPropTypeExpression", "(", "expr", ")", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Invalid type transformation operation\"", ")", ";", "}", "}" ]
An operation expression is a cond or a mapunion
[ "An", "operation", "expression", "is", "a", "cond", "or", "a", "mapunion" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java#L794-L815
24,686
google/closure-compiler
src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java
TypeTransformationParser.validTypeTransformationExpression
private boolean validTypeTransformationExpression(Node expr) { if (!isValidExpression(expr)) { warnInvalidExpression("type transformation", expr); return false; } if (isTypeVar(expr) || isTypeName(expr)) { return true; } // Check for valid keyword String name = getCallName(expr); if (!isValidKeyword(name)) { warnInvalidExpression("type transformation", expr); return false; } Keywords keyword = nameToKeyword(name); // Check the rest of the expression depending on the kind switch (keyword.kind) { case TYPE_CONSTRUCTOR: return validTypeExpression(expr); case OPERATION: return validOperationExpression(expr); default: throw new IllegalStateException("Invalid type transformation expression"); } }
java
private boolean validTypeTransformationExpression(Node expr) { if (!isValidExpression(expr)) { warnInvalidExpression("type transformation", expr); return false; } if (isTypeVar(expr) || isTypeName(expr)) { return true; } // Check for valid keyword String name = getCallName(expr); if (!isValidKeyword(name)) { warnInvalidExpression("type transformation", expr); return false; } Keywords keyword = nameToKeyword(name); // Check the rest of the expression depending on the kind switch (keyword.kind) { case TYPE_CONSTRUCTOR: return validTypeExpression(expr); case OPERATION: return validOperationExpression(expr); default: throw new IllegalStateException("Invalid type transformation expression"); } }
[ "private", "boolean", "validTypeTransformationExpression", "(", "Node", "expr", ")", "{", "if", "(", "!", "isValidExpression", "(", "expr", ")", ")", "{", "warnInvalidExpression", "(", "\"type transformation\"", ",", "expr", ")", ";", "return", "false", ";", "}", "if", "(", "isTypeVar", "(", "expr", ")", "||", "isTypeName", "(", "expr", ")", ")", "{", "return", "true", ";", "}", "// Check for valid keyword", "String", "name", "=", "getCallName", "(", "expr", ")", ";", "if", "(", "!", "isValidKeyword", "(", "name", ")", ")", "{", "warnInvalidExpression", "(", "\"type transformation\"", ",", "expr", ")", ";", "return", "false", ";", "}", "Keywords", "keyword", "=", "nameToKeyword", "(", "name", ")", ";", "// Check the rest of the expression depending on the kind", "switch", "(", "keyword", ".", "kind", ")", "{", "case", "TYPE_CONSTRUCTOR", ":", "return", "validTypeExpression", "(", "expr", ")", ";", "case", "OPERATION", ":", "return", "validOperationExpression", "(", "expr", ")", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Invalid type transformation expression\"", ")", ";", "}", "}" ]
Checks the structure of the AST of a type transformation expression in @template T := TTLExp =:
[ "Checks", "the", "structure", "of", "the", "AST", "of", "a", "type", "transformation", "expression", "in" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java#L821-L845
24,687
google/closure-compiler
src/com/google/javascript/jscomp/ProcessCommonJSModules.java
ProcessCommonJSModules.removeIIFEWrapper
private boolean removeIIFEWrapper(Node root) { checkState(root.isScript()); Node n = root.getFirstChild(); // Sometimes scripts start with a semicolon for easy concatenation. // Skip any empty statements from those while (n != null && n.isEmpty()) { n = n.getNext(); } // An IIFE wrapper must be the only non-empty statement in the script, // and it must be an expression statement. if (n == null || !n.isExprResult() || n.getNext() != null) { return false; } // Function expression can be forced with !, just skip ! // TODO(ChadKillingsworth): // Expression could also be forced with: + - ~ void // ! ~ void can be repeated any number of times if (n != null && n.getFirstChild() != null && n.getFirstChild().isNot()) { n = n.getFirstChild(); } Node call = n.getFirstChild(); if (call == null || !call.isCall()) { return false; } // Find the IIFE call and function nodes Node fnc; if (call.getFirstChild().isFunction()) { fnc = n.getFirstFirstChild(); } else if (call.getFirstChild().isGetProp() && call.getFirstFirstChild().isFunction() && call.getFirstFirstChild().getNext().isString() && call.getFirstFirstChild().getNext().getString().equals("call")) { fnc = call.getFirstFirstChild(); // We only support explicitly binding "this" to the parent "this" or "exports" if (!(call.getSecondChild() != null && (call.getSecondChild().isThis() || call.getSecondChild().matchesQualifiedName(EXPORTS)))) { return false; } } else { return false; } if (NodeUtil.doesFunctionReferenceOwnArgumentsObject(fnc)) { return false; } CompilerInput ci = compiler.getInput(root.getInputId()); ModulePath modulePath = ci.getPath(); if (modulePath == null) { return false; } String iifeLabel = getModuleName(modulePath) + "_iifeWrapper"; FunctionToBlockMutator mutator = new FunctionToBlockMutator(compiler, compiler.getUniqueNameIdSupplier()); Node block = mutator.mutateWithoutRenaming(iifeLabel, fnc, call, null, false, false); root.removeChildren(); root.addChildrenToFront(block.removeChildren()); reportNestedScopesDeleted(fnc); compiler.reportChangeToEnclosingScope(root); return true; }
java
private boolean removeIIFEWrapper(Node root) { checkState(root.isScript()); Node n = root.getFirstChild(); // Sometimes scripts start with a semicolon for easy concatenation. // Skip any empty statements from those while (n != null && n.isEmpty()) { n = n.getNext(); } // An IIFE wrapper must be the only non-empty statement in the script, // and it must be an expression statement. if (n == null || !n.isExprResult() || n.getNext() != null) { return false; } // Function expression can be forced with !, just skip ! // TODO(ChadKillingsworth): // Expression could also be forced with: + - ~ void // ! ~ void can be repeated any number of times if (n != null && n.getFirstChild() != null && n.getFirstChild().isNot()) { n = n.getFirstChild(); } Node call = n.getFirstChild(); if (call == null || !call.isCall()) { return false; } // Find the IIFE call and function nodes Node fnc; if (call.getFirstChild().isFunction()) { fnc = n.getFirstFirstChild(); } else if (call.getFirstChild().isGetProp() && call.getFirstFirstChild().isFunction() && call.getFirstFirstChild().getNext().isString() && call.getFirstFirstChild().getNext().getString().equals("call")) { fnc = call.getFirstFirstChild(); // We only support explicitly binding "this" to the parent "this" or "exports" if (!(call.getSecondChild() != null && (call.getSecondChild().isThis() || call.getSecondChild().matchesQualifiedName(EXPORTS)))) { return false; } } else { return false; } if (NodeUtil.doesFunctionReferenceOwnArgumentsObject(fnc)) { return false; } CompilerInput ci = compiler.getInput(root.getInputId()); ModulePath modulePath = ci.getPath(); if (modulePath == null) { return false; } String iifeLabel = getModuleName(modulePath) + "_iifeWrapper"; FunctionToBlockMutator mutator = new FunctionToBlockMutator(compiler, compiler.getUniqueNameIdSupplier()); Node block = mutator.mutateWithoutRenaming(iifeLabel, fnc, call, null, false, false); root.removeChildren(); root.addChildrenToFront(block.removeChildren()); reportNestedScopesDeleted(fnc); compiler.reportChangeToEnclosingScope(root); return true; }
[ "private", "boolean", "removeIIFEWrapper", "(", "Node", "root", ")", "{", "checkState", "(", "root", ".", "isScript", "(", ")", ")", ";", "Node", "n", "=", "root", ".", "getFirstChild", "(", ")", ";", "// Sometimes scripts start with a semicolon for easy concatenation.", "// Skip any empty statements from those", "while", "(", "n", "!=", "null", "&&", "n", ".", "isEmpty", "(", ")", ")", "{", "n", "=", "n", ".", "getNext", "(", ")", ";", "}", "// An IIFE wrapper must be the only non-empty statement in the script,", "// and it must be an expression statement.", "if", "(", "n", "==", "null", "||", "!", "n", ".", "isExprResult", "(", ")", "||", "n", ".", "getNext", "(", ")", "!=", "null", ")", "{", "return", "false", ";", "}", "// Function expression can be forced with !, just skip !", "// TODO(ChadKillingsworth):", "// Expression could also be forced with: + - ~ void", "// ! ~ void can be repeated any number of times", "if", "(", "n", "!=", "null", "&&", "n", ".", "getFirstChild", "(", ")", "!=", "null", "&&", "n", ".", "getFirstChild", "(", ")", ".", "isNot", "(", ")", ")", "{", "n", "=", "n", ".", "getFirstChild", "(", ")", ";", "}", "Node", "call", "=", "n", ".", "getFirstChild", "(", ")", ";", "if", "(", "call", "==", "null", "||", "!", "call", ".", "isCall", "(", ")", ")", "{", "return", "false", ";", "}", "// Find the IIFE call and function nodes", "Node", "fnc", ";", "if", "(", "call", ".", "getFirstChild", "(", ")", ".", "isFunction", "(", ")", ")", "{", "fnc", "=", "n", ".", "getFirstFirstChild", "(", ")", ";", "}", "else", "if", "(", "call", ".", "getFirstChild", "(", ")", ".", "isGetProp", "(", ")", "&&", "call", ".", "getFirstFirstChild", "(", ")", ".", "isFunction", "(", ")", "&&", "call", ".", "getFirstFirstChild", "(", ")", ".", "getNext", "(", ")", ".", "isString", "(", ")", "&&", "call", ".", "getFirstFirstChild", "(", ")", ".", "getNext", "(", ")", ".", "getString", "(", ")", ".", "equals", "(", "\"call\"", ")", ")", "{", "fnc", "=", "call", ".", "getFirstFirstChild", "(", ")", ";", "// We only support explicitly binding \"this\" to the parent \"this\" or \"exports\"", "if", "(", "!", "(", "call", ".", "getSecondChild", "(", ")", "!=", "null", "&&", "(", "call", ".", "getSecondChild", "(", ")", ".", "isThis", "(", ")", "||", "call", ".", "getSecondChild", "(", ")", ".", "matchesQualifiedName", "(", "EXPORTS", ")", ")", ")", ")", "{", "return", "false", ";", "}", "}", "else", "{", "return", "false", ";", "}", "if", "(", "NodeUtil", ".", "doesFunctionReferenceOwnArgumentsObject", "(", "fnc", ")", ")", "{", "return", "false", ";", "}", "CompilerInput", "ci", "=", "compiler", ".", "getInput", "(", "root", ".", "getInputId", "(", ")", ")", ";", "ModulePath", "modulePath", "=", "ci", ".", "getPath", "(", ")", ";", "if", "(", "modulePath", "==", "null", ")", "{", "return", "false", ";", "}", "String", "iifeLabel", "=", "getModuleName", "(", "modulePath", ")", "+", "\"_iifeWrapper\"", ";", "FunctionToBlockMutator", "mutator", "=", "new", "FunctionToBlockMutator", "(", "compiler", ",", "compiler", ".", "getUniqueNameIdSupplier", "(", ")", ")", ";", "Node", "block", "=", "mutator", ".", "mutateWithoutRenaming", "(", "iifeLabel", ",", "fnc", ",", "call", ",", "null", ",", "false", ",", "false", ")", ";", "root", ".", "removeChildren", "(", ")", ";", "root", ".", "addChildrenToFront", "(", "block", ".", "removeChildren", "(", ")", ")", ";", "reportNestedScopesDeleted", "(", "fnc", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "root", ")", ";", "return", "true", ";", "}" ]
UMD modules are often wrapped in an IIFE for cases where they are used as scripts instead of modules. Remove the wrapper. @return Whether an IIFE wrapper was found and removed.
[ "UMD", "modules", "are", "often", "wrapped", "in", "an", "IIFE", "for", "cases", "where", "they", "are", "used", "as", "scripts", "instead", "of", "modules", ".", "Remove", "the", "wrapper", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessCommonJSModules.java#L398-L468
24,688
google/closure-compiler
src/com/google/javascript/jscomp/ProcessCommonJSModules.java
ProcessCommonJSModules.removeWebpackModuleShim
private void removeWebpackModuleShim(Node root) { checkState(root.isScript()); Node n = root.getFirstChild(); // Sometimes scripts start with a semicolon for easy concatenation. // Skip any empty statements from those while (n != null && n.isEmpty()) { n = n.getNext(); } // An IIFE wrapper must be the only non-empty statement in the script, // and it must be an expression statement. if (n == null || !n.isExprResult() || n.getNext() != null) { return; } Node call = n.getFirstChild(); if (call == null || !call.isCall()) { return; } // Find the IIFE call and function nodes Node fnc; if (call.getFirstChild().isFunction()) { fnc = n.getFirstFirstChild(); } else if (call.getFirstChild().isGetProp() && call.getFirstFirstChild().isFunction() && call.getFirstFirstChild().getNext().matchesQualifiedName("call")) { fnc = call.getFirstFirstChild(); } else { return; } Node params = NodeUtil.getFunctionParameters(fnc); Node moduleParam = null; Node param = params.getFirstChild(); int paramNumber = 0; while (param != null) { paramNumber++; if (param.isName() && param.getString().equals(MODULE)) { moduleParam = param; break; } param = param.getNext(); } if (moduleParam == null) { return; } boolean isFreeCall = call.getBooleanProp(Node.FREE_CALL); Node arg = call.getChildAtIndex(isFreeCall ? paramNumber : paramNumber + 1); if (arg == null) { return; } if (arg.isCall() && arg.getFirstChild().isCall() && isCommonJsImport(arg.getFirstChild()) && arg.getSecondChild().isName() && arg.getSecondChild().getString().equals(MODULE)) { String importPath = getCommonJsImportPath(arg.getFirstChild()); ModulePath modulePath = compiler .getInput(root.getInputId()) .getPath() .resolveJsModule( importPath, arg.getSourceFileName(), arg.getLineno(), arg.getCharno()); if (modulePath == null) { // The module loader will issue an error return; } if (modulePath.toString().contains("/buildin/module.js")) { arg.detach(); param.detach(); compiler.reportChangeToChangeScope(fnc); compiler.reportChangeToEnclosingScope(fnc); } } }
java
private void removeWebpackModuleShim(Node root) { checkState(root.isScript()); Node n = root.getFirstChild(); // Sometimes scripts start with a semicolon for easy concatenation. // Skip any empty statements from those while (n != null && n.isEmpty()) { n = n.getNext(); } // An IIFE wrapper must be the only non-empty statement in the script, // and it must be an expression statement. if (n == null || !n.isExprResult() || n.getNext() != null) { return; } Node call = n.getFirstChild(); if (call == null || !call.isCall()) { return; } // Find the IIFE call and function nodes Node fnc; if (call.getFirstChild().isFunction()) { fnc = n.getFirstFirstChild(); } else if (call.getFirstChild().isGetProp() && call.getFirstFirstChild().isFunction() && call.getFirstFirstChild().getNext().matchesQualifiedName("call")) { fnc = call.getFirstFirstChild(); } else { return; } Node params = NodeUtil.getFunctionParameters(fnc); Node moduleParam = null; Node param = params.getFirstChild(); int paramNumber = 0; while (param != null) { paramNumber++; if (param.isName() && param.getString().equals(MODULE)) { moduleParam = param; break; } param = param.getNext(); } if (moduleParam == null) { return; } boolean isFreeCall = call.getBooleanProp(Node.FREE_CALL); Node arg = call.getChildAtIndex(isFreeCall ? paramNumber : paramNumber + 1); if (arg == null) { return; } if (arg.isCall() && arg.getFirstChild().isCall() && isCommonJsImport(arg.getFirstChild()) && arg.getSecondChild().isName() && arg.getSecondChild().getString().equals(MODULE)) { String importPath = getCommonJsImportPath(arg.getFirstChild()); ModulePath modulePath = compiler .getInput(root.getInputId()) .getPath() .resolveJsModule( importPath, arg.getSourceFileName(), arg.getLineno(), arg.getCharno()); if (modulePath == null) { // The module loader will issue an error return; } if (modulePath.toString().contains("/buildin/module.js")) { arg.detach(); param.detach(); compiler.reportChangeToChangeScope(fnc); compiler.reportChangeToEnclosingScope(fnc); } } }
[ "private", "void", "removeWebpackModuleShim", "(", "Node", "root", ")", "{", "checkState", "(", "root", ".", "isScript", "(", ")", ")", ";", "Node", "n", "=", "root", ".", "getFirstChild", "(", ")", ";", "// Sometimes scripts start with a semicolon for easy concatenation.", "// Skip any empty statements from those", "while", "(", "n", "!=", "null", "&&", "n", ".", "isEmpty", "(", ")", ")", "{", "n", "=", "n", ".", "getNext", "(", ")", ";", "}", "// An IIFE wrapper must be the only non-empty statement in the script,", "// and it must be an expression statement.", "if", "(", "n", "==", "null", "||", "!", "n", ".", "isExprResult", "(", ")", "||", "n", ".", "getNext", "(", ")", "!=", "null", ")", "{", "return", ";", "}", "Node", "call", "=", "n", ".", "getFirstChild", "(", ")", ";", "if", "(", "call", "==", "null", "||", "!", "call", ".", "isCall", "(", ")", ")", "{", "return", ";", "}", "// Find the IIFE call and function nodes", "Node", "fnc", ";", "if", "(", "call", ".", "getFirstChild", "(", ")", ".", "isFunction", "(", ")", ")", "{", "fnc", "=", "n", ".", "getFirstFirstChild", "(", ")", ";", "}", "else", "if", "(", "call", ".", "getFirstChild", "(", ")", ".", "isGetProp", "(", ")", "&&", "call", ".", "getFirstFirstChild", "(", ")", ".", "isFunction", "(", ")", "&&", "call", ".", "getFirstFirstChild", "(", ")", ".", "getNext", "(", ")", ".", "matchesQualifiedName", "(", "\"call\"", ")", ")", "{", "fnc", "=", "call", ".", "getFirstFirstChild", "(", ")", ";", "}", "else", "{", "return", ";", "}", "Node", "params", "=", "NodeUtil", ".", "getFunctionParameters", "(", "fnc", ")", ";", "Node", "moduleParam", "=", "null", ";", "Node", "param", "=", "params", ".", "getFirstChild", "(", ")", ";", "int", "paramNumber", "=", "0", ";", "while", "(", "param", "!=", "null", ")", "{", "paramNumber", "++", ";", "if", "(", "param", ".", "isName", "(", ")", "&&", "param", ".", "getString", "(", ")", ".", "equals", "(", "MODULE", ")", ")", "{", "moduleParam", "=", "param", ";", "break", ";", "}", "param", "=", "param", ".", "getNext", "(", ")", ";", "}", "if", "(", "moduleParam", "==", "null", ")", "{", "return", ";", "}", "boolean", "isFreeCall", "=", "call", ".", "getBooleanProp", "(", "Node", ".", "FREE_CALL", ")", ";", "Node", "arg", "=", "call", ".", "getChildAtIndex", "(", "isFreeCall", "?", "paramNumber", ":", "paramNumber", "+", "1", ")", ";", "if", "(", "arg", "==", "null", ")", "{", "return", ";", "}", "if", "(", "arg", ".", "isCall", "(", ")", "&&", "arg", ".", "getFirstChild", "(", ")", ".", "isCall", "(", ")", "&&", "isCommonJsImport", "(", "arg", ".", "getFirstChild", "(", ")", ")", "&&", "arg", ".", "getSecondChild", "(", ")", ".", "isName", "(", ")", "&&", "arg", ".", "getSecondChild", "(", ")", ".", "getString", "(", ")", ".", "equals", "(", "MODULE", ")", ")", "{", "String", "importPath", "=", "getCommonJsImportPath", "(", "arg", ".", "getFirstChild", "(", ")", ")", ";", "ModulePath", "modulePath", "=", "compiler", ".", "getInput", "(", "root", ".", "getInputId", "(", ")", ")", ".", "getPath", "(", ")", ".", "resolveJsModule", "(", "importPath", ",", "arg", ".", "getSourceFileName", "(", ")", ",", "arg", ".", "getLineno", "(", ")", ",", "arg", ".", "getCharno", "(", ")", ")", ";", "if", "(", "modulePath", "==", "null", ")", "{", "// The module loader will issue an error", "return", ";", "}", "if", "(", "modulePath", ".", "toString", "(", ")", ".", "contains", "(", "\"/buildin/module.js\"", ")", ")", "{", "arg", ".", "detach", "(", ")", ";", "param", ".", "detach", "(", ")", ";", "compiler", ".", "reportChangeToChangeScope", "(", "fnc", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "fnc", ")", ";", "}", "}", "}" ]
For AMD wrappers, webpack adds a shim for the "module" variable. We need that to be a free var so we remove the shim.
[ "For", "AMD", "wrappers", "webpack", "adds", "a", "shim", "for", "the", "module", "variable", ".", "We", "need", "that", "to", "be", "a", "free", "var", "so", "we", "remove", "the", "shim", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessCommonJSModules.java#L474-L554
24,689
google/closure-compiler
src/com/google/javascript/jscomp/LinkedFlowScope.java
LinkedFlowScope.createEntryLattice
public static LinkedFlowScope createEntryLattice(TypedScope scope) { return new LinkedFlowScope(HamtPMap.<TypedScope, OverlayScope>empty(), scope, scope); }
java
public static LinkedFlowScope createEntryLattice(TypedScope scope) { return new LinkedFlowScope(HamtPMap.<TypedScope, OverlayScope>empty(), scope, scope); }
[ "public", "static", "LinkedFlowScope", "createEntryLattice", "(", "TypedScope", "scope", ")", "{", "return", "new", "LinkedFlowScope", "(", "HamtPMap", ".", "<", "TypedScope", ",", "OverlayScope", ">", "empty", "(", ")", ",", "scope", ",", "scope", ")", ";", "}" ]
Creates an entry lattice for the flow.
[ "Creates", "an", "entry", "lattice", "for", "the", "flow", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/LinkedFlowScope.java#L98-L100
24,690
google/closure-compiler
src/com/google/javascript/jscomp/LinkedFlowScope.java
LinkedFlowScope.getSlot
@Override public StaticTypedSlot getSlot(String name) { OverlayScope scope = getOverlayScopeForVar(name, false); return scope != null ? scope.getSlot(name) : syntacticScope.getSlot(name); }
java
@Override public StaticTypedSlot getSlot(String name) { OverlayScope scope = getOverlayScopeForVar(name, false); return scope != null ? scope.getSlot(name) : syntacticScope.getSlot(name); }
[ "@", "Override", "public", "StaticTypedSlot", "getSlot", "(", "String", "name", ")", "{", "OverlayScope", "scope", "=", "getOverlayScopeForVar", "(", "name", ",", "false", ")", ";", "return", "scope", "!=", "null", "?", "scope", ".", "getSlot", "(", "name", ")", ":", "syntacticScope", ".", "getSlot", "(", "name", ")", ";", "}" ]
Get the slot for the given symbol.
[ "Get", "the", "slot", "for", "the", "given", "symbol", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/LinkedFlowScope.java#L175-L179
24,691
google/closure-compiler
src/com/google/javascript/jscomp/LinkedFlowScope.java
LinkedFlowScope.equalSlots
private static boolean equalSlots(StaticTypedSlot slotA, StaticTypedSlot slotB) { return slotA == slotB || !slotA.getType().differsFrom(slotB.getType()); }
java
private static boolean equalSlots(StaticTypedSlot slotA, StaticTypedSlot slotB) { return slotA == slotB || !slotA.getType().differsFrom(slotB.getType()); }
[ "private", "static", "boolean", "equalSlots", "(", "StaticTypedSlot", "slotA", ",", "StaticTypedSlot", "slotB", ")", "{", "return", "slotA", "==", "slotB", "||", "!", "slotA", ".", "getType", "(", ")", ".", "differsFrom", "(", "slotB", ".", "getType", "(", ")", ")", ";", "}" ]
Determines whether two slots are meaningfully different for the purposes of data flow analysis.
[ "Determines", "whether", "two", "slots", "are", "meaningfully", "different", "for", "the", "purposes", "of", "data", "flow", "analysis", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/LinkedFlowScope.java#L302-L304
24,692
google/closure-compiler
src/com/google/javascript/jscomp/PerformanceTracker.java
PerformanceTracker.updateAfterDeserialize
void updateAfterDeserialize(Node jsRoot) { // TODO(bradfordcsmith): Restore line counts for inputs and externs. this.jsRoot = jsRoot; if (!tracksAstSize()) { return; } this.initAstSize = this.astSize = NodeUtil.countAstSize(this.jsRoot); if (!tracksSize()) { return; } PerformanceTrackerCodeSizeEstimator estimator = PerformanceTrackerCodeSizeEstimator.estimate(this.jsRoot, tracksGzSize()); this.initCodeSize = this.codeSize = estimator.getCodeSize(); if (tracksGzSize()) { this.initGzCodeSize = this.gzCodeSize = estimator.getZippedCodeSize(); } }
java
void updateAfterDeserialize(Node jsRoot) { // TODO(bradfordcsmith): Restore line counts for inputs and externs. this.jsRoot = jsRoot; if (!tracksAstSize()) { return; } this.initAstSize = this.astSize = NodeUtil.countAstSize(this.jsRoot); if (!tracksSize()) { return; } PerformanceTrackerCodeSizeEstimator estimator = PerformanceTrackerCodeSizeEstimator.estimate(this.jsRoot, tracksGzSize()); this.initCodeSize = this.codeSize = estimator.getCodeSize(); if (tracksGzSize()) { this.initGzCodeSize = this.gzCodeSize = estimator.getZippedCodeSize(); } }
[ "void", "updateAfterDeserialize", "(", "Node", "jsRoot", ")", "{", "// TODO(bradfordcsmith): Restore line counts for inputs and externs.", "this", ".", "jsRoot", "=", "jsRoot", ";", "if", "(", "!", "tracksAstSize", "(", ")", ")", "{", "return", ";", "}", "this", ".", "initAstSize", "=", "this", ".", "astSize", "=", "NodeUtil", ".", "countAstSize", "(", "this", ".", "jsRoot", ")", ";", "if", "(", "!", "tracksSize", "(", ")", ")", "{", "return", ";", "}", "PerformanceTrackerCodeSizeEstimator", "estimator", "=", "PerformanceTrackerCodeSizeEstimator", ".", "estimate", "(", "this", ".", "jsRoot", ",", "tracksGzSize", "(", ")", ")", ";", "this", ".", "initCodeSize", "=", "this", ".", "codeSize", "=", "estimator", ".", "getCodeSize", "(", ")", ";", "if", "(", "tracksGzSize", "(", ")", ")", "{", "this", ".", "initGzCodeSize", "=", "this", ".", "gzCodeSize", "=", "estimator", ".", "getZippedCodeSize", "(", ")", ";", "}", "}" ]
Updates the saved jsRoot and resets the size tracking fields accordingly. @param jsRoot
[ "Updates", "the", "saved", "jsRoot", "and", "resets", "the", "size", "tracking", "fields", "accordingly", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PerformanceTracker.java#L125-L141
24,693
google/closure-compiler
src/com/google/javascript/jscomp/PerformanceTracker.java
PerformanceTracker.recordPassStop
void recordPassStop(String passName, long runtime) { int allocMem = getAllocatedMegabytes(); Stats logStats = this.currentPass.pop(); checkState(passName.equals(logStats.pass)); this.log.add(logStats); // Update fields that aren't related to code size logStats.runtime = runtime; logStats.allocMem = allocMem; logStats.runs = 1; if (this.codeChange.hasCodeChanged()) { logStats.changes = 1; } if (passName.equals(PassNames.PARSE_INPUTS)) { recordParsingStop(logStats); } else if (this.codeChange.hasCodeChanged() && tracksAstSize()) { recordOtherPassStop(logStats); } }
java
void recordPassStop(String passName, long runtime) { int allocMem = getAllocatedMegabytes(); Stats logStats = this.currentPass.pop(); checkState(passName.equals(logStats.pass)); this.log.add(logStats); // Update fields that aren't related to code size logStats.runtime = runtime; logStats.allocMem = allocMem; logStats.runs = 1; if (this.codeChange.hasCodeChanged()) { logStats.changes = 1; } if (passName.equals(PassNames.PARSE_INPUTS)) { recordParsingStop(logStats); } else if (this.codeChange.hasCodeChanged() && tracksAstSize()) { recordOtherPassStop(logStats); } }
[ "void", "recordPassStop", "(", "String", "passName", ",", "long", "runtime", ")", "{", "int", "allocMem", "=", "getAllocatedMegabytes", "(", ")", ";", "Stats", "logStats", "=", "this", ".", "currentPass", ".", "pop", "(", ")", ";", "checkState", "(", "passName", ".", "equals", "(", "logStats", ".", "pass", ")", ")", ";", "this", ".", "log", ".", "add", "(", "logStats", ")", ";", "// Update fields that aren't related to code size", "logStats", ".", "runtime", "=", "runtime", ";", "logStats", ".", "allocMem", "=", "allocMem", ";", "logStats", ".", "runs", "=", "1", ";", "if", "(", "this", ".", "codeChange", ".", "hasCodeChanged", "(", ")", ")", "{", "logStats", ".", "changes", "=", "1", ";", "}", "if", "(", "passName", ".", "equals", "(", "PassNames", ".", "PARSE_INPUTS", ")", ")", "{", "recordParsingStop", "(", "logStats", ")", ";", "}", "else", "if", "(", "this", ".", "codeChange", ".", "hasCodeChanged", "(", ")", "&&", "tracksAstSize", "(", ")", ")", "{", "recordOtherPassStop", "(", "logStats", ")", ";", "}", "}" ]
Collects information about a pass P after P finishes running, eg, how much time P took and what was its impact on code size. @param passName short name of the pass @param runtime execution time in milliseconds
[ "Collects", "information", "about", "a", "pass", "P", "after", "P", "finishes", "running", "eg", "how", "much", "time", "P", "took", "and", "what", "was", "its", "impact", "on", "code", "size", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PerformanceTracker.java#L150-L168
24,694
google/closure-compiler
src/com/google/javascript/jscomp/deps/DependencyFile.java
DependencyFile.loadGraph
private void loadGraph() throws ServiceException { dependencies.clear(); logger.info("Loading dependency graph"); // Parse the deps.js file. ErrorManager errorManager = new LoggerErrorManager(logger); DepsFileParser parser = new DepsFileParser(errorManager); List<DependencyInfo> depInfos = parser.parseFile(getName(), getContent()); // Ensure the parse succeeded. if (!parser.didParseSucceed()) { throw new ServiceException("Problem parsing " + getName() + ". See logs for details."); } // Incorporate the dependencies into our maps. for (DependencyInfo depInfo : depInfos) { for (String provide : depInfo.getProvides()) { DependencyInfo existing = dependencies.get(provide); if (existing != null && !existing.equals(depInfo)) { throw new ServiceException("Duplicate provide of " + provide + ". Was provided by " + existing.getPathRelativeToClosureBase() + " and " + depInfo.getPathRelativeToClosureBase()); } dependencies.put(provide, depInfo); } } List<String> provides = new ArrayList<>(); provides.add(CLOSURE_BASE_PROVIDE); // Add implicit base.js entry. dependencies.put( CLOSURE_BASE_PROVIDE, SimpleDependencyInfo.builder(CLOSURE_BASE, CLOSURE_BASE).setProvides(provides).build()); errorManager.generateReport(); logger.info("Dependencies loaded"); }
java
private void loadGraph() throws ServiceException { dependencies.clear(); logger.info("Loading dependency graph"); // Parse the deps.js file. ErrorManager errorManager = new LoggerErrorManager(logger); DepsFileParser parser = new DepsFileParser(errorManager); List<DependencyInfo> depInfos = parser.parseFile(getName(), getContent()); // Ensure the parse succeeded. if (!parser.didParseSucceed()) { throw new ServiceException("Problem parsing " + getName() + ". See logs for details."); } // Incorporate the dependencies into our maps. for (DependencyInfo depInfo : depInfos) { for (String provide : depInfo.getProvides()) { DependencyInfo existing = dependencies.get(provide); if (existing != null && !existing.equals(depInfo)) { throw new ServiceException("Duplicate provide of " + provide + ". Was provided by " + existing.getPathRelativeToClosureBase() + " and " + depInfo.getPathRelativeToClosureBase()); } dependencies.put(provide, depInfo); } } List<String> provides = new ArrayList<>(); provides.add(CLOSURE_BASE_PROVIDE); // Add implicit base.js entry. dependencies.put( CLOSURE_BASE_PROVIDE, SimpleDependencyInfo.builder(CLOSURE_BASE, CLOSURE_BASE).setProvides(provides).build()); errorManager.generateReport(); logger.info("Dependencies loaded"); }
[ "private", "void", "loadGraph", "(", ")", "throws", "ServiceException", "{", "dependencies", ".", "clear", "(", ")", ";", "logger", ".", "info", "(", "\"Loading dependency graph\"", ")", ";", "// Parse the deps.js file.", "ErrorManager", "errorManager", "=", "new", "LoggerErrorManager", "(", "logger", ")", ";", "DepsFileParser", "parser", "=", "new", "DepsFileParser", "(", "errorManager", ")", ";", "List", "<", "DependencyInfo", ">", "depInfos", "=", "parser", ".", "parseFile", "(", "getName", "(", ")", ",", "getContent", "(", ")", ")", ";", "// Ensure the parse succeeded.", "if", "(", "!", "parser", ".", "didParseSucceed", "(", ")", ")", "{", "throw", "new", "ServiceException", "(", "\"Problem parsing \"", "+", "getName", "(", ")", "+", "\". See logs for details.\"", ")", ";", "}", "// Incorporate the dependencies into our maps.", "for", "(", "DependencyInfo", "depInfo", ":", "depInfos", ")", "{", "for", "(", "String", "provide", ":", "depInfo", ".", "getProvides", "(", ")", ")", "{", "DependencyInfo", "existing", "=", "dependencies", ".", "get", "(", "provide", ")", ";", "if", "(", "existing", "!=", "null", "&&", "!", "existing", ".", "equals", "(", "depInfo", ")", ")", "{", "throw", "new", "ServiceException", "(", "\"Duplicate provide of \"", "+", "provide", "+", "\". Was provided by \"", "+", "existing", ".", "getPathRelativeToClosureBase", "(", ")", "+", "\" and \"", "+", "depInfo", ".", "getPathRelativeToClosureBase", "(", ")", ")", ";", "}", "dependencies", ".", "put", "(", "provide", ",", "depInfo", ")", ";", "}", "}", "List", "<", "String", ">", "provides", "=", "new", "ArrayList", "<>", "(", ")", ";", "provides", ".", "add", "(", "CLOSURE_BASE_PROVIDE", ")", ";", "// Add implicit base.js entry.", "dependencies", ".", "put", "(", "CLOSURE_BASE_PROVIDE", ",", "SimpleDependencyInfo", ".", "builder", "(", "CLOSURE_BASE", ",", "CLOSURE_BASE", ")", ".", "setProvides", "(", "provides", ")", ".", "build", "(", ")", ")", ";", "errorManager", ".", "generateReport", "(", ")", ";", "logger", ".", "info", "(", "\"Dependencies loaded\"", ")", ";", "}" ]
Loads the dependency graph.
[ "Loads", "the", "dependency", "graph", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DependencyFile.java#L85-L125
24,695
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createIf
Node createIf(Node cond, Node then) { return IR.ifNode(cond, then); }
java
Node createIf(Node cond, Node then) { return IR.ifNode(cond, then); }
[ "Node", "createIf", "(", "Node", "cond", ",", "Node", "then", ")", "{", "return", "IR", ".", "ifNode", "(", "cond", ",", "then", ")", ";", "}" ]
Returns a new IF node. <p>Blocks have no type information, so this is functionally the same as calling {@code IR.ifNode(cond, then)}. It exists so that a pass can be consistent about always using {@code AstFactory} to create new nodes.
[ "Returns", "a", "new", "IF", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L132-L134
24,696
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createFor
Node createFor(Node init, Node cond, Node incr, Node body) { return IR.forNode(init, cond, incr, body); }
java
Node createFor(Node init, Node cond, Node incr, Node body) { return IR.forNode(init, cond, incr, body); }
[ "Node", "createFor", "(", "Node", "init", ",", "Node", "cond", ",", "Node", "incr", ",", "Node", "body", ")", "{", "return", "IR", ".", "forNode", "(", "init", ",", "cond", ",", "incr", ",", "body", ")", ";", "}" ]
Returns a new FOR node. <p>Blocks have no type information, so this is functionally the same as calling {@code IR.forNode(init, cond, incr, body)}. It exists so that a pass can be consistent about always using {@code AstFactory} to create new nodes.
[ "Returns", "a", "new", "FOR", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L154-L156
24,697
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createThisForFunction
Node createThisForFunction(Node functionNode) { final Node result = IR.thisNode(); if (isAddingTypes()) { result.setJSType(getTypeOfThisForFunctionNode(functionNode)); } return result; }
java
Node createThisForFunction(Node functionNode) { final Node result = IR.thisNode(); if (isAddingTypes()) { result.setJSType(getTypeOfThisForFunctionNode(functionNode)); } return result; }
[ "Node", "createThisForFunction", "(", "Node", "functionNode", ")", "{", "final", "Node", "result", "=", "IR", ".", "thisNode", "(", ")", ";", "if", "(", "isAddingTypes", "(", ")", ")", "{", "result", ".", "setJSType", "(", "getTypeOfThisForFunctionNode", "(", "functionNode", ")", ")", ";", "}", "return", "result", ";", "}" ]
Creates a THIS node with the correct type for the given function node.
[ "Creates", "a", "THIS", "node", "with", "the", "correct", "type", "for", "the", "given", "function", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L257-L263
24,698
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createSuperForFunction
Node createSuperForFunction(Node functionNode) { final Node result = IR.superNode(); if (isAddingTypes()) { result.setJSType(getTypeOfSuperForFunctionNode(functionNode)); } return result; }
java
Node createSuperForFunction(Node functionNode) { final Node result = IR.superNode(); if (isAddingTypes()) { result.setJSType(getTypeOfSuperForFunctionNode(functionNode)); } return result; }
[ "Node", "createSuperForFunction", "(", "Node", "functionNode", ")", "{", "final", "Node", "result", "=", "IR", ".", "superNode", "(", ")", ";", "if", "(", "isAddingTypes", "(", ")", ")", "{", "result", ".", "setJSType", "(", "getTypeOfSuperForFunctionNode", "(", "functionNode", ")", ")", ";", "}", "return", "result", ";", "}" ]
Creates a SUPER node with the correct type for the given function node.
[ "Creates", "a", "SUPER", "node", "with", "the", "correct", "type", "for", "the", "given", "function", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L266-L272
24,699
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createThisAliasReferenceForFunction
Node createThisAliasReferenceForFunction(String aliasName, Node functionNode) { final Node result = IR.name(aliasName); if (isAddingTypes()) { result.setJSType(getTypeOfThisForFunctionNode(functionNode)); } return result; }
java
Node createThisAliasReferenceForFunction(String aliasName, Node functionNode) { final Node result = IR.name(aliasName); if (isAddingTypes()) { result.setJSType(getTypeOfThisForFunctionNode(functionNode)); } return result; }
[ "Node", "createThisAliasReferenceForFunction", "(", "String", "aliasName", ",", "Node", "functionNode", ")", "{", "final", "Node", "result", "=", "IR", ".", "name", "(", "aliasName", ")", ";", "if", "(", "isAddingTypes", "(", ")", ")", "{", "result", ".", "setJSType", "(", "getTypeOfThisForFunctionNode", "(", "functionNode", ")", ")", ";", "}", "return", "result", ";", "}" ]
Creates a NAME node having the type of "this" appropriate for the given function node.
[ "Creates", "a", "NAME", "node", "having", "the", "type", "of", "this", "appropriate", "for", "the", "given", "function", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L309-L315