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,400
google/closure-compiler
src/com/google/javascript/jscomp/DisambiguateProperties.java
DisambiguateProperties.recordInterfaces
private void recordInterfaces(FunctionType constructor, JSType relatedType, Property p) { Iterable<ObjectType> interfaces = ancestorInterfaces.get(constructor); if (interfaces == null) { interfaces = constructor.getAncestorInterfaces(); ancestorInterfaces.put(constructor, interfaces); } for (ObjectType itype : interfaces) { JSType top = getTypeWithProperty(p.name, itype); if (top != null) { p.addType(itype, relatedType); } // If this interface invalidated this property, return now. if (p.skipRenaming) { return; } } }
java
private void recordInterfaces(FunctionType constructor, JSType relatedType, Property p) { Iterable<ObjectType> interfaces = ancestorInterfaces.get(constructor); if (interfaces == null) { interfaces = constructor.getAncestorInterfaces(); ancestorInterfaces.put(constructor, interfaces); } for (ObjectType itype : interfaces) { JSType top = getTypeWithProperty(p.name, itype); if (top != null) { p.addType(itype, relatedType); } // If this interface invalidated this property, return now. if (p.skipRenaming) { return; } } }
[ "private", "void", "recordInterfaces", "(", "FunctionType", "constructor", ",", "JSType", "relatedType", ",", "Property", "p", ")", "{", "Iterable", "<", "ObjectType", ">", "interfaces", "=", "ancestorInterfaces", ".", "get", "(", "constructor", ")", ";", "if", "(", "interfaces", "==", "null", ")", "{", "interfaces", "=", "constructor", ".", "getAncestorInterfaces", "(", ")", ";", "ancestorInterfaces", ".", "put", "(", "constructor", ",", "interfaces", ")", ";", "}", "for", "(", "ObjectType", "itype", ":", "interfaces", ")", "{", "JSType", "top", "=", "getTypeWithProperty", "(", "p", ".", "name", ",", "itype", ")", ";", "if", "(", "top", "!=", "null", ")", "{", "p", ".", "addType", "(", "itype", ",", "relatedType", ")", ";", "}", "// If this interface invalidated this property, return now.", "if", "(", "p", ".", "skipRenaming", ")", "{", "return", ";", "}", "}", "}" ]
Records that this property could be referenced from any interface that this type inherits from. <p>If the property p is defined only on a subtype of constructor, then this method has no effect. But we tried modifying getTypeWithProperty to tell us when the returned type is a subtype, and then skip those calls to recordInterface, and there was no speed-up. And it made the code harder to understand, so we don't do it.
[ "Records", "that", "this", "property", "could", "be", "referenced", "from", "any", "interface", "that", "this", "type", "inherits", "from", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DisambiguateProperties.java#L1099-L1115
24,401
google/closure-compiler
src/com/google/javascript/jscomp/PureFunctionIdentifier.java
PureFunctionIdentifier.populateFunctionDefinitions
private void populateFunctionDefinitions(String name, List<Node> references) { AmbiguatedFunctionSummary summaryForName = checkNotNull(summariesByName.get(name)); // Make sure we get absolutely every R-value assigned to `name` or at the very least detect // there are some we're missing. Overlooking a single R-value would invalidate the analysis. List<ImmutableList<Node>> rvaluesAssignedToName = references.stream() // Eliminate any references that we're sure are R-values themselves. Otherwise // there's a high probability we'll inspect an R-value for futher R-values. We wouldn't // find any, and then we'd have to consider `name` impure. .filter((n) -> !isDefinitelyRValue(n)) // For anything that might be an L-reference, get the expression being assigned to it. .map(NodeUtil::getRValueOfLValue) // If the assigned R-value is an analyzable expression, collect all the possible // FUNCTIONs that could result from that expression. If the expression isn't analyzable, // represent that with `null` so we can blacklist `name`. .map((n) -> (n == null) ? null : collectCallableLeaves(n)) .collect(toList()); if (rvaluesAssignedToName.isEmpty() || rvaluesAssignedToName.contains(null)) { // Any of: // - There are no L-values with this name. // - There's a an L-value and we can't find the associated R-values. // - There's a an L-value with R-values are not all known to be callable. summaryForName.setAllFlags(); } else { rvaluesAssignedToName.stream() .flatMap(List::stream) .forEach( (rvalue) -> { if (rvalue.isFunction()) { summariesForAllNamesOfFunctionByNode.put(rvalue, summaryForName); } else { String rvalueName = nameForReference(rvalue); AmbiguatedFunctionSummary rvalueSummary = summariesByName.getOrDefault(rvalueName, unknownFunctionSummary); reverseCallGraph.connect( rvalueSummary.graphNode, SideEffectPropagation.forAlias(), summaryForName.graphNode); } }); }
java
private void populateFunctionDefinitions(String name, List<Node> references) { AmbiguatedFunctionSummary summaryForName = checkNotNull(summariesByName.get(name)); // Make sure we get absolutely every R-value assigned to `name` or at the very least detect // there are some we're missing. Overlooking a single R-value would invalidate the analysis. List<ImmutableList<Node>> rvaluesAssignedToName = references.stream() // Eliminate any references that we're sure are R-values themselves. Otherwise // there's a high probability we'll inspect an R-value for futher R-values. We wouldn't // find any, and then we'd have to consider `name` impure. .filter((n) -> !isDefinitelyRValue(n)) // For anything that might be an L-reference, get the expression being assigned to it. .map(NodeUtil::getRValueOfLValue) // If the assigned R-value is an analyzable expression, collect all the possible // FUNCTIONs that could result from that expression. If the expression isn't analyzable, // represent that with `null` so we can blacklist `name`. .map((n) -> (n == null) ? null : collectCallableLeaves(n)) .collect(toList()); if (rvaluesAssignedToName.isEmpty() || rvaluesAssignedToName.contains(null)) { // Any of: // - There are no L-values with this name. // - There's a an L-value and we can't find the associated R-values. // - There's a an L-value with R-values are not all known to be callable. summaryForName.setAllFlags(); } else { rvaluesAssignedToName.stream() .flatMap(List::stream) .forEach( (rvalue) -> { if (rvalue.isFunction()) { summariesForAllNamesOfFunctionByNode.put(rvalue, summaryForName); } else { String rvalueName = nameForReference(rvalue); AmbiguatedFunctionSummary rvalueSummary = summariesByName.getOrDefault(rvalueName, unknownFunctionSummary); reverseCallGraph.connect( rvalueSummary.graphNode, SideEffectPropagation.forAlias(), summaryForName.graphNode); } }); }
[ "private", "void", "populateFunctionDefinitions", "(", "String", "name", ",", "List", "<", "Node", ">", "references", ")", "{", "AmbiguatedFunctionSummary", "summaryForName", "=", "checkNotNull", "(", "summariesByName", ".", "get", "(", "name", ")", ")", ";", "// Make sure we get absolutely every R-value assigned to `name` or at the very least detect", "// there are some we're missing. Overlooking a single R-value would invalidate the analysis.", "List", "<", "ImmutableList", "<", "Node", ">", ">", "rvaluesAssignedToName", "=", "references", ".", "stream", "(", ")", "// Eliminate any references that we're sure are R-values themselves. Otherwise", "// there's a high probability we'll inspect an R-value for futher R-values. We wouldn't", "// find any, and then we'd have to consider `name` impure.", ".", "filter", "(", "(", "n", ")", "-", ">", "!", "isDefinitelyRValue", "(", "n", ")", ")", "// For anything that might be an L-reference, get the expression being assigned to it.", ".", "map", "(", "NodeUtil", "::", "getRValueOfLValue", ")", "// If the assigned R-value is an analyzable expression, collect all the possible", "// FUNCTIONs that could result from that expression. If the expression isn't analyzable,", "// represent that with `null` so we can blacklist `name`.", ".", "map", "(", "(", "n", ")", "-", ">", "(", "n", "==", "null", ")", "?", "null", ":", "collectCallableLeaves", "(", "n", ")", ")", ".", "collect", "(", "toList", "(", ")", ")", ";", "if", "(", "rvaluesAssignedToName", ".", "isEmpty", "(", ")", "||", "rvaluesAssignedToName", ".", "contains", "(", "null", ")", ")", "{", "// Any of:", "// - There are no L-values with this name.", "// - There's a an L-value and we can't find the associated R-values.", "// - There's a an L-value with R-values are not all known to be callable.", "summaryForName", ".", "setAllFlags", "(", ")", ";", "}", "else", "{", "rvaluesAssignedToName", ".", "stream", "(", ")", ".", "flatMap", "(", "List", "::", "stream", ")", ".", "forEach", "(", "(", "rvalue", ")", "-", ">", "{", "if", "(", "rvalue", ".", "isFunction", "(", ")", ")", "{", "summariesForAllNamesOfFunctionByNode", ".", "put", "(", "rvalue", ",", "summaryForName", ")", ";", "}", "else", "", "{", "String", "rvalueName", "=", "nameForReference", "(", "rvalue", ")", ";", "AmbiguatedFunctionSummary", "rvalueSummary", "=", "summariesByName", ".", "getOrDefault", "(", "rvalueName", ",", "unknownFunctionSummary", ")", ";", "reverseCallGraph", ".", "connect", "(", "rvalueSummary", ".", "graphNode", ",", "SideEffectPropagation", ".", "forAlias", "(", ")", ",", "summaryForName", ".", "graphNode", ")", ";", "}", "}", ")", ";", "}" ]
For a name and its set of references, record the set of functions that may define that name or blacklist the name if there are unclear definitions. @param name A variable or property name, @param references The set of all nodes representing R- and L-value references to {@code name}.
[ "For", "a", "name", "and", "its", "set", "of", "references", "record", "the", "set", "of", "functions", "that", "may", "define", "that", "name", "or", "blacklist", "the", "name", "if", "there", "are", "unclear", "definitions", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PureFunctionIdentifier.java#L417-L460
24,402
google/closure-compiler
src/com/google/javascript/jscomp/PureFunctionIdentifier.java
ExternFunctionAnnotationAnalyzer.updateSideEffectsForExternFunction
private void updateSideEffectsForExternFunction( Node externFunction, AmbiguatedFunctionSummary summary) { checkArgument(externFunction.isFunction()); checkArgument(externFunction.isFromExterns()); JSDocInfo info = NodeUtil.getBestJSDocInfo(externFunction); // Handle externs. JSType typei = externFunction.getJSType(); FunctionType functionType = typei == null ? null : typei.toMaybeFunctionType(); if (functionType == null) { // Assume extern functions return tainted values when we have no type info to say otherwise. summary.setEscapedReturn(); } else { JSType retType = functionType.getReturnType(); if (!isLocalValueType(retType, compiler)) { summary.setEscapedReturn(); } } if (info == null) { // We don't know anything about this function so we assume it has side effects. summary.setMutatesGlobalState(); summary.setFunctionThrows(); } else { if (info.modifiesThis()) { summary.setMutatesThis(); } else if (info.hasSideEffectsArgumentsAnnotation()) { summary.setMutatesArguments(); } else if (!info.getThrownTypes().isEmpty()) { summary.setFunctionThrows(); } else if (info.isNoSideEffects()) { // Do nothing. } else { summary.setMutatesGlobalState(); } } }
java
private void updateSideEffectsForExternFunction( Node externFunction, AmbiguatedFunctionSummary summary) { checkArgument(externFunction.isFunction()); checkArgument(externFunction.isFromExterns()); JSDocInfo info = NodeUtil.getBestJSDocInfo(externFunction); // Handle externs. JSType typei = externFunction.getJSType(); FunctionType functionType = typei == null ? null : typei.toMaybeFunctionType(); if (functionType == null) { // Assume extern functions return tainted values when we have no type info to say otherwise. summary.setEscapedReturn(); } else { JSType retType = functionType.getReturnType(); if (!isLocalValueType(retType, compiler)) { summary.setEscapedReturn(); } } if (info == null) { // We don't know anything about this function so we assume it has side effects. summary.setMutatesGlobalState(); summary.setFunctionThrows(); } else { if (info.modifiesThis()) { summary.setMutatesThis(); } else if (info.hasSideEffectsArgumentsAnnotation()) { summary.setMutatesArguments(); } else if (!info.getThrownTypes().isEmpty()) { summary.setFunctionThrows(); } else if (info.isNoSideEffects()) { // Do nothing. } else { summary.setMutatesGlobalState(); } } }
[ "private", "void", "updateSideEffectsForExternFunction", "(", "Node", "externFunction", ",", "AmbiguatedFunctionSummary", "summary", ")", "{", "checkArgument", "(", "externFunction", ".", "isFunction", "(", ")", ")", ";", "checkArgument", "(", "externFunction", ".", "isFromExterns", "(", ")", ")", ";", "JSDocInfo", "info", "=", "NodeUtil", ".", "getBestJSDocInfo", "(", "externFunction", ")", ";", "// Handle externs.", "JSType", "typei", "=", "externFunction", ".", "getJSType", "(", ")", ";", "FunctionType", "functionType", "=", "typei", "==", "null", "?", "null", ":", "typei", ".", "toMaybeFunctionType", "(", ")", ";", "if", "(", "functionType", "==", "null", ")", "{", "// Assume extern functions return tainted values when we have no type info to say otherwise.", "summary", ".", "setEscapedReturn", "(", ")", ";", "}", "else", "{", "JSType", "retType", "=", "functionType", ".", "getReturnType", "(", ")", ";", "if", "(", "!", "isLocalValueType", "(", "retType", ",", "compiler", ")", ")", "{", "summary", ".", "setEscapedReturn", "(", ")", ";", "}", "}", "if", "(", "info", "==", "null", ")", "{", "// We don't know anything about this function so we assume it has side effects.", "summary", ".", "setMutatesGlobalState", "(", ")", ";", "summary", ".", "setFunctionThrows", "(", ")", ";", "}", "else", "{", "if", "(", "info", ".", "modifiesThis", "(", ")", ")", "{", "summary", ".", "setMutatesThis", "(", ")", ";", "}", "else", "if", "(", "info", ".", "hasSideEffectsArgumentsAnnotation", "(", ")", ")", "{", "summary", ".", "setMutatesArguments", "(", ")", ";", "}", "else", "if", "(", "!", "info", ".", "getThrownTypes", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "summary", ".", "setFunctionThrows", "(", ")", ";", "}", "else", "if", "(", "info", ".", "isNoSideEffects", "(", ")", ")", "{", "// Do nothing.", "}", "else", "{", "summary", ".", "setMutatesGlobalState", "(", ")", ";", "}", "}", "}" ]
Update function for @nosideeffects annotations.
[ "Update", "function", "for" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PureFunctionIdentifier.java#L569-L605
24,403
google/closure-compiler
src/com/google/javascript/jscomp/PureFunctionIdentifier.java
FunctionBodyAnalyzer.visitLhsNodes
private void visitLhsNodes( AmbiguatedFunctionSummary sideEffectInfo, Scope scope, Node enclosingFunction, List<Node> lhsNodes, Predicate<Node> hasLocalRhs) { for (Node lhs : lhsNodes) { if (NodeUtil.isGet(lhs)) { if (lhs.getFirstChild().isThis()) { sideEffectInfo.setMutatesThis(); } else { Node objectNode = lhs.getFirstChild(); if (objectNode.isName()) { Var var = scope.getVar(objectNode.getString()); if (isVarDeclaredInSameContainerScope(var, scope)) { // Maybe a local object modification. We won't know for sure until // we exit the scope and can validate the value of the local. taintedVarsByFunction.put(enclosingFunction, var); } else { sideEffectInfo.setMutatesGlobalState(); } } else { // Don't track multi level locals: local.prop.prop2++; sideEffectInfo.setMutatesGlobalState(); } } } else { checkState(lhs.isName(), lhs); Var var = scope.getVar(lhs.getString()); if (isVarDeclaredInSameContainerScope(var, scope)) { if (!hasLocalRhs.test(lhs)) { // Assigned value is not guaranteed to be a local value, // so if we see any property assignments on this variable, // they could be tainting a non-local value. blacklistedVarsByFunction.put(enclosingFunction, var); } } else { sideEffectInfo.setMutatesGlobalState(); } } } }
java
private void visitLhsNodes( AmbiguatedFunctionSummary sideEffectInfo, Scope scope, Node enclosingFunction, List<Node> lhsNodes, Predicate<Node> hasLocalRhs) { for (Node lhs : lhsNodes) { if (NodeUtil.isGet(lhs)) { if (lhs.getFirstChild().isThis()) { sideEffectInfo.setMutatesThis(); } else { Node objectNode = lhs.getFirstChild(); if (objectNode.isName()) { Var var = scope.getVar(objectNode.getString()); if (isVarDeclaredInSameContainerScope(var, scope)) { // Maybe a local object modification. We won't know for sure until // we exit the scope and can validate the value of the local. taintedVarsByFunction.put(enclosingFunction, var); } else { sideEffectInfo.setMutatesGlobalState(); } } else { // Don't track multi level locals: local.prop.prop2++; sideEffectInfo.setMutatesGlobalState(); } } } else { checkState(lhs.isName(), lhs); Var var = scope.getVar(lhs.getString()); if (isVarDeclaredInSameContainerScope(var, scope)) { if (!hasLocalRhs.test(lhs)) { // Assigned value is not guaranteed to be a local value, // so if we see any property assignments on this variable, // they could be tainting a non-local value. blacklistedVarsByFunction.put(enclosingFunction, var); } } else { sideEffectInfo.setMutatesGlobalState(); } } } }
[ "private", "void", "visitLhsNodes", "(", "AmbiguatedFunctionSummary", "sideEffectInfo", ",", "Scope", "scope", ",", "Node", "enclosingFunction", ",", "List", "<", "Node", ">", "lhsNodes", ",", "Predicate", "<", "Node", ">", "hasLocalRhs", ")", "{", "for", "(", "Node", "lhs", ":", "lhsNodes", ")", "{", "if", "(", "NodeUtil", ".", "isGet", "(", "lhs", ")", ")", "{", "if", "(", "lhs", ".", "getFirstChild", "(", ")", ".", "isThis", "(", ")", ")", "{", "sideEffectInfo", ".", "setMutatesThis", "(", ")", ";", "}", "else", "{", "Node", "objectNode", "=", "lhs", ".", "getFirstChild", "(", ")", ";", "if", "(", "objectNode", ".", "isName", "(", ")", ")", "{", "Var", "var", "=", "scope", ".", "getVar", "(", "objectNode", ".", "getString", "(", ")", ")", ";", "if", "(", "isVarDeclaredInSameContainerScope", "(", "var", ",", "scope", ")", ")", "{", "// Maybe a local object modification. We won't know for sure until", "// we exit the scope and can validate the value of the local.", "taintedVarsByFunction", ".", "put", "(", "enclosingFunction", ",", "var", ")", ";", "}", "else", "{", "sideEffectInfo", ".", "setMutatesGlobalState", "(", ")", ";", "}", "}", "else", "{", "// Don't track multi level locals: local.prop.prop2++;", "sideEffectInfo", ".", "setMutatesGlobalState", "(", ")", ";", "}", "}", "}", "else", "{", "checkState", "(", "lhs", ".", "isName", "(", ")", ",", "lhs", ")", ";", "Var", "var", "=", "scope", ".", "getVar", "(", "lhs", ".", "getString", "(", ")", ")", ";", "if", "(", "isVarDeclaredInSameContainerScope", "(", "var", ",", "scope", ")", ")", "{", "if", "(", "!", "hasLocalRhs", ".", "test", "(", "lhs", ")", ")", "{", "// Assigned value is not guaranteed to be a local value,", "// so if we see any property assignments on this variable,", "// they could be tainting a non-local value.", "blacklistedVarsByFunction", ".", "put", "(", "enclosingFunction", ",", "var", ")", ";", "}", "}", "else", "{", "sideEffectInfo", ".", "setMutatesGlobalState", "(", ")", ";", "}", "}", "}", "}" ]
Record information about the side effects caused by assigning a value to a given LHS. <p>If the operation modifies this or taints global state, mark the enclosing function as having those side effects. @param sideEffectInfo Function side effect record to be updated @param scope variable scope in which the variable assignment occurs @param enclosingFunction FUNCTION node for the enclosing function @param lhsNodes LHS nodes that are all assigned values by a given parent node @param hasLocalRhs Predicate indicating whether a given LHS is being assigned a local value
[ "Record", "information", "about", "the", "side", "effects", "caused", "by", "assigning", "a", "value", "to", "a", "given", "LHS", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PureFunctionIdentifier.java#L922-L963
24,404
google/closure-compiler
src/com/google/javascript/jscomp/PureFunctionIdentifier.java
FunctionBodyAnalyzer.visitCall
private void visitCall(AmbiguatedFunctionSummary callerInfo, Node invocation) { // Handle special cases (Math, RegExp) // TODO: This logic can probably be replaced with @nosideeffects annotations in externs. if (invocation.isCall() && !NodeUtil.functionCallHasSideEffects(invocation, compiler)) { return; } // Handle known cases now (Object, Date, RegExp, etc) if (invocation.isNew() && !NodeUtil.constructorCallHasSideEffects(invocation)) { return; } List<AmbiguatedFunctionSummary> calleeSummaries = getSummariesForCallee(invocation); if (calleeSummaries.isEmpty()) { callerInfo.setAllFlags(); return; } for (AmbiguatedFunctionSummary calleeInfo : calleeSummaries) { SideEffectPropagation edge = SideEffectPropagation.forInvocation(invocation); reverseCallGraph.connect(calleeInfo.graphNode, edge, callerInfo.graphNode); } }
java
private void visitCall(AmbiguatedFunctionSummary callerInfo, Node invocation) { // Handle special cases (Math, RegExp) // TODO: This logic can probably be replaced with @nosideeffects annotations in externs. if (invocation.isCall() && !NodeUtil.functionCallHasSideEffects(invocation, compiler)) { return; } // Handle known cases now (Object, Date, RegExp, etc) if (invocation.isNew() && !NodeUtil.constructorCallHasSideEffects(invocation)) { return; } List<AmbiguatedFunctionSummary> calleeSummaries = getSummariesForCallee(invocation); if (calleeSummaries.isEmpty()) { callerInfo.setAllFlags(); return; } for (AmbiguatedFunctionSummary calleeInfo : calleeSummaries) { SideEffectPropagation edge = SideEffectPropagation.forInvocation(invocation); reverseCallGraph.connect(calleeInfo.graphNode, edge, callerInfo.graphNode); } }
[ "private", "void", "visitCall", "(", "AmbiguatedFunctionSummary", "callerInfo", ",", "Node", "invocation", ")", "{", "// Handle special cases (Math, RegExp)", "// TODO: This logic can probably be replaced with @nosideeffects annotations in externs.", "if", "(", "invocation", ".", "isCall", "(", ")", "&&", "!", "NodeUtil", ".", "functionCallHasSideEffects", "(", "invocation", ",", "compiler", ")", ")", "{", "return", ";", "}", "// Handle known cases now (Object, Date, RegExp, etc)", "if", "(", "invocation", ".", "isNew", "(", ")", "&&", "!", "NodeUtil", ".", "constructorCallHasSideEffects", "(", "invocation", ")", ")", "{", "return", ";", "}", "List", "<", "AmbiguatedFunctionSummary", ">", "calleeSummaries", "=", "getSummariesForCallee", "(", "invocation", ")", ";", "if", "(", "calleeSummaries", ".", "isEmpty", "(", ")", ")", "{", "callerInfo", ".", "setAllFlags", "(", ")", ";", "return", ";", "}", "for", "(", "AmbiguatedFunctionSummary", "calleeInfo", ":", "calleeSummaries", ")", "{", "SideEffectPropagation", "edge", "=", "SideEffectPropagation", ".", "forInvocation", "(", "invocation", ")", ";", "reverseCallGraph", ".", "connect", "(", "calleeInfo", ".", "graphNode", ",", "edge", ",", "callerInfo", ".", "graphNode", ")", ";", "}", "}" ]
Record information about a call site.
[ "Record", "information", "about", "a", "call", "site", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PureFunctionIdentifier.java#L966-L988
24,405
google/closure-compiler
src/com/google/javascript/jscomp/PureFunctionIdentifier.java
SideEffectPropagation.propagate
boolean propagate(AmbiguatedFunctionSummary callee, AmbiguatedFunctionSummary caller) { int initialCallerFlags = caller.bitmask; if (callerIsAlias) { caller.setMask(callee.bitmask); return caller.bitmask != initialCallerFlags; } if (callee.mutatesGlobalState()) { // If the callee modifies global state then so does that caller. caller.setMutatesGlobalState(); } if (callee.functionThrows()) { // If the callee throws an exception then so does the caller. caller.setFunctionThrows(); } if (callee.mutatesArguments() && !allArgsUnescapedLocal) { // If the callee mutates its input arguments and the arguments escape the caller then it has // unbounded side effects. caller.setMutatesGlobalState(); } if (callee.mutatesThis()) { if (invocation.isNew()) { // NEWing a constructor provide a unescaped "this" making side-effects impossible. } else if (calleeThisEqualsCallerThis) { caller.setMutatesThis(); } else { caller.setMutatesGlobalState(); } } return caller.bitmask != initialCallerFlags; }
java
boolean propagate(AmbiguatedFunctionSummary callee, AmbiguatedFunctionSummary caller) { int initialCallerFlags = caller.bitmask; if (callerIsAlias) { caller.setMask(callee.bitmask); return caller.bitmask != initialCallerFlags; } if (callee.mutatesGlobalState()) { // If the callee modifies global state then so does that caller. caller.setMutatesGlobalState(); } if (callee.functionThrows()) { // If the callee throws an exception then so does the caller. caller.setFunctionThrows(); } if (callee.mutatesArguments() && !allArgsUnescapedLocal) { // If the callee mutates its input arguments and the arguments escape the caller then it has // unbounded side effects. caller.setMutatesGlobalState(); } if (callee.mutatesThis()) { if (invocation.isNew()) { // NEWing a constructor provide a unescaped "this" making side-effects impossible. } else if (calleeThisEqualsCallerThis) { caller.setMutatesThis(); } else { caller.setMutatesGlobalState(); } } return caller.bitmask != initialCallerFlags; }
[ "boolean", "propagate", "(", "AmbiguatedFunctionSummary", "callee", ",", "AmbiguatedFunctionSummary", "caller", ")", "{", "int", "initialCallerFlags", "=", "caller", ".", "bitmask", ";", "if", "(", "callerIsAlias", ")", "{", "caller", ".", "setMask", "(", "callee", ".", "bitmask", ")", ";", "return", "caller", ".", "bitmask", "!=", "initialCallerFlags", ";", "}", "if", "(", "callee", ".", "mutatesGlobalState", "(", ")", ")", "{", "// If the callee modifies global state then so does that caller.", "caller", ".", "setMutatesGlobalState", "(", ")", ";", "}", "if", "(", "callee", ".", "functionThrows", "(", ")", ")", "{", "// If the callee throws an exception then so does the caller.", "caller", ".", "setFunctionThrows", "(", ")", ";", "}", "if", "(", "callee", ".", "mutatesArguments", "(", ")", "&&", "!", "allArgsUnescapedLocal", ")", "{", "// If the callee mutates its input arguments and the arguments escape the caller then it has", "// unbounded side effects.", "caller", ".", "setMutatesGlobalState", "(", ")", ";", "}", "if", "(", "callee", ".", "mutatesThis", "(", ")", ")", "{", "if", "(", "invocation", ".", "isNew", "(", ")", ")", "{", "// NEWing a constructor provide a unescaped \"this\" making side-effects impossible.", "}", "else", "if", "(", "calleeThisEqualsCallerThis", ")", "{", "caller", ".", "setMutatesThis", "(", ")", ";", "}", "else", "{", "caller", ".", "setMutatesGlobalState", "(", ")", ";", "}", "}", "return", "caller", ".", "bitmask", "!=", "initialCallerFlags", ";", "}" ]
Propagate the side effects from the callee to the caller. @param callee propagate from @param caller propagate to @return Returns true if the propagation changed the side effects on the caller.
[ "Propagate", "the", "side", "effects", "from", "the", "callee", "to", "the", "caller", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PureFunctionIdentifier.java#L1111-L1143
24,406
google/closure-compiler
src/com/google/javascript/rhino/jstype/TemplateTypeMapReplacer.java
TemplateTypeMapReplacer.hasVisitedType
@SuppressWarnings("ReferenceEquality") private boolean hasVisitedType(TemplateType type) { for (TemplateType visitedType : visitedTypes) { if (visitedType == type) { return true; } } return false; }
java
@SuppressWarnings("ReferenceEquality") private boolean hasVisitedType(TemplateType type) { for (TemplateType visitedType : visitedTypes) { if (visitedType == type) { return true; } } return false; }
[ "@", "SuppressWarnings", "(", "\"ReferenceEquality\"", ")", "private", "boolean", "hasVisitedType", "(", "TemplateType", "type", ")", "{", "for", "(", "TemplateType", "visitedType", ":", "visitedTypes", ")", "{", "if", "(", "visitedType", "==", "type", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the specified type has already been visited during the Visitor's traversal of a JSType.
[ "Checks", "if", "the", "specified", "type", "has", "already", "been", "visited", "during", "the", "Visitor", "s", "traversal", "of", "a", "JSType", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMapReplacer.java#L144-L152
24,407
google/closure-compiler
src/com/google/javascript/jscomp/WhitelistWarningsGuard.java
WhitelistWarningsGuard.normalizeWhitelist
protected Set<String> normalizeWhitelist(Set<String> whitelist) { Set<String> result = new HashSet<>(); for (String line : whitelist) { String trimmed = line.trim(); if (trimmed.isEmpty() || trimmed.charAt(0) == '#') { // strip out empty lines and comments. continue; } // Strip line number for matching. result.add(LINE_NUMBER.matcher(trimmed).replaceFirst(":")); } return ImmutableSet.copyOf(result); }
java
protected Set<String> normalizeWhitelist(Set<String> whitelist) { Set<String> result = new HashSet<>(); for (String line : whitelist) { String trimmed = line.trim(); if (trimmed.isEmpty() || trimmed.charAt(0) == '#') { // strip out empty lines and comments. continue; } // Strip line number for matching. result.add(LINE_NUMBER.matcher(trimmed).replaceFirst(":")); } return ImmutableSet.copyOf(result); }
[ "protected", "Set", "<", "String", ">", "normalizeWhitelist", "(", "Set", "<", "String", ">", "whitelist", ")", "{", "Set", "<", "String", ">", "result", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "String", "line", ":", "whitelist", ")", "{", "String", "trimmed", "=", "line", ".", "trim", "(", ")", ";", "if", "(", "trimmed", ".", "isEmpty", "(", ")", "||", "trimmed", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "// strip out empty lines and comments.", "continue", ";", "}", "// Strip line number for matching.", "result", ".", "add", "(", "LINE_NUMBER", ".", "matcher", "(", "trimmed", ")", ".", "replaceFirst", "(", "\":\"", ")", ")", ";", "}", "return", "ImmutableSet", ".", "copyOf", "(", "result", ")", ";", "}" ]
Loads legacy warnings list from the set of strings. During development line numbers are changed very often - we just cut them and compare without ones. @return known legacy warnings without line numbers.
[ "Loads", "legacy", "warnings", "list", "from", "the", "set", "of", "strings", ".", "During", "development", "line", "numbers", "are", "changed", "very", "often", "-", "we", "just", "cut", "them", "and", "compare", "without", "ones", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/WhitelistWarningsGuard.java#L86-L99
24,408
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.removeType
public void removeType(StaticScope scope, String name) { scopedNameTable.remove(getRootNodeForScope(getLookupScope(scope, name)), name); }
java
public void removeType(StaticScope scope, String name) { scopedNameTable.remove(getRootNodeForScope(getLookupScope(scope, name)), name); }
[ "public", "void", "removeType", "(", "StaticScope", "scope", ",", "String", "name", ")", "{", "scopedNameTable", ".", "remove", "(", "getRootNodeForScope", "(", "getLookupScope", "(", "scope", ",", "name", ")", ")", ",", "name", ")", ";", "}" ]
Removes a type by name. @param name The name string.
[ "Removes", "a", "type", "by", "name", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L870-L872
24,409
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.isObjectLiteralThatCanBeSkipped
private static boolean isObjectLiteralThatCanBeSkipped(JSType t) { t = t.restrictByNotNullOrUndefined(); return t.isRecordType() || t.isLiteralObject(); }
java
private static boolean isObjectLiteralThatCanBeSkipped(JSType t) { t = t.restrictByNotNullOrUndefined(); return t.isRecordType() || t.isLiteralObject(); }
[ "private", "static", "boolean", "isObjectLiteralThatCanBeSkipped", "(", "JSType", "t", ")", "{", "t", "=", "t", ".", "restrictByNotNullOrUndefined", "(", ")", ";", "return", "t", ".", "isRecordType", "(", ")", "||", "t", ".", "isLiteralObject", "(", ")", ";", "}" ]
we don't need to store these properties in the propertyIndex separately.
[ "we", "don", "t", "need", "to", "store", "these", "properties", "in", "the", "propertyIndex", "separately", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L881-L884
24,410
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.canPropertyBeDefined
public PropDefinitionKind canPropertyBeDefined(JSType type, String propertyName) { if (type.isStruct()) { // We are stricter about "struct" types and only allow access to // properties that to the best of our knowledge are available at creation // time and specifically not properties only defined on subtypes. switch (type.getPropertyKind(propertyName)) { case KNOWN_PRESENT: return PropDefinitionKind.KNOWN; case MAYBE_PRESENT: // TODO(johnlenz): return LOOSE_UNION here. return PropDefinitionKind.KNOWN; case ABSENT: return PropDefinitionKind.UNKNOWN; } } else { if (!type.isEmptyType() && !type.isUnknownType()) { switch (type.getPropertyKind(propertyName)) { case KNOWN_PRESENT: return PropDefinitionKind.KNOWN; case MAYBE_PRESENT: // TODO(johnlenz): return LOOSE_UNION here. return PropDefinitionKind.KNOWN; case ABSENT: // check for loose properties below. break; } } if (typesIndexedByProperty.containsKey(propertyName)) { for (JSType alternative : typesIndexedByProperty.get(propertyName)) { JSType greatestSubtype = alternative.getGreatestSubtype(type); if (!greatestSubtype.isEmptyType()) { // We've found a type with this property. Now we just have to make // sure it's not a type used for internal bookkeeping. RecordType maybeRecordType = greatestSubtype.toMaybeRecordType(); if (maybeRecordType != null && maybeRecordType.isSynthetic()) { continue; } return PropDefinitionKind.LOOSE; } } } if (type.toMaybeRecordType() != null) { RecordType rec = type.toMaybeRecordType(); boolean mayBeInUnion = false; for (String pname : rec.getPropertyMap().getOwnPropertyNames()) { if (this.propertiesOfSupertypesInUnions.contains(pname)) { mayBeInUnion = true; break; } } if (mayBeInUnion && this.droppedPropertiesOfUnions.contains(propertyName)) { return PropDefinitionKind.LOOSE; } } } return PropDefinitionKind.UNKNOWN; }
java
public PropDefinitionKind canPropertyBeDefined(JSType type, String propertyName) { if (type.isStruct()) { // We are stricter about "struct" types and only allow access to // properties that to the best of our knowledge are available at creation // time and specifically not properties only defined on subtypes. switch (type.getPropertyKind(propertyName)) { case KNOWN_PRESENT: return PropDefinitionKind.KNOWN; case MAYBE_PRESENT: // TODO(johnlenz): return LOOSE_UNION here. return PropDefinitionKind.KNOWN; case ABSENT: return PropDefinitionKind.UNKNOWN; } } else { if (!type.isEmptyType() && !type.isUnknownType()) { switch (type.getPropertyKind(propertyName)) { case KNOWN_PRESENT: return PropDefinitionKind.KNOWN; case MAYBE_PRESENT: // TODO(johnlenz): return LOOSE_UNION here. return PropDefinitionKind.KNOWN; case ABSENT: // check for loose properties below. break; } } if (typesIndexedByProperty.containsKey(propertyName)) { for (JSType alternative : typesIndexedByProperty.get(propertyName)) { JSType greatestSubtype = alternative.getGreatestSubtype(type); if (!greatestSubtype.isEmptyType()) { // We've found a type with this property. Now we just have to make // sure it's not a type used for internal bookkeeping. RecordType maybeRecordType = greatestSubtype.toMaybeRecordType(); if (maybeRecordType != null && maybeRecordType.isSynthetic()) { continue; } return PropDefinitionKind.LOOSE; } } } if (type.toMaybeRecordType() != null) { RecordType rec = type.toMaybeRecordType(); boolean mayBeInUnion = false; for (String pname : rec.getPropertyMap().getOwnPropertyNames()) { if (this.propertiesOfSupertypesInUnions.contains(pname)) { mayBeInUnion = true; break; } } if (mayBeInUnion && this.droppedPropertiesOfUnions.contains(propertyName)) { return PropDefinitionKind.LOOSE; } } } return PropDefinitionKind.UNKNOWN; }
[ "public", "PropDefinitionKind", "canPropertyBeDefined", "(", "JSType", "type", ",", "String", "propertyName", ")", "{", "if", "(", "type", ".", "isStruct", "(", ")", ")", "{", "// We are stricter about \"struct\" types and only allow access to", "// properties that to the best of our knowledge are available at creation", "// time and specifically not properties only defined on subtypes.", "switch", "(", "type", ".", "getPropertyKind", "(", "propertyName", ")", ")", "{", "case", "KNOWN_PRESENT", ":", "return", "PropDefinitionKind", ".", "KNOWN", ";", "case", "MAYBE_PRESENT", ":", "// TODO(johnlenz): return LOOSE_UNION here.", "return", "PropDefinitionKind", ".", "KNOWN", ";", "case", "ABSENT", ":", "return", "PropDefinitionKind", ".", "UNKNOWN", ";", "}", "}", "else", "{", "if", "(", "!", "type", ".", "isEmptyType", "(", ")", "&&", "!", "type", ".", "isUnknownType", "(", ")", ")", "{", "switch", "(", "type", ".", "getPropertyKind", "(", "propertyName", ")", ")", "{", "case", "KNOWN_PRESENT", ":", "return", "PropDefinitionKind", ".", "KNOWN", ";", "case", "MAYBE_PRESENT", ":", "// TODO(johnlenz): return LOOSE_UNION here.", "return", "PropDefinitionKind", ".", "KNOWN", ";", "case", "ABSENT", ":", "// check for loose properties below.", "break", ";", "}", "}", "if", "(", "typesIndexedByProperty", ".", "containsKey", "(", "propertyName", ")", ")", "{", "for", "(", "JSType", "alternative", ":", "typesIndexedByProperty", ".", "get", "(", "propertyName", ")", ")", "{", "JSType", "greatestSubtype", "=", "alternative", ".", "getGreatestSubtype", "(", "type", ")", ";", "if", "(", "!", "greatestSubtype", ".", "isEmptyType", "(", ")", ")", "{", "// We've found a type with this property. Now we just have to make", "// sure it's not a type used for internal bookkeeping.", "RecordType", "maybeRecordType", "=", "greatestSubtype", ".", "toMaybeRecordType", "(", ")", ";", "if", "(", "maybeRecordType", "!=", "null", "&&", "maybeRecordType", ".", "isSynthetic", "(", ")", ")", "{", "continue", ";", "}", "return", "PropDefinitionKind", ".", "LOOSE", ";", "}", "}", "}", "if", "(", "type", ".", "toMaybeRecordType", "(", ")", "!=", "null", ")", "{", "RecordType", "rec", "=", "type", ".", "toMaybeRecordType", "(", ")", ";", "boolean", "mayBeInUnion", "=", "false", ";", "for", "(", "String", "pname", ":", "rec", ".", "getPropertyMap", "(", ")", ".", "getOwnPropertyNames", "(", ")", ")", "{", "if", "(", "this", ".", "propertiesOfSupertypesInUnions", ".", "contains", "(", "pname", ")", ")", "{", "mayBeInUnion", "=", "true", ";", "break", ";", "}", "}", "if", "(", "mayBeInUnion", "&&", "this", ".", "droppedPropertiesOfUnions", ".", "contains", "(", "propertyName", ")", ")", "{", "return", "PropDefinitionKind", ".", "LOOSE", ";", "}", "}", "}", "return", "PropDefinitionKind", ".", "UNKNOWN", ";", "}" ]
Returns whether the given property can possibly be set on the given type.
[ "Returns", "whether", "the", "given", "property", "can", "possibly", "be", "set", "on", "the", "given", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L998-L1059
24,411
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.findCommonSuperObject
ObjectType findCommonSuperObject(ObjectType a, ObjectType b) { List<ObjectType> stackA = getSuperStack(a); List<ObjectType> stackB = getSuperStack(b); ObjectType result = getNativeObjectType(JSTypeNative.OBJECT_TYPE); while (!stackA.isEmpty() && !stackB.isEmpty()) { ObjectType currentA = stackA.remove(stackA.size() - 1); ObjectType currentB = stackB.remove(stackB.size() - 1); if (currentA.isEquivalentTo(currentB)) { result = currentA; } else { return result; } } return result; }
java
ObjectType findCommonSuperObject(ObjectType a, ObjectType b) { List<ObjectType> stackA = getSuperStack(a); List<ObjectType> stackB = getSuperStack(b); ObjectType result = getNativeObjectType(JSTypeNative.OBJECT_TYPE); while (!stackA.isEmpty() && !stackB.isEmpty()) { ObjectType currentA = stackA.remove(stackA.size() - 1); ObjectType currentB = stackB.remove(stackB.size() - 1); if (currentA.isEquivalentTo(currentB)) { result = currentA; } else { return result; } } return result; }
[ "ObjectType", "findCommonSuperObject", "(", "ObjectType", "a", ",", "ObjectType", "b", ")", "{", "List", "<", "ObjectType", ">", "stackA", "=", "getSuperStack", "(", "a", ")", ";", "List", "<", "ObjectType", ">", "stackB", "=", "getSuperStack", "(", "b", ")", ";", "ObjectType", "result", "=", "getNativeObjectType", "(", "JSTypeNative", ".", "OBJECT_TYPE", ")", ";", "while", "(", "!", "stackA", ".", "isEmpty", "(", ")", "&&", "!", "stackB", ".", "isEmpty", "(", ")", ")", "{", "ObjectType", "currentA", "=", "stackA", ".", "remove", "(", "stackA", ".", "size", "(", ")", "-", "1", ")", ";", "ObjectType", "currentB", "=", "stackB", ".", "remove", "(", "stackB", ".", "size", "(", ")", "-", "1", ")", ";", "if", "(", "currentA", ".", "isEquivalentTo", "(", "currentB", ")", ")", "{", "result", "=", "currentA", ";", "}", "else", "{", "return", "result", ";", "}", "}", "return", "result", ";", "}" ]
Finds the common supertype of the two given object types.
[ "Finds", "the", "common", "supertype", "of", "the", "two", "given", "object", "types", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1083-L1098
24,412
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.overwriteDeclaredType
public void overwriteDeclaredType(StaticScope scope, String name, JSType type) { checkState(isDeclaredForScope(scope, name), "missing name %s", name); reregister(scope, type, name); }
java
public void overwriteDeclaredType(StaticScope scope, String name, JSType type) { checkState(isDeclaredForScope(scope, name), "missing name %s", name); reregister(scope, type, name); }
[ "public", "void", "overwriteDeclaredType", "(", "StaticScope", "scope", ",", "String", "name", ",", "JSType", "type", ")", "{", "checkState", "(", "isDeclaredForScope", "(", "scope", ",", "name", ")", ",", "\"missing name %s\"", ",", "name", ")", ";", "reregister", "(", "scope", ",", "type", ",", "name", ")", ";", "}" ]
Overrides a declared global type name. Throws an exception if this type name hasn't been declared yet.
[ "Overrides", "a", "declared", "global", "type", "name", ".", "Throws", "an", "exception", "if", "this", "type", "name", "hasn", "t", "been", "declared", "yet", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1179-L1182
24,413
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.getType
public JSType getType( StaticTypedScope scope, String jsTypeName, String sourceName, int lineno, int charno) { return getType(scope, jsTypeName, sourceName, lineno, charno, true); }
java
public JSType getType( StaticTypedScope scope, String jsTypeName, String sourceName, int lineno, int charno) { return getType(scope, jsTypeName, sourceName, lineno, charno, true); }
[ "public", "JSType", "getType", "(", "StaticTypedScope", "scope", ",", "String", "jsTypeName", ",", "String", "sourceName", ",", "int", "lineno", ",", "int", "charno", ")", "{", "return", "getType", "(", "scope", ",", "jsTypeName", ",", "sourceName", ",", "lineno", ",", "charno", ",", "true", ")", ";", "}" ]
Looks up a type by name. To allow for forward references to types, an unrecognized string has to be bound to a NamedType object that will be resolved later. @param scope A scope for doing type name resolution. @param jsTypeName The name string. @param sourceName The name of the source file where this reference appears. @param lineno The line number of the reference. @return a NamedType if the string argument is not one of the known types, otherwise the corresponding JSType object.
[ "Looks", "up", "a", "type", "by", "name", ".", "To", "allow", "for", "forward", "references", "to", "types", "an", "unrecognized", "string", "has", "to", "be", "bound", "to", "a", "NamedType", "object", "that", "will", "be", "resolved", "later", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1361-L1364
24,414
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.resolveTypes
public void resolveTypes() { for (NamedType type : unresolvedNamedTypes) { type.resolve(reporter); } unresolvedNamedTypes.clear(); // By default, the global "this" type is just an anonymous object. // If the user has defined a Window type, make the Window the // implicit prototype of "this". PrototypeObjectType globalThis = (PrototypeObjectType) getNativeType( JSTypeNative.GLOBAL_THIS); JSType windowType = getTypeInternal(null, "Window"); if (globalThis.isUnknownType()) { ObjectType windowObjType = ObjectType.cast(windowType); if (windowObjType != null) { globalThis.setImplicitPrototype(windowObjType); } else { globalThis.setImplicitPrototype( getNativeObjectType(JSTypeNative.OBJECT_TYPE)); } } }
java
public void resolveTypes() { for (NamedType type : unresolvedNamedTypes) { type.resolve(reporter); } unresolvedNamedTypes.clear(); // By default, the global "this" type is just an anonymous object. // If the user has defined a Window type, make the Window the // implicit prototype of "this". PrototypeObjectType globalThis = (PrototypeObjectType) getNativeType( JSTypeNative.GLOBAL_THIS); JSType windowType = getTypeInternal(null, "Window"); if (globalThis.isUnknownType()) { ObjectType windowObjType = ObjectType.cast(windowType); if (windowObjType != null) { globalThis.setImplicitPrototype(windowObjType); } else { globalThis.setImplicitPrototype( getNativeObjectType(JSTypeNative.OBJECT_TYPE)); } } }
[ "public", "void", "resolveTypes", "(", ")", "{", "for", "(", "NamedType", "type", ":", "unresolvedNamedTypes", ")", "{", "type", ".", "resolve", "(", "reporter", ")", ";", "}", "unresolvedNamedTypes", ".", "clear", "(", ")", ";", "// By default, the global \"this\" type is just an anonymous object.", "// If the user has defined a Window type, make the Window the", "// implicit prototype of \"this\".", "PrototypeObjectType", "globalThis", "=", "(", "PrototypeObjectType", ")", "getNativeType", "(", "JSTypeNative", ".", "GLOBAL_THIS", ")", ";", "JSType", "windowType", "=", "getTypeInternal", "(", "null", ",", "\"Window\"", ")", ";", "if", "(", "globalThis", ".", "isUnknownType", "(", ")", ")", "{", "ObjectType", "windowObjType", "=", "ObjectType", ".", "cast", "(", "windowType", ")", ";", "if", "(", "windowObjType", "!=", "null", ")", "{", "globalThis", ".", "setImplicitPrototype", "(", "windowObjType", ")", ";", "}", "else", "{", "globalThis", ".", "setImplicitPrototype", "(", "getNativeObjectType", "(", "JSTypeNative", ".", "OBJECT_TYPE", ")", ")", ";", "}", "}", "}" ]
Resolve all the unresolved types in the given scope.
[ "Resolve", "all", "the", "unresolved", "types", "in", "the", "given", "scope", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1444-L1466
24,415
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createOptionalType
public JSType createOptionalType(JSType type) { if (type instanceof UnknownType || type.isAllType()) { return type; } else { return createUnionType(type, getNativeType(JSTypeNative.VOID_TYPE)); } }
java
public JSType createOptionalType(JSType type) { if (type instanceof UnknownType || type.isAllType()) { return type; } else { return createUnionType(type, getNativeType(JSTypeNative.VOID_TYPE)); } }
[ "public", "JSType", "createOptionalType", "(", "JSType", "type", ")", "{", "if", "(", "type", "instanceof", "UnknownType", "||", "type", ".", "isAllType", "(", ")", ")", "{", "return", "type", ";", "}", "else", "{", "return", "createUnionType", "(", "type", ",", "getNativeType", "(", "JSTypeNative", ".", "VOID_TYPE", ")", ")", ";", "}", "}" ]
Creates a type representing optional values of the given type. @return the union of the type and the void type
[ "Creates", "a", "type", "representing", "optional", "values", "of", "the", "given", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1476-L1482
24,416
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createOptionalNullableType
public JSType createOptionalNullableType(JSType type) { return createUnionType(type, getNativeType(JSTypeNative.VOID_TYPE), getNativeType(JSTypeNative.NULL_TYPE)); }
java
public JSType createOptionalNullableType(JSType type) { return createUnionType(type, getNativeType(JSTypeNative.VOID_TYPE), getNativeType(JSTypeNative.NULL_TYPE)); }
[ "public", "JSType", "createOptionalNullableType", "(", "JSType", "type", ")", "{", "return", "createUnionType", "(", "type", ",", "getNativeType", "(", "JSTypeNative", ".", "VOID_TYPE", ")", ",", "getNativeType", "(", "JSTypeNative", ".", "NULL_TYPE", ")", ")", ";", "}" ]
Creates a nullable and undefine-able value of the given type. @return The union of the type and null and undefined.
[ "Creates", "a", "nullable", "and", "undefine", "-", "able", "value", "of", "the", "given", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1510-L1513
24,417
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createUnionType
public JSType createUnionType(JSType... variants) { UnionTypeBuilder builder = UnionTypeBuilder.create(this); for (JSType type : variants) { builder.addAlternate(type); } return builder.build(); }
java
public JSType createUnionType(JSType... variants) { UnionTypeBuilder builder = UnionTypeBuilder.create(this); for (JSType type : variants) { builder.addAlternate(type); } return builder.build(); }
[ "public", "JSType", "createUnionType", "(", "JSType", "...", "variants", ")", "{", "UnionTypeBuilder", "builder", "=", "UnionTypeBuilder", ".", "create", "(", "this", ")", ";", "for", "(", "JSType", "type", ":", "variants", ")", "{", "builder", ".", "addAlternate", "(", "type", ")", ";", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Creates a union type whose variants are the arguments.
[ "Creates", "a", "union", "type", "whose", "variants", "are", "the", "arguments", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1518-L1524
24,418
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createUnionType
public JSType createUnionType(JSTypeNative... variants) { UnionTypeBuilder builder = UnionTypeBuilder.create(this); for (JSTypeNative typeId : variants) { builder.addAlternate(getNativeType(typeId)); } return builder.build(); }
java
public JSType createUnionType(JSTypeNative... variants) { UnionTypeBuilder builder = UnionTypeBuilder.create(this); for (JSTypeNative typeId : variants) { builder.addAlternate(getNativeType(typeId)); } return builder.build(); }
[ "public", "JSType", "createUnionType", "(", "JSTypeNative", "...", "variants", ")", "{", "UnionTypeBuilder", "builder", "=", "UnionTypeBuilder", ".", "create", "(", "this", ")", ";", "for", "(", "JSTypeNative", "typeId", ":", "variants", ")", "{", "builder", ".", "addAlternate", "(", "getNativeType", "(", "typeId", ")", ")", ";", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Creates a union type whose variants are the built-in types specified by the arguments.
[ "Creates", "a", "union", "type", "whose", "variants", "are", "the", "built", "-", "in", "types", "specified", "by", "the", "arguments", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1534-L1540
24,419
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createEnumType
public EnumType createEnumType(String name, Node source, JSType elementsType) { return new EnumType(this, name, source, elementsType); }
java
public EnumType createEnumType(String name, Node source, JSType elementsType) { return new EnumType(this, name, source, elementsType); }
[ "public", "EnumType", "createEnumType", "(", "String", "name", ",", "Node", "source", ",", "JSType", "elementsType", ")", "{", "return", "new", "EnumType", "(", "this", ",", "name", ",", "source", ",", "elementsType", ")", ";", "}" ]
Creates an enum type. @param name The human-readable name associated with the enum, or null if unknown.
[ "Creates", "an", "enum", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1547-L1549
24,420
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createFunctionType
public FunctionType createFunctionType( JSType returnType, JSType... parameterTypes) { return createFunctionType(returnType, createParameters(parameterTypes)); }
java
public FunctionType createFunctionType( JSType returnType, JSType... parameterTypes) { return createFunctionType(returnType, createParameters(parameterTypes)); }
[ "public", "FunctionType", "createFunctionType", "(", "JSType", "returnType", ",", "JSType", "...", "parameterTypes", ")", "{", "return", "createFunctionType", "(", "returnType", ",", "createParameters", "(", "parameterTypes", ")", ")", ";", "}" ]
Creates a function type. @param returnType the function's return type @param parameterTypes the parameters' types
[ "Creates", "a", "function", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1589-L1592
24,421
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createParameters
private Node createParameters(boolean lastVarArgs, JSType... parameterTypes) { FunctionParamBuilder builder = new FunctionParamBuilder(this); int max = parameterTypes.length - 1; for (int i = 0; i <= max; i++) { if (lastVarArgs && i == max) { builder.addVarArgs(parameterTypes[i]); } else { builder.addRequiredParams(parameterTypes[i]); } } return builder.build(); }
java
private Node createParameters(boolean lastVarArgs, JSType... parameterTypes) { FunctionParamBuilder builder = new FunctionParamBuilder(this); int max = parameterTypes.length - 1; for (int i = 0; i <= max; i++) { if (lastVarArgs && i == max) { builder.addVarArgs(parameterTypes[i]); } else { builder.addRequiredParams(parameterTypes[i]); } } return builder.build(); }
[ "private", "Node", "createParameters", "(", "boolean", "lastVarArgs", ",", "JSType", "...", "parameterTypes", ")", "{", "FunctionParamBuilder", "builder", "=", "new", "FunctionParamBuilder", "(", "this", ")", ";", "int", "max", "=", "parameterTypes", ".", "length", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "max", ";", "i", "++", ")", "{", "if", "(", "lastVarArgs", "&&", "i", "==", "max", ")", "{", "builder", ".", "addVarArgs", "(", "parameterTypes", "[", "i", "]", ")", ";", "}", "else", "{", "builder", ".", "addRequiredParams", "(", "parameterTypes", "[", "i", "]", ")", ";", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Creates a tree hierarchy representing a typed argument list. @param lastVarArgs whether the last type should considered as a variable length argument. @param parameterTypes the parameter types. The last element of this array is considered a variable length argument is {@code lastVarArgs} is {@code true}. @return a tree hierarchy representing a typed argument list
[ "Creates", "a", "tree", "hierarchy", "representing", "a", "typed", "argument", "list", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1665-L1676
24,422
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createOptionalParameters
public Node createOptionalParameters(JSType... parameterTypes) { FunctionParamBuilder builder = new FunctionParamBuilder(this); builder.addOptionalParams(parameterTypes); return builder.build(); }
java
public Node createOptionalParameters(JSType... parameterTypes) { FunctionParamBuilder builder = new FunctionParamBuilder(this); builder.addOptionalParams(parameterTypes); return builder.build(); }
[ "public", "Node", "createOptionalParameters", "(", "JSType", "...", "parameterTypes", ")", "{", "FunctionParamBuilder", "builder", "=", "new", "FunctionParamBuilder", "(", "this", ")", ";", "builder", ".", "addOptionalParams", "(", "parameterTypes", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Creates a tree hierarchy representing a typed parameter list in which every parameter is optional.
[ "Creates", "a", "tree", "hierarchy", "representing", "a", "typed", "parameter", "list", "in", "which", "every", "parameter", "is", "optional", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1694-L1698
24,423
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createFunctionTypeWithNewReturnType
public FunctionType createFunctionTypeWithNewReturnType( FunctionType existingFunctionType, JSType returnType) { return FunctionType.builder(this) .copyFromOtherFunction(existingFunctionType) .withReturnType(returnType) .build(); }
java
public FunctionType createFunctionTypeWithNewReturnType( FunctionType existingFunctionType, JSType returnType) { return FunctionType.builder(this) .copyFromOtherFunction(existingFunctionType) .withReturnType(returnType) .build(); }
[ "public", "FunctionType", "createFunctionTypeWithNewReturnType", "(", "FunctionType", "existingFunctionType", ",", "JSType", "returnType", ")", "{", "return", "FunctionType", ".", "builder", "(", "this", ")", ".", "copyFromOtherFunction", "(", "existingFunctionType", ")", ".", "withReturnType", "(", "returnType", ")", ".", "build", "(", ")", ";", "}" ]
Creates a new function type based on an existing function type but with a new return type. @param existingFunctionType the existing function type. @param returnType the new return type.
[ "Creates", "a", "new", "function", "type", "based", "on", "an", "existing", "function", "type", "but", "with", "a", "new", "return", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1706-L1712
24,424
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createAnonymousObjectType
public ObjectType createAnonymousObjectType(JSDocInfo info) { PrototypeObjectType type = new PrototypeObjectType( this, null, null, true /* anonymousType */); type.setPrettyPrint(true); type.setJSDocInfo(info); return type; }
java
public ObjectType createAnonymousObjectType(JSDocInfo info) { PrototypeObjectType type = new PrototypeObjectType( this, null, null, true /* anonymousType */); type.setPrettyPrint(true); type.setJSDocInfo(info); return type; }
[ "public", "ObjectType", "createAnonymousObjectType", "(", "JSDocInfo", "info", ")", "{", "PrototypeObjectType", "type", "=", "new", "PrototypeObjectType", "(", "this", ",", "null", ",", "null", ",", "true", "/* anonymousType */", ")", ";", "type", ".", "setPrettyPrint", "(", "true", ")", ";", "type", ".", "setJSDocInfo", "(", "info", ")", ";", "return", "type", ";", "}" ]
Create an anonymous object type. @param info Used to mark object literals as structs; can be {@code null}
[ "Create", "an", "anonymous", "object", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1764-L1770
24,425
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createConstructorType
public FunctionType createConstructorType( String name, Node source, Node parameters, JSType returnType, ImmutableList<TemplateType> templateKeys, boolean isAbstract) { checkArgument(source == null || source.isFunction() || source.isClass()); return FunctionType.builder(this) .forConstructor() .withName(name) .withSourceNode(source) .withParamsNode(parameters) .withReturnType(returnType) .withTemplateKeys(templateKeys) .withIsAbstract(isAbstract) .build(); }
java
public FunctionType createConstructorType( String name, Node source, Node parameters, JSType returnType, ImmutableList<TemplateType> templateKeys, boolean isAbstract) { checkArgument(source == null || source.isFunction() || source.isClass()); return FunctionType.builder(this) .forConstructor() .withName(name) .withSourceNode(source) .withParamsNode(parameters) .withReturnType(returnType) .withTemplateKeys(templateKeys) .withIsAbstract(isAbstract) .build(); }
[ "public", "FunctionType", "createConstructorType", "(", "String", "name", ",", "Node", "source", ",", "Node", "parameters", ",", "JSType", "returnType", ",", "ImmutableList", "<", "TemplateType", ">", "templateKeys", ",", "boolean", "isAbstract", ")", "{", "checkArgument", "(", "source", "==", "null", "||", "source", ".", "isFunction", "(", ")", "||", "source", ".", "isClass", "(", ")", ")", ";", "return", "FunctionType", ".", "builder", "(", "this", ")", ".", "forConstructor", "(", ")", ".", "withName", "(", "name", ")", ".", "withSourceNode", "(", "source", ")", ".", "withParamsNode", "(", "parameters", ")", ".", "withReturnType", "(", "returnType", ")", ".", "withTemplateKeys", "(", "templateKeys", ")", ".", "withIsAbstract", "(", "isAbstract", ")", ".", "build", "(", ")", ";", "}" ]
Creates a constructor function type. @param name the function's name or {@code null} to indicate that the function is anonymous. @param source the node defining this function. Its type ({@link Node#getToken()} ()}) must be {@link Token#FUNCTION}. @param parameters the function's parameters or {@code null} to indicate that the parameter types are unknown. @param returnType the function's return type or {@code null} to indicate that the return type is unknown. @param templateKeys the templatized types for the class. @param isAbstract whether the function type represents an abstract class
[ "Creates", "a", "constructor", "function", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1799-L1816
24,426
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createInterfaceType
public FunctionType createInterfaceType( String name, Node source, ImmutableList<TemplateType> templateKeys, boolean struct) { FunctionType fn = FunctionType.builder(this) .forInterface() .withName(name) .withSourceNode(source) .withEmptyParams() .withTemplateKeys(templateKeys) .build(); if (struct) { fn.setStruct(); } return fn; }
java
public FunctionType createInterfaceType( String name, Node source, ImmutableList<TemplateType> templateKeys, boolean struct) { FunctionType fn = FunctionType.builder(this) .forInterface() .withName(name) .withSourceNode(source) .withEmptyParams() .withTemplateKeys(templateKeys) .build(); if (struct) { fn.setStruct(); } return fn; }
[ "public", "FunctionType", "createInterfaceType", "(", "String", "name", ",", "Node", "source", ",", "ImmutableList", "<", "TemplateType", ">", "templateKeys", ",", "boolean", "struct", ")", "{", "FunctionType", "fn", "=", "FunctionType", ".", "builder", "(", "this", ")", ".", "forInterface", "(", ")", ".", "withName", "(", "name", ")", ".", "withSourceNode", "(", "source", ")", ".", "withEmptyParams", "(", ")", ".", "withTemplateKeys", "(", "templateKeys", ")", ".", "build", "(", ")", ";", "if", "(", "struct", ")", "{", "fn", ".", "setStruct", "(", ")", ";", "}", "return", "fn", ";", "}" ]
Creates an interface function type. @param name the function's name @param source the node defining this function. Its type ({@link Node#getToken()}) must be {@link Token#FUNCTION}. @param templateKeys the templatized types for the interface.
[ "Creates", "an", "interface", "function", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1826-L1840
24,427
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createTemplateTypeMap
public TemplateTypeMap createTemplateTypeMap( ImmutableList<TemplateType> templateKeys, ImmutableList<JSType> templateValues) { if (templateKeys == null) { templateKeys = ImmutableList.of(); } if (templateValues == null) { templateValues = ImmutableList.of(); } return (templateKeys.isEmpty() && templateValues.isEmpty()) ? emptyTemplateTypeMap : new TemplateTypeMap(this, templateKeys, templateValues); }
java
public TemplateTypeMap createTemplateTypeMap( ImmutableList<TemplateType> templateKeys, ImmutableList<JSType> templateValues) { if (templateKeys == null) { templateKeys = ImmutableList.of(); } if (templateValues == null) { templateValues = ImmutableList.of(); } return (templateKeys.isEmpty() && templateValues.isEmpty()) ? emptyTemplateTypeMap : new TemplateTypeMap(this, templateKeys, templateValues); }
[ "public", "TemplateTypeMap", "createTemplateTypeMap", "(", "ImmutableList", "<", "TemplateType", ">", "templateKeys", ",", "ImmutableList", "<", "JSType", ">", "templateValues", ")", "{", "if", "(", "templateKeys", "==", "null", ")", "{", "templateKeys", "=", "ImmutableList", ".", "of", "(", ")", ";", "}", "if", "(", "templateValues", "==", "null", ")", "{", "templateValues", "=", "ImmutableList", ".", "of", "(", ")", ";", "}", "return", "(", "templateKeys", ".", "isEmpty", "(", ")", "&&", "templateValues", ".", "isEmpty", "(", ")", ")", "?", "emptyTemplateTypeMap", ":", "new", "TemplateTypeMap", "(", "this", ",", "templateKeys", ",", "templateValues", ")", ";", "}" ]
Creates a template type map from the specified list of template keys and template value types.
[ "Creates", "a", "template", "type", "map", "from", "the", "specified", "list", "of", "template", "keys", "and", "template", "value", "types", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1855-L1867
24,428
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createNamedType
@VisibleForTesting public NamedType createNamedType( StaticTypedScope scope, String reference, String sourceName, int lineno, int charno) { return new NamedType(scope, this, reference, sourceName, lineno, charno); }
java
@VisibleForTesting public NamedType createNamedType( StaticTypedScope scope, String reference, String sourceName, int lineno, int charno) { return new NamedType(scope, this, reference, sourceName, lineno, charno); }
[ "@", "VisibleForTesting", "public", "NamedType", "createNamedType", "(", "StaticTypedScope", "scope", ",", "String", "reference", ",", "String", "sourceName", ",", "int", "lineno", ",", "int", "charno", ")", "{", "return", "new", "NamedType", "(", "scope", ",", "this", ",", "reference", ",", "sourceName", ",", "lineno", ",", "charno", ")", ";", "}" ]
Creates a named type.
[ "Creates", "a", "named", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1934-L1938
24,429
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createTypeFromCommentNode
@SuppressWarnings("unchecked") public JSType createTypeFromCommentNode(Node n, String sourceName, StaticTypedScope scope) { return createFromTypeNodesInternal(n, sourceName, scope, true); }
java
@SuppressWarnings("unchecked") public JSType createTypeFromCommentNode(Node n, String sourceName, StaticTypedScope scope) { return createFromTypeNodesInternal(n, sourceName, scope, true); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "JSType", "createTypeFromCommentNode", "(", "Node", "n", ",", "String", "sourceName", ",", "StaticTypedScope", "scope", ")", "{", "return", "createFromTypeNodesInternal", "(", "n", ",", "sourceName", ",", "scope", ",", "true", ")", ";", "}" ]
Creates a JSType from the nodes representing a type. @param n The node with type info. @param sourceName The source file name. @param scope A scope for doing type name lookups.
[ "Creates", "a", "JSType", "from", "the", "nodes", "representing", "a", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1971-L1974
24,430
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createRecordTypeFromNodes
private JSType createRecordTypeFromNodes(Node n, String sourceName, StaticTypedScope scope) { RecordTypeBuilder builder = new RecordTypeBuilder(this); // For each of the fields in the record type. for (Node fieldTypeNode = n.getFirstChild(); fieldTypeNode != null; fieldTypeNode = fieldTypeNode.getNext()) { // Get the property's name. Node fieldNameNode = fieldTypeNode; boolean hasType = false; if (fieldTypeNode.getToken() == Token.COLON) { fieldNameNode = fieldTypeNode.getFirstChild(); hasType = true; } String fieldName = fieldNameNode.getString(); // TODO(user): Move this into the lexer/parser. // Remove the string literal characters around a field name, // if any. if (fieldName.startsWith("'") || fieldName.startsWith("\"")) { fieldName = fieldName.substring(1, fieldName.length() - 1); } // Get the property's type. JSType fieldType = null; if (hasType) { // We have a declared type. fieldType = createFromTypeNodesInternal( fieldTypeNode.getLastChild(), sourceName, scope, true); } else { // Otherwise, the type is UNKNOWN. fieldType = getNativeType(JSTypeNative.UNKNOWN_TYPE); } builder.addProperty(fieldName, fieldType, fieldNameNode); } return builder.build(); }
java
private JSType createRecordTypeFromNodes(Node n, String sourceName, StaticTypedScope scope) { RecordTypeBuilder builder = new RecordTypeBuilder(this); // For each of the fields in the record type. for (Node fieldTypeNode = n.getFirstChild(); fieldTypeNode != null; fieldTypeNode = fieldTypeNode.getNext()) { // Get the property's name. Node fieldNameNode = fieldTypeNode; boolean hasType = false; if (fieldTypeNode.getToken() == Token.COLON) { fieldNameNode = fieldTypeNode.getFirstChild(); hasType = true; } String fieldName = fieldNameNode.getString(); // TODO(user): Move this into the lexer/parser. // Remove the string literal characters around a field name, // if any. if (fieldName.startsWith("'") || fieldName.startsWith("\"")) { fieldName = fieldName.substring(1, fieldName.length() - 1); } // Get the property's type. JSType fieldType = null; if (hasType) { // We have a declared type. fieldType = createFromTypeNodesInternal( fieldTypeNode.getLastChild(), sourceName, scope, true); } else { // Otherwise, the type is UNKNOWN. fieldType = getNativeType(JSTypeNative.UNKNOWN_TYPE); } builder.addProperty(fieldName, fieldType, fieldNameNode); } return builder.build(); }
[ "private", "JSType", "createRecordTypeFromNodes", "(", "Node", "n", ",", "String", "sourceName", ",", "StaticTypedScope", "scope", ")", "{", "RecordTypeBuilder", "builder", "=", "new", "RecordTypeBuilder", "(", "this", ")", ";", "// For each of the fields in the record type.", "for", "(", "Node", "fieldTypeNode", "=", "n", ".", "getFirstChild", "(", ")", ";", "fieldTypeNode", "!=", "null", ";", "fieldTypeNode", "=", "fieldTypeNode", ".", "getNext", "(", ")", ")", "{", "// Get the property's name.", "Node", "fieldNameNode", "=", "fieldTypeNode", ";", "boolean", "hasType", "=", "false", ";", "if", "(", "fieldTypeNode", ".", "getToken", "(", ")", "==", "Token", ".", "COLON", ")", "{", "fieldNameNode", "=", "fieldTypeNode", ".", "getFirstChild", "(", ")", ";", "hasType", "=", "true", ";", "}", "String", "fieldName", "=", "fieldNameNode", ".", "getString", "(", ")", ";", "// TODO(user): Move this into the lexer/parser.", "// Remove the string literal characters around a field name,", "// if any.", "if", "(", "fieldName", ".", "startsWith", "(", "\"'\"", ")", "||", "fieldName", ".", "startsWith", "(", "\"\\\"\"", ")", ")", "{", "fieldName", "=", "fieldName", ".", "substring", "(", "1", ",", "fieldName", ".", "length", "(", ")", "-", "1", ")", ";", "}", "// Get the property's type.", "JSType", "fieldType", "=", "null", ";", "if", "(", "hasType", ")", "{", "// We have a declared type.", "fieldType", "=", "createFromTypeNodesInternal", "(", "fieldTypeNode", ".", "getLastChild", "(", ")", ",", "sourceName", ",", "scope", ",", "true", ")", ";", "}", "else", "{", "// Otherwise, the type is UNKNOWN.", "fieldType", "=", "getNativeType", "(", "JSTypeNative", ".", "UNKNOWN_TYPE", ")", ";", "}", "builder", ".", "addProperty", "(", "fieldName", ",", "fieldType", ",", "fieldNameNode", ")", ";", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Creates a RecordType from the nodes representing said record type. @param n The node with type info. @param sourceName The source file name. @param scope A scope for doing type name lookups.
[ "Creates", "a", "RecordType", "from", "the", "nodes", "representing", "said", "record", "type", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L2208-L2251
24,431
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.registerTemplateTypeNamesInScope
public void registerTemplateTypeNamesInScope(Iterable<TemplateType> keys, Node scopeRoot) { for (TemplateType key : keys) { scopedNameTable.put(scopeRoot, key.getReferenceName(), key); } }
java
public void registerTemplateTypeNamesInScope(Iterable<TemplateType> keys, Node scopeRoot) { for (TemplateType key : keys) { scopedNameTable.put(scopeRoot, key.getReferenceName(), key); } }
[ "public", "void", "registerTemplateTypeNamesInScope", "(", "Iterable", "<", "TemplateType", ">", "keys", ",", "Node", "scopeRoot", ")", "{", "for", "(", "TemplateType", "key", ":", "keys", ")", "{", "scopedNameTable", ".", "put", "(", "scopeRoot", ",", "key", ".", "getReferenceName", "(", ")", ",", "key", ")", ";", "}", "}" ]
Registers template types on the given scope root. This takes a Node rather than a StaticScope because at the time it is called, the scope has not yet been created.
[ "Registers", "template", "types", "on", "the", "given", "scope", "root", ".", "This", "takes", "a", "Node", "rather", "than", "a", "StaticScope", "because", "at", "the", "time", "it", "is", "called", "the", "scope", "has", "not", "yet", "been", "created", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L2257-L2261
24,432
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createScopeWithTemplates
public StaticTypedScope createScopeWithTemplates( StaticTypedScope scope, Iterable<TemplateType> templates) { return new SyntheticTemplateScope(scope, templates); }
java
public StaticTypedScope createScopeWithTemplates( StaticTypedScope scope, Iterable<TemplateType> templates) { return new SyntheticTemplateScope(scope, templates); }
[ "public", "StaticTypedScope", "createScopeWithTemplates", "(", "StaticTypedScope", "scope", ",", "Iterable", "<", "TemplateType", ">", "templates", ")", "{", "return", "new", "SyntheticTemplateScope", "(", "scope", ",", "templates", ")", ";", "}" ]
Returns a new scope that includes the given template names for type resolution purposes.
[ "Returns", "a", "new", "scope", "that", "includes", "the", "given", "template", "names", "for", "type", "resolution", "purposes", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L2267-L2270
24,433
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.saveContents
@SuppressWarnings("unchecked") @GwtIncompatible("ObjectOutputStream") public void saveContents(ObjectOutputStream out) throws IOException { out.writeObject(eachRefTypeIndexedByProperty); out.writeObject(interfaceToImplementors); out.writeObject(typesIndexedByProperty); }
java
@SuppressWarnings("unchecked") @GwtIncompatible("ObjectOutputStream") public void saveContents(ObjectOutputStream out) throws IOException { out.writeObject(eachRefTypeIndexedByProperty); out.writeObject(interfaceToImplementors); out.writeObject(typesIndexedByProperty); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "GwtIncompatible", "(", "\"ObjectOutputStream\"", ")", "public", "void", "saveContents", "(", "ObjectOutputStream", "out", ")", "throws", "IOException", "{", "out", ".", "writeObject", "(", "eachRefTypeIndexedByProperty", ")", ";", "out", ".", "writeObject", "(", "interfaceToImplementors", ")", ";", "out", ".", "writeObject", "(", "typesIndexedByProperty", ")", ";", "}" ]
Saves the derived state. Note: This should be only used when serializing the compiler state and needs to be done at the end, after serializing CompilerState.
[ "Saves", "the", "derived", "state", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L2332-L2338
24,434
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.restoreContents
@SuppressWarnings("unchecked") @GwtIncompatible("ObjectInputStream") public void restoreContents(ObjectInputStream in) throws IOException, ClassNotFoundException { eachRefTypeIndexedByProperty = (Map<String, Map<String, ObjectType>>) in.readObject(); interfaceToImplementors = (Multimap<String, FunctionType>) in.readObject(); typesIndexedByProperty = (Multimap<String, JSType>) in.readObject(); }
java
@SuppressWarnings("unchecked") @GwtIncompatible("ObjectInputStream") public void restoreContents(ObjectInputStream in) throws IOException, ClassNotFoundException { eachRefTypeIndexedByProperty = (Map<String, Map<String, ObjectType>>) in.readObject(); interfaceToImplementors = (Multimap<String, FunctionType>) in.readObject(); typesIndexedByProperty = (Multimap<String, JSType>) in.readObject(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "GwtIncompatible", "(", "\"ObjectInputStream\"", ")", "public", "void", "restoreContents", "(", "ObjectInputStream", "in", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "eachRefTypeIndexedByProperty", "=", "(", "Map", "<", "String", ",", "Map", "<", "String", ",", "ObjectType", ">", ">", ")", "in", ".", "readObject", "(", ")", ";", "interfaceToImplementors", "=", "(", "Multimap", "<", "String", ",", "FunctionType", ">", ")", "in", ".", "readObject", "(", ")", ";", "typesIndexedByProperty", "=", "(", "Multimap", "<", "String", ",", "JSType", ">", ")", "in", ".", "readObject", "(", ")", ";", "}" ]
Restores the derived state. Note: This should be only used when deserializing the compiler state and needs to be done at the end, after deserializing CompilerState.
[ "Restores", "the", "derived", "state", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L2346-L2352
24,435
google/closure-compiler
src/com/google/javascript/jscomp/PolymerPassSuppressBehaviors.java
PolymerPassSuppressBehaviors.suppressBehavior
private void suppressBehavior(Node behaviorValue, Node reportNode) { if (behaviorValue == null) { compiler.report(JSError.make(reportNode, PolymerPassErrors.POLYMER_UNQUALIFIED_BEHAVIOR)); return; } if (behaviorValue.isArrayLit()) { for (Node child : behaviorValue.children()) { suppressBehavior(child, behaviorValue); } } else if (behaviorValue.isObjectLit()) { stripPropertyTypes(behaviorValue); addBehaviorSuppressions(behaviorValue); } }
java
private void suppressBehavior(Node behaviorValue, Node reportNode) { if (behaviorValue == null) { compiler.report(JSError.make(reportNode, PolymerPassErrors.POLYMER_UNQUALIFIED_BEHAVIOR)); return; } if (behaviorValue.isArrayLit()) { for (Node child : behaviorValue.children()) { suppressBehavior(child, behaviorValue); } } else if (behaviorValue.isObjectLit()) { stripPropertyTypes(behaviorValue); addBehaviorSuppressions(behaviorValue); } }
[ "private", "void", "suppressBehavior", "(", "Node", "behaviorValue", ",", "Node", "reportNode", ")", "{", "if", "(", "behaviorValue", "==", "null", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "reportNode", ",", "PolymerPassErrors", ".", "POLYMER_UNQUALIFIED_BEHAVIOR", ")", ")", ";", "return", ";", "}", "if", "(", "behaviorValue", ".", "isArrayLit", "(", ")", ")", "{", "for", "(", "Node", "child", ":", "behaviorValue", ".", "children", "(", ")", ")", "{", "suppressBehavior", "(", "child", ",", "behaviorValue", ")", ";", "}", "}", "else", "if", "(", "behaviorValue", ".", "isObjectLit", "(", ")", ")", "{", "stripPropertyTypes", "(", "behaviorValue", ")", ";", "addBehaviorSuppressions", "(", "behaviorValue", ")", ";", "}", "}" ]
Strip property type annotations and add suppressions on functions.
[ "Strip", "property", "type", "annotations", "and", "add", "suppressions", "on", "functions", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerPassSuppressBehaviors.java#L58-L72
24,436
google/closure-compiler
src/com/google/debugging/sourcemap/Base64VLQ.java
Base64VLQ.encode
public static void encode(Appendable out, int value) throws IOException { value = toVLQSigned(value); do { int digit = value & VLQ_BASE_MASK; value >>>= VLQ_BASE_SHIFT; if (value > 0) { digit |= VLQ_CONTINUATION_BIT; } out.append(Base64.toBase64(digit)); } while (value > 0); }
java
public static void encode(Appendable out, int value) throws IOException { value = toVLQSigned(value); do { int digit = value & VLQ_BASE_MASK; value >>>= VLQ_BASE_SHIFT; if (value > 0) { digit |= VLQ_CONTINUATION_BIT; } out.append(Base64.toBase64(digit)); } while (value > 0); }
[ "public", "static", "void", "encode", "(", "Appendable", "out", ",", "int", "value", ")", "throws", "IOException", "{", "value", "=", "toVLQSigned", "(", "value", ")", ";", "do", "{", "int", "digit", "=", "value", "&", "VLQ_BASE_MASK", ";", "value", ">>>=", "VLQ_BASE_SHIFT", ";", "if", "(", "value", ">", "0", ")", "{", "digit", "|=", "VLQ_CONTINUATION_BIT", ";", "}", "out", ".", "append", "(", "Base64", ".", "toBase64", "(", "digit", ")", ")", ";", "}", "while", "(", "value", ">", "0", ")", ";", "}" ]
Writes a VLQ encoded value to the provide appendable. @throws IOException
[ "Writes", "a", "VLQ", "encoded", "value", "to", "the", "provide", "appendable", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/Base64VLQ.java#L72-L83
24,437
google/closure-compiler
src/com/google/debugging/sourcemap/Base64VLQ.java
Base64VLQ.decode
public static int decode(CharIterator in) { int result = 0; boolean continuation; int shift = 0; do { char c = in.next(); int digit = Base64.fromBase64(c); continuation = (digit & VLQ_CONTINUATION_BIT) != 0; digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift = shift + VLQ_BASE_SHIFT; } while (continuation); return fromVLQSigned(result); }
java
public static int decode(CharIterator in) { int result = 0; boolean continuation; int shift = 0; do { char c = in.next(); int digit = Base64.fromBase64(c); continuation = (digit & VLQ_CONTINUATION_BIT) != 0; digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift = shift + VLQ_BASE_SHIFT; } while (continuation); return fromVLQSigned(result); }
[ "public", "static", "int", "decode", "(", "CharIterator", "in", ")", "{", "int", "result", "=", "0", ";", "boolean", "continuation", ";", "int", "shift", "=", "0", ";", "do", "{", "char", "c", "=", "in", ".", "next", "(", ")", ";", "int", "digit", "=", "Base64", ".", "fromBase64", "(", "c", ")", ";", "continuation", "=", "(", "digit", "&", "VLQ_CONTINUATION_BIT", ")", "!=", "0", ";", "digit", "&=", "VLQ_BASE_MASK", ";", "result", "=", "result", "+", "(", "digit", "<<", "shift", ")", ";", "shift", "=", "shift", "+", "VLQ_BASE_SHIFT", ";", "}", "while", "(", "continuation", ")", ";", "return", "fromVLQSigned", "(", "result", ")", ";", "}" ]
Decodes the next VLQValue from the provided CharIterator.
[ "Decodes", "the", "next", "VLQValue", "from", "the", "provided", "CharIterator", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/Base64VLQ.java#L98-L112
24,438
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.getAllSymbolsSorted
public List<Symbol> getAllSymbolsSorted() { List<Symbol> sortedSymbols = getNaturalSymbolOrdering().sortedCopy(symbols.values()); return sortedSymbols; }
java
public List<Symbol> getAllSymbolsSorted() { List<Symbol> sortedSymbols = getNaturalSymbolOrdering().sortedCopy(symbols.values()); return sortedSymbols; }
[ "public", "List", "<", "Symbol", ">", "getAllSymbolsSorted", "(", ")", "{", "List", "<", "Symbol", ">", "sortedSymbols", "=", "getNaturalSymbolOrdering", "(", ")", ".", "sortedCopy", "(", "symbols", ".", "values", "(", ")", ")", ";", "return", "sortedSymbols", ";", "}" ]
Get the symbols in their natural ordering. Always returns a mutable list.
[ "Get", "the", "symbols", "in", "their", "natural", "ordering", ".", "Always", "returns", "a", "mutable", "list", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L145-L148
24,439
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.getSymbolForScope
public Symbol getSymbolForScope(SymbolScope scope) { if (scope.getSymbolForScope() == null) { scope.setSymbolForScope(findSymbolForScope(scope)); } return scope.getSymbolForScope(); }
java
public Symbol getSymbolForScope(SymbolScope scope) { if (scope.getSymbolForScope() == null) { scope.setSymbolForScope(findSymbolForScope(scope)); } return scope.getSymbolForScope(); }
[ "public", "Symbol", "getSymbolForScope", "(", "SymbolScope", "scope", ")", "{", "if", "(", "scope", ".", "getSymbolForScope", "(", ")", "==", "null", ")", "{", "scope", ".", "setSymbolForScope", "(", "findSymbolForScope", "(", "scope", ")", ")", ";", "}", "return", "scope", ".", "getSymbolForScope", "(", ")", ";", "}" ]
All local scopes are associated with a function, and some functions are associated with a symbol. Returns the symbol associated with the given scope.
[ "All", "local", "scopes", "are", "associated", "with", "a", "function", "and", "some", "functions", "are", "associated", "with", "a", "symbol", ".", "Returns", "the", "symbol", "associated", "with", "the", "given", "scope", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L246-L251
24,440
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.findSymbolForScope
private Symbol findSymbolForScope(SymbolScope scope) { Node rootNode = scope.getRootNode(); if (rootNode.getParent() == null) { return globalScope.getSlot(GLOBAL_THIS); } if (!rootNode.isFunction()) { return null; } String name = NodeUtil.getBestLValueName(NodeUtil.getBestLValue(rootNode)); return name == null ? null : scope.getParentScope().getQualifiedSlot(name); }
java
private Symbol findSymbolForScope(SymbolScope scope) { Node rootNode = scope.getRootNode(); if (rootNode.getParent() == null) { return globalScope.getSlot(GLOBAL_THIS); } if (!rootNode.isFunction()) { return null; } String name = NodeUtil.getBestLValueName(NodeUtil.getBestLValue(rootNode)); return name == null ? null : scope.getParentScope().getQualifiedSlot(name); }
[ "private", "Symbol", "findSymbolForScope", "(", "SymbolScope", "scope", ")", "{", "Node", "rootNode", "=", "scope", ".", "getRootNode", "(", ")", ";", "if", "(", "rootNode", ".", "getParent", "(", ")", "==", "null", ")", "{", "return", "globalScope", ".", "getSlot", "(", "GLOBAL_THIS", ")", ";", "}", "if", "(", "!", "rootNode", ".", "isFunction", "(", ")", ")", "{", "return", "null", ";", "}", "String", "name", "=", "NodeUtil", ".", "getBestLValueName", "(", "NodeUtil", ".", "getBestLValue", "(", "rootNode", ")", ")", ";", "return", "name", "==", "null", "?", "null", ":", "scope", ".", "getParentScope", "(", ")", ".", "getQualifiedSlot", "(", "name", ")", ";", "}" ]
Find the symbol associated with the given scope. Notice that we won't always be able to figure out this association dynamically, so sometimes we'll just create the association when we create the scope.
[ "Find", "the", "symbol", "associated", "with", "the", "given", "scope", ".", "Notice", "that", "we", "won", "t", "always", "be", "able", "to", "figure", "out", "this", "association", "dynamically", "so", "sometimes", "we", "ll", "just", "create", "the", "association", "when", "we", "create", "the", "scope", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L258-L270
24,441
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.getSymbolDeclaredBy
public Symbol getSymbolDeclaredBy(FunctionType fn) { checkState(fn.isConstructor() || fn.isInterface()); ObjectType instanceType = fn.getInstanceType(); return getSymbolForName(fn.getSource(), instanceType.getReferenceName()); }
java
public Symbol getSymbolDeclaredBy(FunctionType fn) { checkState(fn.isConstructor() || fn.isInterface()); ObjectType instanceType = fn.getInstanceType(); return getSymbolForName(fn.getSource(), instanceType.getReferenceName()); }
[ "public", "Symbol", "getSymbolDeclaredBy", "(", "FunctionType", "fn", ")", "{", "checkState", "(", "fn", ".", "isConstructor", "(", ")", "||", "fn", ".", "isInterface", "(", ")", ")", ";", "ObjectType", "instanceType", "=", "fn", ".", "getInstanceType", "(", ")", ";", "return", "getSymbolForName", "(", "fn", ".", "getSource", "(", ")", ",", "instanceType", ".", "getReferenceName", "(", ")", ")", ";", "}" ]
Gets the symbol for the given constructor or interface.
[ "Gets", "the", "symbol", "for", "the", "given", "constructor", "or", "interface", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L288-L292
24,442
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.getSymbolForInstancesOf
public Symbol getSymbolForInstancesOf(Symbol sym) { FunctionType fn = sym.getFunctionType(); if (fn != null && fn.isNominalConstructor()) { return getSymbolForInstancesOf(fn); } return null; }
java
public Symbol getSymbolForInstancesOf(Symbol sym) { FunctionType fn = sym.getFunctionType(); if (fn != null && fn.isNominalConstructor()) { return getSymbolForInstancesOf(fn); } return null; }
[ "public", "Symbol", "getSymbolForInstancesOf", "(", "Symbol", "sym", ")", "{", "FunctionType", "fn", "=", "sym", ".", "getFunctionType", "(", ")", ";", "if", "(", "fn", "!=", "null", "&&", "fn", ".", "isNominalConstructor", "(", ")", ")", "{", "return", "getSymbolForInstancesOf", "(", "fn", ")", ";", "}", "return", "null", ";", "}" ]
Gets the symbol for the prototype if this is the symbol for a constructor or interface.
[ "Gets", "the", "symbol", "for", "the", "prototype", "if", "this", "is", "the", "symbol", "for", "a", "constructor", "or", "interface", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L300-L306
24,443
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.getSymbolForInstancesOf
public Symbol getSymbolForInstancesOf(FunctionType fn) { checkState(fn.isConstructor() || fn.isInterface()); ObjectType pType = fn.getPrototype(); return getSymbolForName(fn.getSource(), pType.getReferenceName()); }
java
public Symbol getSymbolForInstancesOf(FunctionType fn) { checkState(fn.isConstructor() || fn.isInterface()); ObjectType pType = fn.getPrototype(); return getSymbolForName(fn.getSource(), pType.getReferenceName()); }
[ "public", "Symbol", "getSymbolForInstancesOf", "(", "FunctionType", "fn", ")", "{", "checkState", "(", "fn", ".", "isConstructor", "(", ")", "||", "fn", ".", "isInterface", "(", ")", ")", ";", "ObjectType", "pType", "=", "fn", ".", "getPrototype", "(", ")", ";", "return", "getSymbolForName", "(", "fn", ".", "getSource", "(", ")", ",", "pType", ".", "getReferenceName", "(", ")", ")", ";", "}" ]
Gets the symbol for the prototype of the given constructor or interface.
[ "Gets", "the", "symbol", "for", "the", "prototype", "of", "the", "given", "constructor", "or", "interface", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L309-L313
24,444
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.getAllSymbolsForType
public List<Symbol> getAllSymbolsForType(JSType type) { if (type == null) { return ImmutableList.of(); } UnionType unionType = type.toMaybeUnionType(); if (unionType != null) { List<Symbol> result = new ArrayList<>(2); for (JSType alt : unionType.getAlternates()) { // Our type system never has nested unions. Symbol altSym = getSymbolForTypeHelper(alt, true); if (altSym != null) { result.add(altSym); } } return result; } Symbol result = getSymbolForTypeHelper(type, true); return result == null ? ImmutableList.of() : ImmutableList.of(result); }
java
public List<Symbol> getAllSymbolsForType(JSType type) { if (type == null) { return ImmutableList.of(); } UnionType unionType = type.toMaybeUnionType(); if (unionType != null) { List<Symbol> result = new ArrayList<>(2); for (JSType alt : unionType.getAlternates()) { // Our type system never has nested unions. Symbol altSym = getSymbolForTypeHelper(alt, true); if (altSym != null) { result.add(altSym); } } return result; } Symbol result = getSymbolForTypeHelper(type, true); return result == null ? ImmutableList.of() : ImmutableList.of(result); }
[ "public", "List", "<", "Symbol", ">", "getAllSymbolsForType", "(", "JSType", "type", ")", "{", "if", "(", "type", "==", "null", ")", "{", "return", "ImmutableList", ".", "of", "(", ")", ";", "}", "UnionType", "unionType", "=", "type", ".", "toMaybeUnionType", "(", ")", ";", "if", "(", "unionType", "!=", "null", ")", "{", "List", "<", "Symbol", ">", "result", "=", "new", "ArrayList", "<>", "(", "2", ")", ";", "for", "(", "JSType", "alt", ":", "unionType", ".", "getAlternates", "(", ")", ")", "{", "// Our type system never has nested unions.", "Symbol", "altSym", "=", "getSymbolForTypeHelper", "(", "alt", ",", "true", ")", ";", "if", "(", "altSym", "!=", "null", ")", "{", "result", ".", "add", "(", "altSym", ")", ";", "}", "}", "return", "result", ";", "}", "Symbol", "result", "=", "getSymbolForTypeHelper", "(", "type", ",", "true", ")", ";", "return", "result", "==", "null", "?", "ImmutableList", ".", "of", "(", ")", ":", "ImmutableList", ".", "of", "(", "result", ")", ";", "}" ]
Gets all symbols associated with the given type. For union types, this may be multiple symbols. For instance types, this will return the constructor of that instance.
[ "Gets", "all", "symbols", "associated", "with", "the", "given", "type", ".", "For", "union", "types", "this", "may", "be", "multiple", "symbols", ".", "For", "instance", "types", "this", "will", "return", "the", "constructor", "of", "that", "instance", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L331-L350
24,445
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.getSymbolForTypeHelper
private Symbol getSymbolForTypeHelper(JSType type, boolean linkToCtor) { if (type == null) { return null; } if (type.isGlobalThisType()) { return globalScope.getSlot(GLOBAL_THIS); } else if (type.isNominalConstructor()) { return linkToCtor ? globalScope.getSlot("Function") : getSymbolDeclaredBy(type.toMaybeFunctionType()); } else if (type.isFunctionPrototypeType()) { FunctionType ownerFn = ((ObjectType) type).getOwnerFunction(); if (!ownerFn.isConstructor() && !ownerFn.isInterface()) { return null; } return linkToCtor ? getSymbolDeclaredBy(ownerFn) : getSymbolForInstancesOf(ownerFn); } else if (type.isInstanceType()) { FunctionType ownerFn = ((ObjectType) type).getConstructor(); return linkToCtor ? getSymbolDeclaredBy(ownerFn) : getSymbolForInstancesOf(ownerFn); } else if (type.isFunctionType()) { return linkToCtor ? globalScope.getSlot("Function") : globalScope.getQualifiedSlot("Function.prototype"); } else if (type.autoboxesTo() != null) { return getSymbolForTypeHelper(type.autoboxesTo(), linkToCtor); } else { return null; } }
java
private Symbol getSymbolForTypeHelper(JSType type, boolean linkToCtor) { if (type == null) { return null; } if (type.isGlobalThisType()) { return globalScope.getSlot(GLOBAL_THIS); } else if (type.isNominalConstructor()) { return linkToCtor ? globalScope.getSlot("Function") : getSymbolDeclaredBy(type.toMaybeFunctionType()); } else if (type.isFunctionPrototypeType()) { FunctionType ownerFn = ((ObjectType) type).getOwnerFunction(); if (!ownerFn.isConstructor() && !ownerFn.isInterface()) { return null; } return linkToCtor ? getSymbolDeclaredBy(ownerFn) : getSymbolForInstancesOf(ownerFn); } else if (type.isInstanceType()) { FunctionType ownerFn = ((ObjectType) type).getConstructor(); return linkToCtor ? getSymbolDeclaredBy(ownerFn) : getSymbolForInstancesOf(ownerFn); } else if (type.isFunctionType()) { return linkToCtor ? globalScope.getSlot("Function") : globalScope.getQualifiedSlot("Function.prototype"); } else if (type.autoboxesTo() != null) { return getSymbolForTypeHelper(type.autoboxesTo(), linkToCtor); } else { return null; } }
[ "private", "Symbol", "getSymbolForTypeHelper", "(", "JSType", "type", ",", "boolean", "linkToCtor", ")", "{", "if", "(", "type", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "type", ".", "isGlobalThisType", "(", ")", ")", "{", "return", "globalScope", ".", "getSlot", "(", "GLOBAL_THIS", ")", ";", "}", "else", "if", "(", "type", ".", "isNominalConstructor", "(", ")", ")", "{", "return", "linkToCtor", "?", "globalScope", ".", "getSlot", "(", "\"Function\"", ")", ":", "getSymbolDeclaredBy", "(", "type", ".", "toMaybeFunctionType", "(", ")", ")", ";", "}", "else", "if", "(", "type", ".", "isFunctionPrototypeType", "(", ")", ")", "{", "FunctionType", "ownerFn", "=", "(", "(", "ObjectType", ")", "type", ")", ".", "getOwnerFunction", "(", ")", ";", "if", "(", "!", "ownerFn", ".", "isConstructor", "(", ")", "&&", "!", "ownerFn", ".", "isInterface", "(", ")", ")", "{", "return", "null", ";", "}", "return", "linkToCtor", "?", "getSymbolDeclaredBy", "(", "ownerFn", ")", ":", "getSymbolForInstancesOf", "(", "ownerFn", ")", ";", "}", "else", "if", "(", "type", ".", "isInstanceType", "(", ")", ")", "{", "FunctionType", "ownerFn", "=", "(", "(", "ObjectType", ")", "type", ")", ".", "getConstructor", "(", ")", ";", "return", "linkToCtor", "?", "getSymbolDeclaredBy", "(", "ownerFn", ")", ":", "getSymbolForInstancesOf", "(", "ownerFn", ")", ";", "}", "else", "if", "(", "type", ".", "isFunctionType", "(", ")", ")", "{", "return", "linkToCtor", "?", "globalScope", ".", "getSlot", "(", "\"Function\"", ")", ":", "globalScope", ".", "getQualifiedSlot", "(", "\"Function.prototype\"", ")", ";", "}", "else", "if", "(", "type", ".", "autoboxesTo", "(", ")", "!=", "null", ")", "{", "return", "getSymbolForTypeHelper", "(", "type", ".", "autoboxesTo", "(", ")", ",", "linkToCtor", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets all symbols associated with the given type. If there is more that one symbol associated with the given type, return null. @param type The type. @param linkToCtor If true, we should link instance types back to their constructor function. If false, we should link instance types back to their prototype. See the comments at the top of this file for more information on how our internal type system is more granular than Symbols.
[ "Gets", "all", "symbols", "associated", "with", "the", "given", "type", ".", "If", "there", "is", "more", "that", "one", "symbol", "associated", "with", "the", "given", "type", "return", "null", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L362-L391
24,446
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.findScopes
void findScopes(Node externs, Node root) { NodeTraversal.traverseRoots( compiler, new NodeTraversal.AbstractScopedCallback() { @Override public void enterScope(NodeTraversal t) { createScopeFrom(t.getScope()); } @Override public void visit(NodeTraversal t, Node n, Node p) {} }, externs, root); }
java
void findScopes(Node externs, Node root) { NodeTraversal.traverseRoots( compiler, new NodeTraversal.AbstractScopedCallback() { @Override public void enterScope(NodeTraversal t) { createScopeFrom(t.getScope()); } @Override public void visit(NodeTraversal t, Node n, Node p) {} }, externs, root); }
[ "void", "findScopes", "(", "Node", "externs", ",", "Node", "root", ")", "{", "NodeTraversal", ".", "traverseRoots", "(", "compiler", ",", "new", "NodeTraversal", ".", "AbstractScopedCallback", "(", ")", "{", "@", "Override", "public", "void", "enterScope", "(", "NodeTraversal", "t", ")", "{", "createScopeFrom", "(", "t", ".", "getScope", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "visit", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "p", ")", "{", "}", "}", ",", "externs", ",", "root", ")", ";", "}" ]
Finds all the scopes and adds them to this symbol table.
[ "Finds", "all", "the", "scopes", "and", "adds", "them", "to", "this", "symbol", "table", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L445-L459
24,447
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.addAnonymousFunctions
public void addAnonymousFunctions() { TreeSet<SymbolScope> scopes = new TreeSet<>(lexicalScopeOrdering); for (SymbolScope scope : getAllScopes()) { if (scope.isLexicalScope()) { scopes.add(scope); } } for (SymbolScope scope : scopes) { addAnonymousFunctionsInScope(scope); } }
java
public void addAnonymousFunctions() { TreeSet<SymbolScope> scopes = new TreeSet<>(lexicalScopeOrdering); for (SymbolScope scope : getAllScopes()) { if (scope.isLexicalScope()) { scopes.add(scope); } } for (SymbolScope scope : scopes) { addAnonymousFunctionsInScope(scope); } }
[ "public", "void", "addAnonymousFunctions", "(", ")", "{", "TreeSet", "<", "SymbolScope", ">", "scopes", "=", "new", "TreeSet", "<>", "(", "lexicalScopeOrdering", ")", ";", "for", "(", "SymbolScope", "scope", ":", "getAllScopes", "(", ")", ")", "{", "if", "(", "scope", ".", "isLexicalScope", "(", ")", ")", "{", "scopes", ".", "add", "(", "scope", ")", ";", "}", "}", "for", "(", "SymbolScope", "scope", ":", "scopes", ")", "{", "addAnonymousFunctionsInScope", "(", "scope", ")", ";", "}", "}" ]
Finds anonymous functions in local scopes, and gives them names and symbols. They will show up as local variables with names "function%0", "function%1", etc.
[ "Finds", "anonymous", "functions", "in", "local", "scopes", "and", "gives", "them", "names", "and", "symbols", ".", "They", "will", "show", "up", "as", "local", "variables", "with", "names", "function%0", "function%1", "etc", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L470-L481
24,448
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.isAnySymbolDeclared
private Symbol isAnySymbolDeclared(String name, Node declNode, SymbolScope scope) { Symbol sym = symbols.get(declNode, name); if (sym == null) { // Sometimes, our symbol tables will disagree on where the // declaration node should be. In the rare case where this happens, // trust the existing symbol. // See SymbolTableTest#testDeclarationDisagreement. return scope.ownSymbols.get(name); } return sym; }
java
private Symbol isAnySymbolDeclared(String name, Node declNode, SymbolScope scope) { Symbol sym = symbols.get(declNode, name); if (sym == null) { // Sometimes, our symbol tables will disagree on where the // declaration node should be. In the rare case where this happens, // trust the existing symbol. // See SymbolTableTest#testDeclarationDisagreement. return scope.ownSymbols.get(name); } return sym; }
[ "private", "Symbol", "isAnySymbolDeclared", "(", "String", "name", ",", "Node", "declNode", ",", "SymbolScope", "scope", ")", "{", "Symbol", "sym", "=", "symbols", ".", "get", "(", "declNode", ",", "name", ")", ";", "if", "(", "sym", "==", "null", ")", "{", "// Sometimes, our symbol tables will disagree on where the", "// declaration node should be. In the rare case where this happens,", "// trust the existing symbol.", "// See SymbolTableTest#testDeclarationDisagreement.", "return", "scope", ".", "ownSymbols", ".", "get", "(", "name", ")", ";", "}", "return", "sym", ";", "}" ]
Checks if any symbol is already declared at the given node and scope for the given name. If so, returns it.
[ "Checks", "if", "any", "symbol", "is", "already", "declared", "at", "the", "given", "node", "and", "scope", "for", "the", "given", "name", ".", "If", "so", "returns", "it", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L562-L572
24,449
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.findBestDeclToAdd
private <S extends StaticSlot, R extends StaticRef> StaticRef findBestDeclToAdd( StaticSymbolTable<S, R> otherSymbolTable, S slot) { StaticRef decl = slot.getDeclaration(); if (isGoodRefToAdd(decl)) { return decl; } for (R ref : otherSymbolTable.getReferences(slot)) { if (isGoodRefToAdd(ref)) { return ref; } } return null; }
java
private <S extends StaticSlot, R extends StaticRef> StaticRef findBestDeclToAdd( StaticSymbolTable<S, R> otherSymbolTable, S slot) { StaticRef decl = slot.getDeclaration(); if (isGoodRefToAdd(decl)) { return decl; } for (R ref : otherSymbolTable.getReferences(slot)) { if (isGoodRefToAdd(ref)) { return ref; } } return null; }
[ "private", "<", "S", "extends", "StaticSlot", ",", "R", "extends", "StaticRef", ">", "StaticRef", "findBestDeclToAdd", "(", "StaticSymbolTable", "<", "S", ",", "R", ">", "otherSymbolTable", ",", "S", "slot", ")", "{", "StaticRef", "decl", "=", "slot", ".", "getDeclaration", "(", ")", ";", "if", "(", "isGoodRefToAdd", "(", "decl", ")", ")", "{", "return", "decl", ";", "}", "for", "(", "R", "ref", ":", "otherSymbolTable", ".", "getReferences", "(", "slot", ")", ")", "{", "if", "(", "isGoodRefToAdd", "(", "ref", ")", ")", "{", "return", "ref", ";", "}", "}", "return", "null", ";", "}" ]
Helper for addSymbolsFrom, to determine the best declaration spot.
[ "Helper", "for", "addSymbolsFrom", "to", "determine", "the", "best", "declaration", "spot", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L575-L589
24,450
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.mergeSymbol
private void mergeSymbol(Symbol from, Symbol to) { for (Node nodeToMove : from.references.keySet()) { if (!nodeToMove.equals(from.getDeclarationNode())) { to.defineReferenceAt(nodeToMove); } } removeSymbol(from); }
java
private void mergeSymbol(Symbol from, Symbol to) { for (Node nodeToMove : from.references.keySet()) { if (!nodeToMove.equals(from.getDeclarationNode())) { to.defineReferenceAt(nodeToMove); } } removeSymbol(from); }
[ "private", "void", "mergeSymbol", "(", "Symbol", "from", ",", "Symbol", "to", ")", "{", "for", "(", "Node", "nodeToMove", ":", "from", ".", "references", ".", "keySet", "(", ")", ")", "{", "if", "(", "!", "nodeToMove", ".", "equals", "(", "from", ".", "getDeclarationNode", "(", ")", ")", ")", "{", "to", ".", "defineReferenceAt", "(", "nodeToMove", ")", ";", "}", "}", "removeSymbol", "(", "from", ")", ";", "}" ]
Merges 'from' symbol to 'to' symbol by moving all references to point to the 'to' symbol and removing 'from' symbol.
[ "Merges", "from", "symbol", "to", "to", "symbol", "by", "moving", "all", "references", "to", "point", "to", "the", "to", "symbol", "and", "removing", "from", "symbol", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L653-L660
24,451
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.pruneOrphanedNames
void pruneOrphanedNames() { nextSymbol: for (Symbol s : getAllSymbols()) { if (s.isProperty()) { continue; } String currentName = s.getName(); int dot = -1; while (-1 != (dot = currentName.lastIndexOf('.'))) { currentName = currentName.substring(0, dot); Symbol owner = s.scope.getQualifiedSlot(currentName); if (owner != null && getType(owner) != null && (getType(owner).isNominalConstructor() || getType(owner).isFunctionPrototypeType() || getType(owner).isEnumType())) { removeSymbol(s); continue nextSymbol; } } } }
java
void pruneOrphanedNames() { nextSymbol: for (Symbol s : getAllSymbols()) { if (s.isProperty()) { continue; } String currentName = s.getName(); int dot = -1; while (-1 != (dot = currentName.lastIndexOf('.'))) { currentName = currentName.substring(0, dot); Symbol owner = s.scope.getQualifiedSlot(currentName); if (owner != null && getType(owner) != null && (getType(owner).isNominalConstructor() || getType(owner).isFunctionPrototypeType() || getType(owner).isEnumType())) { removeSymbol(s); continue nextSymbol; } } } }
[ "void", "pruneOrphanedNames", "(", ")", "{", "nextSymbol", ":", "for", "(", "Symbol", "s", ":", "getAllSymbols", "(", ")", ")", "{", "if", "(", "s", ".", "isProperty", "(", ")", ")", "{", "continue", ";", "}", "String", "currentName", "=", "s", ".", "getName", "(", ")", ";", "int", "dot", "=", "-", "1", ";", "while", "(", "-", "1", "!=", "(", "dot", "=", "currentName", ".", "lastIndexOf", "(", "'", "'", ")", ")", ")", "{", "currentName", "=", "currentName", ".", "substring", "(", "0", ",", "dot", ")", ";", "Symbol", "owner", "=", "s", ".", "scope", ".", "getQualifiedSlot", "(", "currentName", ")", ";", "if", "(", "owner", "!=", "null", "&&", "getType", "(", "owner", ")", "!=", "null", "&&", "(", "getType", "(", "owner", ")", ".", "isNominalConstructor", "(", ")", "||", "getType", "(", "owner", ")", ".", "isFunctionPrototypeType", "(", ")", "||", "getType", "(", "owner", ")", ".", "isEnumType", "(", ")", ")", ")", "{", "removeSymbol", "(", "s", ")", ";", "continue", "nextSymbol", ";", "}", "}", "}", "}" ]
Removes symbols where the namespace they're on has been removed. <p>After filling property scopes, we may have two symbols represented in different ways. For example, "A.superClass_.foo" and B.prototype.foo". <p>This resolves that ambiguity by pruning the duplicates. If we have a lexical symbol with a constructor in its property chain, then we assume there's also a property path to this symbol. In other words, we can remove "A.superClass_.foo" because it's rooted at "A", and we built a property scope for "A" above.
[ "Removes", "symbols", "where", "the", "namespace", "they", "re", "on", "has", "been", "removed", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L900-L923
24,452
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.fillJSDocInfo
void fillJSDocInfo(Node externs, Node root) { NodeTraversal.traverseRoots( compiler, new JSDocInfoCollector(compiler.getTypeRegistry()), externs, root); // Create references to parameters in the JSDoc. for (Symbol sym : getAllSymbols()) { JSDocInfo info = sym.getJSDocInfo(); if (info == null) { continue; } for (Marker marker : info.getMarkers()) { SourcePosition<Node> pos = marker.getNameNode(); if (pos == null) { continue; } Node paramNode = pos.getItem(); String name = paramNode.getString(); Symbol param = getParameterInFunction(sym, name); if (param == null) { // There is no reference to this parameter in the actual JavaScript // code, so we'll try to create a special JsDoc-only symbol in // a JsDoc-only scope. SourcePosition<Node> typePos = marker.getType(); JSType type = null; if (typePos != null) { type = typePos.getItem().getJSType(); } if (sym.docScope == null) { sym.docScope = new SymbolScope( null /* root */, null /* parent scope */, null /* type of this */, sym); } // Check to make sure there's no existing symbol. In theory, this // should never happen, but we check anyway and fail silently // if our assumptions are wrong. (We do not want to put the symbol // table into an invalid state). Symbol existingSymbol = isAnySymbolDeclared(name, paramNode, sym.docScope); if (existingSymbol == null) { declareSymbol(name, type, type == null, sym.docScope, paramNode, null /* info */); } } else { param.defineReferenceAt(paramNode); } } } }
java
void fillJSDocInfo(Node externs, Node root) { NodeTraversal.traverseRoots( compiler, new JSDocInfoCollector(compiler.getTypeRegistry()), externs, root); // Create references to parameters in the JSDoc. for (Symbol sym : getAllSymbols()) { JSDocInfo info = sym.getJSDocInfo(); if (info == null) { continue; } for (Marker marker : info.getMarkers()) { SourcePosition<Node> pos = marker.getNameNode(); if (pos == null) { continue; } Node paramNode = pos.getItem(); String name = paramNode.getString(); Symbol param = getParameterInFunction(sym, name); if (param == null) { // There is no reference to this parameter in the actual JavaScript // code, so we'll try to create a special JsDoc-only symbol in // a JsDoc-only scope. SourcePosition<Node> typePos = marker.getType(); JSType type = null; if (typePos != null) { type = typePos.getItem().getJSType(); } if (sym.docScope == null) { sym.docScope = new SymbolScope( null /* root */, null /* parent scope */, null /* type of this */, sym); } // Check to make sure there's no existing symbol. In theory, this // should never happen, but we check anyway and fail silently // if our assumptions are wrong. (We do not want to put the symbol // table into an invalid state). Symbol existingSymbol = isAnySymbolDeclared(name, paramNode, sym.docScope); if (existingSymbol == null) { declareSymbol(name, type, type == null, sym.docScope, paramNode, null /* info */); } } else { param.defineReferenceAt(paramNode); } } } }
[ "void", "fillJSDocInfo", "(", "Node", "externs", ",", "Node", "root", ")", "{", "NodeTraversal", ".", "traverseRoots", "(", "compiler", ",", "new", "JSDocInfoCollector", "(", "compiler", ".", "getTypeRegistry", "(", ")", ")", ",", "externs", ",", "root", ")", ";", "// Create references to parameters in the JSDoc.", "for", "(", "Symbol", "sym", ":", "getAllSymbols", "(", ")", ")", "{", "JSDocInfo", "info", "=", "sym", ".", "getJSDocInfo", "(", ")", ";", "if", "(", "info", "==", "null", ")", "{", "continue", ";", "}", "for", "(", "Marker", "marker", ":", "info", ".", "getMarkers", "(", ")", ")", "{", "SourcePosition", "<", "Node", ">", "pos", "=", "marker", ".", "getNameNode", "(", ")", ";", "if", "(", "pos", "==", "null", ")", "{", "continue", ";", "}", "Node", "paramNode", "=", "pos", ".", "getItem", "(", ")", ";", "String", "name", "=", "paramNode", ".", "getString", "(", ")", ";", "Symbol", "param", "=", "getParameterInFunction", "(", "sym", ",", "name", ")", ";", "if", "(", "param", "==", "null", ")", "{", "// There is no reference to this parameter in the actual JavaScript", "// code, so we'll try to create a special JsDoc-only symbol in", "// a JsDoc-only scope.", "SourcePosition", "<", "Node", ">", "typePos", "=", "marker", ".", "getType", "(", ")", ";", "JSType", "type", "=", "null", ";", "if", "(", "typePos", "!=", "null", ")", "{", "type", "=", "typePos", ".", "getItem", "(", ")", ".", "getJSType", "(", ")", ";", "}", "if", "(", "sym", ".", "docScope", "==", "null", ")", "{", "sym", ".", "docScope", "=", "new", "SymbolScope", "(", "null", "/* root */", ",", "null", "/* parent scope */", ",", "null", "/* type of this */", ",", "sym", ")", ";", "}", "// Check to make sure there's no existing symbol. In theory, this", "// should never happen, but we check anyway and fail silently", "// if our assumptions are wrong. (We do not want to put the symbol", "// table into an invalid state).", "Symbol", "existingSymbol", "=", "isAnySymbolDeclared", "(", "name", ",", "paramNode", ",", "sym", ".", "docScope", ")", ";", "if", "(", "existingSymbol", "==", "null", ")", "{", "declareSymbol", "(", "name", ",", "type", ",", "type", "==", "null", ",", "sym", ".", "docScope", ",", "paramNode", ",", "null", "/* info */", ")", ";", "}", "}", "else", "{", "param", ".", "defineReferenceAt", "(", "paramNode", ")", ";", "}", "}", "}", "}" ]
Index JSDocInfo.
[ "Index", "JSDocInfo", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L944-L993
24,453
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.fillSymbolVisibility
void fillSymbolVisibility(Node externs, Node root) { CollectFileOverviewVisibility collectPass = new CollectFileOverviewVisibility(compiler); collectPass.process(externs, root); ImmutableMap<StaticSourceFile, Visibility> visibilityMap = collectPass.getFileOverviewVisibilityMap(); NodeTraversal.traverseRoots( compiler, new VisibilityCollector(visibilityMap, compiler.getCodingConvention()), externs, root); }
java
void fillSymbolVisibility(Node externs, Node root) { CollectFileOverviewVisibility collectPass = new CollectFileOverviewVisibility(compiler); collectPass.process(externs, root); ImmutableMap<StaticSourceFile, Visibility> visibilityMap = collectPass.getFileOverviewVisibilityMap(); NodeTraversal.traverseRoots( compiler, new VisibilityCollector(visibilityMap, compiler.getCodingConvention()), externs, root); }
[ "void", "fillSymbolVisibility", "(", "Node", "externs", ",", "Node", "root", ")", "{", "CollectFileOverviewVisibility", "collectPass", "=", "new", "CollectFileOverviewVisibility", "(", "compiler", ")", ";", "collectPass", ".", "process", "(", "externs", ",", "root", ")", ";", "ImmutableMap", "<", "StaticSourceFile", ",", "Visibility", ">", "visibilityMap", "=", "collectPass", ".", "getFileOverviewVisibilityMap", "(", ")", ";", "NodeTraversal", ".", "traverseRoots", "(", "compiler", ",", "new", "VisibilityCollector", "(", "visibilityMap", ",", "compiler", ".", "getCodingConvention", "(", ")", ")", ",", "externs", ",", "root", ")", ";", "}" ]
Records the visibility of each symbol.
[ "Records", "the", "visibility", "of", "each", "symbol", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L996-L1007
24,454
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.createPropertyScopeFor
@SuppressWarnings("ReferenceEquality") private void createPropertyScopeFor(Symbol s) { // In order to build a property scope for s, we will need to build // a property scope for all its implicit prototypes first. This means // that sometimes we will already have built its property scope // for a previous symbol. if (s.propertyScope != null) { return; } ObjectType type = getType(s) == null ? null : getType(s).toObjectType(); if (type == null) { return; } // Create an empty property scope for the given symbol, maybe with a parent scope if it has // an implicit prototype. SymbolScope parentPropertyScope = maybeGetParentPropertyScope(type); s.setPropertyScope(new SymbolScope(null, parentPropertyScope, type, s)); // If this symbol represents some 'a.b.c.prototype', add any instance properties of a.b.c // into the symbol scope. ObjectType instanceType = type; Iterable<String> propNames = type.getOwnPropertyNames(); if (instanceType.isFunctionPrototypeType()) { // Guard against modifying foo.prototype when foo is a regular (non-constructor) function. if (instanceType.getOwnerFunction().hasInstanceType()) { // Merge the properties of "Foo.prototype" and "new Foo()" together. instanceType = instanceType.getOwnerFunction().getInstanceType(); propNames = Iterables.concat(propNames, instanceType.getOwnPropertyNames()); } } // Add all declared properties in propNames into the property scope for (String propName : propNames) { StaticSlot newProp = instanceType.getSlot(propName); if (newProp.getDeclaration() == null) { // Skip properties without declarations. We won't know how to index // them, because we index things by node. continue; } // We have symbol tables that do not do type analysis. They just try // to build a complete index of all objects in the program. So we might // already have symbols for things like "Foo.bar". If this happens, // throw out the old symbol and use the type-based symbol. Symbol oldProp = symbols.get(newProp.getDeclaration().getNode(), s.getName() + "." + propName); // If we've already have an entry in the table for this symbol, // then skip it. This should only happen if we screwed up, // and declared multiple distinct properties with the same name // at the same node. We bail out here to be safe. if (symbols.get(newProp.getDeclaration().getNode(), newProp.getName()) != null) { if (logger.isLoggable(Level.FINE)) { logger.fine("Found duplicate symbol " + newProp); } continue; } Symbol newSym = copySymbolTo(newProp, s.propertyScope); if (oldProp != null) { if (newSym.getJSDocInfo() == null) { newSym.setJSDocInfo(oldProp.getJSDocInfo()); } newSym.setPropertyScope(oldProp.propertyScope); for (Reference ref : oldProp.references.values()) { newSym.defineReferenceAt(ref.getNode()); } // All references/scopes from oldProp were updated to use the newProp. Time to remove // oldProp. removeSymbol(oldProp); } } }
java
@SuppressWarnings("ReferenceEquality") private void createPropertyScopeFor(Symbol s) { // In order to build a property scope for s, we will need to build // a property scope for all its implicit prototypes first. This means // that sometimes we will already have built its property scope // for a previous symbol. if (s.propertyScope != null) { return; } ObjectType type = getType(s) == null ? null : getType(s).toObjectType(); if (type == null) { return; } // Create an empty property scope for the given symbol, maybe with a parent scope if it has // an implicit prototype. SymbolScope parentPropertyScope = maybeGetParentPropertyScope(type); s.setPropertyScope(new SymbolScope(null, parentPropertyScope, type, s)); // If this symbol represents some 'a.b.c.prototype', add any instance properties of a.b.c // into the symbol scope. ObjectType instanceType = type; Iterable<String> propNames = type.getOwnPropertyNames(); if (instanceType.isFunctionPrototypeType()) { // Guard against modifying foo.prototype when foo is a regular (non-constructor) function. if (instanceType.getOwnerFunction().hasInstanceType()) { // Merge the properties of "Foo.prototype" and "new Foo()" together. instanceType = instanceType.getOwnerFunction().getInstanceType(); propNames = Iterables.concat(propNames, instanceType.getOwnPropertyNames()); } } // Add all declared properties in propNames into the property scope for (String propName : propNames) { StaticSlot newProp = instanceType.getSlot(propName); if (newProp.getDeclaration() == null) { // Skip properties without declarations. We won't know how to index // them, because we index things by node. continue; } // We have symbol tables that do not do type analysis. They just try // to build a complete index of all objects in the program. So we might // already have symbols for things like "Foo.bar". If this happens, // throw out the old symbol and use the type-based symbol. Symbol oldProp = symbols.get(newProp.getDeclaration().getNode(), s.getName() + "." + propName); // If we've already have an entry in the table for this symbol, // then skip it. This should only happen if we screwed up, // and declared multiple distinct properties with the same name // at the same node. We bail out here to be safe. if (symbols.get(newProp.getDeclaration().getNode(), newProp.getName()) != null) { if (logger.isLoggable(Level.FINE)) { logger.fine("Found duplicate symbol " + newProp); } continue; } Symbol newSym = copySymbolTo(newProp, s.propertyScope); if (oldProp != null) { if (newSym.getJSDocInfo() == null) { newSym.setJSDocInfo(oldProp.getJSDocInfo()); } newSym.setPropertyScope(oldProp.propertyScope); for (Reference ref : oldProp.references.values()) { newSym.defineReferenceAt(ref.getNode()); } // All references/scopes from oldProp were updated to use the newProp. Time to remove // oldProp. removeSymbol(oldProp); } } }
[ "@", "SuppressWarnings", "(", "\"ReferenceEquality\"", ")", "private", "void", "createPropertyScopeFor", "(", "Symbol", "s", ")", "{", "// In order to build a property scope for s, we will need to build", "// a property scope for all its implicit prototypes first. This means", "// that sometimes we will already have built its property scope", "// for a previous symbol.", "if", "(", "s", ".", "propertyScope", "!=", "null", ")", "{", "return", ";", "}", "ObjectType", "type", "=", "getType", "(", "s", ")", "==", "null", "?", "null", ":", "getType", "(", "s", ")", ".", "toObjectType", "(", ")", ";", "if", "(", "type", "==", "null", ")", "{", "return", ";", "}", "// Create an empty property scope for the given symbol, maybe with a parent scope if it has", "// an implicit prototype.", "SymbolScope", "parentPropertyScope", "=", "maybeGetParentPropertyScope", "(", "type", ")", ";", "s", ".", "setPropertyScope", "(", "new", "SymbolScope", "(", "null", ",", "parentPropertyScope", ",", "type", ",", "s", ")", ")", ";", "// If this symbol represents some 'a.b.c.prototype', add any instance properties of a.b.c", "// into the symbol scope.", "ObjectType", "instanceType", "=", "type", ";", "Iterable", "<", "String", ">", "propNames", "=", "type", ".", "getOwnPropertyNames", "(", ")", ";", "if", "(", "instanceType", ".", "isFunctionPrototypeType", "(", ")", ")", "{", "// Guard against modifying foo.prototype when foo is a regular (non-constructor) function.", "if", "(", "instanceType", ".", "getOwnerFunction", "(", ")", ".", "hasInstanceType", "(", ")", ")", "{", "// Merge the properties of \"Foo.prototype\" and \"new Foo()\" together.", "instanceType", "=", "instanceType", ".", "getOwnerFunction", "(", ")", ".", "getInstanceType", "(", ")", ";", "propNames", "=", "Iterables", ".", "concat", "(", "propNames", ",", "instanceType", ".", "getOwnPropertyNames", "(", ")", ")", ";", "}", "}", "// Add all declared properties in propNames into the property scope", "for", "(", "String", "propName", ":", "propNames", ")", "{", "StaticSlot", "newProp", "=", "instanceType", ".", "getSlot", "(", "propName", ")", ";", "if", "(", "newProp", ".", "getDeclaration", "(", ")", "==", "null", ")", "{", "// Skip properties without declarations. We won't know how to index", "// them, because we index things by node.", "continue", ";", "}", "// We have symbol tables that do not do type analysis. They just try", "// to build a complete index of all objects in the program. So we might", "// already have symbols for things like \"Foo.bar\". If this happens,", "// throw out the old symbol and use the type-based symbol.", "Symbol", "oldProp", "=", "symbols", ".", "get", "(", "newProp", ".", "getDeclaration", "(", ")", ".", "getNode", "(", ")", ",", "s", ".", "getName", "(", ")", "+", "\".\"", "+", "propName", ")", ";", "// If we've already have an entry in the table for this symbol,", "// then skip it. This should only happen if we screwed up,", "// and declared multiple distinct properties with the same name", "// at the same node. We bail out here to be safe.", "if", "(", "symbols", ".", "get", "(", "newProp", ".", "getDeclaration", "(", ")", ".", "getNode", "(", ")", ",", "newProp", ".", "getName", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "logger", ".", "fine", "(", "\"Found duplicate symbol \"", "+", "newProp", ")", ";", "}", "continue", ";", "}", "Symbol", "newSym", "=", "copySymbolTo", "(", "newProp", ",", "s", ".", "propertyScope", ")", ";", "if", "(", "oldProp", "!=", "null", ")", "{", "if", "(", "newSym", ".", "getJSDocInfo", "(", ")", "==", "null", ")", "{", "newSym", ".", "setJSDocInfo", "(", "oldProp", ".", "getJSDocInfo", "(", ")", ")", ";", "}", "newSym", ".", "setPropertyScope", "(", "oldProp", ".", "propertyScope", ")", ";", "for", "(", "Reference", "ref", ":", "oldProp", ".", "references", ".", "values", "(", ")", ")", "{", "newSym", ".", "defineReferenceAt", "(", "ref", ".", "getNode", "(", ")", ")", ";", "}", "// All references/scopes from oldProp were updated to use the newProp. Time to remove", "// oldProp.", "removeSymbol", "(", "oldProp", ")", ";", "}", "}", "}" ]
This function uses == to compare types to be exact same instances.
[ "This", "function", "uses", "==", "to", "compare", "types", "to", "be", "exact", "same", "instances", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L1019-L1093
24,455
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.maybeGetParentPropertyScope
@Nullable private SymbolScope maybeGetParentPropertyScope(ObjectType symbolObjectType) { ObjectType proto = symbolObjectType.getImplicitPrototype(); if (proto == null || proto == symbolObjectType) { return null; } final Symbol parentSymbol; if (isEs6ClassConstructor(proto)) { // given `class Foo {} class Bar extends Foo {}`, `Foo` is the implicit prototype of `Bar`. parentSymbol = getSymbolDeclaredBy(proto.toMaybeFunctionType()); } else if (proto.getConstructor() != null) { // given // /** @constructor */ function Foo() {} // /** @constructor */ function Bar() {} // goog.inherits(Bar, Foo); // the implicit prototype of Bar.prototype is the instance of Foo. parentSymbol = getSymbolForInstancesOf(proto.getConstructor()); } else { return null; } if (parentSymbol == null) { return null; } createPropertyScopeFor(parentSymbol); return parentSymbol.getPropertyScope(); }
java
@Nullable private SymbolScope maybeGetParentPropertyScope(ObjectType symbolObjectType) { ObjectType proto = symbolObjectType.getImplicitPrototype(); if (proto == null || proto == symbolObjectType) { return null; } final Symbol parentSymbol; if (isEs6ClassConstructor(proto)) { // given `class Foo {} class Bar extends Foo {}`, `Foo` is the implicit prototype of `Bar`. parentSymbol = getSymbolDeclaredBy(proto.toMaybeFunctionType()); } else if (proto.getConstructor() != null) { // given // /** @constructor */ function Foo() {} // /** @constructor */ function Bar() {} // goog.inherits(Bar, Foo); // the implicit prototype of Bar.prototype is the instance of Foo. parentSymbol = getSymbolForInstancesOf(proto.getConstructor()); } else { return null; } if (parentSymbol == null) { return null; } createPropertyScopeFor(parentSymbol); return parentSymbol.getPropertyScope(); }
[ "@", "Nullable", "private", "SymbolScope", "maybeGetParentPropertyScope", "(", "ObjectType", "symbolObjectType", ")", "{", "ObjectType", "proto", "=", "symbolObjectType", ".", "getImplicitPrototype", "(", ")", ";", "if", "(", "proto", "==", "null", "||", "proto", "==", "symbolObjectType", ")", "{", "return", "null", ";", "}", "final", "Symbol", "parentSymbol", ";", "if", "(", "isEs6ClassConstructor", "(", "proto", ")", ")", "{", "// given `class Foo {} class Bar extends Foo {}`, `Foo` is the implicit prototype of `Bar`.", "parentSymbol", "=", "getSymbolDeclaredBy", "(", "proto", ".", "toMaybeFunctionType", "(", ")", ")", ";", "}", "else", "if", "(", "proto", ".", "getConstructor", "(", ")", "!=", "null", ")", "{", "// given", "// /** @constructor */ function Foo() {}", "// /** @constructor */ function Bar() {}", "// goog.inherits(Bar, Foo);", "// the implicit prototype of Bar.prototype is the instance of Foo.", "parentSymbol", "=", "getSymbolForInstancesOf", "(", "proto", ".", "getConstructor", "(", ")", ")", ";", "}", "else", "{", "return", "null", ";", "}", "if", "(", "parentSymbol", "==", "null", ")", "{", "return", "null", ";", "}", "createPropertyScopeFor", "(", "parentSymbol", ")", ";", "return", "parentSymbol", ".", "getPropertyScope", "(", ")", ";", "}" ]
If this type has an implicit prototype set, returns the SymbolScope corresponding to the properties of the implicit prototype. Otherwise returns null. <p>Note that currently we only handle cases where the implicit prototype is a) a class or b) is an instance object.
[ "If", "this", "type", "has", "an", "implicit", "prototype", "set", "returns", "the", "SymbolScope", "corresponding", "to", "the", "properties", "of", "the", "implicit", "prototype", ".", "Otherwise", "returns", "null", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L1102-L1127
24,456
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.fillSuperReferences
void fillSuperReferences(Node externs, Node root) { NodeTraversal.Callback collectSuper = new AbstractPostOrderCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { // Process only 'super' nodes with types. if (!n.isSuper() || n.getJSType() == null) { return; } Symbol classSymbol = getSymbolForTypeHelper(n.getJSType(), /* linkToCtor= */ false); if (classSymbol != null) { classSymbol.defineReferenceAt(n); } } }; NodeTraversal.traverseRoots(compiler, collectSuper, externs, root); }
java
void fillSuperReferences(Node externs, Node root) { NodeTraversal.Callback collectSuper = new AbstractPostOrderCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { // Process only 'super' nodes with types. if (!n.isSuper() || n.getJSType() == null) { return; } Symbol classSymbol = getSymbolForTypeHelper(n.getJSType(), /* linkToCtor= */ false); if (classSymbol != null) { classSymbol.defineReferenceAt(n); } } }; NodeTraversal.traverseRoots(compiler, collectSuper, externs, root); }
[ "void", "fillSuperReferences", "(", "Node", "externs", ",", "Node", "root", ")", "{", "NodeTraversal", ".", "Callback", "collectSuper", "=", "new", "AbstractPostOrderCallback", "(", ")", "{", "@", "Override", "public", "void", "visit", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "parent", ")", "{", "// Process only 'super' nodes with types.", "if", "(", "!", "n", ".", "isSuper", "(", ")", "||", "n", ".", "getJSType", "(", ")", "==", "null", ")", "{", "return", ";", "}", "Symbol", "classSymbol", "=", "getSymbolForTypeHelper", "(", "n", ".", "getJSType", "(", ")", ",", "/* linkToCtor= */", "false", ")", ";", "if", "(", "classSymbol", "!=", "null", ")", "{", "classSymbol", ".", "defineReferenceAt", "(", "n", ")", ";", "}", "}", "}", ";", "NodeTraversal", ".", "traverseRoots", "(", "compiler", ",", "collectSuper", ",", "externs", ",", "root", ")", ";", "}" ]
Fill in references to "super" variables.
[ "Fill", "in", "references", "to", "super", "variables", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L1141-L1157
24,457
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.isSymbolDuplicatedExternOnWindow
private boolean isSymbolDuplicatedExternOnWindow(Symbol symbol) { Node node = symbol.getDeclarationNode(); // Check that node is of type "window.foo"; return !node.isIndexable() && node.isGetProp() && node.getFirstChild().isName() && node.getFirstChild().getString().equals("window"); }
java
private boolean isSymbolDuplicatedExternOnWindow(Symbol symbol) { Node node = symbol.getDeclarationNode(); // Check that node is of type "window.foo"; return !node.isIndexable() && node.isGetProp() && node.getFirstChild().isName() && node.getFirstChild().getString().equals("window"); }
[ "private", "boolean", "isSymbolDuplicatedExternOnWindow", "(", "Symbol", "symbol", ")", "{", "Node", "node", "=", "symbol", ".", "getDeclarationNode", "(", ")", ";", "// Check that node is of type \"window.foo\";", "return", "!", "node", ".", "isIndexable", "(", ")", "&&", "node", ".", "isGetProp", "(", ")", "&&", "node", ".", "getFirstChild", "(", ")", ".", "isName", "(", ")", "&&", "node", ".", "getFirstChild", "(", ")", ".", "getString", "(", ")", ".", "equals", "(", "\"window\"", ")", ";", "}" ]
Heuristic method to check whether symbol was created by DeclaredGlobalExternsOnWindow.java pass.
[ "Heuristic", "method", "to", "check", "whether", "symbol", "was", "created", "by", "DeclaredGlobalExternsOnWindow", ".", "java", "pass", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L1175-L1182
24,458
google/closure-compiler
src/com/google/javascript/jscomp/SymbolTable.java
SymbolTable.getLexicalScopeDepth
private int getLexicalScopeDepth(SymbolScope scope) { if (scope.isLexicalScope() || scope.isDocScope()) { return scope.getScopeDepth(); } else { checkState(scope.isPropertyScope()); Symbol sym = scope.getSymbolForScope(); checkNotNull(sym); return getLexicalScopeDepth(getScope(sym)) + 1; } }
java
private int getLexicalScopeDepth(SymbolScope scope) { if (scope.isLexicalScope() || scope.isDocScope()) { return scope.getScopeDepth(); } else { checkState(scope.isPropertyScope()); Symbol sym = scope.getSymbolForScope(); checkNotNull(sym); return getLexicalScopeDepth(getScope(sym)) + 1; } }
[ "private", "int", "getLexicalScopeDepth", "(", "SymbolScope", "scope", ")", "{", "if", "(", "scope", ".", "isLexicalScope", "(", ")", "||", "scope", ".", "isDocScope", "(", ")", ")", "{", "return", "scope", ".", "getScopeDepth", "(", ")", ";", "}", "else", "{", "checkState", "(", "scope", ".", "isPropertyScope", "(", ")", ")", ";", "Symbol", "sym", "=", "scope", ".", "getSymbolForScope", "(", ")", ";", "checkNotNull", "(", "sym", ")", ";", "return", "getLexicalScopeDepth", "(", "getScope", "(", "sym", ")", ")", "+", "1", ";", "}", "}" ]
For a lexical scope, just returns the normal scope depth. <p>For a property scope, returns the number of scopes we have to search to find the nearest lexical scope, plus that lexical scope's depth. <p>For a doc info scope, returns 0.
[ "For", "a", "lexical", "scope", "just", "returns", "the", "normal", "scope", "depth", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L2070-L2079
24,459
google/closure-compiler
src/com/google/javascript/jscomp/Normalize.java
Normalize.removeDuplicateDeclarations
private void removeDuplicateDeclarations(Node externs, Node root) { Callback tickler = new ScopeTicklingCallback(); ScopeCreator scopeCreator = new Es6SyntacticScopeCreator(compiler, new DuplicateDeclarationHandler()); NodeTraversal t = new NodeTraversal(compiler, tickler, scopeCreator); t.traverseRoots(externs, root); }
java
private void removeDuplicateDeclarations(Node externs, Node root) { Callback tickler = new ScopeTicklingCallback(); ScopeCreator scopeCreator = new Es6SyntacticScopeCreator(compiler, new DuplicateDeclarationHandler()); NodeTraversal t = new NodeTraversal(compiler, tickler, scopeCreator); t.traverseRoots(externs, root); }
[ "private", "void", "removeDuplicateDeclarations", "(", "Node", "externs", ",", "Node", "root", ")", "{", "Callback", "tickler", "=", "new", "ScopeTicklingCallback", "(", ")", ";", "ScopeCreator", "scopeCreator", "=", "new", "Es6SyntacticScopeCreator", "(", "compiler", ",", "new", "DuplicateDeclarationHandler", "(", ")", ")", ";", "NodeTraversal", "t", "=", "new", "NodeTraversal", "(", "compiler", ",", "tickler", ",", "scopeCreator", ")", ";", "t", ".", "traverseRoots", "(", "externs", ",", "root", ")", ";", "}" ]
Remove duplicate VAR declarations.
[ "Remove", "duplicate", "VAR", "declarations", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Normalize.java#L793-L799
24,460
google/closure-compiler
src/com/google/javascript/jscomp/OptimizeReturns.java
OptimizeReturns.isRemovableValue
private boolean isRemovableValue(Node n) { switch (n.getToken()) { case TEMPLATELIT: case ARRAYLIT: for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if ((!child.isEmpty()) && !isRemovableValue(child)) { return false; } } return true; case REGEXP: case STRING: case NUMBER: case NULL: case TRUE: case FALSE: case TEMPLATELIT_STRING: return true; case TEMPLATELIT_SUB: case CAST: case NOT: case VOID: case NEG: return isRemovableValue(n.getFirstChild()); default: return false; } }
java
private boolean isRemovableValue(Node n) { switch (n.getToken()) { case TEMPLATELIT: case ARRAYLIT: for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if ((!child.isEmpty()) && !isRemovableValue(child)) { return false; } } return true; case REGEXP: case STRING: case NUMBER: case NULL: case TRUE: case FALSE: case TEMPLATELIT_STRING: return true; case TEMPLATELIT_SUB: case CAST: case NOT: case VOID: case NEG: return isRemovableValue(n.getFirstChild()); default: return false; } }
[ "private", "boolean", "isRemovableValue", "(", "Node", "n", ")", "{", "switch", "(", "n", ".", "getToken", "(", ")", ")", "{", "case", "TEMPLATELIT", ":", "case", "ARRAYLIT", ":", "for", "(", "Node", "child", "=", "n", ".", "getFirstChild", "(", ")", ";", "child", "!=", "null", ";", "child", "=", "child", ".", "getNext", "(", ")", ")", "{", "if", "(", "(", "!", "child", ".", "isEmpty", "(", ")", ")", "&&", "!", "isRemovableValue", "(", "child", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "case", "REGEXP", ":", "case", "STRING", ":", "case", "NUMBER", ":", "case", "NULL", ":", "case", "TRUE", ":", "case", "FALSE", ":", "case", "TEMPLATELIT_STRING", ":", "return", "true", ";", "case", "TEMPLATELIT_SUB", ":", "case", "CAST", ":", "case", "NOT", ":", "case", "VOID", ":", "case", "NEG", ":", "return", "isRemovableValue", "(", "n", ".", "getFirstChild", "(", ")", ")", ";", "default", ":", "return", "false", ";", "}", "}" ]
So we don't need to update the graph.
[ "So", "we", "don", "t", "need", "to", "update", "the", "graph", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/OptimizeReturns.java#L206-L235
24,461
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.warnAboutNamespaceAliasing
private void warnAboutNamespaceAliasing(Name nameObj, Ref ref) { compiler.report(JSError.make(ref.getNode(), UNSAFE_NAMESPACE_WARNING, nameObj.getFullName())); }
java
private void warnAboutNamespaceAliasing(Name nameObj, Ref ref) { compiler.report(JSError.make(ref.getNode(), UNSAFE_NAMESPACE_WARNING, nameObj.getFullName())); }
[ "private", "void", "warnAboutNamespaceAliasing", "(", "Name", "nameObj", ",", "Ref", "ref", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "ref", ".", "getNode", "(", ")", ",", "UNSAFE_NAMESPACE_WARNING", ",", "nameObj", ".", "getFullName", "(", ")", ")", ")", ";", "}" ]
Reports a warning because a namespace was aliased. @param nameObj A namespace that is being aliased @param ref The reference that forced the alias
[ "Reports", "a", "warning", "because", "a", "namespace", "was", "aliased", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L224-L226
24,462
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.warnAboutNamespaceRedefinition
private void warnAboutNamespaceRedefinition(Name nameObj, Ref ref) { compiler.report( JSError.make(ref.getNode(), NAMESPACE_REDEFINED_WARNING, nameObj.getFullName())); }
java
private void warnAboutNamespaceRedefinition(Name nameObj, Ref ref) { compiler.report( JSError.make(ref.getNode(), NAMESPACE_REDEFINED_WARNING, nameObj.getFullName())); }
[ "private", "void", "warnAboutNamespaceRedefinition", "(", "Name", "nameObj", ",", "Ref", "ref", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "ref", ".", "getNode", "(", ")", ",", "NAMESPACE_REDEFINED_WARNING", ",", "nameObj", ".", "getFullName", "(", ")", ")", ")", ";", "}" ]
Reports a warning because a namespace was redefined. @param nameObj A namespace that is being redefined @param ref The reference that set the namespace
[ "Reports", "a", "warning", "because", "a", "namespace", "was", "redefined", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L234-L237
24,463
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.flattenReferencesToCollapsibleDescendantNames
private void flattenReferencesToCollapsibleDescendantNames( Name n, String alias) { if (n.props == null || n.isCollapsingExplicitlyDenied()) { return; } for (Name p : n.props) { String propAlias = appendPropForAlias(alias, p.getBaseName()); boolean isAllowedToCollapse = propertyCollapseLevel != PropertyCollapseLevel.MODULE_EXPORT || p.isModuleExport(); if (isAllowedToCollapse && p.canCollapse()) { flattenReferencesTo(p, propAlias); } else if (isAllowedToCollapse && p.isSimpleStubDeclaration() && !p.isCollapsingExplicitlyDenied()) { flattenSimpleStubDeclaration(p, propAlias); } flattenReferencesToCollapsibleDescendantNames(p, propAlias); } }
java
private void flattenReferencesToCollapsibleDescendantNames( Name n, String alias) { if (n.props == null || n.isCollapsingExplicitlyDenied()) { return; } for (Name p : n.props) { String propAlias = appendPropForAlias(alias, p.getBaseName()); boolean isAllowedToCollapse = propertyCollapseLevel != PropertyCollapseLevel.MODULE_EXPORT || p.isModuleExport(); if (isAllowedToCollapse && p.canCollapse()) { flattenReferencesTo(p, propAlias); } else if (isAllowedToCollapse && p.isSimpleStubDeclaration() && !p.isCollapsingExplicitlyDenied()) { flattenSimpleStubDeclaration(p, propAlias); } flattenReferencesToCollapsibleDescendantNames(p, propAlias); } }
[ "private", "void", "flattenReferencesToCollapsibleDescendantNames", "(", "Name", "n", ",", "String", "alias", ")", "{", "if", "(", "n", ".", "props", "==", "null", "||", "n", ".", "isCollapsingExplicitlyDenied", "(", ")", ")", "{", "return", ";", "}", "for", "(", "Name", "p", ":", "n", ".", "props", ")", "{", "String", "propAlias", "=", "appendPropForAlias", "(", "alias", ",", "p", ".", "getBaseName", "(", ")", ")", ";", "boolean", "isAllowedToCollapse", "=", "propertyCollapseLevel", "!=", "PropertyCollapseLevel", ".", "MODULE_EXPORT", "||", "p", ".", "isModuleExport", "(", ")", ";", "if", "(", "isAllowedToCollapse", "&&", "p", ".", "canCollapse", "(", ")", ")", "{", "flattenReferencesTo", "(", "p", ",", "propAlias", ")", ";", "}", "else", "if", "(", "isAllowedToCollapse", "&&", "p", ".", "isSimpleStubDeclaration", "(", ")", "&&", "!", "p", ".", "isCollapsingExplicitlyDenied", "(", ")", ")", "{", "flattenSimpleStubDeclaration", "(", "p", ",", "propAlias", ")", ";", "}", "flattenReferencesToCollapsibleDescendantNames", "(", "p", ",", "propAlias", ")", ";", "}", "}" ]
Flattens all references to collapsible properties of a global name except their initial definitions. Recurs on subnames. @param n An object representing a global name @param alias The flattened name for {@code n}
[ "Flattens", "all", "references", "to", "collapsible", "properties", "of", "a", "global", "name", "except", "their", "initial", "definitions", ".", "Recurs", "on", "subnames", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L246-L268
24,464
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.flattenSimpleStubDeclaration
private void flattenSimpleStubDeclaration(Name name, String alias) { Ref ref = Iterables.getOnlyElement(name.getRefs()); Node nameNode = NodeUtil.newName(compiler, alias, ref.getNode(), name.getFullName()); Node varNode = IR.var(nameNode).useSourceInfoIfMissingFrom(nameNode); checkState(ref.getNode().getParent().isExprResult()); Node parent = ref.getNode().getParent(); Node grandparent = parent.getParent(); grandparent.replaceChild(parent, varNode); compiler.reportChangeToEnclosingScope(varNode); }
java
private void flattenSimpleStubDeclaration(Name name, String alias) { Ref ref = Iterables.getOnlyElement(name.getRefs()); Node nameNode = NodeUtil.newName(compiler, alias, ref.getNode(), name.getFullName()); Node varNode = IR.var(nameNode).useSourceInfoIfMissingFrom(nameNode); checkState(ref.getNode().getParent().isExprResult()); Node parent = ref.getNode().getParent(); Node grandparent = parent.getParent(); grandparent.replaceChild(parent, varNode); compiler.reportChangeToEnclosingScope(varNode); }
[ "private", "void", "flattenSimpleStubDeclaration", "(", "Name", "name", ",", "String", "alias", ")", "{", "Ref", "ref", "=", "Iterables", ".", "getOnlyElement", "(", "name", ".", "getRefs", "(", ")", ")", ";", "Node", "nameNode", "=", "NodeUtil", ".", "newName", "(", "compiler", ",", "alias", ",", "ref", ".", "getNode", "(", ")", ",", "name", ".", "getFullName", "(", ")", ")", ";", "Node", "varNode", "=", "IR", ".", "var", "(", "nameNode", ")", ".", "useSourceInfoIfMissingFrom", "(", "nameNode", ")", ";", "checkState", "(", "ref", ".", "getNode", "(", ")", ".", "getParent", "(", ")", ".", "isExprResult", "(", ")", ")", ";", "Node", "parent", "=", "ref", ".", "getNode", "(", ")", ".", "getParent", "(", ")", ";", "Node", "grandparent", "=", "parent", ".", "getParent", "(", ")", ";", "grandparent", ".", "replaceChild", "(", "parent", ",", "varNode", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "varNode", ")", ";", "}" ]
Flattens a stub declaration. This is mostly a hack to support legacy users.
[ "Flattens", "a", "stub", "declaration", ".", "This", "is", "mostly", "a", "hack", "to", "support", "legacy", "users", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L274-L284
24,465
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.flattenReferencesTo
private void flattenReferencesTo(Name n, String alias) { String originalName = n.getFullName(); for (Ref r : n.getRefs()) { if (r == n.getDeclaration()) { // Declarations are handled separately. continue; } Node rParent = r.getNode().getParent(); // There are two cases when we shouldn't flatten a reference: // 1) Object literal keys, because duplicate keys show up as refs. // 2) References inside a complex assign. (a = x.y = 0). These are // called TWIN references, because they show up twice in the // reference list. Only collapse the set, not the alias. if (!NodeUtil.mayBeObjectLitKey(r.getNode()) && (r.getTwin() == null || r.isSet())) { flattenNameRef(alias, r.getNode(), rParent, originalName); } else if (r.getNode().isStringKey() && r.getNode().getParent().isObjectPattern()) { Node newNode = IR.name(alias).srcref(r.getNode()); NodeUtil.copyNameAnnotations(r.getNode(), newNode); DestructuringGlobalNameExtractor.reassignDestructringLvalue( r.getNode(), newNode, null, r, compiler); } } // Flatten all occurrences of a name as a prefix of its subnames. For // example, if {@code n} corresponds to the name "a.b", then "a.b" will be // replaced with "a$b" in all occurrences of "a.b.c", "a.b.c.d", etc. if (n.props != null) { for (Name p : n.props) { flattenPrefixes(alias, p, 1); } } }
java
private void flattenReferencesTo(Name n, String alias) { String originalName = n.getFullName(); for (Ref r : n.getRefs()) { if (r == n.getDeclaration()) { // Declarations are handled separately. continue; } Node rParent = r.getNode().getParent(); // There are two cases when we shouldn't flatten a reference: // 1) Object literal keys, because duplicate keys show up as refs. // 2) References inside a complex assign. (a = x.y = 0). These are // called TWIN references, because they show up twice in the // reference list. Only collapse the set, not the alias. if (!NodeUtil.mayBeObjectLitKey(r.getNode()) && (r.getTwin() == null || r.isSet())) { flattenNameRef(alias, r.getNode(), rParent, originalName); } else if (r.getNode().isStringKey() && r.getNode().getParent().isObjectPattern()) { Node newNode = IR.name(alias).srcref(r.getNode()); NodeUtil.copyNameAnnotations(r.getNode(), newNode); DestructuringGlobalNameExtractor.reassignDestructringLvalue( r.getNode(), newNode, null, r, compiler); } } // Flatten all occurrences of a name as a prefix of its subnames. For // example, if {@code n} corresponds to the name "a.b", then "a.b" will be // replaced with "a$b" in all occurrences of "a.b.c", "a.b.c.d", etc. if (n.props != null) { for (Name p : n.props) { flattenPrefixes(alias, p, 1); } } }
[ "private", "void", "flattenReferencesTo", "(", "Name", "n", ",", "String", "alias", ")", "{", "String", "originalName", "=", "n", ".", "getFullName", "(", ")", ";", "for", "(", "Ref", "r", ":", "n", ".", "getRefs", "(", ")", ")", "{", "if", "(", "r", "==", "n", ".", "getDeclaration", "(", ")", ")", "{", "// Declarations are handled separately.", "continue", ";", "}", "Node", "rParent", "=", "r", ".", "getNode", "(", ")", ".", "getParent", "(", ")", ";", "// There are two cases when we shouldn't flatten a reference:", "// 1) Object literal keys, because duplicate keys show up as refs.", "// 2) References inside a complex assign. (a = x.y = 0). These are", "// called TWIN references, because they show up twice in the", "// reference list. Only collapse the set, not the alias.", "if", "(", "!", "NodeUtil", ".", "mayBeObjectLitKey", "(", "r", ".", "getNode", "(", ")", ")", "&&", "(", "r", ".", "getTwin", "(", ")", "==", "null", "||", "r", ".", "isSet", "(", ")", ")", ")", "{", "flattenNameRef", "(", "alias", ",", "r", ".", "getNode", "(", ")", ",", "rParent", ",", "originalName", ")", ";", "}", "else", "if", "(", "r", ".", "getNode", "(", ")", ".", "isStringKey", "(", ")", "&&", "r", ".", "getNode", "(", ")", ".", "getParent", "(", ")", ".", "isObjectPattern", "(", ")", ")", "{", "Node", "newNode", "=", "IR", ".", "name", "(", "alias", ")", ".", "srcref", "(", "r", ".", "getNode", "(", ")", ")", ";", "NodeUtil", ".", "copyNameAnnotations", "(", "r", ".", "getNode", "(", ")", ",", "newNode", ")", ";", "DestructuringGlobalNameExtractor", ".", "reassignDestructringLvalue", "(", "r", ".", "getNode", "(", ")", ",", "newNode", ",", "null", ",", "r", ",", "compiler", ")", ";", "}", "}", "// Flatten all occurrences of a name as a prefix of its subnames. For", "// example, if {@code n} corresponds to the name \"a.b\", then \"a.b\" will be", "// replaced with \"a$b\" in all occurrences of \"a.b.c\", \"a.b.c.d\", etc.", "if", "(", "n", ".", "props", "!=", "null", ")", "{", "for", "(", "Name", "p", ":", "n", ".", "props", ")", "{", "flattenPrefixes", "(", "alias", ",", "p", ",", "1", ")", ";", "}", "}", "}" ]
Flattens all references to a collapsible property of a global name except its initial definition. @param n A global property name (e.g. "a.b" or "a.b.c.d") @param alias The flattened name (e.g. "a$b" or "a$b$c$d")
[ "Flattens", "all", "references", "to", "a", "collapsible", "property", "of", "a", "global", "name", "except", "its", "initial", "definition", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L293-L324
24,466
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.flattenPrefixes
private void flattenPrefixes(String alias, Name n, int depth) { // Only flatten the prefix of a name declaration if the name being // initialized is fully qualified (i.e. not an object literal key). String originalName = n.getFullName(); Ref decl = n.getDeclaration(); if (decl != null && decl.getNode() != null && decl.getNode().isGetProp()) { flattenNameRefAtDepth(alias, decl.getNode(), depth, originalName); } for (Ref r : n.getRefs()) { if (r == decl) { // Declarations are handled separately. continue; } // References inside a complex assign (a = x.y = 0) // have twins. We should only flatten one of the twins. if (r.getTwin() == null || r.isSet()) { flattenNameRefAtDepth(alias, r.getNode(), depth, originalName); } } if (n.props != null) { for (Name p : n.props) { flattenPrefixes(alias, p, depth + 1); } } }
java
private void flattenPrefixes(String alias, Name n, int depth) { // Only flatten the prefix of a name declaration if the name being // initialized is fully qualified (i.e. not an object literal key). String originalName = n.getFullName(); Ref decl = n.getDeclaration(); if (decl != null && decl.getNode() != null && decl.getNode().isGetProp()) { flattenNameRefAtDepth(alias, decl.getNode(), depth, originalName); } for (Ref r : n.getRefs()) { if (r == decl) { // Declarations are handled separately. continue; } // References inside a complex assign (a = x.y = 0) // have twins. We should only flatten one of the twins. if (r.getTwin() == null || r.isSet()) { flattenNameRefAtDepth(alias, r.getNode(), depth, originalName); } } if (n.props != null) { for (Name p : n.props) { flattenPrefixes(alias, p, depth + 1); } } }
[ "private", "void", "flattenPrefixes", "(", "String", "alias", ",", "Name", "n", ",", "int", "depth", ")", "{", "// Only flatten the prefix of a name declaration if the name being", "// initialized is fully qualified (i.e. not an object literal key).", "String", "originalName", "=", "n", ".", "getFullName", "(", ")", ";", "Ref", "decl", "=", "n", ".", "getDeclaration", "(", ")", ";", "if", "(", "decl", "!=", "null", "&&", "decl", ".", "getNode", "(", ")", "!=", "null", "&&", "decl", ".", "getNode", "(", ")", ".", "isGetProp", "(", ")", ")", "{", "flattenNameRefAtDepth", "(", "alias", ",", "decl", ".", "getNode", "(", ")", ",", "depth", ",", "originalName", ")", ";", "}", "for", "(", "Ref", "r", ":", "n", ".", "getRefs", "(", ")", ")", "{", "if", "(", "r", "==", "decl", ")", "{", "// Declarations are handled separately.", "continue", ";", "}", "// References inside a complex assign (a = x.y = 0)", "// have twins. We should only flatten one of the twins.", "if", "(", "r", ".", "getTwin", "(", ")", "==", "null", "||", "r", ".", "isSet", "(", ")", ")", "{", "flattenNameRefAtDepth", "(", "alias", ",", "r", ".", "getNode", "(", ")", ",", "depth", ",", "originalName", ")", ";", "}", "}", "if", "(", "n", ".", "props", "!=", "null", ")", "{", "for", "(", "Name", "p", ":", "n", ".", "props", ")", "{", "flattenPrefixes", "(", "alias", ",", "p", ",", "depth", "+", "1", ")", ";", "}", "}", "}" ]
Flattens all occurrences of a name as a prefix of subnames beginning with a particular subname. @param n A global property name (e.g. "a.b.c.d") @param alias A flattened prefix name (e.g. "a$b") @param depth The difference in depth between the property name and the prefix name (e.g. 2)
[ "Flattens", "all", "occurrences", "of", "a", "name", "as", "a", "prefix", "of", "subnames", "beginning", "with", "a", "particular", "subname", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L335-L362
24,467
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.flattenNameRefAtDepth
private void flattenNameRefAtDepth(String alias, Node n, int depth, String originalName) { // This method has to work for both GETPROP chains and, in rare cases, // OBJLIT keys, possibly nested. That's why we check for children before // proceeding. In the OBJLIT case, we don't need to do anything. Token nType = n.getToken(); boolean isQName = nType == Token.NAME || nType == Token.GETPROP; boolean isObjKey = NodeUtil.mayBeObjectLitKey(n); checkState(isObjKey || isQName); if (isQName) { for (int i = 1; i < depth && n.hasChildren(); i++) { n = n.getFirstChild(); } if (n.isGetProp() && n.getFirstChild().isGetProp()) { flattenNameRef(alias, n.getFirstChild(), n, originalName); } } }
java
private void flattenNameRefAtDepth(String alias, Node n, int depth, String originalName) { // This method has to work for both GETPROP chains and, in rare cases, // OBJLIT keys, possibly nested. That's why we check for children before // proceeding. In the OBJLIT case, we don't need to do anything. Token nType = n.getToken(); boolean isQName = nType == Token.NAME || nType == Token.GETPROP; boolean isObjKey = NodeUtil.mayBeObjectLitKey(n); checkState(isObjKey || isQName); if (isQName) { for (int i = 1; i < depth && n.hasChildren(); i++) { n = n.getFirstChild(); } if (n.isGetProp() && n.getFirstChild().isGetProp()) { flattenNameRef(alias, n.getFirstChild(), n, originalName); } } }
[ "private", "void", "flattenNameRefAtDepth", "(", "String", "alias", ",", "Node", "n", ",", "int", "depth", ",", "String", "originalName", ")", "{", "// This method has to work for both GETPROP chains and, in rare cases,", "// OBJLIT keys, possibly nested. That's why we check for children before", "// proceeding. In the OBJLIT case, we don't need to do anything.", "Token", "nType", "=", "n", ".", "getToken", "(", ")", ";", "boolean", "isQName", "=", "nType", "==", "Token", ".", "NAME", "||", "nType", "==", "Token", ".", "GETPROP", ";", "boolean", "isObjKey", "=", "NodeUtil", ".", "mayBeObjectLitKey", "(", "n", ")", ";", "checkState", "(", "isObjKey", "||", "isQName", ")", ";", "if", "(", "isQName", ")", "{", "for", "(", "int", "i", "=", "1", ";", "i", "<", "depth", "&&", "n", ".", "hasChildren", "(", ")", ";", "i", "++", ")", "{", "n", "=", "n", ".", "getFirstChild", "(", ")", ";", "}", "if", "(", "n", ".", "isGetProp", "(", ")", "&&", "n", ".", "getFirstChild", "(", ")", ".", "isGetProp", "(", ")", ")", "{", "flattenNameRef", "(", "alias", ",", "n", ".", "getFirstChild", "(", ")", ",", "n", ",", "originalName", ")", ";", "}", "}", "}" ]
Flattens a particular prefix of a single name reference. @param alias A flattened prefix name (e.g. "a$b") @param n The node corresponding to a subproperty name (e.g. "a.b.c.d") @param depth The difference in depth between the property name and the prefix name (e.g. 2) @param originalName String version of the property name.
[ "Flattens", "a", "particular", "prefix", "of", "a", "single", "name", "reference", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L373-L390
24,468
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.collapseDeclarationOfNameAndDescendants
private void collapseDeclarationOfNameAndDescendants(Name n, String alias) { boolean canCollapseChildNames = n.canCollapseUnannotatedChildNames(); // Handle this name first so that nested object literals get unrolled. if (canCollapse(n)) { updateGlobalNameDeclaration(n, alias, canCollapseChildNames); } if (n.props == null) { return; } for (Name p : n.props) { collapseDeclarationOfNameAndDescendants(p, appendPropForAlias(alias, p.getBaseName())); } }
java
private void collapseDeclarationOfNameAndDescendants(Name n, String alias) { boolean canCollapseChildNames = n.canCollapseUnannotatedChildNames(); // Handle this name first so that nested object literals get unrolled. if (canCollapse(n)) { updateGlobalNameDeclaration(n, alias, canCollapseChildNames); } if (n.props == null) { return; } for (Name p : n.props) { collapseDeclarationOfNameAndDescendants(p, appendPropForAlias(alias, p.getBaseName())); } }
[ "private", "void", "collapseDeclarationOfNameAndDescendants", "(", "Name", "n", ",", "String", "alias", ")", "{", "boolean", "canCollapseChildNames", "=", "n", ".", "canCollapseUnannotatedChildNames", "(", ")", ";", "// Handle this name first so that nested object literals get unrolled.", "if", "(", "canCollapse", "(", "n", ")", ")", "{", "updateGlobalNameDeclaration", "(", "n", ",", "alias", ",", "canCollapseChildNames", ")", ";", "}", "if", "(", "n", ".", "props", "==", "null", ")", "{", "return", ";", "}", "for", "(", "Name", "p", ":", "n", ".", "props", ")", "{", "collapseDeclarationOfNameAndDescendants", "(", "p", ",", "appendPropForAlias", "(", "alias", ",", "p", ".", "getBaseName", "(", ")", ")", ")", ";", "}", "}" ]
Collapses definitions of the collapsible properties of a global name. Recurs on subnames that also represent JavaScript objects with collapsible properties. @param n A node representing a global name @param alias The flattened name for {@code n}
[ "Collapses", "definitions", "of", "the", "collapsible", "properties", "of", "a", "global", "name", ".", "Recurs", "on", "subnames", "that", "also", "represent", "JavaScript", "objects", "with", "collapsible", "properties", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L438-L452
24,469
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.checkForHosedThisReferences
private void checkForHosedThisReferences(Node function, JSDocInfo docInfo, final Name name) { // A function is getting collapsed. Make sure that if it refers to "this", // it must be a constructor, interface, record, arrow function, or documented with @this. boolean isAllowedToReferenceThis = (docInfo != null && (docInfo.isConstructorOrInterface() || docInfo.hasThisType())) || function.isArrowFunction(); if (!isAllowedToReferenceThis) { NodeTraversal.traverse(compiler, function.getLastChild(), new NodeTraversal.AbstractShallowCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isThis()) { compiler.report( JSError.make(n, UNSAFE_THIS, name.getFullName())); } } }); } }
java
private void checkForHosedThisReferences(Node function, JSDocInfo docInfo, final Name name) { // A function is getting collapsed. Make sure that if it refers to "this", // it must be a constructor, interface, record, arrow function, or documented with @this. boolean isAllowedToReferenceThis = (docInfo != null && (docInfo.isConstructorOrInterface() || docInfo.hasThisType())) || function.isArrowFunction(); if (!isAllowedToReferenceThis) { NodeTraversal.traverse(compiler, function.getLastChild(), new NodeTraversal.AbstractShallowCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isThis()) { compiler.report( JSError.make(n, UNSAFE_THIS, name.getFullName())); } } }); } }
[ "private", "void", "checkForHosedThisReferences", "(", "Node", "function", ",", "JSDocInfo", "docInfo", ",", "final", "Name", "name", ")", "{", "// A function is getting collapsed. Make sure that if it refers to \"this\",", "// it must be a constructor, interface, record, arrow function, or documented with @this.", "boolean", "isAllowedToReferenceThis", "=", "(", "docInfo", "!=", "null", "&&", "(", "docInfo", ".", "isConstructorOrInterface", "(", ")", "||", "docInfo", ".", "hasThisType", "(", ")", ")", ")", "||", "function", ".", "isArrowFunction", "(", ")", ";", "if", "(", "!", "isAllowedToReferenceThis", ")", "{", "NodeTraversal", ".", "traverse", "(", "compiler", ",", "function", ".", "getLastChild", "(", ")", ",", "new", "NodeTraversal", ".", "AbstractShallowCallback", "(", ")", "{", "@", "Override", "public", "void", "visit", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "parent", ")", "{", "if", "(", "n", ".", "isThis", "(", ")", ")", "{", "compiler", ".", "report", "(", "JSError", ".", "make", "(", "n", ",", "UNSAFE_THIS", ",", "name", ".", "getFullName", "(", ")", ")", ")", ";", "}", "}", "}", ")", ";", "}", "}" ]
Warns about any references to "this" in the given FUNCTION. The function is getting collapsed, so the references will change.
[ "Warns", "about", "any", "references", "to", "this", "in", "the", "given", "FUNCTION", ".", "The", "function", "is", "getting", "collapsed", "so", "the", "references", "will", "change", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L643-L662
24,470
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.declareVariablesForObjLitValues
private void declareVariablesForObjLitValues( Name objlitName, String alias, Node objlit, Node varNode, Node nameToAddAfter, Node varParent) { int arbitraryNameCounter = 0; boolean discardKeys = !objlitName.shouldKeepKeys(); for (Node key = objlit.getFirstChild(), nextKey; key != null; key = nextKey) { Node value = key.getFirstChild(); nextKey = key.getNext(); // A computed property, or a get or a set can not be rewritten as a VAR. We don't know what // properties will be generated by a spread. switch (key.getToken()) { case GETTER_DEF: case SETTER_DEF: case COMPUTED_PROP: case SPREAD: continue; case STRING_KEY: case MEMBER_FUNCTION_DEF: break; default: throw new IllegalStateException("Unexpected child of OBJECTLIT: " + key.toStringTree()); } // We generate arbitrary names for keys that aren't valid JavaScript // identifiers, since those keys are never referenced. (If they were, // this object literal's child names wouldn't be collapsible.) The only // reason that we don't eliminate them entirely is the off chance that // their values are expressions that have side effects. boolean isJsIdentifier = !key.isNumber() && TokenStream.isJSIdentifier(key.getString()); String propName = isJsIdentifier ? key.getString() : String.valueOf(++arbitraryNameCounter); // If the name cannot be collapsed, skip it. String qName = objlitName.getFullName() + '.' + propName; Name p = nameMap.get(qName); if (p != null && !canCollapse(p)) { continue; } String propAlias = appendPropForAlias(alias, propName); Node refNode = null; if (discardKeys) { objlit.removeChild(key); value.detach(); // Don't report a change here because the objlit has already been removed from the tree. } else { // Substitute a reference for the value. refNode = IR.name(propAlias); if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) { refNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); } key.replaceChild(value, refNode); compiler.reportChangeToEnclosingScope(refNode); } // Declare the collapsed name as a variable with the original value. Node nameNode = IR.name(propAlias); nameNode.addChildToFront(value); if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); } Node newVar = IR.var(nameNode).useSourceInfoIfMissingFromForTree(key); if (nameToAddAfter != null) { varParent.addChildAfter(newVar, nameToAddAfter); } else { varParent.addChildBefore(newVar, varNode); } compiler.reportChangeToEnclosingScope(newVar); nameToAddAfter = newVar; // Update the global name's node ancestry if it hasn't already been // done. (Duplicate keys in an object literal can bring us here twice // for the same global name.) if (isJsIdentifier && p != null) { if (!discardKeys) { p.addAliasingGetClonedFromDeclaration(refNode); } p.updateRefNode(p.getDeclaration(), nameNode); if (value.isFunction()) { checkForHosedThisReferences(value, key.getJSDocInfo(), p); } } } }
java
private void declareVariablesForObjLitValues( Name objlitName, String alias, Node objlit, Node varNode, Node nameToAddAfter, Node varParent) { int arbitraryNameCounter = 0; boolean discardKeys = !objlitName.shouldKeepKeys(); for (Node key = objlit.getFirstChild(), nextKey; key != null; key = nextKey) { Node value = key.getFirstChild(); nextKey = key.getNext(); // A computed property, or a get or a set can not be rewritten as a VAR. We don't know what // properties will be generated by a spread. switch (key.getToken()) { case GETTER_DEF: case SETTER_DEF: case COMPUTED_PROP: case SPREAD: continue; case STRING_KEY: case MEMBER_FUNCTION_DEF: break; default: throw new IllegalStateException("Unexpected child of OBJECTLIT: " + key.toStringTree()); } // We generate arbitrary names for keys that aren't valid JavaScript // identifiers, since those keys are never referenced. (If they were, // this object literal's child names wouldn't be collapsible.) The only // reason that we don't eliminate them entirely is the off chance that // their values are expressions that have side effects. boolean isJsIdentifier = !key.isNumber() && TokenStream.isJSIdentifier(key.getString()); String propName = isJsIdentifier ? key.getString() : String.valueOf(++arbitraryNameCounter); // If the name cannot be collapsed, skip it. String qName = objlitName.getFullName() + '.' + propName; Name p = nameMap.get(qName); if (p != null && !canCollapse(p)) { continue; } String propAlias = appendPropForAlias(alias, propName); Node refNode = null; if (discardKeys) { objlit.removeChild(key); value.detach(); // Don't report a change here because the objlit has already been removed from the tree. } else { // Substitute a reference for the value. refNode = IR.name(propAlias); if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) { refNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); } key.replaceChild(value, refNode); compiler.reportChangeToEnclosingScope(refNode); } // Declare the collapsed name as a variable with the original value. Node nameNode = IR.name(propAlias); nameNode.addChildToFront(value); if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); } Node newVar = IR.var(nameNode).useSourceInfoIfMissingFromForTree(key); if (nameToAddAfter != null) { varParent.addChildAfter(newVar, nameToAddAfter); } else { varParent.addChildBefore(newVar, varNode); } compiler.reportChangeToEnclosingScope(newVar); nameToAddAfter = newVar; // Update the global name's node ancestry if it hasn't already been // done. (Duplicate keys in an object literal can bring us here twice // for the same global name.) if (isJsIdentifier && p != null) { if (!discardKeys) { p.addAliasingGetClonedFromDeclaration(refNode); } p.updateRefNode(p.getDeclaration(), nameNode); if (value.isFunction()) { checkForHosedThisReferences(value, key.getJSDocInfo(), p); } } } }
[ "private", "void", "declareVariablesForObjLitValues", "(", "Name", "objlitName", ",", "String", "alias", ",", "Node", "objlit", ",", "Node", "varNode", ",", "Node", "nameToAddAfter", ",", "Node", "varParent", ")", "{", "int", "arbitraryNameCounter", "=", "0", ";", "boolean", "discardKeys", "=", "!", "objlitName", ".", "shouldKeepKeys", "(", ")", ";", "for", "(", "Node", "key", "=", "objlit", ".", "getFirstChild", "(", ")", ",", "nextKey", ";", "key", "!=", "null", ";", "key", "=", "nextKey", ")", "{", "Node", "value", "=", "key", ".", "getFirstChild", "(", ")", ";", "nextKey", "=", "key", ".", "getNext", "(", ")", ";", "// A computed property, or a get or a set can not be rewritten as a VAR. We don't know what", "// properties will be generated by a spread.", "switch", "(", "key", ".", "getToken", "(", ")", ")", "{", "case", "GETTER_DEF", ":", "case", "SETTER_DEF", ":", "case", "COMPUTED_PROP", ":", "case", "SPREAD", ":", "continue", ";", "case", "STRING_KEY", ":", "case", "MEMBER_FUNCTION_DEF", ":", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unexpected child of OBJECTLIT: \"", "+", "key", ".", "toStringTree", "(", ")", ")", ";", "}", "// We generate arbitrary names for keys that aren't valid JavaScript", "// identifiers, since those keys are never referenced. (If they were,", "// this object literal's child names wouldn't be collapsible.) The only", "// reason that we don't eliminate them entirely is the off chance that", "// their values are expressions that have side effects.", "boolean", "isJsIdentifier", "=", "!", "key", ".", "isNumber", "(", ")", "&&", "TokenStream", ".", "isJSIdentifier", "(", "key", ".", "getString", "(", ")", ")", ";", "String", "propName", "=", "isJsIdentifier", "?", "key", ".", "getString", "(", ")", ":", "String", ".", "valueOf", "(", "++", "arbitraryNameCounter", ")", ";", "// If the name cannot be collapsed, skip it.", "String", "qName", "=", "objlitName", ".", "getFullName", "(", ")", "+", "'", "'", "+", "propName", ";", "Name", "p", "=", "nameMap", ".", "get", "(", "qName", ")", ";", "if", "(", "p", "!=", "null", "&&", "!", "canCollapse", "(", "p", ")", ")", "{", "continue", ";", "}", "String", "propAlias", "=", "appendPropForAlias", "(", "alias", ",", "propName", ")", ";", "Node", "refNode", "=", "null", ";", "if", "(", "discardKeys", ")", "{", "objlit", ".", "removeChild", "(", "key", ")", ";", "value", ".", "detach", "(", ")", ";", "// Don't report a change here because the objlit has already been removed from the tree.", "}", "else", "{", "// Substitute a reference for the value.", "refNode", "=", "IR", ".", "name", "(", "propAlias", ")", ";", "if", "(", "key", ".", "getBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ")", ")", "{", "refNode", ".", "putBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ",", "true", ")", ";", "}", "key", ".", "replaceChild", "(", "value", ",", "refNode", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "refNode", ")", ";", "}", "// Declare the collapsed name as a variable with the original value.", "Node", "nameNode", "=", "IR", ".", "name", "(", "propAlias", ")", ";", "nameNode", ".", "addChildToFront", "(", "value", ")", ";", "if", "(", "key", ".", "getBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ")", ")", "{", "nameNode", ".", "putBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ",", "true", ")", ";", "}", "Node", "newVar", "=", "IR", ".", "var", "(", "nameNode", ")", ".", "useSourceInfoIfMissingFromForTree", "(", "key", ")", ";", "if", "(", "nameToAddAfter", "!=", "null", ")", "{", "varParent", ".", "addChildAfter", "(", "newVar", ",", "nameToAddAfter", ")", ";", "}", "else", "{", "varParent", ".", "addChildBefore", "(", "newVar", ",", "varNode", ")", ";", "}", "compiler", ".", "reportChangeToEnclosingScope", "(", "newVar", ")", ";", "nameToAddAfter", "=", "newVar", ";", "// Update the global name's node ancestry if it hasn't already been", "// done. (Duplicate keys in an object literal can bring us here twice", "// for the same global name.)", "if", "(", "isJsIdentifier", "&&", "p", "!=", "null", ")", "{", "if", "(", "!", "discardKeys", ")", "{", "p", ".", "addAliasingGetClonedFromDeclaration", "(", "refNode", ")", ";", "}", "p", ".", "updateRefNode", "(", "p", ".", "getDeclaration", "(", ")", ",", "nameNode", ")", ";", "if", "(", "value", ".", "isFunction", "(", ")", ")", "{", "checkForHosedThisReferences", "(", "value", ",", "key", ".", "getJSDocInfo", "(", ")", ",", "p", ")", ";", "}", "}", "}", "}" ]
Declares global variables to serve as aliases for the values in an object literal, optionally removing all of the object literal's keys and values. @param alias The object literal's flattened name (e.g. "a$b$c") @param objlit The OBJLIT node @param varNode The VAR node to which new global variables should be added as children @param nameToAddAfter The child of {@code varNode} after which new variables should be added (may be null) @param varParent {@code varNode}'s parent
[ "Declares", "global", "variables", "to", "serve", "as", "aliases", "for", "the", "values", "in", "an", "object", "literal", "optionally", "removing", "all", "of", "the", "object", "literal", "s", "keys", "and", "values", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L786-L878
24,471
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.addStubsForUndeclaredProperties
private void addStubsForUndeclaredProperties(Name n, String alias, Node parent, Node addAfter) { checkState(n.canCollapseUnannotatedChildNames(), n); checkArgument(NodeUtil.isStatementBlock(parent), parent); checkNotNull(addAfter); if (n.props == null) { return; } for (Name p : n.props) { if (p.needsToBeStubbed()) { String propAlias = appendPropForAlias(alias, p.getBaseName()); Node nameNode = IR.name(propAlias); Node newVar = IR.var(nameNode).useSourceInfoIfMissingFromForTree(addAfter); parent.addChildAfter(newVar, addAfter); addAfter = newVar; compiler.reportChangeToEnclosingScope(newVar); // Determine if this is a constant var by checking the first // reference to it. Don't check the declaration, as it might be null. if (p.getFirstRef().getNode().getLastChild().getBooleanProp(Node.IS_CONSTANT_NAME)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); compiler.reportChangeToEnclosingScope(nameNode); } } } }
java
private void addStubsForUndeclaredProperties(Name n, String alias, Node parent, Node addAfter) { checkState(n.canCollapseUnannotatedChildNames(), n); checkArgument(NodeUtil.isStatementBlock(parent), parent); checkNotNull(addAfter); if (n.props == null) { return; } for (Name p : n.props) { if (p.needsToBeStubbed()) { String propAlias = appendPropForAlias(alias, p.getBaseName()); Node nameNode = IR.name(propAlias); Node newVar = IR.var(nameNode).useSourceInfoIfMissingFromForTree(addAfter); parent.addChildAfter(newVar, addAfter); addAfter = newVar; compiler.reportChangeToEnclosingScope(newVar); // Determine if this is a constant var by checking the first // reference to it. Don't check the declaration, as it might be null. if (p.getFirstRef().getNode().getLastChild().getBooleanProp(Node.IS_CONSTANT_NAME)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); compiler.reportChangeToEnclosingScope(nameNode); } } } }
[ "private", "void", "addStubsForUndeclaredProperties", "(", "Name", "n", ",", "String", "alias", ",", "Node", "parent", ",", "Node", "addAfter", ")", "{", "checkState", "(", "n", ".", "canCollapseUnannotatedChildNames", "(", ")", ",", "n", ")", ";", "checkArgument", "(", "NodeUtil", ".", "isStatementBlock", "(", "parent", ")", ",", "parent", ")", ";", "checkNotNull", "(", "addAfter", ")", ";", "if", "(", "n", ".", "props", "==", "null", ")", "{", "return", ";", "}", "for", "(", "Name", "p", ":", "n", ".", "props", ")", "{", "if", "(", "p", ".", "needsToBeStubbed", "(", ")", ")", "{", "String", "propAlias", "=", "appendPropForAlias", "(", "alias", ",", "p", ".", "getBaseName", "(", ")", ")", ";", "Node", "nameNode", "=", "IR", ".", "name", "(", "propAlias", ")", ";", "Node", "newVar", "=", "IR", ".", "var", "(", "nameNode", ")", ".", "useSourceInfoIfMissingFromForTree", "(", "addAfter", ")", ";", "parent", ".", "addChildAfter", "(", "newVar", ",", "addAfter", ")", ";", "addAfter", "=", "newVar", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "newVar", ")", ";", "// Determine if this is a constant var by checking the first", "// reference to it. Don't check the declaration, as it might be null.", "if", "(", "p", ".", "getFirstRef", "(", ")", ".", "getNode", "(", ")", ".", "getLastChild", "(", ")", ".", "getBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ")", ")", "{", "nameNode", ".", "putBooleanProp", "(", "Node", ".", "IS_CONSTANT_NAME", ",", "true", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "nameNode", ")", ";", "}", "}", "}", "}" ]
Adds global variable "stubs" for any properties of a global name that are only set in a local scope or read but never set. @param n An object representing a global name (e.g. "a", "a.b.c") @param alias The flattened name of the object whose properties we are adding stubs for (e.g. "a$b$c") @param parent The node to which new global variables should be added as children @param addAfter The child of after which new variables should be added
[ "Adds", "global", "variable", "stubs", "for", "any", "properties", "of", "a", "global", "name", "that", "are", "only", "set", "in", "a", "local", "scope", "or", "read", "but", "never", "set", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L890-L913
24,472
google/closure-compiler
src/com/google/javascript/jscomp/AbstractPeepholeOptimization.java
AbstractPeepholeOptimization.report
protected void report(DiagnosticType diagnostic, Node n) { JSError error = JSError.make(n, diagnostic, n.toString()); compiler.report(error); }
java
protected void report(DiagnosticType diagnostic, Node n) { JSError error = JSError.make(n, diagnostic, n.toString()); compiler.report(error); }
[ "protected", "void", "report", "(", "DiagnosticType", "diagnostic", ",", "Node", "n", ")", "{", "JSError", "error", "=", "JSError", ".", "make", "(", "n", ",", "diagnostic", ",", "n", ".", "toString", "(", ")", ")", ";", "compiler", ".", "report", "(", "error", ")", ";", "}" ]
Helper method for reporting an error to the compiler when applying a peephole optimization. @param diagnostic The error type @param n The node for which the error should be reported
[ "Helper", "method", "for", "reporting", "an", "error", "to", "the", "compiler", "when", "applying", "a", "peephole", "optimization", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AbstractPeepholeOptimization.java#L53-L56
24,473
google/closure-compiler
src/com/google/javascript/jscomp/AbstractPeepholeOptimization.java
AbstractPeepholeOptimization.areNodesEqualForInlining
protected boolean areNodesEqualForInlining(Node n1, Node n2) { /* Our implementation delegates to the compiler. We provide this * method because we don't want to expose Compiler to PeepholeOptimizations. */ checkNotNull(compiler); return compiler.areNodesEqualForInlining(n1, n2); }
java
protected boolean areNodesEqualForInlining(Node n1, Node n2) { /* Our implementation delegates to the compiler. We provide this * method because we don't want to expose Compiler to PeepholeOptimizations. */ checkNotNull(compiler); return compiler.areNodesEqualForInlining(n1, n2); }
[ "protected", "boolean", "areNodesEqualForInlining", "(", "Node", "n1", ",", "Node", "n2", ")", "{", "/* Our implementation delegates to the compiler. We provide this\n * method because we don't want to expose Compiler to PeepholeOptimizations.\n */", "checkNotNull", "(", "compiler", ")", ";", "return", "compiler", ".", "areNodesEqualForInlining", "(", "n1", ",", "n2", ")", ";", "}" ]
Are the nodes equal for the purpose of inlining? If type aware optimizations are on, type equality is checked.
[ "Are", "the", "nodes", "equal", "for", "the", "purpose", "of", "inlining?", "If", "type", "aware", "optimizations", "are", "on", "type", "equality", "is", "checked", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AbstractPeepholeOptimization.java#L62-L68
24,474
google/closure-compiler
src/com/google/javascript/jscomp/gwt/client/Es6ClassConverterJsDocHelper.java
Es6ClassConverterJsDocHelper.getClassJsDoc
@JsMethod(name = "getClassJsDoc", namespace = "jscomp") public static String getClassJsDoc(String jsDoc) { if (Strings.isNullOrEmpty(jsDoc)) { return null; } Config config = Config.builder() .setLanguageMode(LanguageMode.ECMASCRIPT3) .setStrictMode(Config.StrictMode.SLOPPY) .setJsDocParsingMode(JsDocParsing.INCLUDE_DESCRIPTIONS_WITH_WHITESPACE) .build(); JsDocInfoParser parser = new JsDocInfoParser( // Stream expects us to remove the leading /** new JsDocTokenStream(jsDoc.substring(3)), jsDoc, 0, null, config, ErrorReporter.NULL_INSTANCE); parser.parse(); JSDocInfo parsed = parser.retrieveAndResetParsedJSDocInfo(); JSDocInfo classComments = parsed.cloneClassDoc(); JSDocInfoPrinter printer = new JSDocInfoPrinter(/* useOriginalName= */ true, /* printDesc= */ true); String comment = printer.print(classComments); // Don't return empty comments, return null instead. if (comment == null || RegExp.compile("\\s*/\\*\\*\\s*\\*/\\s*").test(comment)) { return null; } return comment.trim(); }
java
@JsMethod(name = "getClassJsDoc", namespace = "jscomp") public static String getClassJsDoc(String jsDoc) { if (Strings.isNullOrEmpty(jsDoc)) { return null; } Config config = Config.builder() .setLanguageMode(LanguageMode.ECMASCRIPT3) .setStrictMode(Config.StrictMode.SLOPPY) .setJsDocParsingMode(JsDocParsing.INCLUDE_DESCRIPTIONS_WITH_WHITESPACE) .build(); JsDocInfoParser parser = new JsDocInfoParser( // Stream expects us to remove the leading /** new JsDocTokenStream(jsDoc.substring(3)), jsDoc, 0, null, config, ErrorReporter.NULL_INSTANCE); parser.parse(); JSDocInfo parsed = parser.retrieveAndResetParsedJSDocInfo(); JSDocInfo classComments = parsed.cloneClassDoc(); JSDocInfoPrinter printer = new JSDocInfoPrinter(/* useOriginalName= */ true, /* printDesc= */ true); String comment = printer.print(classComments); // Don't return empty comments, return null instead. if (comment == null || RegExp.compile("\\s*/\\*\\*\\s*\\*/\\s*").test(comment)) { return null; } return comment.trim(); }
[ "@", "JsMethod", "(", "name", "=", "\"getClassJsDoc\"", ",", "namespace", "=", "\"jscomp\"", ")", "public", "static", "String", "getClassJsDoc", "(", "String", "jsDoc", ")", "{", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "jsDoc", ")", ")", "{", "return", "null", ";", "}", "Config", "config", "=", "Config", ".", "builder", "(", ")", ".", "setLanguageMode", "(", "LanguageMode", ".", "ECMASCRIPT3", ")", ".", "setStrictMode", "(", "Config", ".", "StrictMode", ".", "SLOPPY", ")", ".", "setJsDocParsingMode", "(", "JsDocParsing", ".", "INCLUDE_DESCRIPTIONS_WITH_WHITESPACE", ")", ".", "build", "(", ")", ";", "JsDocInfoParser", "parser", "=", "new", "JsDocInfoParser", "(", "// Stream expects us to remove the leading /**", "new", "JsDocTokenStream", "(", "jsDoc", ".", "substring", "(", "3", ")", ")", ",", "jsDoc", ",", "0", ",", "null", ",", "config", ",", "ErrorReporter", ".", "NULL_INSTANCE", ")", ";", "parser", ".", "parse", "(", ")", ";", "JSDocInfo", "parsed", "=", "parser", ".", "retrieveAndResetParsedJSDocInfo", "(", ")", ";", "JSDocInfo", "classComments", "=", "parsed", ".", "cloneClassDoc", "(", ")", ";", "JSDocInfoPrinter", "printer", "=", "new", "JSDocInfoPrinter", "(", "/* useOriginalName= */", "true", ",", "/* printDesc= */", "true", ")", ";", "String", "comment", "=", "printer", ".", "print", "(", "classComments", ")", ";", "// Don't return empty comments, return null instead.", "if", "(", "comment", "==", "null", "||", "RegExp", ".", "compile", "(", "\"\\\\s*/\\\\*\\\\*\\\\s*\\\\*/\\\\s*\"", ")", ".", "test", "(", "comment", ")", ")", "{", "return", "null", ";", "}", "return", "comment", ".", "trim", "(", ")", ";", "}" ]
Gets JS Doc that should be retained on a class. Used to upgrade ES5 to ES6 classes and separate class from constructor comments.
[ "Gets", "JS", "Doc", "that", "should", "be", "retained", "on", "a", "class", ".", "Used", "to", "upgrade", "ES5", "to", "ES6", "classes", "and", "separate", "class", "from", "constructor", "comments", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/gwt/client/Es6ClassConverterJsDocHelper.java#L57-L88
24,475
google/closure-compiler
src/com/google/javascript/jscomp/gwt/client/Es6ClassConverterJsDocHelper.java
Es6ClassConverterJsDocHelper.getConstructorJsDoc
@JsMethod(name = "getConstructorJsDoc", namespace = "jscomp") public static String getConstructorJsDoc(String jsDoc) { if (Strings.isNullOrEmpty(jsDoc)) { return null; } Config config = Config.builder() .setLanguageMode(LanguageMode.ECMASCRIPT3) .setStrictMode(Config.StrictMode.SLOPPY) .setJsDocParsingMode(JsDocParsing.INCLUDE_DESCRIPTIONS_WITH_WHITESPACE) .build(); JsDocInfoParser parser = new JsDocInfoParser( // Stream expects us to remove the leading /** new JsDocTokenStream(jsDoc.substring(3)), jsDoc, 0, null, config, ErrorReporter.NULL_INSTANCE); parser.parse(); JSDocInfo parsed = parser.retrieveAndResetParsedJSDocInfo(); JSDocInfo params = parsed.cloneConstructorDoc(); if (parsed.getParameterNames().isEmpty() && parsed.getSuppressions().isEmpty()) { return null; } JSDocInfoPrinter printer = new JSDocInfoPrinter(/* useOriginalName= */ true, /* printDesc= */ true); return printer.print(params).trim(); }
java
@JsMethod(name = "getConstructorJsDoc", namespace = "jscomp") public static String getConstructorJsDoc(String jsDoc) { if (Strings.isNullOrEmpty(jsDoc)) { return null; } Config config = Config.builder() .setLanguageMode(LanguageMode.ECMASCRIPT3) .setStrictMode(Config.StrictMode.SLOPPY) .setJsDocParsingMode(JsDocParsing.INCLUDE_DESCRIPTIONS_WITH_WHITESPACE) .build(); JsDocInfoParser parser = new JsDocInfoParser( // Stream expects us to remove the leading /** new JsDocTokenStream(jsDoc.substring(3)), jsDoc, 0, null, config, ErrorReporter.NULL_INSTANCE); parser.parse(); JSDocInfo parsed = parser.retrieveAndResetParsedJSDocInfo(); JSDocInfo params = parsed.cloneConstructorDoc(); if (parsed.getParameterNames().isEmpty() && parsed.getSuppressions().isEmpty()) { return null; } JSDocInfoPrinter printer = new JSDocInfoPrinter(/* useOriginalName= */ true, /* printDesc= */ true); return printer.print(params).trim(); }
[ "@", "JsMethod", "(", "name", "=", "\"getConstructorJsDoc\"", ",", "namespace", "=", "\"jscomp\"", ")", "public", "static", "String", "getConstructorJsDoc", "(", "String", "jsDoc", ")", "{", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "jsDoc", ")", ")", "{", "return", "null", ";", "}", "Config", "config", "=", "Config", ".", "builder", "(", ")", ".", "setLanguageMode", "(", "LanguageMode", ".", "ECMASCRIPT3", ")", ".", "setStrictMode", "(", "Config", ".", "StrictMode", ".", "SLOPPY", ")", ".", "setJsDocParsingMode", "(", "JsDocParsing", ".", "INCLUDE_DESCRIPTIONS_WITH_WHITESPACE", ")", ".", "build", "(", ")", ";", "JsDocInfoParser", "parser", "=", "new", "JsDocInfoParser", "(", "// Stream expects us to remove the leading /**", "new", "JsDocTokenStream", "(", "jsDoc", ".", "substring", "(", "3", ")", ")", ",", "jsDoc", ",", "0", ",", "null", ",", "config", ",", "ErrorReporter", ".", "NULL_INSTANCE", ")", ";", "parser", ".", "parse", "(", ")", ";", "JSDocInfo", "parsed", "=", "parser", ".", "retrieveAndResetParsedJSDocInfo", "(", ")", ";", "JSDocInfo", "params", "=", "parsed", ".", "cloneConstructorDoc", "(", ")", ";", "if", "(", "parsed", ".", "getParameterNames", "(", ")", ".", "isEmpty", "(", ")", "&&", "parsed", ".", "getSuppressions", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "JSDocInfoPrinter", "printer", "=", "new", "JSDocInfoPrinter", "(", "/* useOriginalName= */", "true", ",", "/* printDesc= */", "true", ")", ";", "return", "printer", ".", "print", "(", "params", ")", ".", "trim", "(", ")", ";", "}" ]
Gets JS Doc that should be moved to a constructor. Used to upgrade ES5 to ES6 classes and separate class from constructor comments.
[ "Gets", "JS", "Doc", "that", "should", "be", "moved", "to", "a", "constructor", ".", "Used", "to", "upgrade", "ES5", "to", "ES6", "classes", "and", "separate", "class", "from", "constructor", "comments", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/gwt/client/Es6ClassConverterJsDocHelper.java#L94-L123
24,476
google/closure-compiler
src/com/google/javascript/jscomp/CompilerInput.java
CompilerInput.getRequires
@Override public ImmutableList<Require> getRequires() { if (hasFullParseDependencyInfo) { return ImmutableList.copyOf(orderedRequires); } return getDependencyInfo().getRequires(); }
java
@Override public ImmutableList<Require> getRequires() { if (hasFullParseDependencyInfo) { return ImmutableList.copyOf(orderedRequires); } return getDependencyInfo().getRequires(); }
[ "@", "Override", "public", "ImmutableList", "<", "Require", ">", "getRequires", "(", ")", "{", "if", "(", "hasFullParseDependencyInfo", ")", "{", "return", "ImmutableList", ".", "copyOf", "(", "orderedRequires", ")", ";", "}", "return", "getDependencyInfo", "(", ")", ".", "getRequires", "(", ")", ";", "}" ]
Gets a list of types depended on by this input.
[ "Gets", "a", "list", "of", "types", "depended", "on", "by", "this", "input", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CompilerInput.java#L161-L168
24,477
google/closure-compiler
src/com/google/javascript/jscomp/CompilerInput.java
CompilerInput.getKnownRequires
ImmutableCollection<Require> getKnownRequires() { return concat( dependencyInfo != null ? dependencyInfo.getRequires() : ImmutableList.of(), extraRequires); }
java
ImmutableCollection<Require> getKnownRequires() { return concat( dependencyInfo != null ? dependencyInfo.getRequires() : ImmutableList.of(), extraRequires); }
[ "ImmutableCollection", "<", "Require", ">", "getKnownRequires", "(", ")", "{", "return", "concat", "(", "dependencyInfo", "!=", "null", "?", "dependencyInfo", ".", "getRequires", "(", ")", ":", "ImmutableList", ".", "of", "(", ")", ",", "extraRequires", ")", ";", "}" ]
Gets a list of namespaces and paths depended on by this input, but does not attempt to regenerate the dependency information. Typically this occurs from module rewriting.
[ "Gets", "a", "list", "of", "namespaces", "and", "paths", "depended", "on", "by", "this", "input", "but", "does", "not", "attempt", "to", "regenerate", "the", "dependency", "information", ".", "Typically", "this", "occurs", "from", "module", "rewriting", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CompilerInput.java#L179-L182
24,478
google/closure-compiler
src/com/google/javascript/jscomp/CompilerInput.java
CompilerInput.getKnownProvides
ImmutableCollection<String> getKnownProvides() { return concat( dependencyInfo != null ? dependencyInfo.getProvides() : ImmutableList.<String>of(), extraProvides); }
java
ImmutableCollection<String> getKnownProvides() { return concat( dependencyInfo != null ? dependencyInfo.getProvides() : ImmutableList.<String>of(), extraProvides); }
[ "ImmutableCollection", "<", "String", ">", "getKnownProvides", "(", ")", "{", "return", "concat", "(", "dependencyInfo", "!=", "null", "?", "dependencyInfo", ".", "getProvides", "(", ")", ":", "ImmutableList", ".", "<", "String", ">", "of", "(", ")", ",", "extraProvides", ")", ";", "}" ]
Gets a list of types provided, but does not attempt to regenerate the dependency information. Typically this occurs from module rewriting.
[ "Gets", "a", "list", "of", "types", "provided", "but", "does", "not", "attempt", "to", "regenerate", "the", "dependency", "information", ".", "Typically", "this", "occurs", "from", "module", "rewriting", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CompilerInput.java#L209-L213
24,479
google/closure-compiler
src/com/google/javascript/jscomp/CompilerInput.java
CompilerInput.addOrderedRequire
public boolean addOrderedRequire(Require require) { if (!orderedRequires.contains(require)) { orderedRequires.add(require); return true; } return false; }
java
public boolean addOrderedRequire(Require require) { if (!orderedRequires.contains(require)) { orderedRequires.add(require); return true; } return false; }
[ "public", "boolean", "addOrderedRequire", "(", "Require", "require", ")", "{", "if", "(", "!", "orderedRequires", ".", "contains", "(", "require", ")", ")", "{", "orderedRequires", ".", "add", "(", "require", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Registers a type that this input depends on in the order seen in the file.
[ "Registers", "a", "type", "that", "this", "input", "depends", "on", "in", "the", "order", "seen", "in", "the", "file", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CompilerInput.java#L224-L230
24,480
google/closure-compiler
src/com/google/javascript/jscomp/CompilerInput.java
CompilerInput.addDynamicRequire
public boolean addDynamicRequire(String require) { if (!dynamicRequires.contains(require)) { dynamicRequires.add(require); return true; } return false; }
java
public boolean addDynamicRequire(String require) { if (!dynamicRequires.contains(require)) { dynamicRequires.add(require); return true; } return false; }
[ "public", "boolean", "addDynamicRequire", "(", "String", "require", ")", "{", "if", "(", "!", "dynamicRequires", ".", "contains", "(", "require", ")", ")", "{", "dynamicRequires", ".", "add", "(", "require", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Registers a type that this input depends on in the order seen in the file. The type was loaded dynamically so while it is part of the dependency graph, it does not need sorted before this input.
[ "Registers", "a", "type", "that", "this", "input", "depends", "on", "in", "the", "order", "seen", "in", "the", "file", ".", "The", "type", "was", "loaded", "dynamically", "so", "while", "it", "is", "part", "of", "the", "dependency", "graph", "it", "does", "not", "need", "sorted", "before", "this", "input", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CompilerInput.java#L246-L252
24,481
google/closure-compiler
src/com/google/javascript/jscomp/CompilerInput.java
CompilerInput.getDependencyInfo
DependencyInfo getDependencyInfo() { if (dependencyInfo == null) { dependencyInfo = generateDependencyInfo(); } if (!extraRequires.isEmpty() || !extraProvides.isEmpty()) { dependencyInfo = SimpleDependencyInfo.builder(getName(), getName()) .setProvides(concat(dependencyInfo.getProvides(), extraProvides)) .setRequires(concat(dependencyInfo.getRequires(), extraRequires)) .setTypeRequires(dependencyInfo.getTypeRequires()) .setLoadFlags(dependencyInfo.getLoadFlags()) .setHasExternsAnnotation(dependencyInfo.getHasExternsAnnotation()) .setHasNoCompileAnnotation(dependencyInfo.getHasNoCompileAnnotation()) .build(); extraRequires.clear(); extraProvides.clear(); } return dependencyInfo; }
java
DependencyInfo getDependencyInfo() { if (dependencyInfo == null) { dependencyInfo = generateDependencyInfo(); } if (!extraRequires.isEmpty() || !extraProvides.isEmpty()) { dependencyInfo = SimpleDependencyInfo.builder(getName(), getName()) .setProvides(concat(dependencyInfo.getProvides(), extraProvides)) .setRequires(concat(dependencyInfo.getRequires(), extraRequires)) .setTypeRequires(dependencyInfo.getTypeRequires()) .setLoadFlags(dependencyInfo.getLoadFlags()) .setHasExternsAnnotation(dependencyInfo.getHasExternsAnnotation()) .setHasNoCompileAnnotation(dependencyInfo.getHasNoCompileAnnotation()) .build(); extraRequires.clear(); extraProvides.clear(); } return dependencyInfo; }
[ "DependencyInfo", "getDependencyInfo", "(", ")", "{", "if", "(", "dependencyInfo", "==", "null", ")", "{", "dependencyInfo", "=", "generateDependencyInfo", "(", ")", ";", "}", "if", "(", "!", "extraRequires", ".", "isEmpty", "(", ")", "||", "!", "extraProvides", ".", "isEmpty", "(", ")", ")", "{", "dependencyInfo", "=", "SimpleDependencyInfo", ".", "builder", "(", "getName", "(", ")", ",", "getName", "(", ")", ")", ".", "setProvides", "(", "concat", "(", "dependencyInfo", ".", "getProvides", "(", ")", ",", "extraProvides", ")", ")", ".", "setRequires", "(", "concat", "(", "dependencyInfo", ".", "getRequires", "(", ")", ",", "extraRequires", ")", ")", ".", "setTypeRequires", "(", "dependencyInfo", ".", "getTypeRequires", "(", ")", ")", ".", "setLoadFlags", "(", "dependencyInfo", ".", "getLoadFlags", "(", ")", ")", ".", "setHasExternsAnnotation", "(", "dependencyInfo", ".", "getHasExternsAnnotation", "(", ")", ")", ".", "setHasNoCompileAnnotation", "(", "dependencyInfo", ".", "getHasNoCompileAnnotation", "(", ")", ")", ".", "build", "(", ")", ";", "extraRequires", ".", "clear", "(", ")", ";", "extraProvides", ".", "clear", "(", ")", ";", "}", "return", "dependencyInfo", ";", "}" ]
Returns the DependencyInfo object, generating it lazily if necessary.
[ "Returns", "the", "DependencyInfo", "object", "generating", "it", "lazily", "if", "necessary", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CompilerInput.java#L272-L290
24,482
google/closure-compiler
src/com/google/javascript/jscomp/CompilerInput.java
CompilerInput.setModule
public void setModule(JSModule module) { // An input may only belong to one module. checkArgument(module == null || this.module == null || this.module == module); this.module = module; }
java
public void setModule(JSModule module) { // An input may only belong to one module. checkArgument(module == null || this.module == null || this.module == module); this.module = module; }
[ "public", "void", "setModule", "(", "JSModule", "module", ")", "{", "// An input may only belong to one module.", "checkArgument", "(", "module", "==", "null", "||", "this", ".", "module", "==", "null", "||", "this", ".", "module", "==", "module", ")", ";", "this", ".", "module", "=", "module", ";", "}" ]
Sets the module to which the input belongs.
[ "Sets", "the", "module", "to", "which", "the", "input", "belongs", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CompilerInput.java#L516-L520
24,483
google/closure-compiler
src/com/google/javascript/jscomp/Es6ConvertSuperConstructorCalls.java
Es6ConvertSuperConstructorCalls.isUnextendableNativeClass
private boolean isUnextendableNativeClass(NodeTraversal t, String className) { // This list originally taken from the list of built-in objects at // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference // as of 2016-10-22. // - Intl.* classes were left out, because it doesn't seem worth the extra effort // of handling the qualified name. // - Deprecated and experimental classes were left out. switch (className) { case "Array": case "ArrayBuffer": case "Boolean": case "DataView": case "Date": case "Float32Array": case "Function": case "Generator": case "GeneratorFunction": case "Int16Array": case "Int32Array": case "Int8Array": case "InternalError": case "Map": case "Number": case "Promise": case "Proxy": case "RegExp": case "Set": case "String": case "Symbol": case "TypedArray": case "Uint16Array": case "Uint32Array": case "Uint8Array": case "Uint8ClampedArray": case "WeakMap": case "WeakSet": return !isDefinedInSources(t, className); default: return false; } }
java
private boolean isUnextendableNativeClass(NodeTraversal t, String className) { // This list originally taken from the list of built-in objects at // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference // as of 2016-10-22. // - Intl.* classes were left out, because it doesn't seem worth the extra effort // of handling the qualified name. // - Deprecated and experimental classes were left out. switch (className) { case "Array": case "ArrayBuffer": case "Boolean": case "DataView": case "Date": case "Float32Array": case "Function": case "Generator": case "GeneratorFunction": case "Int16Array": case "Int32Array": case "Int8Array": case "InternalError": case "Map": case "Number": case "Promise": case "Proxy": case "RegExp": case "Set": case "String": case "Symbol": case "TypedArray": case "Uint16Array": case "Uint32Array": case "Uint8Array": case "Uint8ClampedArray": case "WeakMap": case "WeakSet": return !isDefinedInSources(t, className); default: return false; } }
[ "private", "boolean", "isUnextendableNativeClass", "(", "NodeTraversal", "t", ",", "String", "className", ")", "{", "// This list originally taken from the list of built-in objects at", "// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference", "// as of 2016-10-22.", "// - Intl.* classes were left out, because it doesn't seem worth the extra effort", "// of handling the qualified name.", "// - Deprecated and experimental classes were left out.", "switch", "(", "className", ")", "{", "case", "\"Array\"", ":", "case", "\"ArrayBuffer\"", ":", "case", "\"Boolean\"", ":", "case", "\"DataView\"", ":", "case", "\"Date\"", ":", "case", "\"Float32Array\"", ":", "case", "\"Function\"", ":", "case", "\"Generator\"", ":", "case", "\"GeneratorFunction\"", ":", "case", "\"Int16Array\"", ":", "case", "\"Int32Array\"", ":", "case", "\"Int8Array\"", ":", "case", "\"InternalError\"", ":", "case", "\"Map\"", ":", "case", "\"Number\"", ":", "case", "\"Promise\"", ":", "case", "\"Proxy\"", ":", "case", "\"RegExp\"", ":", "case", "\"Set\"", ":", "case", "\"String\"", ":", "case", "\"Symbol\"", ":", "case", "\"TypedArray\"", ":", "case", "\"Uint16Array\"", ":", "case", "\"Uint32Array\"", ":", "case", "\"Uint8Array\"", ":", "case", "\"Uint8ClampedArray\"", ":", "case", "\"WeakMap\"", ":", "case", "\"WeakSet\"", ":", "return", "!", "isDefinedInSources", "(", "t", ",", "className", ")", ";", "default", ":", "return", "false", ";", "}", "}" ]
Is the given class a native class for which we cannot properly transpile extension? @param t @param className
[ "Is", "the", "given", "class", "a", "native", "class", "for", "which", "we", "cannot", "properly", "transpile", "extension?" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6ConvertSuperConstructorCalls.java#L434-L474
24,484
google/closure-compiler
src/com/google/javascript/jscomp/Es6ConvertSuperConstructorCalls.java
Es6ConvertSuperConstructorCalls.isDefinedInSources
private boolean isDefinedInSources(NodeTraversal t, String varName) { Var objectVar = t.getScope().getVar(varName); return objectVar != null && !objectVar.isExtern(); }
java
private boolean isDefinedInSources(NodeTraversal t, String varName) { Var objectVar = t.getScope().getVar(varName); return objectVar != null && !objectVar.isExtern(); }
[ "private", "boolean", "isDefinedInSources", "(", "NodeTraversal", "t", ",", "String", "varName", ")", "{", "Var", "objectVar", "=", "t", ".", "getScope", "(", ")", ".", "getVar", "(", "varName", ")", ";", "return", "objectVar", "!=", "null", "&&", "!", "objectVar", ".", "isExtern", "(", ")", ";", "}" ]
Is a variable with the given name defined in the source code being compiled? <p>Please note that the call to {@code t.getScope()} is expensive, so we should avoid calling this method when possible. @param t @param varName
[ "Is", "a", "variable", "with", "the", "given", "name", "defined", "in", "the", "source", "code", "being", "compiled?" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6ConvertSuperConstructorCalls.java#L484-L487
24,485
google/closure-compiler
src/com/google/javascript/jscomp/MinimizedCondition.java
MinimizedCondition.fromConditionNode
static MinimizedCondition fromConditionNode(Node n) { checkState(n.getParent() != null); switch (n.getToken()) { case NOT: case AND: case OR: case HOOK: case COMMA: return computeMinimizedCondition(n); default: return unoptimized(n); } }
java
static MinimizedCondition fromConditionNode(Node n) { checkState(n.getParent() != null); switch (n.getToken()) { case NOT: case AND: case OR: case HOOK: case COMMA: return computeMinimizedCondition(n); default: return unoptimized(n); } }
[ "static", "MinimizedCondition", "fromConditionNode", "(", "Node", "n", ")", "{", "checkState", "(", "n", ".", "getParent", "(", ")", "!=", "null", ")", ";", "switch", "(", "n", ".", "getToken", "(", ")", ")", "{", "case", "NOT", ":", "case", "AND", ":", "case", "OR", ":", "case", "HOOK", ":", "case", "COMMA", ":", "return", "computeMinimizedCondition", "(", "n", ")", ";", "default", ":", "return", "unoptimized", "(", "n", ")", ";", "}", "}" ]
Returns a MinimizedCondition that represents the condition node after minimization.
[ "Returns", "a", "MinimizedCondition", "that", "represents", "the", "condition", "node", "after", "minimization", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MinimizedCondition.java#L65-L77
24,486
google/closure-compiler
src/com/google/javascript/jscomp/MinimizedCondition.java
MinimizedCondition.pickBest
static MeasuredNode pickBest(MeasuredNode a, MeasuredNode b) { if (a.length == b.length) { return (b.isChanged()) ? a : b; } return (a.length < b.length) ? a : b; }
java
static MeasuredNode pickBest(MeasuredNode a, MeasuredNode b) { if (a.length == b.length) { return (b.isChanged()) ? a : b; } return (a.length < b.length) ? a : b; }
[ "static", "MeasuredNode", "pickBest", "(", "MeasuredNode", "a", ",", "MeasuredNode", "b", ")", "{", "if", "(", "a", ".", "length", "==", "b", ".", "length", ")", "{", "return", "(", "b", ".", "isChanged", "(", ")", ")", "?", "a", ":", "b", ";", "}", "return", "(", "a", ".", "length", "<", "b", ".", "length", ")", "?", "a", ":", "b", ";", "}" ]
return the best, prefer unchanged
[ "return", "the", "best", "prefer", "unchanged" ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MinimizedCondition.java#L128-L134
24,487
google/closure-compiler
src/com/google/javascript/jscomp/MinimizedCondition.java
MinimizedCondition.computeMinimizedCondition
private static MinimizedCondition computeMinimizedCondition(Node n) { switch (n.getToken()) { case NOT: { MinimizedCondition subtree = computeMinimizedCondition(n.getFirstChild()); MeasuredNode positive = pickBest( MeasuredNode.addNode(n, subtree.positive), subtree.negative); MeasuredNode negative = pickBest( subtree.negative.negate(), subtree.positive); return new MinimizedCondition(positive, negative); } case AND: case OR: { Node complementNode = new Node(n.getToken() == Token.AND ? Token.OR : Token.AND).srcref(n); MinimizedCondition leftSubtree = computeMinimizedCondition(n.getFirstChild()); MinimizedCondition rightSubtree = computeMinimizedCondition(n.getLastChild()); MeasuredNode positive = pickBest( MeasuredNode.addNode(n, leftSubtree.positive, rightSubtree.positive), MeasuredNode.addNode(complementNode, leftSubtree.negative, rightSubtree.negative).negate()); MeasuredNode negative = pickBest( MeasuredNode.addNode(n, leftSubtree.positive, rightSubtree.positive).negate(), MeasuredNode.addNode(complementNode, leftSubtree.negative, rightSubtree.negative).change()); return new MinimizedCondition(positive, negative); } case HOOK: { Node cond = n.getFirstChild(); Node thenNode = cond.getNext(); Node elseNode = thenNode.getNext(); MinimizedCondition thenSubtree = computeMinimizedCondition(thenNode); MinimizedCondition elseSubtree = computeMinimizedCondition(elseNode); MeasuredNode positive = MeasuredNode.addNode( n, MeasuredNode.forNode(cond), thenSubtree.positive, elseSubtree.positive); MeasuredNode negative = MeasuredNode.addNode( n, MeasuredNode.forNode(cond), thenSubtree.negative, elseSubtree.negative); return new MinimizedCondition(positive, negative); } case COMMA: { Node lhs = n.getFirstChild(); MinimizedCondition rhsSubtree = computeMinimizedCondition(lhs.getNext()); MeasuredNode positive = MeasuredNode.addNode( n, MeasuredNode.forNode(lhs), rhsSubtree.positive); MeasuredNode negative = MeasuredNode.addNode( n, MeasuredNode.forNode(lhs), rhsSubtree.negative); return new MinimizedCondition(positive, negative); } default: { MeasuredNode pos = MeasuredNode.forNode(n); MeasuredNode neg = pos.negate(); return new MinimizedCondition(pos, neg); } } }
java
private static MinimizedCondition computeMinimizedCondition(Node n) { switch (n.getToken()) { case NOT: { MinimizedCondition subtree = computeMinimizedCondition(n.getFirstChild()); MeasuredNode positive = pickBest( MeasuredNode.addNode(n, subtree.positive), subtree.negative); MeasuredNode negative = pickBest( subtree.negative.negate(), subtree.positive); return new MinimizedCondition(positive, negative); } case AND: case OR: { Node complementNode = new Node(n.getToken() == Token.AND ? Token.OR : Token.AND).srcref(n); MinimizedCondition leftSubtree = computeMinimizedCondition(n.getFirstChild()); MinimizedCondition rightSubtree = computeMinimizedCondition(n.getLastChild()); MeasuredNode positive = pickBest( MeasuredNode.addNode(n, leftSubtree.positive, rightSubtree.positive), MeasuredNode.addNode(complementNode, leftSubtree.negative, rightSubtree.negative).negate()); MeasuredNode negative = pickBest( MeasuredNode.addNode(n, leftSubtree.positive, rightSubtree.positive).negate(), MeasuredNode.addNode(complementNode, leftSubtree.negative, rightSubtree.negative).change()); return new MinimizedCondition(positive, negative); } case HOOK: { Node cond = n.getFirstChild(); Node thenNode = cond.getNext(); Node elseNode = thenNode.getNext(); MinimizedCondition thenSubtree = computeMinimizedCondition(thenNode); MinimizedCondition elseSubtree = computeMinimizedCondition(elseNode); MeasuredNode positive = MeasuredNode.addNode( n, MeasuredNode.forNode(cond), thenSubtree.positive, elseSubtree.positive); MeasuredNode negative = MeasuredNode.addNode( n, MeasuredNode.forNode(cond), thenSubtree.negative, elseSubtree.negative); return new MinimizedCondition(positive, negative); } case COMMA: { Node lhs = n.getFirstChild(); MinimizedCondition rhsSubtree = computeMinimizedCondition(lhs.getNext()); MeasuredNode positive = MeasuredNode.addNode( n, MeasuredNode.forNode(lhs), rhsSubtree.positive); MeasuredNode negative = MeasuredNode.addNode( n, MeasuredNode.forNode(lhs), rhsSubtree.negative); return new MinimizedCondition(positive, negative); } default: { MeasuredNode pos = MeasuredNode.forNode(n); MeasuredNode neg = pos.negate(); return new MinimizedCondition(pos, neg); } } }
[ "private", "static", "MinimizedCondition", "computeMinimizedCondition", "(", "Node", "n", ")", "{", "switch", "(", "n", ".", "getToken", "(", ")", ")", "{", "case", "NOT", ":", "{", "MinimizedCondition", "subtree", "=", "computeMinimizedCondition", "(", "n", ".", "getFirstChild", "(", ")", ")", ";", "MeasuredNode", "positive", "=", "pickBest", "(", "MeasuredNode", ".", "addNode", "(", "n", ",", "subtree", ".", "positive", ")", ",", "subtree", ".", "negative", ")", ";", "MeasuredNode", "negative", "=", "pickBest", "(", "subtree", ".", "negative", ".", "negate", "(", ")", ",", "subtree", ".", "positive", ")", ";", "return", "new", "MinimizedCondition", "(", "positive", ",", "negative", ")", ";", "}", "case", "AND", ":", "case", "OR", ":", "{", "Node", "complementNode", "=", "new", "Node", "(", "n", ".", "getToken", "(", ")", "==", "Token", ".", "AND", "?", "Token", ".", "OR", ":", "Token", ".", "AND", ")", ".", "srcref", "(", "n", ")", ";", "MinimizedCondition", "leftSubtree", "=", "computeMinimizedCondition", "(", "n", ".", "getFirstChild", "(", ")", ")", ";", "MinimizedCondition", "rightSubtree", "=", "computeMinimizedCondition", "(", "n", ".", "getLastChild", "(", ")", ")", ";", "MeasuredNode", "positive", "=", "pickBest", "(", "MeasuredNode", ".", "addNode", "(", "n", ",", "leftSubtree", ".", "positive", ",", "rightSubtree", ".", "positive", ")", ",", "MeasuredNode", ".", "addNode", "(", "complementNode", ",", "leftSubtree", ".", "negative", ",", "rightSubtree", ".", "negative", ")", ".", "negate", "(", ")", ")", ";", "MeasuredNode", "negative", "=", "pickBest", "(", "MeasuredNode", ".", "addNode", "(", "n", ",", "leftSubtree", ".", "positive", ",", "rightSubtree", ".", "positive", ")", ".", "negate", "(", ")", ",", "MeasuredNode", ".", "addNode", "(", "complementNode", ",", "leftSubtree", ".", "negative", ",", "rightSubtree", ".", "negative", ")", ".", "change", "(", ")", ")", ";", "return", "new", "MinimizedCondition", "(", "positive", ",", "negative", ")", ";", "}", "case", "HOOK", ":", "{", "Node", "cond", "=", "n", ".", "getFirstChild", "(", ")", ";", "Node", "thenNode", "=", "cond", ".", "getNext", "(", ")", ";", "Node", "elseNode", "=", "thenNode", ".", "getNext", "(", ")", ";", "MinimizedCondition", "thenSubtree", "=", "computeMinimizedCondition", "(", "thenNode", ")", ";", "MinimizedCondition", "elseSubtree", "=", "computeMinimizedCondition", "(", "elseNode", ")", ";", "MeasuredNode", "positive", "=", "MeasuredNode", ".", "addNode", "(", "n", ",", "MeasuredNode", ".", "forNode", "(", "cond", ")", ",", "thenSubtree", ".", "positive", ",", "elseSubtree", ".", "positive", ")", ";", "MeasuredNode", "negative", "=", "MeasuredNode", ".", "addNode", "(", "n", ",", "MeasuredNode", ".", "forNode", "(", "cond", ")", ",", "thenSubtree", ".", "negative", ",", "elseSubtree", ".", "negative", ")", ";", "return", "new", "MinimizedCondition", "(", "positive", ",", "negative", ")", ";", "}", "case", "COMMA", ":", "{", "Node", "lhs", "=", "n", ".", "getFirstChild", "(", ")", ";", "MinimizedCondition", "rhsSubtree", "=", "computeMinimizedCondition", "(", "lhs", ".", "getNext", "(", ")", ")", ";", "MeasuredNode", "positive", "=", "MeasuredNode", ".", "addNode", "(", "n", ",", "MeasuredNode", ".", "forNode", "(", "lhs", ")", ",", "rhsSubtree", ".", "positive", ")", ";", "MeasuredNode", "negative", "=", "MeasuredNode", ".", "addNode", "(", "n", ",", "MeasuredNode", ".", "forNode", "(", "lhs", ")", ",", "rhsSubtree", ".", "negative", ")", ";", "return", "new", "MinimizedCondition", "(", "positive", ",", "negative", ")", ";", "}", "default", ":", "{", "MeasuredNode", "pos", "=", "MeasuredNode", ".", "forNode", "(", "n", ")", ";", "MeasuredNode", "neg", "=", "pos", ".", "negate", "(", ")", ";", "return", "new", "MinimizedCondition", "(", "pos", ",", "neg", ")", ";", "}", "}", "}" ]
Minimize the condition at the given node. @param n the conditional expression tree to minimize. @return a MinimizedCondition object representing that tree.
[ "Minimize", "the", "condition", "at", "the", "given", "node", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MinimizedCondition.java#L142-L212
24,488
google/closure-compiler
src/com/google/javascript/jscomp/Es6ToEs3Util.java
Es6ToEs3Util.withType
static Node withType(Node n, JSType t) { if (t != null) { n.setJSType(t); } return n; }
java
static Node withType(Node n, JSType t) { if (t != null) { n.setJSType(t); } return n; }
[ "static", "Node", "withType", "(", "Node", "n", ",", "JSType", "t", ")", "{", "if", "(", "t", "!=", "null", ")", "{", "n", ".", "setJSType", "(", "t", ")", ";", "}", "return", "n", ";", "}" ]
Adds the type t to Node n, and returns n. Does nothing if t is null.
[ "Adds", "the", "type", "t", "to", "Node", "n", "and", "returns", "n", ".", "Does", "nothing", "if", "t", "is", "null", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6ToEs3Util.java#L97-L102
24,489
google/closure-compiler
src/com/google/javascript/jscomp/Es6ToEs3Util.java
Es6ToEs3Util.createType
static JSType createType(boolean shouldCreate, JSTypeRegistry registry, JSTypeNative typeName) { if (!shouldCreate) { return null; } return registry.getNativeType(typeName); }
java
static JSType createType(boolean shouldCreate, JSTypeRegistry registry, JSTypeNative typeName) { if (!shouldCreate) { return null; } return registry.getNativeType(typeName); }
[ "static", "JSType", "createType", "(", "boolean", "shouldCreate", ",", "JSTypeRegistry", "registry", ",", "JSTypeNative", "typeName", ")", "{", "if", "(", "!", "shouldCreate", ")", "{", "return", "null", ";", "}", "return", "registry", ".", "getNativeType", "(", "typeName", ")", ";", "}" ]
Returns the JSType as specified by the typeName. Returns null if shouldCreate is false.
[ "Returns", "the", "JSType", "as", "specified", "by", "the", "typeName", ".", "Returns", "null", "if", "shouldCreate", "is", "false", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6ToEs3Util.java#L108-L113
24,490
google/closure-compiler
src/com/google/javascript/jscomp/Es6ToEs3Util.java
Es6ToEs3Util.createGenericType
static JSType createGenericType( boolean shouldCreate, JSTypeRegistry registry, JSTypeNative typeName, JSType typeArg) { if (!shouldCreate) { return null; } ObjectType genericType = (ObjectType) (registry.getNativeType(typeName)); ObjectType uninstantiated = genericType.getRawType(); return registry.instantiateGenericType(uninstantiated, ImmutableList.of(typeArg)); }
java
static JSType createGenericType( boolean shouldCreate, JSTypeRegistry registry, JSTypeNative typeName, JSType typeArg) { if (!shouldCreate) { return null; } ObjectType genericType = (ObjectType) (registry.getNativeType(typeName)); ObjectType uninstantiated = genericType.getRawType(); return registry.instantiateGenericType(uninstantiated, ImmutableList.of(typeArg)); }
[ "static", "JSType", "createGenericType", "(", "boolean", "shouldCreate", ",", "JSTypeRegistry", "registry", ",", "JSTypeNative", "typeName", ",", "JSType", "typeArg", ")", "{", "if", "(", "!", "shouldCreate", ")", "{", "return", "null", ";", "}", "ObjectType", "genericType", "=", "(", "ObjectType", ")", "(", "registry", ".", "getNativeType", "(", "typeName", ")", ")", ";", "ObjectType", "uninstantiated", "=", "genericType", ".", "getRawType", "(", ")", ";", "return", "registry", ".", "instantiateGenericType", "(", "uninstantiated", ",", "ImmutableList", ".", "of", "(", "typeArg", ")", ")", ";", "}" ]
Returns the JSType as specified by the typeName and instantiated by the typeArg. Returns null if shouldCreate is false.
[ "Returns", "the", "JSType", "as", "specified", "by", "the", "typeName", "and", "instantiated", "by", "the", "typeArg", ".", "Returns", "null", "if", "shouldCreate", "is", "false", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6ToEs3Util.java#L119-L127
24,491
google/closure-compiler
src/com/google/javascript/jscomp/MaybeReachingVariableUse.java
MaybeReachingVariableUse.addToUseIfLocal
private void addToUseIfLocal(String name, Node node, ReachingUses use) { Var var = allVarsInFn.get(name); if (var == null) { return; } if (!escaped.contains(var)) { use.mayUseMap.put(var, node); } }
java
private void addToUseIfLocal(String name, Node node, ReachingUses use) { Var var = allVarsInFn.get(name); if (var == null) { return; } if (!escaped.contains(var)) { use.mayUseMap.put(var, node); } }
[ "private", "void", "addToUseIfLocal", "(", "String", "name", ",", "Node", "node", ",", "ReachingUses", "use", ")", "{", "Var", "var", "=", "allVarsInFn", ".", "get", "(", "name", ")", ";", "if", "(", "var", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "escaped", ".", "contains", "(", "var", ")", ")", "{", "use", ".", "mayUseMap", ".", "put", "(", "var", ",", "node", ")", ";", "}", "}" ]
Sets the variable for the given name to the node value in the upward exposed lattice. Do nothing if the variable name is one of the escaped variable.
[ "Sets", "the", "variable", "for", "the", "given", "name", "to", "the", "node", "value", "in", "the", "upward", "exposed", "lattice", ".", "Do", "nothing", "if", "the", "variable", "name", "is", "one", "of", "the", "escaped", "variable", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MaybeReachingVariableUse.java#L308-L316
24,492
google/closure-compiler
src/com/google/javascript/jscomp/MaybeReachingVariableUse.java
MaybeReachingVariableUse.removeFromUseIfLocal
private void removeFromUseIfLocal(String name, ReachingUses use) { Var var = allVarsInFn.get(name); if (var == null) { return; } if (!escaped.contains(var)) { use.mayUseMap.removeAll(var); } }
java
private void removeFromUseIfLocal(String name, ReachingUses use) { Var var = allVarsInFn.get(name); if (var == null) { return; } if (!escaped.contains(var)) { use.mayUseMap.removeAll(var); } }
[ "private", "void", "removeFromUseIfLocal", "(", "String", "name", ",", "ReachingUses", "use", ")", "{", "Var", "var", "=", "allVarsInFn", ".", "get", "(", "name", ")", ";", "if", "(", "var", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "escaped", ".", "contains", "(", "var", ")", ")", "{", "use", ".", "mayUseMap", ".", "removeAll", "(", "var", ")", ";", "}", "}" ]
Removes the variable for the given name from the node value in the upward exposed lattice. Do nothing if the variable name is one of the escaped variable.
[ "Removes", "the", "variable", "for", "the", "given", "name", "from", "the", "node", "value", "in", "the", "upward", "exposed", "lattice", ".", "Do", "nothing", "if", "the", "variable", "name", "is", "one", "of", "the", "escaped", "variable", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MaybeReachingVariableUse.java#L323-L331
24,493
google/closure-compiler
src/com/google/javascript/jscomp/Promises.java
Promises.getTemplateTypeOfThenable
static final JSType getTemplateTypeOfThenable(JSTypeRegistry registry, JSType maybeThenable) { return maybeThenable // Without ".restrictByNotNullOrUndefined" we'd get the unknown type for "?IThenable<null>" .restrictByNotNullOrUndefined() .getInstantiatedTypeArgument(registry.getNativeType(JSTypeNative.I_THENABLE_TYPE)); }
java
static final JSType getTemplateTypeOfThenable(JSTypeRegistry registry, JSType maybeThenable) { return maybeThenable // Without ".restrictByNotNullOrUndefined" we'd get the unknown type for "?IThenable<null>" .restrictByNotNullOrUndefined() .getInstantiatedTypeArgument(registry.getNativeType(JSTypeNative.I_THENABLE_TYPE)); }
[ "static", "final", "JSType", "getTemplateTypeOfThenable", "(", "JSTypeRegistry", "registry", ",", "JSType", "maybeThenable", ")", "{", "return", "maybeThenable", "// Without \".restrictByNotNullOrUndefined\" we'd get the unknown type for \"?IThenable<null>\"", ".", "restrictByNotNullOrUndefined", "(", ")", ".", "getInstantiatedTypeArgument", "(", "registry", ".", "getNativeType", "(", "JSTypeNative", ".", "I_THENABLE_TYPE", ")", ")", ";", "}" ]
If this object is known to be an IThenable, returns the type it resolves to. <p>Returns unknown otherwise. <p>(This is different from {@code getResolvedType}, which will attempt to model the then type of an expression after calling Promise.resolve() on it.
[ "If", "this", "object", "is", "known", "to", "be", "an", "IThenable", "returns", "the", "type", "it", "resolves", "to", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Promises.java#L46-L51
24,494
google/closure-compiler
src/com/google/javascript/jscomp/Promises.java
Promises.wrapInIThenable
static final JSType wrapInIThenable(JSTypeRegistry registry, JSType maybeThenable) { // Unwrap for simplicity first in the event it is a thenable. JSType unwrapped = getResolvedType(registry, maybeThenable); return registry.createTemplatizedType( registry.getNativeObjectType(JSTypeNative.I_THENABLE_TYPE), unwrapped); }
java
static final JSType wrapInIThenable(JSTypeRegistry registry, JSType maybeThenable) { // Unwrap for simplicity first in the event it is a thenable. JSType unwrapped = getResolvedType(registry, maybeThenable); return registry.createTemplatizedType( registry.getNativeObjectType(JSTypeNative.I_THENABLE_TYPE), unwrapped); }
[ "static", "final", "JSType", "wrapInIThenable", "(", "JSTypeRegistry", "registry", ",", "JSType", "maybeThenable", ")", "{", "// Unwrap for simplicity first in the event it is a thenable.", "JSType", "unwrapped", "=", "getResolvedType", "(", "registry", ",", "maybeThenable", ")", ";", "return", "registry", ".", "createTemplatizedType", "(", "registry", ".", "getNativeObjectType", "(", "JSTypeNative", ".", "I_THENABLE_TYPE", ")", ",", "unwrapped", ")", ";", "}" ]
Wraps the given type in an IThenable. <p>If the given type is already IThenable it is first unwrapped. For example: <p>{@code number} becomes {@code IThenable<number>} <p>{@code IThenable<number>} becomes {@code IThenable<number>} <p>{@code Promise<number>} becomes {@code IThenable<number>} <p>{@code IThenable<number>|string} becomes {@code IThenable<number|string>} <p>{@code IThenable<number>|IThenable<string>} becomes {@code IThenable<number|string>}
[ "Wraps", "the", "given", "type", "in", "an", "IThenable", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Promises.java#L119-L124
24,495
google/closure-compiler
src/com/google/javascript/jscomp/gwt/linker/MinimalLinker.java
MinimalLinker.formatOutput
private static String formatOutput(String js, boolean export) { StringBuilder output = new StringBuilder(); // Shadow window so that non-browser environments can pass their own global object here. output.append("(function(window){"); // If $wnd is set to this, then JSInterop's normal export will run, and pollute the global // namespace. If export is false, fake out $wnd with an empty object. // (We also add Error to work around StackTraceCreator using it in a static block). output.append("var $wnd=").append(export ? "this" : "{'Error':{}}").append(";"); // Shadow $doc, $moduleName and $moduleBase. output.append("var $doc={},$moduleName,$moduleBase;"); // Append output JS. output.append(js); // 1. Export $gwtExport, needed for transpile.js // 2. Reset $wnd (nb. this occurs after jscompiler's JS has run) // 3. Call gwtOnLoad, if defined: this invokes onModuleLoad for all loaded modules. output.append("this['$gwtExport']=$wnd;$wnd=this;typeof gwtOnLoad==='function'&&gwtOnLoad()"); // Overspecify the global object, to capture Node and browser environments. String globalObject = "this&&this.self||" + "(typeof window!=='undefined'?window:(typeof global!=='undefined'?global:this))"; // Call the outer function with the global object as this and its first argument, so that we // fake window in Node environments, allowing our code to do things like "window.console(...)". output.append("}).call(").append(globalObject).append(",").append(globalObject).append(");"); return output.toString(); }
java
private static String formatOutput(String js, boolean export) { StringBuilder output = new StringBuilder(); // Shadow window so that non-browser environments can pass their own global object here. output.append("(function(window){"); // If $wnd is set to this, then JSInterop's normal export will run, and pollute the global // namespace. If export is false, fake out $wnd with an empty object. // (We also add Error to work around StackTraceCreator using it in a static block). output.append("var $wnd=").append(export ? "this" : "{'Error':{}}").append(";"); // Shadow $doc, $moduleName and $moduleBase. output.append("var $doc={},$moduleName,$moduleBase;"); // Append output JS. output.append(js); // 1. Export $gwtExport, needed for transpile.js // 2. Reset $wnd (nb. this occurs after jscompiler's JS has run) // 3. Call gwtOnLoad, if defined: this invokes onModuleLoad for all loaded modules. output.append("this['$gwtExport']=$wnd;$wnd=this;typeof gwtOnLoad==='function'&&gwtOnLoad()"); // Overspecify the global object, to capture Node and browser environments. String globalObject = "this&&this.self||" + "(typeof window!=='undefined'?window:(typeof global!=='undefined'?global:this))"; // Call the outer function with the global object as this and its first argument, so that we // fake window in Node environments, allowing our code to do things like "window.console(...)". output.append("}).call(").append(globalObject).append(",").append(globalObject).append(");"); return output.toString(); }
[ "private", "static", "String", "formatOutput", "(", "String", "js", ",", "boolean", "export", ")", "{", "StringBuilder", "output", "=", "new", "StringBuilder", "(", ")", ";", "// Shadow window so that non-browser environments can pass their own global object here.", "output", ".", "append", "(", "\"(function(window){\"", ")", ";", "// If $wnd is set to this, then JSInterop's normal export will run, and pollute the global", "// namespace. If export is false, fake out $wnd with an empty object.", "// (We also add Error to work around StackTraceCreator using it in a static block).", "output", ".", "append", "(", "\"var $wnd=\"", ")", ".", "append", "(", "export", "?", "\"this\"", ":", "\"{'Error':{}}\"", ")", ".", "append", "(", "\";\"", ")", ";", "// Shadow $doc, $moduleName and $moduleBase.", "output", ".", "append", "(", "\"var $doc={},$moduleName,$moduleBase;\"", ")", ";", "// Append output JS.", "output", ".", "append", "(", "js", ")", ";", "// 1. Export $gwtExport, needed for transpile.js", "// 2. Reset $wnd (nb. this occurs after jscompiler's JS has run)", "// 3. Call gwtOnLoad, if defined: this invokes onModuleLoad for all loaded modules.", "output", ".", "append", "(", "\"this['$gwtExport']=$wnd;$wnd=this;typeof gwtOnLoad==='function'&&gwtOnLoad()\"", ")", ";", "// Overspecify the global object, to capture Node and browser environments.", "String", "globalObject", "=", "\"this&&this.self||\"", "+", "\"(typeof window!=='undefined'?window:(typeof global!=='undefined'?global:this))\"", ";", "// Call the outer function with the global object as this and its first argument, so that we", "// fake window in Node environments, allowing our code to do things like \"window.console(...)\".", "output", ".", "append", "(", "\"}).call(\"", ")", ".", "append", "(", "globalObject", ")", ".", "append", "(", "\",\"", ")", ".", "append", "(", "globalObject", ")", ".", "append", "(", "\");\"", ")", ";", "return", "output", ".", "toString", "(", ")", ";", "}" ]
Formats the application's JS code for output. @param js Code to format. @param export Whether to export via JSInterop. @return Formatted, linked code.
[ "Formats", "the", "application", "s", "JS", "code", "for", "output", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/gwt/linker/MinimalLinker.java#L67-L98
24,496
google/closure-compiler
src/com/google/javascript/jscomp/regex/CharRanges.java
CharRanges.withRanges
public static CharRanges withRanges(int... ranges) { if ((ranges.length & 1) != 0) { throw new IllegalArgumentException(); } for (int i = 1; i < ranges.length; ++i) { if (ranges[i] <= ranges[i - 1]) { throw new IllegalArgumentException(ranges[i] + " > " + ranges[i - 1]); } } return new CharRanges(ranges); }
java
public static CharRanges withRanges(int... ranges) { if ((ranges.length & 1) != 0) { throw new IllegalArgumentException(); } for (int i = 1; i < ranges.length; ++i) { if (ranges[i] <= ranges[i - 1]) { throw new IllegalArgumentException(ranges[i] + " > " + ranges[i - 1]); } } return new CharRanges(ranges); }
[ "public", "static", "CharRanges", "withRanges", "(", "int", "...", "ranges", ")", "{", "if", "(", "(", "ranges", ".", "length", "&", "1", ")", "!=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "for", "(", "int", "i", "=", "1", ";", "i", "<", "ranges", ".", "length", ";", "++", "i", ")", "{", "if", "(", "ranges", "[", "i", "]", "<=", "ranges", "[", "i", "-", "1", "]", ")", "{", "throw", "new", "IllegalArgumentException", "(", "ranges", "[", "i", "]", "+", "\" > \"", "+", "ranges", "[", "i", "-", "1", "]", ")", ";", "}", "}", "return", "new", "CharRanges", "(", "ranges", ")", ";", "}" ]
Returns an instance containing the given ranges. @param ranges An even-length ordered sequence of non-overlapping, non-contiguous, [inclusive start, exclusive end) ranges.
[ "Returns", "an", "instance", "containing", "the", "given", "ranges", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/regex/CharRanges.java#L61-L69
24,497
google/closure-compiler
src/com/google/javascript/jscomp/XtbMessageBundle.java
XtbMessageBundle.isStartOfIcuMessage
static boolean isStartOfIcuMessage(String part) { // ICU messages start with a '{' followed by an identifier, followed by a ',' and then 'plural' // or 'select' follows by another comma. // the 'startsWith' check is redundant but should allow us to skip using the matcher if (!part.startsWith("{")) { return false; } int commaIndex = part.indexOf(',', 1); // if commaIndex == 1 that means the identifier is empty, which isn't allowed. if (commaIndex <= 1) { return false; } int nextBracketIndex = part.indexOf('{', 1); return (nextBracketIndex == -1 || nextBracketIndex > commaIndex) && (part.startsWith("plural,", commaIndex + 1) || part.startsWith("select,", commaIndex + 1)); }
java
static boolean isStartOfIcuMessage(String part) { // ICU messages start with a '{' followed by an identifier, followed by a ',' and then 'plural' // or 'select' follows by another comma. // the 'startsWith' check is redundant but should allow us to skip using the matcher if (!part.startsWith("{")) { return false; } int commaIndex = part.indexOf(',', 1); // if commaIndex == 1 that means the identifier is empty, which isn't allowed. if (commaIndex <= 1) { return false; } int nextBracketIndex = part.indexOf('{', 1); return (nextBracketIndex == -1 || nextBracketIndex > commaIndex) && (part.startsWith("plural,", commaIndex + 1) || part.startsWith("select,", commaIndex + 1)); }
[ "static", "boolean", "isStartOfIcuMessage", "(", "String", "part", ")", "{", "// ICU messages start with a '{' followed by an identifier, followed by a ',' and then 'plural'", "// or 'select' follows by another comma.", "// the 'startsWith' check is redundant but should allow us to skip using the matcher", "if", "(", "!", "part", ".", "startsWith", "(", "\"{\"", ")", ")", "{", "return", "false", ";", "}", "int", "commaIndex", "=", "part", ".", "indexOf", "(", "'", "'", ",", "1", ")", ";", "// if commaIndex == 1 that means the identifier is empty, which isn't allowed.", "if", "(", "commaIndex", "<=", "1", ")", "{", "return", "false", ";", "}", "int", "nextBracketIndex", "=", "part", ".", "indexOf", "(", "'", "'", ",", "1", ")", ";", "return", "(", "nextBracketIndex", "==", "-", "1", "||", "nextBracketIndex", ">", "commaIndex", ")", "&&", "(", "part", ".", "startsWith", "(", "\"plural,\"", ",", "commaIndex", "+", "1", ")", "||", "part", ".", "startsWith", "(", "\"select,\"", ",", "commaIndex", "+", "1", ")", ")", ";", "}" ]
Detects an ICU-formatted plural or select message. Any placeholders occurring inside these messages must be rewritten in ICU format.
[ "Detects", "an", "ICU", "-", "formatted", "plural", "or", "select", "message", ".", "Any", "placeholders", "occurring", "inside", "these", "messages", "must", "be", "rewritten", "in", "ICU", "format", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/XtbMessageBundle.java#L56-L72
24,498
google/closure-compiler
src/com/google/javascript/jscomp/XtbMessageBundle.java
XtbMessageBundle.createSAXParser
private static SAXParser createSAXParser() throws ParserConfigurationException, SAXException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setXIncludeAware(false); factory.setFeature( "http://xml.org/sax/features/external-general-entities", false); factory.setFeature( "http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); SAXParser parser = factory.newSAXParser(); XMLReader xmlReader = parser.getXMLReader(); xmlReader.setEntityResolver(NOOP_RESOLVER); return parser; }
java
private static SAXParser createSAXParser() throws ParserConfigurationException, SAXException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setXIncludeAware(false); factory.setFeature( "http://xml.org/sax/features/external-general-entities", false); factory.setFeature( "http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); SAXParser parser = factory.newSAXParser(); XMLReader xmlReader = parser.getXMLReader(); xmlReader.setEntityResolver(NOOP_RESOLVER); return parser; }
[ "private", "static", "SAXParser", "createSAXParser", "(", ")", "throws", "ParserConfigurationException", ",", "SAXException", "{", "SAXParserFactory", "factory", "=", "SAXParserFactory", ".", "newInstance", "(", ")", ";", "factory", ".", "setValidating", "(", "false", ")", ";", "factory", ".", "setXIncludeAware", "(", "false", ")", ";", "factory", ".", "setFeature", "(", "\"http://xml.org/sax/features/external-general-entities\"", ",", "false", ")", ";", "factory", ".", "setFeature", "(", "\"http://xml.org/sax/features/external-parameter-entities\"", ",", "false", ")", ";", "factory", ".", "setFeature", "(", "\"http://apache.org/xml/features/nonvalidating/load-external-dtd\"", ",", "false", ")", ";", "factory", ".", "setFeature", "(", "XMLConstants", ".", "FEATURE_SECURE_PROCESSING", ",", "true", ")", ";", "SAXParser", "parser", "=", "factory", ".", "newSAXParser", "(", ")", ";", "XMLReader", "xmlReader", "=", "parser", ".", "getXMLReader", "(", ")", ";", "xmlReader", ".", "setEntityResolver", "(", "NOOP_RESOLVER", ")", ";", "return", "parser", ";", "}" ]
Inlined from guava-internal.
[ "Inlined", "from", "guava", "-", "internal", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/XtbMessageBundle.java#L113-L131
24,499
google/closure-compiler
src/com/google/javascript/jscomp/deps/ModuleResolver.java
ModuleResolver.locate
@Nullable protected String locate(String scriptAddress, String name) { String canonicalizedPath = canonicalizePath(scriptAddress, name); String normalizedPath = canonicalizedPath; if (ModuleLoader.isAmbiguousIdentifier(canonicalizedPath)) { normalizedPath = ModuleLoader.MODULE_SLASH + canonicalizedPath; } // First check to see if the module is known with it's provided path if (modulePaths.contains(normalizedPath)) { return canonicalizedPath; } // Check for the module beneath each of the module roots for (String rootPath : moduleRootPaths) { String modulePath = rootPath + normalizedPath; // Since there might be code that relying on whether the path has a leading slash or not, // honor the state it was provided in. In an ideal world this would always be normalized // to contain a leading slash. if (modulePaths.contains(modulePath)) { return canonicalizedPath; } } return null; }
java
@Nullable protected String locate(String scriptAddress, String name) { String canonicalizedPath = canonicalizePath(scriptAddress, name); String normalizedPath = canonicalizedPath; if (ModuleLoader.isAmbiguousIdentifier(canonicalizedPath)) { normalizedPath = ModuleLoader.MODULE_SLASH + canonicalizedPath; } // First check to see if the module is known with it's provided path if (modulePaths.contains(normalizedPath)) { return canonicalizedPath; } // Check for the module beneath each of the module roots for (String rootPath : moduleRootPaths) { String modulePath = rootPath + normalizedPath; // Since there might be code that relying on whether the path has a leading slash or not, // honor the state it was provided in. In an ideal world this would always be normalized // to contain a leading slash. if (modulePaths.contains(modulePath)) { return canonicalizedPath; } } return null; }
[ "@", "Nullable", "protected", "String", "locate", "(", "String", "scriptAddress", ",", "String", "name", ")", "{", "String", "canonicalizedPath", "=", "canonicalizePath", "(", "scriptAddress", ",", "name", ")", ";", "String", "normalizedPath", "=", "canonicalizedPath", ";", "if", "(", "ModuleLoader", ".", "isAmbiguousIdentifier", "(", "canonicalizedPath", ")", ")", "{", "normalizedPath", "=", "ModuleLoader", ".", "MODULE_SLASH", "+", "canonicalizedPath", ";", "}", "// First check to see if the module is known with it's provided path", "if", "(", "modulePaths", ".", "contains", "(", "normalizedPath", ")", ")", "{", "return", "canonicalizedPath", ";", "}", "// Check for the module beneath each of the module roots", "for", "(", "String", "rootPath", ":", "moduleRootPaths", ")", "{", "String", "modulePath", "=", "rootPath", "+", "normalizedPath", ";", "// Since there might be code that relying on whether the path has a leading slash or not,", "// honor the state it was provided in. In an ideal world this would always be normalized", "// to contain a leading slash.", "if", "(", "modulePaths", ".", "contains", "(", "modulePath", ")", ")", "{", "return", "canonicalizedPath", ";", "}", "}", "return", "null", ";", "}" ]
Locates the module with the given name, but returns null if there is no JS file in the expected location.
[ "Locates", "the", "module", "with", "the", "given", "name", "but", "returns", "null", "if", "there", "is", "no", "JS", "file", "in", "the", "expected", "location", "." ]
d81e36740f6a9e8ac31a825ee8758182e1dc5aae
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/ModuleResolver.java#L76-L103