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,700
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createThisAliasDeclarationForFunction
Node createThisAliasDeclarationForFunction(String aliasName, Node functionNode) { return createSingleConstNameDeclaration( aliasName, createThis(getTypeOfThisForFunctionNode(functionNode))); }
java
Node createThisAliasDeclarationForFunction(String aliasName, Node functionNode) { return createSingleConstNameDeclaration( aliasName, createThis(getTypeOfThisForFunctionNode(functionNode))); }
[ "Node", "createThisAliasDeclarationForFunction", "(", "String", "aliasName", ",", "Node", "functionNode", ")", "{", "return", "createSingleConstNameDeclaration", "(", "aliasName", ",", "createThis", "(", "getTypeOfThisForFunctionNode", "(", "functionNode", ")", ")", ")", ";", "}" ]
Creates a statement declaring a const alias for "this" to be used in the given function node. <p>e.g. `const aliasName = this;`
[ "Creates", "a", "statement", "declaring", "a", "const", "alias", "for", "this", "to", "be", "used", "in", "the", "given", "function", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L322-L325
24,701
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createSingleConstNameDeclaration
Node createSingleConstNameDeclaration(String variableName, Node value) { return IR.constNode(createName(variableName, value.getJSType()), value); }
java
Node createSingleConstNameDeclaration(String variableName, Node value) { return IR.constNode(createName(variableName, value.getJSType()), value); }
[ "Node", "createSingleConstNameDeclaration", "(", "String", "variableName", ",", "Node", "value", ")", "{", "return", "IR", ".", "constNode", "(", "createName", "(", "variableName", ",", "value", ".", "getJSType", "(", ")", ")", ",", "value", ")", ";", "}" ]
Creates a new `const` declaration statement for a single variable name. <p>Takes the type for the variable name from the value node. <p>e.g. `const variableName = value;`
[ "Creates", "a", "new", "const", "declaration", "statement", "for", "a", "single", "variable", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L334-L336
24,702
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createArgumentsReference
Node createArgumentsReference() { Node result = IR.name("arguments"); if (isAddingTypes()) { result.setJSType(argumentsTypeSupplier.get()); } return result; }
java
Node createArgumentsReference() { Node result = IR.name("arguments"); if (isAddingTypes()) { result.setJSType(argumentsTypeSupplier.get()); } return result; }
[ "Node", "createArgumentsReference", "(", ")", "{", "Node", "result", "=", "IR", ".", "name", "(", "\"arguments\"", ")", ";", "if", "(", "isAddingTypes", "(", ")", ")", "{", "result", ".", "setJSType", "(", "argumentsTypeSupplier", ".", "get", "(", ")", ")", ";", "}", "return", "result", ";", "}" ]
Creates a reference to "arguments" with the type specified in externs, or unknown if the externs for it weren't included.
[ "Creates", "a", "reference", "to", "arguments", "with", "the", "type", "specified", "in", "externs", "or", "unknown", "if", "the", "externs", "for", "it", "weren", "t", "included", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L342-L348
24,703
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createObjectDotAssignCall
Node createObjectDotAssignCall(Scope scope, JSType returnType, Node... args) { Node objAssign = createQName(scope, "Object.assign"); Node result = createCall(objAssign, args); if (isAddingTypes()) { // Make a unique function type that returns the exact type we've inferred it to be. // Object.assign in the externs just returns !Object, which loses type information. JSType objAssignType = registry.createFunctionTypeWithVarArgs( returnType, registry.getNativeType(JSTypeNative.OBJECT_TYPE), registry.createUnionType(JSTypeNative.OBJECT_TYPE, JSTypeNative.NULL_TYPE)); objAssign.setJSType(objAssignType); result.setJSType(returnType); } return result; }
java
Node createObjectDotAssignCall(Scope scope, JSType returnType, Node... args) { Node objAssign = createQName(scope, "Object.assign"); Node result = createCall(objAssign, args); if (isAddingTypes()) { // Make a unique function type that returns the exact type we've inferred it to be. // Object.assign in the externs just returns !Object, which loses type information. JSType objAssignType = registry.createFunctionTypeWithVarArgs( returnType, registry.getNativeType(JSTypeNative.OBJECT_TYPE), registry.createUnionType(JSTypeNative.OBJECT_TYPE, JSTypeNative.NULL_TYPE)); objAssign.setJSType(objAssignType); result.setJSType(returnType); } return result; }
[ "Node", "createObjectDotAssignCall", "(", "Scope", "scope", ",", "JSType", "returnType", ",", "Node", "...", "args", ")", "{", "Node", "objAssign", "=", "createQName", "(", "scope", ",", "\"Object.assign\"", ")", ";", "Node", "result", "=", "createCall", "(", "objAssign", ",", "args", ")", ";", "if", "(", "isAddingTypes", "(", ")", ")", "{", "// Make a unique function type that returns the exact type we've inferred it to be.", "// Object.assign in the externs just returns !Object, which loses type information.", "JSType", "objAssignType", "=", "registry", ".", "createFunctionTypeWithVarArgs", "(", "returnType", ",", "registry", ".", "getNativeType", "(", "JSTypeNative", ".", "OBJECT_TYPE", ")", ",", "registry", ".", "createUnionType", "(", "JSTypeNative", ".", "OBJECT_TYPE", ",", "JSTypeNative", ".", "NULL_TYPE", ")", ")", ";", "objAssign", ".", "setJSType", "(", "objAssignType", ")", ";", "result", ".", "setJSType", "(", "returnType", ")", ";", "}", "return", "result", ";", "}" ]
Creates a call to Object.assign that returns the specified type. <p>Object.assign returns !Object in the externs, which can lose type information if the actual type is known.
[ "Creates", "a", "call", "to", "Object", ".", "assign", "that", "returns", "the", "specified", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L572-L589
24,704
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createAssignStatement
Node createAssignStatement(Node lhs, Node rhs) { return exprResult(createAssign(lhs, rhs)); }
java
Node createAssignStatement(Node lhs, Node rhs) { return exprResult(createAssign(lhs, rhs)); }
[ "Node", "createAssignStatement", "(", "Node", "lhs", ",", "Node", "rhs", ")", "{", "return", "exprResult", "(", "createAssign", "(", "lhs", ",", "rhs", ")", ")", ";", "}" ]
Creates a statement `lhs = rhs;`.
[ "Creates", "a", "statement", "lhs", "=", "rhs", ";", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L652-L654
24,705
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createAssign
Node createAssign(Node lhs, Node rhs) { Node result = IR.assign(lhs, rhs); if (isAddingTypes()) { result.setJSType(rhs.getJSType()); } return result; }
java
Node createAssign(Node lhs, Node rhs) { Node result = IR.assign(lhs, rhs); if (isAddingTypes()) { result.setJSType(rhs.getJSType()); } return result; }
[ "Node", "createAssign", "(", "Node", "lhs", ",", "Node", "rhs", ")", "{", "Node", "result", "=", "IR", ".", "assign", "(", "lhs", ",", "rhs", ")", ";", "if", "(", "isAddingTypes", "(", ")", ")", "{", "result", ".", "setJSType", "(", "rhs", ".", "getJSType", "(", ")", ")", ";", "}", "return", "result", ";", "}" ]
Creates an assignment expression `lhs = rhs`
[ "Creates", "an", "assignment", "expression", "lhs", "=", "rhs" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L657-L663
24,706
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.getVarNameType
private JSType getVarNameType(Scope scope, String name) { Var var = scope.getVar(name); JSType type = null; if (var != null) { Node nameDefinitionNode = var.getNode(); if (nameDefinitionNode != null) { type = nameDefinitionNode.getJSType(); } } if (type == null) { // TODO(bradfordcsmith): Consider throwing an error if the type cannot be found. type = unknownType; } return type; }
java
private JSType getVarNameType(Scope scope, String name) { Var var = scope.getVar(name); JSType type = null; if (var != null) { Node nameDefinitionNode = var.getNode(); if (nameDefinitionNode != null) { type = nameDefinitionNode.getJSType(); } } if (type == null) { // TODO(bradfordcsmith): Consider throwing an error if the type cannot be found. type = unknownType; } return type; }
[ "private", "JSType", "getVarNameType", "(", "Scope", "scope", ",", "String", "name", ")", "{", "Var", "var", "=", "scope", ".", "getVar", "(", "name", ")", ";", "JSType", "type", "=", "null", ";", "if", "(", "var", "!=", "null", ")", "{", "Node", "nameDefinitionNode", "=", "var", ".", "getNode", "(", ")", ";", "if", "(", "nameDefinitionNode", "!=", "null", ")", "{", "type", "=", "nameDefinitionNode", ".", "getJSType", "(", ")", ";", "}", "}", "if", "(", "type", "==", "null", ")", "{", "// TODO(bradfordcsmith): Consider throwing an error if the type cannot be found.", "type", "=", "unknownType", ";", "}", "return", "type", ";", "}" ]
Look up the correct type for the given name in the given scope. <p>Returns the unknown type if no type can be found
[ "Look", "up", "the", "correct", "type", "for", "the", "given", "name", "in", "the", "given", "scope", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L978-L992
24,707
google/closure-compiler
src/com/google/javascript/jscomp/SideEffectsAnalysis.java
SideEffectsAnalysis.nodesHaveSameControlFlow
private static boolean nodesHaveSameControlFlow(Node node1, Node node2) { /* * We conservatively approximate this with the following criteria: * * Define the "deepest control dependent block" for a node to be the * closest ancestor whose *parent* is a control structure and where that * ancestor may or may be executed depending on the parent. * * So, for example, in: * if (a) { * b; * } else { * c; * } * * a has not deepest control dependent block. * b's deepest control dependent block is the "then" block of the IF. * c's deepest control dependent block is the "else" block of the IF. * * We'll say two nodes have the same control flow if * * 1) they have the same deepest control dependent block * 2) that block is either a CASE (which can't have early exits) or it * doesn't have any early exits (e.g. breaks, continues, returns.) * */ Node node1DeepestControlDependentBlock = closestControlDependentAncestor(node1); Node node2DeepestControlDependentBlock = closestControlDependentAncestor(node2); if (node1DeepestControlDependentBlock == node2DeepestControlDependentBlock) { if (node2DeepestControlDependentBlock != null) { // CASE is complicated because we have to deal with fall through and // because some BREAKs are early exits and some are not. // For now, we don't allow movement within a CASE. // // TODO(dcc): be less conservative about movement within CASE if (node2DeepestControlDependentBlock.isCase()) { return false; } // Don't allow breaks, continues, returns in control dependent // block because we don't actually create a control-flow graph // and so don't know if early exits site between the source // and the destination. // // This is overly conservative as it doesn't allow, for example, // moving in the following case: // while (a) { // source(); // // while(b) { // break; // } // // destination(); // } // // To fully support this kind of movement, we'll probably have to use // a CFG-based analysis rather than just looking at the AST. // // TODO(dcc): have nodesHaveSameControlFlow() use a CFG Predicate<Node> isEarlyExitPredicate = new Predicate<Node>() { @Override public boolean apply(Node input) { Token nodeType = input.getToken(); return nodeType == Token.RETURN || nodeType == Token.BREAK || nodeType == Token.CONTINUE; } }; return !NodeUtil.has(node2DeepestControlDependentBlock, isEarlyExitPredicate, NOT_FUNCTION_PREDICATE); } else { return true; } } else { return false; } }
java
private static boolean nodesHaveSameControlFlow(Node node1, Node node2) { /* * We conservatively approximate this with the following criteria: * * Define the "deepest control dependent block" for a node to be the * closest ancestor whose *parent* is a control structure and where that * ancestor may or may be executed depending on the parent. * * So, for example, in: * if (a) { * b; * } else { * c; * } * * a has not deepest control dependent block. * b's deepest control dependent block is the "then" block of the IF. * c's deepest control dependent block is the "else" block of the IF. * * We'll say two nodes have the same control flow if * * 1) they have the same deepest control dependent block * 2) that block is either a CASE (which can't have early exits) or it * doesn't have any early exits (e.g. breaks, continues, returns.) * */ Node node1DeepestControlDependentBlock = closestControlDependentAncestor(node1); Node node2DeepestControlDependentBlock = closestControlDependentAncestor(node2); if (node1DeepestControlDependentBlock == node2DeepestControlDependentBlock) { if (node2DeepestControlDependentBlock != null) { // CASE is complicated because we have to deal with fall through and // because some BREAKs are early exits and some are not. // For now, we don't allow movement within a CASE. // // TODO(dcc): be less conservative about movement within CASE if (node2DeepestControlDependentBlock.isCase()) { return false; } // Don't allow breaks, continues, returns in control dependent // block because we don't actually create a control-flow graph // and so don't know if early exits site between the source // and the destination. // // This is overly conservative as it doesn't allow, for example, // moving in the following case: // while (a) { // source(); // // while(b) { // break; // } // // destination(); // } // // To fully support this kind of movement, we'll probably have to use // a CFG-based analysis rather than just looking at the AST. // // TODO(dcc): have nodesHaveSameControlFlow() use a CFG Predicate<Node> isEarlyExitPredicate = new Predicate<Node>() { @Override public boolean apply(Node input) { Token nodeType = input.getToken(); return nodeType == Token.RETURN || nodeType == Token.BREAK || nodeType == Token.CONTINUE; } }; return !NodeUtil.has(node2DeepestControlDependentBlock, isEarlyExitPredicate, NOT_FUNCTION_PREDICATE); } else { return true; } } else { return false; } }
[ "private", "static", "boolean", "nodesHaveSameControlFlow", "(", "Node", "node1", ",", "Node", "node2", ")", "{", "/*\n * We conservatively approximate this with the following criteria:\n *\n * Define the \"deepest control dependent block\" for a node to be the\n * closest ancestor whose *parent* is a control structure and where that\n * ancestor may or may be executed depending on the parent.\n *\n * So, for example, in:\n * if (a) {\n * b;\n * } else {\n * c;\n * }\n *\n * a has not deepest control dependent block.\n * b's deepest control dependent block is the \"then\" block of the IF.\n * c's deepest control dependent block is the \"else\" block of the IF.\n *\n * We'll say two nodes have the same control flow if\n *\n * 1) they have the same deepest control dependent block\n * 2) that block is either a CASE (which can't have early exits) or it\n * doesn't have any early exits (e.g. breaks, continues, returns.)\n *\n */", "Node", "node1DeepestControlDependentBlock", "=", "closestControlDependentAncestor", "(", "node1", ")", ";", "Node", "node2DeepestControlDependentBlock", "=", "closestControlDependentAncestor", "(", "node2", ")", ";", "if", "(", "node1DeepestControlDependentBlock", "==", "node2DeepestControlDependentBlock", ")", "{", "if", "(", "node2DeepestControlDependentBlock", "!=", "null", ")", "{", "// CASE is complicated because we have to deal with fall through and", "// because some BREAKs are early exits and some are not.", "// For now, we don't allow movement within a CASE.", "//", "// TODO(dcc): be less conservative about movement within CASE", "if", "(", "node2DeepestControlDependentBlock", ".", "isCase", "(", ")", ")", "{", "return", "false", ";", "}", "// Don't allow breaks, continues, returns in control dependent", "// block because we don't actually create a control-flow graph", "// and so don't know if early exits site between the source", "// and the destination.", "//", "// This is overly conservative as it doesn't allow, for example,", "// moving in the following case:", "// while (a) {", "// source();", "//", "// while(b) {", "// break;", "// }", "//", "// destination();", "// }", "//", "// To fully support this kind of movement, we'll probably have to use", "// a CFG-based analysis rather than just looking at the AST.", "//", "// TODO(dcc): have nodesHaveSameControlFlow() use a CFG", "Predicate", "<", "Node", ">", "isEarlyExitPredicate", "=", "new", "Predicate", "<", "Node", ">", "(", ")", "{", "@", "Override", "public", "boolean", "apply", "(", "Node", "input", ")", "{", "Token", "nodeType", "=", "input", ".", "getToken", "(", ")", ";", "return", "nodeType", "==", "Token", ".", "RETURN", "||", "nodeType", "==", "Token", ".", "BREAK", "||", "nodeType", "==", "Token", ".", "CONTINUE", ";", "}", "}", ";", "return", "!", "NodeUtil", ".", "has", "(", "node2DeepestControlDependentBlock", ",", "isEarlyExitPredicate", ",", "NOT_FUNCTION_PREDICATE", ")", ";", "}", "else", "{", "return", "true", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}" ]
Returns true if the two nodes have the same control flow properties, that is, is node1 be executed every time node2 is executed and vice versa?
[ "Returns", "true", "if", "the", "two", "nodes", "have", "the", "same", "control", "flow", "properties", "that", "is", "is", "node1", "be", "executed", "every", "time", "node2", "is", "executed", "and", "vice", "versa?" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SideEffectsAnalysis.java#L227-L314
24,708
google/closure-compiler
src/com/google/javascript/jscomp/SideEffectsAnalysis.java
SideEffectsAnalysis.isControlDependentChild
private static boolean isControlDependentChild(Node child) { Node parent = child.getParent(); if (parent == null) { return false; } ArrayList<Node> siblings = new ArrayList<>(); Iterables.addAll(siblings, parent.children()); int indexOfChildInParent = siblings.indexOf(child); switch (parent.getToken()) { case IF: case HOOK: return (indexOfChildInParent == 1 || indexOfChildInParent == 2); case FOR: case FOR_IN: // Only initializer is not control dependent return indexOfChildInParent != 0; case SWITCH: return indexOfChildInParent > 0; case WHILE: case DO: case AND: case OR: case FUNCTION: return true; default: return false; } }
java
private static boolean isControlDependentChild(Node child) { Node parent = child.getParent(); if (parent == null) { return false; } ArrayList<Node> siblings = new ArrayList<>(); Iterables.addAll(siblings, parent.children()); int indexOfChildInParent = siblings.indexOf(child); switch (parent.getToken()) { case IF: case HOOK: return (indexOfChildInParent == 1 || indexOfChildInParent == 2); case FOR: case FOR_IN: // Only initializer is not control dependent return indexOfChildInParent != 0; case SWITCH: return indexOfChildInParent > 0; case WHILE: case DO: case AND: case OR: case FUNCTION: return true; default: return false; } }
[ "private", "static", "boolean", "isControlDependentChild", "(", "Node", "child", ")", "{", "Node", "parent", "=", "child", ".", "getParent", "(", ")", ";", "if", "(", "parent", "==", "null", ")", "{", "return", "false", ";", "}", "ArrayList", "<", "Node", ">", "siblings", "=", "new", "ArrayList", "<>", "(", ")", ";", "Iterables", ".", "addAll", "(", "siblings", ",", "parent", ".", "children", "(", ")", ")", ";", "int", "indexOfChildInParent", "=", "siblings", ".", "indexOf", "(", "child", ")", ";", "switch", "(", "parent", ".", "getToken", "(", ")", ")", "{", "case", "IF", ":", "case", "HOOK", ":", "return", "(", "indexOfChildInParent", "==", "1", "||", "indexOfChildInParent", "==", "2", ")", ";", "case", "FOR", ":", "case", "FOR_IN", ":", "// Only initializer is not control dependent", "return", "indexOfChildInParent", "!=", "0", ";", "case", "SWITCH", ":", "return", "indexOfChildInParent", ">", "0", ";", "case", "WHILE", ":", "case", "DO", ":", "case", "AND", ":", "case", "OR", ":", "case", "FUNCTION", ":", "return", "true", ";", "default", ":", "return", "false", ";", "}", "}" ]
Returns true if the number of times the child executes depends on the parent. For example, the guard of an IF is not control dependent on the IF, but its two THEN/ELSE blocks are. Also, the guard of WHILE and DO are control dependent on the parent since the number of times it executes depends on the parent.
[ "Returns", "true", "if", "the", "number", "of", "times", "the", "child", "executes", "depends", "on", "the", "parent", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SideEffectsAnalysis.java#L326-L358
24,709
google/closure-compiler
src/com/google/javascript/jscomp/SideEffectsAnalysis.java
SideEffectsAnalysis.nodeHasCall
private static boolean nodeHasCall(Node node) { return NodeUtil.has(node, new Predicate<Node>() { @Override public boolean apply(Node input) { return input.isCall() || input.isNew() || input.isTaggedTemplateLit(); }}, NOT_FUNCTION_PREDICATE); }
java
private static boolean nodeHasCall(Node node) { return NodeUtil.has(node, new Predicate<Node>() { @Override public boolean apply(Node input) { return input.isCall() || input.isNew() || input.isTaggedTemplateLit(); }}, NOT_FUNCTION_PREDICATE); }
[ "private", "static", "boolean", "nodeHasCall", "(", "Node", "node", ")", "{", "return", "NodeUtil", ".", "has", "(", "node", ",", "new", "Predicate", "<", "Node", ">", "(", ")", "{", "@", "Override", "public", "boolean", "apply", "(", "Node", "input", ")", "{", "return", "input", ".", "isCall", "(", ")", "||", "input", ".", "isNew", "(", ")", "||", "input", ".", "isTaggedTemplateLit", "(", ")", ";", "}", "}", ",", "NOT_FUNCTION_PREDICATE", ")", ";", "}" ]
Returns true if a node has a CALL or a NEW descendant.
[ "Returns", "true", "if", "a", "node", "has", "a", "CALL", "or", "a", "NEW", "descendant", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SideEffectsAnalysis.java#L394-L401
24,710
google/closure-compiler
src/com/google/javascript/jscomp/DefaultExterns.java
DefaultExterns.prepareExterns
public static List<SourceFile> prepareExterns(CompilerOptions.Environment env, Map<String, SourceFile> externs) { List<SourceFile> out = new ArrayList<>(); for (String key : BUILTIN_LANG_EXTERNS) { Preconditions.checkState(externs.containsKey(key), "Externs must contain builtin: %s", key); out.add(externs.remove(key)); } if (env == CompilerOptions.Environment.BROWSER) { for (String key : BROWSER_EXTERN_DEP_ORDER) { Preconditions.checkState(externs.containsKey(key), "Externs must contain builtin for env %s: %s", env, key); out.add(externs.remove(key)); } out.addAll(externs.values()); } return out; }
java
public static List<SourceFile> prepareExterns(CompilerOptions.Environment env, Map<String, SourceFile> externs) { List<SourceFile> out = new ArrayList<>(); for (String key : BUILTIN_LANG_EXTERNS) { Preconditions.checkState(externs.containsKey(key), "Externs must contain builtin: %s", key); out.add(externs.remove(key)); } if (env == CompilerOptions.Environment.BROWSER) { for (String key : BROWSER_EXTERN_DEP_ORDER) { Preconditions.checkState(externs.containsKey(key), "Externs must contain builtin for env %s: %s", env, key); out.add(externs.remove(key)); } out.addAll(externs.values()); } return out; }
[ "public", "static", "List", "<", "SourceFile", ">", "prepareExterns", "(", "CompilerOptions", ".", "Environment", "env", ",", "Map", "<", "String", ",", "SourceFile", ">", "externs", ")", "{", "List", "<", "SourceFile", ">", "out", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "key", ":", "BUILTIN_LANG_EXTERNS", ")", "{", "Preconditions", ".", "checkState", "(", "externs", ".", "containsKey", "(", "key", ")", ",", "\"Externs must contain builtin: %s\"", ",", "key", ")", ";", "out", ".", "add", "(", "externs", ".", "remove", "(", "key", ")", ")", ";", "}", "if", "(", "env", "==", "CompilerOptions", ".", "Environment", ".", "BROWSER", ")", "{", "for", "(", "String", "key", ":", "BROWSER_EXTERN_DEP_ORDER", ")", "{", "Preconditions", ".", "checkState", "(", "externs", ".", "containsKey", "(", "key", ")", ",", "\"Externs must contain builtin for env %s: %s\"", ",", "env", ",", "key", ")", ";", "out", ".", "add", "(", "externs", ".", "remove", "(", "key", ")", ")", ";", "}", "out", ".", "addAll", "(", "externs", ".", "values", "(", ")", ")", ";", "}", "return", "out", ";", "}" ]
Filters and orders the passed externs for the specified environment. @param env The environment being used. @param externs Flat tilename to source externs map. Must be mutable and will be modified. @return Ordered list of externs.
[ "Filters", "and", "orders", "the", "passed", "externs", "for", "the", "specified", "environment", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DefaultExterns.java#L68-L88
24,711
google/closure-compiler
src/com/google/javascript/jscomp/PhaseOptimizer.java
PhaseOptimizer.setValidityCheck
void setValidityCheck(PassFactory validityCheck) { this.validityCheck = validityCheck; this.changeVerifier = new ChangeVerifier(compiler).snapshot(jsRoot); }
java
void setValidityCheck(PassFactory validityCheck) { this.validityCheck = validityCheck; this.changeVerifier = new ChangeVerifier(compiler).snapshot(jsRoot); }
[ "void", "setValidityCheck", "(", "PassFactory", "validityCheck", ")", "{", "this", ".", "validityCheck", "=", "validityCheck", ";", "this", ".", "changeVerifier", "=", "new", "ChangeVerifier", "(", "compiler", ")", ".", "snapshot", "(", "jsRoot", ")", ";", "}" ]
Adds a checker to be run after every pass. Intended for development.
[ "Adds", "a", "checker", "to", "be", "run", "after", "every", "pass", ".", "Intended", "for", "development", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PhaseOptimizer.java#L200-L203
24,712
google/closure-compiler
src/com/google/javascript/jscomp/PhaseOptimizer.java
PhaseOptimizer.process
@Override public void process(Node externs, Node root) { progress = 0.0; progressStep = 0.0; if (progressRange != null) { progressStep = (progressRange.maxValue - progressRange.initialValue) / passes.size(); progress = progressRange.initialValue; } // When looking at this code, one can mistakenly think that the instance of // PhaseOptimizer keeps all compiler passes live. This would be undesirable. A pass can // create large data structures that are only useful to the pass, and we shouldn't // retain them until the end of the compilation. But if you look at // NamedPass#process, the actual pass is created and immediately executed, and no // reference to it is retained in PhaseOptimizer: // factory.create(compiler).process(externs, root); for (CompilerPass pass : passes) { if (Thread.interrupted()) { throw new RuntimeException(new InterruptedException()); } pass.process(externs, root); if (hasHaltingErrors()) { return; } } }
java
@Override public void process(Node externs, Node root) { progress = 0.0; progressStep = 0.0; if (progressRange != null) { progressStep = (progressRange.maxValue - progressRange.initialValue) / passes.size(); progress = progressRange.initialValue; } // When looking at this code, one can mistakenly think that the instance of // PhaseOptimizer keeps all compiler passes live. This would be undesirable. A pass can // create large data structures that are only useful to the pass, and we shouldn't // retain them until the end of the compilation. But if you look at // NamedPass#process, the actual pass is created and immediately executed, and no // reference to it is retained in PhaseOptimizer: // factory.create(compiler).process(externs, root); for (CompilerPass pass : passes) { if (Thread.interrupted()) { throw new RuntimeException(new InterruptedException()); } pass.process(externs, root); if (hasHaltingErrors()) { return; } } }
[ "@", "Override", "public", "void", "process", "(", "Node", "externs", ",", "Node", "root", ")", "{", "progress", "=", "0.0", ";", "progressStep", "=", "0.0", ";", "if", "(", "progressRange", "!=", "null", ")", "{", "progressStep", "=", "(", "progressRange", ".", "maxValue", "-", "progressRange", ".", "initialValue", ")", "/", "passes", ".", "size", "(", ")", ";", "progress", "=", "progressRange", ".", "initialValue", ";", "}", "// When looking at this code, one can mistakenly think that the instance of", "// PhaseOptimizer keeps all compiler passes live. This would be undesirable. A pass can", "// create large data structures that are only useful to the pass, and we shouldn't", "// retain them until the end of the compilation. But if you look at", "// NamedPass#process, the actual pass is created and immediately executed, and no", "// reference to it is retained in PhaseOptimizer:", "// factory.create(compiler).process(externs, root);", "for", "(", "CompilerPass", "pass", ":", "passes", ")", "{", "if", "(", "Thread", ".", "interrupted", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "new", "InterruptedException", "(", ")", ")", ";", "}", "pass", ".", "process", "(", "externs", ",", "root", ")", ";", "if", "(", "hasHaltingErrors", "(", ")", ")", "{", "return", ";", "}", "}", "}" ]
Run all the passes in the optimizer.
[ "Run", "all", "the", "passes", "in", "the", "optimizer", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PhaseOptimizer.java#L216-L242
24,713
google/closure-compiler
src/com/google/javascript/jscomp/PhaseOptimizer.java
PhaseOptimizer.maybeRunValidityCheck
private void maybeRunValidityCheck(String passName, Node externs, Node root) { if (validityCheck == null) { return; } try { validityCheck.create(compiler).process(externs, root); changeVerifier.checkRecordedChanges(passName, jsRoot); } catch (Exception e) { throw new IllegalStateException("Validity checks failed for pass: " + passName, e); } }
java
private void maybeRunValidityCheck(String passName, Node externs, Node root) { if (validityCheck == null) { return; } try { validityCheck.create(compiler).process(externs, root); changeVerifier.checkRecordedChanges(passName, jsRoot); } catch (Exception e) { throw new IllegalStateException("Validity checks failed for pass: " + passName, e); } }
[ "private", "void", "maybeRunValidityCheck", "(", "String", "passName", ",", "Node", "externs", ",", "Node", "root", ")", "{", "if", "(", "validityCheck", "==", "null", ")", "{", "return", ";", "}", "try", "{", "validityCheck", ".", "create", "(", "compiler", ")", ".", "process", "(", "externs", ",", "root", ")", ";", "changeVerifier", ".", "checkRecordedChanges", "(", "passName", ",", "jsRoot", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Validity checks failed for pass: \"", "+", "passName", ",", "e", ")", ";", "}", "}" ]
Runs the validity check if it is available.
[ "Runs", "the", "validity", "check", "if", "it", "is", "available", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PhaseOptimizer.java#L255-L265
24,714
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteClassExtendsExpressions.java
Es6RewriteClassExtendsExpressions.canDecomposeSimply
private boolean canDecomposeSimply(Node classNode) { Node enclosingStatement = checkNotNull(NodeUtil.getEnclosingStatement(classNode), classNode); if (enclosingStatement == classNode) { // `class Foo extends some_expression {}` // can always be converted to // ``` // const tmpvar = some_expression; // class Foo extends tmpvar {} // ``` return true; } else { Node classNodeParent = classNode.getParent(); if (NodeUtil.isNameDeclaration(enclosingStatement) && classNodeParent.isName() && classNodeParent.isFirstChildOf(enclosingStatement)) { // `const Foo = class extends some_expression {}, maybe_other_var;` // can always be converted to // ``` // const tmpvar = some_expression; // const Foo = class extends tmpvar {}, maybe_other_var; // ``` return true; } else if (enclosingStatement.isExprResult() && classNodeParent.isOnlyChildOf(enclosingStatement) && classNodeParent.isAssign() && classNode.isSecondChildOf(classNodeParent)) { // `lhs = class extends some_expression {};` Node lhsNode = classNodeParent.getFirstChild(); // We can extract a temporary variable for some_expression as long as lhs expression // has no side effects. return !NodeUtil.mayHaveSideEffects(lhsNode, compiler); } else { return false; } } }
java
private boolean canDecomposeSimply(Node classNode) { Node enclosingStatement = checkNotNull(NodeUtil.getEnclosingStatement(classNode), classNode); if (enclosingStatement == classNode) { // `class Foo extends some_expression {}` // can always be converted to // ``` // const tmpvar = some_expression; // class Foo extends tmpvar {} // ``` return true; } else { Node classNodeParent = classNode.getParent(); if (NodeUtil.isNameDeclaration(enclosingStatement) && classNodeParent.isName() && classNodeParent.isFirstChildOf(enclosingStatement)) { // `const Foo = class extends some_expression {}, maybe_other_var;` // can always be converted to // ``` // const tmpvar = some_expression; // const Foo = class extends tmpvar {}, maybe_other_var; // ``` return true; } else if (enclosingStatement.isExprResult() && classNodeParent.isOnlyChildOf(enclosingStatement) && classNodeParent.isAssign() && classNode.isSecondChildOf(classNodeParent)) { // `lhs = class extends some_expression {};` Node lhsNode = classNodeParent.getFirstChild(); // We can extract a temporary variable for some_expression as long as lhs expression // has no side effects. return !NodeUtil.mayHaveSideEffects(lhsNode, compiler); } else { return false; } } }
[ "private", "boolean", "canDecomposeSimply", "(", "Node", "classNode", ")", "{", "Node", "enclosingStatement", "=", "checkNotNull", "(", "NodeUtil", ".", "getEnclosingStatement", "(", "classNode", ")", ",", "classNode", ")", ";", "if", "(", "enclosingStatement", "==", "classNode", ")", "{", "// `class Foo extends some_expression {}`", "// can always be converted to", "// ```", "// const tmpvar = some_expression;", "// class Foo extends tmpvar {}", "// ```", "return", "true", ";", "}", "else", "{", "Node", "classNodeParent", "=", "classNode", ".", "getParent", "(", ")", ";", "if", "(", "NodeUtil", ".", "isNameDeclaration", "(", "enclosingStatement", ")", "&&", "classNodeParent", ".", "isName", "(", ")", "&&", "classNodeParent", ".", "isFirstChildOf", "(", "enclosingStatement", ")", ")", "{", "// `const Foo = class extends some_expression {}, maybe_other_var;`", "// can always be converted to", "// ```", "// const tmpvar = some_expression;", "// const Foo = class extends tmpvar {}, maybe_other_var;", "// ```", "return", "true", ";", "}", "else", "if", "(", "enclosingStatement", ".", "isExprResult", "(", ")", "&&", "classNodeParent", ".", "isOnlyChildOf", "(", "enclosingStatement", ")", "&&", "classNodeParent", ".", "isAssign", "(", ")", "&&", "classNode", ".", "isSecondChildOf", "(", "classNodeParent", ")", ")", "{", "// `lhs = class extends some_expression {};`", "Node", "lhsNode", "=", "classNodeParent", ".", "getFirstChild", "(", ")", ";", "// We can extract a temporary variable for some_expression as long as lhs expression", "// has no side effects.", "return", "!", "NodeUtil", ".", "mayHaveSideEffects", "(", "lhsNode", ",", "compiler", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}" ]
Find common cases where we can safely decompose class extends expressions which are not qualified names. Enables transpilation of complex extends expressions. <p>We can only decompose the expression in a limited set of cases to avoid changing evaluation order of side-effect causing statements.
[ "Find", "common", "cases", "where", "we", "can", "safely", "decompose", "class", "extends", "expressions", "which", "are", "not", "qualified", "names", ".", "Enables", "transpilation", "of", "complex", "extends", "expressions", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteClassExtendsExpressions.java#L97-L132
24,715
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteClassExtendsExpressions.java
Es6RewriteClassExtendsExpressions.decomposeInIIFE
private void decomposeInIIFE(NodeTraversal t, Node classNode) { // converts // `class X extends something {}` // to // `(function() { return class X extends something {}; })()` Node functionBody = IR.block(); Node function = IR.function(IR.name(""), IR.paramList(), functionBody); Node call = NodeUtil.newCallNode(function); classNode.replaceWith(call); functionBody.addChildToBack(IR.returnNode(classNode)); call.useSourceInfoIfMissingFromForTree(classNode); // NOTE: extractExtends() will end up reporting the change for the new function, so we only // need to report the change to the enclosing scope t.reportCodeChange(call); // Now do the extends expression extraction within the IIFE extractExtends(t, classNode); }
java
private void decomposeInIIFE(NodeTraversal t, Node classNode) { // converts // `class X extends something {}` // to // `(function() { return class X extends something {}; })()` Node functionBody = IR.block(); Node function = IR.function(IR.name(""), IR.paramList(), functionBody); Node call = NodeUtil.newCallNode(function); classNode.replaceWith(call); functionBody.addChildToBack(IR.returnNode(classNode)); call.useSourceInfoIfMissingFromForTree(classNode); // NOTE: extractExtends() will end up reporting the change for the new function, so we only // need to report the change to the enclosing scope t.reportCodeChange(call); // Now do the extends expression extraction within the IIFE extractExtends(t, classNode); }
[ "private", "void", "decomposeInIIFE", "(", "NodeTraversal", "t", ",", "Node", "classNode", ")", "{", "// converts", "// `class X extends something {}`", "// to", "// `(function() { return class X extends something {}; })()`", "Node", "functionBody", "=", "IR", ".", "block", "(", ")", ";", "Node", "function", "=", "IR", ".", "function", "(", "IR", ".", "name", "(", "\"\"", ")", ",", "IR", ".", "paramList", "(", ")", ",", "functionBody", ")", ";", "Node", "call", "=", "NodeUtil", ".", "newCallNode", "(", "function", ")", ";", "classNode", ".", "replaceWith", "(", "call", ")", ";", "functionBody", ".", "addChildToBack", "(", "IR", ".", "returnNode", "(", "classNode", ")", ")", ";", "call", ".", "useSourceInfoIfMissingFromForTree", "(", "classNode", ")", ";", "// NOTE: extractExtends() will end up reporting the change for the new function, so we only", "// need to report the change to the enclosing scope", "t", ".", "reportCodeChange", "(", "call", ")", ";", "// Now do the extends expression extraction within the IIFE", "extractExtends", "(", "t", ",", "classNode", ")", ";", "}" ]
When a class is used in an expressions where adding an alias as the previous statement might change execution order of a side-effect causing statement, wrap the class in an IIFE so that decomposition can happen safely.
[ "When", "a", "class", "is", "used", "in", "an", "expressions", "where", "adding", "an", "alias", "as", "the", "previous", "statement", "might", "change", "execution", "order", "of", "a", "side", "-", "effect", "causing", "statement", "wrap", "the", "class", "in", "an", "IIFE", "so", "that", "decomposition", "can", "happen", "safely", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteClassExtendsExpressions.java#L156-L172
24,716
google/closure-compiler
src/com/google/javascript/jscomp/BasicBlock.java
BasicBlock.provablyExecutesBefore
boolean provablyExecutesBefore(BasicBlock thatBlock) { // If thatBlock is a descendant of this block, and there are no hoisted // blocks between them, then this block must start before thatBlock. BasicBlock currentBlock; for (currentBlock = thatBlock; currentBlock != null && currentBlock != this; currentBlock = currentBlock.getParent()) {} if (currentBlock == this) { return true; } return isGlobalScopeBlock() && thatBlock.isGlobalScopeBlock(); }
java
boolean provablyExecutesBefore(BasicBlock thatBlock) { // If thatBlock is a descendant of this block, and there are no hoisted // blocks between them, then this block must start before thatBlock. BasicBlock currentBlock; for (currentBlock = thatBlock; currentBlock != null && currentBlock != this; currentBlock = currentBlock.getParent()) {} if (currentBlock == this) { return true; } return isGlobalScopeBlock() && thatBlock.isGlobalScopeBlock(); }
[ "boolean", "provablyExecutesBefore", "(", "BasicBlock", "thatBlock", ")", "{", "// If thatBlock is a descendant of this block, and there are no hoisted", "// blocks between them, then this block must start before thatBlock.", "BasicBlock", "currentBlock", ";", "for", "(", "currentBlock", "=", "thatBlock", ";", "currentBlock", "!=", "null", "&&", "currentBlock", "!=", "this", ";", "currentBlock", "=", "currentBlock", ".", "getParent", "(", ")", ")", "{", "}", "if", "(", "currentBlock", "==", "this", ")", "{", "return", "true", ";", "}", "return", "isGlobalScopeBlock", "(", ")", "&&", "thatBlock", ".", "isGlobalScopeBlock", "(", ")", ";", "}" ]
Determines whether this block is guaranteed to begin executing before the given block does.
[ "Determines", "whether", "this", "block", "is", "guaranteed", "to", "begin", "executing", "before", "the", "given", "block", "does", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/BasicBlock.java#L81-L93
24,717
google/closure-compiler
src/com/google/javascript/jscomp/Denormalize.java
Denormalize.maybeCollapseIntoForStatements
private void maybeCollapseIntoForStatements(Node n, Node parent) { // Only SCRIPT, BLOCK, and LABELs can have FORs that can be collapsed into. // LABELs are not supported here. if (parent == null || !NodeUtil.isStatementBlock(parent)) { return; } // Is the current node something that can be in a for loop initializer? if (!n.isExprResult() && !n.isVar()) { return; } // Is the next statement a valid FOR? Node nextSibling = n.getNext(); if (nextSibling == null) { return; } else if (nextSibling.isForIn() || nextSibling.isForOf()) { Node forNode = nextSibling; Node forVar = forNode.getFirstChild(); if (forVar.isName() && n.isVar() && n.hasOneChild()) { Node name = n.getFirstChild(); if (!name.hasChildren() && forVar.getString().equals(name.getString())) { // OK, the names match, and the var declaration does not have an // initializer. Move it into the loop. parent.removeChild(n); forNode.replaceChild(forVar, n); compiler.reportChangeToEnclosingScope(parent); } } } else if (nextSibling.isVanillaFor() && nextSibling.getFirstChild().isEmpty()) { // Does the current node contain an in operator? If so, embedding // the expression in a for loop can cause some JavaScript parsers (such // as the PlayStation 3's browser based on Access's NetFront // browser) to fail to parse the code. // See bug 1778863 for details. if (NodeUtil.containsType(n, Token.IN)) { return; } // Move the current node into the FOR loop initializer. Node forNode = nextSibling; Node oldInitializer = forNode.getFirstChild(); parent.removeChild(n); Node newInitializer; if (n.isVar()) { newInitializer = n; } else { // Extract the expression from EXPR_RESULT node. checkState(n.hasOneChild(), n); newInitializer = n.getFirstChild(); n.removeChild(newInitializer); } forNode.replaceChild(oldInitializer, newInitializer); compiler.reportChangeToEnclosingScope(forNode); } }
java
private void maybeCollapseIntoForStatements(Node n, Node parent) { // Only SCRIPT, BLOCK, and LABELs can have FORs that can be collapsed into. // LABELs are not supported here. if (parent == null || !NodeUtil.isStatementBlock(parent)) { return; } // Is the current node something that can be in a for loop initializer? if (!n.isExprResult() && !n.isVar()) { return; } // Is the next statement a valid FOR? Node nextSibling = n.getNext(); if (nextSibling == null) { return; } else if (nextSibling.isForIn() || nextSibling.isForOf()) { Node forNode = nextSibling; Node forVar = forNode.getFirstChild(); if (forVar.isName() && n.isVar() && n.hasOneChild()) { Node name = n.getFirstChild(); if (!name.hasChildren() && forVar.getString().equals(name.getString())) { // OK, the names match, and the var declaration does not have an // initializer. Move it into the loop. parent.removeChild(n); forNode.replaceChild(forVar, n); compiler.reportChangeToEnclosingScope(parent); } } } else if (nextSibling.isVanillaFor() && nextSibling.getFirstChild().isEmpty()) { // Does the current node contain an in operator? If so, embedding // the expression in a for loop can cause some JavaScript parsers (such // as the PlayStation 3's browser based on Access's NetFront // browser) to fail to parse the code. // See bug 1778863 for details. if (NodeUtil.containsType(n, Token.IN)) { return; } // Move the current node into the FOR loop initializer. Node forNode = nextSibling; Node oldInitializer = forNode.getFirstChild(); parent.removeChild(n); Node newInitializer; if (n.isVar()) { newInitializer = n; } else { // Extract the expression from EXPR_RESULT node. checkState(n.hasOneChild(), n); newInitializer = n.getFirstChild(); n.removeChild(newInitializer); } forNode.replaceChild(oldInitializer, newInitializer); compiler.reportChangeToEnclosingScope(forNode); } }
[ "private", "void", "maybeCollapseIntoForStatements", "(", "Node", "n", ",", "Node", "parent", ")", "{", "// Only SCRIPT, BLOCK, and LABELs can have FORs that can be collapsed into.", "// LABELs are not supported here.", "if", "(", "parent", "==", "null", "||", "!", "NodeUtil", ".", "isStatementBlock", "(", "parent", ")", ")", "{", "return", ";", "}", "// Is the current node something that can be in a for loop initializer?", "if", "(", "!", "n", ".", "isExprResult", "(", ")", "&&", "!", "n", ".", "isVar", "(", ")", ")", "{", "return", ";", "}", "// Is the next statement a valid FOR?", "Node", "nextSibling", "=", "n", ".", "getNext", "(", ")", ";", "if", "(", "nextSibling", "==", "null", ")", "{", "return", ";", "}", "else", "if", "(", "nextSibling", ".", "isForIn", "(", ")", "||", "nextSibling", ".", "isForOf", "(", ")", ")", "{", "Node", "forNode", "=", "nextSibling", ";", "Node", "forVar", "=", "forNode", ".", "getFirstChild", "(", ")", ";", "if", "(", "forVar", ".", "isName", "(", ")", "&&", "n", ".", "isVar", "(", ")", "&&", "n", ".", "hasOneChild", "(", ")", ")", "{", "Node", "name", "=", "n", ".", "getFirstChild", "(", ")", ";", "if", "(", "!", "name", ".", "hasChildren", "(", ")", "&&", "forVar", ".", "getString", "(", ")", ".", "equals", "(", "name", ".", "getString", "(", ")", ")", ")", "{", "// OK, the names match, and the var declaration does not have an", "// initializer. Move it into the loop.", "parent", ".", "removeChild", "(", "n", ")", ";", "forNode", ".", "replaceChild", "(", "forVar", ",", "n", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "parent", ")", ";", "}", "}", "}", "else", "if", "(", "nextSibling", ".", "isVanillaFor", "(", ")", "&&", "nextSibling", ".", "getFirstChild", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "// Does the current node contain an in operator? If so, embedding", "// the expression in a for loop can cause some JavaScript parsers (such", "// as the PlayStation 3's browser based on Access's NetFront", "// browser) to fail to parse the code.", "// See bug 1778863 for details.", "if", "(", "NodeUtil", ".", "containsType", "(", "n", ",", "Token", ".", "IN", ")", ")", "{", "return", ";", "}", "// Move the current node into the FOR loop initializer.", "Node", "forNode", "=", "nextSibling", ";", "Node", "oldInitializer", "=", "forNode", ".", "getFirstChild", "(", ")", ";", "parent", ".", "removeChild", "(", "n", ")", ";", "Node", "newInitializer", ";", "if", "(", "n", ".", "isVar", "(", ")", ")", "{", "newInitializer", "=", "n", ";", "}", "else", "{", "// Extract the expression from EXPR_RESULT node.", "checkState", "(", "n", ".", "hasOneChild", "(", ")", ",", "n", ")", ";", "newInitializer", "=", "n", ".", "getFirstChild", "(", ")", ";", "n", ".", "removeChild", "(", "newInitializer", ")", ";", "}", "forNode", ".", "replaceChild", "(", "oldInitializer", ",", "newInitializer", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "forNode", ")", ";", "}", "}" ]
Collapse VARs and EXPR_RESULT node into FOR loop initializers where possible.
[ "Collapse", "VARs", "and", "EXPR_RESULT", "node", "into", "FOR", "loop", "initializers", "where", "possible", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Denormalize.java#L127-L188
24,718
google/closure-compiler
src/com/google/javascript/jscomp/Tracer.java
Tracer.longToPaddedString
private static String longToPaddedString(long v, int digitsColumnWidth) { int digitWidth = numDigits(v); StringBuilder sb = new StringBuilder(); appendSpaces(sb, digitsColumnWidth - digitWidth); sb.append(v); return sb.toString(); }
java
private static String longToPaddedString(long v, int digitsColumnWidth) { int digitWidth = numDigits(v); StringBuilder sb = new StringBuilder(); appendSpaces(sb, digitsColumnWidth - digitWidth); sb.append(v); return sb.toString(); }
[ "private", "static", "String", "longToPaddedString", "(", "long", "v", ",", "int", "digitsColumnWidth", ")", "{", "int", "digitWidth", "=", "numDigits", "(", "v", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "appendSpaces", "(", "sb", ",", "digitsColumnWidth", "-", "digitWidth", ")", ";", "sb", ".", "append", "(", "v", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Converts 'v' to a string and pads it with up to 16 spaces for improved alignment. @param v The value to convert. @param digitsColumnWidth The desired with of the string.
[ "Converts", "v", "to", "a", "string", "and", "pads", "it", "with", "up", "to", "16", "spaces", "for", "improved", "alignment", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Tracer.java#L295-L301
24,719
google/closure-compiler
src/com/google/javascript/jscomp/Tracer.java
Tracer.appendSpaces
@VisibleForTesting static void appendSpaces(StringBuilder sb, int numSpaces) { if (numSpaces > 16) { logger.warning("Tracer.appendSpaces called with large numSpaces"); // Avoid long loop in case some bug in the caller numSpaces = 16; } while (numSpaces >= 5) { sb.append(" "); numSpaces -= 5; } // We know it's less than 5 now switch (numSpaces) { case 1: sb.append(" "); break; case 2: sb.append(" "); break; case 3: sb.append(" "); break; case 4: sb.append(" "); break; } }
java
@VisibleForTesting static void appendSpaces(StringBuilder sb, int numSpaces) { if (numSpaces > 16) { logger.warning("Tracer.appendSpaces called with large numSpaces"); // Avoid long loop in case some bug in the caller numSpaces = 16; } while (numSpaces >= 5) { sb.append(" "); numSpaces -= 5; } // We know it's less than 5 now switch (numSpaces) { case 1: sb.append(" "); break; case 2: sb.append(" "); break; case 3: sb.append(" "); break; case 4: sb.append(" "); break; } }
[ "@", "VisibleForTesting", "static", "void", "appendSpaces", "(", "StringBuilder", "sb", ",", "int", "numSpaces", ")", "{", "if", "(", "numSpaces", ">", "16", ")", "{", "logger", ".", "warning", "(", "\"Tracer.appendSpaces called with large numSpaces\"", ")", ";", "// Avoid long loop in case some bug in the caller", "numSpaces", "=", "16", ";", "}", "while", "(", "numSpaces", ">=", "5", ")", "{", "sb", ".", "append", "(", "\" \"", ")", ";", "numSpaces", "-=", "5", ";", "}", "// We know it's less than 5 now", "switch", "(", "numSpaces", ")", "{", "case", "1", ":", "sb", ".", "append", "(", "\" \"", ")", ";", "break", ";", "case", "2", ":", "sb", ".", "append", "(", "\" \"", ")", ";", "break", ";", "case", "3", ":", "sb", ".", "append", "(", "\" \"", ")", ";", "break", ";", "case", "4", ":", "sb", ".", "append", "(", "\" \"", ")", ";", "break", ";", "}", "}" ]
Gets a string of spaces of the length specified. @param sb The string builder to append to. @param numSpaces The number of spaces in the string.
[ "Gets", "a", "string", "of", "spaces", "of", "the", "length", "specified", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Tracer.java#L323-L350
24,720
google/closure-compiler
src/com/google/javascript/jscomp/Tracer.java
Tracer.addTracingStatistic
static int addTracingStatistic(TracingStatistic tracingStatistic) { // Check to see if we can enable the tracing statistic before actually // adding it. if (tracingStatistic.enable()) { // No synchronization needed, since this is a copy-on-write array. extraTracingStatistics.add(tracingStatistic); // 99.9% of the time, this will be O(1) and return // extraTracingStatistics.length - 1 return extraTracingStatistics.lastIndexOf(tracingStatistic); } else { return -1; } }
java
static int addTracingStatistic(TracingStatistic tracingStatistic) { // Check to see if we can enable the tracing statistic before actually // adding it. if (tracingStatistic.enable()) { // No synchronization needed, since this is a copy-on-write array. extraTracingStatistics.add(tracingStatistic); // 99.9% of the time, this will be O(1) and return // extraTracingStatistics.length - 1 return extraTracingStatistics.lastIndexOf(tracingStatistic); } else { return -1; } }
[ "static", "int", "addTracingStatistic", "(", "TracingStatistic", "tracingStatistic", ")", "{", "// Check to see if we can enable the tracing statistic before actually", "// adding it.", "if", "(", "tracingStatistic", ".", "enable", "(", ")", ")", "{", "// No synchronization needed, since this is a copy-on-write array.", "extraTracingStatistics", ".", "add", "(", "tracingStatistic", ")", ";", "// 99.9% of the time, this will be O(1) and return", "// extraTracingStatistics.length - 1", "return", "extraTracingStatistics", ".", "lastIndexOf", "(", "tracingStatistic", ")", ";", "}", "else", "{", "return", "-", "1", ";", "}", "}" ]
Adds a new tracing statistic to a trace @param tracingStatistic to enable a run @return The index of this statistic (for use with stat.extraInfo()), or -1 if the statistic is not enabled.
[ "Adds", "a", "new", "tracing", "statistic", "to", "a", "trace" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Tracer.java#L359-L371
24,721
google/closure-compiler
src/com/google/javascript/jscomp/Tracer.java
Tracer.stop
long stop(int silenceThreshold) { checkState(Thread.currentThread() == startThread); ThreadTrace trace = getThreadTrace(); // Do nothing if the thread trace was not initialized. if (!trace.isInitialized()) { return 0; } stopTimeMs = clock.currentTimeMillis(); if (extraTracingValues != null) { // We use extraTracingValues.length rather than // extraTracingStatistics.size() because a new statistic may // have been added for (int i = 0; i < extraTracingValues.length; i++) { long value = extraTracingStatistics.get(i).stop(startThread); extraTracingValues[i] = value - extraTracingValues[i]; } } // Do nothing if the thread trace was not initialized. if (!trace.isInitialized()) { return 0; } trace.endEvent(this, silenceThreshold); return stopTimeMs - startTimeMs; }
java
long stop(int silenceThreshold) { checkState(Thread.currentThread() == startThread); ThreadTrace trace = getThreadTrace(); // Do nothing if the thread trace was not initialized. if (!trace.isInitialized()) { return 0; } stopTimeMs = clock.currentTimeMillis(); if (extraTracingValues != null) { // We use extraTracingValues.length rather than // extraTracingStatistics.size() because a new statistic may // have been added for (int i = 0; i < extraTracingValues.length; i++) { long value = extraTracingStatistics.get(i).stop(startThread); extraTracingValues[i] = value - extraTracingValues[i]; } } // Do nothing if the thread trace was not initialized. if (!trace.isInitialized()) { return 0; } trace.endEvent(this, silenceThreshold); return stopTimeMs - startTimeMs; }
[ "long", "stop", "(", "int", "silenceThreshold", ")", "{", "checkState", "(", "Thread", ".", "currentThread", "(", ")", "==", "startThread", ")", ";", "ThreadTrace", "trace", "=", "getThreadTrace", "(", ")", ";", "// Do nothing if the thread trace was not initialized.", "if", "(", "!", "trace", ".", "isInitialized", "(", ")", ")", "{", "return", "0", ";", "}", "stopTimeMs", "=", "clock", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "extraTracingValues", "!=", "null", ")", "{", "// We use extraTracingValues.length rather than", "// extraTracingStatistics.size() because a new statistic may", "// have been added", "for", "(", "int", "i", "=", "0", ";", "i", "<", "extraTracingValues", ".", "length", ";", "i", "++", ")", "{", "long", "value", "=", "extraTracingStatistics", ".", "get", "(", "i", ")", ".", "stop", "(", "startThread", ")", ";", "extraTracingValues", "[", "i", "]", "=", "value", "-", "extraTracingValues", "[", "i", "]", ";", "}", "}", "// Do nothing if the thread trace was not initialized.", "if", "(", "!", "trace", ".", "isInitialized", "(", ")", ")", "{", "return", "0", ";", "}", "trace", ".", "endEvent", "(", "this", ",", "silenceThreshold", ")", ";", "return", "stopTimeMs", "-", "startTimeMs", ";", "}" ]
Stop the trace. This may only be done once and must be done from the same thread that started it. @param silenceThreshold Traces for time less than silence_threshold ms will be left out of the trace report. A value of -1 indicates that the current ThreadTrace silence_threshold should be used. @return The time that this trace actually ran
[ "Stop", "the", "trace", ".", "This", "may", "only", "be", "done", "once", "and", "must", "be", "done", "from", "the", "same", "thread", "that", "started", "it", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Tracer.java#L394-L421
24,722
google/closure-compiler
src/com/google/javascript/jscomp/Tracer.java
Tracer.initCurrentThreadTrace
static void initCurrentThreadTrace() { ThreadTrace events = getThreadTrace(); if (!events.isEmpty()) { logger.log(Level.WARNING, "Non-empty timer log:\n" + events, new Throwable()); clearThreadTrace(); // Grab a new thread trace if we find a previous non-empty ThreadTrace. events = getThreadTrace(); } // Mark the thread trace as initialized. events.init(); }
java
static void initCurrentThreadTrace() { ThreadTrace events = getThreadTrace(); if (!events.isEmpty()) { logger.log(Level.WARNING, "Non-empty timer log:\n" + events, new Throwable()); clearThreadTrace(); // Grab a new thread trace if we find a previous non-empty ThreadTrace. events = getThreadTrace(); } // Mark the thread trace as initialized. events.init(); }
[ "static", "void", "initCurrentThreadTrace", "(", ")", "{", "ThreadTrace", "events", "=", "getThreadTrace", "(", ")", ";", "if", "(", "!", "events", ".", "isEmpty", "(", ")", ")", "{", "logger", ".", "log", "(", "Level", ".", "WARNING", ",", "\"Non-empty timer log:\\n\"", "+", "events", ",", "new", "Throwable", "(", ")", ")", ";", "clearThreadTrace", "(", ")", ";", "// Grab a new thread trace if we find a previous non-empty ThreadTrace.", "events", "=", "getThreadTrace", "(", ")", ";", "}", "// Mark the thread trace as initialized.", "events", ".", "init", "(", ")", ";", "}" ]
Initialize the trace associated with the current thread by clearing out any existing trace. There shouldn't be a trace so if one is found we log it as an error.
[ "Initialize", "the", "trace", "associated", "with", "the", "current", "thread", "by", "clearing", "out", "any", "existing", "trace", ".", "There", "shouldn", "t", "be", "a", "trace", "so", "if", "one", "is", "found", "we", "log", "it", "as", "an", "error", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Tracer.java#L448-L462
24,723
google/closure-compiler
src/com/google/javascript/jscomp/Tracer.java
Tracer.logCurrentThreadTrace
static void logCurrentThreadTrace() { ThreadTrace trace = getThreadTrace(); // New threads must call Tracer.initCurrentThreadTrace() before Tracer // statistics are gathered. This is a recent change (Jun 2007) that // prevents spurious Third Eye messages when an application uses a class in // a different package that happens to call Tracer without knowledge of the // application authors. if (!trace.isInitialized()) { logger.log( Level.INFO, "Tracer log requested for this thread but was not " + "initialized using Tracer.initCurrentThreadTrace().", new Throwable()); return; } if (!trace.isEmpty()) { logger.log(Level.INFO, "timers:\n{0}", getCurrentThreadTraceReport()); } }
java
static void logCurrentThreadTrace() { ThreadTrace trace = getThreadTrace(); // New threads must call Tracer.initCurrentThreadTrace() before Tracer // statistics are gathered. This is a recent change (Jun 2007) that // prevents spurious Third Eye messages when an application uses a class in // a different package that happens to call Tracer without knowledge of the // application authors. if (!trace.isInitialized()) { logger.log( Level.INFO, "Tracer log requested for this thread but was not " + "initialized using Tracer.initCurrentThreadTrace().", new Throwable()); return; } if (!trace.isEmpty()) { logger.log(Level.INFO, "timers:\n{0}", getCurrentThreadTraceReport()); } }
[ "static", "void", "logCurrentThreadTrace", "(", ")", "{", "ThreadTrace", "trace", "=", "getThreadTrace", "(", ")", ";", "// New threads must call Tracer.initCurrentThreadTrace() before Tracer", "// statistics are gathered. This is a recent change (Jun 2007) that", "// prevents spurious Third Eye messages when an application uses a class in", "// a different package that happens to call Tracer without knowledge of the", "// application authors.", "if", "(", "!", "trace", ".", "isInitialized", "(", ")", ")", "{", "logger", ".", "log", "(", "Level", ".", "INFO", ",", "\"Tracer log requested for this thread but was not \"", "+", "\"initialized using Tracer.initCurrentThreadTrace().\"", ",", "new", "Throwable", "(", ")", ")", ";", "return", ";", "}", "if", "(", "!", "trace", ".", "isEmpty", "(", ")", ")", "{", "logger", ".", "log", "(", "Level", ".", "INFO", ",", "\"timers:\\n{0}\"", ",", "getCurrentThreadTraceReport", "(", ")", ")", ";", "}", "}" ]
Logs a timer report similar to the one described in the class comment.
[ "Logs", "a", "timer", "report", "similar", "to", "the", "one", "described", "in", "the", "class", "comment", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Tracer.java#L481-L501
24,724
google/closure-compiler
src/com/google/javascript/jscomp/Tracer.java
Tracer.getStatsForType
static Stat getStatsForType(String type) { Stat stat = getThreadTrace().stats.get(type); return stat != null ? stat : ZERO_STAT; }
java
static Stat getStatsForType(String type) { Stat stat = getThreadTrace().stats.get(type); return stat != null ? stat : ZERO_STAT; }
[ "static", "Stat", "getStatsForType", "(", "String", "type", ")", "{", "Stat", "stat", "=", "getThreadTrace", "(", ")", ".", "stats", ".", "get", "(", "type", ")", ";", "return", "stat", "!=", "null", "?", "stat", ":", "ZERO_STAT", ";", "}" ]
Gets the Stat for a tracer type; never returns null
[ "Gets", "the", "Stat", "for", "a", "tracer", "type", ";", "never", "returns", "null" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Tracer.java#L616-L619
24,725
google/closure-compiler
src/com/google/javascript/jscomp/Tracer.java
Tracer.getThreadTrace
static ThreadTrace getThreadTrace() { ThreadTrace t = traces.get(); if (t == null) { t = new ThreadTrace(); t.prettyPrint = defaultPrettyPrint; traces.set(t); } return t; }
java
static ThreadTrace getThreadTrace() { ThreadTrace t = traces.get(); if (t == null) { t = new ThreadTrace(); t.prettyPrint = defaultPrettyPrint; traces.set(t); } return t; }
[ "static", "ThreadTrace", "getThreadTrace", "(", ")", "{", "ThreadTrace", "t", "=", "traces", ".", "get", "(", ")", ";", "if", "(", "t", "==", "null", ")", "{", "t", "=", "new", "ThreadTrace", "(", ")", ";", "t", ".", "prettyPrint", "=", "defaultPrettyPrint", ";", "traces", ".", "set", "(", "t", ")", ";", "}", "return", "t", ";", "}" ]
Get the ThreadTrace for the current thread, creating one if necessary.
[ "Get", "the", "ThreadTrace", "for", "the", "current", "thread", "creating", "one", "if", "necessary", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Tracer.java#L945-L953
24,726
google/closure-compiler
src/com/google/javascript/jscomp/LiveVariablesAnalysis.java
LiveVariablesAnalysis.addScopeVariables
private void addScopeVariables() { int num = 0; for (Var v : orderedVars) { scopeVariables.put(v.getName(), num); num++; } }
java
private void addScopeVariables() { int num = 0; for (Var v : orderedVars) { scopeVariables.put(v.getName(), num); num++; } }
[ "private", "void", "addScopeVariables", "(", ")", "{", "int", "num", "=", "0", ";", "for", "(", "Var", "v", ":", "orderedVars", ")", "{", "scopeVariables", ".", "put", "(", "v", ".", "getName", "(", ")", ",", "num", ")", ";", "num", "++", ";", "}", "}" ]
Parameters belong to the function scope, but variables defined in the function body belong to the function body scope. Assign a unique index to each variable, regardless of which scope it's in.
[ "Parameters", "belong", "to", "the", "function", "scope", "but", "variables", "defined", "in", "the", "function", "body", "belong", "to", "the", "function", "body", "scope", ".", "Assign", "a", "unique", "index", "to", "each", "variable", "regardless", "of", "which", "scope", "it", "s", "in", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/LiveVariablesAnalysis.java#L170-L176
24,727
google/closure-compiler
src/com/google/javascript/jscomp/LiveVariablesAnalysis.java
LiveVariablesAnalysis.markAllParametersEscaped
void markAllParametersEscaped() { Node paramList = NodeUtil.getFunctionParameters(jsScope.getRootNode()); for (Node arg = paramList.getFirstChild(); arg != null; arg = arg.getNext()) { if (arg.isRest() || arg.isDefaultValue()) { escaped.add(jsScope.getVar(arg.getFirstChild().getString())); } else { escaped.add(jsScope.getVar(arg.getString())); } } }
java
void markAllParametersEscaped() { Node paramList = NodeUtil.getFunctionParameters(jsScope.getRootNode()); for (Node arg = paramList.getFirstChild(); arg != null; arg = arg.getNext()) { if (arg.isRest() || arg.isDefaultValue()) { escaped.add(jsScope.getVar(arg.getFirstChild().getString())); } else { escaped.add(jsScope.getVar(arg.getString())); } } }
[ "void", "markAllParametersEscaped", "(", ")", "{", "Node", "paramList", "=", "NodeUtil", ".", "getFunctionParameters", "(", "jsScope", ".", "getRootNode", "(", ")", ")", ";", "for", "(", "Node", "arg", "=", "paramList", ".", "getFirstChild", "(", ")", ";", "arg", "!=", "null", ";", "arg", "=", "arg", ".", "getNext", "(", ")", ")", "{", "if", "(", "arg", ".", "isRest", "(", ")", "||", "arg", ".", "isDefaultValue", "(", ")", ")", "{", "escaped", ".", "add", "(", "jsScope", ".", "getVar", "(", "arg", ".", "getFirstChild", "(", ")", ".", "getString", "(", ")", ")", ")", ";", "}", "else", "{", "escaped", ".", "add", "(", "jsScope", ".", "getVar", "(", "arg", ".", "getString", "(", ")", ")", ")", ";", "}", "}", "}" ]
Give up computing liveness of formal parameter by putting all the parameter names in the escaped set.
[ "Give", "up", "computing", "liveness", "of", "formal", "parameter", "by", "putting", "all", "the", "parameter", "names", "in", "the", "escaped", "set", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/LiveVariablesAnalysis.java#L400-L409
24,728
google/closure-compiler
src/com/google/javascript/jscomp/DiagnosticGroupPathSuppressingWarningsGuard.java
DiagnosticGroupPathSuppressingWarningsGuard.level
@Override public CheckLevel level(JSError error) { return error.sourceName != null && error.sourceName.contains(part) ? super.level(error) /** suppress */ : null /** proceed */; }
java
@Override public CheckLevel level(JSError error) { return error.sourceName != null && error.sourceName.contains(part) ? super.level(error) /** suppress */ : null /** proceed */; }
[ "@", "Override", "public", "CheckLevel", "level", "(", "JSError", "error", ")", "{", "return", "error", ".", "sourceName", "!=", "null", "&&", "error", ".", "sourceName", ".", "contains", "(", "part", ")", "?", "super", ".", "level", "(", "error", ")", "/** suppress */", ":", "null", "/** proceed */", ";", "}" ]
Does not touch warnings in other paths.
[ "Does", "not", "touch", "warnings", "in", "other", "paths", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DiagnosticGroupPathSuppressingWarningsGuard.java#L38-L42
24,729
google/closure-compiler
src/com/google/javascript/rhino/jstype/TemplatizedType.java
TemplatizedType.getCtorImplementedInterfaces
@Override public Iterable<ObjectType> getCtorImplementedInterfaces() { LinkedHashSet<ObjectType> resolvedImplementedInterfaces = new LinkedHashSet<>(); for (ObjectType obj : getReferencedObjTypeInternal().getCtorImplementedInterfaces()) { resolvedImplementedInterfaces.add(obj.visit(replacer).toObjectType()); } return resolvedImplementedInterfaces; }
java
@Override public Iterable<ObjectType> getCtorImplementedInterfaces() { LinkedHashSet<ObjectType> resolvedImplementedInterfaces = new LinkedHashSet<>(); for (ObjectType obj : getReferencedObjTypeInternal().getCtorImplementedInterfaces()) { resolvedImplementedInterfaces.add(obj.visit(replacer).toObjectType()); } return resolvedImplementedInterfaces; }
[ "@", "Override", "public", "Iterable", "<", "ObjectType", ">", "getCtorImplementedInterfaces", "(", ")", "{", "LinkedHashSet", "<", "ObjectType", ">", "resolvedImplementedInterfaces", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "for", "(", "ObjectType", "obj", ":", "getReferencedObjTypeInternal", "(", ")", ".", "getCtorImplementedInterfaces", "(", ")", ")", "{", "resolvedImplementedInterfaces", ".", "add", "(", "obj", ".", "visit", "(", "replacer", ")", ".", "toObjectType", "(", ")", ")", ";", "}", "return", "resolvedImplementedInterfaces", ";", "}" ]
an UnsupportedOperationException.
[ "an", "UnsupportedOperationException", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplatizedType.java#L91-L98
24,730
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.checkTypeDeprecation
private void checkTypeDeprecation(NodeTraversal t, Node n) { if (!shouldEmitDeprecationWarning(t, n)) { return; } ObjectType instanceType = n.getJSType().toMaybeFunctionType().getInstanceType(); String deprecationInfo = getTypeDeprecationInfo(instanceType); if (deprecationInfo == null) { return; } DiagnosticType message = deprecationInfo.isEmpty() ? DEPRECATED_CLASS : DEPRECATED_CLASS_REASON; compiler.report(JSError.make(n, message, instanceType.toString(), deprecationInfo)); }
java
private void checkTypeDeprecation(NodeTraversal t, Node n) { if (!shouldEmitDeprecationWarning(t, n)) { return; } ObjectType instanceType = n.getJSType().toMaybeFunctionType().getInstanceType(); String deprecationInfo = getTypeDeprecationInfo(instanceType); if (deprecationInfo == null) { return; } DiagnosticType message = deprecationInfo.isEmpty() ? DEPRECATED_CLASS : DEPRECATED_CLASS_REASON; compiler.report(JSError.make(n, message, instanceType.toString(), deprecationInfo)); }
[ "private", "void", "checkTypeDeprecation", "(", "NodeTraversal", "t", ",", "Node", "n", ")", "{", "if", "(", "!", "shouldEmitDeprecationWarning", "(", "t", ",", "n", ")", ")", "{", "return", ";", "}", "ObjectType", "instanceType", "=", "n", ".", "getJSType", "(", ")", ".", "toMaybeFunctionType", "(", ")", ".", "getInstanceType", "(", ")", ";", "String", "deprecationInfo", "=", "getTypeDeprecationInfo", "(", "instanceType", ")", ";", "if", "(", "deprecationInfo", "==", "null", ")", "{", "return", ";", "}", "DiagnosticType", "message", "=", "deprecationInfo", ".", "isEmpty", "(", ")", "?", "DEPRECATED_CLASS", ":", "DEPRECATED_CLASS_REASON", ";", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "n", ",", "message", ",", "instanceType", ".", "toString", "(", ")", ",", "deprecationInfo", ")", ")", ";", "}" ]
Reports deprecation issue with regard to a type usage. <p>Precondition: {@code n} has a constructor {@link JSType}.
[ "Reports", "deprecation", "issue", "with", "regard", "to", "a", "type", "usage", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L431-L445
24,731
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.checkNameDeprecation
private void checkNameDeprecation(NodeTraversal t, Node n) { if (!n.isName()) { return; } if (!shouldEmitDeprecationWarning(t, n)) { return; } Var var = t.getScope().getVar(n.getString()); JSDocInfo docInfo = var == null ? null : var.getJSDocInfo(); if (docInfo != null && docInfo.isDeprecated()) { if (docInfo.getDeprecationReason() != null) { compiler.report( JSError.make(n, DEPRECATED_NAME_REASON, n.getString(), docInfo.getDeprecationReason())); } else { compiler.report(JSError.make(n, DEPRECATED_NAME, n.getString())); } } }
java
private void checkNameDeprecation(NodeTraversal t, Node n) { if (!n.isName()) { return; } if (!shouldEmitDeprecationWarning(t, n)) { return; } Var var = t.getScope().getVar(n.getString()); JSDocInfo docInfo = var == null ? null : var.getJSDocInfo(); if (docInfo != null && docInfo.isDeprecated()) { if (docInfo.getDeprecationReason() != null) { compiler.report( JSError.make(n, DEPRECATED_NAME_REASON, n.getString(), docInfo.getDeprecationReason())); } else { compiler.report(JSError.make(n, DEPRECATED_NAME, n.getString())); } } }
[ "private", "void", "checkNameDeprecation", "(", "NodeTraversal", "t", ",", "Node", "n", ")", "{", "if", "(", "!", "n", ".", "isName", "(", ")", ")", "{", "return", ";", "}", "if", "(", "!", "shouldEmitDeprecationWarning", "(", "t", ",", "n", ")", ")", "{", "return", ";", "}", "Var", "var", "=", "t", ".", "getScope", "(", ")", ".", "getVar", "(", "n", ".", "getString", "(", ")", ")", ";", "JSDocInfo", "docInfo", "=", "var", "==", "null", "?", "null", ":", "var", ".", "getJSDocInfo", "(", ")", ";", "if", "(", "docInfo", "!=", "null", "&&", "docInfo", ".", "isDeprecated", "(", ")", ")", "{", "if", "(", "docInfo", ".", "getDeprecationReason", "(", ")", "!=", "null", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "n", ",", "DEPRECATED_NAME_REASON", ",", "n", ".", "getString", "(", ")", ",", "docInfo", ".", "getDeprecationReason", "(", ")", ")", ")", ";", "}", "else", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "n", ",", "DEPRECATED_NAME", ",", "n", ".", "getString", "(", ")", ")", ")", ";", "}", "}", "}" ]
Checks the given NAME node to ensure that access restrictions are obeyed.
[ "Checks", "the", "given", "NAME", "node", "to", "ensure", "that", "access", "restrictions", "are", "obeyed", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L448-L468
24,732
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.checkPropertyDeprecation
private void checkPropertyDeprecation(NodeTraversal t, PropertyReference propRef) { if (!shouldEmitDeprecationWarning(t, propRef)) { return; } // Don't bother checking constructors. if (propRef.getSourceNode().getParent().isNew()) { return; } ObjectType objectType = castToObject(dereference(propRef.getReceiverType())); String propertyName = propRef.getName(); if (objectType != null) { String deprecationInfo = getPropertyDeprecationInfo(objectType, propertyName); if (deprecationInfo != null) { if (!deprecationInfo.isEmpty()) { compiler.report( JSError.make( propRef.getSourceNode(), DEPRECATED_PROP_REASON, propertyName, propRef.getReadableTypeNameOrDefault(), deprecationInfo)); } else { compiler.report( JSError.make( propRef.getSourceNode(), DEPRECATED_PROP, propertyName, propRef.getReadableTypeNameOrDefault())); } } } }
java
private void checkPropertyDeprecation(NodeTraversal t, PropertyReference propRef) { if (!shouldEmitDeprecationWarning(t, propRef)) { return; } // Don't bother checking constructors. if (propRef.getSourceNode().getParent().isNew()) { return; } ObjectType objectType = castToObject(dereference(propRef.getReceiverType())); String propertyName = propRef.getName(); if (objectType != null) { String deprecationInfo = getPropertyDeprecationInfo(objectType, propertyName); if (deprecationInfo != null) { if (!deprecationInfo.isEmpty()) { compiler.report( JSError.make( propRef.getSourceNode(), DEPRECATED_PROP_REASON, propertyName, propRef.getReadableTypeNameOrDefault(), deprecationInfo)); } else { compiler.report( JSError.make( propRef.getSourceNode(), DEPRECATED_PROP, propertyName, propRef.getReadableTypeNameOrDefault())); } } } }
[ "private", "void", "checkPropertyDeprecation", "(", "NodeTraversal", "t", ",", "PropertyReference", "propRef", ")", "{", "if", "(", "!", "shouldEmitDeprecationWarning", "(", "t", ",", "propRef", ")", ")", "{", "return", ";", "}", "// Don't bother checking constructors.", "if", "(", "propRef", ".", "getSourceNode", "(", ")", ".", "getParent", "(", ")", ".", "isNew", "(", ")", ")", "{", "return", ";", "}", "ObjectType", "objectType", "=", "castToObject", "(", "dereference", "(", "propRef", ".", "getReceiverType", "(", ")", ")", ")", ";", "String", "propertyName", "=", "propRef", ".", "getName", "(", ")", ";", "if", "(", "objectType", "!=", "null", ")", "{", "String", "deprecationInfo", "=", "getPropertyDeprecationInfo", "(", "objectType", ",", "propertyName", ")", ";", "if", "(", "deprecationInfo", "!=", "null", ")", "{", "if", "(", "!", "deprecationInfo", ".", "isEmpty", "(", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "propRef", ".", "getSourceNode", "(", ")", ",", "DEPRECATED_PROP_REASON", ",", "propertyName", ",", "propRef", ".", "getReadableTypeNameOrDefault", "(", ")", ",", "deprecationInfo", ")", ")", ";", "}", "else", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "propRef", ".", "getSourceNode", "(", ")", ",", "DEPRECATED_PROP", ",", "propertyName", ",", "propRef", ".", "getReadableTypeNameOrDefault", "(", ")", ")", ")", ";", "}", "}", "}", "}" ]
Checks the given GETPROP node to ensure that access restrictions are obeyed.
[ "Checks", "the", "given", "GETPROP", "node", "to", "ensure", "that", "access", "restrictions", "are", "obeyed", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L471-L508
24,733
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.checkKeyVisibilityConvention
private void checkKeyVisibilityConvention(Node key, Node parent) { JSDocInfo info = key.getJSDocInfo(); if (info == null) { return; } if (!isPrivateByConvention(key.getString())) { return; } Node assign = parent.getParent(); if (assign == null || !assign.isAssign()) { return; } Node left = assign.getFirstChild(); if (!left.isGetProp() || !left.getLastChild().getString().equals("prototype")) { return; } Visibility declaredVisibility = info.getVisibility(); // Visibility is declared to be something other than private. if (declaredVisibility != Visibility.INHERITED && declaredVisibility != Visibility.PRIVATE) { compiler.report(JSError.make(key, CONVENTION_MISMATCH)); } }
java
private void checkKeyVisibilityConvention(Node key, Node parent) { JSDocInfo info = key.getJSDocInfo(); if (info == null) { return; } if (!isPrivateByConvention(key.getString())) { return; } Node assign = parent.getParent(); if (assign == null || !assign.isAssign()) { return; } Node left = assign.getFirstChild(); if (!left.isGetProp() || !left.getLastChild().getString().equals("prototype")) { return; } Visibility declaredVisibility = info.getVisibility(); // Visibility is declared to be something other than private. if (declaredVisibility != Visibility.INHERITED && declaredVisibility != Visibility.PRIVATE) { compiler.report(JSError.make(key, CONVENTION_MISMATCH)); } }
[ "private", "void", "checkKeyVisibilityConvention", "(", "Node", "key", ",", "Node", "parent", ")", "{", "JSDocInfo", "info", "=", "key", ".", "getJSDocInfo", "(", ")", ";", "if", "(", "info", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "isPrivateByConvention", "(", "key", ".", "getString", "(", ")", ")", ")", "{", "return", ";", "}", "Node", "assign", "=", "parent", ".", "getParent", "(", ")", ";", "if", "(", "assign", "==", "null", "||", "!", "assign", ".", "isAssign", "(", ")", ")", "{", "return", ";", "}", "Node", "left", "=", "assign", ".", "getFirstChild", "(", ")", ";", "if", "(", "!", "left", ".", "isGetProp", "(", ")", "||", "!", "left", ".", "getLastChild", "(", ")", ".", "getString", "(", ")", ".", "equals", "(", "\"prototype\"", ")", ")", "{", "return", ";", "}", "Visibility", "declaredVisibility", "=", "info", ".", "getVisibility", "(", ")", ";", "// Visibility is declared to be something other than private.", "if", "(", "declaredVisibility", "!=", "Visibility", ".", "INHERITED", "&&", "declaredVisibility", "!=", "Visibility", ".", "PRIVATE", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "key", ",", "CONVENTION_MISMATCH", ")", ")", ";", "}", "}" ]
Determines whether the given OBJECTLIT property visibility violates the coding convention. @param key The objectlit key node (STRING_KEY, GETTER_DEF, SETTER_DEF, MEMBER_FUNCTION_DEF).
[ "Determines", "whether", "the", "given", "OBJECTLIT", "property", "visibility", "violates", "the", "coding", "convention", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L520-L543
24,734
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.checkNameVisibility
private void checkNameVisibility(Scope scope, Node name) { if (!name.isName()) { return; } Var var = scope.getVar(name.getString()); if (var == null) { return; } Visibility v = checkPrivateNameConvention( AccessControlUtils.getEffectiveNameVisibility( name, var, defaultVisibilityForFiles), name); switch (v) { case PACKAGE: if (!isPackageAccessAllowed(var, name)) { compiler.report( JSError.make( name, BAD_PACKAGE_PROPERTY_ACCESS, name.getString(), var.getSourceFile().getName())); } break; case PRIVATE: if (!isPrivateAccessAllowed(var, name)) { compiler.report( JSError.make( name, BAD_PRIVATE_GLOBAL_ACCESS, name.getString(), var.getSourceFile().getName())); } break; default: // Nothing to do for PUBLIC and PROTECTED // (which is irrelevant for names). break; } }
java
private void checkNameVisibility(Scope scope, Node name) { if (!name.isName()) { return; } Var var = scope.getVar(name.getString()); if (var == null) { return; } Visibility v = checkPrivateNameConvention( AccessControlUtils.getEffectiveNameVisibility( name, var, defaultVisibilityForFiles), name); switch (v) { case PACKAGE: if (!isPackageAccessAllowed(var, name)) { compiler.report( JSError.make( name, BAD_PACKAGE_PROPERTY_ACCESS, name.getString(), var.getSourceFile().getName())); } break; case PRIVATE: if (!isPrivateAccessAllowed(var, name)) { compiler.report( JSError.make( name, BAD_PRIVATE_GLOBAL_ACCESS, name.getString(), var.getSourceFile().getName())); } break; default: // Nothing to do for PUBLIC and PROTECTED // (which is irrelevant for names). break; } }
[ "private", "void", "checkNameVisibility", "(", "Scope", "scope", ",", "Node", "name", ")", "{", "if", "(", "!", "name", ".", "isName", "(", ")", ")", "{", "return", ";", "}", "Var", "var", "=", "scope", ".", "getVar", "(", "name", ".", "getString", "(", ")", ")", ";", "if", "(", "var", "==", "null", ")", "{", "return", ";", "}", "Visibility", "v", "=", "checkPrivateNameConvention", "(", "AccessControlUtils", ".", "getEffectiveNameVisibility", "(", "name", ",", "var", ",", "defaultVisibilityForFiles", ")", ",", "name", ")", ";", "switch", "(", "v", ")", "{", "case", "PACKAGE", ":", "if", "(", "!", "isPackageAccessAllowed", "(", "var", ",", "name", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "name", ",", "BAD_PACKAGE_PROPERTY_ACCESS", ",", "name", ".", "getString", "(", ")", ",", "var", ".", "getSourceFile", "(", ")", ".", "getName", "(", ")", ")", ")", ";", "}", "break", ";", "case", "PRIVATE", ":", "if", "(", "!", "isPrivateAccessAllowed", "(", "var", ",", "name", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "name", ",", "BAD_PRIVATE_GLOBAL_ACCESS", ",", "name", ".", "getString", "(", ")", ",", "var", ".", "getSourceFile", "(", ")", ".", "getName", "(", ")", ")", ")", ";", "}", "break", ";", "default", ":", "// Nothing to do for PUBLIC and PROTECTED", "// (which is irrelevant for names).", "break", ";", "}", "}" ]
Reports an error if the given name is not visible in the current context. @param scope The current scope. @param name The name node.
[ "Reports", "an", "error", "if", "the", "given", "name", "is", "not", "visible", "in", "the", "current", "context", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L551-L591
24,735
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.checkFinalClassOverrides
private void checkFinalClassOverrides(Node ctor) { if (!isFunctionOrClass(ctor)) { return; } JSType type = ctor.getJSType().toMaybeFunctionType(); if (type != null && type.isConstructor()) { JSType finalParentClass = getSuperClassInstanceIfFinal(bestInstanceTypeForMethodOrCtor(ctor)); if (finalParentClass != null) { compiler.report( JSError.make( ctor, EXTEND_FINAL_CLASS, type.getDisplayName(), finalParentClass.getDisplayName())); } } }
java
private void checkFinalClassOverrides(Node ctor) { if (!isFunctionOrClass(ctor)) { return; } JSType type = ctor.getJSType().toMaybeFunctionType(); if (type != null && type.isConstructor()) { JSType finalParentClass = getSuperClassInstanceIfFinal(bestInstanceTypeForMethodOrCtor(ctor)); if (finalParentClass != null) { compiler.report( JSError.make( ctor, EXTEND_FINAL_CLASS, type.getDisplayName(), finalParentClass.getDisplayName())); } } }
[ "private", "void", "checkFinalClassOverrides", "(", "Node", "ctor", ")", "{", "if", "(", "!", "isFunctionOrClass", "(", "ctor", ")", ")", "{", "return", ";", "}", "JSType", "type", "=", "ctor", ".", "getJSType", "(", ")", ".", "toMaybeFunctionType", "(", ")", ";", "if", "(", "type", "!=", "null", "&&", "type", ".", "isConstructor", "(", ")", ")", "{", "JSType", "finalParentClass", "=", "getSuperClassInstanceIfFinal", "(", "bestInstanceTypeForMethodOrCtor", "(", "ctor", ")", ")", ";", "if", "(", "finalParentClass", "!=", "null", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "ctor", ",", "EXTEND_FINAL_CLASS", ",", "type", ".", "getDisplayName", "(", ")", ",", "finalParentClass", ".", "getDisplayName", "(", ")", ")", ")", ";", "}", "}", "}" ]
Checks if a constructor is trying to override a final class.
[ "Checks", "if", "a", "constructor", "is", "trying", "to", "override", "a", "final", "class", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L661-L678
24,736
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.getCanonicalInstance
static ObjectType getCanonicalInstance(ObjectType obj) { FunctionType ctor = obj.getConstructor(); return ctor == null ? obj : ctor.getInstanceType(); }
java
static ObjectType getCanonicalInstance(ObjectType obj) { FunctionType ctor = obj.getConstructor(); return ctor == null ? obj : ctor.getInstanceType(); }
[ "static", "ObjectType", "getCanonicalInstance", "(", "ObjectType", "obj", ")", "{", "FunctionType", "ctor", "=", "obj", ".", "getConstructor", "(", ")", ";", "return", "ctor", "==", "null", "?", "obj", ":", "ctor", ".", "getInstanceType", "(", ")", ";", "}" ]
Return an object with the same nominal type as obj, but without any possible extra properties that exist on obj.
[ "Return", "an", "object", "with", "the", "same", "nominal", "type", "as", "obj", "but", "without", "any", "possible", "extra", "properties", "that", "exist", "on", "obj", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L742-L745
24,737
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.checkPropertyVisibility
private void checkPropertyVisibility(PropertyReference propRef) { if (NodeUtil.isEs6ConstructorMemberFunctionDef(propRef.getSourceNode())) { // Class ctor *declarations* can never violate visibility restrictions. They are not // accesses and we don't consider them overrides. // // TODO(nickreid): It would be a lot cleaner if we could model this using `PropertyReference` // rather than defining a special case here. I think the problem is that the current // implementation of this method conflates "override" with "declaration". But that only works // because it ignores cases where there's no overridden definition. return; } JSType rawReferenceType = typeOrUnknown(propRef.getReceiverType()).autobox(); ObjectType referenceType = castToObject(rawReferenceType); String propertyName = propRef.getName(); boolean isPrivateByConvention = isPrivateByConvention(propertyName); if (isPrivateByConvention && propertyIsDeclaredButNotPrivate(propRef)) { compiler.report(JSError.make(propRef.getSourceNode(), CONVENTION_MISMATCH)); return; } StaticSourceFile definingSource = AccessControlUtils.getDefiningSource(propRef.getSourceNode(), referenceType, propertyName); // Is this a normal property access, or are we trying to override // an existing property? boolean isOverride = propRef.isDocumentedDeclaration() || propRef.isOverride(); ObjectType objectType = AccessControlUtils.getObjectType( referenceType, isOverride, propertyName); Visibility fileOverviewVisibility = defaultVisibilityForFiles.get(definingSource); Visibility visibility = getEffectivePropertyVisibility( propRef, referenceType, defaultVisibilityForFiles, enforceCodingConventions ? compiler.getCodingConvention() : null); if (isOverride) { Visibility overriding = getOverridingPropertyVisibility(propRef); if (overriding != null) { checkPropertyOverrideVisibilityIsSame( overriding, visibility, fileOverviewVisibility, propRef); } } JSType reportType = rawReferenceType; if (objectType != null) { Node node = objectType.getOwnPropertyDefSite(propertyName); if (node == null) { // Assume the property is public. return; } reportType = objectType; definingSource = node.getStaticSourceFile(); } else if (!isPrivateByConvention && fileOverviewVisibility == null) { // We can only check visibility references if we know what file // it was defined in. // Otherwise just assume the property is public. return; } StaticSourceFile referenceSource = propRef.getSourceNode().getStaticSourceFile(); if (isOverride) { boolean sameInput = referenceSource != null && referenceSource.getName().equals(definingSource.getName()); checkPropertyOverrideVisibility( propRef, visibility, fileOverviewVisibility, reportType, sameInput); } else { checkPropertyAccessVisibility( propRef, visibility, reportType, referenceSource, definingSource); } }
java
private void checkPropertyVisibility(PropertyReference propRef) { if (NodeUtil.isEs6ConstructorMemberFunctionDef(propRef.getSourceNode())) { // Class ctor *declarations* can never violate visibility restrictions. They are not // accesses and we don't consider them overrides. // // TODO(nickreid): It would be a lot cleaner if we could model this using `PropertyReference` // rather than defining a special case here. I think the problem is that the current // implementation of this method conflates "override" with "declaration". But that only works // because it ignores cases where there's no overridden definition. return; } JSType rawReferenceType = typeOrUnknown(propRef.getReceiverType()).autobox(); ObjectType referenceType = castToObject(rawReferenceType); String propertyName = propRef.getName(); boolean isPrivateByConvention = isPrivateByConvention(propertyName); if (isPrivateByConvention && propertyIsDeclaredButNotPrivate(propRef)) { compiler.report(JSError.make(propRef.getSourceNode(), CONVENTION_MISMATCH)); return; } StaticSourceFile definingSource = AccessControlUtils.getDefiningSource(propRef.getSourceNode(), referenceType, propertyName); // Is this a normal property access, or are we trying to override // an existing property? boolean isOverride = propRef.isDocumentedDeclaration() || propRef.isOverride(); ObjectType objectType = AccessControlUtils.getObjectType( referenceType, isOverride, propertyName); Visibility fileOverviewVisibility = defaultVisibilityForFiles.get(definingSource); Visibility visibility = getEffectivePropertyVisibility( propRef, referenceType, defaultVisibilityForFiles, enforceCodingConventions ? compiler.getCodingConvention() : null); if (isOverride) { Visibility overriding = getOverridingPropertyVisibility(propRef); if (overriding != null) { checkPropertyOverrideVisibilityIsSame( overriding, visibility, fileOverviewVisibility, propRef); } } JSType reportType = rawReferenceType; if (objectType != null) { Node node = objectType.getOwnPropertyDefSite(propertyName); if (node == null) { // Assume the property is public. return; } reportType = objectType; definingSource = node.getStaticSourceFile(); } else if (!isPrivateByConvention && fileOverviewVisibility == null) { // We can only check visibility references if we know what file // it was defined in. // Otherwise just assume the property is public. return; } StaticSourceFile referenceSource = propRef.getSourceNode().getStaticSourceFile(); if (isOverride) { boolean sameInput = referenceSource != null && referenceSource.getName().equals(definingSource.getName()); checkPropertyOverrideVisibility( propRef, visibility, fileOverviewVisibility, reportType, sameInput); } else { checkPropertyAccessVisibility( propRef, visibility, reportType, referenceSource, definingSource); } }
[ "private", "void", "checkPropertyVisibility", "(", "PropertyReference", "propRef", ")", "{", "if", "(", "NodeUtil", ".", "isEs6ConstructorMemberFunctionDef", "(", "propRef", ".", "getSourceNode", "(", ")", ")", ")", "{", "// Class ctor *declarations* can never violate visibility restrictions. They are not", "// accesses and we don't consider them overrides.", "//", "// TODO(nickreid): It would be a lot cleaner if we could model this using `PropertyReference`", "// rather than defining a special case here. I think the problem is that the current", "// implementation of this method conflates \"override\" with \"declaration\". But that only works", "// because it ignores cases where there's no overridden definition.", "return", ";", "}", "JSType", "rawReferenceType", "=", "typeOrUnknown", "(", "propRef", ".", "getReceiverType", "(", ")", ")", ".", "autobox", "(", ")", ";", "ObjectType", "referenceType", "=", "castToObject", "(", "rawReferenceType", ")", ";", "String", "propertyName", "=", "propRef", ".", "getName", "(", ")", ";", "boolean", "isPrivateByConvention", "=", "isPrivateByConvention", "(", "propertyName", ")", ";", "if", "(", "isPrivateByConvention", "&&", "propertyIsDeclaredButNotPrivate", "(", "propRef", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "propRef", ".", "getSourceNode", "(", ")", ",", "CONVENTION_MISMATCH", ")", ")", ";", "return", ";", "}", "StaticSourceFile", "definingSource", "=", "AccessControlUtils", ".", "getDefiningSource", "(", "propRef", ".", "getSourceNode", "(", ")", ",", "referenceType", ",", "propertyName", ")", ";", "// Is this a normal property access, or are we trying to override", "// an existing property?", "boolean", "isOverride", "=", "propRef", ".", "isDocumentedDeclaration", "(", ")", "||", "propRef", ".", "isOverride", "(", ")", ";", "ObjectType", "objectType", "=", "AccessControlUtils", ".", "getObjectType", "(", "referenceType", ",", "isOverride", ",", "propertyName", ")", ";", "Visibility", "fileOverviewVisibility", "=", "defaultVisibilityForFiles", ".", "get", "(", "definingSource", ")", ";", "Visibility", "visibility", "=", "getEffectivePropertyVisibility", "(", "propRef", ",", "referenceType", ",", "defaultVisibilityForFiles", ",", "enforceCodingConventions", "?", "compiler", ".", "getCodingConvention", "(", ")", ":", "null", ")", ";", "if", "(", "isOverride", ")", "{", "Visibility", "overriding", "=", "getOverridingPropertyVisibility", "(", "propRef", ")", ";", "if", "(", "overriding", "!=", "null", ")", "{", "checkPropertyOverrideVisibilityIsSame", "(", "overriding", ",", "visibility", ",", "fileOverviewVisibility", ",", "propRef", ")", ";", "}", "}", "JSType", "reportType", "=", "rawReferenceType", ";", "if", "(", "objectType", "!=", "null", ")", "{", "Node", "node", "=", "objectType", ".", "getOwnPropertyDefSite", "(", "propertyName", ")", ";", "if", "(", "node", "==", "null", ")", "{", "// Assume the property is public.", "return", ";", "}", "reportType", "=", "objectType", ";", "definingSource", "=", "node", ".", "getStaticSourceFile", "(", ")", ";", "}", "else", "if", "(", "!", "isPrivateByConvention", "&&", "fileOverviewVisibility", "==", "null", ")", "{", "// We can only check visibility references if we know what file", "// it was defined in.", "// Otherwise just assume the property is public.", "return", ";", "}", "StaticSourceFile", "referenceSource", "=", "propRef", ".", "getSourceNode", "(", ")", ".", "getStaticSourceFile", "(", ")", ";", "if", "(", "isOverride", ")", "{", "boolean", "sameInput", "=", "referenceSource", "!=", "null", "&&", "referenceSource", ".", "getName", "(", ")", ".", "equals", "(", "definingSource", ".", "getName", "(", ")", ")", ";", "checkPropertyOverrideVisibility", "(", "propRef", ",", "visibility", ",", "fileOverviewVisibility", ",", "reportType", ",", "sameInput", ")", ";", "}", "else", "{", "checkPropertyAccessVisibility", "(", "propRef", ",", "visibility", ",", "reportType", ",", "referenceSource", ",", "definingSource", ")", ";", "}", "}" ]
Reports an error if the given property is not visible in the current context. <p>This method covers both: <ul> <li>accesses to properties during execution <li>overrides of properties during declaration </ul> TODO(nickreid): Things would probably be a lot simpler, though a bit duplicated, if these two concepts were separated. Much of the underlying logic could stop checking various inconsistent definitions of "is this an override".
[ "Reports", "an", "error", "if", "the", "given", "property", "is", "not", "visible", "in", "the", "current", "context", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L779-L857
24,738
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.canAccessDeprecatedTypes
private boolean canAccessDeprecatedTypes(NodeTraversal t) { Node scopeRoot = t.getClosestHoistScopeRoot(); if (NodeUtil.isFunctionBlock(scopeRoot)) { scopeRoot = scopeRoot.getParent(); } Node scopeRootParent = scopeRoot.getParent(); return // Case #1 (deprecationDepth > 0) // Case #2 || (getTypeDeprecationInfo(getTypeOfThis(scopeRoot)) != null) // Case #3 || (scopeRootParent != null && scopeRootParent.isAssign() && getTypeDeprecationInfo(bestInstanceTypeForMethodOrCtor(scopeRoot)) != null); }
java
private boolean canAccessDeprecatedTypes(NodeTraversal t) { Node scopeRoot = t.getClosestHoistScopeRoot(); if (NodeUtil.isFunctionBlock(scopeRoot)) { scopeRoot = scopeRoot.getParent(); } Node scopeRootParent = scopeRoot.getParent(); return // Case #1 (deprecationDepth > 0) // Case #2 || (getTypeDeprecationInfo(getTypeOfThis(scopeRoot)) != null) // Case #3 || (scopeRootParent != null && scopeRootParent.isAssign() && getTypeDeprecationInfo(bestInstanceTypeForMethodOrCtor(scopeRoot)) != null); }
[ "private", "boolean", "canAccessDeprecatedTypes", "(", "NodeTraversal", "t", ")", "{", "Node", "scopeRoot", "=", "t", ".", "getClosestHoistScopeRoot", "(", ")", ";", "if", "(", "NodeUtil", ".", "isFunctionBlock", "(", "scopeRoot", ")", ")", "{", "scopeRoot", "=", "scopeRoot", ".", "getParent", "(", ")", ";", "}", "Node", "scopeRootParent", "=", "scopeRoot", ".", "getParent", "(", ")", ";", "return", "// Case #1", "(", "deprecationDepth", ">", "0", ")", "// Case #2", "||", "(", "getTypeDeprecationInfo", "(", "getTypeOfThis", "(", "scopeRoot", ")", ")", "!=", "null", ")", "// Case #3", "||", "(", "scopeRootParent", "!=", "null", "&&", "scopeRootParent", ".", "isAssign", "(", ")", "&&", "getTypeDeprecationInfo", "(", "bestInstanceTypeForMethodOrCtor", "(", "scopeRoot", ")", ")", "!=", "null", ")", ";", "}" ]
Returns whether it's currently OK to access deprecated names and properties. There are 3 exceptions when we're allowed to use a deprecated type or property: 1) When we're in a deprecated function. 2) When we're in a deprecated class. 3) When we're in a static method of a deprecated class.
[ "Returns", "whether", "it", "s", "currently", "OK", "to", "access", "deprecated", "names", "and", "properties", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L1109-L1125
24,739
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.getTypeDeprecationInfo
private static String getTypeDeprecationInfo(JSType type) { if (type == null) { return null; } String depReason = getDeprecationReason(type.getJSDocInfo()); if (depReason != null) { return depReason; } ObjectType objType = castToObject(type); if (objType != null) { ObjectType implicitProto = objType.getImplicitPrototype(); if (implicitProto != null) { return getTypeDeprecationInfo(implicitProto); } } return null; }
java
private static String getTypeDeprecationInfo(JSType type) { if (type == null) { return null; } String depReason = getDeprecationReason(type.getJSDocInfo()); if (depReason != null) { return depReason; } ObjectType objType = castToObject(type); if (objType != null) { ObjectType implicitProto = objType.getImplicitPrototype(); if (implicitProto != null) { return getTypeDeprecationInfo(implicitProto); } } return null; }
[ "private", "static", "String", "getTypeDeprecationInfo", "(", "JSType", "type", ")", "{", "if", "(", "type", "==", "null", ")", "{", "return", "null", ";", "}", "String", "depReason", "=", "getDeprecationReason", "(", "type", ".", "getJSDocInfo", "(", ")", ")", ";", "if", "(", "depReason", "!=", "null", ")", "{", "return", "depReason", ";", "}", "ObjectType", "objType", "=", "castToObject", "(", "type", ")", ";", "if", "(", "objType", "!=", "null", ")", "{", "ObjectType", "implicitProto", "=", "objType", ".", "getImplicitPrototype", "(", ")", ";", "if", "(", "implicitProto", "!=", "null", ")", "{", "return", "getTypeDeprecationInfo", "(", "implicitProto", ")", ";", "}", "}", "return", "null", ";", "}" ]
Returns the deprecation reason for the type if it is marked as being deprecated. Returns empty string if the type is deprecated but no reason was given. Returns null if the type is not deprecated.
[ "Returns", "the", "deprecation", "reason", "for", "the", "type", "if", "it", "is", "marked", "as", "being", "deprecated", ".", "Returns", "empty", "string", "if", "the", "type", "is", "deprecated", "but", "no", "reason", "was", "given", ".", "Returns", "null", "if", "the", "type", "is", "not", "deprecated", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L1140-L1158
24,740
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.isPropertyDeclaredConstant
private boolean isPropertyDeclaredConstant( ObjectType objectType, String prop) { if (enforceCodingConventions && compiler.getCodingConvention().isConstant(prop)) { return true; } for (; objectType != null; objectType = objectType.getImplicitPrototype()) { JSDocInfo docInfo = objectType.getOwnPropertyJSDocInfo(prop); if (docInfo != null && docInfo.isConstant()) { return true; } } return false; }
java
private boolean isPropertyDeclaredConstant( ObjectType objectType, String prop) { if (enforceCodingConventions && compiler.getCodingConvention().isConstant(prop)) { return true; } for (; objectType != null; objectType = objectType.getImplicitPrototype()) { JSDocInfo docInfo = objectType.getOwnPropertyJSDocInfo(prop); if (docInfo != null && docInfo.isConstant()) { return true; } } return false; }
[ "private", "boolean", "isPropertyDeclaredConstant", "(", "ObjectType", "objectType", ",", "String", "prop", ")", "{", "if", "(", "enforceCodingConventions", "&&", "compiler", ".", "getCodingConvention", "(", ")", ".", "isConstant", "(", "prop", ")", ")", "{", "return", "true", ";", "}", "for", "(", ";", "objectType", "!=", "null", ";", "objectType", "=", "objectType", ".", "getImplicitPrototype", "(", ")", ")", "{", "JSDocInfo", "docInfo", "=", "objectType", ".", "getOwnPropertyJSDocInfo", "(", "prop", ")", ";", "if", "(", "docInfo", "!=", "null", "&&", "docInfo", ".", "isConstant", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns if a property is declared constant.
[ "Returns", "if", "a", "property", "is", "declared", "constant", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L1173-L1186
24,741
google/closure-compiler
src/com/google/javascript/jscomp/CheckAccessControls.java
CheckAccessControls.getPropertyDeprecationInfo
@Nullable private static String getPropertyDeprecationInfo(ObjectType type, String prop) { String depReason = getDeprecationReason(type.getOwnPropertyJSDocInfo(prop)); if (depReason != null) { return depReason; } ObjectType implicitProto = type.getImplicitPrototype(); if (implicitProto != null) { return getPropertyDeprecationInfo(implicitProto, prop); } return null; }
java
@Nullable private static String getPropertyDeprecationInfo(ObjectType type, String prop) { String depReason = getDeprecationReason(type.getOwnPropertyJSDocInfo(prop)); if (depReason != null) { return depReason; } ObjectType implicitProto = type.getImplicitPrototype(); if (implicitProto != null) { return getPropertyDeprecationInfo(implicitProto, prop); } return null; }
[ "@", "Nullable", "private", "static", "String", "getPropertyDeprecationInfo", "(", "ObjectType", "type", ",", "String", "prop", ")", "{", "String", "depReason", "=", "getDeprecationReason", "(", "type", ".", "getOwnPropertyJSDocInfo", "(", "prop", ")", ")", ";", "if", "(", "depReason", "!=", "null", ")", "{", "return", "depReason", ";", "}", "ObjectType", "implicitProto", "=", "type", ".", "getImplicitPrototype", "(", ")", ";", "if", "(", "implicitProto", "!=", "null", ")", "{", "return", "getPropertyDeprecationInfo", "(", "implicitProto", ",", "prop", ")", ";", "}", "return", "null", ";", "}" ]
Returns the deprecation reason for the property if it is marked as being deprecated. Returns empty string if the property is deprecated but no reason was given. Returns null if the property is not deprecated.
[ "Returns", "the", "deprecation", "reason", "for", "the", "property", "if", "it", "is", "marked", "as", "being", "deprecated", ".", "Returns", "empty", "string", "if", "the", "property", "is", "deprecated", "but", "no", "reason", "was", "given", ".", "Returns", "null", "if", "the", "property", "is", "not", "deprecated", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckAccessControls.java#L1193-L1205
24,742
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteRestAndSpread.java
Es6RewriteRestAndSpread.visitArrayLitOrCallWithSpread
private void visitArrayLitOrCallWithSpread(Node spreadParent) { if (spreadParent.isArrayLit()) { visitArrayLitContainingSpread(spreadParent); } else if (spreadParent.isCall()) { visitCallContainingSpread(spreadParent); } else { checkArgument(spreadParent.isNew(), spreadParent); visitNewWithSpread(spreadParent); } }
java
private void visitArrayLitOrCallWithSpread(Node spreadParent) { if (spreadParent.isArrayLit()) { visitArrayLitContainingSpread(spreadParent); } else if (spreadParent.isCall()) { visitCallContainingSpread(spreadParent); } else { checkArgument(spreadParent.isNew(), spreadParent); visitNewWithSpread(spreadParent); } }
[ "private", "void", "visitArrayLitOrCallWithSpread", "(", "Node", "spreadParent", ")", "{", "if", "(", "spreadParent", ".", "isArrayLit", "(", ")", ")", "{", "visitArrayLitContainingSpread", "(", "spreadParent", ")", ";", "}", "else", "if", "(", "spreadParent", ".", "isCall", "(", ")", ")", "{", "visitCallContainingSpread", "(", "spreadParent", ")", ";", "}", "else", "{", "checkArgument", "(", "spreadParent", ".", "isNew", "(", ")", ",", "spreadParent", ")", ";", "visitNewWithSpread", "(", "spreadParent", ")", ";", "}", "}" ]
Processes array literals or calls to eliminate spreads. <p>Examples: <ul> <li>[1, 2, ...x, 4, 5] => [].concat([1, 2], $jscomp.arrayFromIterable(x), [4, 5]) <li>f(1, ...arr) => f.apply(null, [1].concat($jscomp.arrayFromIterable(arr))) <li>new F(...args) => new Function.prototype.bind.apply(F, [null].concat($jscomp.arrayFromIterable(args))) </ul>
[ "Processes", "array", "literals", "or", "calls", "to", "eliminate", "spreads", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteRestAndSpread.java#L222-L231
24,743
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteRestAndSpread.java
Es6RewriteRestAndSpread.visitArrayLitContainingSpread
private void visitArrayLitContainingSpread(Node spreadParent) { checkArgument(spreadParent.isArrayLit()); List<Node> groups = extractSpreadGroups(spreadParent); final Node baseArrayLit; if (groups.get(0).isArrayLit()) { // g0.concat(g1, g2, ..., gn) baseArrayLit = groups.remove(0); } else { // [].concat(g0, g1, g2, ..., gn) baseArrayLit = arrayLitWithJSType(); } final Node joinedGroups; if (groups.isEmpty()) { joinedGroups = baseArrayLit; } else { Node concat = IR.getprop(baseArrayLit, IR.string("concat")).setJSType(concatFnType); joinedGroups = IR.call(concat, groups.toArray(new Node[0])); } joinedGroups.useSourceInfoIfMissingFromForTree(spreadParent); joinedGroups.setJSType(arrayType); spreadParent.replaceWith(joinedGroups); compiler.reportChangeToEnclosingScope(joinedGroups); }
java
private void visitArrayLitContainingSpread(Node spreadParent) { checkArgument(spreadParent.isArrayLit()); List<Node> groups = extractSpreadGroups(spreadParent); final Node baseArrayLit; if (groups.get(0).isArrayLit()) { // g0.concat(g1, g2, ..., gn) baseArrayLit = groups.remove(0); } else { // [].concat(g0, g1, g2, ..., gn) baseArrayLit = arrayLitWithJSType(); } final Node joinedGroups; if (groups.isEmpty()) { joinedGroups = baseArrayLit; } else { Node concat = IR.getprop(baseArrayLit, IR.string("concat")).setJSType(concatFnType); joinedGroups = IR.call(concat, groups.toArray(new Node[0])); } joinedGroups.useSourceInfoIfMissingFromForTree(spreadParent); joinedGroups.setJSType(arrayType); spreadParent.replaceWith(joinedGroups); compiler.reportChangeToEnclosingScope(joinedGroups); }
[ "private", "void", "visitArrayLitContainingSpread", "(", "Node", "spreadParent", ")", "{", "checkArgument", "(", "spreadParent", ".", "isArrayLit", "(", ")", ")", ";", "List", "<", "Node", ">", "groups", "=", "extractSpreadGroups", "(", "spreadParent", ")", ";", "final", "Node", "baseArrayLit", ";", "if", "(", "groups", ".", "get", "(", "0", ")", ".", "isArrayLit", "(", ")", ")", "{", "// g0.concat(g1, g2, ..., gn)", "baseArrayLit", "=", "groups", ".", "remove", "(", "0", ")", ";", "}", "else", "{", "// [].concat(g0, g1, g2, ..., gn)", "baseArrayLit", "=", "arrayLitWithJSType", "(", ")", ";", "}", "final", "Node", "joinedGroups", ";", "if", "(", "groups", ".", "isEmpty", "(", ")", ")", "{", "joinedGroups", "=", "baseArrayLit", ";", "}", "else", "{", "Node", "concat", "=", "IR", ".", "getprop", "(", "baseArrayLit", ",", "IR", ".", "string", "(", "\"concat\"", ")", ")", ".", "setJSType", "(", "concatFnType", ")", ";", "joinedGroups", "=", "IR", ".", "call", "(", "concat", ",", "groups", ".", "toArray", "(", "new", "Node", "[", "0", "]", ")", ")", ";", "}", "joinedGroups", ".", "useSourceInfoIfMissingFromForTree", "(", "spreadParent", ")", ";", "joinedGroups", ".", "setJSType", "(", "arrayType", ")", ";", "spreadParent", ".", "replaceWith", "(", "joinedGroups", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "joinedGroups", ")", ";", "}" ]
Processes array literals containing spreads. <p>Example: <pre><code> [1, 2, ...x, 4, 5] => [1, 2].concat($jscomp.arrayFromIterable(x), [4, 5]) </code></pre>
[ "Processes", "array", "literals", "containing", "spreads", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteRestAndSpread.java#L309-L336
24,744
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteRestAndSpread.java
Es6RewriteRestAndSpread.visitCallContainingSpread
private void visitCallContainingSpread(Node spreadParent) { checkArgument(spreadParent.isCall()); Node callee = spreadParent.getFirstChild(); // Check if the callee has side effects before removing it from the AST (since some NodeUtil // methods assume the node they are passed has a non-null parent). boolean calleeMayHaveSideEffects = NodeUtil.mayHaveSideEffects(callee, compiler); // Must remove callee before extracting argument groups. spreadParent.removeChild(callee); final Node joinedGroups; if (spreadParent.hasOneChild() && isSpreadOfArguments(spreadParent.getOnlyChild())) { // Check for special case of `foo(...arguments)` and pass `arguments` directly to // `foo.apply(null, arguments)`. We want to avoid calling $jscomp.arrayFromIterable(arguments) // for this case, because it can have side effects, which prevents code removal. // // TODO(b/74074478): Generalize this to avoid ever calling $jscomp.arrayFromIterable() for // `arguments`. joinedGroups = spreadParent.removeFirstChild().removeFirstChild(); } else { List<Node> groups = extractSpreadGroups(spreadParent); checkState(!groups.isEmpty()); if (groups.size() == 1) { // A single group can just be passed to `apply()` as-is // It could be `arguments`, an array literal, or $jscomp.arrayFromIterable(someExpression). joinedGroups = groups.remove(0); } else { // If the first group is an array literal, we can just use that for concatenation, // otherwise use an empty array literal. // // TODO(nickreid): Stop distringuishing between array literals and variables when this pass // is moved after type-checking. Node baseArrayLit = groups.get(0).isArrayLit() ? groups.remove(0) : arrayLitWithJSType(); Node concat = IR.getprop(baseArrayLit, IR.string("concat")).setJSType(concatFnType); joinedGroups = IR.call(concat, groups.toArray(new Node[0])).setJSType(arrayType); } joinedGroups.setJSType(arrayType); } final Node callToApply; if (calleeMayHaveSideEffects && callee.isGetProp()) { JSType receiverType = callee.getFirstChild().getJSType(); // Type of `foo()`. // foo().method(...[a, b, c]) // must convert to // var freshVar; // (freshVar = foo()).method.apply(freshVar, [a, b, c]) Node freshVar = IR.name(FRESH_SPREAD_VAR + compiler.getUniqueNameIdSupplier().get()) .setJSType(receiverType); Node freshVarDeclaration = IR.var(freshVar.cloneTree()); Node statementContainingSpread = NodeUtil.getEnclosingStatement(spreadParent); freshVarDeclaration.useSourceInfoIfMissingFromForTree(statementContainingSpread); statementContainingSpread .getParent() .addChildBefore(freshVarDeclaration, statementContainingSpread); callee.addChildToFront( IR.assign(freshVar.cloneTree(), callee.removeFirstChild()).setJSType(receiverType)); callToApply = IR.call(getpropInferringJSType(callee, "apply"), freshVar.cloneTree(), joinedGroups); } else { // foo.method(...[a, b, c]) -> foo.method.apply(foo, [a, b, c]) // foo['method'](...[a, b, c]) -> foo['method'].apply(foo, [a, b, c]) // or // foo(...[a, b, c]) -> foo.apply(null, [a, b, c]) Node context = (callee.isGetProp() || callee.isGetElem()) ? callee.getFirstChild().cloneTree() : nullWithJSType(); callToApply = IR.call(getpropInferringJSType(callee, "apply"), context, joinedGroups); } callToApply.setJSType(spreadParent.getJSType()); callToApply.useSourceInfoIfMissingFromForTree(spreadParent); spreadParent.replaceWith(callToApply); compiler.reportChangeToEnclosingScope(callToApply); }
java
private void visitCallContainingSpread(Node spreadParent) { checkArgument(spreadParent.isCall()); Node callee = spreadParent.getFirstChild(); // Check if the callee has side effects before removing it from the AST (since some NodeUtil // methods assume the node they are passed has a non-null parent). boolean calleeMayHaveSideEffects = NodeUtil.mayHaveSideEffects(callee, compiler); // Must remove callee before extracting argument groups. spreadParent.removeChild(callee); final Node joinedGroups; if (spreadParent.hasOneChild() && isSpreadOfArguments(spreadParent.getOnlyChild())) { // Check for special case of `foo(...arguments)` and pass `arguments` directly to // `foo.apply(null, arguments)`. We want to avoid calling $jscomp.arrayFromIterable(arguments) // for this case, because it can have side effects, which prevents code removal. // // TODO(b/74074478): Generalize this to avoid ever calling $jscomp.arrayFromIterable() for // `arguments`. joinedGroups = spreadParent.removeFirstChild().removeFirstChild(); } else { List<Node> groups = extractSpreadGroups(spreadParent); checkState(!groups.isEmpty()); if (groups.size() == 1) { // A single group can just be passed to `apply()` as-is // It could be `arguments`, an array literal, or $jscomp.arrayFromIterable(someExpression). joinedGroups = groups.remove(0); } else { // If the first group is an array literal, we can just use that for concatenation, // otherwise use an empty array literal. // // TODO(nickreid): Stop distringuishing between array literals and variables when this pass // is moved after type-checking. Node baseArrayLit = groups.get(0).isArrayLit() ? groups.remove(0) : arrayLitWithJSType(); Node concat = IR.getprop(baseArrayLit, IR.string("concat")).setJSType(concatFnType); joinedGroups = IR.call(concat, groups.toArray(new Node[0])).setJSType(arrayType); } joinedGroups.setJSType(arrayType); } final Node callToApply; if (calleeMayHaveSideEffects && callee.isGetProp()) { JSType receiverType = callee.getFirstChild().getJSType(); // Type of `foo()`. // foo().method(...[a, b, c]) // must convert to // var freshVar; // (freshVar = foo()).method.apply(freshVar, [a, b, c]) Node freshVar = IR.name(FRESH_SPREAD_VAR + compiler.getUniqueNameIdSupplier().get()) .setJSType(receiverType); Node freshVarDeclaration = IR.var(freshVar.cloneTree()); Node statementContainingSpread = NodeUtil.getEnclosingStatement(spreadParent); freshVarDeclaration.useSourceInfoIfMissingFromForTree(statementContainingSpread); statementContainingSpread .getParent() .addChildBefore(freshVarDeclaration, statementContainingSpread); callee.addChildToFront( IR.assign(freshVar.cloneTree(), callee.removeFirstChild()).setJSType(receiverType)); callToApply = IR.call(getpropInferringJSType(callee, "apply"), freshVar.cloneTree(), joinedGroups); } else { // foo.method(...[a, b, c]) -> foo.method.apply(foo, [a, b, c]) // foo['method'](...[a, b, c]) -> foo['method'].apply(foo, [a, b, c]) // or // foo(...[a, b, c]) -> foo.apply(null, [a, b, c]) Node context = (callee.isGetProp() || callee.isGetElem()) ? callee.getFirstChild().cloneTree() : nullWithJSType(); callToApply = IR.call(getpropInferringJSType(callee, "apply"), context, joinedGroups); } callToApply.setJSType(spreadParent.getJSType()); callToApply.useSourceInfoIfMissingFromForTree(spreadParent); spreadParent.replaceWith(callToApply); compiler.reportChangeToEnclosingScope(callToApply); }
[ "private", "void", "visitCallContainingSpread", "(", "Node", "spreadParent", ")", "{", "checkArgument", "(", "spreadParent", ".", "isCall", "(", ")", ")", ";", "Node", "callee", "=", "spreadParent", ".", "getFirstChild", "(", ")", ";", "// Check if the callee has side effects before removing it from the AST (since some NodeUtil", "// methods assume the node they are passed has a non-null parent).", "boolean", "calleeMayHaveSideEffects", "=", "NodeUtil", ".", "mayHaveSideEffects", "(", "callee", ",", "compiler", ")", ";", "// Must remove callee before extracting argument groups.", "spreadParent", ".", "removeChild", "(", "callee", ")", ";", "final", "Node", "joinedGroups", ";", "if", "(", "spreadParent", ".", "hasOneChild", "(", ")", "&&", "isSpreadOfArguments", "(", "spreadParent", ".", "getOnlyChild", "(", ")", ")", ")", "{", "// Check for special case of `foo(...arguments)` and pass `arguments` directly to", "// `foo.apply(null, arguments)`. We want to avoid calling $jscomp.arrayFromIterable(arguments)", "// for this case, because it can have side effects, which prevents code removal.", "//", "// TODO(b/74074478): Generalize this to avoid ever calling $jscomp.arrayFromIterable() for", "// `arguments`.", "joinedGroups", "=", "spreadParent", ".", "removeFirstChild", "(", ")", ".", "removeFirstChild", "(", ")", ";", "}", "else", "{", "List", "<", "Node", ">", "groups", "=", "extractSpreadGroups", "(", "spreadParent", ")", ";", "checkState", "(", "!", "groups", ".", "isEmpty", "(", ")", ")", ";", "if", "(", "groups", ".", "size", "(", ")", "==", "1", ")", "{", "// A single group can just be passed to `apply()` as-is", "// It could be `arguments`, an array literal, or $jscomp.arrayFromIterable(someExpression).", "joinedGroups", "=", "groups", ".", "remove", "(", "0", ")", ";", "}", "else", "{", "// If the first group is an array literal, we can just use that for concatenation,", "// otherwise use an empty array literal.", "//", "// TODO(nickreid): Stop distringuishing between array literals and variables when this pass", "// is moved after type-checking.", "Node", "baseArrayLit", "=", "groups", ".", "get", "(", "0", ")", ".", "isArrayLit", "(", ")", "?", "groups", ".", "remove", "(", "0", ")", ":", "arrayLitWithJSType", "(", ")", ";", "Node", "concat", "=", "IR", ".", "getprop", "(", "baseArrayLit", ",", "IR", ".", "string", "(", "\"concat\"", ")", ")", ".", "setJSType", "(", "concatFnType", ")", ";", "joinedGroups", "=", "IR", ".", "call", "(", "concat", ",", "groups", ".", "toArray", "(", "new", "Node", "[", "0", "]", ")", ")", ".", "setJSType", "(", "arrayType", ")", ";", "}", "joinedGroups", ".", "setJSType", "(", "arrayType", ")", ";", "}", "final", "Node", "callToApply", ";", "if", "(", "calleeMayHaveSideEffects", "&&", "callee", ".", "isGetProp", "(", ")", ")", "{", "JSType", "receiverType", "=", "callee", ".", "getFirstChild", "(", ")", ".", "getJSType", "(", ")", ";", "// Type of `foo()`.", "// foo().method(...[a, b, c])", "// must convert to", "// var freshVar;", "// (freshVar = foo()).method.apply(freshVar, [a, b, c])", "Node", "freshVar", "=", "IR", ".", "name", "(", "FRESH_SPREAD_VAR", "+", "compiler", ".", "getUniqueNameIdSupplier", "(", ")", ".", "get", "(", ")", ")", ".", "setJSType", "(", "receiverType", ")", ";", "Node", "freshVarDeclaration", "=", "IR", ".", "var", "(", "freshVar", ".", "cloneTree", "(", ")", ")", ";", "Node", "statementContainingSpread", "=", "NodeUtil", ".", "getEnclosingStatement", "(", "spreadParent", ")", ";", "freshVarDeclaration", ".", "useSourceInfoIfMissingFromForTree", "(", "statementContainingSpread", ")", ";", "statementContainingSpread", ".", "getParent", "(", ")", ".", "addChildBefore", "(", "freshVarDeclaration", ",", "statementContainingSpread", ")", ";", "callee", ".", "addChildToFront", "(", "IR", ".", "assign", "(", "freshVar", ".", "cloneTree", "(", ")", ",", "callee", ".", "removeFirstChild", "(", ")", ")", ".", "setJSType", "(", "receiverType", ")", ")", ";", "callToApply", "=", "IR", ".", "call", "(", "getpropInferringJSType", "(", "callee", ",", "\"apply\"", ")", ",", "freshVar", ".", "cloneTree", "(", ")", ",", "joinedGroups", ")", ";", "}", "else", "{", "// foo.method(...[a, b, c]) -> foo.method.apply(foo, [a, b, c])", "// foo['method'](...[a, b, c]) -> foo['method'].apply(foo, [a, b, c])", "// or", "// foo(...[a, b, c]) -> foo.apply(null, [a, b, c])", "Node", "context", "=", "(", "callee", ".", "isGetProp", "(", ")", "||", "callee", ".", "isGetElem", "(", ")", ")", "?", "callee", ".", "getFirstChild", "(", ")", ".", "cloneTree", "(", ")", ":", "nullWithJSType", "(", ")", ";", "callToApply", "=", "IR", ".", "call", "(", "getpropInferringJSType", "(", "callee", ",", "\"apply\"", ")", ",", "context", ",", "joinedGroups", ")", ";", "}", "callToApply", ".", "setJSType", "(", "spreadParent", ".", "getJSType", "(", ")", ")", ";", "callToApply", ".", "useSourceInfoIfMissingFromForTree", "(", "spreadParent", ")", ";", "spreadParent", ".", "replaceWith", "(", "callToApply", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "callToApply", ")", ";", "}" ]
Processes calls containing spreads. <p>Examples: <pre><code> f(...arr) => f.apply(null, $jscomp.arrayFromIterable(arr)) f(a, ...arr) => f.apply(null, [a].concat($jscomp.arrayFromIterable(arr))) f(...arr, b) => f.apply(null, [].concat($jscomp.arrayFromIterable(arr), [b])) </code></pre>
[ "Processes", "calls", "containing", "spreads", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteRestAndSpread.java#L349-L429
24,745
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteRestAndSpread.java
Es6RewriteRestAndSpread.visitNewWithSpread
private void visitNewWithSpread(Node spreadParent) { checkArgument(spreadParent.isNew()); // Must remove callee before extracting argument groups. Node callee = spreadParent.removeFirstChild(); List<Node> groups = extractSpreadGroups(spreadParent); // We need to generate // `new (Function.prototype.bind.apply(callee, [null].concat(other, args))();`. // `null` stands in for the 'this' arg to the contructor. final Node baseArrayLit; if (groups.get(0).isArrayLit()) { baseArrayLit = groups.remove(0); } else { baseArrayLit = arrayLitWithJSType(); } baseArrayLit.addChildToFront(nullWithJSType()); Node joinedGroups = groups.isEmpty() ? baseArrayLit : IR.call( IR.getprop(baseArrayLit, IR.string("concat")).setJSType(concatFnType), groups.toArray(new Node[0])) .setJSType(arrayType); if (FeatureSet.ES3.contains(compiler.getOptions().getOutputFeatureSet())) { // TODO(tbreisacher): Support this in ES3 too by not relying on Function.bind. Es6ToEs3Util.cannotConvert( compiler, spreadParent, "\"...\" passed to a constructor (consider using --language_out=ES5)"); } // Function.prototype.bind => // function(this:function(new:[spreadParent], ...?), ...?):function(new:[spreadParent]) // Function.prototype.bind.apply => // function(function(new:[spreadParent], ...?), !Array<?>):function(new:[spreadParent]) Node bindApply = getpropInferringJSType( IR.getprop( getpropInferringJSType( IR.name("Function").setJSType(functionFunctionType), "prototype"), "bind") .setJSType(u2uFunctionType), "apply"); Node result = IR.newNode( callInferringJSType( bindApply, callee, joinedGroups /* function(new:[spreadParent]) */)) .setJSType(spreadParent.getJSType()); result.useSourceInfoIfMissingFromForTree(spreadParent); spreadParent.replaceWith(result); compiler.reportChangeToEnclosingScope(result); }
java
private void visitNewWithSpread(Node spreadParent) { checkArgument(spreadParent.isNew()); // Must remove callee before extracting argument groups. Node callee = spreadParent.removeFirstChild(); List<Node> groups = extractSpreadGroups(spreadParent); // We need to generate // `new (Function.prototype.bind.apply(callee, [null].concat(other, args))();`. // `null` stands in for the 'this' arg to the contructor. final Node baseArrayLit; if (groups.get(0).isArrayLit()) { baseArrayLit = groups.remove(0); } else { baseArrayLit = arrayLitWithJSType(); } baseArrayLit.addChildToFront(nullWithJSType()); Node joinedGroups = groups.isEmpty() ? baseArrayLit : IR.call( IR.getprop(baseArrayLit, IR.string("concat")).setJSType(concatFnType), groups.toArray(new Node[0])) .setJSType(arrayType); if (FeatureSet.ES3.contains(compiler.getOptions().getOutputFeatureSet())) { // TODO(tbreisacher): Support this in ES3 too by not relying on Function.bind. Es6ToEs3Util.cannotConvert( compiler, spreadParent, "\"...\" passed to a constructor (consider using --language_out=ES5)"); } // Function.prototype.bind => // function(this:function(new:[spreadParent], ...?), ...?):function(new:[spreadParent]) // Function.prototype.bind.apply => // function(function(new:[spreadParent], ...?), !Array<?>):function(new:[spreadParent]) Node bindApply = getpropInferringJSType( IR.getprop( getpropInferringJSType( IR.name("Function").setJSType(functionFunctionType), "prototype"), "bind") .setJSType(u2uFunctionType), "apply"); Node result = IR.newNode( callInferringJSType( bindApply, callee, joinedGroups /* function(new:[spreadParent]) */)) .setJSType(spreadParent.getJSType()); result.useSourceInfoIfMissingFromForTree(spreadParent); spreadParent.replaceWith(result); compiler.reportChangeToEnclosingScope(result); }
[ "private", "void", "visitNewWithSpread", "(", "Node", "spreadParent", ")", "{", "checkArgument", "(", "spreadParent", ".", "isNew", "(", ")", ")", ";", "// Must remove callee before extracting argument groups.", "Node", "callee", "=", "spreadParent", ".", "removeFirstChild", "(", ")", ";", "List", "<", "Node", ">", "groups", "=", "extractSpreadGroups", "(", "spreadParent", ")", ";", "// We need to generate", "// `new (Function.prototype.bind.apply(callee, [null].concat(other, args))();`.", "// `null` stands in for the 'this' arg to the contructor.", "final", "Node", "baseArrayLit", ";", "if", "(", "groups", ".", "get", "(", "0", ")", ".", "isArrayLit", "(", ")", ")", "{", "baseArrayLit", "=", "groups", ".", "remove", "(", "0", ")", ";", "}", "else", "{", "baseArrayLit", "=", "arrayLitWithJSType", "(", ")", ";", "}", "baseArrayLit", ".", "addChildToFront", "(", "nullWithJSType", "(", ")", ")", ";", "Node", "joinedGroups", "=", "groups", ".", "isEmpty", "(", ")", "?", "baseArrayLit", ":", "IR", ".", "call", "(", "IR", ".", "getprop", "(", "baseArrayLit", ",", "IR", ".", "string", "(", "\"concat\"", ")", ")", ".", "setJSType", "(", "concatFnType", ")", ",", "groups", ".", "toArray", "(", "new", "Node", "[", "0", "]", ")", ")", ".", "setJSType", "(", "arrayType", ")", ";", "if", "(", "FeatureSet", ".", "ES3", ".", "contains", "(", "compiler", ".", "getOptions", "(", ")", ".", "getOutputFeatureSet", "(", ")", ")", ")", "{", "// TODO(tbreisacher): Support this in ES3 too by not relying on Function.bind.", "Es6ToEs3Util", ".", "cannotConvert", "(", "compiler", ",", "spreadParent", ",", "\"\\\"...\\\" passed to a constructor (consider using --language_out=ES5)\"", ")", ";", "}", "// Function.prototype.bind =>", "// function(this:function(new:[spreadParent], ...?), ...?):function(new:[spreadParent])", "// Function.prototype.bind.apply =>", "// function(function(new:[spreadParent], ...?), !Array<?>):function(new:[spreadParent])", "Node", "bindApply", "=", "getpropInferringJSType", "(", "IR", ".", "getprop", "(", "getpropInferringJSType", "(", "IR", ".", "name", "(", "\"Function\"", ")", ".", "setJSType", "(", "functionFunctionType", ")", ",", "\"prototype\"", ")", ",", "\"bind\"", ")", ".", "setJSType", "(", "u2uFunctionType", ")", ",", "\"apply\"", ")", ";", "Node", "result", "=", "IR", ".", "newNode", "(", "callInferringJSType", "(", "bindApply", ",", "callee", ",", "joinedGroups", "/* function(new:[spreadParent]) */", ")", ")", ".", "setJSType", "(", "spreadParent", ".", "getJSType", "(", ")", ")", ";", "result", ".", "useSourceInfoIfMissingFromForTree", "(", "spreadParent", ")", ";", "spreadParent", ".", "replaceWith", "(", "result", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "result", ")", ";", "}" ]
Processes new calls containing spreads. <p>Example: <pre><code> new F(...args) => new Function.prototype.bind.apply(F, [].concat($jscomp.arrayFromIterable(args))) </code></pre>
[ "Processes", "new", "calls", "containing", "spreads", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteRestAndSpread.java#L445-L499
24,746
google/closure-compiler
src/com/google/javascript/jscomp/FlowSensitiveInlineVariables.java
FlowSensitiveInlineVariables.checkPostExpressions
private static boolean checkPostExpressions( Node n, Node expressionRoot, Predicate<Node> predicate) { for (Node p = n; p != expressionRoot; p = p.getParent()) { for (Node cur = p.getNext(); cur != null; cur = cur.getNext()) { if (predicate.apply(cur)) { return true; } } } return false; }
java
private static boolean checkPostExpressions( Node n, Node expressionRoot, Predicate<Node> predicate) { for (Node p = n; p != expressionRoot; p = p.getParent()) { for (Node cur = p.getNext(); cur != null; cur = cur.getNext()) { if (predicate.apply(cur)) { return true; } } } return false; }
[ "private", "static", "boolean", "checkPostExpressions", "(", "Node", "n", ",", "Node", "expressionRoot", ",", "Predicate", "<", "Node", ">", "predicate", ")", "{", "for", "(", "Node", "p", "=", "n", ";", "p", "!=", "expressionRoot", ";", "p", "=", "p", ".", "getParent", "(", ")", ")", "{", "for", "(", "Node", "cur", "=", "p", ".", "getNext", "(", ")", ";", "cur", "!=", "null", ";", "cur", "=", "cur", ".", "getNext", "(", ")", ")", "{", "if", "(", "predicate", ".", "apply", "(", "cur", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Given an expression by its root and sub-expression n, return true if the predicate is true for some expression evaluated after n. <p>NOTE: this doesn't correctly check destructuring patterns, because their order of evaluation is different from AST traversal order, but currently this is ok because FlowSensitiveInlineVariables never inlines variable assignments inside destructuring. <p>Example: <p>NotChecked(), NotChecked(), n, Checked(), Checked();
[ "Given", "an", "expression", "by", "its", "root", "and", "sub", "-", "expression", "n", "return", "true", "if", "the", "predicate", "is", "true", "for", "some", "expression", "evaluated", "after", "n", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FlowSensitiveInlineVariables.java#L662-L672
24,747
google/closure-compiler
src/com/google/javascript/jscomp/FlowSensitiveInlineVariables.java
FlowSensitiveInlineVariables.checkPreExpressions
private static boolean checkPreExpressions( Node n, Node expressionRoot, Predicate<Node> predicate) { for (Node p = n; p != expressionRoot; p = p.getParent()) { Node oldestSibling = p.getParent().getFirstChild(); // Evaluate a destructuring assignment right-to-left. if (oldestSibling.isDestructuringPattern()) { if (p.isDestructuringPattern()) { if (p.getNext() != null && predicate.apply(p.getNext())) { return true; } } continue; } for (Node cur = oldestSibling; cur != p; cur = cur.getNext()) { if (predicate.apply(cur)) { return true; } } } return false; }
java
private static boolean checkPreExpressions( Node n, Node expressionRoot, Predicate<Node> predicate) { for (Node p = n; p != expressionRoot; p = p.getParent()) { Node oldestSibling = p.getParent().getFirstChild(); // Evaluate a destructuring assignment right-to-left. if (oldestSibling.isDestructuringPattern()) { if (p.isDestructuringPattern()) { if (p.getNext() != null && predicate.apply(p.getNext())) { return true; } } continue; } for (Node cur = oldestSibling; cur != p; cur = cur.getNext()) { if (predicate.apply(cur)) { return true; } } } return false; }
[ "private", "static", "boolean", "checkPreExpressions", "(", "Node", "n", ",", "Node", "expressionRoot", ",", "Predicate", "<", "Node", ">", "predicate", ")", "{", "for", "(", "Node", "p", "=", "n", ";", "p", "!=", "expressionRoot", ";", "p", "=", "p", ".", "getParent", "(", ")", ")", "{", "Node", "oldestSibling", "=", "p", ".", "getParent", "(", ")", ".", "getFirstChild", "(", ")", ";", "// Evaluate a destructuring assignment right-to-left.", "if", "(", "oldestSibling", ".", "isDestructuringPattern", "(", ")", ")", "{", "if", "(", "p", ".", "isDestructuringPattern", "(", ")", ")", "{", "if", "(", "p", ".", "getNext", "(", ")", "!=", "null", "&&", "predicate", ".", "apply", "(", "p", ".", "getNext", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "continue", ";", "}", "for", "(", "Node", "cur", "=", "oldestSibling", ";", "cur", "!=", "p", ";", "cur", "=", "cur", ".", "getNext", "(", ")", ")", "{", "if", "(", "predicate", ".", "apply", "(", "cur", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Given an expression by its root and sub-expression n, return true if the predicate is true for some expression evaluated before n. <p>In most cases evaluation order follows left-to-right AST order. Destructuring pattern evaluation is an exception. <p>Example: <p>Checked(), Checked(), n, NotChecked(), NotChecked();
[ "Given", "an", "expression", "by", "its", "root", "and", "sub", "-", "expression", "n", "return", "true", "if", "the", "predicate", "is", "true", "for", "some", "expression", "evaluated", "before", "n", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FlowSensitiveInlineVariables.java#L685-L705
24,748
google/closure-compiler
src/com/google/javascript/jscomp/PolymerClassDefinition.java
PolymerClassDefinition.extractFromClassNode
@Nullable static PolymerClassDefinition extractFromClassNode( Node classNode, AbstractCompiler compiler, GlobalNamespace globalNames) { checkState(classNode != null && classNode.isClass()); // The supported case is for the config getter to return an object literal descriptor. Node propertiesDescriptor = null; Node propertiesGetter = NodeUtil.getFirstGetterMatchingKey(NodeUtil.getClassMembers(classNode), "properties"); if (propertiesGetter != null) { if (!propertiesGetter.isStaticMember()) { // report bad class definition compiler.report( JSError.make(classNode, PolymerPassErrors.POLYMER_CLASS_PROPERTIES_NOT_STATIC)); } else { for (Node child : NodeUtil.getFunctionBody(propertiesGetter.getFirstChild()).children()) { if (child.isReturn()) { if (child.hasChildren() && child.getFirstChild().isObjectLit()) { propertiesDescriptor = child.getFirstChild(); break; } else { compiler.report( JSError.make( propertiesGetter, PolymerPassErrors.POLYMER_CLASS_PROPERTIES_INVALID)); } } } } } Node target; if (NodeUtil.isNameDeclaration(classNode.getGrandparent())) { target = IR.name(classNode.getParent().getString()); } else if (classNode.getParent().isAssign() && classNode.getParent().getFirstChild().isQualifiedName()) { target = classNode.getParent().getFirstChild(); } else if (!classNode.getFirstChild().isEmpty()) { target = classNode.getFirstChild(); } else { // issue error - no name found compiler.report(JSError.make(classNode, PolymerPassErrors.POLYMER_CLASS_UNNAMED)); return null; } JSDocInfo classInfo = NodeUtil.getBestJSDocInfo(classNode); JSDocInfo ctorInfo = null; Node constructor = NodeUtil.getEs6ClassConstructorMemberFunctionDef(classNode); if (constructor != null) { ctorInfo = NodeUtil.getBestJSDocInfo(constructor); } List<MemberDefinition> allProperties = PolymerPassStaticUtils.extractProperties( propertiesDescriptor, DefinitionType.ES6Class, compiler, constructor); List<MemberDefinition> methods = new ArrayList<>(); for (Node keyNode : NodeUtil.getClassMembers(classNode).children()) { if (!keyNode.isMemberFunctionDef()) { continue; } methods.add(new MemberDefinition( NodeUtil.getBestJSDocInfo(keyNode), keyNode, keyNode.getFirstChild())); } return new PolymerClassDefinition( DefinitionType.ES6Class, classNode, target, propertiesDescriptor, classInfo, new MemberDefinition(ctorInfo, null, constructor), null, allProperties, methods, null, null); }
java
@Nullable static PolymerClassDefinition extractFromClassNode( Node classNode, AbstractCompiler compiler, GlobalNamespace globalNames) { checkState(classNode != null && classNode.isClass()); // The supported case is for the config getter to return an object literal descriptor. Node propertiesDescriptor = null; Node propertiesGetter = NodeUtil.getFirstGetterMatchingKey(NodeUtil.getClassMembers(classNode), "properties"); if (propertiesGetter != null) { if (!propertiesGetter.isStaticMember()) { // report bad class definition compiler.report( JSError.make(classNode, PolymerPassErrors.POLYMER_CLASS_PROPERTIES_NOT_STATIC)); } else { for (Node child : NodeUtil.getFunctionBody(propertiesGetter.getFirstChild()).children()) { if (child.isReturn()) { if (child.hasChildren() && child.getFirstChild().isObjectLit()) { propertiesDescriptor = child.getFirstChild(); break; } else { compiler.report( JSError.make( propertiesGetter, PolymerPassErrors.POLYMER_CLASS_PROPERTIES_INVALID)); } } } } } Node target; if (NodeUtil.isNameDeclaration(classNode.getGrandparent())) { target = IR.name(classNode.getParent().getString()); } else if (classNode.getParent().isAssign() && classNode.getParent().getFirstChild().isQualifiedName()) { target = classNode.getParent().getFirstChild(); } else if (!classNode.getFirstChild().isEmpty()) { target = classNode.getFirstChild(); } else { // issue error - no name found compiler.report(JSError.make(classNode, PolymerPassErrors.POLYMER_CLASS_UNNAMED)); return null; } JSDocInfo classInfo = NodeUtil.getBestJSDocInfo(classNode); JSDocInfo ctorInfo = null; Node constructor = NodeUtil.getEs6ClassConstructorMemberFunctionDef(classNode); if (constructor != null) { ctorInfo = NodeUtil.getBestJSDocInfo(constructor); } List<MemberDefinition> allProperties = PolymerPassStaticUtils.extractProperties( propertiesDescriptor, DefinitionType.ES6Class, compiler, constructor); List<MemberDefinition> methods = new ArrayList<>(); for (Node keyNode : NodeUtil.getClassMembers(classNode).children()) { if (!keyNode.isMemberFunctionDef()) { continue; } methods.add(new MemberDefinition( NodeUtil.getBestJSDocInfo(keyNode), keyNode, keyNode.getFirstChild())); } return new PolymerClassDefinition( DefinitionType.ES6Class, classNode, target, propertiesDescriptor, classInfo, new MemberDefinition(ctorInfo, null, constructor), null, allProperties, methods, null, null); }
[ "@", "Nullable", "static", "PolymerClassDefinition", "extractFromClassNode", "(", "Node", "classNode", ",", "AbstractCompiler", "compiler", ",", "GlobalNamespace", "globalNames", ")", "{", "checkState", "(", "classNode", "!=", "null", "&&", "classNode", ".", "isClass", "(", ")", ")", ";", "// The supported case is for the config getter to return an object literal descriptor.", "Node", "propertiesDescriptor", "=", "null", ";", "Node", "propertiesGetter", "=", "NodeUtil", ".", "getFirstGetterMatchingKey", "(", "NodeUtil", ".", "getClassMembers", "(", "classNode", ")", ",", "\"properties\"", ")", ";", "if", "(", "propertiesGetter", "!=", "null", ")", "{", "if", "(", "!", "propertiesGetter", ".", "isStaticMember", "(", ")", ")", "{", "// report bad class definition", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "classNode", ",", "PolymerPassErrors", ".", "POLYMER_CLASS_PROPERTIES_NOT_STATIC", ")", ")", ";", "}", "else", "{", "for", "(", "Node", "child", ":", "NodeUtil", ".", "getFunctionBody", "(", "propertiesGetter", ".", "getFirstChild", "(", ")", ")", ".", "children", "(", ")", ")", "{", "if", "(", "child", ".", "isReturn", "(", ")", ")", "{", "if", "(", "child", ".", "hasChildren", "(", ")", "&&", "child", ".", "getFirstChild", "(", ")", ".", "isObjectLit", "(", ")", ")", "{", "propertiesDescriptor", "=", "child", ".", "getFirstChild", "(", ")", ";", "break", ";", "}", "else", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "propertiesGetter", ",", "PolymerPassErrors", ".", "POLYMER_CLASS_PROPERTIES_INVALID", ")", ")", ";", "}", "}", "}", "}", "}", "Node", "target", ";", "if", "(", "NodeUtil", ".", "isNameDeclaration", "(", "classNode", ".", "getGrandparent", "(", ")", ")", ")", "{", "target", "=", "IR", ".", "name", "(", "classNode", ".", "getParent", "(", ")", ".", "getString", "(", ")", ")", ";", "}", "else", "if", "(", "classNode", ".", "getParent", "(", ")", ".", "isAssign", "(", ")", "&&", "classNode", ".", "getParent", "(", ")", ".", "getFirstChild", "(", ")", ".", "isQualifiedName", "(", ")", ")", "{", "target", "=", "classNode", ".", "getParent", "(", ")", ".", "getFirstChild", "(", ")", ";", "}", "else", "if", "(", "!", "classNode", ".", "getFirstChild", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "target", "=", "classNode", ".", "getFirstChild", "(", ")", ";", "}", "else", "{", "// issue error - no name found", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "classNode", ",", "PolymerPassErrors", ".", "POLYMER_CLASS_UNNAMED", ")", ")", ";", "return", "null", ";", "}", "JSDocInfo", "classInfo", "=", "NodeUtil", ".", "getBestJSDocInfo", "(", "classNode", ")", ";", "JSDocInfo", "ctorInfo", "=", "null", ";", "Node", "constructor", "=", "NodeUtil", ".", "getEs6ClassConstructorMemberFunctionDef", "(", "classNode", ")", ";", "if", "(", "constructor", "!=", "null", ")", "{", "ctorInfo", "=", "NodeUtil", ".", "getBestJSDocInfo", "(", "constructor", ")", ";", "}", "List", "<", "MemberDefinition", ">", "allProperties", "=", "PolymerPassStaticUtils", ".", "extractProperties", "(", "propertiesDescriptor", ",", "DefinitionType", ".", "ES6Class", ",", "compiler", ",", "constructor", ")", ";", "List", "<", "MemberDefinition", ">", "methods", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Node", "keyNode", ":", "NodeUtil", ".", "getClassMembers", "(", "classNode", ")", ".", "children", "(", ")", ")", "{", "if", "(", "!", "keyNode", ".", "isMemberFunctionDef", "(", ")", ")", "{", "continue", ";", "}", "methods", ".", "add", "(", "new", "MemberDefinition", "(", "NodeUtil", ".", "getBestJSDocInfo", "(", "keyNode", ")", ",", "keyNode", ",", "keyNode", ".", "getFirstChild", "(", ")", ")", ")", ";", "}", "return", "new", "PolymerClassDefinition", "(", "DefinitionType", ".", "ES6Class", ",", "classNode", ",", "target", ",", "propertiesDescriptor", ",", "classInfo", ",", "new", "MemberDefinition", "(", "ctorInfo", ",", "null", ",", "constructor", ")", ",", "null", ",", "allProperties", ",", "methods", ",", "null", ",", "null", ")", ";", "}" ]
Validates the class definition and if valid, extracts the class definition from the AST. As opposed to the Polymer 1 extraction, this operation is non-destructive.
[ "Validates", "the", "class", "definition", "and", "if", "valid", "extracts", "the", "class", "definition", "from", "the", "AST", ".", "As", "opposed", "to", "the", "Polymer", "1", "extraction", "this", "operation", "is", "non", "-", "destructive", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassDefinition.java#L208-L285
24,749
google/closure-compiler
src/com/google/javascript/jscomp/PolymerClassDefinition.java
PolymerClassDefinition.overwriteMembersIfPresent
private static void overwriteMembersIfPresent( List<MemberDefinition> list, List<MemberDefinition> newMembers) { for (MemberDefinition newMember : newMembers) { for (MemberDefinition member : list) { if (member.name.getString().equals(newMember.name.getString())) { list.remove(member); break; } } list.add(newMember); } }
java
private static void overwriteMembersIfPresent( List<MemberDefinition> list, List<MemberDefinition> newMembers) { for (MemberDefinition newMember : newMembers) { for (MemberDefinition member : list) { if (member.name.getString().equals(newMember.name.getString())) { list.remove(member); break; } } list.add(newMember); } }
[ "private", "static", "void", "overwriteMembersIfPresent", "(", "List", "<", "MemberDefinition", ">", "list", ",", "List", "<", "MemberDefinition", ">", "newMembers", ")", "{", "for", "(", "MemberDefinition", "newMember", ":", "newMembers", ")", "{", "for", "(", "MemberDefinition", "member", ":", "list", ")", "{", "if", "(", "member", ".", "name", ".", "getString", "(", ")", ".", "equals", "(", "newMember", ".", "name", ".", "getString", "(", ")", ")", ")", "{", "list", ".", "remove", "(", "member", ")", ";", "break", ";", "}", "}", "list", ".", "add", "(", "newMember", ")", ";", "}", "}" ]
Appends a list of new MemberDefinitions to the end of a list and removes any previous MemberDefinition in the list which has the same name as the new member.
[ "Appends", "a", "list", "of", "new", "MemberDefinitions", "to", "the", "end", "of", "a", "list", "and", "removes", "any", "previous", "MemberDefinition", "in", "the", "list", "which", "has", "the", "same", "name", "as", "the", "new", "member", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassDefinition.java#L291-L302
24,750
google/closure-compiler
src/com/google/javascript/jscomp/StaticSuperPropReplacer.java
StaticSuperPropReplacer.tryReplaceSuper
private void tryReplaceSuper(Node superNode) { checkState(!superclasses.isEmpty(), "`super` cannot appear outside a function"); Optional<Node> currentSuperclass = superclasses.peek(); if (!currentSuperclass.isPresent() || !currentSuperclass.get().isQualifiedName()) { // either if a) we're in a static class fn without an 'extends' clause or b) we're not in // a static class function return; } Node fullyQualifiedSuperRef = currentSuperclass.get().cloneTree(); superNode.replaceWith(fullyQualifiedSuperRef); compiler.reportChangeToEnclosingScope(fullyQualifiedSuperRef); }
java
private void tryReplaceSuper(Node superNode) { checkState(!superclasses.isEmpty(), "`super` cannot appear outside a function"); Optional<Node> currentSuperclass = superclasses.peek(); if (!currentSuperclass.isPresent() || !currentSuperclass.get().isQualifiedName()) { // either if a) we're in a static class fn without an 'extends' clause or b) we're not in // a static class function return; } Node fullyQualifiedSuperRef = currentSuperclass.get().cloneTree(); superNode.replaceWith(fullyQualifiedSuperRef); compiler.reportChangeToEnclosingScope(fullyQualifiedSuperRef); }
[ "private", "void", "tryReplaceSuper", "(", "Node", "superNode", ")", "{", "checkState", "(", "!", "superclasses", ".", "isEmpty", "(", ")", ",", "\"`super` cannot appear outside a function\"", ")", ";", "Optional", "<", "Node", ">", "currentSuperclass", "=", "superclasses", ".", "peek", "(", ")", ";", "if", "(", "!", "currentSuperclass", ".", "isPresent", "(", ")", "||", "!", "currentSuperclass", ".", "get", "(", ")", ".", "isQualifiedName", "(", ")", ")", "{", "// either if a) we're in a static class fn without an 'extends' clause or b) we're not in", "// a static class function", "return", ";", "}", "Node", "fullyQualifiedSuperRef", "=", "currentSuperclass", ".", "get", "(", ")", ".", "cloneTree", "(", ")", ";", "superNode", ".", "replaceWith", "(", "fullyQualifiedSuperRef", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "fullyQualifiedSuperRef", ")", ";", "}" ]
Replaces `super` with `Super.Class` if in a static class method with a qname superclass
[ "Replaces", "super", "with", "Super", ".", "Class", "if", "in", "a", "static", "class", "method", "with", "a", "qname", "superclass" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/StaticSuperPropReplacer.java#L98-L110
24,751
google/closure-compiler
src/com/google/javascript/jscomp/ConstParamCheck.java
ConstParamCheck.isSafeValue
private boolean isSafeValue(Scope scope, Node argument) { if (NodeUtil.isSomeCompileTimeConstStringValue(argument)) { return true; } else if (argument.isAdd()) { Node left = argument.getFirstChild(); Node right = argument.getLastChild(); return isSafeValue(scope, left) && isSafeValue(scope, right); } else if (argument.isName()) { String name = argument.getString(); Var var = scope.getVar(name); if (var == null || !var.isInferredConst()) { return false; } Node initialValue = var.getInitialValue(); if (initialValue == null) { return false; } return isSafeValue(var.getScope(), initialValue); } return false; }
java
private boolean isSafeValue(Scope scope, Node argument) { if (NodeUtil.isSomeCompileTimeConstStringValue(argument)) { return true; } else if (argument.isAdd()) { Node left = argument.getFirstChild(); Node right = argument.getLastChild(); return isSafeValue(scope, left) && isSafeValue(scope, right); } else if (argument.isName()) { String name = argument.getString(); Var var = scope.getVar(name); if (var == null || !var.isInferredConst()) { return false; } Node initialValue = var.getInitialValue(); if (initialValue == null) { return false; } return isSafeValue(var.getScope(), initialValue); } return false; }
[ "private", "boolean", "isSafeValue", "(", "Scope", "scope", ",", "Node", "argument", ")", "{", "if", "(", "NodeUtil", ".", "isSomeCompileTimeConstStringValue", "(", "argument", ")", ")", "{", "return", "true", ";", "}", "else", "if", "(", "argument", ".", "isAdd", "(", ")", ")", "{", "Node", "left", "=", "argument", ".", "getFirstChild", "(", ")", ";", "Node", "right", "=", "argument", ".", "getLastChild", "(", ")", ";", "return", "isSafeValue", "(", "scope", ",", "left", ")", "&&", "isSafeValue", "(", "scope", ",", "right", ")", ";", "}", "else", "if", "(", "argument", ".", "isName", "(", ")", ")", "{", "String", "name", "=", "argument", ".", "getString", "(", ")", ";", "Var", "var", "=", "scope", ".", "getVar", "(", "name", ")", ";", "if", "(", "var", "==", "null", "||", "!", "var", ".", "isInferredConst", "(", ")", ")", "{", "return", "false", ";", "}", "Node", "initialValue", "=", "var", ".", "getInitialValue", "(", ")", ";", "if", "(", "initialValue", "==", "null", ")", "{", "return", "false", ";", "}", "return", "isSafeValue", "(", "var", ".", "getScope", "(", ")", ",", "initialValue", ")", ";", "}", "return", "false", ";", "}" ]
Checks if the method call argument is made of constant string literals. <p>This function argument checker will return true if: <ol> <li>The argument is a constant variable assigned from a string literal, or <li>The argument is an expression that is a string literal, or <li>The argument is a ternary expression choosing between string literals, or <li>The argument is a concatenation of the above. </ol> @param scope The scope chain to use in name lookups. @param argument The node of function argument to check.
[ "Checks", "if", "the", "method", "call", "argument", "is", "made", "of", "constant", "string", "literals", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ConstParamCheck.java#L118-L138
24,752
google/closure-compiler
src/com/google/javascript/jscomp/ijs/PotentialDeclaration.java
PotentialDeclaration.remove
final void remove(AbstractCompiler compiler) { if (isDetached()) { return; } Node statement = getRemovableNode(); NodeUtil.deleteNode(statement, compiler); statement.removeChildren(); }
java
final void remove(AbstractCompiler compiler) { if (isDetached()) { return; } Node statement = getRemovableNode(); NodeUtil.deleteNode(statement, compiler); statement.removeChildren(); }
[ "final", "void", "remove", "(", "AbstractCompiler", "compiler", ")", "{", "if", "(", "isDetached", "(", ")", ")", "{", "return", ";", "}", "Node", "statement", "=", "getRemovableNode", "(", ")", ";", "NodeUtil", ".", "deleteNode", "(", "statement", ",", "compiler", ")", ";", "statement", ".", "removeChildren", "(", ")", ";", "}" ]
Remove this "potential declaration" completely. Usually, this is because the same symbol has already been declared in this file.
[ "Remove", "this", "potential", "declaration", "completely", ".", "Usually", "this", "is", "because", "the", "same", "symbol", "has", "already", "been", "declared", "in", "this", "file", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ijs/PotentialDeclaration.java#L123-L130
24,753
google/closure-compiler
src/com/google/javascript/jscomp/ijs/PotentialDeclaration.java
PotentialDeclaration.simplifyEnumValues
private void simplifyEnumValues(AbstractCompiler compiler) { if (getRhs().isObjectLit() && getRhs().hasChildren()) { for (Node key : getRhs().children()) { removeStringKeyValue(key); } compiler.reportChangeToEnclosingScope(getRhs()); } }
java
private void simplifyEnumValues(AbstractCompiler compiler) { if (getRhs().isObjectLit() && getRhs().hasChildren()) { for (Node key : getRhs().children()) { removeStringKeyValue(key); } compiler.reportChangeToEnclosingScope(getRhs()); } }
[ "private", "void", "simplifyEnumValues", "(", "AbstractCompiler", "compiler", ")", "{", "if", "(", "getRhs", "(", ")", ".", "isObjectLit", "(", ")", "&&", "getRhs", "(", ")", ".", "hasChildren", "(", ")", ")", "{", "for", "(", "Node", "key", ":", "getRhs", "(", ")", ".", "children", "(", ")", ")", "{", "removeStringKeyValue", "(", "key", ")", ";", "}", "compiler", ".", "reportChangeToEnclosingScope", "(", "getRhs", "(", ")", ")", ";", "}", "}" ]
Remove values from enums
[ "Remove", "values", "from", "enums" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ijs/PotentialDeclaration.java#L437-L444
24,754
google/closure-compiler
src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java
ProcessClosureProvidesAndRequires.collectProvidedNames
Map<String, ProvidedName> collectProvidedNames(Node externs, Node root) { if (this.providedNames.isEmpty()) { // goog is special-cased because it is provided in Closure's base library. providedNames.put(GOOG, new ProvidedName(GOOG, null, null, false /* implicit */, false)); NodeTraversal.traverseRoots(compiler, new CollectDefinitions(), externs, root); } return this.providedNames; }
java
Map<String, ProvidedName> collectProvidedNames(Node externs, Node root) { if (this.providedNames.isEmpty()) { // goog is special-cased because it is provided in Closure's base library. providedNames.put(GOOG, new ProvidedName(GOOG, null, null, false /* implicit */, false)); NodeTraversal.traverseRoots(compiler, new CollectDefinitions(), externs, root); } return this.providedNames; }
[ "Map", "<", "String", ",", "ProvidedName", ">", "collectProvidedNames", "(", "Node", "externs", ",", "Node", "root", ")", "{", "if", "(", "this", ".", "providedNames", ".", "isEmpty", "(", ")", ")", "{", "// goog is special-cased because it is provided in Closure's base library.", "providedNames", ".", "put", "(", "GOOG", ",", "new", "ProvidedName", "(", "GOOG", ",", "null", ",", "null", ",", "false", "/* implicit */", ",", "false", ")", ")", ";", "NodeTraversal", ".", "traverseRoots", "(", "compiler", ",", "new", "CollectDefinitions", "(", ")", ",", "externs", ",", "root", ")", ";", "}", "return", "this", ".", "providedNames", ";", "}" ]
Collects all goog.provides in the given namespace and warns on invalid code
[ "Collects", "all", "goog", ".", "provides", "in", "the", "given", "namespace", "and", "warns", "on", "invalid", "code" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java#L97-L104
24,755
google/closure-compiler
src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java
ProcessClosureProvidesAndRequires.rewriteProvidesAndRequires
void rewriteProvidesAndRequires(Node externs, Node root) { checkState(!hasRewritingOccurred, "Cannot call rewriteProvidesAndRequires twice per instance"); hasRewritingOccurred = true; collectProvidedNames(externs, root); for (ProvidedName pn : providedNames.values()) { pn.replace(); } deleteNamespaceInitializationsFromPreviousProvides(); if (requiresLevel.isOn()) { for (UnrecognizedRequire r : unrecognizedRequires) { checkForLateOrMissingProvide(r); } } for (Node closureRequire : requiresToBeRemoved) { compiler.reportChangeToEnclosingScope(closureRequire); closureRequire.detach(); } for (Node forwardDeclare : forwardDeclaresToRemove) { NodeUtil.deleteNode(forwardDeclare, compiler); } }
java
void rewriteProvidesAndRequires(Node externs, Node root) { checkState(!hasRewritingOccurred, "Cannot call rewriteProvidesAndRequires twice per instance"); hasRewritingOccurred = true; collectProvidedNames(externs, root); for (ProvidedName pn : providedNames.values()) { pn.replace(); } deleteNamespaceInitializationsFromPreviousProvides(); if (requiresLevel.isOn()) { for (UnrecognizedRequire r : unrecognizedRequires) { checkForLateOrMissingProvide(r); } } for (Node closureRequire : requiresToBeRemoved) { compiler.reportChangeToEnclosingScope(closureRequire); closureRequire.detach(); } for (Node forwardDeclare : forwardDeclaresToRemove) { NodeUtil.deleteNode(forwardDeclare, compiler); } }
[ "void", "rewriteProvidesAndRequires", "(", "Node", "externs", ",", "Node", "root", ")", "{", "checkState", "(", "!", "hasRewritingOccurred", ",", "\"Cannot call rewriteProvidesAndRequires twice per instance\"", ")", ";", "hasRewritingOccurred", "=", "true", ";", "collectProvidedNames", "(", "externs", ",", "root", ")", ";", "for", "(", "ProvidedName", "pn", ":", "providedNames", ".", "values", "(", ")", ")", "{", "pn", ".", "replace", "(", ")", ";", "}", "deleteNamespaceInitializationsFromPreviousProvides", "(", ")", ";", "if", "(", "requiresLevel", ".", "isOn", "(", ")", ")", "{", "for", "(", "UnrecognizedRequire", "r", ":", "unrecognizedRequires", ")", "{", "checkForLateOrMissingProvide", "(", "r", ")", ";", "}", "}", "for", "(", "Node", "closureRequire", ":", "requiresToBeRemoved", ")", "{", "compiler", ".", "reportChangeToEnclosingScope", "(", "closureRequire", ")", ";", "closureRequire", ".", "detach", "(", ")", ";", "}", "for", "(", "Node", "forwardDeclare", ":", "forwardDeclaresToRemove", ")", "{", "NodeUtil", ".", "deleteNode", "(", "forwardDeclare", ",", "compiler", ")", ";", "}", "}" ]
Rewrites all provides and requires in the given namespace. <p>Call this instead of {@link #collectProvidedNames(Node, Node)} if you want rewriting.
[ "Rewrites", "all", "provides", "and", "requires", "in", "the", "given", "namespace", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java#L111-L135
24,756
google/closure-compiler
src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java
ProcessClosureProvidesAndRequires.processRequireCall
private void processRequireCall(NodeTraversal t, Node n, Node parent) { Node left = n.getFirstChild(); Node arg = left.getNext(); String method = left.getFirstChild().getNext().getString(); if (verifyLastArgumentIsString(left, arg)) { String ns = arg.getString(); ProvidedName provided = providedNames.get(ns); if (provided == null || !provided.isExplicitlyProvided()) { unrecognizedRequires.add(new UnrecognizedRequire(n, ns, method.equals("requireType"))); } else { JSModule providedModule = provided.explicitModule; if (!provided.isFromExterns()) { checkNotNull(providedModule, n); JSModule module = t.getModule(); // A cross-chunk goog.require must match a goog.provide in an earlier chunk. However, a // cross-chunk goog.requireType is allowed to match a goog.provide in a later chunk. if (module != providedModule && !moduleGraph.dependsOn(module, providedModule) && !method.equals("requireType")) { compiler.report( JSError.make( n, ProcessClosurePrimitives.XMODULE_REQUIRE_ERROR, ns, providedModule.getName(), module.getName())); } } } maybeAddNameToSymbolTable(left); maybeAddStringToSymbolTable(arg); // Requires should be removed before further processing. // Some clients run closure pass multiple times, first with // the checks for broken requires turned off. In these cases, we // allow broken requires to be preserved by the first run to // let them be caught in the subsequent run. if (!preserveGoogProvidesAndRequires && (provided != null || requiresLevel.isOn())) { requiresToBeRemoved.add(parent); } } }
java
private void processRequireCall(NodeTraversal t, Node n, Node parent) { Node left = n.getFirstChild(); Node arg = left.getNext(); String method = left.getFirstChild().getNext().getString(); if (verifyLastArgumentIsString(left, arg)) { String ns = arg.getString(); ProvidedName provided = providedNames.get(ns); if (provided == null || !provided.isExplicitlyProvided()) { unrecognizedRequires.add(new UnrecognizedRequire(n, ns, method.equals("requireType"))); } else { JSModule providedModule = provided.explicitModule; if (!provided.isFromExterns()) { checkNotNull(providedModule, n); JSModule module = t.getModule(); // A cross-chunk goog.require must match a goog.provide in an earlier chunk. However, a // cross-chunk goog.requireType is allowed to match a goog.provide in a later chunk. if (module != providedModule && !moduleGraph.dependsOn(module, providedModule) && !method.equals("requireType")) { compiler.report( JSError.make( n, ProcessClosurePrimitives.XMODULE_REQUIRE_ERROR, ns, providedModule.getName(), module.getName())); } } } maybeAddNameToSymbolTable(left); maybeAddStringToSymbolTable(arg); // Requires should be removed before further processing. // Some clients run closure pass multiple times, first with // the checks for broken requires turned off. In these cases, we // allow broken requires to be preserved by the first run to // let them be caught in the subsequent run. if (!preserveGoogProvidesAndRequires && (provided != null || requiresLevel.isOn())) { requiresToBeRemoved.add(parent); } } }
[ "private", "void", "processRequireCall", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "parent", ")", "{", "Node", "left", "=", "n", ".", "getFirstChild", "(", ")", ";", "Node", "arg", "=", "left", ".", "getNext", "(", ")", ";", "String", "method", "=", "left", ".", "getFirstChild", "(", ")", ".", "getNext", "(", ")", ".", "getString", "(", ")", ";", "if", "(", "verifyLastArgumentIsString", "(", "left", ",", "arg", ")", ")", "{", "String", "ns", "=", "arg", ".", "getString", "(", ")", ";", "ProvidedName", "provided", "=", "providedNames", ".", "get", "(", "ns", ")", ";", "if", "(", "provided", "==", "null", "||", "!", "provided", ".", "isExplicitlyProvided", "(", ")", ")", "{", "unrecognizedRequires", ".", "add", "(", "new", "UnrecognizedRequire", "(", "n", ",", "ns", ",", "method", ".", "equals", "(", "\"requireType\"", ")", ")", ")", ";", "}", "else", "{", "JSModule", "providedModule", "=", "provided", ".", "explicitModule", ";", "if", "(", "!", "provided", ".", "isFromExterns", "(", ")", ")", "{", "checkNotNull", "(", "providedModule", ",", "n", ")", ";", "JSModule", "module", "=", "t", ".", "getModule", "(", ")", ";", "// A cross-chunk goog.require must match a goog.provide in an earlier chunk. However, a", "// cross-chunk goog.requireType is allowed to match a goog.provide in a later chunk.", "if", "(", "module", "!=", "providedModule", "&&", "!", "moduleGraph", ".", "dependsOn", "(", "module", ",", "providedModule", ")", "&&", "!", "method", ".", "equals", "(", "\"requireType\"", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "n", ",", "ProcessClosurePrimitives", ".", "XMODULE_REQUIRE_ERROR", ",", "ns", ",", "providedModule", ".", "getName", "(", ")", ",", "module", ".", "getName", "(", ")", ")", ")", ";", "}", "}", "}", "maybeAddNameToSymbolTable", "(", "left", ")", ";", "maybeAddStringToSymbolTable", "(", "arg", ")", ";", "// Requires should be removed before further processing.", "// Some clients run closure pass multiple times, first with", "// the checks for broken requires turned off. In these cases, we", "// allow broken requires to be preserved by the first run to", "// let them be caught in the subsequent run.", "if", "(", "!", "preserveGoogProvidesAndRequires", "&&", "(", "provided", "!=", "null", "||", "requiresLevel", ".", "isOn", "(", ")", ")", ")", "{", "requiresToBeRemoved", ".", "add", "(", "parent", ")", ";", "}", "}", "}" ]
Handles a goog.require or goog.requireType call.
[ "Handles", "a", "goog", ".", "require", "or", "goog", ".", "requireType", "call", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java#L296-L340
24,757
google/closure-compiler
src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java
ProcessClosureProvidesAndRequires.processLegacyModuleCall
private void processLegacyModuleCall(String namespace, Node googModuleCall, JSModule module) { registerAnyProvidedPrefixes(namespace, googModuleCall, module); providedNames.put( namespace, new ProvidedName( namespace, googModuleCall, module, /* explicit= */ true, /* fromPreviousProvide= */ false)); }
java
private void processLegacyModuleCall(String namespace, Node googModuleCall, JSModule module) { registerAnyProvidedPrefixes(namespace, googModuleCall, module); providedNames.put( namespace, new ProvidedName( namespace, googModuleCall, module, /* explicit= */ true, /* fromPreviousProvide= */ false)); }
[ "private", "void", "processLegacyModuleCall", "(", "String", "namespace", ",", "Node", "googModuleCall", ",", "JSModule", "module", ")", "{", "registerAnyProvidedPrefixes", "(", "namespace", ",", "googModuleCall", ",", "module", ")", ";", "providedNames", ".", "put", "(", "namespace", ",", "new", "ProvidedName", "(", "namespace", ",", "googModuleCall", ",", "module", ",", "/* explicit= */", "true", ",", "/* fromPreviousProvide= */", "false", ")", ")", ";", "}" ]
Handles a goog.module that is a legacy namespace.
[ "Handles", "a", "goog", ".", "module", "that", "is", "a", "legacy", "namespace", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java#L343-L353
24,758
google/closure-compiler
src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java
ProcessClosureProvidesAndRequires.processProvideCall
private void processProvideCall(NodeTraversal t, Node n, Node parent) { checkState(n.isCall()); Node left = n.getFirstChild(); Node arg = left.getNext(); if (verifyProvide(left, arg)) { String ns = arg.getString(); maybeAddNameToSymbolTable(left); maybeAddStringToSymbolTable(arg); if (providedNames.containsKey(ns)) { ProvidedName previouslyProvided = providedNames.get(ns); if (!previouslyProvided.isExplicitlyProvided() || previouslyProvided.isPreviouslyProvided) { previouslyProvided.addProvide(parent, t.getModule(), true); } else { String explicitSourceName = previouslyProvided.explicitNode.getSourceFileName(); compiler.report( JSError.make( n, ProcessClosurePrimitives.DUPLICATE_NAMESPACE_ERROR, ns, explicitSourceName)); } } else { registerAnyProvidedPrefixes(ns, parent, t.getModule()); providedNames.put( ns, new ProvidedName( ns, parent, t.getModule(), /* explicit= */ true, /* fromPreviousProvide= */ false)); } } }
java
private void processProvideCall(NodeTraversal t, Node n, Node parent) { checkState(n.isCall()); Node left = n.getFirstChild(); Node arg = left.getNext(); if (verifyProvide(left, arg)) { String ns = arg.getString(); maybeAddNameToSymbolTable(left); maybeAddStringToSymbolTable(arg); if (providedNames.containsKey(ns)) { ProvidedName previouslyProvided = providedNames.get(ns); if (!previouslyProvided.isExplicitlyProvided() || previouslyProvided.isPreviouslyProvided) { previouslyProvided.addProvide(parent, t.getModule(), true); } else { String explicitSourceName = previouslyProvided.explicitNode.getSourceFileName(); compiler.report( JSError.make( n, ProcessClosurePrimitives.DUPLICATE_NAMESPACE_ERROR, ns, explicitSourceName)); } } else { registerAnyProvidedPrefixes(ns, parent, t.getModule()); providedNames.put( ns, new ProvidedName( ns, parent, t.getModule(), /* explicit= */ true, /* fromPreviousProvide= */ false)); } } }
[ "private", "void", "processProvideCall", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "parent", ")", "{", "checkState", "(", "n", ".", "isCall", "(", ")", ")", ";", "Node", "left", "=", "n", ".", "getFirstChild", "(", ")", ";", "Node", "arg", "=", "left", ".", "getNext", "(", ")", ";", "if", "(", "verifyProvide", "(", "left", ",", "arg", ")", ")", "{", "String", "ns", "=", "arg", ".", "getString", "(", ")", ";", "maybeAddNameToSymbolTable", "(", "left", ")", ";", "maybeAddStringToSymbolTable", "(", "arg", ")", ";", "if", "(", "providedNames", ".", "containsKey", "(", "ns", ")", ")", "{", "ProvidedName", "previouslyProvided", "=", "providedNames", ".", "get", "(", "ns", ")", ";", "if", "(", "!", "previouslyProvided", ".", "isExplicitlyProvided", "(", ")", "||", "previouslyProvided", ".", "isPreviouslyProvided", ")", "{", "previouslyProvided", ".", "addProvide", "(", "parent", ",", "t", ".", "getModule", "(", ")", ",", "true", ")", ";", "}", "else", "{", "String", "explicitSourceName", "=", "previouslyProvided", ".", "explicitNode", ".", "getSourceFileName", "(", ")", ";", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "n", ",", "ProcessClosurePrimitives", ".", "DUPLICATE_NAMESPACE_ERROR", ",", "ns", ",", "explicitSourceName", ")", ")", ";", "}", "}", "else", "{", "registerAnyProvidedPrefixes", "(", "ns", ",", "parent", ",", "t", ".", "getModule", "(", ")", ")", ";", "providedNames", ".", "put", "(", "ns", ",", "new", "ProvidedName", "(", "ns", ",", "parent", ",", "t", ".", "getModule", "(", ")", ",", "/* explicit= */", "true", ",", "/* fromPreviousProvide= */", "false", ")", ")", ";", "}", "}", "}" ]
Handles a goog.provide call.
[ "Handles", "a", "goog", ".", "provide", "call", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java#L356-L384
24,759
google/closure-compiler
src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java
ProcessClosureProvidesAndRequires.handleCandidateProvideDefinition
private void handleCandidateProvideDefinition(NodeTraversal t, Node n, Node parent) { if (t.inGlobalHoistScope()) { String name = null; if (n.isName() && NodeUtil.isNameDeclaration(parent)) { name = n.getString(); } else if (n.isAssign() && parent.isExprResult()) { name = n.getFirstChild().getQualifiedName(); } if (name != null) { if (parent.getBooleanProp(Node.IS_NAMESPACE)) { // TODO(b/128361464): stop including goog.module exports in this case. processProvideFromPreviousPass(t, name, parent); } else { ProvidedName pn = providedNames.get(name); if (pn != null) { pn.addDefinition(parent, t.getModule()); } } } } }
java
private void handleCandidateProvideDefinition(NodeTraversal t, Node n, Node parent) { if (t.inGlobalHoistScope()) { String name = null; if (n.isName() && NodeUtil.isNameDeclaration(parent)) { name = n.getString(); } else if (n.isAssign() && parent.isExprResult()) { name = n.getFirstChild().getQualifiedName(); } if (name != null) { if (parent.getBooleanProp(Node.IS_NAMESPACE)) { // TODO(b/128361464): stop including goog.module exports in this case. processProvideFromPreviousPass(t, name, parent); } else { ProvidedName pn = providedNames.get(name); if (pn != null) { pn.addDefinition(parent, t.getModule()); } } } } }
[ "private", "void", "handleCandidateProvideDefinition", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "parent", ")", "{", "if", "(", "t", ".", "inGlobalHoistScope", "(", ")", ")", "{", "String", "name", "=", "null", ";", "if", "(", "n", ".", "isName", "(", ")", "&&", "NodeUtil", ".", "isNameDeclaration", "(", "parent", ")", ")", "{", "name", "=", "n", ".", "getString", "(", ")", ";", "}", "else", "if", "(", "n", ".", "isAssign", "(", ")", "&&", "parent", ".", "isExprResult", "(", ")", ")", "{", "name", "=", "n", ".", "getFirstChild", "(", ")", ".", "getQualifiedName", "(", ")", ";", "}", "if", "(", "name", "!=", "null", ")", "{", "if", "(", "parent", ".", "getBooleanProp", "(", "Node", ".", "IS_NAMESPACE", ")", ")", "{", "// TODO(b/128361464): stop including goog.module exports in this case.", "processProvideFromPreviousPass", "(", "t", ",", "name", ",", "parent", ")", ";", "}", "else", "{", "ProvidedName", "pn", "=", "providedNames", ".", "get", "(", "name", ")", ";", "if", "(", "pn", "!=", "null", ")", "{", "pn", ".", "addDefinition", "(", "parent", ",", "t", ".", "getModule", "(", ")", ")", ";", "}", "}", "}", "}", "}" ]
Handles a candidate definition for a goog.provided name.
[ "Handles", "a", "candidate", "definition", "for", "a", "goog", ".", "provided", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java#L417-L438
24,760
google/closure-compiler
src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java
ProcessClosureProvidesAndRequires.processProvideFromPreviousPass
private void processProvideFromPreviousPass(NodeTraversal t, String name, Node parent) { JSModule module = t.getModule(); if (providedNames.containsKey(name)) { ProvidedName provided = providedNames.get(name); provided.addDefinition(parent, module); if (isNamespacePlaceholder(parent)) { // Remove this later if it is a simple object literal. Replacing the corresponding // ProvidedName will create a new definition. // Don't add this as a 'definition' of the provided name to support pushing provides // into earlier modules. previouslyProvidedDefinitions.add(parent); } } else { // Record this provide created on a previous pass. This can happen if the previous pass had // goog.provide('foo.bar');, but all we have now is the rewritten `foo.bar = {};`. registerAnyProvidedPrefixes(name, parent, module); ProvidedName provided = new ProvidedName(name, parent, module, true, true); providedNames.put(name, provided); provided.addDefinition(parent, module); } }
java
private void processProvideFromPreviousPass(NodeTraversal t, String name, Node parent) { JSModule module = t.getModule(); if (providedNames.containsKey(name)) { ProvidedName provided = providedNames.get(name); provided.addDefinition(parent, module); if (isNamespacePlaceholder(parent)) { // Remove this later if it is a simple object literal. Replacing the corresponding // ProvidedName will create a new definition. // Don't add this as a 'definition' of the provided name to support pushing provides // into earlier modules. previouslyProvidedDefinitions.add(parent); } } else { // Record this provide created on a previous pass. This can happen if the previous pass had // goog.provide('foo.bar');, but all we have now is the rewritten `foo.bar = {};`. registerAnyProvidedPrefixes(name, parent, module); ProvidedName provided = new ProvidedName(name, parent, module, true, true); providedNames.put(name, provided); provided.addDefinition(parent, module); } }
[ "private", "void", "processProvideFromPreviousPass", "(", "NodeTraversal", "t", ",", "String", "name", ",", "Node", "parent", ")", "{", "JSModule", "module", "=", "t", ".", "getModule", "(", ")", ";", "if", "(", "providedNames", ".", "containsKey", "(", "name", ")", ")", "{", "ProvidedName", "provided", "=", "providedNames", ".", "get", "(", "name", ")", ";", "provided", ".", "addDefinition", "(", "parent", ",", "module", ")", ";", "if", "(", "isNamespacePlaceholder", "(", "parent", ")", ")", "{", "// Remove this later if it is a simple object literal. Replacing the corresponding", "// ProvidedName will create a new definition.", "// Don't add this as a 'definition' of the provided name to support pushing provides", "// into earlier modules.", "previouslyProvidedDefinitions", ".", "add", "(", "parent", ")", ";", "}", "}", "else", "{", "// Record this provide created on a previous pass. This can happen if the previous pass had", "// goog.provide('foo.bar');, but all we have now is the rewritten `foo.bar = {};`.", "registerAnyProvidedPrefixes", "(", "name", ",", "parent", ",", "module", ")", ";", "ProvidedName", "provided", "=", "new", "ProvidedName", "(", "name", ",", "parent", ",", "module", ",", "true", ",", "true", ")", ";", "providedNames", ".", "put", "(", "name", ",", "provided", ")", ";", "provided", ".", "addDefinition", "(", "parent", ",", "module", ")", ";", "}", "}" ]
Processes the output of processed-provide from a previous pass. This will update our data structures in the same manner as if the provide had been processed in this pass. <p>TODO(b/128120127): delete this method
[ "Processes", "the", "output", "of", "processed", "-", "provide", "from", "a", "previous", "pass", ".", "This", "will", "update", "our", "data", "structures", "in", "the", "same", "manner", "as", "if", "the", "provide", "had", "been", "processed", "in", "this", "pass", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java#L457-L478
24,761
google/closure-compiler
src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java
ProcessClosureProvidesAndRequires.registerAnyProvidedPrefixes
private void registerAnyProvidedPrefixes(String ns, Node node, JSModule module) { int pos = ns.indexOf('.'); while (pos != -1) { String prefixNs = ns.substring(0, pos); pos = ns.indexOf('.', pos + 1); if (providedNames.containsKey(prefixNs)) { providedNames.get(prefixNs).addProvide(node, module, /* explicit= */ false); } else { providedNames.put( prefixNs, new ProvidedName( prefixNs, node, module, /* explicit= */ false, /* fromPreviousProvide= */ false)); } } }
java
private void registerAnyProvidedPrefixes(String ns, Node node, JSModule module) { int pos = ns.indexOf('.'); while (pos != -1) { String prefixNs = ns.substring(0, pos); pos = ns.indexOf('.', pos + 1); if (providedNames.containsKey(prefixNs)) { providedNames.get(prefixNs).addProvide(node, module, /* explicit= */ false); } else { providedNames.put( prefixNs, new ProvidedName( prefixNs, node, module, /* explicit= */ false, /* fromPreviousProvide= */ false)); } } }
[ "private", "void", "registerAnyProvidedPrefixes", "(", "String", "ns", ",", "Node", "node", ",", "JSModule", "module", ")", "{", "int", "pos", "=", "ns", ".", "indexOf", "(", "'", "'", ")", ";", "while", "(", "pos", "!=", "-", "1", ")", "{", "String", "prefixNs", "=", "ns", ".", "substring", "(", "0", ",", "pos", ")", ";", "pos", "=", "ns", ".", "indexOf", "(", "'", "'", ",", "pos", "+", "1", ")", ";", "if", "(", "providedNames", ".", "containsKey", "(", "prefixNs", ")", ")", "{", "providedNames", ".", "get", "(", "prefixNs", ")", ".", "addProvide", "(", "node", ",", "module", ",", "/* explicit= */", "false", ")", ";", "}", "else", "{", "providedNames", ".", "put", "(", "prefixNs", ",", "new", "ProvidedName", "(", "prefixNs", ",", "node", ",", "module", ",", "/* explicit= */", "false", ",", "/* fromPreviousProvide= */", "false", ")", ")", ";", "}", "}", "}" ]
Registers ProvidedNames for prefix namespaces if they haven't already been defined. The prefix namespaces must be registered in order from shortest to longest. @param ns The namespace whose prefixes may need to be provided. @param node The EXPR of the provide call. @param module The current module.
[ "Registers", "ProvidedNames", "for", "prefix", "namespaces", "if", "they", "haven", "t", "already", "been", "defined", ".", "The", "prefix", "namespaces", "must", "be", "registered", "in", "order", "from", "shortest", "to", "longest", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java#L587-L601
24,762
google/closure-compiler
src/com/google/javascript/jscomp/AggressiveInlineAliases.java
AggressiveInlineAliases.mayBeGlobalAlias
private boolean mayBeGlobalAlias(Ref alias) { // Note: alias.scope is the closest scope in which the aliasing assignment occurred. // So for "if (true) { var alias = aliasedVar; }", the alias.scope would be the IF block scope. if (alias.scope.isGlobal()) { return true; } // If the scope in which the alias is assigned is not global, look up the LHS of the assignment. Node aliasParent = alias.getNode().getParent(); if (!aliasParent.isAssign() && !aliasParent.isName()) { // Only handle variable assignments and initializing declarations. return true; } Node aliasLhsNode = aliasParent.isName() ? aliasParent : aliasParent.getFirstChild(); if (!aliasLhsNode.isName()) { // Only handle assignments to simple names, not qualified names or GETPROPs. return true; } String aliasVarName = aliasLhsNode.getString(); Var aliasVar = alias.scope.getVar(aliasVarName); if (aliasVar != null) { return aliasVar.isGlobal(); } return true; }
java
private boolean mayBeGlobalAlias(Ref alias) { // Note: alias.scope is the closest scope in which the aliasing assignment occurred. // So for "if (true) { var alias = aliasedVar; }", the alias.scope would be the IF block scope. if (alias.scope.isGlobal()) { return true; } // If the scope in which the alias is assigned is not global, look up the LHS of the assignment. Node aliasParent = alias.getNode().getParent(); if (!aliasParent.isAssign() && !aliasParent.isName()) { // Only handle variable assignments and initializing declarations. return true; } Node aliasLhsNode = aliasParent.isName() ? aliasParent : aliasParent.getFirstChild(); if (!aliasLhsNode.isName()) { // Only handle assignments to simple names, not qualified names or GETPROPs. return true; } String aliasVarName = aliasLhsNode.getString(); Var aliasVar = alias.scope.getVar(aliasVarName); if (aliasVar != null) { return aliasVar.isGlobal(); } return true; }
[ "private", "boolean", "mayBeGlobalAlias", "(", "Ref", "alias", ")", "{", "// Note: alias.scope is the closest scope in which the aliasing assignment occurred.", "// So for \"if (true) { var alias = aliasedVar; }\", the alias.scope would be the IF block scope.", "if", "(", "alias", ".", "scope", ".", "isGlobal", "(", ")", ")", "{", "return", "true", ";", "}", "// If the scope in which the alias is assigned is not global, look up the LHS of the assignment.", "Node", "aliasParent", "=", "alias", ".", "getNode", "(", ")", ".", "getParent", "(", ")", ";", "if", "(", "!", "aliasParent", ".", "isAssign", "(", ")", "&&", "!", "aliasParent", ".", "isName", "(", ")", ")", "{", "// Only handle variable assignments and initializing declarations.", "return", "true", ";", "}", "Node", "aliasLhsNode", "=", "aliasParent", ".", "isName", "(", ")", "?", "aliasParent", ":", "aliasParent", ".", "getFirstChild", "(", ")", ";", "if", "(", "!", "aliasLhsNode", ".", "isName", "(", ")", ")", "{", "// Only handle assignments to simple names, not qualified names or GETPROPs.", "return", "true", ";", "}", "String", "aliasVarName", "=", "aliasLhsNode", ".", "getString", "(", ")", ";", "Var", "aliasVar", "=", "alias", ".", "scope", ".", "getVar", "(", "aliasVarName", ")", ";", "if", "(", "aliasVar", "!=", "null", ")", "{", "return", "aliasVar", ".", "isGlobal", "(", ")", ";", "}", "return", "true", ";", "}" ]
Returns true if the alias is possibly defined in the global scope, which we handle with more caution than with locally scoped variables. May return false positives. @param alias An aliasing get. @return If the alias is possibly defined in the global scope.
[ "Returns", "true", "if", "the", "alias", "is", "possibly", "defined", "in", "the", "global", "scope", "which", "we", "handle", "with", "more", "caution", "than", "with", "locally", "scoped", "variables", ".", "May", "return", "false", "positives", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AggressiveInlineAliases.java#L273-L296
24,763
google/closure-compiler
src/com/google/javascript/jscomp/AggressiveInlineAliases.java
AggressiveInlineAliases.inlineAliasIfPossible
private void inlineAliasIfPossible(Name name, Ref alias, GlobalNamespace namespace) { // Ensure that the alias is assigned to a local variable at that // variable's declaration. If the alias's parent is a NAME, // then the NAME must be the child of a VAR, LET, or CONST node, and we must // be in a VAR, LET, or CONST assignment. // Otherwise if the parent is an assign, we are in a "a = alias" case. Node aliasParent = alias.getNode().getParent(); if (aliasParent.isName() || aliasParent.isAssign()) { Node aliasLhsNode = aliasParent.isName() ? aliasParent : aliasParent.getFirstChild(); String aliasVarName = aliasLhsNode.getString(); Var aliasVar = alias.scope.getVar(aliasVarName); checkState(aliasVar != null, "Expected variable to be defined in scope", aliasVarName); ReferenceCollectingCallback collector = new ReferenceCollectingCallback( compiler, ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR, new Es6SyntacticScopeCreator(compiler), Predicates.equalTo(aliasVar)); Scope aliasScope = aliasVar.getScope(); collector.processScope(aliasScope); ReferenceCollection aliasRefs = collector.getReferences(aliasVar); Set<AstChange> newNodes = new LinkedHashSet<>(); if (aliasRefs.isWellDefined() && aliasRefs.isAssignedOnceInLifetime()) { // The alias is well-formed, so do the inlining now. int size = aliasRefs.references.size(); // It's initialized on either the first or second reference. int firstRead = aliasRefs.references.get(0).isInitializingDeclaration() ? 1 : 2; for (int i = firstRead; i < size; i++) { Reference aliasRef = aliasRefs.references.get(i); newNodes.add(replaceAliasReference(alias, aliasRef)); } // just set the original alias to null. tryReplacingAliasingAssignment(alias, aliasLhsNode); // Inlining the variable may have introduced new references // to descendants of {@code name}. So those need to be collected now. namespace.scanNewNodes(newNodes); return; } if (name.isConstructor()) { // TODO(lharker): the main reason this was added is because method decomposition inside // generators introduces some constructor aliases that weren't getting inlined. // If we find another (safer) way to avoid aliasing in method decomposition, consider // removing this. if (!partiallyInlineAlias(alias, namespace, aliasRefs, aliasLhsNode)) { // If we can't inline all alias references, make sure there are no unsafe property // accesses. if (referencesCollapsibleProperty(aliasRefs, name, namespace)) { compiler.report(JSError.make(aliasParent, UNSAFE_CTOR_ALIASING, aliasVarName)); } } } } }
java
private void inlineAliasIfPossible(Name name, Ref alias, GlobalNamespace namespace) { // Ensure that the alias is assigned to a local variable at that // variable's declaration. If the alias's parent is a NAME, // then the NAME must be the child of a VAR, LET, or CONST node, and we must // be in a VAR, LET, or CONST assignment. // Otherwise if the parent is an assign, we are in a "a = alias" case. Node aliasParent = alias.getNode().getParent(); if (aliasParent.isName() || aliasParent.isAssign()) { Node aliasLhsNode = aliasParent.isName() ? aliasParent : aliasParent.getFirstChild(); String aliasVarName = aliasLhsNode.getString(); Var aliasVar = alias.scope.getVar(aliasVarName); checkState(aliasVar != null, "Expected variable to be defined in scope", aliasVarName); ReferenceCollectingCallback collector = new ReferenceCollectingCallback( compiler, ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR, new Es6SyntacticScopeCreator(compiler), Predicates.equalTo(aliasVar)); Scope aliasScope = aliasVar.getScope(); collector.processScope(aliasScope); ReferenceCollection aliasRefs = collector.getReferences(aliasVar); Set<AstChange> newNodes = new LinkedHashSet<>(); if (aliasRefs.isWellDefined() && aliasRefs.isAssignedOnceInLifetime()) { // The alias is well-formed, so do the inlining now. int size = aliasRefs.references.size(); // It's initialized on either the first or second reference. int firstRead = aliasRefs.references.get(0).isInitializingDeclaration() ? 1 : 2; for (int i = firstRead; i < size; i++) { Reference aliasRef = aliasRefs.references.get(i); newNodes.add(replaceAliasReference(alias, aliasRef)); } // just set the original alias to null. tryReplacingAliasingAssignment(alias, aliasLhsNode); // Inlining the variable may have introduced new references // to descendants of {@code name}. So those need to be collected now. namespace.scanNewNodes(newNodes); return; } if (name.isConstructor()) { // TODO(lharker): the main reason this was added is because method decomposition inside // generators introduces some constructor aliases that weren't getting inlined. // If we find another (safer) way to avoid aliasing in method decomposition, consider // removing this. if (!partiallyInlineAlias(alias, namespace, aliasRefs, aliasLhsNode)) { // If we can't inline all alias references, make sure there are no unsafe property // accesses. if (referencesCollapsibleProperty(aliasRefs, name, namespace)) { compiler.report(JSError.make(aliasParent, UNSAFE_CTOR_ALIASING, aliasVarName)); } } } } }
[ "private", "void", "inlineAliasIfPossible", "(", "Name", "name", ",", "Ref", "alias", ",", "GlobalNamespace", "namespace", ")", "{", "// Ensure that the alias is assigned to a local variable at that", "// variable's declaration. If the alias's parent is a NAME,", "// then the NAME must be the child of a VAR, LET, or CONST node, and we must", "// be in a VAR, LET, or CONST assignment.", "// Otherwise if the parent is an assign, we are in a \"a = alias\" case.", "Node", "aliasParent", "=", "alias", ".", "getNode", "(", ")", ".", "getParent", "(", ")", ";", "if", "(", "aliasParent", ".", "isName", "(", ")", "||", "aliasParent", ".", "isAssign", "(", ")", ")", "{", "Node", "aliasLhsNode", "=", "aliasParent", ".", "isName", "(", ")", "?", "aliasParent", ":", "aliasParent", ".", "getFirstChild", "(", ")", ";", "String", "aliasVarName", "=", "aliasLhsNode", ".", "getString", "(", ")", ";", "Var", "aliasVar", "=", "alias", ".", "scope", ".", "getVar", "(", "aliasVarName", ")", ";", "checkState", "(", "aliasVar", "!=", "null", ",", "\"Expected variable to be defined in scope\"", ",", "aliasVarName", ")", ";", "ReferenceCollectingCallback", "collector", "=", "new", "ReferenceCollectingCallback", "(", "compiler", ",", "ReferenceCollectingCallback", ".", "DO_NOTHING_BEHAVIOR", ",", "new", "Es6SyntacticScopeCreator", "(", "compiler", ")", ",", "Predicates", ".", "equalTo", "(", "aliasVar", ")", ")", ";", "Scope", "aliasScope", "=", "aliasVar", ".", "getScope", "(", ")", ";", "collector", ".", "processScope", "(", "aliasScope", ")", ";", "ReferenceCollection", "aliasRefs", "=", "collector", ".", "getReferences", "(", "aliasVar", ")", ";", "Set", "<", "AstChange", ">", "newNodes", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "if", "(", "aliasRefs", ".", "isWellDefined", "(", ")", "&&", "aliasRefs", ".", "isAssignedOnceInLifetime", "(", ")", ")", "{", "// The alias is well-formed, so do the inlining now.", "int", "size", "=", "aliasRefs", ".", "references", ".", "size", "(", ")", ";", "// It's initialized on either the first or second reference.", "int", "firstRead", "=", "aliasRefs", ".", "references", ".", "get", "(", "0", ")", ".", "isInitializingDeclaration", "(", ")", "?", "1", ":", "2", ";", "for", "(", "int", "i", "=", "firstRead", ";", "i", "<", "size", ";", "i", "++", ")", "{", "Reference", "aliasRef", "=", "aliasRefs", ".", "references", ".", "get", "(", "i", ")", ";", "newNodes", ".", "add", "(", "replaceAliasReference", "(", "alias", ",", "aliasRef", ")", ")", ";", "}", "// just set the original alias to null.", "tryReplacingAliasingAssignment", "(", "alias", ",", "aliasLhsNode", ")", ";", "// Inlining the variable may have introduced new references", "// to descendants of {@code name}. So those need to be collected now.", "namespace", ".", "scanNewNodes", "(", "newNodes", ")", ";", "return", ";", "}", "if", "(", "name", ".", "isConstructor", "(", ")", ")", "{", "// TODO(lharker): the main reason this was added is because method decomposition inside", "// generators introduces some constructor aliases that weren't getting inlined.", "// If we find another (safer) way to avoid aliasing in method decomposition, consider", "// removing this.", "if", "(", "!", "partiallyInlineAlias", "(", "alias", ",", "namespace", ",", "aliasRefs", ",", "aliasLhsNode", ")", ")", "{", "// If we can't inline all alias references, make sure there are no unsafe property", "// accesses.", "if", "(", "referencesCollapsibleProperty", "(", "aliasRefs", ",", "name", ",", "namespace", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "aliasParent", ",", "UNSAFE_CTOR_ALIASING", ",", "aliasVarName", ")", ")", ";", "}", "}", "}", "}", "}" ]
Attempts to inline a non-global alias of a global name. <p>It is assumed that the name for which it is an alias meets conditions (a) and (b). <p>The non-global alias is only inlinable if it is well-defined and assigned once, according to the definitions in {@link ReferenceCollection} <p>If the aliasing name is completely removed, also deletes the aliasing Ref. @param name The global name being aliased @param alias The aliasing reference to the name to remove
[ "Attempts", "to", "inline", "a", "non", "-", "global", "alias", "of", "a", "global", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AggressiveInlineAliases.java#L311-L369
24,764
google/closure-compiler
src/com/google/javascript/jscomp/AggressiveInlineAliases.java
AggressiveInlineAliases.partiallyInlineAlias
private boolean partiallyInlineAlias( Ref alias, GlobalNamespace namespace, ReferenceCollection aliasRefs, Node aliasLhsNode) { BasicBlock aliasBlock = null; // This initial iteration through all the alias references does two things: // a) Find the control flow block in which the alias is assigned. // b) See if the alias var is assigned to in multiple places, and return if that's the case. // NOTE: we still may inline if the alias is assigned in a loop or inner function and that // assignment statement is potentially executed multiple times. // This is more aggressive than what "inlineAliasIfPossible" does. for (Reference aliasRef : aliasRefs) { Node aliasRefNode = aliasRef.getNode(); if (aliasRefNode == aliasLhsNode) { aliasBlock = aliasRef.getBasicBlock(); continue; } else if (aliasRef.isLvalue()) { // Don't replace any references if the alias is reassigned return false; } } Set<AstChange> newNodes = new LinkedHashSet<>(); boolean alreadySeenInitialAlias = false; boolean foundNonReplaceableAlias = false; // Do a second iteration through all the alias references, and replace any inlinable references. for (Reference aliasRef : aliasRefs) { Node aliasRefNode = aliasRef.getNode(); if (aliasRefNode == aliasLhsNode) { alreadySeenInitialAlias = true; continue; } else if (aliasRef.isDeclaration()) { // Ignore any alias declarations, e.g. "var alias;", since there's nothing to inline. continue; } BasicBlock refBlock = aliasRef.getBasicBlock(); if ((refBlock != aliasBlock && aliasBlock.provablyExecutesBefore(refBlock)) || (refBlock == aliasBlock && alreadySeenInitialAlias)) { // We replace the alias only if the alias and reference are in the same BasicBlock, // the aliasing assignment takes place before the reference, and the alias is // never reassigned. codeChanged = true; newNodes.add(replaceAliasReference(alias, aliasRef)); } else { foundNonReplaceableAlias = true; } } // We removed all references to the alias, so remove the original aliasing assignment. if (!foundNonReplaceableAlias) { tryReplacingAliasingAssignment(alias, aliasLhsNode); } if (codeChanged) { // Inlining the variable may have introduced new references // to descendants of {@code name}. So those need to be collected now. namespace.scanNewNodes(newNodes); } return !foundNonReplaceableAlias; }
java
private boolean partiallyInlineAlias( Ref alias, GlobalNamespace namespace, ReferenceCollection aliasRefs, Node aliasLhsNode) { BasicBlock aliasBlock = null; // This initial iteration through all the alias references does two things: // a) Find the control flow block in which the alias is assigned. // b) See if the alias var is assigned to in multiple places, and return if that's the case. // NOTE: we still may inline if the alias is assigned in a loop or inner function and that // assignment statement is potentially executed multiple times. // This is more aggressive than what "inlineAliasIfPossible" does. for (Reference aliasRef : aliasRefs) { Node aliasRefNode = aliasRef.getNode(); if (aliasRefNode == aliasLhsNode) { aliasBlock = aliasRef.getBasicBlock(); continue; } else if (aliasRef.isLvalue()) { // Don't replace any references if the alias is reassigned return false; } } Set<AstChange> newNodes = new LinkedHashSet<>(); boolean alreadySeenInitialAlias = false; boolean foundNonReplaceableAlias = false; // Do a second iteration through all the alias references, and replace any inlinable references. for (Reference aliasRef : aliasRefs) { Node aliasRefNode = aliasRef.getNode(); if (aliasRefNode == aliasLhsNode) { alreadySeenInitialAlias = true; continue; } else if (aliasRef.isDeclaration()) { // Ignore any alias declarations, e.g. "var alias;", since there's nothing to inline. continue; } BasicBlock refBlock = aliasRef.getBasicBlock(); if ((refBlock != aliasBlock && aliasBlock.provablyExecutesBefore(refBlock)) || (refBlock == aliasBlock && alreadySeenInitialAlias)) { // We replace the alias only if the alias and reference are in the same BasicBlock, // the aliasing assignment takes place before the reference, and the alias is // never reassigned. codeChanged = true; newNodes.add(replaceAliasReference(alias, aliasRef)); } else { foundNonReplaceableAlias = true; } } // We removed all references to the alias, so remove the original aliasing assignment. if (!foundNonReplaceableAlias) { tryReplacingAliasingAssignment(alias, aliasLhsNode); } if (codeChanged) { // Inlining the variable may have introduced new references // to descendants of {@code name}. So those need to be collected now. namespace.scanNewNodes(newNodes); } return !foundNonReplaceableAlias; }
[ "private", "boolean", "partiallyInlineAlias", "(", "Ref", "alias", ",", "GlobalNamespace", "namespace", ",", "ReferenceCollection", "aliasRefs", ",", "Node", "aliasLhsNode", ")", "{", "BasicBlock", "aliasBlock", "=", "null", ";", "// This initial iteration through all the alias references does two things:", "// a) Find the control flow block in which the alias is assigned.", "// b) See if the alias var is assigned to in multiple places, and return if that's the case.", "// NOTE: we still may inline if the alias is assigned in a loop or inner function and that", "// assignment statement is potentially executed multiple times.", "// This is more aggressive than what \"inlineAliasIfPossible\" does.", "for", "(", "Reference", "aliasRef", ":", "aliasRefs", ")", "{", "Node", "aliasRefNode", "=", "aliasRef", ".", "getNode", "(", ")", ";", "if", "(", "aliasRefNode", "==", "aliasLhsNode", ")", "{", "aliasBlock", "=", "aliasRef", ".", "getBasicBlock", "(", ")", ";", "continue", ";", "}", "else", "if", "(", "aliasRef", ".", "isLvalue", "(", ")", ")", "{", "// Don't replace any references if the alias is reassigned", "return", "false", ";", "}", "}", "Set", "<", "AstChange", ">", "newNodes", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "boolean", "alreadySeenInitialAlias", "=", "false", ";", "boolean", "foundNonReplaceableAlias", "=", "false", ";", "// Do a second iteration through all the alias references, and replace any inlinable references.", "for", "(", "Reference", "aliasRef", ":", "aliasRefs", ")", "{", "Node", "aliasRefNode", "=", "aliasRef", ".", "getNode", "(", ")", ";", "if", "(", "aliasRefNode", "==", "aliasLhsNode", ")", "{", "alreadySeenInitialAlias", "=", "true", ";", "continue", ";", "}", "else", "if", "(", "aliasRef", ".", "isDeclaration", "(", ")", ")", "{", "// Ignore any alias declarations, e.g. \"var alias;\", since there's nothing to inline.", "continue", ";", "}", "BasicBlock", "refBlock", "=", "aliasRef", ".", "getBasicBlock", "(", ")", ";", "if", "(", "(", "refBlock", "!=", "aliasBlock", "&&", "aliasBlock", ".", "provablyExecutesBefore", "(", "refBlock", ")", ")", "||", "(", "refBlock", "==", "aliasBlock", "&&", "alreadySeenInitialAlias", ")", ")", "{", "// We replace the alias only if the alias and reference are in the same BasicBlock,", "// the aliasing assignment takes place before the reference, and the alias is", "// never reassigned.", "codeChanged", "=", "true", ";", "newNodes", ".", "add", "(", "replaceAliasReference", "(", "alias", ",", "aliasRef", ")", ")", ";", "}", "else", "{", "foundNonReplaceableAlias", "=", "true", ";", "}", "}", "// We removed all references to the alias, so remove the original aliasing assignment.", "if", "(", "!", "foundNonReplaceableAlias", ")", "{", "tryReplacingAliasingAssignment", "(", "alias", ",", "aliasLhsNode", ")", ";", "}", "if", "(", "codeChanged", ")", "{", "// Inlining the variable may have introduced new references", "// to descendants of {@code name}. So those need to be collected now.", "namespace", ".", "scanNewNodes", "(", "newNodes", ")", ";", "}", "return", "!", "foundNonReplaceableAlias", ";", "}" ]
Inlines some references to an alias with its value. This handles cases where the alias is not declared at initialization. It does nothing if the alias is reassigned after being initialized, unless the reassignment occurs because of an enclosing function or a loop. @param alias An alias of some variable, which may not be well-defined. @param namespace The GlobalNamespace, which will be updated with all new nodes created. @param aliasRefs All references to the alias in its scope. @param aliasLhsNode The lhs name of the alias when it is first initialized. @return Whether all references to the alias were inlined
[ "Inlines", "some", "references", "to", "an", "alias", "with", "its", "value", ".", "This", "handles", "cases", "where", "the", "alias", "is", "not", "declared", "at", "initialization", ".", "It", "does", "nothing", "if", "the", "alias", "is", "reassigned", "after", "being", "initialized", "unless", "the", "reassignment", "occurs", "because", "of", "an", "enclosing", "function", "or", "a", "loop", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AggressiveInlineAliases.java#L382-L440
24,765
google/closure-compiler
src/com/google/javascript/jscomp/AggressiveInlineAliases.java
AggressiveInlineAliases.tryReplacingAliasingAssignment
private boolean tryReplacingAliasingAssignment(Ref alias, Node aliasLhsNode) { // either VAR/CONST/LET or ASSIGN. Node assignment = aliasLhsNode.getParent(); if (!NodeUtil.isNameDeclaration(assignment) && NodeUtil.isExpressionResultUsed(assignment)) { // e.g. don't change "if (alias = someVariable)" to "if (alias = null)" // TODO(lharker): instead replace the entire assignment with the RHS - "alias = x" becomes "x" return false; } Node aliasParent = alias.getNode().getParent(); aliasParent.replaceChild(alias.getNode(), IR.nullNode()); alias.name.removeRef(alias); codeChanged = true; compiler.reportChangeToEnclosingScope(aliasParent); return true; }
java
private boolean tryReplacingAliasingAssignment(Ref alias, Node aliasLhsNode) { // either VAR/CONST/LET or ASSIGN. Node assignment = aliasLhsNode.getParent(); if (!NodeUtil.isNameDeclaration(assignment) && NodeUtil.isExpressionResultUsed(assignment)) { // e.g. don't change "if (alias = someVariable)" to "if (alias = null)" // TODO(lharker): instead replace the entire assignment with the RHS - "alias = x" becomes "x" return false; } Node aliasParent = alias.getNode().getParent(); aliasParent.replaceChild(alias.getNode(), IR.nullNode()); alias.name.removeRef(alias); codeChanged = true; compiler.reportChangeToEnclosingScope(aliasParent); return true; }
[ "private", "boolean", "tryReplacingAliasingAssignment", "(", "Ref", "alias", ",", "Node", "aliasLhsNode", ")", "{", "// either VAR/CONST/LET or ASSIGN.", "Node", "assignment", "=", "aliasLhsNode", ".", "getParent", "(", ")", ";", "if", "(", "!", "NodeUtil", ".", "isNameDeclaration", "(", "assignment", ")", "&&", "NodeUtil", ".", "isExpressionResultUsed", "(", "assignment", ")", ")", "{", "// e.g. don't change \"if (alias = someVariable)\" to \"if (alias = null)\"", "// TODO(lharker): instead replace the entire assignment with the RHS - \"alias = x\" becomes \"x\"", "return", "false", ";", "}", "Node", "aliasParent", "=", "alias", ".", "getNode", "(", ")", ".", "getParent", "(", ")", ";", "aliasParent", ".", "replaceChild", "(", "alias", ".", "getNode", "(", ")", ",", "IR", ".", "nullNode", "(", ")", ")", ";", "alias", ".", "name", ".", "removeRef", "(", "alias", ")", ";", "codeChanged", "=", "true", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "aliasParent", ")", ";", "return", "true", ";", "}" ]
Replaces the rhs of an aliasing assignment with null, unless the assignment result is used in a complex expression.
[ "Replaces", "the", "rhs", "of", "an", "aliasing", "assignment", "with", "null", "unless", "the", "assignment", "result", "is", "used", "in", "a", "complex", "expression", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AggressiveInlineAliases.java#L446-L460
24,766
google/closure-compiler
src/com/google/javascript/jscomp/AggressiveInlineAliases.java
AggressiveInlineAliases.referencesCollapsibleProperty
private boolean referencesCollapsibleProperty( ReferenceCollection aliasRefs, Name aliasedName, GlobalNamespace namespace) { for (Reference ref : aliasRefs.references) { if (ref.getParent() == null) { continue; } if (ref.getParent().isGetProp()) { Node propertyNode = ref.getNode().getNext(); // e.g. if the reference is "alias.b.someProp", this will be "b". String propertyName = propertyNode.getString(); // e.g. if the aliased name is "originalName", this will be "originalName.b". String originalPropertyName = aliasedName.getName() + "." + propertyName; Name originalProperty = namespace.getOwnSlot(originalPropertyName); // If the original property isn't in the namespace or can't be collapsed, keep going. if (originalProperty == null || !originalProperty.canCollapse()) { continue; } return true; } } return false; }
java
private boolean referencesCollapsibleProperty( ReferenceCollection aliasRefs, Name aliasedName, GlobalNamespace namespace) { for (Reference ref : aliasRefs.references) { if (ref.getParent() == null) { continue; } if (ref.getParent().isGetProp()) { Node propertyNode = ref.getNode().getNext(); // e.g. if the reference is "alias.b.someProp", this will be "b". String propertyName = propertyNode.getString(); // e.g. if the aliased name is "originalName", this will be "originalName.b". String originalPropertyName = aliasedName.getName() + "." + propertyName; Name originalProperty = namespace.getOwnSlot(originalPropertyName); // If the original property isn't in the namespace or can't be collapsed, keep going. if (originalProperty == null || !originalProperty.canCollapse()) { continue; } return true; } } return false; }
[ "private", "boolean", "referencesCollapsibleProperty", "(", "ReferenceCollection", "aliasRefs", ",", "Name", "aliasedName", ",", "GlobalNamespace", "namespace", ")", "{", "for", "(", "Reference", "ref", ":", "aliasRefs", ".", "references", ")", "{", "if", "(", "ref", ".", "getParent", "(", ")", "==", "null", ")", "{", "continue", ";", "}", "if", "(", "ref", ".", "getParent", "(", ")", ".", "isGetProp", "(", ")", ")", "{", "Node", "propertyNode", "=", "ref", ".", "getNode", "(", ")", ".", "getNext", "(", ")", ";", "// e.g. if the reference is \"alias.b.someProp\", this will be \"b\".", "String", "propertyName", "=", "propertyNode", ".", "getString", "(", ")", ";", "// e.g. if the aliased name is \"originalName\", this will be \"originalName.b\".", "String", "originalPropertyName", "=", "aliasedName", ".", "getName", "(", ")", "+", "\".\"", "+", "propertyName", ";", "Name", "originalProperty", "=", "namespace", ".", "getOwnSlot", "(", "originalPropertyName", ")", ";", "// If the original property isn't in the namespace or can't be collapsed, keep going.", "if", "(", "originalProperty", "==", "null", "||", "!", "originalProperty", ".", "canCollapse", "(", ")", ")", "{", "continue", ";", "}", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns whether a ReferenceCollection for some aliasing variable references a property on the original aliased variable that may be collapsed in CollapseProperties. <p>See {@link GlobalNamespace.Name#canCollapse} for what can/cannot be collapsed.
[ "Returns", "whether", "a", "ReferenceCollection", "for", "some", "aliasing", "variable", "references", "a", "property", "on", "the", "original", "aliased", "variable", "that", "may", "be", "collapsed", "in", "CollapseProperties", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AggressiveInlineAliases.java#L468-L489
24,767
google/closure-compiler
src/com/google/javascript/jscomp/AggressiveInlineAliases.java
AggressiveInlineAliases.rewriteAliasReferences
private void rewriteAliasReferences(Name aliasingName, Ref aliasingRef, Set<AstChange> newNodes) { List<Ref> refs = new ArrayList<>(aliasingName.getRefs()); for (Ref ref : refs) { switch (ref.type) { case SET_FROM_GLOBAL: continue; case DIRECT_GET: case ALIASING_GET: case PROTOTYPE_GET: case CALL_GET: case SUBCLASSING_GET: if (ref.getTwin() != null) { // The reference is the left-hand side of a nested assignment. This means we store two // separate 'twin' Refs with the same node of types ALIASING_GET and SET_FROM_GLOBAL. // For example, the read of `c.d` has a twin reference in // a.b = c.d = e.f; // We handle this case later. checkState(ref.type == Type.ALIASING_GET, ref); break; } if (ref.getNode().isStringKey()) { // e.g. `y` in `const {y} = x;` DestructuringGlobalNameExtractor.reassignDestructringLvalue( ref.getNode(), aliasingRef.getNode().cloneTree(), newNodes, ref, compiler); } else { // e.g. `x.y` checkState(ref.getNode().isGetProp() || ref.getNode().isName()); Node newNode = aliasingRef.getNode().cloneTree(); Node node = ref.getNode(); node.replaceWith(newNode); compiler.reportChangeToEnclosingScope(newNode); newNodes.add(new AstChange(ref.module, ref.scope, newNode)); } aliasingName.removeRef(ref); break; default: throw new IllegalStateException(); } } }
java
private void rewriteAliasReferences(Name aliasingName, Ref aliasingRef, Set<AstChange> newNodes) { List<Ref> refs = new ArrayList<>(aliasingName.getRefs()); for (Ref ref : refs) { switch (ref.type) { case SET_FROM_GLOBAL: continue; case DIRECT_GET: case ALIASING_GET: case PROTOTYPE_GET: case CALL_GET: case SUBCLASSING_GET: if (ref.getTwin() != null) { // The reference is the left-hand side of a nested assignment. This means we store two // separate 'twin' Refs with the same node of types ALIASING_GET and SET_FROM_GLOBAL. // For example, the read of `c.d` has a twin reference in // a.b = c.d = e.f; // We handle this case later. checkState(ref.type == Type.ALIASING_GET, ref); break; } if (ref.getNode().isStringKey()) { // e.g. `y` in `const {y} = x;` DestructuringGlobalNameExtractor.reassignDestructringLvalue( ref.getNode(), aliasingRef.getNode().cloneTree(), newNodes, ref, compiler); } else { // e.g. `x.y` checkState(ref.getNode().isGetProp() || ref.getNode().isName()); Node newNode = aliasingRef.getNode().cloneTree(); Node node = ref.getNode(); node.replaceWith(newNode); compiler.reportChangeToEnclosingScope(newNode); newNodes.add(new AstChange(ref.module, ref.scope, newNode)); } aliasingName.removeRef(ref); break; default: throw new IllegalStateException(); } } }
[ "private", "void", "rewriteAliasReferences", "(", "Name", "aliasingName", ",", "Ref", "aliasingRef", ",", "Set", "<", "AstChange", ">", "newNodes", ")", "{", "List", "<", "Ref", ">", "refs", "=", "new", "ArrayList", "<>", "(", "aliasingName", ".", "getRefs", "(", ")", ")", ";", "for", "(", "Ref", "ref", ":", "refs", ")", "{", "switch", "(", "ref", ".", "type", ")", "{", "case", "SET_FROM_GLOBAL", ":", "continue", ";", "case", "DIRECT_GET", ":", "case", "ALIASING_GET", ":", "case", "PROTOTYPE_GET", ":", "case", "CALL_GET", ":", "case", "SUBCLASSING_GET", ":", "if", "(", "ref", ".", "getTwin", "(", ")", "!=", "null", ")", "{", "// The reference is the left-hand side of a nested assignment. This means we store two", "// separate 'twin' Refs with the same node of types ALIASING_GET and SET_FROM_GLOBAL.", "// For example, the read of `c.d` has a twin reference in", "// a.b = c.d = e.f;", "// We handle this case later.", "checkState", "(", "ref", ".", "type", "==", "Type", ".", "ALIASING_GET", ",", "ref", ")", ";", "break", ";", "}", "if", "(", "ref", ".", "getNode", "(", ")", ".", "isStringKey", "(", ")", ")", "{", "// e.g. `y` in `const {y} = x;`", "DestructuringGlobalNameExtractor", ".", "reassignDestructringLvalue", "(", "ref", ".", "getNode", "(", ")", ",", "aliasingRef", ".", "getNode", "(", ")", ".", "cloneTree", "(", ")", ",", "newNodes", ",", "ref", ",", "compiler", ")", ";", "}", "else", "{", "// e.g. `x.y`", "checkState", "(", "ref", ".", "getNode", "(", ")", ".", "isGetProp", "(", ")", "||", "ref", ".", "getNode", "(", ")", ".", "isName", "(", ")", ")", ";", "Node", "newNode", "=", "aliasingRef", ".", "getNode", "(", ")", ".", "cloneTree", "(", ")", ";", "Node", "node", "=", "ref", ".", "getNode", "(", ")", ";", "node", ".", "replaceWith", "(", "newNode", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "newNode", ")", ";", "newNodes", ".", "add", "(", "new", "AstChange", "(", "ref", ".", "module", ",", "ref", ".", "scope", ",", "newNode", ")", ")", ";", "}", "aliasingName", ".", "removeRef", "(", "ref", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", ")", ";", "}", "}", "}" ]
Replaces all reads of a name with the name it aliases
[ "Replaces", "all", "reads", "of", "a", "name", "with", "the", "name", "it", "aliases" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AggressiveInlineAliases.java#L589-L628
24,768
google/closure-compiler
src/com/google/javascript/jscomp/AggressiveInlineAliases.java
AggressiveInlineAliases.rewriteNestedAliasReference
private void rewriteNestedAliasReference( Node value, int depth, Set<AstChange> newNodes, Name prop) { rewriteAliasProps(prop, value, depth + 1, newNodes); List<Ref> refs = new ArrayList<>(prop.getRefs()); for (Ref ref : refs) { Node target = ref.getNode(); if (target.isStringKey() && target.getParent().isDestructuringPattern()) { // Do nothing for alias properties accessed through object destructuring. This would be // redundant. This method is intended for names nested inside getprop chains, because // GlobalNamespace only creates a single Ref for the outermost getprop. However, for // destructuring property accesses, GlobalNamespace creates multiple Refs, one for the // destructured object, and one for each string key in the pattern. // // For example, consider: // const originalObj = {key: 0}; // const rhs = originalObj; // const {key: lhs} = rhs; // const otherLhs = rhs.key; // AggressiveInlineAliases is inlining rhs -> originalObj. // // GlobalNamespace creates two Refs for the name 'rhs': one for its declaration, // and one for 'const {key: lhs} = rhs;'. There is no Ref pointing directly to the 'rhs' // in 'const otherLhs = rhs.key', though. // There are also two Refs to the name 'rhs.key': one for the destructuring access and one // for the getprop access. This loop will visit both Refs. // This method is responsible for inlining "const otherLhs = originalObj.key" but not // "const {key: lhs} = originalObj;". We bail out at the Ref in the latter case. checkState( target.getGrandparent().isAssign() || target.getGrandparent().isDestructuringLhs(), // Currently GlobalNamespace doesn't create Refs for 'b' in const {a: {b}} = obj; // If it does start creating those Refs, we may have to update this method to handle // them explicitly. "Did not expect GlobalNamespace to create Ref for key in nested object pattern %s", target); continue; } for (int i = 0; i <= depth; i++) { if (target.isGetProp()) { target = target.getFirstChild(); } else if (NodeUtil.isObjectLitKey(target)) { // Object literal key definitions are a little trickier, as we // need to find the assignment target Node gparent = target.getGrandparent(); if (gparent.isAssign()) { target = gparent.getFirstChild(); } else { checkState(NodeUtil.isObjectLitKey(gparent)); target = gparent; } } else { throw new IllegalStateException("unexpected node: " + target); } } checkState(target.isGetProp() || target.isName()); Node newValue = value.cloneTree(); target.replaceWith(newValue); compiler.reportChangeToEnclosingScope(newValue); prop.removeRef(ref); // Rescan the expression root. newNodes.add(new AstChange(ref.module, ref.scope, ref.getNode())); codeChanged = true; } }
java
private void rewriteNestedAliasReference( Node value, int depth, Set<AstChange> newNodes, Name prop) { rewriteAliasProps(prop, value, depth + 1, newNodes); List<Ref> refs = new ArrayList<>(prop.getRefs()); for (Ref ref : refs) { Node target = ref.getNode(); if (target.isStringKey() && target.getParent().isDestructuringPattern()) { // Do nothing for alias properties accessed through object destructuring. This would be // redundant. This method is intended for names nested inside getprop chains, because // GlobalNamespace only creates a single Ref for the outermost getprop. However, for // destructuring property accesses, GlobalNamespace creates multiple Refs, one for the // destructured object, and one for each string key in the pattern. // // For example, consider: // const originalObj = {key: 0}; // const rhs = originalObj; // const {key: lhs} = rhs; // const otherLhs = rhs.key; // AggressiveInlineAliases is inlining rhs -> originalObj. // // GlobalNamespace creates two Refs for the name 'rhs': one for its declaration, // and one for 'const {key: lhs} = rhs;'. There is no Ref pointing directly to the 'rhs' // in 'const otherLhs = rhs.key', though. // There are also two Refs to the name 'rhs.key': one for the destructuring access and one // for the getprop access. This loop will visit both Refs. // This method is responsible for inlining "const otherLhs = originalObj.key" but not // "const {key: lhs} = originalObj;". We bail out at the Ref in the latter case. checkState( target.getGrandparent().isAssign() || target.getGrandparent().isDestructuringLhs(), // Currently GlobalNamespace doesn't create Refs for 'b' in const {a: {b}} = obj; // If it does start creating those Refs, we may have to update this method to handle // them explicitly. "Did not expect GlobalNamespace to create Ref for key in nested object pattern %s", target); continue; } for (int i = 0; i <= depth; i++) { if (target.isGetProp()) { target = target.getFirstChild(); } else if (NodeUtil.isObjectLitKey(target)) { // Object literal key definitions are a little trickier, as we // need to find the assignment target Node gparent = target.getGrandparent(); if (gparent.isAssign()) { target = gparent.getFirstChild(); } else { checkState(NodeUtil.isObjectLitKey(gparent)); target = gparent; } } else { throw new IllegalStateException("unexpected node: " + target); } } checkState(target.isGetProp() || target.isName()); Node newValue = value.cloneTree(); target.replaceWith(newValue); compiler.reportChangeToEnclosingScope(newValue); prop.removeRef(ref); // Rescan the expression root. newNodes.add(new AstChange(ref.module, ref.scope, ref.getNode())); codeChanged = true; } }
[ "private", "void", "rewriteNestedAliasReference", "(", "Node", "value", ",", "int", "depth", ",", "Set", "<", "AstChange", ">", "newNodes", ",", "Name", "prop", ")", "{", "rewriteAliasProps", "(", "prop", ",", "value", ",", "depth", "+", "1", ",", "newNodes", ")", ";", "List", "<", "Ref", ">", "refs", "=", "new", "ArrayList", "<>", "(", "prop", ".", "getRefs", "(", ")", ")", ";", "for", "(", "Ref", "ref", ":", "refs", ")", "{", "Node", "target", "=", "ref", ".", "getNode", "(", ")", ";", "if", "(", "target", ".", "isStringKey", "(", ")", "&&", "target", ".", "getParent", "(", ")", ".", "isDestructuringPattern", "(", ")", ")", "{", "// Do nothing for alias properties accessed through object destructuring. This would be", "// redundant. This method is intended for names nested inside getprop chains, because", "// GlobalNamespace only creates a single Ref for the outermost getprop. However, for", "// destructuring property accesses, GlobalNamespace creates multiple Refs, one for the", "// destructured object, and one for each string key in the pattern.", "//", "// For example, consider:", "// const originalObj = {key: 0};", "// const rhs = originalObj;", "// const {key: lhs} = rhs;", "// const otherLhs = rhs.key;", "// AggressiveInlineAliases is inlining rhs -> originalObj.", "//", "// GlobalNamespace creates two Refs for the name 'rhs': one for its declaration,", "// and one for 'const {key: lhs} = rhs;'. There is no Ref pointing directly to the 'rhs'", "// in 'const otherLhs = rhs.key', though.", "// There are also two Refs to the name 'rhs.key': one for the destructuring access and one", "// for the getprop access. This loop will visit both Refs.", "// This method is responsible for inlining \"const otherLhs = originalObj.key\" but not", "// \"const {key: lhs} = originalObj;\". We bail out at the Ref in the latter case.", "checkState", "(", "target", ".", "getGrandparent", "(", ")", ".", "isAssign", "(", ")", "||", "target", ".", "getGrandparent", "(", ")", ".", "isDestructuringLhs", "(", ")", ",", "// Currently GlobalNamespace doesn't create Refs for 'b' in const {a: {b}} = obj;", "// If it does start creating those Refs, we may have to update this method to handle", "// them explicitly.", "\"Did not expect GlobalNamespace to create Ref for key in nested object pattern %s\"", ",", "target", ")", ";", "continue", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "depth", ";", "i", "++", ")", "{", "if", "(", "target", ".", "isGetProp", "(", ")", ")", "{", "target", "=", "target", ".", "getFirstChild", "(", ")", ";", "}", "else", "if", "(", "NodeUtil", ".", "isObjectLitKey", "(", "target", ")", ")", "{", "// Object literal key definitions are a little trickier, as we", "// need to find the assignment target", "Node", "gparent", "=", "target", ".", "getGrandparent", "(", ")", ";", "if", "(", "gparent", ".", "isAssign", "(", ")", ")", "{", "target", "=", "gparent", ".", "getFirstChild", "(", ")", ";", "}", "else", "{", "checkState", "(", "NodeUtil", ".", "isObjectLitKey", "(", "gparent", ")", ")", ";", "target", "=", "gparent", ";", "}", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"unexpected node: \"", "+", "target", ")", ";", "}", "}", "checkState", "(", "target", ".", "isGetProp", "(", ")", "||", "target", ".", "isName", "(", ")", ")", ";", "Node", "newValue", "=", "value", ".", "cloneTree", "(", ")", ";", "target", ".", "replaceWith", "(", "newValue", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "newValue", ")", ";", "prop", ".", "removeRef", "(", "ref", ")", ";", "// Rescan the expression root.", "newNodes", ".", "add", "(", "new", "AstChange", "(", "ref", ".", "module", ",", "ref", ".", "scope", ",", "ref", ".", "getNode", "(", ")", ")", ")", ";", "codeChanged", "=", "true", ";", "}", "}" ]
Replaces references to an alias that are nested inside a longer getprop chain or an object literal <p>For example: if we have an inlined alias 'const A = B;', and reference a property 'A.x', then this method is responsible for replacing 'A.x' with 'B.x'. <p>This is necessary because in the above example, given 'A.x', there is only one {@link Ref} that points to the whole name 'A.x', not a direct {@link Ref} to 'A'. So the only way to replace 'A.x' with 'B.x' is by looking at the property 'x' reference. @param value The value to use when rewriting. @param depth The property chain depth. @param newNodes Expression nodes that have been updated. @param prop The property to rewrite with value.
[ "Replaces", "references", "to", "an", "alias", "that", "are", "nested", "inside", "a", "longer", "getprop", "chain", "or", "an", "object", "literal" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AggressiveInlineAliases.java#L685-L748
24,769
google/closure-compiler
src/com/google/javascript/jscomp/AggressiveInlineAliases.java
AggressiveInlineAliases.getSubclassForEs6Superclass
@Nullable private static Node getSubclassForEs6Superclass(Node superclass) { Node classNode = superclass.getParent(); checkArgument(classNode.isClass(), classNode); if (NodeUtil.isNameDeclaration(classNode.getGrandparent())) { // const Clazz = class extends Super { return classNode.getParent(); } else if (superclass.getGrandparent().isAssign()) { // ns.foo.Clazz = class extends Super { return classNode.getPrevious(); } else if (NodeUtil.isClassDeclaration(classNode)) { // class Clazz extends Super { return classNode.getFirstChild(); } return null; }
java
@Nullable private static Node getSubclassForEs6Superclass(Node superclass) { Node classNode = superclass.getParent(); checkArgument(classNode.isClass(), classNode); if (NodeUtil.isNameDeclaration(classNode.getGrandparent())) { // const Clazz = class extends Super { return classNode.getParent(); } else if (superclass.getGrandparent().isAssign()) { // ns.foo.Clazz = class extends Super { return classNode.getPrevious(); } else if (NodeUtil.isClassDeclaration(classNode)) { // class Clazz extends Super { return classNode.getFirstChild(); } return null; }
[ "@", "Nullable", "private", "static", "Node", "getSubclassForEs6Superclass", "(", "Node", "superclass", ")", "{", "Node", "classNode", "=", "superclass", ".", "getParent", "(", ")", ";", "checkArgument", "(", "classNode", ".", "isClass", "(", ")", ",", "classNode", ")", ";", "if", "(", "NodeUtil", ".", "isNameDeclaration", "(", "classNode", ".", "getGrandparent", "(", ")", ")", ")", "{", "// const Clazz = class extends Super {", "return", "classNode", ".", "getParent", "(", ")", ";", "}", "else", "if", "(", "superclass", ".", "getGrandparent", "(", ")", ".", "isAssign", "(", ")", ")", "{", "// ns.foo.Clazz = class extends Super {", "return", "classNode", ".", "getPrevious", "(", ")", ";", "}", "else", "if", "(", "NodeUtil", ".", "isClassDeclaration", "(", "classNode", ")", ")", "{", "// class Clazz extends Super {", "return", "classNode", ".", "getFirstChild", "(", ")", ";", "}", "return", "null", ";", "}" ]
Tries to find an lvalue for the subclass given the superclass node in an `class ... extends ` clause <p>Only handles cases where we have either a class declaration or a class expression in an assignment or name declaration. Otherwise returns null.
[ "Tries", "to", "find", "an", "lvalue", "for", "the", "subclass", "given", "the", "superclass", "node", "in", "an", "class", "...", "extends", "clause" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AggressiveInlineAliases.java#L757-L772
24,770
google/closure-compiler
src/com/google/javascript/jscomp/ImplicitNullabilityCheck.java
ImplicitNullabilityCheck.visit
@Override public void visit(final NodeTraversal t, final Node n, final Node p) { final JSDocInfo info = n.getJSDocInfo(); if (info == null) { return; } final JSTypeRegistry registry = compiler.getTypeRegistry(); final List<Node> thrownTypes = transform( info.getThrownTypes(), new Function<JSTypeExpression, Node>() { @Override public Node apply(JSTypeExpression expr) { return expr.getRoot(); } }); final Scope scope = t.getScope(); for (Node typeRoot : info.getTypeNodes()) { NodeUtil.visitPreOrder( typeRoot, new NodeUtil.Visitor() { @Override public void visit(Node node) { if (!node.isString()) { return; } if (thrownTypes.contains(node)) { return; } Node parent = node.getParent(); if (parent != null) { switch (parent.getToken()) { case BANG: case QMARK: case THIS: // The names inside function(this:Foo) and case NEW: // function(new:Bar) are already non-null. case TYPEOF: // Names after 'typeof' don't have nullability. return; case PIPE: { // Inside a union Node gp = parent.getParent(); if (gp != null && gp.getToken() == Token.QMARK) { return; // Inside an explicitly nullable union } for (Node child : parent.children()) { if ((child.isString() && child.getString().equals("null")) || child.getToken() == Token.QMARK) { return; // Inside a union that contains null or nullable type } } break; } default: break; } } String typeName = node.getString(); if (typeName.equals("null") || registry.getType(scope, typeName) == null) { return; } JSType type = registry.createTypeFromCommentNode(node); if (type.isNullable()) { compiler.report(JSError.make(node, IMPLICITLY_NULLABLE_JSDOC, typeName)); } } }, Predicates.alwaysTrue()); } }
java
@Override public void visit(final NodeTraversal t, final Node n, final Node p) { final JSDocInfo info = n.getJSDocInfo(); if (info == null) { return; } final JSTypeRegistry registry = compiler.getTypeRegistry(); final List<Node> thrownTypes = transform( info.getThrownTypes(), new Function<JSTypeExpression, Node>() { @Override public Node apply(JSTypeExpression expr) { return expr.getRoot(); } }); final Scope scope = t.getScope(); for (Node typeRoot : info.getTypeNodes()) { NodeUtil.visitPreOrder( typeRoot, new NodeUtil.Visitor() { @Override public void visit(Node node) { if (!node.isString()) { return; } if (thrownTypes.contains(node)) { return; } Node parent = node.getParent(); if (parent != null) { switch (parent.getToken()) { case BANG: case QMARK: case THIS: // The names inside function(this:Foo) and case NEW: // function(new:Bar) are already non-null. case TYPEOF: // Names after 'typeof' don't have nullability. return; case PIPE: { // Inside a union Node gp = parent.getParent(); if (gp != null && gp.getToken() == Token.QMARK) { return; // Inside an explicitly nullable union } for (Node child : parent.children()) { if ((child.isString() && child.getString().equals("null")) || child.getToken() == Token.QMARK) { return; // Inside a union that contains null or nullable type } } break; } default: break; } } String typeName = node.getString(); if (typeName.equals("null") || registry.getType(scope, typeName) == null) { return; } JSType type = registry.createTypeFromCommentNode(node); if (type.isNullable()) { compiler.report(JSError.make(node, IMPLICITLY_NULLABLE_JSDOC, typeName)); } } }, Predicates.alwaysTrue()); } }
[ "@", "Override", "public", "void", "visit", "(", "final", "NodeTraversal", "t", ",", "final", "Node", "n", ",", "final", "Node", "p", ")", "{", "final", "JSDocInfo", "info", "=", "n", ".", "getJSDocInfo", "(", ")", ";", "if", "(", "info", "==", "null", ")", "{", "return", ";", "}", "final", "JSTypeRegistry", "registry", "=", "compiler", ".", "getTypeRegistry", "(", ")", ";", "final", "List", "<", "Node", ">", "thrownTypes", "=", "transform", "(", "info", ".", "getThrownTypes", "(", ")", ",", "new", "Function", "<", "JSTypeExpression", ",", "Node", ">", "(", ")", "{", "@", "Override", "public", "Node", "apply", "(", "JSTypeExpression", "expr", ")", "{", "return", "expr", ".", "getRoot", "(", ")", ";", "}", "}", ")", ";", "final", "Scope", "scope", "=", "t", ".", "getScope", "(", ")", ";", "for", "(", "Node", "typeRoot", ":", "info", ".", "getTypeNodes", "(", ")", ")", "{", "NodeUtil", ".", "visitPreOrder", "(", "typeRoot", ",", "new", "NodeUtil", ".", "Visitor", "(", ")", "{", "@", "Override", "public", "void", "visit", "(", "Node", "node", ")", "{", "if", "(", "!", "node", ".", "isString", "(", ")", ")", "{", "return", ";", "}", "if", "(", "thrownTypes", ".", "contains", "(", "node", ")", ")", "{", "return", ";", "}", "Node", "parent", "=", "node", ".", "getParent", "(", ")", ";", "if", "(", "parent", "!=", "null", ")", "{", "switch", "(", "parent", ".", "getToken", "(", ")", ")", "{", "case", "BANG", ":", "case", "QMARK", ":", "case", "THIS", ":", "// The names inside function(this:Foo) and", "case", "NEW", ":", "// function(new:Bar) are already non-null.", "case", "TYPEOF", ":", "// Names after 'typeof' don't have nullability.", "return", ";", "case", "PIPE", ":", "{", "// Inside a union", "Node", "gp", "=", "parent", ".", "getParent", "(", ")", ";", "if", "(", "gp", "!=", "null", "&&", "gp", ".", "getToken", "(", ")", "==", "Token", ".", "QMARK", ")", "{", "return", ";", "// Inside an explicitly nullable union", "}", "for", "(", "Node", "child", ":", "parent", ".", "children", "(", ")", ")", "{", "if", "(", "(", "child", ".", "isString", "(", ")", "&&", "child", ".", "getString", "(", ")", ".", "equals", "(", "\"null\"", ")", ")", "||", "child", ".", "getToken", "(", ")", "==", "Token", ".", "QMARK", ")", "{", "return", ";", "// Inside a union that contains null or nullable type", "}", "}", "break", ";", "}", "default", ":", "break", ";", "}", "}", "String", "typeName", "=", "node", ".", "getString", "(", ")", ";", "if", "(", "typeName", ".", "equals", "(", "\"null\"", ")", "||", "registry", ".", "getType", "(", "scope", ",", "typeName", ")", "==", "null", ")", "{", "return", ";", "}", "JSType", "type", "=", "registry", ".", "createTypeFromCommentNode", "(", "node", ")", ";", "if", "(", "type", ".", "isNullable", "(", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "node", ",", "IMPLICITLY_NULLABLE_JSDOC", ",", "typeName", ")", ")", ";", "}", "}", "}", ",", "Predicates", ".", "alwaysTrue", "(", ")", ")", ";", "}", "}" ]
Crawls the JSDoc of the given node to find any names in JSDoc that are implicitly null.
[ "Crawls", "the", "JSDoc", "of", "the", "given", "node", "to", "find", "any", "names", "in", "JSDoc", "that", "are", "implicitly", "null", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ImplicitNullabilityCheck.java#L60-L130
24,771
google/closure-compiler
src/com/google/javascript/jscomp/lint/CheckRequiresSorted.java
CheckRequiresSorted.canonicalizeImports
private static List<ImportStatement> canonicalizeImports( Multimap<String, ImportStatement> importsByNamespace) { List<ImportStatement> canonicalImports = new ArrayList<>(); for (String namespace : importsByNamespace.keySet()) { Collection<ImportStatement> allImports = importsByNamespace.get(namespace); // Find the strongest primitive across all existing imports. Every emitted import for this // namespace will use this primitive. This makes the logic simpler and cannot change runtime // behavior, but may produce spurious changes when multiple aliasing imports of differing // strength exist (which are already in violation of the style guide). ImportPrimitive strongestPrimitive = allImports.stream() .map(ImportStatement::primitive) .reduce(ImportPrimitive.WEAKEST, ImportPrimitive::stronger); // Emit each aliasing import separately, as deduplicating them would require code references // to be rewritten. boolean hasAliasing = false; for (ImportStatement stmt : Iterables.filter(allImports, ImportStatement::isAliasing)) { canonicalImports.add(stmt.upgrade(strongestPrimitive)); hasAliasing = true; } // Emit a single destructuring import with a non-empty pattern, merged from the existing // destructuring imports. boolean hasDestructuring = false; ImmutableList<Node> destructuringNodes = allImports.stream() .filter(ImportStatement::isDestructuring) .flatMap(i -> i.nodes().stream()) .collect(toImmutableList()); ImmutableList<DestructuringBinding> destructures = allImports.stream() .filter(ImportStatement::isDestructuring) .flatMap(i -> i.destructures().stream()) .distinct() .sorted() .collect(toImmutableList()); if (!destructures.isEmpty()) { canonicalImports.add( ImportStatement.of( destructuringNodes, strongestPrimitive, namespace, /* alias= */ null, destructures)); hasDestructuring = true; } // Emit a standalone import unless an aliasing or destructuring one already exists. if (!hasAliasing && !hasDestructuring) { ImmutableList<Node> standaloneNodes = allImports.stream() .filter(ImportStatement::isStandalone) .flatMap(i -> i.nodes().stream()) .collect(toImmutableList()); canonicalImports.add( ImportStatement.of( standaloneNodes, strongestPrimitive, namespace, /* alias= */ null, /* destructures= */ null)); } } // Sorting by natural order yields the correct result due to the implementation of // ImportStatement#compareTo. Collections.sort(canonicalImports); return canonicalImports; }
java
private static List<ImportStatement> canonicalizeImports( Multimap<String, ImportStatement> importsByNamespace) { List<ImportStatement> canonicalImports = new ArrayList<>(); for (String namespace : importsByNamespace.keySet()) { Collection<ImportStatement> allImports = importsByNamespace.get(namespace); // Find the strongest primitive across all existing imports. Every emitted import for this // namespace will use this primitive. This makes the logic simpler and cannot change runtime // behavior, but may produce spurious changes when multiple aliasing imports of differing // strength exist (which are already in violation of the style guide). ImportPrimitive strongestPrimitive = allImports.stream() .map(ImportStatement::primitive) .reduce(ImportPrimitive.WEAKEST, ImportPrimitive::stronger); // Emit each aliasing import separately, as deduplicating them would require code references // to be rewritten. boolean hasAliasing = false; for (ImportStatement stmt : Iterables.filter(allImports, ImportStatement::isAliasing)) { canonicalImports.add(stmt.upgrade(strongestPrimitive)); hasAliasing = true; } // Emit a single destructuring import with a non-empty pattern, merged from the existing // destructuring imports. boolean hasDestructuring = false; ImmutableList<Node> destructuringNodes = allImports.stream() .filter(ImportStatement::isDestructuring) .flatMap(i -> i.nodes().stream()) .collect(toImmutableList()); ImmutableList<DestructuringBinding> destructures = allImports.stream() .filter(ImportStatement::isDestructuring) .flatMap(i -> i.destructures().stream()) .distinct() .sorted() .collect(toImmutableList()); if (!destructures.isEmpty()) { canonicalImports.add( ImportStatement.of( destructuringNodes, strongestPrimitive, namespace, /* alias= */ null, destructures)); hasDestructuring = true; } // Emit a standalone import unless an aliasing or destructuring one already exists. if (!hasAliasing && !hasDestructuring) { ImmutableList<Node> standaloneNodes = allImports.stream() .filter(ImportStatement::isStandalone) .flatMap(i -> i.nodes().stream()) .collect(toImmutableList()); canonicalImports.add( ImportStatement.of( standaloneNodes, strongestPrimitive, namespace, /* alias= */ null, /* destructures= */ null)); } } // Sorting by natural order yields the correct result due to the implementation of // ImportStatement#compareTo. Collections.sort(canonicalImports); return canonicalImports; }
[ "private", "static", "List", "<", "ImportStatement", ">", "canonicalizeImports", "(", "Multimap", "<", "String", ",", "ImportStatement", ">", "importsByNamespace", ")", "{", "List", "<", "ImportStatement", ">", "canonicalImports", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "namespace", ":", "importsByNamespace", ".", "keySet", "(", ")", ")", "{", "Collection", "<", "ImportStatement", ">", "allImports", "=", "importsByNamespace", ".", "get", "(", "namespace", ")", ";", "// Find the strongest primitive across all existing imports. Every emitted import for this", "// namespace will use this primitive. This makes the logic simpler and cannot change runtime", "// behavior, but may produce spurious changes when multiple aliasing imports of differing", "// strength exist (which are already in violation of the style guide).", "ImportPrimitive", "strongestPrimitive", "=", "allImports", ".", "stream", "(", ")", ".", "map", "(", "ImportStatement", "::", "primitive", ")", ".", "reduce", "(", "ImportPrimitive", ".", "WEAKEST", ",", "ImportPrimitive", "::", "stronger", ")", ";", "// Emit each aliasing import separately, as deduplicating them would require code references", "// to be rewritten.", "boolean", "hasAliasing", "=", "false", ";", "for", "(", "ImportStatement", "stmt", ":", "Iterables", ".", "filter", "(", "allImports", ",", "ImportStatement", "::", "isAliasing", ")", ")", "{", "canonicalImports", ".", "add", "(", "stmt", ".", "upgrade", "(", "strongestPrimitive", ")", ")", ";", "hasAliasing", "=", "true", ";", "}", "// Emit a single destructuring import with a non-empty pattern, merged from the existing", "// destructuring imports.", "boolean", "hasDestructuring", "=", "false", ";", "ImmutableList", "<", "Node", ">", "destructuringNodes", "=", "allImports", ".", "stream", "(", ")", ".", "filter", "(", "ImportStatement", "::", "isDestructuring", ")", ".", "flatMap", "(", "i", "->", "i", ".", "nodes", "(", ")", ".", "stream", "(", ")", ")", ".", "collect", "(", "toImmutableList", "(", ")", ")", ";", "ImmutableList", "<", "DestructuringBinding", ">", "destructures", "=", "allImports", ".", "stream", "(", ")", ".", "filter", "(", "ImportStatement", "::", "isDestructuring", ")", ".", "flatMap", "(", "i", "->", "i", ".", "destructures", "(", ")", ".", "stream", "(", ")", ")", ".", "distinct", "(", ")", ".", "sorted", "(", ")", ".", "collect", "(", "toImmutableList", "(", ")", ")", ";", "if", "(", "!", "destructures", ".", "isEmpty", "(", ")", ")", "{", "canonicalImports", ".", "add", "(", "ImportStatement", ".", "of", "(", "destructuringNodes", ",", "strongestPrimitive", ",", "namespace", ",", "/* alias= */", "null", ",", "destructures", ")", ")", ";", "hasDestructuring", "=", "true", ";", "}", "// Emit a standalone import unless an aliasing or destructuring one already exists.", "if", "(", "!", "hasAliasing", "&&", "!", "hasDestructuring", ")", "{", "ImmutableList", "<", "Node", ">", "standaloneNodes", "=", "allImports", ".", "stream", "(", ")", ".", "filter", "(", "ImportStatement", "::", "isStandalone", ")", ".", "flatMap", "(", "i", "->", "i", ".", "nodes", "(", ")", ".", "stream", "(", ")", ")", ".", "collect", "(", "toImmutableList", "(", ")", ")", ";", "canonicalImports", ".", "add", "(", "ImportStatement", ".", "of", "(", "standaloneNodes", ",", "strongestPrimitive", ",", "namespace", ",", "/* alias= */", "null", ",", "/* destructures= */", "null", ")", ")", ";", "}", "}", "// Sorting by natural order yields the correct result due to the implementation of", "// ImportStatement#compareTo.", "Collections", ".", "sort", "(", "canonicalImports", ")", ";", "return", "canonicalImports", ";", "}" ]
Canonicalizes a list of import statements by deduplicating and merging imports for the same namespace, and sorting the result.
[ "Canonicalizes", "a", "list", "of", "import", "statements", "by", "deduplicating", "and", "merging", "imports", "for", "the", "same", "namespace", "and", "sorting", "the", "result", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/lint/CheckRequiresSorted.java#L407-L479
24,772
google/closure-compiler
src/com/google/javascript/jscomp/MakeDeclaredNamesUnique.java
MakeDeclaredNamesUnique.getReplacementName
private String getReplacementName(String oldName) { for (Renamer renamer : renamerStack) { String newName = renamer.getReplacementName(oldName); if (newName != null) { return newName; } } return null; }
java
private String getReplacementName(String oldName) { for (Renamer renamer : renamerStack) { String newName = renamer.getReplacementName(oldName); if (newName != null) { return newName; } } return null; }
[ "private", "String", "getReplacementName", "(", "String", "oldName", ")", "{", "for", "(", "Renamer", "renamer", ":", "renamerStack", ")", "{", "String", "newName", "=", "renamer", ".", "getReplacementName", "(", "oldName", ")", ";", "if", "(", "newName", "!=", "null", ")", "{", "return", "newName", ";", "}", "}", "return", "null", ";", "}" ]
Walks the stack of name maps and finds the replacement name for the current scope.
[ "Walks", "the", "stack", "of", "name", "maps", "and", "finds", "the", "replacement", "name", "for", "the", "current", "scope", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MakeDeclaredNamesUnique.java#L147-L155
24,773
google/closure-compiler
src/com/google/javascript/jscomp/StatementFusion.java
StatementFusion.fuseIntoOneStatement
private static Node fuseIntoOneStatement(Node parent, Node first, Node last) { // Nothing to fuse if there is only one statement. if (first.getNext() == last) { return first; } // Step one: Create a comma tree that contains all the statements. Node commaTree = first.removeFirstChild(); Node next = null; for (Node cur = first.getNext(); cur != last; cur = next) { commaTree = fuseExpressionIntoExpression( commaTree, cur.removeFirstChild()); next = cur.getNext(); parent.removeChild(cur); } // Step two: The last EXPR_RESULT will now hold the comma tree with all // the fused statements. first.addChildToBack(commaTree); return first; }
java
private static Node fuseIntoOneStatement(Node parent, Node first, Node last) { // Nothing to fuse if there is only one statement. if (first.getNext() == last) { return first; } // Step one: Create a comma tree that contains all the statements. Node commaTree = first.removeFirstChild(); Node next = null; for (Node cur = first.getNext(); cur != last; cur = next) { commaTree = fuseExpressionIntoExpression( commaTree, cur.removeFirstChild()); next = cur.getNext(); parent.removeChild(cur); } // Step two: The last EXPR_RESULT will now hold the comma tree with all // the fused statements. first.addChildToBack(commaTree); return first; }
[ "private", "static", "Node", "fuseIntoOneStatement", "(", "Node", "parent", ",", "Node", "first", ",", "Node", "last", ")", "{", "// Nothing to fuse if there is only one statement.", "if", "(", "first", ".", "getNext", "(", ")", "==", "last", ")", "{", "return", "first", ";", "}", "// Step one: Create a comma tree that contains all the statements.", "Node", "commaTree", "=", "first", ".", "removeFirstChild", "(", ")", ";", "Node", "next", "=", "null", ";", "for", "(", "Node", "cur", "=", "first", ".", "getNext", "(", ")", ";", "cur", "!=", "last", ";", "cur", "=", "next", ")", "{", "commaTree", "=", "fuseExpressionIntoExpression", "(", "commaTree", ",", "cur", ".", "removeFirstChild", "(", ")", ")", ";", "next", "=", "cur", ".", "getNext", "(", ")", ";", "parent", ".", "removeChild", "(", "cur", ")", ";", "}", "// Step two: The last EXPR_RESULT will now hold the comma tree with all", "// the fused statements.", "first", ".", "addChildToBack", "(", "commaTree", ")", ";", "return", "first", ";", "}" ]
Given a block, fuse a list of statements with comma's. @param parent The parent that contains the statements. @param first The first statement to fuse (inclusive) @param last The last statement to fuse (exclusive) @return A single statement that contains all the fused statement as one.
[ "Given", "a", "block", "fuse", "a", "list", "of", "statements", "with", "comma", "s", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/StatementFusion.java#L164-L185
24,774
google/closure-compiler
src/com/google/javascript/jscomp/graph/GraphColoring.java
GraphColoring.getPartitionSuperNode
public N getPartitionSuperNode(N node) { checkNotNull(colorToNodeMap, "No coloring founded. color() should be called first."); Color color = graph.getNode(node).getAnnotation(); N headNode = colorToNodeMap[color.value]; if (headNode == null) { colorToNodeMap[color.value] = node; return node; } else { return headNode; } }
java
public N getPartitionSuperNode(N node) { checkNotNull(colorToNodeMap, "No coloring founded. color() should be called first."); Color color = graph.getNode(node).getAnnotation(); N headNode = colorToNodeMap[color.value]; if (headNode == null) { colorToNodeMap[color.value] = node; return node; } else { return headNode; } }
[ "public", "N", "getPartitionSuperNode", "(", "N", "node", ")", "{", "checkNotNull", "(", "colorToNodeMap", ",", "\"No coloring founded. color() should be called first.\"", ")", ";", "Color", "color", "=", "graph", ".", "getNode", "(", "node", ")", ".", "getAnnotation", "(", ")", ";", "N", "headNode", "=", "colorToNodeMap", "[", "color", ".", "value", "]", ";", "if", "(", "headNode", "==", "null", ")", "{", "colorToNodeMap", "[", "color", ".", "value", "]", "=", "node", ";", "return", "node", ";", "}", "else", "{", "return", "headNode", ";", "}", "}" ]
Using the coloring as partitions, finds the node that represents that partition as the super node. The first to retrieve its partition will become the super node.
[ "Using", "the", "coloring", "as", "partitions", "finds", "the", "node", "that", "represents", "that", "partition", "as", "the", "super", "node", ".", "The", "first", "to", "retrieve", "its", "partition", "will", "become", "the", "super", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/graph/GraphColoring.java#L69-L79
24,775
google/closure-compiler
src/com/google/javascript/jscomp/FunctionArgumentInjector.java
FunctionArgumentInjector.inject
static Node inject( AbstractCompiler compiler, Node node, Node parent, Map<String, Node> replacements) { return inject(compiler, node, parent, replacements, /* replaceThis */ true); }
java
static Node inject( AbstractCompiler compiler, Node node, Node parent, Map<String, Node> replacements) { return inject(compiler, node, parent, replacements, /* replaceThis */ true); }
[ "static", "Node", "inject", "(", "AbstractCompiler", "compiler", ",", "Node", "node", ",", "Node", "parent", ",", "Map", "<", "String", ",", "Node", ">", "replacements", ")", "{", "return", "inject", "(", "compiler", ",", "node", ",", "parent", ",", "replacements", ",", "/* replaceThis */", "true", ")", ";", "}" ]
With the map provided, replace the names with expression trees. @param node The root node of the tree within which to perform the substitutions. @param parent The parent root node. @param replacements The map of names to template node trees with which to replace the name Nodes. @return The root node or its replacement.
[ "With", "the", "map", "provided", "replace", "the", "names", "with", "expression", "trees", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionArgumentInjector.java#L65-L68
24,776
google/closure-compiler
src/com/google/javascript/jscomp/FunctionArgumentInjector.java
FunctionArgumentInjector.getFunctionCallParameterMap
static ImmutableMap<String, Node> getFunctionCallParameterMap( final Node fnNode, Node callNode, Supplier<String> safeNameIdSupplier) { checkNotNull(fnNode); // Create an argName -> expression map ImmutableMap.Builder<String, Node> argMap = ImmutableMap.builder(); // CALL NODE: [ NAME, ARG1, ARG2, ... ] Node cArg = callNode.getSecondChild(); if (cArg != null && NodeUtil.isFunctionObjectCall(callNode)) { argMap.put(THIS_MARKER, cArg); cArg = cArg.getNext(); } else { // 'apply' isn't supported yet. checkState(!NodeUtil.isFunctionObjectApply(callNode), callNode); argMap.put(THIS_MARKER, NodeUtil.newUndefinedNode(callNode)); } for (Node fnParam : NodeUtil.getFunctionParameters(fnNode).children()) { if (cArg != null) { if (fnParam.isRest()) { checkState(fnParam.getOnlyChild().isName(), fnParam.getOnlyChild()); Node array = IR.arraylit(); array.useSourceInfoIfMissingFromForTree(cArg); while (cArg != null) { array.addChildToBack(cArg.cloneTree()); cArg = cArg.getNext(); } argMap.put(fnParam.getOnlyChild().getString(), array); return argMap.build(); } else { checkState(fnParam.isName(), fnParam); argMap.put(fnParam.getString(), cArg); } cArg = cArg.getNext(); } else { // cArg != null if (fnParam.isRest()) { checkState(fnParam.getOnlyChild().isName(), fnParam); //No arguments for REST parameters Node array = IR.arraylit(); argMap.put(fnParam.getOnlyChild().getString(), array); } else { checkState(fnParam.isName(), fnParam); Node srcLocation = callNode; argMap.put(fnParam.getString(), NodeUtil.newUndefinedNode(srcLocation)); } } } // Add temp names for arguments that don't have named parameters in the // called function. while (cArg != null) { String uniquePlaceholder = getUniqueAnonymousParameterName(safeNameIdSupplier); argMap.put(uniquePlaceholder, cArg); cArg = cArg.getNext(); } return argMap.build(); }
java
static ImmutableMap<String, Node> getFunctionCallParameterMap( final Node fnNode, Node callNode, Supplier<String> safeNameIdSupplier) { checkNotNull(fnNode); // Create an argName -> expression map ImmutableMap.Builder<String, Node> argMap = ImmutableMap.builder(); // CALL NODE: [ NAME, ARG1, ARG2, ... ] Node cArg = callNode.getSecondChild(); if (cArg != null && NodeUtil.isFunctionObjectCall(callNode)) { argMap.put(THIS_MARKER, cArg); cArg = cArg.getNext(); } else { // 'apply' isn't supported yet. checkState(!NodeUtil.isFunctionObjectApply(callNode), callNode); argMap.put(THIS_MARKER, NodeUtil.newUndefinedNode(callNode)); } for (Node fnParam : NodeUtil.getFunctionParameters(fnNode).children()) { if (cArg != null) { if (fnParam.isRest()) { checkState(fnParam.getOnlyChild().isName(), fnParam.getOnlyChild()); Node array = IR.arraylit(); array.useSourceInfoIfMissingFromForTree(cArg); while (cArg != null) { array.addChildToBack(cArg.cloneTree()); cArg = cArg.getNext(); } argMap.put(fnParam.getOnlyChild().getString(), array); return argMap.build(); } else { checkState(fnParam.isName(), fnParam); argMap.put(fnParam.getString(), cArg); } cArg = cArg.getNext(); } else { // cArg != null if (fnParam.isRest()) { checkState(fnParam.getOnlyChild().isName(), fnParam); //No arguments for REST parameters Node array = IR.arraylit(); argMap.put(fnParam.getOnlyChild().getString(), array); } else { checkState(fnParam.isName(), fnParam); Node srcLocation = callNode; argMap.put(fnParam.getString(), NodeUtil.newUndefinedNode(srcLocation)); } } } // Add temp names for arguments that don't have named parameters in the // called function. while (cArg != null) { String uniquePlaceholder = getUniqueAnonymousParameterName(safeNameIdSupplier); argMap.put(uniquePlaceholder, cArg); cArg = cArg.getNext(); } return argMap.build(); }
[ "static", "ImmutableMap", "<", "String", ",", "Node", ">", "getFunctionCallParameterMap", "(", "final", "Node", "fnNode", ",", "Node", "callNode", ",", "Supplier", "<", "String", ">", "safeNameIdSupplier", ")", "{", "checkNotNull", "(", "fnNode", ")", ";", "// Create an argName -> expression map", "ImmutableMap", ".", "Builder", "<", "String", ",", "Node", ">", "argMap", "=", "ImmutableMap", ".", "builder", "(", ")", ";", "// CALL NODE: [ NAME, ARG1, ARG2, ... ]", "Node", "cArg", "=", "callNode", ".", "getSecondChild", "(", ")", ";", "if", "(", "cArg", "!=", "null", "&&", "NodeUtil", ".", "isFunctionObjectCall", "(", "callNode", ")", ")", "{", "argMap", ".", "put", "(", "THIS_MARKER", ",", "cArg", ")", ";", "cArg", "=", "cArg", ".", "getNext", "(", ")", ";", "}", "else", "{", "// 'apply' isn't supported yet.", "checkState", "(", "!", "NodeUtil", ".", "isFunctionObjectApply", "(", "callNode", ")", ",", "callNode", ")", ";", "argMap", ".", "put", "(", "THIS_MARKER", ",", "NodeUtil", ".", "newUndefinedNode", "(", "callNode", ")", ")", ";", "}", "for", "(", "Node", "fnParam", ":", "NodeUtil", ".", "getFunctionParameters", "(", "fnNode", ")", ".", "children", "(", ")", ")", "{", "if", "(", "cArg", "!=", "null", ")", "{", "if", "(", "fnParam", ".", "isRest", "(", ")", ")", "{", "checkState", "(", "fnParam", ".", "getOnlyChild", "(", ")", ".", "isName", "(", ")", ",", "fnParam", ".", "getOnlyChild", "(", ")", ")", ";", "Node", "array", "=", "IR", ".", "arraylit", "(", ")", ";", "array", ".", "useSourceInfoIfMissingFromForTree", "(", "cArg", ")", ";", "while", "(", "cArg", "!=", "null", ")", "{", "array", ".", "addChildToBack", "(", "cArg", ".", "cloneTree", "(", ")", ")", ";", "cArg", "=", "cArg", ".", "getNext", "(", ")", ";", "}", "argMap", ".", "put", "(", "fnParam", ".", "getOnlyChild", "(", ")", ".", "getString", "(", ")", ",", "array", ")", ";", "return", "argMap", ".", "build", "(", ")", ";", "}", "else", "{", "checkState", "(", "fnParam", ".", "isName", "(", ")", ",", "fnParam", ")", ";", "argMap", ".", "put", "(", "fnParam", ".", "getString", "(", ")", ",", "cArg", ")", ";", "}", "cArg", "=", "cArg", ".", "getNext", "(", ")", ";", "}", "else", "{", "// cArg != null", "if", "(", "fnParam", ".", "isRest", "(", ")", ")", "{", "checkState", "(", "fnParam", ".", "getOnlyChild", "(", ")", ".", "isName", "(", ")", ",", "fnParam", ")", ";", "//No arguments for REST parameters", "Node", "array", "=", "IR", ".", "arraylit", "(", ")", ";", "argMap", ".", "put", "(", "fnParam", ".", "getOnlyChild", "(", ")", ".", "getString", "(", ")", ",", "array", ")", ";", "}", "else", "{", "checkState", "(", "fnParam", ".", "isName", "(", ")", ",", "fnParam", ")", ";", "Node", "srcLocation", "=", "callNode", ";", "argMap", ".", "put", "(", "fnParam", ".", "getString", "(", ")", ",", "NodeUtil", ".", "newUndefinedNode", "(", "srcLocation", ")", ")", ";", "}", "}", "}", "// Add temp names for arguments that don't have named parameters in the", "// called function.", "while", "(", "cArg", "!=", "null", ")", "{", "String", "uniquePlaceholder", "=", "getUniqueAnonymousParameterName", "(", "safeNameIdSupplier", ")", ";", "argMap", ".", "put", "(", "uniquePlaceholder", ",", "cArg", ")", ";", "cArg", "=", "cArg", ".", "getNext", "(", ")", ";", "}", "return", "argMap", ".", "build", "(", ")", ";", "}" ]
Get a mapping for function parameter names to call arguments.
[ "Get", "a", "mapping", "for", "function", "parameter", "names", "to", "call", "arguments", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionArgumentInjector.java#L123-L180
24,777
google/closure-compiler
src/com/google/javascript/jscomp/FunctionArgumentInjector.java
FunctionArgumentInjector.maybeAddTempsForCallArguments
static void maybeAddTempsForCallArguments( AbstractCompiler compiler, Node fnNode, ImmutableMap<String, Node> argMap, Set<String> namesNeedingTemps, CodingConvention convention) { if (argMap.isEmpty()) { // No arguments to check, we are done. return; } checkArgument(fnNode.isFunction(), fnNode); Node block = fnNode.getLastChild(); int argCount = argMap.size(); // We limit the "trivial" bodies to those where there is a single expression or // return, the expression is boolean isTrivialBody = (!block.hasChildren() || (block.hasOneChild() && !bodyMayHaveConditionalCode(block.getLastChild()))); boolean hasMinimalParameters = NodeUtil.isUndefined(argMap.get(THIS_MARKER)) && argCount <= 2; // this + one parameter // Get the list of parameters that may need temporaries due to side-effects. ImmutableSet<String> namesAfterSideEffects = findParametersReferencedAfterSideEffect( argMap.keySet(), block); // Check for arguments that are evaluated more than once. for (Map.Entry<String, Node> entry : argMap.entrySet()) { String argName = entry.getKey(); if (namesNeedingTemps.contains(argName)) { continue; } Node cArg = entry.getValue(); boolean safe = true; int references = NodeUtil.getNameReferenceCount(block, argName); boolean argSideEffects = NodeUtil.mayHaveSideEffects(cArg, compiler); if (!argSideEffects && references == 0) { safe = true; } else if (isTrivialBody && hasMinimalParameters && references == 1 && !(NodeUtil.canBeSideEffected(cArg) && namesAfterSideEffects.contains(argName))) { // For functions with a trivial body, and where the parameter evaluation order // can't change, and there aren't any side-effect before the parameter, we can // avoid creating a temporary. // // This is done to help inline common trivial functions safe = true; } else if (NodeUtil.mayEffectMutableState(cArg, compiler) && references > 0) { // Note: Mutable arguments should be assigned to temps, as the // may be within in a loop: // function x(a) { // for(var i=0; i<0; i++) { // foo(a); // } // x( [] ); // // The parameter in the call to foo should not become "[]". safe = false; } else if (argSideEffects) { // Even if there are no references, we still need to evaluate the // expression if it has side-effects. safe = false; } else if (NodeUtil.canBeSideEffected(cArg) && namesAfterSideEffects.contains(argName)) { safe = false; } else if (references > 1) { // Safe is a misnomer, this is a check for "large". switch (cArg.getToken()) { case NAME: String name = cArg.getString(); safe = !(convention.isExported(name)); break; case THIS: safe = true; break; case STRING: safe = (cArg.getString().length() < 2); break; default: safe = NodeUtil.isImmutableValue(cArg); break; } } if (!safe) { namesNeedingTemps.add(argName); } } }
java
static void maybeAddTempsForCallArguments( AbstractCompiler compiler, Node fnNode, ImmutableMap<String, Node> argMap, Set<String> namesNeedingTemps, CodingConvention convention) { if (argMap.isEmpty()) { // No arguments to check, we are done. return; } checkArgument(fnNode.isFunction(), fnNode); Node block = fnNode.getLastChild(); int argCount = argMap.size(); // We limit the "trivial" bodies to those where there is a single expression or // return, the expression is boolean isTrivialBody = (!block.hasChildren() || (block.hasOneChild() && !bodyMayHaveConditionalCode(block.getLastChild()))); boolean hasMinimalParameters = NodeUtil.isUndefined(argMap.get(THIS_MARKER)) && argCount <= 2; // this + one parameter // Get the list of parameters that may need temporaries due to side-effects. ImmutableSet<String> namesAfterSideEffects = findParametersReferencedAfterSideEffect( argMap.keySet(), block); // Check for arguments that are evaluated more than once. for (Map.Entry<String, Node> entry : argMap.entrySet()) { String argName = entry.getKey(); if (namesNeedingTemps.contains(argName)) { continue; } Node cArg = entry.getValue(); boolean safe = true; int references = NodeUtil.getNameReferenceCount(block, argName); boolean argSideEffects = NodeUtil.mayHaveSideEffects(cArg, compiler); if (!argSideEffects && references == 0) { safe = true; } else if (isTrivialBody && hasMinimalParameters && references == 1 && !(NodeUtil.canBeSideEffected(cArg) && namesAfterSideEffects.contains(argName))) { // For functions with a trivial body, and where the parameter evaluation order // can't change, and there aren't any side-effect before the parameter, we can // avoid creating a temporary. // // This is done to help inline common trivial functions safe = true; } else if (NodeUtil.mayEffectMutableState(cArg, compiler) && references > 0) { // Note: Mutable arguments should be assigned to temps, as the // may be within in a loop: // function x(a) { // for(var i=0; i<0; i++) { // foo(a); // } // x( [] ); // // The parameter in the call to foo should not become "[]". safe = false; } else if (argSideEffects) { // Even if there are no references, we still need to evaluate the // expression if it has side-effects. safe = false; } else if (NodeUtil.canBeSideEffected(cArg) && namesAfterSideEffects.contains(argName)) { safe = false; } else if (references > 1) { // Safe is a misnomer, this is a check for "large". switch (cArg.getToken()) { case NAME: String name = cArg.getString(); safe = !(convention.isExported(name)); break; case THIS: safe = true; break; case STRING: safe = (cArg.getString().length() < 2); break; default: safe = NodeUtil.isImmutableValue(cArg); break; } } if (!safe) { namesNeedingTemps.add(argName); } } }
[ "static", "void", "maybeAddTempsForCallArguments", "(", "AbstractCompiler", "compiler", ",", "Node", "fnNode", ",", "ImmutableMap", "<", "String", ",", "Node", ">", "argMap", ",", "Set", "<", "String", ">", "namesNeedingTemps", ",", "CodingConvention", "convention", ")", "{", "if", "(", "argMap", ".", "isEmpty", "(", ")", ")", "{", "// No arguments to check, we are done.", "return", ";", "}", "checkArgument", "(", "fnNode", ".", "isFunction", "(", ")", ",", "fnNode", ")", ";", "Node", "block", "=", "fnNode", ".", "getLastChild", "(", ")", ";", "int", "argCount", "=", "argMap", ".", "size", "(", ")", ";", "// We limit the \"trivial\" bodies to those where there is a single expression or", "// return, the expression is", "boolean", "isTrivialBody", "=", "(", "!", "block", ".", "hasChildren", "(", ")", "||", "(", "block", ".", "hasOneChild", "(", ")", "&&", "!", "bodyMayHaveConditionalCode", "(", "block", ".", "getLastChild", "(", ")", ")", ")", ")", ";", "boolean", "hasMinimalParameters", "=", "NodeUtil", ".", "isUndefined", "(", "argMap", ".", "get", "(", "THIS_MARKER", ")", ")", "&&", "argCount", "<=", "2", ";", "// this + one parameter", "// Get the list of parameters that may need temporaries due to side-effects.", "ImmutableSet", "<", "String", ">", "namesAfterSideEffects", "=", "findParametersReferencedAfterSideEffect", "(", "argMap", ".", "keySet", "(", ")", ",", "block", ")", ";", "// Check for arguments that are evaluated more than once.", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Node", ">", "entry", ":", "argMap", ".", "entrySet", "(", ")", ")", "{", "String", "argName", "=", "entry", ".", "getKey", "(", ")", ";", "if", "(", "namesNeedingTemps", ".", "contains", "(", "argName", ")", ")", "{", "continue", ";", "}", "Node", "cArg", "=", "entry", ".", "getValue", "(", ")", ";", "boolean", "safe", "=", "true", ";", "int", "references", "=", "NodeUtil", ".", "getNameReferenceCount", "(", "block", ",", "argName", ")", ";", "boolean", "argSideEffects", "=", "NodeUtil", ".", "mayHaveSideEffects", "(", "cArg", ",", "compiler", ")", ";", "if", "(", "!", "argSideEffects", "&&", "references", "==", "0", ")", "{", "safe", "=", "true", ";", "}", "else", "if", "(", "isTrivialBody", "&&", "hasMinimalParameters", "&&", "references", "==", "1", "&&", "!", "(", "NodeUtil", ".", "canBeSideEffected", "(", "cArg", ")", "&&", "namesAfterSideEffects", ".", "contains", "(", "argName", ")", ")", ")", "{", "// For functions with a trivial body, and where the parameter evaluation order", "// can't change, and there aren't any side-effect before the parameter, we can", "// avoid creating a temporary.", "//", "// This is done to help inline common trivial functions", "safe", "=", "true", ";", "}", "else", "if", "(", "NodeUtil", ".", "mayEffectMutableState", "(", "cArg", ",", "compiler", ")", "&&", "references", ">", "0", ")", "{", "// Note: Mutable arguments should be assigned to temps, as the", "// may be within in a loop:", "// function x(a) {", "// for(var i=0; i<0; i++) {", "// foo(a);", "// }", "// x( [] );", "//", "// The parameter in the call to foo should not become \"[]\".", "safe", "=", "false", ";", "}", "else", "if", "(", "argSideEffects", ")", "{", "// Even if there are no references, we still need to evaluate the", "// expression if it has side-effects.", "safe", "=", "false", ";", "}", "else", "if", "(", "NodeUtil", ".", "canBeSideEffected", "(", "cArg", ")", "&&", "namesAfterSideEffects", ".", "contains", "(", "argName", ")", ")", "{", "safe", "=", "false", ";", "}", "else", "if", "(", "references", ">", "1", ")", "{", "// Safe is a misnomer, this is a check for \"large\".", "switch", "(", "cArg", ".", "getToken", "(", ")", ")", "{", "case", "NAME", ":", "String", "name", "=", "cArg", ".", "getString", "(", ")", ";", "safe", "=", "!", "(", "convention", ".", "isExported", "(", "name", ")", ")", ";", "break", ";", "case", "THIS", ":", "safe", "=", "true", ";", "break", ";", "case", "STRING", ":", "safe", "=", "(", "cArg", ".", "getString", "(", ")", ".", "length", "(", ")", "<", "2", ")", ";", "break", ";", "default", ":", "safe", "=", "NodeUtil", ".", "isImmutableValue", "(", "cArg", ")", ";", "break", ";", "}", "}", "if", "(", "!", "safe", ")", "{", "namesNeedingTemps", ".", "add", "(", "argName", ")", ";", "}", "}", "}" ]
Updates the set of parameter names in set unsafe to include any arguments from the call site that require aliases. @param fnNode The FUNCTION node to be inlined. @param argMap The argument list for the call to fnNode. @param namesNeedingTemps The set of names to update.
[ "Updates", "the", "set", "of", "parameter", "names", "in", "set", "unsafe", "to", "include", "any", "arguments", "from", "the", "call", "site", "that", "require", "aliases", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionArgumentInjector.java#L271-L359
24,778
google/closure-compiler
src/com/google/javascript/jscomp/FunctionArgumentInjector.java
FunctionArgumentInjector.bodyMayHaveConditionalCode
static boolean bodyMayHaveConditionalCode(Node n) { if (!n.isReturn() && !n.isExprResult()) { return true; } return mayHaveConditionalCode(n); }
java
static boolean bodyMayHaveConditionalCode(Node n) { if (!n.isReturn() && !n.isExprResult()) { return true; } return mayHaveConditionalCode(n); }
[ "static", "boolean", "bodyMayHaveConditionalCode", "(", "Node", "n", ")", "{", "if", "(", "!", "n", ".", "isReturn", "(", ")", "&&", "!", "n", ".", "isExprResult", "(", ")", ")", "{", "return", "true", ";", "}", "return", "mayHaveConditionalCode", "(", "n", ")", ";", "}" ]
We consider a return or expression trivial if it doesn't contain a conditional expression or a function.
[ "We", "consider", "a", "return", "or", "expression", "trivial", "if", "it", "doesn", "t", "contain", "a", "conditional", "expression", "or", "a", "function", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionArgumentInjector.java#L365-L370
24,779
google/closure-compiler
src/com/google/javascript/jscomp/FunctionArgumentInjector.java
FunctionArgumentInjector.mayHaveConditionalCode
static boolean mayHaveConditionalCode(Node n) { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { switch (c.getToken()) { case FUNCTION: case AND: case OR: case HOOK: return true; default: break; } if (mayHaveConditionalCode(c)) { return true; } } return false; }
java
static boolean mayHaveConditionalCode(Node n) { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { switch (c.getToken()) { case FUNCTION: case AND: case OR: case HOOK: return true; default: break; } if (mayHaveConditionalCode(c)) { return true; } } return false; }
[ "static", "boolean", "mayHaveConditionalCode", "(", "Node", "n", ")", "{", "for", "(", "Node", "c", "=", "n", ".", "getFirstChild", "(", ")", ";", "c", "!=", "null", ";", "c", "=", "c", ".", "getNext", "(", ")", ")", "{", "switch", "(", "c", ".", "getToken", "(", ")", ")", "{", "case", "FUNCTION", ":", "case", "AND", ":", "case", "OR", ":", "case", "HOOK", ":", "return", "true", ";", "default", ":", "break", ";", "}", "if", "(", "mayHaveConditionalCode", "(", "c", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
We consider an expression trivial if it doesn't contain a conditional expression or a function.
[ "We", "consider", "an", "expression", "trivial", "if", "it", "doesn", "t", "contain", "a", "conditional", "expression", "or", "a", "function", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionArgumentInjector.java#L376-L392
24,780
google/closure-compiler
src/com/google/javascript/jscomp/FunctionArgumentInjector.java
FunctionArgumentInjector.findParametersReferencedAfterSideEffect
private static ImmutableSet<String> findParametersReferencedAfterSideEffect( ImmutableSet<String> parameters, Node root) { // TODO(johnlenz): Consider using scope for this. Set<String> locals = new HashSet<>(parameters); gatherLocalNames(root, locals); ReferencedAfterSideEffect collector = new ReferencedAfterSideEffect( parameters, ImmutableSet.copyOf(locals)); NodeUtil.visitPostOrder( root, collector, collector); return collector.getResults(); }
java
private static ImmutableSet<String> findParametersReferencedAfterSideEffect( ImmutableSet<String> parameters, Node root) { // TODO(johnlenz): Consider using scope for this. Set<String> locals = new HashSet<>(parameters); gatherLocalNames(root, locals); ReferencedAfterSideEffect collector = new ReferencedAfterSideEffect( parameters, ImmutableSet.copyOf(locals)); NodeUtil.visitPostOrder( root, collector, collector); return collector.getResults(); }
[ "private", "static", "ImmutableSet", "<", "String", ">", "findParametersReferencedAfterSideEffect", "(", "ImmutableSet", "<", "String", ">", "parameters", ",", "Node", "root", ")", "{", "// TODO(johnlenz): Consider using scope for this.", "Set", "<", "String", ">", "locals", "=", "new", "HashSet", "<>", "(", "parameters", ")", ";", "gatherLocalNames", "(", "root", ",", "locals", ")", ";", "ReferencedAfterSideEffect", "collector", "=", "new", "ReferencedAfterSideEffect", "(", "parameters", ",", "ImmutableSet", ".", "copyOf", "(", "locals", ")", ")", ";", "NodeUtil", ".", "visitPostOrder", "(", "root", ",", "collector", ",", "collector", ")", ";", "return", "collector", ".", "getResults", "(", ")", ";", "}" ]
Bootstrap a traversal to look for parameters referenced after a non-local side-effect. NOTE: This assumes no-inner functions. @param parameters The set of parameter names. @param root The function code block. @return The subset of parameters referenced after the first seen non-local side-effect.
[ "Bootstrap", "a", "traversal", "to", "look", "for", "parameters", "referenced", "after", "a", "non", "-", "local", "side", "-", "effect", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionArgumentInjector.java#L403-L417
24,781
google/closure-compiler
src/com/google/javascript/jscomp/FunctionArgumentInjector.java
FunctionArgumentInjector.gatherLocalNames
private static void gatherLocalNames(Node n, Set<String> names) { if (n.isFunction()) { if (NodeUtil.isFunctionDeclaration(n)) { names.add(n.getFirstChild().getString()); } // Don't traverse into inner function scopes; return; } else if (n.isName()) { switch (n.getParent().getToken()) { case VAR: case LET: case CONST: case CATCH: names.add(n.getString()); break; default: break; } } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { gatherLocalNames(c, names); } }
java
private static void gatherLocalNames(Node n, Set<String> names) { if (n.isFunction()) { if (NodeUtil.isFunctionDeclaration(n)) { names.add(n.getFirstChild().getString()); } // Don't traverse into inner function scopes; return; } else if (n.isName()) { switch (n.getParent().getToken()) { case VAR: case LET: case CONST: case CATCH: names.add(n.getString()); break; default: break; } } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { gatherLocalNames(c, names); } }
[ "private", "static", "void", "gatherLocalNames", "(", "Node", "n", ",", "Set", "<", "String", ">", "names", ")", "{", "if", "(", "n", ".", "isFunction", "(", ")", ")", "{", "if", "(", "NodeUtil", ".", "isFunctionDeclaration", "(", "n", ")", ")", "{", "names", ".", "add", "(", "n", ".", "getFirstChild", "(", ")", ".", "getString", "(", ")", ")", ";", "}", "// Don't traverse into inner function scopes;", "return", ";", "}", "else", "if", "(", "n", ".", "isName", "(", ")", ")", "{", "switch", "(", "n", ".", "getParent", "(", ")", ".", "getToken", "(", ")", ")", "{", "case", "VAR", ":", "case", "LET", ":", "case", "CONST", ":", "case", "CATCH", ":", "names", ".", "add", "(", "n", ".", "getString", "(", ")", ")", ";", "break", ";", "default", ":", "break", ";", "}", "}", "for", "(", "Node", "c", "=", "n", ".", "getFirstChild", "(", ")", ";", "c", "!=", "null", ";", "c", "=", "c", ".", "getNext", "(", ")", ")", "{", "gatherLocalNames", "(", "c", ",", "names", ")", ";", "}", "}" ]
Gather any names declared in the local scope.
[ "Gather", "any", "names", "declared", "in", "the", "local", "scope", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionArgumentInjector.java#L548-L571
24,782
google/closure-compiler
src/com/google/javascript/jscomp/FunctionArgumentInjector.java
FunctionArgumentInjector.getFunctionParameterSet
private static ImmutableSet<String> getFunctionParameterSet(Node fnNode) { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); for (Node n : NodeUtil.getFunctionParameters(fnNode).children()) { if (n.isRest()){ builder.add(REST_MARKER); } else if (n.isDefaultValue() || n.isObjectPattern() || n.isArrayPattern()) { throw new IllegalStateException("Not supported: " + n); } else { builder.add(n.getString()); } } return builder.build(); }
java
private static ImmutableSet<String> getFunctionParameterSet(Node fnNode) { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); for (Node n : NodeUtil.getFunctionParameters(fnNode).children()) { if (n.isRest()){ builder.add(REST_MARKER); } else if (n.isDefaultValue() || n.isObjectPattern() || n.isArrayPattern()) { throw new IllegalStateException("Not supported: " + n); } else { builder.add(n.getString()); } } return builder.build(); }
[ "private", "static", "ImmutableSet", "<", "String", ">", "getFunctionParameterSet", "(", "Node", "fnNode", ")", "{", "ImmutableSet", ".", "Builder", "<", "String", ">", "builder", "=", "ImmutableSet", ".", "builder", "(", ")", ";", "for", "(", "Node", "n", ":", "NodeUtil", ".", "getFunctionParameters", "(", "fnNode", ")", ".", "children", "(", ")", ")", "{", "if", "(", "n", ".", "isRest", "(", ")", ")", "{", "builder", ".", "add", "(", "REST_MARKER", ")", ";", "}", "else", "if", "(", "n", ".", "isDefaultValue", "(", ")", "||", "n", ".", "isObjectPattern", "(", ")", "||", "n", ".", "isArrayPattern", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Not supported: \"", "+", "n", ")", ";", "}", "else", "{", "builder", ".", "add", "(", "n", ".", "getString", "(", ")", ")", ";", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Get a set of function parameter names.
[ "Get", "a", "set", "of", "function", "parameter", "names", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionArgumentInjector.java#L576-L588
24,783
google/closure-compiler
src/com/google/javascript/jscomp/resources/ResourceLoader.java
ResourceLoader.loadGlobalConformance
public static ConformanceConfig loadGlobalConformance(Class<?> clazz) { ConformanceConfig.Builder builder = ConformanceConfig.newBuilder(); if (resourceExists(clazz, "global_conformance.binarypb")) { try { builder.mergeFrom(clazz.getResourceAsStream("global_conformance.binarypb")); } catch (IOException e) { throw new RuntimeException(e); } } return builder.build(); }
java
public static ConformanceConfig loadGlobalConformance(Class<?> clazz) { ConformanceConfig.Builder builder = ConformanceConfig.newBuilder(); if (resourceExists(clazz, "global_conformance.binarypb")) { try { builder.mergeFrom(clazz.getResourceAsStream("global_conformance.binarypb")); } catch (IOException e) { throw new RuntimeException(e); } } return builder.build(); }
[ "public", "static", "ConformanceConfig", "loadGlobalConformance", "(", "Class", "<", "?", ">", "clazz", ")", "{", "ConformanceConfig", ".", "Builder", "builder", "=", "ConformanceConfig", ".", "newBuilder", "(", ")", ";", "if", "(", "resourceExists", "(", "clazz", ",", "\"global_conformance.binarypb\"", ")", ")", "{", "try", "{", "builder", ".", "mergeFrom", "(", "clazz", ".", "getResourceAsStream", "(", "\"global_conformance.binarypb\"", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Load the global ConformanceConfig
[ "Load", "the", "global", "ConformanceConfig" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/resources/ResourceLoader.java#L47-L57
24,784
google/closure-compiler
src/com/google/javascript/jscomp/lint/CheckUselessBlocks.java
CheckUselessBlocks.isLoneBlock
private boolean isLoneBlock(Node n) { Node parent = n.getParent(); if (parent != null && (parent.isScript() || (parent.isBlock() && !parent.isSyntheticBlock() && !parent.isAddedBlock()))) { return !n.isSyntheticBlock() && !n.isAddedBlock(); } return false; }
java
private boolean isLoneBlock(Node n) { Node parent = n.getParent(); if (parent != null && (parent.isScript() || (parent.isBlock() && !parent.isSyntheticBlock() && !parent.isAddedBlock()))) { return !n.isSyntheticBlock() && !n.isAddedBlock(); } return false; }
[ "private", "boolean", "isLoneBlock", "(", "Node", "n", ")", "{", "Node", "parent", "=", "n", ".", "getParent", "(", ")", ";", "if", "(", "parent", "!=", "null", "&&", "(", "parent", ".", "isScript", "(", ")", "||", "(", "parent", ".", "isBlock", "(", ")", "&&", "!", "parent", ".", "isSyntheticBlock", "(", ")", "&&", "!", "parent", ".", "isAddedBlock", "(", ")", ")", ")", ")", "{", "return", "!", "n", ".", "isSyntheticBlock", "(", ")", "&&", "!", "n", ".", "isAddedBlock", "(", ")", ";", "}", "return", "false", ";", "}" ]
A lone block is a non-synthetic, not-added BLOCK that is a direct child of another non-synthetic, not-added BLOCK or a SCRIPT node.
[ "A", "lone", "block", "is", "a", "non", "-", "synthetic", "not", "-", "added", "BLOCK", "that", "is", "a", "direct", "child", "of", "another", "non", "-", "synthetic", "not", "-", "added", "BLOCK", "or", "a", "SCRIPT", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/lint/CheckUselessBlocks.java#L74-L81
24,785
google/closure-compiler
src/com/google/javascript/jscomp/lint/CheckUselessBlocks.java
CheckUselessBlocks.allowLoneBlock
private void allowLoneBlock(Node parent) { if (loneBlocks.isEmpty()) { return; } if (loneBlocks.peek() == parent) { loneBlocks.pop(); } }
java
private void allowLoneBlock(Node parent) { if (loneBlocks.isEmpty()) { return; } if (loneBlocks.peek() == parent) { loneBlocks.pop(); } }
[ "private", "void", "allowLoneBlock", "(", "Node", "parent", ")", "{", "if", "(", "loneBlocks", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "if", "(", "loneBlocks", ".", "peek", "(", ")", "==", "parent", ")", "{", "loneBlocks", ".", "pop", "(", ")", ";", "}", "}" ]
Remove the enclosing block of a block-scoped declaration from the loneBlocks stack.
[ "Remove", "the", "enclosing", "block", "of", "a", "block", "-", "scoped", "declaration", "from", "the", "loneBlocks", "stack", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/lint/CheckUselessBlocks.java#L86-L94
24,786
google/closure-compiler
src/com/google/javascript/jscomp/ExpressionDecomposer.java
ExpressionDecomposer.maybeExposeExpression
void maybeExposeExpression(Node expression) { // If the expression needs to exposed. int i = 0; while (DecompositionType.DECOMPOSABLE == canExposeExpression(expression)) { exposeExpression(expression); i++; if (i > MAX_ITERATIONS) { throw new IllegalStateException( "DecomposeExpression depth exceeded on:\n" + expression.toStringTree()); } } }
java
void maybeExposeExpression(Node expression) { // If the expression needs to exposed. int i = 0; while (DecompositionType.DECOMPOSABLE == canExposeExpression(expression)) { exposeExpression(expression); i++; if (i > MAX_ITERATIONS) { throw new IllegalStateException( "DecomposeExpression depth exceeded on:\n" + expression.toStringTree()); } } }
[ "void", "maybeExposeExpression", "(", "Node", "expression", ")", "{", "// If the expression needs to exposed.", "int", "i", "=", "0", ";", "while", "(", "DecompositionType", ".", "DECOMPOSABLE", "==", "canExposeExpression", "(", "expression", ")", ")", "{", "exposeExpression", "(", "expression", ")", ";", "i", "++", ";", "if", "(", "i", ">", "MAX_ITERATIONS", ")", "{", "throw", "new", "IllegalStateException", "(", "\"DecomposeExpression depth exceeded on:\\n\"", "+", "expression", ".", "toStringTree", "(", ")", ")", ";", "}", "}", "}" ]
If required, rewrite the statement containing the expression. @param expression The expression to be exposed. @see #canExposeExpression
[ "If", "required", "rewrite", "the", "statement", "containing", "the", "expression", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExpressionDecomposer.java#L108-L119
24,787
google/closure-compiler
src/com/google/javascript/jscomp/ExpressionDecomposer.java
ExpressionDecomposer.moveExpression
void moveExpression(Node expression) { // TODO(johnlenz): This is not currently used by the function inliner, // as moving the call out of the expression before the actual function call // causes additional variables to be introduced. As the variable // inliner is improved, this might be a viable option. String resultName = getResultValueName(); Node injectionPoint = findInjectionPoint(expression); checkNotNull(injectionPoint); Node injectionPointParent = injectionPoint.getParent(); checkNotNull(injectionPointParent); checkState(NodeUtil.isStatementBlock(injectionPointParent)); // Replace the expression with a reference to the new name. Node expressionParent = expression.getParent(); expressionParent.replaceChild( expression, withType(IR.name(resultName), expression.getJSType())); // Re-add the expression at the appropriate place. Node newExpressionRoot = NodeUtil.newVarNode(resultName, expression); newExpressionRoot.getFirstChild().setJSType(expression.getJSType()); injectionPointParent.addChildBefore(newExpressionRoot, injectionPoint); compiler.reportChangeToEnclosingScope(injectionPointParent); }
java
void moveExpression(Node expression) { // TODO(johnlenz): This is not currently used by the function inliner, // as moving the call out of the expression before the actual function call // causes additional variables to be introduced. As the variable // inliner is improved, this might be a viable option. String resultName = getResultValueName(); Node injectionPoint = findInjectionPoint(expression); checkNotNull(injectionPoint); Node injectionPointParent = injectionPoint.getParent(); checkNotNull(injectionPointParent); checkState(NodeUtil.isStatementBlock(injectionPointParent)); // Replace the expression with a reference to the new name. Node expressionParent = expression.getParent(); expressionParent.replaceChild( expression, withType(IR.name(resultName), expression.getJSType())); // Re-add the expression at the appropriate place. Node newExpressionRoot = NodeUtil.newVarNode(resultName, expression); newExpressionRoot.getFirstChild().setJSType(expression.getJSType()); injectionPointParent.addChildBefore(newExpressionRoot, injectionPoint); compiler.reportChangeToEnclosingScope(injectionPointParent); }
[ "void", "moveExpression", "(", "Node", "expression", ")", "{", "// TODO(johnlenz): This is not currently used by the function inliner,", "// as moving the call out of the expression before the actual function call", "// causes additional variables to be introduced. As the variable", "// inliner is improved, this might be a viable option.", "String", "resultName", "=", "getResultValueName", "(", ")", ";", "Node", "injectionPoint", "=", "findInjectionPoint", "(", "expression", ")", ";", "checkNotNull", "(", "injectionPoint", ")", ";", "Node", "injectionPointParent", "=", "injectionPoint", ".", "getParent", "(", ")", ";", "checkNotNull", "(", "injectionPointParent", ")", ";", "checkState", "(", "NodeUtil", ".", "isStatementBlock", "(", "injectionPointParent", ")", ")", ";", "// Replace the expression with a reference to the new name.", "Node", "expressionParent", "=", "expression", ".", "getParent", "(", ")", ";", "expressionParent", ".", "replaceChild", "(", "expression", ",", "withType", "(", "IR", ".", "name", "(", "resultName", ")", ",", "expression", ".", "getJSType", "(", ")", ")", ")", ";", "// Re-add the expression at the appropriate place.", "Node", "newExpressionRoot", "=", "NodeUtil", ".", "newVarNode", "(", "resultName", ",", "expression", ")", ";", "newExpressionRoot", ".", "getFirstChild", "(", ")", ".", "setJSType", "(", "expression", ".", "getJSType", "(", ")", ")", ";", "injectionPointParent", ".", "addChildBefore", "(", "newExpressionRoot", ",", "injectionPoint", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "injectionPointParent", ")", ";", "}" ]
Extract the specified expression from its parent expression. @see #canExposeExpression
[ "Extract", "the", "specified", "expression", "from", "its", "parent", "expression", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExpressionDecomposer.java#L257-L281
24,788
google/closure-compiler
src/com/google/javascript/jscomp/ExpressionDecomposer.java
ExpressionDecomposer.buildResultExpression
private static Node buildResultExpression(Node expr, boolean needResult, String tempName) { if (needResult) { JSType type = expr.getJSType(); return withType(IR.assign(withType(IR.name(tempName), type), expr), type).srcrefTree(expr); } else { return expr; } }
java
private static Node buildResultExpression(Node expr, boolean needResult, String tempName) { if (needResult) { JSType type = expr.getJSType(); return withType(IR.assign(withType(IR.name(tempName), type), expr), type).srcrefTree(expr); } else { return expr; } }
[ "private", "static", "Node", "buildResultExpression", "(", "Node", "expr", ",", "boolean", "needResult", ",", "String", "tempName", ")", "{", "if", "(", "needResult", ")", "{", "JSType", "type", "=", "expr", ".", "getJSType", "(", ")", ";", "return", "withType", "(", "IR", ".", "assign", "(", "withType", "(", "IR", ".", "name", "(", "tempName", ")", ",", "type", ")", ",", "expr", ")", ",", "type", ")", ".", "srcrefTree", "(", "expr", ")", ";", "}", "else", "{", "return", "expr", ";", "}", "}" ]
Create an expression tree for an expression. <p>If the result of the expression is needed, then: <pre> ASSIGN tempName expr </pre> otherwise, simply: `expr`
[ "Create", "an", "expression", "tree", "for", "an", "expression", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExpressionDecomposer.java#L474-L481
24,789
google/closure-compiler
src/com/google/javascript/jscomp/ExpressionDecomposer.java
ExpressionDecomposer.rewriteCallExpression
private Node rewriteCallExpression(Node call, DecompositionState state) { checkArgument(call.isCall(), call); Node first = call.getFirstChild(); checkArgument(NodeUtil.isGet(first), first); // Find the type of (fn expression).call JSType fnType = first.getJSType(); JSType fnCallType = null; if (fnType != null) { fnCallType = fnType.isFunctionType() ? fnType.toMaybeFunctionType().getPropertyType("call") : unknownType; } // Extracts the expression representing the function to call. For example: // "a['b'].c" from "a['b'].c()" Node getVarNode = extractExpression(first, state.extractBeforeStatement); state.extractBeforeStatement = getVarNode; // Extracts the object reference to be used as "this". For example: // "a['b']" from "a['b'].c" Node getExprNode = getVarNode.getFirstFirstChild(); checkArgument(NodeUtil.isGet(getExprNode), getExprNode); Node thisVarNode = extractExpression(getExprNode.getFirstChild(), state.extractBeforeStatement); state.extractBeforeStatement = thisVarNode; // Rewrite the CALL expression. Node thisNameNode = thisVarNode.getFirstChild(); Node functionNameNode = getVarNode.getFirstChild(); // CALL // GETPROP // functionName // "call" // thisName // original-parameter1 // original-parameter2 // ... Node newCall = IR.call( withType( IR.getprop( functionNameNode.cloneNode(), withType(IR.string("call"), stringType)), fnCallType), thisNameNode.cloneNode()) .setJSType(call.getJSType()) .useSourceInfoIfMissingFromForTree(call); // Throw away the call name call.removeFirstChild(); if (call.hasChildren()) { // Add the call parameters to the new call. newCall.addChildrenToBack(call.removeChildren()); } call.replaceWith(newCall); return newCall; }
java
private Node rewriteCallExpression(Node call, DecompositionState state) { checkArgument(call.isCall(), call); Node first = call.getFirstChild(); checkArgument(NodeUtil.isGet(first), first); // Find the type of (fn expression).call JSType fnType = first.getJSType(); JSType fnCallType = null; if (fnType != null) { fnCallType = fnType.isFunctionType() ? fnType.toMaybeFunctionType().getPropertyType("call") : unknownType; } // Extracts the expression representing the function to call. For example: // "a['b'].c" from "a['b'].c()" Node getVarNode = extractExpression(first, state.extractBeforeStatement); state.extractBeforeStatement = getVarNode; // Extracts the object reference to be used as "this". For example: // "a['b']" from "a['b'].c" Node getExprNode = getVarNode.getFirstFirstChild(); checkArgument(NodeUtil.isGet(getExprNode), getExprNode); Node thisVarNode = extractExpression(getExprNode.getFirstChild(), state.extractBeforeStatement); state.extractBeforeStatement = thisVarNode; // Rewrite the CALL expression. Node thisNameNode = thisVarNode.getFirstChild(); Node functionNameNode = getVarNode.getFirstChild(); // CALL // GETPROP // functionName // "call" // thisName // original-parameter1 // original-parameter2 // ... Node newCall = IR.call( withType( IR.getprop( functionNameNode.cloneNode(), withType(IR.string("call"), stringType)), fnCallType), thisNameNode.cloneNode()) .setJSType(call.getJSType()) .useSourceInfoIfMissingFromForTree(call); // Throw away the call name call.removeFirstChild(); if (call.hasChildren()) { // Add the call parameters to the new call. newCall.addChildrenToBack(call.removeChildren()); } call.replaceWith(newCall); return newCall; }
[ "private", "Node", "rewriteCallExpression", "(", "Node", "call", ",", "DecompositionState", "state", ")", "{", "checkArgument", "(", "call", ".", "isCall", "(", ")", ",", "call", ")", ";", "Node", "first", "=", "call", ".", "getFirstChild", "(", ")", ";", "checkArgument", "(", "NodeUtil", ".", "isGet", "(", "first", ")", ",", "first", ")", ";", "// Find the type of (fn expression).call", "JSType", "fnType", "=", "first", ".", "getJSType", "(", ")", ";", "JSType", "fnCallType", "=", "null", ";", "if", "(", "fnType", "!=", "null", ")", "{", "fnCallType", "=", "fnType", ".", "isFunctionType", "(", ")", "?", "fnType", ".", "toMaybeFunctionType", "(", ")", ".", "getPropertyType", "(", "\"call\"", ")", ":", "unknownType", ";", "}", "// Extracts the expression representing the function to call. For example:", "// \"a['b'].c\" from \"a['b'].c()\"", "Node", "getVarNode", "=", "extractExpression", "(", "first", ",", "state", ".", "extractBeforeStatement", ")", ";", "state", ".", "extractBeforeStatement", "=", "getVarNode", ";", "// Extracts the object reference to be used as \"this\". For example:", "// \"a['b']\" from \"a['b'].c\"", "Node", "getExprNode", "=", "getVarNode", ".", "getFirstFirstChild", "(", ")", ";", "checkArgument", "(", "NodeUtil", ".", "isGet", "(", "getExprNode", ")", ",", "getExprNode", ")", ";", "Node", "thisVarNode", "=", "extractExpression", "(", "getExprNode", ".", "getFirstChild", "(", ")", ",", "state", ".", "extractBeforeStatement", ")", ";", "state", ".", "extractBeforeStatement", "=", "thisVarNode", ";", "// Rewrite the CALL expression.", "Node", "thisNameNode", "=", "thisVarNode", ".", "getFirstChild", "(", ")", ";", "Node", "functionNameNode", "=", "getVarNode", ".", "getFirstChild", "(", ")", ";", "// CALL", "// GETPROP", "// functionName", "// \"call\"", "// thisName", "// original-parameter1", "// original-parameter2", "// ...", "Node", "newCall", "=", "IR", ".", "call", "(", "withType", "(", "IR", ".", "getprop", "(", "functionNameNode", ".", "cloneNode", "(", ")", ",", "withType", "(", "IR", ".", "string", "(", "\"call\"", ")", ",", "stringType", ")", ")", ",", "fnCallType", ")", ",", "thisNameNode", ".", "cloneNode", "(", ")", ")", ".", "setJSType", "(", "call", ".", "getJSType", "(", ")", ")", ".", "useSourceInfoIfMissingFromForTree", "(", "call", ")", ";", "// Throw away the call name", "call", ".", "removeFirstChild", "(", ")", ";", "if", "(", "call", ".", "hasChildren", "(", ")", ")", "{", "// Add the call parameters to the new call.", "newCall", ".", "addChildrenToBack", "(", "call", ".", "removeChildren", "(", ")", ")", ";", "}", "call", ".", "replaceWith", "(", "newCall", ")", ";", "return", "newCall", ";", "}" ]
Rewrite the call so "this" is preserved. <pre>a.b(c);</pre> becomes: <pre> var temp1 = a; var temp0 = temp1.b; temp0.call(temp1,c); </pre> @return The replacement node.
[ "Rewrite", "the", "call", "so", "this", "is", "preserved", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExpressionDecomposer.java#L606-L666
24,790
google/closure-compiler
src/com/google/javascript/jscomp/ExpressionDecomposer.java
ExpressionDecomposer.getTempConstantValueName
private String getTempConstantValueName() { String name = tempNamePrefix + "_const" + ContextualRenamer.UNIQUE_ID_SEPARATOR + safeNameIdSupplier.get(); this.knownConstants.add(name); return name; }
java
private String getTempConstantValueName() { String name = tempNamePrefix + "_const" + ContextualRenamer.UNIQUE_ID_SEPARATOR + safeNameIdSupplier.get(); this.knownConstants.add(name); return name; }
[ "private", "String", "getTempConstantValueName", "(", ")", "{", "String", "name", "=", "tempNamePrefix", "+", "\"_const\"", "+", "ContextualRenamer", ".", "UNIQUE_ID_SEPARATOR", "+", "safeNameIdSupplier", ".", "get", "(", ")", ";", "this", ".", "knownConstants", ".", "add", "(", "name", ")", ";", "return", "name", ";", "}" ]
Create a constant unique temp name.
[ "Create", "a", "constant", "unique", "temp", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExpressionDecomposer.java#L694-L702
24,791
google/closure-compiler
src/com/google/javascript/jscomp/ExpressionDecomposer.java
ExpressionDecomposer.getEvaluationDirection
private static EvaluationDirection getEvaluationDirection(Node node) { switch (node.getToken()) { case DESTRUCTURING_LHS: case ASSIGN: case DEFAULT_VALUE: if (node.getFirstChild().isDestructuringPattern()) { // The lhs of a destructuring assignment is evaluated AFTER the rhs. This is only true for // destructuring, though, not assignments like "first().x = second()" where "first()" is // evaluated first. return EvaluationDirection.REVERSE; } // fall through default: return EvaluationDirection.FORWARD; } }
java
private static EvaluationDirection getEvaluationDirection(Node node) { switch (node.getToken()) { case DESTRUCTURING_LHS: case ASSIGN: case DEFAULT_VALUE: if (node.getFirstChild().isDestructuringPattern()) { // The lhs of a destructuring assignment is evaluated AFTER the rhs. This is only true for // destructuring, though, not assignments like "first().x = second()" where "first()" is // evaluated first. return EvaluationDirection.REVERSE; } // fall through default: return EvaluationDirection.FORWARD; } }
[ "private", "static", "EvaluationDirection", "getEvaluationDirection", "(", "Node", "node", ")", "{", "switch", "(", "node", ".", "getToken", "(", ")", ")", "{", "case", "DESTRUCTURING_LHS", ":", "case", "ASSIGN", ":", "case", "DEFAULT_VALUE", ":", "if", "(", "node", ".", "getFirstChild", "(", ")", ".", "isDestructuringPattern", "(", ")", ")", "{", "// The lhs of a destructuring assignment is evaluated AFTER the rhs. This is only true for", "// destructuring, though, not assignments like \"first().x = second()\" where \"first()\" is", "// evaluated first.", "return", "EvaluationDirection", ".", "REVERSE", ";", "}", "// fall through", "default", ":", "return", "EvaluationDirection", ".", "FORWARD", ";", "}", "}" ]
Returns the order in which the given node's children should be evaluated. <p>In most cases, this is EvaluationDirection.FORWARD because the AST order matches the actual evaluation order. A few nodes require reversed evaluation instead.
[ "Returns", "the", "order", "in", "which", "the", "given", "node", "s", "children", "should", "be", "evaluated", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExpressionDecomposer.java#L969-L984
24,792
google/closure-compiler
src/com/google/javascript/jscomp/FunctionToBlockMutator.java
FunctionToBlockMutator.mutateWithoutRenaming
Node mutateWithoutRenaming( String fnName, Node fnNode, Node callNode, String resultName, boolean needsDefaultResult, boolean isCallInLoop) { return mutateInternal( fnName, fnNode, callNode, resultName, needsDefaultResult, isCallInLoop, /* renameLocals */ false); }
java
Node mutateWithoutRenaming( String fnName, Node fnNode, Node callNode, String resultName, boolean needsDefaultResult, boolean isCallInLoop) { return mutateInternal( fnName, fnNode, callNode, resultName, needsDefaultResult, isCallInLoop, /* renameLocals */ false); }
[ "Node", "mutateWithoutRenaming", "(", "String", "fnName", ",", "Node", "fnNode", ",", "Node", "callNode", ",", "String", "resultName", ",", "boolean", "needsDefaultResult", ",", "boolean", "isCallInLoop", ")", "{", "return", "mutateInternal", "(", "fnName", ",", "fnNode", ",", "callNode", ",", "resultName", ",", "needsDefaultResult", ",", "isCallInLoop", ",", "/* renameLocals */", "false", ")", ";", "}" ]
Used where the inlining occurs into an isolated scope such as a module. Renaming is avoided since the associated JSDoc annotations are not updated. @param fnName The name to use when preparing human readable names. @param fnNode The function to prepare. @param callNode The call node that will be replaced. @param resultName Function results should be assigned to this name. @param needsDefaultResult Whether the result value must be set. @param isCallInLoop Whether the function body must be prepared to be injected into the body of a loop. @return A clone of the function body mutated to be suitable for injection as a statement into another code block.
[ "Used", "where", "the", "inlining", "occurs", "into", "an", "isolated", "scope", "such", "as", "a", "module", ".", "Renaming", "is", "avoided", "since", "the", "associated", "JSDoc", "annotations", "are", "not", "updated", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionToBlockMutator.java#L87-L102
24,793
google/closure-compiler
src/com/google/javascript/jscomp/FunctionToBlockMutator.java
FunctionToBlockMutator.fixUninitializedVarDeclarations
private static void fixUninitializedVarDeclarations(Node n, Node containingBlock) { // Inner loop structure must already have logic to initialize its // variables. In particular FOR-IN structures must not be modified. if (NodeUtil.isLoopStructure(n)) { return; } if ((n.isVar() || n.isLet()) && n.hasOneChild()) { Node name = n.getFirstChild(); // It isn't initialized. if (!name.hasChildren()) { Node srcLocation = name; name.addChildToBack(NodeUtil.newUndefinedNode(srcLocation)); containingBlock.addChildToFront(n.detach()); } return; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { fixUninitializedVarDeclarations(c, containingBlock); } }
java
private static void fixUninitializedVarDeclarations(Node n, Node containingBlock) { // Inner loop structure must already have logic to initialize its // variables. In particular FOR-IN structures must not be modified. if (NodeUtil.isLoopStructure(n)) { return; } if ((n.isVar() || n.isLet()) && n.hasOneChild()) { Node name = n.getFirstChild(); // It isn't initialized. if (!name.hasChildren()) { Node srcLocation = name; name.addChildToBack(NodeUtil.newUndefinedNode(srcLocation)); containingBlock.addChildToFront(n.detach()); } return; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { fixUninitializedVarDeclarations(c, containingBlock); } }
[ "private", "static", "void", "fixUninitializedVarDeclarations", "(", "Node", "n", ",", "Node", "containingBlock", ")", "{", "// Inner loop structure must already have logic to initialize its", "// variables. In particular FOR-IN structures must not be modified.", "if", "(", "NodeUtil", ".", "isLoopStructure", "(", "n", ")", ")", "{", "return", ";", "}", "if", "(", "(", "n", ".", "isVar", "(", ")", "||", "n", ".", "isLet", "(", ")", ")", "&&", "n", ".", "hasOneChild", "(", ")", ")", "{", "Node", "name", "=", "n", ".", "getFirstChild", "(", ")", ";", "// It isn't initialized.", "if", "(", "!", "name", ".", "hasChildren", "(", ")", ")", "{", "Node", "srcLocation", "=", "name", ";", "name", ".", "addChildToBack", "(", "NodeUtil", ".", "newUndefinedNode", "(", "srcLocation", ")", ")", ";", "containingBlock", ".", "addChildToFront", "(", "n", ".", "detach", "(", ")", ")", ";", "}", "return", ";", "}", "for", "(", "Node", "c", "=", "n", ".", "getFirstChild", "(", ")", ";", "c", "!=", "null", ";", "c", "=", "c", ".", "getNext", "(", ")", ")", "{", "fixUninitializedVarDeclarations", "(", "c", ",", "containingBlock", ")", ";", "}", "}" ]
For all VAR node with uninitialized declarations, set the values to be "undefined".
[ "For", "all", "VAR", "node", "with", "uninitialized", "declarations", "set", "the", "values", "to", "be", "undefined", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionToBlockMutator.java#L228-L249
24,794
google/closure-compiler
src/com/google/javascript/jscomp/FunctionToBlockMutator.java
FunctionToBlockMutator.makeLocalNamesUnique
private void makeLocalNamesUnique(Node fnNode, boolean isCallInLoop) { Supplier<String> idSupplier = compiler.getUniqueNameIdSupplier(); // Make variable names unique to this instance. NodeTraversal.traverseScopeRoots( compiler, null, ImmutableList.of(fnNode), new MakeDeclaredNamesUnique( new InlineRenamer( compiler.getCodingConvention(), idSupplier, "inline_", isCallInLoop, true, null), false), true); // Make label names unique to this instance. new RenameLabels(compiler, new LabelNameSupplier(idSupplier), false, false) .process(null, fnNode); }
java
private void makeLocalNamesUnique(Node fnNode, boolean isCallInLoop) { Supplier<String> idSupplier = compiler.getUniqueNameIdSupplier(); // Make variable names unique to this instance. NodeTraversal.traverseScopeRoots( compiler, null, ImmutableList.of(fnNode), new MakeDeclaredNamesUnique( new InlineRenamer( compiler.getCodingConvention(), idSupplier, "inline_", isCallInLoop, true, null), false), true); // Make label names unique to this instance. new RenameLabels(compiler, new LabelNameSupplier(idSupplier), false, false) .process(null, fnNode); }
[ "private", "void", "makeLocalNamesUnique", "(", "Node", "fnNode", ",", "boolean", "isCallInLoop", ")", "{", "Supplier", "<", "String", ">", "idSupplier", "=", "compiler", ".", "getUniqueNameIdSupplier", "(", ")", ";", "// Make variable names unique to this instance.", "NodeTraversal", ".", "traverseScopeRoots", "(", "compiler", ",", "null", ",", "ImmutableList", ".", "of", "(", "fnNode", ")", ",", "new", "MakeDeclaredNamesUnique", "(", "new", "InlineRenamer", "(", "compiler", ".", "getCodingConvention", "(", ")", ",", "idSupplier", ",", "\"inline_\"", ",", "isCallInLoop", ",", "true", ",", "null", ")", ",", "false", ")", ",", "true", ")", ";", "// Make label names unique to this instance.", "new", "RenameLabels", "(", "compiler", ",", "new", "LabelNameSupplier", "(", "idSupplier", ")", ",", "false", ",", "false", ")", ".", "process", "(", "null", ",", "fnNode", ")", ";", "}" ]
Fix-up all local names to be unique for this subtree. @param fnNode A mutable instance of the function to be inlined.
[ "Fix", "-", "up", "all", "local", "names", "to", "be", "unique", "for", "this", "subtree", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionToBlockMutator.java#L255-L270
24,795
google/closure-compiler
src/com/google/javascript/jscomp/FunctionToBlockMutator.java
FunctionToBlockMutator.getLabelNameForFunction
private String getLabelNameForFunction(String fnName) { String name = (isNullOrEmpty(fnName)) ? "anon" : fnName; return "JSCompiler_inline_label_" + name + "_" + safeNameIdSupplier.get(); }
java
private String getLabelNameForFunction(String fnName) { String name = (isNullOrEmpty(fnName)) ? "anon" : fnName; return "JSCompiler_inline_label_" + name + "_" + safeNameIdSupplier.get(); }
[ "private", "String", "getLabelNameForFunction", "(", "String", "fnName", ")", "{", "String", "name", "=", "(", "isNullOrEmpty", "(", "fnName", ")", ")", "?", "\"anon\"", ":", "fnName", ";", "return", "\"JSCompiler_inline_label_\"", "+", "name", "+", "\"_\"", "+", "safeNameIdSupplier", ".", "get", "(", ")", ";", "}" ]
Create a unique label name.
[ "Create", "a", "unique", "label", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionToBlockMutator.java#L288-L291
24,796
google/closure-compiler
src/com/google/javascript/jscomp/FunctionToBlockMutator.java
FunctionToBlockMutator.aliasAndInlineArguments
private Node aliasAndInlineArguments( Node fnTemplateRoot, ImmutableMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, argMap); checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = new HashMap<>(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = new ArrayList<>(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { if (name.equals(THIS_MARKER)) { boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot); // Update "this", this is only necessary if "this" is referenced // and the value of "this" is not Token.THIS, or the value of "this" // has side effects. Node value = entry.getValue(); if (!value.isThis() && (referencesThis || NodeUtil.mayHaveSideEffects(value, compiler))) { String newName = getUniqueThisName(); Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(newName, newValue) .useSourceInfoIfMissingFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.put(THIS_MARKER, IR.name(newName) .srcrefTree(newValue)); } } else { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .useSourceInfoIfMissingFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, newArgMap); checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } }
java
private Node aliasAndInlineArguments( Node fnTemplateRoot, ImmutableMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, argMap); checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = new HashMap<>(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = new ArrayList<>(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { if (name.equals(THIS_MARKER)) { boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot); // Update "this", this is only necessary if "this" is referenced // and the value of "this" is not Token.THIS, or the value of "this" // has side effects. Node value = entry.getValue(); if (!value.isThis() && (referencesThis || NodeUtil.mayHaveSideEffects(value, compiler))) { String newName = getUniqueThisName(); Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(newName, newValue) .useSourceInfoIfMissingFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.put(THIS_MARKER, IR.name(newName) .srcrefTree(newValue)); } } else { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .useSourceInfoIfMissingFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, newArgMap); checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } }
[ "private", "Node", "aliasAndInlineArguments", "(", "Node", "fnTemplateRoot", ",", "ImmutableMap", "<", "String", ",", "Node", ">", "argMap", ",", "Set", "<", "String", ">", "namesToAlias", ")", "{", "if", "(", "namesToAlias", "==", "null", "||", "namesToAlias", ".", "isEmpty", "(", ")", ")", "{", "// There are no names to alias, just inline the arguments directly.", "Node", "result", "=", "FunctionArgumentInjector", ".", "inject", "(", "compiler", ",", "fnTemplateRoot", ",", "null", ",", "argMap", ")", ";", "checkState", "(", "result", "==", "fnTemplateRoot", ")", ";", "return", "result", ";", "}", "else", "{", "// Create local alias of names that can not be safely", "// used directly.", "// An arg map that will be updated to contain the", "// safe aliases.", "Map", "<", "String", ",", "Node", ">", "newArgMap", "=", "new", "HashMap", "<>", "(", "argMap", ")", ";", "// Declare the alias in the same order as they", "// are declared.", "List", "<", "Node", ">", "newVars", "=", "new", "ArrayList", "<>", "(", ")", ";", "// NOTE: argMap is a linked map so we get the parameters in the", "// order that they were declared.", "for", "(", "Entry", "<", "String", ",", "Node", ">", "entry", ":", "argMap", ".", "entrySet", "(", ")", ")", "{", "String", "name", "=", "entry", ".", "getKey", "(", ")", ";", "if", "(", "namesToAlias", ".", "contains", "(", "name", ")", ")", "{", "if", "(", "name", ".", "equals", "(", "THIS_MARKER", ")", ")", "{", "boolean", "referencesThis", "=", "NodeUtil", ".", "referencesThis", "(", "fnTemplateRoot", ")", ";", "// Update \"this\", this is only necessary if \"this\" is referenced", "// and the value of \"this\" is not Token.THIS, or the value of \"this\"", "// has side effects.", "Node", "value", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "!", "value", ".", "isThis", "(", ")", "&&", "(", "referencesThis", "||", "NodeUtil", ".", "mayHaveSideEffects", "(", "value", ",", "compiler", ")", ")", ")", "{", "String", "newName", "=", "getUniqueThisName", "(", ")", ";", "Node", "newValue", "=", "entry", ".", "getValue", "(", ")", ".", "cloneTree", "(", ")", ";", "Node", "newNode", "=", "NodeUtil", ".", "newVarNode", "(", "newName", ",", "newValue", ")", ".", "useSourceInfoIfMissingFromForTree", "(", "newValue", ")", ";", "newVars", ".", "add", "(", "0", ",", "newNode", ")", ";", "// Remove the parameter from the list to replace.", "newArgMap", ".", "put", "(", "THIS_MARKER", ",", "IR", ".", "name", "(", "newName", ")", ".", "srcrefTree", "(", "newValue", ")", ")", ";", "}", "}", "else", "{", "Node", "newValue", "=", "entry", ".", "getValue", "(", ")", ".", "cloneTree", "(", ")", ";", "Node", "newNode", "=", "NodeUtil", ".", "newVarNode", "(", "name", ",", "newValue", ")", ".", "useSourceInfoIfMissingFromForTree", "(", "newValue", ")", ";", "newVars", ".", "add", "(", "0", ",", "newNode", ")", ";", "// Remove the parameter from the list to replace.", "newArgMap", ".", "remove", "(", "name", ")", ";", "}", "}", "}", "// Inline the arguments.", "Node", "result", "=", "FunctionArgumentInjector", ".", "inject", "(", "compiler", ",", "fnTemplateRoot", ",", "null", ",", "newArgMap", ")", ";", "checkState", "(", "result", "==", "fnTemplateRoot", ")", ";", "// Now that the names have been replaced, add the new aliases for", "// the old names.", "for", "(", "Node", "n", ":", "newVars", ")", "{", "fnTemplateRoot", ".", "addChildToFront", "(", "n", ")", ";", "}", "return", "result", ";", "}", "}" ]
Inlines the arguments within the node tree using the given argument map, replaces "unsafe" names with local aliases. The aliases for unsafe require new VAR declarations, so this function can not be used in for direct CALL node replacement as VAR nodes can not be created there. @return The node or its replacement.
[ "Inlines", "the", "arguments", "within", "the", "node", "tree", "using", "the", "given", "argument", "map", "replaces", "unsafe", "names", "with", "local", "aliases", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionToBlockMutator.java#L310-L379
24,797
google/closure-compiler
src/com/google/javascript/jscomp/FunctionToBlockMutator.java
FunctionToBlockMutator.createAssignStatementNode
private static Node createAssignStatementNode(String name, Node expression) { // Create 'name = result-expression;' statement. // EXPR (ASSIGN (NAME, EXPRESSION)) Node nameNode = IR.name(name); Node assign = IR.assign(nameNode, expression); return NodeUtil.newExpr(assign); }
java
private static Node createAssignStatementNode(String name, Node expression) { // Create 'name = result-expression;' statement. // EXPR (ASSIGN (NAME, EXPRESSION)) Node nameNode = IR.name(name); Node assign = IR.assign(nameNode, expression); return NodeUtil.newExpr(assign); }
[ "private", "static", "Node", "createAssignStatementNode", "(", "String", "name", ",", "Node", "expression", ")", "{", "// Create 'name = result-expression;' statement.", "// EXPR (ASSIGN (NAME, EXPRESSION))", "Node", "nameNode", "=", "IR", ".", "name", "(", "name", ")", ";", "Node", "assign", "=", "IR", ".", "assign", "(", "nameNode", ",", "expression", ")", ";", "return", "NodeUtil", ".", "newExpr", "(", "assign", ")", ";", "}" ]
Create a valid statement Node containing an assignment to name of the given expression.
[ "Create", "a", "valid", "statement", "Node", "containing", "an", "assignment", "to", "name", "of", "the", "given", "expression", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionToBlockMutator.java#L496-L502
24,798
google/closure-compiler
src/com/google/javascript/jscomp/JSModuleGraph.java
JSModuleGraph.makeWeakModule
private List<JSModule> makeWeakModule(List<JSModule> modulesInDepOrder) { boolean hasWeakModule = false; for (JSModule module : modulesInDepOrder) { if (module.getName().equals(JSModule.WEAK_MODULE_NAME)) { hasWeakModule = true; Set<JSModule> allOtherModules = new HashSet<>(modulesInDepOrder); allOtherModules.remove(module); checkState( module.getAllDependencies().containsAll(allOtherModules), "A weak module already exists but it does not depend on every other module."); checkState( module.getAllDependencies().size() == allOtherModules.size(), "The weak module cannot have extra dependencies."); break; } } if (hasWeakModule) { // All weak files (and only weak files) should be in the weak module. for (JSModule module : modulesInDepOrder) { for (CompilerInput input : module.getInputs()) { if (module.getName().equals(JSModule.WEAK_MODULE_NAME)) { checkState( input.getSourceFile().isWeak(), "A weak module already exists but strong sources were found in it."); } else { checkState( !input.getSourceFile().isWeak(), "A weak module already exists but weak sources were found in other modules."); } } } } else { JSModule weakModule = new JSModule(JSModule.WEAK_MODULE_NAME); for (JSModule module : modulesInDepOrder) { weakModule.addDependency(module); } modulesInDepOrder = new ArrayList<>(modulesInDepOrder); modulesInDepOrder.add(weakModule); } return modulesInDepOrder; }
java
private List<JSModule> makeWeakModule(List<JSModule> modulesInDepOrder) { boolean hasWeakModule = false; for (JSModule module : modulesInDepOrder) { if (module.getName().equals(JSModule.WEAK_MODULE_NAME)) { hasWeakModule = true; Set<JSModule> allOtherModules = new HashSet<>(modulesInDepOrder); allOtherModules.remove(module); checkState( module.getAllDependencies().containsAll(allOtherModules), "A weak module already exists but it does not depend on every other module."); checkState( module.getAllDependencies().size() == allOtherModules.size(), "The weak module cannot have extra dependencies."); break; } } if (hasWeakModule) { // All weak files (and only weak files) should be in the weak module. for (JSModule module : modulesInDepOrder) { for (CompilerInput input : module.getInputs()) { if (module.getName().equals(JSModule.WEAK_MODULE_NAME)) { checkState( input.getSourceFile().isWeak(), "A weak module already exists but strong sources were found in it."); } else { checkState( !input.getSourceFile().isWeak(), "A weak module already exists but weak sources were found in other modules."); } } } } else { JSModule weakModule = new JSModule(JSModule.WEAK_MODULE_NAME); for (JSModule module : modulesInDepOrder) { weakModule.addDependency(module); } modulesInDepOrder = new ArrayList<>(modulesInDepOrder); modulesInDepOrder.add(weakModule); } return modulesInDepOrder; }
[ "private", "List", "<", "JSModule", ">", "makeWeakModule", "(", "List", "<", "JSModule", ">", "modulesInDepOrder", ")", "{", "boolean", "hasWeakModule", "=", "false", ";", "for", "(", "JSModule", "module", ":", "modulesInDepOrder", ")", "{", "if", "(", "module", ".", "getName", "(", ")", ".", "equals", "(", "JSModule", ".", "WEAK_MODULE_NAME", ")", ")", "{", "hasWeakModule", "=", "true", ";", "Set", "<", "JSModule", ">", "allOtherModules", "=", "new", "HashSet", "<>", "(", "modulesInDepOrder", ")", ";", "allOtherModules", ".", "remove", "(", "module", ")", ";", "checkState", "(", "module", ".", "getAllDependencies", "(", ")", ".", "containsAll", "(", "allOtherModules", ")", ",", "\"A weak module already exists but it does not depend on every other module.\"", ")", ";", "checkState", "(", "module", ".", "getAllDependencies", "(", ")", ".", "size", "(", ")", "==", "allOtherModules", ".", "size", "(", ")", ",", "\"The weak module cannot have extra dependencies.\"", ")", ";", "break", ";", "}", "}", "if", "(", "hasWeakModule", ")", "{", "// All weak files (and only weak files) should be in the weak module.", "for", "(", "JSModule", "module", ":", "modulesInDepOrder", ")", "{", "for", "(", "CompilerInput", "input", ":", "module", ".", "getInputs", "(", ")", ")", "{", "if", "(", "module", ".", "getName", "(", ")", ".", "equals", "(", "JSModule", ".", "WEAK_MODULE_NAME", ")", ")", "{", "checkState", "(", "input", ".", "getSourceFile", "(", ")", ".", "isWeak", "(", ")", ",", "\"A weak module already exists but strong sources were found in it.\"", ")", ";", "}", "else", "{", "checkState", "(", "!", "input", ".", "getSourceFile", "(", ")", ".", "isWeak", "(", ")", ",", "\"A weak module already exists but weak sources were found in other modules.\"", ")", ";", "}", "}", "}", "}", "else", "{", "JSModule", "weakModule", "=", "new", "JSModule", "(", "JSModule", ".", "WEAK_MODULE_NAME", ")", ";", "for", "(", "JSModule", "module", ":", "modulesInDepOrder", ")", "{", "weakModule", ".", "addDependency", "(", "module", ")", ";", "}", "modulesInDepOrder", "=", "new", "ArrayList", "<>", "(", "modulesInDepOrder", ")", ";", "modulesInDepOrder", ".", "add", "(", "weakModule", ")", ";", "}", "return", "modulesInDepOrder", ";", "}" ]
If a weak module doesn't already exist, creates a weak module depending on every other module. <p>Does not move any sources into the weak module. @return a new list of modules that includes the weak module, if it was newly created, or the same list if the weak module already existed @throws IllegalStateException if a weak module already exists but doesn't fulfill the above conditions
[ "If", "a", "weak", "module", "doesn", "t", "already", "exist", "creates", "a", "weak", "module", "depending", "on", "every", "other", "module", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JSModuleGraph.java#L164-L204
24,799
google/closure-compiler
src/com/google/javascript/jscomp/JSModuleGraph.java
JSModuleGraph.getAllInputs
Iterable<CompilerInput> getAllInputs() { return Iterables.concat(Iterables.transform(Arrays.asList(modules), JSModule::getInputs)); }
java
Iterable<CompilerInput> getAllInputs() { return Iterables.concat(Iterables.transform(Arrays.asList(modules), JSModule::getInputs)); }
[ "Iterable", "<", "CompilerInput", ">", "getAllInputs", "(", ")", "{", "return", "Iterables", ".", "concat", "(", "Iterables", ".", "transform", "(", "Arrays", ".", "asList", "(", "modules", ")", ",", "JSModule", "::", "getInputs", ")", ")", ";", "}" ]
Gets an iterable over all input source files in dependency order.
[ "Gets", "an", "iterable", "over", "all", "input", "source", "files", "in", "dependency", "order", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JSModuleGraph.java#L239-L241