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,100 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.makesDicts | public final boolean makesDicts() {
if (!isConstructor()) {
return false;
}
if (propAccess == PropAccess.DICT) {
return true;
}
FunctionType superc = getSuperClassConstructor();
if (superc != null && superc.makesDicts()) {
setDict();
return true;
}
return false;
} | java | public final boolean makesDicts() {
if (!isConstructor()) {
return false;
}
if (propAccess == PropAccess.DICT) {
return true;
}
FunctionType superc = getSuperClassConstructor();
if (superc != null && superc.makesDicts()) {
setDict();
return true;
}
return false;
} | [
"public",
"final",
"boolean",
"makesDicts",
"(",
")",
"{",
"if",
"(",
"!",
"isConstructor",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"propAccess",
"==",
"PropAccess",
".",
"DICT",
")",
"{",
"return",
"true",
";",
"}",
"FunctionType",
"superc",
"=",
"getSuperClassConstructor",
"(",
")",
";",
"if",
"(",
"superc",
"!=",
"null",
"&&",
"superc",
".",
"makesDicts",
"(",
")",
")",
"{",
"setDict",
"(",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | When a class B inherits from A and A is annotated as a dict, then B automatically gets the
annotation, even if B's constructor is not explicitly annotated. | [
"When",
"a",
"class",
"B",
"inherits",
"from",
"A",
"and",
"A",
"is",
"annotated",
"as",
"a",
"dict",
"then",
"B",
"automatically",
"gets",
"the",
"annotation",
"even",
"if",
"B",
"s",
"constructor",
"is",
"not",
"explicitly",
"annotated",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L258-L271 |
24,101 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.getMinArity | public final int getMinArity() {
// NOTE(nicksantos): There are some native functions that have optional
// parameters before required parameters. This algorithm finds the position
// of the last required parameter.
int i = 0;
int min = 0;
for (Node n : getParameters()) {
i++;
if (!n.isOptionalArg() && !n.isVarArgs()) {
min = i;
}
}
return min;
} | java | public final int getMinArity() {
// NOTE(nicksantos): There are some native functions that have optional
// parameters before required parameters. This algorithm finds the position
// of the last required parameter.
int i = 0;
int min = 0;
for (Node n : getParameters()) {
i++;
if (!n.isOptionalArg() && !n.isVarArgs()) {
min = i;
}
}
return min;
} | [
"public",
"final",
"int",
"getMinArity",
"(",
")",
"{",
"// NOTE(nicksantos): There are some native functions that have optional",
"// parameters before required parameters. This algorithm finds the position",
"// of the last required parameter.",
"int",
"i",
"=",
"0",
";",
"int",
"min",
"=",
"0",
";",
"for",
"(",
"Node",
"n",
":",
"getParameters",
"(",
")",
")",
"{",
"i",
"++",
";",
"if",
"(",
"!",
"n",
".",
"isOptionalArg",
"(",
")",
"&&",
"!",
"n",
".",
"isVarArgs",
"(",
")",
")",
"{",
"min",
"=",
"i",
";",
"}",
"}",
"return",
"min",
";",
"}"
] | Gets the minimum number of arguments that this function requires. | [
"Gets",
"the",
"minimum",
"number",
"of",
"arguments",
"that",
"this",
"function",
"requires",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L325-L338 |
24,102 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.getMaxArity | public final int getMaxArity() {
Node params = getParametersNode();
if (params != null) {
Node lastParam = params.getLastChild();
if (lastParam == null || !lastParam.isVarArgs()) {
return params.getChildCount();
}
}
return Integer.MAX_VALUE;
} | java | public final int getMaxArity() {
Node params = getParametersNode();
if (params != null) {
Node lastParam = params.getLastChild();
if (lastParam == null || !lastParam.isVarArgs()) {
return params.getChildCount();
}
}
return Integer.MAX_VALUE;
} | [
"public",
"final",
"int",
"getMaxArity",
"(",
")",
"{",
"Node",
"params",
"=",
"getParametersNode",
"(",
")",
";",
"if",
"(",
"params",
"!=",
"null",
")",
"{",
"Node",
"lastParam",
"=",
"params",
".",
"getLastChild",
"(",
")",
";",
"if",
"(",
"lastParam",
"==",
"null",
"||",
"!",
"lastParam",
".",
"isVarArgs",
"(",
")",
")",
"{",
"return",
"params",
".",
"getChildCount",
"(",
")",
";",
"}",
"}",
"return",
"Integer",
".",
"MAX_VALUE",
";",
"}"
] | Gets the maximum number of arguments that this function requires, or Integer.MAX_VALUE if this
is a variable argument function. | [
"Gets",
"the",
"maximum",
"number",
"of",
"arguments",
"that",
"this",
"function",
"requires",
"or",
"Integer",
".",
"MAX_VALUE",
"if",
"this",
"is",
"a",
"variable",
"argument",
"function",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L344-L354 |
24,103 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.getOwnPropertyNames | @Override
public final Set<String> getOwnPropertyNames() {
if (prototypeSlot == null) {
return super.getOwnPropertyNames();
} else {
ImmutableSet.Builder<String> names = ImmutableSet.builder();
names.add("prototype");
names.addAll(super.getOwnPropertyNames());
return names.build();
}
} | java | @Override
public final Set<String> getOwnPropertyNames() {
if (prototypeSlot == null) {
return super.getOwnPropertyNames();
} else {
ImmutableSet.Builder<String> names = ImmutableSet.builder();
names.add("prototype");
names.addAll(super.getOwnPropertyNames());
return names.build();
}
} | [
"@",
"Override",
"public",
"final",
"Set",
"<",
"String",
">",
"getOwnPropertyNames",
"(",
")",
"{",
"if",
"(",
"prototypeSlot",
"==",
"null",
")",
"{",
"return",
"super",
".",
"getOwnPropertyNames",
"(",
")",
";",
"}",
"else",
"{",
"ImmutableSet",
".",
"Builder",
"<",
"String",
">",
"names",
"=",
"ImmutableSet",
".",
"builder",
"(",
")",
";",
"names",
".",
"add",
"(",
"\"prototype\"",
")",
";",
"names",
".",
"addAll",
"(",
"super",
".",
"getOwnPropertyNames",
"(",
")",
")",
";",
"return",
"names",
".",
"build",
"(",
")",
";",
"}",
"}"
] | Includes the prototype iff someone has created it. We do not want to expose the prototype for
ordinary functions. | [
"Includes",
"the",
"prototype",
"iff",
"someone",
"has",
"created",
"it",
".",
"We",
"do",
"not",
"want",
"to",
"expose",
"the",
"prototype",
"for",
"ordinary",
"functions",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L384-L394 |
24,104 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.setPrototype | final boolean setPrototype(ObjectType prototype, Node propertyNode) {
if (prototype == null) {
return false;
}
// getInstanceType fails if the function is not a constructor
if (isConstructor() && prototype == getInstanceType()) {
return false;
}
return setPrototypeNoCheck(prototype, propertyNode);
} | java | final boolean setPrototype(ObjectType prototype, Node propertyNode) {
if (prototype == null) {
return false;
}
// getInstanceType fails if the function is not a constructor
if (isConstructor() && prototype == getInstanceType()) {
return false;
}
return setPrototypeNoCheck(prototype, propertyNode);
} | [
"final",
"boolean",
"setPrototype",
"(",
"ObjectType",
"prototype",
",",
"Node",
"propertyNode",
")",
"{",
"if",
"(",
"prototype",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"// getInstanceType fails if the function is not a constructor",
"if",
"(",
"isConstructor",
"(",
")",
"&&",
"prototype",
"==",
"getInstanceType",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"setPrototypeNoCheck",
"(",
"prototype",
",",
"propertyNode",
")",
";",
"}"
] | Sets the prototype.
@param prototype the prototype. If this value is {@code null} it will silently be discarded. | [
"Sets",
"the",
"prototype",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L485-L494 |
24,105 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.setPrototypeNoCheck | private boolean setPrototypeNoCheck(ObjectType prototype, Node propertyNode) {
ObjectType oldPrototype = prototypeSlot == null ? null : (ObjectType) prototypeSlot.getType();
boolean replacedPrototype = oldPrototype != null;
this.prototypeSlot =
new Property("prototype", prototype, true, propertyNode == null ? source : propertyNode);
prototype.setOwnerFunction(this);
if (oldPrototype != null) {
// Disassociating the old prototype makes this easier to debug--
// we don't have to worry about two prototypes running around.
oldPrototype.setOwnerFunction(null);
}
if (isConstructor() || isInterface()) {
FunctionType superClass = getSuperClassConstructor();
if (superClass != null) {
superClass.addSubType(this);
wasAddedToExtendedConstructorSubtypes = true;
}
if (isInterface()) {
for (ObjectType interfaceType : getExtendedInterfaces()) {
if (interfaceType.getConstructor() != null) {
interfaceType.getConstructor().addSubType(this);
}
}
}
}
if (replacedPrototype) {
clearCachedValues();
}
return true;
} | java | private boolean setPrototypeNoCheck(ObjectType prototype, Node propertyNode) {
ObjectType oldPrototype = prototypeSlot == null ? null : (ObjectType) prototypeSlot.getType();
boolean replacedPrototype = oldPrototype != null;
this.prototypeSlot =
new Property("prototype", prototype, true, propertyNode == null ? source : propertyNode);
prototype.setOwnerFunction(this);
if (oldPrototype != null) {
// Disassociating the old prototype makes this easier to debug--
// we don't have to worry about two prototypes running around.
oldPrototype.setOwnerFunction(null);
}
if (isConstructor() || isInterface()) {
FunctionType superClass = getSuperClassConstructor();
if (superClass != null) {
superClass.addSubType(this);
wasAddedToExtendedConstructorSubtypes = true;
}
if (isInterface()) {
for (ObjectType interfaceType : getExtendedInterfaces()) {
if (interfaceType.getConstructor() != null) {
interfaceType.getConstructor().addSubType(this);
}
}
}
}
if (replacedPrototype) {
clearCachedValues();
}
return true;
} | [
"private",
"boolean",
"setPrototypeNoCheck",
"(",
"ObjectType",
"prototype",
",",
"Node",
"propertyNode",
")",
"{",
"ObjectType",
"oldPrototype",
"=",
"prototypeSlot",
"==",
"null",
"?",
"null",
":",
"(",
"ObjectType",
")",
"prototypeSlot",
".",
"getType",
"(",
")",
";",
"boolean",
"replacedPrototype",
"=",
"oldPrototype",
"!=",
"null",
";",
"this",
".",
"prototypeSlot",
"=",
"new",
"Property",
"(",
"\"prototype\"",
",",
"prototype",
",",
"true",
",",
"propertyNode",
"==",
"null",
"?",
"source",
":",
"propertyNode",
")",
";",
"prototype",
".",
"setOwnerFunction",
"(",
"this",
")",
";",
"if",
"(",
"oldPrototype",
"!=",
"null",
")",
"{",
"// Disassociating the old prototype makes this easier to debug--",
"// we don't have to worry about two prototypes running around.",
"oldPrototype",
".",
"setOwnerFunction",
"(",
"null",
")",
";",
"}",
"if",
"(",
"isConstructor",
"(",
")",
"||",
"isInterface",
"(",
")",
")",
"{",
"FunctionType",
"superClass",
"=",
"getSuperClassConstructor",
"(",
")",
";",
"if",
"(",
"superClass",
"!=",
"null",
")",
"{",
"superClass",
".",
"addSubType",
"(",
"this",
")",
";",
"wasAddedToExtendedConstructorSubtypes",
"=",
"true",
";",
"}",
"if",
"(",
"isInterface",
"(",
")",
")",
"{",
"for",
"(",
"ObjectType",
"interfaceType",
":",
"getExtendedInterfaces",
"(",
")",
")",
"{",
"if",
"(",
"interfaceType",
".",
"getConstructor",
"(",
")",
"!=",
"null",
")",
"{",
"interfaceType",
".",
"getConstructor",
"(",
")",
".",
"addSubType",
"(",
"this",
")",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"replacedPrototype",
")",
"{",
"clearCachedValues",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Set the prototype without doing any sanity checks. | [
"Set",
"the",
"prototype",
"without",
"doing",
"any",
"sanity",
"checks",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L497-L532 |
24,106 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.getAllImplementedInterfaces | public final Iterable<ObjectType> getAllImplementedInterfaces() {
// Store them in a linked hash set, so that the compile job is
// deterministic.
Set<ObjectType> interfaces = new LinkedHashSet<>();
for (ObjectType type : getImplementedInterfaces()) {
addRelatedInterfaces(type, interfaces);
}
return interfaces;
} | java | public final Iterable<ObjectType> getAllImplementedInterfaces() {
// Store them in a linked hash set, so that the compile job is
// deterministic.
Set<ObjectType> interfaces = new LinkedHashSet<>();
for (ObjectType type : getImplementedInterfaces()) {
addRelatedInterfaces(type, interfaces);
}
return interfaces;
} | [
"public",
"final",
"Iterable",
"<",
"ObjectType",
">",
"getAllImplementedInterfaces",
"(",
")",
"{",
"// Store them in a linked hash set, so that the compile job is",
"// deterministic.",
"Set",
"<",
"ObjectType",
">",
"interfaces",
"=",
"new",
"LinkedHashSet",
"<>",
"(",
")",
";",
"for",
"(",
"ObjectType",
"type",
":",
"getImplementedInterfaces",
"(",
")",
")",
"{",
"addRelatedInterfaces",
"(",
"type",
",",
"interfaces",
")",
";",
"}",
"return",
"interfaces",
";",
"}"
] | Returns all interfaces implemented by a class or its superclass and any superclasses for any of
those interfaces. If this is called before all types are resolved, it may return an incomplete
set. | [
"Returns",
"all",
"interfaces",
"implemented",
"by",
"a",
"class",
"or",
"its",
"superclass",
"and",
"any",
"superclasses",
"for",
"any",
"of",
"those",
"interfaces",
".",
"If",
"this",
"is",
"called",
"before",
"all",
"types",
"are",
"resolved",
"it",
"may",
"return",
"an",
"incomplete",
"set",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L539-L548 |
24,107 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.getImplementedInterfaces | public final ImmutableList<ObjectType> getImplementedInterfaces() {
FunctionType superCtor = isConstructor() ? getSuperClassConstructor() : null;
if (superCtor == null) {
return implementedInterfaces;
}
ImmutableList.Builder<ObjectType> builder = ImmutableList.builder();
builder.addAll(implementedInterfaces);
while (superCtor != null) {
builder.addAll(superCtor.implementedInterfaces);
superCtor = superCtor.getSuperClassConstructor();
}
return builder.build();
} | java | public final ImmutableList<ObjectType> getImplementedInterfaces() {
FunctionType superCtor = isConstructor() ? getSuperClassConstructor() : null;
if (superCtor == null) {
return implementedInterfaces;
}
ImmutableList.Builder<ObjectType> builder = ImmutableList.builder();
builder.addAll(implementedInterfaces);
while (superCtor != null) {
builder.addAll(superCtor.implementedInterfaces);
superCtor = superCtor.getSuperClassConstructor();
}
return builder.build();
} | [
"public",
"final",
"ImmutableList",
"<",
"ObjectType",
">",
"getImplementedInterfaces",
"(",
")",
"{",
"FunctionType",
"superCtor",
"=",
"isConstructor",
"(",
")",
"?",
"getSuperClassConstructor",
"(",
")",
":",
"null",
";",
"if",
"(",
"superCtor",
"==",
"null",
")",
"{",
"return",
"implementedInterfaces",
";",
"}",
"ImmutableList",
".",
"Builder",
"<",
"ObjectType",
">",
"builder",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"builder",
".",
"addAll",
"(",
"implementedInterfaces",
")",
";",
"while",
"(",
"superCtor",
"!=",
"null",
")",
"{",
"builder",
".",
"addAll",
"(",
"superCtor",
".",
"implementedInterfaces",
")",
";",
"superCtor",
"=",
"superCtor",
".",
"getSuperClassConstructor",
"(",
")",
";",
"}",
"return",
"builder",
".",
"build",
"(",
")",
";",
"}"
] | Returns interfaces implemented directly by a class or its superclass. | [
"Returns",
"interfaces",
"implemented",
"directly",
"by",
"a",
"class",
"or",
"its",
"superclass",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L578-L590 |
24,108 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.getBindReturnType | public final FunctionType getBindReturnType(int argsToBind) {
Builder builder =
builder(registry)
.withReturnType(getReturnType())
.withTemplateKeys(getTemplateTypeMap().getTemplateKeys());
if (argsToBind >= 0) {
Node origParams = getParametersNode();
if (origParams != null) {
Node params = origParams.cloneTree();
for (int i = 1; i < argsToBind && params.getFirstChild() != null; i++) {
if (params.getFirstChild().isVarArgs()) {
break;
}
params.removeFirstChild();
}
builder.withParamsNode(params);
}
}
return builder.build();
} | java | public final FunctionType getBindReturnType(int argsToBind) {
Builder builder =
builder(registry)
.withReturnType(getReturnType())
.withTemplateKeys(getTemplateTypeMap().getTemplateKeys());
if (argsToBind >= 0) {
Node origParams = getParametersNode();
if (origParams != null) {
Node params = origParams.cloneTree();
for (int i = 1; i < argsToBind && params.getFirstChild() != null; i++) {
if (params.getFirstChild().isVarArgs()) {
break;
}
params.removeFirstChild();
}
builder.withParamsNode(params);
}
}
return builder.build();
} | [
"public",
"final",
"FunctionType",
"getBindReturnType",
"(",
"int",
"argsToBind",
")",
"{",
"Builder",
"builder",
"=",
"builder",
"(",
"registry",
")",
".",
"withReturnType",
"(",
"getReturnType",
"(",
")",
")",
".",
"withTemplateKeys",
"(",
"getTemplateTypeMap",
"(",
")",
".",
"getTemplateKeys",
"(",
")",
")",
";",
"if",
"(",
"argsToBind",
">=",
"0",
")",
"{",
"Node",
"origParams",
"=",
"getParametersNode",
"(",
")",
";",
"if",
"(",
"origParams",
"!=",
"null",
")",
"{",
"Node",
"params",
"=",
"origParams",
".",
"cloneTree",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"argsToBind",
"&&",
"params",
".",
"getFirstChild",
"(",
")",
"!=",
"null",
";",
"i",
"++",
")",
"{",
"if",
"(",
"params",
".",
"getFirstChild",
"(",
")",
".",
"isVarArgs",
"(",
")",
")",
"{",
"break",
";",
"}",
"params",
".",
"removeFirstChild",
"(",
")",
";",
"}",
"builder",
".",
"withParamsNode",
"(",
"params",
")",
";",
"}",
"}",
"return",
"builder",
".",
"build",
"(",
")",
";",
"}"
] | Get the return value of calling "bind" on this function with the specified number of arguments.
<p>If -1 is passed, then we will return a result that accepts any parameters. | [
"Get",
"the",
"return",
"value",
"of",
"calling",
"bind",
"on",
"this",
"function",
"with",
"the",
"specified",
"number",
"of",
"arguments",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L670-L689 |
24,109 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.checkFunctionEquivalenceHelper | final boolean checkFunctionEquivalenceHelper(
FunctionType that, EquivalenceMethod eqMethod, EqCache eqCache) {
if (this == that) {
return true;
}
if (kind != that.kind) {
return false;
}
switch (kind) {
case CONSTRUCTOR:
return false; // constructors use identity semantics, which we already checked for above.
case INTERFACE:
return getReferenceName().equals(that.getReferenceName());
case ORDINARY:
return typeOfThis.checkEquivalenceHelper(that.typeOfThis, eqMethod, eqCache)
&& call.checkArrowEquivalenceHelper(that.call, eqMethod, eqCache);
default:
throw new AssertionError();
}
} | java | final boolean checkFunctionEquivalenceHelper(
FunctionType that, EquivalenceMethod eqMethod, EqCache eqCache) {
if (this == that) {
return true;
}
if (kind != that.kind) {
return false;
}
switch (kind) {
case CONSTRUCTOR:
return false; // constructors use identity semantics, which we already checked for above.
case INTERFACE:
return getReferenceName().equals(that.getReferenceName());
case ORDINARY:
return typeOfThis.checkEquivalenceHelper(that.typeOfThis, eqMethod, eqCache)
&& call.checkArrowEquivalenceHelper(that.call, eqMethod, eqCache);
default:
throw new AssertionError();
}
} | [
"final",
"boolean",
"checkFunctionEquivalenceHelper",
"(",
"FunctionType",
"that",
",",
"EquivalenceMethod",
"eqMethod",
",",
"EqCache",
"eqCache",
")",
"{",
"if",
"(",
"this",
"==",
"that",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"kind",
"!=",
"that",
".",
"kind",
")",
"{",
"return",
"false",
";",
"}",
"switch",
"(",
"kind",
")",
"{",
"case",
"CONSTRUCTOR",
":",
"return",
"false",
";",
"// constructors use identity semantics, which we already checked for above.",
"case",
"INTERFACE",
":",
"return",
"getReferenceName",
"(",
")",
".",
"equals",
"(",
"that",
".",
"getReferenceName",
"(",
")",
")",
";",
"case",
"ORDINARY",
":",
"return",
"typeOfThis",
".",
"checkEquivalenceHelper",
"(",
"that",
".",
"typeOfThis",
",",
"eqMethod",
",",
"eqCache",
")",
"&&",
"call",
".",
"checkArrowEquivalenceHelper",
"(",
"that",
".",
"call",
",",
"eqMethod",
",",
"eqCache",
")",
";",
"default",
":",
"throw",
"new",
"AssertionError",
"(",
")",
";",
"}",
"}"
] | Two function types are equal if their signatures match. Since they don't have signatures, two
interfaces are equal if their names match. | [
"Two",
"function",
"types",
"are",
"equal",
"if",
"their",
"signatures",
"match",
".",
"Since",
"they",
"don",
"t",
"have",
"signatures",
"two",
"interfaces",
"are",
"equal",
"if",
"their",
"names",
"match",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L902-L921 |
24,110 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.appendVarArgsString | private void appendVarArgsString(StringBuilder sb, JSType paramType, boolean forAnnotations) {
sb.append("...");
paramType.appendAsNonNull(sb, forAnnotations);
} | java | private void appendVarArgsString(StringBuilder sb, JSType paramType, boolean forAnnotations) {
sb.append("...");
paramType.appendAsNonNull(sb, forAnnotations);
} | [
"private",
"void",
"appendVarArgsString",
"(",
"StringBuilder",
"sb",
",",
"JSType",
"paramType",
",",
"boolean",
"forAnnotations",
")",
"{",
"sb",
".",
"append",
"(",
"\"...\"",
")",
";",
"paramType",
".",
"appendAsNonNull",
"(",
"sb",
",",
"forAnnotations",
")",
";",
"}"
] | Gets the string representation of a var args param. | [
"Gets",
"the",
"string",
"representation",
"of",
"a",
"var",
"args",
"param",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L1011-L1014 |
24,111 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.appendOptionalArgString | private void appendOptionalArgString(StringBuilder sb, JSType paramType, boolean forAnnotations) {
if (paramType.isUnionType()) {
// Remove the optionality from the var arg.
paramType =
paramType
.toMaybeUnionType()
.getRestrictedUnion(registry.getNativeType(JSTypeNative.VOID_TYPE));
}
paramType.appendAsNonNull(sb, forAnnotations).append("=");
} | java | private void appendOptionalArgString(StringBuilder sb, JSType paramType, boolean forAnnotations) {
if (paramType.isUnionType()) {
// Remove the optionality from the var arg.
paramType =
paramType
.toMaybeUnionType()
.getRestrictedUnion(registry.getNativeType(JSTypeNative.VOID_TYPE));
}
paramType.appendAsNonNull(sb, forAnnotations).append("=");
} | [
"private",
"void",
"appendOptionalArgString",
"(",
"StringBuilder",
"sb",
",",
"JSType",
"paramType",
",",
"boolean",
"forAnnotations",
")",
"{",
"if",
"(",
"paramType",
".",
"isUnionType",
"(",
")",
")",
"{",
"// Remove the optionality from the var arg.",
"paramType",
"=",
"paramType",
".",
"toMaybeUnionType",
"(",
")",
".",
"getRestrictedUnion",
"(",
"registry",
".",
"getNativeType",
"(",
"JSTypeNative",
".",
"VOID_TYPE",
")",
")",
";",
"}",
"paramType",
".",
"appendAsNonNull",
"(",
"sb",
",",
"forAnnotations",
")",
".",
"append",
"(",
"\"=\"",
")",
";",
"}"
] | Gets the string representation of an optional param. | [
"Gets",
"the",
"string",
"representation",
"of",
"an",
"optional",
"param",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L1017-L1026 |
24,112 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.setSource | public final void setSource(Node source) {
if (prototypeSlot != null) {
// NOTE(bashir): On one hand when source is null we want to drop any
// references to old nodes retained in prototypeSlot. On the other hand
// we cannot simply drop prototypeSlot, so we retain all information
// except the propertyNode for which we use an approximation! These
// details mostly matter in hot-swap passes.
if (source == null || prototypeSlot.getNode() == null) {
prototypeSlot =
new Property(
prototypeSlot.getName(),
prototypeSlot.getType(),
prototypeSlot.isTypeInferred(),
source);
}
}
this.source = source;
} | java | public final void setSource(Node source) {
if (prototypeSlot != null) {
// NOTE(bashir): On one hand when source is null we want to drop any
// references to old nodes retained in prototypeSlot. On the other hand
// we cannot simply drop prototypeSlot, so we retain all information
// except the propertyNode for which we use an approximation! These
// details mostly matter in hot-swap passes.
if (source == null || prototypeSlot.getNode() == null) {
prototypeSlot =
new Property(
prototypeSlot.getName(),
prototypeSlot.getType(),
prototypeSlot.isTypeInferred(),
source);
}
}
this.source = source;
} | [
"public",
"final",
"void",
"setSource",
"(",
"Node",
"source",
")",
"{",
"if",
"(",
"prototypeSlot",
"!=",
"null",
")",
"{",
"// NOTE(bashir): On one hand when source is null we want to drop any",
"// references to old nodes retained in prototypeSlot. On the other hand",
"// we cannot simply drop prototypeSlot, so we retain all information",
"// except the propertyNode for which we use an approximation! These",
"// details mostly matter in hot-swap passes.",
"if",
"(",
"source",
"==",
"null",
"||",
"prototypeSlot",
".",
"getNode",
"(",
")",
"==",
"null",
")",
"{",
"prototypeSlot",
"=",
"new",
"Property",
"(",
"prototypeSlot",
".",
"getName",
"(",
")",
",",
"prototypeSlot",
".",
"getType",
"(",
")",
",",
"prototypeSlot",
".",
"isTypeInferred",
"(",
")",
",",
"source",
")",
";",
"}",
"}",
"this",
".",
"source",
"=",
"source",
";",
"}"
] | Sets the source node. | [
"Sets",
"the",
"source",
"node",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L1131-L1148 |
24,113 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.addSubType | private void addSubType(FunctionType subType) {
if (subTypes == null) {
subTypes = new ArrayList<>();
}
subTypes.add(subType);
} | java | private void addSubType(FunctionType subType) {
if (subTypes == null) {
subTypes = new ArrayList<>();
}
subTypes.add(subType);
} | [
"private",
"void",
"addSubType",
"(",
"FunctionType",
"subType",
")",
"{",
"if",
"(",
"subTypes",
"==",
"null",
")",
"{",
"subTypes",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"subTypes",
".",
"add",
"(",
"subType",
")",
";",
"}"
] | Adds a type to the list of subtypes for this type. | [
"Adds",
"a",
"type",
"to",
"the",
"list",
"of",
"subtypes",
"for",
"this",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L1151-L1156 |
24,114 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.clearCachedValues | @Override
public final void clearCachedValues() {
super.clearCachedValues();
if (subTypes != null) {
for (FunctionType subType : subTypes) {
subType.clearCachedValues();
}
}
if (!isNativeObjectType()) {
if (hasInstanceType()) {
getInstanceType().clearCachedValues();
}
if (prototypeSlot != null) {
((ObjectType) prototypeSlot.getType()).clearCachedValues();
}
}
} | java | @Override
public final void clearCachedValues() {
super.clearCachedValues();
if (subTypes != null) {
for (FunctionType subType : subTypes) {
subType.clearCachedValues();
}
}
if (!isNativeObjectType()) {
if (hasInstanceType()) {
getInstanceType().clearCachedValues();
}
if (prototypeSlot != null) {
((ObjectType) prototypeSlot.getType()).clearCachedValues();
}
}
} | [
"@",
"Override",
"public",
"final",
"void",
"clearCachedValues",
"(",
")",
"{",
"super",
".",
"clearCachedValues",
"(",
")",
";",
"if",
"(",
"subTypes",
"!=",
"null",
")",
"{",
"for",
"(",
"FunctionType",
"subType",
":",
"subTypes",
")",
"{",
"subType",
".",
"clearCachedValues",
"(",
")",
";",
"}",
"}",
"if",
"(",
"!",
"isNativeObjectType",
"(",
")",
")",
"{",
"if",
"(",
"hasInstanceType",
"(",
")",
")",
"{",
"getInstanceType",
"(",
")",
".",
"clearCachedValues",
"(",
")",
";",
"}",
"if",
"(",
"prototypeSlot",
"!=",
"null",
")",
"{",
"(",
"(",
"ObjectType",
")",
"prototypeSlot",
".",
"getType",
"(",
")",
")",
".",
"clearCachedValues",
"(",
")",
";",
"}",
"}",
"}"
] | prototypeSlot is non-null, and this override does nothing to change that state. | [
"prototypeSlot",
"is",
"non",
"-",
"null",
"and",
"this",
"override",
"does",
"nothing",
"to",
"change",
"that",
"state",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L1177-L1196 |
24,115 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.resolveTypeListHelper | private ImmutableList<ObjectType> resolveTypeListHelper(
ImmutableList<ObjectType> list, ErrorReporter reporter) {
boolean changed = false;
ImmutableList.Builder<ObjectType> resolvedList = ImmutableList.builder();
for (ObjectType type : list) {
JSType rt = type.resolve(reporter);
if (!rt.isObjectType()) {
reporter.warning(
"not an object type: " + rt + " (at " + toString() + ")",
source.getSourceFileName(),
source.getLineno(),
source.getCharno());
continue;
}
ObjectType resolved = rt.toObjectType();
resolvedList.add(resolved);
changed |= (resolved != type);
}
return changed ? resolvedList.build() : null;
} | java | private ImmutableList<ObjectType> resolveTypeListHelper(
ImmutableList<ObjectType> list, ErrorReporter reporter) {
boolean changed = false;
ImmutableList.Builder<ObjectType> resolvedList = ImmutableList.builder();
for (ObjectType type : list) {
JSType rt = type.resolve(reporter);
if (!rt.isObjectType()) {
reporter.warning(
"not an object type: " + rt + " (at " + toString() + ")",
source.getSourceFileName(),
source.getLineno(),
source.getCharno());
continue;
}
ObjectType resolved = rt.toObjectType();
resolvedList.add(resolved);
changed |= (resolved != type);
}
return changed ? resolvedList.build() : null;
} | [
"private",
"ImmutableList",
"<",
"ObjectType",
">",
"resolveTypeListHelper",
"(",
"ImmutableList",
"<",
"ObjectType",
">",
"list",
",",
"ErrorReporter",
"reporter",
")",
"{",
"boolean",
"changed",
"=",
"false",
";",
"ImmutableList",
".",
"Builder",
"<",
"ObjectType",
">",
"resolvedList",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"for",
"(",
"ObjectType",
"type",
":",
"list",
")",
"{",
"JSType",
"rt",
"=",
"type",
".",
"resolve",
"(",
"reporter",
")",
";",
"if",
"(",
"!",
"rt",
".",
"isObjectType",
"(",
")",
")",
"{",
"reporter",
".",
"warning",
"(",
"\"not an object type: \"",
"+",
"rt",
"+",
"\" (at \"",
"+",
"toString",
"(",
")",
"+",
"\")\"",
",",
"source",
".",
"getSourceFileName",
"(",
")",
",",
"source",
".",
"getLineno",
"(",
")",
",",
"source",
".",
"getCharno",
"(",
")",
")",
";",
"continue",
";",
"}",
"ObjectType",
"resolved",
"=",
"rt",
".",
"toObjectType",
"(",
")",
";",
"resolvedList",
".",
"add",
"(",
"resolved",
")",
";",
"changed",
"|=",
"(",
"resolved",
"!=",
"type",
")",
";",
"}",
"return",
"changed",
"?",
"resolvedList",
".",
"build",
"(",
")",
":",
"null",
";",
"}"
] | Resolve each item in the list, and return a new list if any references changed. Otherwise,
return null. | [
"Resolve",
"each",
"item",
"in",
"the",
"list",
"and",
"return",
"a",
"new",
"list",
"if",
"any",
"references",
"changed",
".",
"Otherwise",
"return",
"null",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L1260-L1279 |
24,116 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.getPropertyTypeMap | @Override
public final Map<String, JSType> getPropertyTypeMap() {
Map<String, JSType> propTypeMap = new LinkedHashMap<>();
updatePropertyTypeMap(this, propTypeMap, new HashSet<FunctionType>());
return propTypeMap;
} | java | @Override
public final Map<String, JSType> getPropertyTypeMap() {
Map<String, JSType> propTypeMap = new LinkedHashMap<>();
updatePropertyTypeMap(this, propTypeMap, new HashSet<FunctionType>());
return propTypeMap;
} | [
"@",
"Override",
"public",
"final",
"Map",
"<",
"String",
",",
"JSType",
">",
"getPropertyTypeMap",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"JSType",
">",
"propTypeMap",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"updatePropertyTypeMap",
"(",
"this",
",",
"propTypeMap",
",",
"new",
"HashSet",
"<",
"FunctionType",
">",
"(",
")",
")",
";",
"return",
"propTypeMap",
";",
"}"
] | get the map of properties to types covered in a function type
@return a Map that maps the property's name to the property's type | [
"get",
"the",
"map",
"of",
"properties",
"to",
"types",
"covered",
"in",
"a",
"function",
"type"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L1357-L1362 |
24,117 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.forgetParameterAndReturnTypes | public final FunctionType forgetParameterAndReturnTypes() {
FunctionType result =
builder(registry)
.withName(getReferenceName())
.withSourceNode(source)
.withTypeOfThis(getInstanceType())
.withKind(kind)
.build();
result.setPrototypeBasedOn(getInstanceType());
return result;
} | java | public final FunctionType forgetParameterAndReturnTypes() {
FunctionType result =
builder(registry)
.withName(getReferenceName())
.withSourceNode(source)
.withTypeOfThis(getInstanceType())
.withKind(kind)
.build();
result.setPrototypeBasedOn(getInstanceType());
return result;
} | [
"public",
"final",
"FunctionType",
"forgetParameterAndReturnTypes",
"(",
")",
"{",
"FunctionType",
"result",
"=",
"builder",
"(",
"registry",
")",
".",
"withName",
"(",
"getReferenceName",
"(",
")",
")",
".",
"withSourceNode",
"(",
"source",
")",
".",
"withTypeOfThis",
"(",
"getInstanceType",
"(",
")",
")",
".",
"withKind",
"(",
"kind",
")",
".",
"build",
"(",
")",
";",
"result",
".",
"setPrototypeBasedOn",
"(",
"getInstanceType",
"(",
")",
")",
";",
"return",
"result",
";",
"}"
] | Create a new constructor with the parameters and return type stripped. | [
"Create",
"a",
"new",
"constructor",
"with",
"the",
"parameters",
"and",
"return",
"type",
"stripped",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L1463-L1473 |
24,118 | google/closure-compiler | src/com/google/javascript/rhino/jstype/FunctionType.java | FunctionType.getConstructorOnlyTemplateParameters | public final ImmutableList<TemplateType> getConstructorOnlyTemplateParameters() {
TemplateTypeMap ctorMap = getTemplateTypeMap();
TemplateTypeMap instanceMap = getInstanceType().getTemplateTypeMap();
if (ctorMap == instanceMap) {
return ImmutableList.of();
}
ImmutableList.Builder<TemplateType> ctorKeys = ImmutableList.builder();
Set<TemplateType> instanceKeys = ImmutableSet.copyOf(instanceMap.getUnfilledTemplateKeys());
for (TemplateType ctorKey : ctorMap.getUnfilledTemplateKeys()) {
if (!instanceKeys.contains(ctorKey)) {
ctorKeys.add(ctorKey);
}
}
return ctorKeys.build();
} | java | public final ImmutableList<TemplateType> getConstructorOnlyTemplateParameters() {
TemplateTypeMap ctorMap = getTemplateTypeMap();
TemplateTypeMap instanceMap = getInstanceType().getTemplateTypeMap();
if (ctorMap == instanceMap) {
return ImmutableList.of();
}
ImmutableList.Builder<TemplateType> ctorKeys = ImmutableList.builder();
Set<TemplateType> instanceKeys = ImmutableSet.copyOf(instanceMap.getUnfilledTemplateKeys());
for (TemplateType ctorKey : ctorMap.getUnfilledTemplateKeys()) {
if (!instanceKeys.contains(ctorKey)) {
ctorKeys.add(ctorKey);
}
}
return ctorKeys.build();
} | [
"public",
"final",
"ImmutableList",
"<",
"TemplateType",
">",
"getConstructorOnlyTemplateParameters",
"(",
")",
"{",
"TemplateTypeMap",
"ctorMap",
"=",
"getTemplateTypeMap",
"(",
")",
";",
"TemplateTypeMap",
"instanceMap",
"=",
"getInstanceType",
"(",
")",
".",
"getTemplateTypeMap",
"(",
")",
";",
"if",
"(",
"ctorMap",
"==",
"instanceMap",
")",
"{",
"return",
"ImmutableList",
".",
"of",
"(",
")",
";",
"}",
"ImmutableList",
".",
"Builder",
"<",
"TemplateType",
">",
"ctorKeys",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"Set",
"<",
"TemplateType",
">",
"instanceKeys",
"=",
"ImmutableSet",
".",
"copyOf",
"(",
"instanceMap",
".",
"getUnfilledTemplateKeys",
"(",
")",
")",
";",
"for",
"(",
"TemplateType",
"ctorKey",
":",
"ctorMap",
".",
"getUnfilledTemplateKeys",
"(",
")",
")",
"{",
"if",
"(",
"!",
"instanceKeys",
".",
"contains",
"(",
"ctorKey",
")",
")",
"{",
"ctorKeys",
".",
"add",
"(",
"ctorKey",
")",
";",
"}",
"}",
"return",
"ctorKeys",
".",
"build",
"(",
")",
";",
"}"
] | Returns a list of template types present on the constructor but not on the instance. | [
"Returns",
"a",
"list",
"of",
"template",
"types",
"present",
"on",
"the",
"constructor",
"but",
"not",
"on",
"the",
"instance",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/FunctionType.java#L1476-L1490 |
24,119 | google/closure-compiler | src/com/google/javascript/jscomp/PreprocessorSymbolTable.java | PreprocessorSymbolTable.addStringNode | void addStringNode(Node n, AbstractCompiler compiler) {
String name = n.getString();
Node syntheticRef =
NodeUtil.newQName(
compiler, name, n /* real source offsets will be filled in below */, name);
// Offsets to add to source. Named for documentation purposes.
final int forQuote = 1;
final int forDot = 1;
Node current = null;
for (current = syntheticRef; current.isGetProp(); current = current.getFirstChild()) {
int fullLen = current.getQualifiedName().length();
int namespaceLen = current.getFirstChild().getQualifiedName().length();
current.setSourceEncodedPosition(n.getSourcePosition() + forQuote);
current.setLength(fullLen);
current
.getLastChild()
.setSourceEncodedPosition(n.getSourcePosition() + namespaceLen + forQuote + forDot);
current.getLastChild().setLength(current.getLastChild().getString().length());
}
current.setSourceEncodedPosition(n.getSourcePosition() + forQuote);
current.setLength(current.getString().length());
addReference(syntheticRef);
} | java | void addStringNode(Node n, AbstractCompiler compiler) {
String name = n.getString();
Node syntheticRef =
NodeUtil.newQName(
compiler, name, n /* real source offsets will be filled in below */, name);
// Offsets to add to source. Named for documentation purposes.
final int forQuote = 1;
final int forDot = 1;
Node current = null;
for (current = syntheticRef; current.isGetProp(); current = current.getFirstChild()) {
int fullLen = current.getQualifiedName().length();
int namespaceLen = current.getFirstChild().getQualifiedName().length();
current.setSourceEncodedPosition(n.getSourcePosition() + forQuote);
current.setLength(fullLen);
current
.getLastChild()
.setSourceEncodedPosition(n.getSourcePosition() + namespaceLen + forQuote + forDot);
current.getLastChild().setLength(current.getLastChild().getString().length());
}
current.setSourceEncodedPosition(n.getSourcePosition() + forQuote);
current.setLength(current.getString().length());
addReference(syntheticRef);
} | [
"void",
"addStringNode",
"(",
"Node",
"n",
",",
"AbstractCompiler",
"compiler",
")",
"{",
"String",
"name",
"=",
"n",
".",
"getString",
"(",
")",
";",
"Node",
"syntheticRef",
"=",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"name",
",",
"n",
"/* real source offsets will be filled in below */",
",",
"name",
")",
";",
"// Offsets to add to source. Named for documentation purposes.",
"final",
"int",
"forQuote",
"=",
"1",
";",
"final",
"int",
"forDot",
"=",
"1",
";",
"Node",
"current",
"=",
"null",
";",
"for",
"(",
"current",
"=",
"syntheticRef",
";",
"current",
".",
"isGetProp",
"(",
")",
";",
"current",
"=",
"current",
".",
"getFirstChild",
"(",
")",
")",
"{",
"int",
"fullLen",
"=",
"current",
".",
"getQualifiedName",
"(",
")",
".",
"length",
"(",
")",
";",
"int",
"namespaceLen",
"=",
"current",
".",
"getFirstChild",
"(",
")",
".",
"getQualifiedName",
"(",
")",
".",
"length",
"(",
")",
";",
"current",
".",
"setSourceEncodedPosition",
"(",
"n",
".",
"getSourcePosition",
"(",
")",
"+",
"forQuote",
")",
";",
"current",
".",
"setLength",
"(",
"fullLen",
")",
";",
"current",
".",
"getLastChild",
"(",
")",
".",
"setSourceEncodedPosition",
"(",
"n",
".",
"getSourcePosition",
"(",
")",
"+",
"namespaceLen",
"+",
"forQuote",
"+",
"forDot",
")",
";",
"current",
".",
"getLastChild",
"(",
")",
".",
"setLength",
"(",
"current",
".",
"getLastChild",
"(",
")",
".",
"getString",
"(",
")",
".",
"length",
"(",
")",
")",
";",
"}",
"current",
".",
"setSourceEncodedPosition",
"(",
"n",
".",
"getSourcePosition",
"(",
")",
"+",
"forQuote",
")",
";",
"current",
".",
"setLength",
"(",
"current",
".",
"getString",
"(",
")",
".",
"length",
"(",
")",
")",
";",
"addReference",
"(",
"syntheticRef",
")",
";",
"}"
] | Adds a synthetic reference for a 'string' node representing a reference name.
<p>This does some work to set the source info for the reference as well. | [
"Adds",
"a",
"synthetic",
"reference",
"for",
"a",
"string",
"node",
"representing",
"a",
"reference",
"name",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PreprocessorSymbolTable.java#L165-L193 |
24,120 | google/closure-compiler | src/com/google/javascript/jscomp/GlobalVarReferenceMap.java | GlobalVarReferenceMap.resetGlobalVarReferences | private void resetGlobalVarReferences(
Map<Var, ReferenceCollection> globalRefMap) {
refMap = new LinkedHashMap<>();
for (Entry<Var, ReferenceCollection> entry : globalRefMap.entrySet()) {
Var var = entry.getKey();
if (var.isGlobal()) {
refMap.put(var.getName(), entry.getValue());
}
}
} | java | private void resetGlobalVarReferences(
Map<Var, ReferenceCollection> globalRefMap) {
refMap = new LinkedHashMap<>();
for (Entry<Var, ReferenceCollection> entry : globalRefMap.entrySet()) {
Var var = entry.getKey();
if (var.isGlobal()) {
refMap.put(var.getName(), entry.getValue());
}
}
} | [
"private",
"void",
"resetGlobalVarReferences",
"(",
"Map",
"<",
"Var",
",",
"ReferenceCollection",
">",
"globalRefMap",
")",
"{",
"refMap",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"for",
"(",
"Entry",
"<",
"Var",
",",
"ReferenceCollection",
">",
"entry",
":",
"globalRefMap",
".",
"entrySet",
"(",
")",
")",
"{",
"Var",
"var",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"if",
"(",
"var",
".",
"isGlobal",
"(",
")",
")",
"{",
"refMap",
".",
"put",
"(",
"var",
".",
"getName",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Resets global var reference map with the new provide map.
@param globalRefMap The reference map result of a
{@link ReferenceCollectingCallback} pass collected from the whole AST. | [
"Resets",
"global",
"var",
"reference",
"map",
"with",
"the",
"new",
"provide",
"map",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/GlobalVarReferenceMap.java#L75-L84 |
24,121 | google/closure-compiler | src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java | DevirtualizePrototypeMethods.isPrototypeMethodDefinition | private static boolean isPrototypeMethodDefinition(Node node) {
Node parent = node.getParent();
Node grandparent = node.getGrandparent();
if (parent == null || grandparent == null) {
return false;
}
switch (node.getToken()) {
case MEMBER_FUNCTION_DEF:
if (NodeUtil.isEs6ConstructorMemberFunctionDef(node)) {
return false; // Constructors aren't methods.
}
return true;
case GETPROP:
{
// Case: `Foo.prototype.bar = function() { };
if (parent.getFirstChild() != node) {
return false;
}
if (!NodeUtil.isExprAssign(grandparent)) {
return false;
}
Node functionNode = parent.getLastChild();
if ((functionNode == null) || !functionNode.isFunction()) {
return false;
}
Node nameNode = node.getFirstChild();
return nameNode.isGetProp() && nameNode.getLastChild().getString().equals("prototype");
}
case STRING_KEY:
{
// Case: `Foo.prototype = {
// bar: function() { },
// }`
checkArgument(parent.isObjectLit(), parent);
if (!grandparent.isAssign()) {
return false;
}
if (grandparent.getLastChild() != parent) {
return false;
}
Node greatgrandparent = grandparent.getParent();
if (greatgrandparent == null || !greatgrandparent.isExprResult()) {
return false;
}
Node functionNode = node.getFirstChild();
if ((functionNode == null) || !functionNode.isFunction()) {
return false;
}
Node target = grandparent.getFirstChild();
return target.isGetProp() && target.getLastChild().getString().equals("prototype");
}
default:
return false;
}
} | java | private static boolean isPrototypeMethodDefinition(Node node) {
Node parent = node.getParent();
Node grandparent = node.getGrandparent();
if (parent == null || grandparent == null) {
return false;
}
switch (node.getToken()) {
case MEMBER_FUNCTION_DEF:
if (NodeUtil.isEs6ConstructorMemberFunctionDef(node)) {
return false; // Constructors aren't methods.
}
return true;
case GETPROP:
{
// Case: `Foo.prototype.bar = function() { };
if (parent.getFirstChild() != node) {
return false;
}
if (!NodeUtil.isExprAssign(grandparent)) {
return false;
}
Node functionNode = parent.getLastChild();
if ((functionNode == null) || !functionNode.isFunction()) {
return false;
}
Node nameNode = node.getFirstChild();
return nameNode.isGetProp() && nameNode.getLastChild().getString().equals("prototype");
}
case STRING_KEY:
{
// Case: `Foo.prototype = {
// bar: function() { },
// }`
checkArgument(parent.isObjectLit(), parent);
if (!grandparent.isAssign()) {
return false;
}
if (grandparent.getLastChild() != parent) {
return false;
}
Node greatgrandparent = grandparent.getParent();
if (greatgrandparent == null || !greatgrandparent.isExprResult()) {
return false;
}
Node functionNode = node.getFirstChild();
if ((functionNode == null) || !functionNode.isFunction()) {
return false;
}
Node target = grandparent.getFirstChild();
return target.isGetProp() && target.getLastChild().getString().equals("prototype");
}
default:
return false;
}
} | [
"private",
"static",
"boolean",
"isPrototypeMethodDefinition",
"(",
"Node",
"node",
")",
"{",
"Node",
"parent",
"=",
"node",
".",
"getParent",
"(",
")",
";",
"Node",
"grandparent",
"=",
"node",
".",
"getGrandparent",
"(",
")",
";",
"if",
"(",
"parent",
"==",
"null",
"||",
"grandparent",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"switch",
"(",
"node",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"MEMBER_FUNCTION_DEF",
":",
"if",
"(",
"NodeUtil",
".",
"isEs6ConstructorMemberFunctionDef",
"(",
"node",
")",
")",
"{",
"return",
"false",
";",
"// Constructors aren't methods.",
"}",
"return",
"true",
";",
"case",
"GETPROP",
":",
"{",
"// Case: `Foo.prototype.bar = function() { };",
"if",
"(",
"parent",
".",
"getFirstChild",
"(",
")",
"!=",
"node",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"NodeUtil",
".",
"isExprAssign",
"(",
"grandparent",
")",
")",
"{",
"return",
"false",
";",
"}",
"Node",
"functionNode",
"=",
"parent",
".",
"getLastChild",
"(",
")",
";",
"if",
"(",
"(",
"functionNode",
"==",
"null",
")",
"||",
"!",
"functionNode",
".",
"isFunction",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"Node",
"nameNode",
"=",
"node",
".",
"getFirstChild",
"(",
")",
";",
"return",
"nameNode",
".",
"isGetProp",
"(",
")",
"&&",
"nameNode",
".",
"getLastChild",
"(",
")",
".",
"getString",
"(",
")",
".",
"equals",
"(",
"\"prototype\"",
")",
";",
"}",
"case",
"STRING_KEY",
":",
"{",
"// Case: `Foo.prototype = {",
"// bar: function() { },",
"// }`",
"checkArgument",
"(",
"parent",
".",
"isObjectLit",
"(",
")",
",",
"parent",
")",
";",
"if",
"(",
"!",
"grandparent",
".",
"isAssign",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"grandparent",
".",
"getLastChild",
"(",
")",
"!=",
"parent",
")",
"{",
"return",
"false",
";",
"}",
"Node",
"greatgrandparent",
"=",
"grandparent",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"greatgrandparent",
"==",
"null",
"||",
"!",
"greatgrandparent",
".",
"isExprResult",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"Node",
"functionNode",
"=",
"node",
".",
"getFirstChild",
"(",
")",
";",
"if",
"(",
"(",
"functionNode",
"==",
"null",
")",
"||",
"!",
"functionNode",
".",
"isFunction",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"Node",
"target",
"=",
"grandparent",
".",
"getFirstChild",
"(",
")",
";",
"return",
"target",
".",
"isGetProp",
"(",
")",
"&&",
"target",
".",
"getLastChild",
"(",
")",
".",
"getString",
"(",
")",
".",
"equals",
"(",
"\"prototype\"",
")",
";",
"}",
"default",
":",
"return",
"false",
";",
"}",
"}"
] | Determines if the current node is a function prototype definition. | [
"Determines",
"if",
"the",
"current",
"node",
"is",
"a",
"function",
"prototype",
"definition",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java#L136-L203 |
24,122 | google/closure-compiler | src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java | DevirtualizePrototypeMethods.isEligibleDefinitionSite | private boolean isEligibleDefinitionSite(String name, Node definitionSite) {
switch (definitionSite.getToken()) {
case GETPROP:
case MEMBER_FUNCTION_DEF:
case STRING_KEY:
break;
default:
// No other node types are supported.
throw new IllegalArgumentException(definitionSite.toString());
}
// Exporting a method prevents rewrite.
CodingConvention codingConvention = compiler.getCodingConvention();
if (codingConvention.isExported(name)) {
return false;
}
if (!isPrototypeMethodDefinition(definitionSite)) {
return false;
}
return true;
} | java | private boolean isEligibleDefinitionSite(String name, Node definitionSite) {
switch (definitionSite.getToken()) {
case GETPROP:
case MEMBER_FUNCTION_DEF:
case STRING_KEY:
break;
default:
// No other node types are supported.
throw new IllegalArgumentException(definitionSite.toString());
}
// Exporting a method prevents rewrite.
CodingConvention codingConvention = compiler.getCodingConvention();
if (codingConvention.isExported(name)) {
return false;
}
if (!isPrototypeMethodDefinition(definitionSite)) {
return false;
}
return true;
} | [
"private",
"boolean",
"isEligibleDefinitionSite",
"(",
"String",
"name",
",",
"Node",
"definitionSite",
")",
"{",
"switch",
"(",
"definitionSite",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"GETPROP",
":",
"case",
"MEMBER_FUNCTION_DEF",
":",
"case",
"STRING_KEY",
":",
"break",
";",
"default",
":",
"// No other node types are supported.",
"throw",
"new",
"IllegalArgumentException",
"(",
"definitionSite",
".",
"toString",
"(",
")",
")",
";",
"}",
"// Exporting a method prevents rewrite.",
"CodingConvention",
"codingConvention",
"=",
"compiler",
".",
"getCodingConvention",
"(",
")",
";",
"if",
"(",
"codingConvention",
".",
"isExported",
"(",
"name",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"isPrototypeMethodDefinition",
"(",
"definitionSite",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Determines if a method definition site is eligible for rewrite as a global.
<p>In order to be eligible for rewrite, the definition site must:
<ul>
<li>Not be exported
<li>Be for a prototype method
</ul> | [
"Determines",
"if",
"a",
"method",
"definition",
"site",
"is",
"eligible",
"for",
"rewrite",
"as",
"a",
"global",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java#L215-L238 |
24,123 | google/closure-compiler | src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java | DevirtualizePrototypeMethods.isEligibleDefinitionFunction | private boolean isEligibleDefinitionFunction(Node definitionFunction) {
checkArgument(definitionFunction.isFunction(), definitionFunction);
if (definitionFunction.isArrowFunction()) {
return false;
}
for (Node ancestor = definitionFunction.getParent();
ancestor != null;
ancestor = ancestor.getParent()) {
// The definition must be made exactly once. (i.e. not in a loop, conditional, or function)
if (isScopingOrBranchingConstruct(ancestor)) {
return false;
}
// TODO(nickreid): Support this so long as the definition doesn't reference the name.
// We can't allow this in general because references to the local name:
// - won't be rewritten correctly
// - won't be the same across multiple definitions, even if they are node-wise identical.
if (ancestor.isClass() && localNameIsDeclaredByClass(ancestor)) {
return false;
}
}
if (NodeUtil.containsType(definitionFunction, Token.SUPER)) {
// TODO(b/120452418): Remove this when we have a rewrite for `super`. We punted initially due
// to complexity.
return false;
}
if (NodeUtil.doesFunctionReferenceOwnArgumentsObject(definitionFunction)) {
// Functions that access "arguments" are not eligible since rewriting changes the structure of
// the function params.
return false;
}
return true;
} | java | private boolean isEligibleDefinitionFunction(Node definitionFunction) {
checkArgument(definitionFunction.isFunction(), definitionFunction);
if (definitionFunction.isArrowFunction()) {
return false;
}
for (Node ancestor = definitionFunction.getParent();
ancestor != null;
ancestor = ancestor.getParent()) {
// The definition must be made exactly once. (i.e. not in a loop, conditional, or function)
if (isScopingOrBranchingConstruct(ancestor)) {
return false;
}
// TODO(nickreid): Support this so long as the definition doesn't reference the name.
// We can't allow this in general because references to the local name:
// - won't be rewritten correctly
// - won't be the same across multiple definitions, even if they are node-wise identical.
if (ancestor.isClass() && localNameIsDeclaredByClass(ancestor)) {
return false;
}
}
if (NodeUtil.containsType(definitionFunction, Token.SUPER)) {
// TODO(b/120452418): Remove this when we have a rewrite for `super`. We punted initially due
// to complexity.
return false;
}
if (NodeUtil.doesFunctionReferenceOwnArgumentsObject(definitionFunction)) {
// Functions that access "arguments" are not eligible since rewriting changes the structure of
// the function params.
return false;
}
return true;
} | [
"private",
"boolean",
"isEligibleDefinitionFunction",
"(",
"Node",
"definitionFunction",
")",
"{",
"checkArgument",
"(",
"definitionFunction",
".",
"isFunction",
"(",
")",
",",
"definitionFunction",
")",
";",
"if",
"(",
"definitionFunction",
".",
"isArrowFunction",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"Node",
"ancestor",
"=",
"definitionFunction",
".",
"getParent",
"(",
")",
";",
"ancestor",
"!=",
"null",
";",
"ancestor",
"=",
"ancestor",
".",
"getParent",
"(",
")",
")",
"{",
"// The definition must be made exactly once. (i.e. not in a loop, conditional, or function)",
"if",
"(",
"isScopingOrBranchingConstruct",
"(",
"ancestor",
")",
")",
"{",
"return",
"false",
";",
"}",
"// TODO(nickreid): Support this so long as the definition doesn't reference the name.",
"// We can't allow this in general because references to the local name:",
"// - won't be rewritten correctly",
"// - won't be the same across multiple definitions, even if they are node-wise identical.",
"if",
"(",
"ancestor",
".",
"isClass",
"(",
")",
"&&",
"localNameIsDeclaredByClass",
"(",
"ancestor",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"NodeUtil",
".",
"containsType",
"(",
"definitionFunction",
",",
"Token",
".",
"SUPER",
")",
")",
"{",
"// TODO(b/120452418): Remove this when we have a rewrite for `super`. We punted initially due",
"// to complexity.",
"return",
"false",
";",
"}",
"if",
"(",
"NodeUtil",
".",
"doesFunctionReferenceOwnArgumentsObject",
"(",
"definitionFunction",
")",
")",
"{",
"// Functions that access \"arguments\" are not eligible since rewriting changes the structure of",
"// the function params.",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Determines if a method definition function is eligible for rewrite as a global function.
<p>In order to be eligible for rewrite, the definition function must:
<ul>
<li>Be instantiated exactly once
<li>Be the only possible implementation at a given site
<li>Not refer to its `arguments`; no implicit varags
<li>Not be an arrow function
</ul> | [
"Determines",
"if",
"a",
"method",
"definition",
"function",
"is",
"eligible",
"for",
"rewrite",
"as",
"a",
"global",
"function",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java#L252-L289 |
24,124 | google/closure-compiler | src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java | DevirtualizePrototypeMethods.rewriteCall | private void rewriteCall(Node getprop, String newMethodName) {
checkArgument(getprop.isGetProp(), getprop);
Node call = getprop.getParent();
checkArgument(call.isCall(), call);
Node receiver = getprop.getFirstChild();
// This rewriting does not exactly preserve order of operations; the newly inserted static
// method name will be resolved before `receiver` is evaluated. This is known to be safe due
// to the eligibility checks earlier in the pass.
//
// We choose not to do a full-fidelity rewriting (e.g. using `ExpressionDecomposer`) because
// doing so means extracting `receiver` into a new variable at each call-site. This has a
// significant code-size impact (circa 2018-11-19).
getprop.removeChild(receiver);
call.replaceChild(getprop, receiver);
call.addChildToFront(IR.name(newMethodName).srcref(getprop));
if (receiver.isSuper()) {
// Case: `super.foo(a, b)` => `foo(this, a, b)`
receiver.setToken(Token.THIS);
}
call.putBooleanProp(Node.FREE_CALL, true);
compiler.reportChangeToEnclosingScope(call);
} | java | private void rewriteCall(Node getprop, String newMethodName) {
checkArgument(getprop.isGetProp(), getprop);
Node call = getprop.getParent();
checkArgument(call.isCall(), call);
Node receiver = getprop.getFirstChild();
// This rewriting does not exactly preserve order of operations; the newly inserted static
// method name will be resolved before `receiver` is evaluated. This is known to be safe due
// to the eligibility checks earlier in the pass.
//
// We choose not to do a full-fidelity rewriting (e.g. using `ExpressionDecomposer`) because
// doing so means extracting `receiver` into a new variable at each call-site. This has a
// significant code-size impact (circa 2018-11-19).
getprop.removeChild(receiver);
call.replaceChild(getprop, receiver);
call.addChildToFront(IR.name(newMethodName).srcref(getprop));
if (receiver.isSuper()) {
// Case: `super.foo(a, b)` => `foo(this, a, b)`
receiver.setToken(Token.THIS);
}
call.putBooleanProp(Node.FREE_CALL, true);
compiler.reportChangeToEnclosingScope(call);
} | [
"private",
"void",
"rewriteCall",
"(",
"Node",
"getprop",
",",
"String",
"newMethodName",
")",
"{",
"checkArgument",
"(",
"getprop",
".",
"isGetProp",
"(",
")",
",",
"getprop",
")",
";",
"Node",
"call",
"=",
"getprop",
".",
"getParent",
"(",
")",
";",
"checkArgument",
"(",
"call",
".",
"isCall",
"(",
")",
",",
"call",
")",
";",
"Node",
"receiver",
"=",
"getprop",
".",
"getFirstChild",
"(",
")",
";",
"// This rewriting does not exactly preserve order of operations; the newly inserted static",
"// method name will be resolved before `receiver` is evaluated. This is known to be safe due",
"// to the eligibility checks earlier in the pass.",
"//",
"// We choose not to do a full-fidelity rewriting (e.g. using `ExpressionDecomposer`) because",
"// doing so means extracting `receiver` into a new variable at each call-site. This has a",
"// significant code-size impact (circa 2018-11-19).",
"getprop",
".",
"removeChild",
"(",
"receiver",
")",
";",
"call",
".",
"replaceChild",
"(",
"getprop",
",",
"receiver",
")",
";",
"call",
".",
"addChildToFront",
"(",
"IR",
".",
"name",
"(",
"newMethodName",
")",
".",
"srcref",
"(",
"getprop",
")",
")",
";",
"if",
"(",
"receiver",
".",
"isSuper",
"(",
")",
")",
"{",
"// Case: `super.foo(a, b)` => `foo(this, a, b)`",
"receiver",
".",
"setToken",
"(",
"Token",
".",
"THIS",
")",
";",
"}",
"call",
".",
"putBooleanProp",
"(",
"Node",
".",
"FREE_CALL",
",",
"true",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"call",
")",
";",
"}"
] | Rewrites object method call sites as calls to global functions that take "this" as their first
argument.
<p>Before: o.foo(a, b, c)
<p>After: foo(o, a, b, c) | [
"Rewrites",
"object",
"method",
"call",
"sites",
"as",
"calls",
"to",
"global",
"functions",
"that",
"take",
"this",
"as",
"their",
"first",
"argument",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java#L363-L388 |
24,125 | google/closure-compiler | src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java | DevirtualizePrototypeMethods.rewriteDefinition | private void rewriteDefinition(Node definitionSite, String newMethodName) {
final Node function;
final Node subtreeToRemove;
final Node nameSource;
switch (definitionSite.getToken()) {
case GETPROP:
function = definitionSite.getParent().getLastChild();
nameSource = definitionSite.getLastChild();
subtreeToRemove = NodeUtil.getEnclosingStatement(definitionSite);
break;
case STRING_KEY:
case MEMBER_FUNCTION_DEF:
function = definitionSite.getLastChild();
nameSource = definitionSite;
subtreeToRemove = definitionSite;
break;
default:
throw new IllegalArgumentException(definitionSite.toString());
}
// Define a new variable after the original declaration.
Node statement = NodeUtil.getEnclosingStatement(definitionSite);
Node newNameNode = IR.name(newMethodName).useSourceInfoIfMissingFrom(nameSource);
Node newVarNode = IR.var(newNameNode).useSourceInfoIfMissingFrom(nameSource);
statement.getParent().addChildBefore(newVarNode, statement);
// Attatch the function to the new variable.
function.detach();
newNameNode.addChildToFront(function);
// Create the `this` param.
String selfName = newMethodName + "$self";
Node paramList = function.getSecondChild();
paramList.addChildToFront(IR.name(selfName).useSourceInfoIfMissingFrom(function));
compiler.reportChangeToEnclosingScope(paramList);
// Eliminate `this`.
replaceReferencesToThis(function.getSecondChild(), selfName); // In default param values.
replaceReferencesToThis(function.getLastChild(), selfName); // In function body.
fixFunctionType(function);
// Clean up dangling AST.
NodeUtil.deleteNode(subtreeToRemove, compiler);
compiler.reportChangeToEnclosingScope(newVarNode);
} | java | private void rewriteDefinition(Node definitionSite, String newMethodName) {
final Node function;
final Node subtreeToRemove;
final Node nameSource;
switch (definitionSite.getToken()) {
case GETPROP:
function = definitionSite.getParent().getLastChild();
nameSource = definitionSite.getLastChild();
subtreeToRemove = NodeUtil.getEnclosingStatement(definitionSite);
break;
case STRING_KEY:
case MEMBER_FUNCTION_DEF:
function = definitionSite.getLastChild();
nameSource = definitionSite;
subtreeToRemove = definitionSite;
break;
default:
throw new IllegalArgumentException(definitionSite.toString());
}
// Define a new variable after the original declaration.
Node statement = NodeUtil.getEnclosingStatement(definitionSite);
Node newNameNode = IR.name(newMethodName).useSourceInfoIfMissingFrom(nameSource);
Node newVarNode = IR.var(newNameNode).useSourceInfoIfMissingFrom(nameSource);
statement.getParent().addChildBefore(newVarNode, statement);
// Attatch the function to the new variable.
function.detach();
newNameNode.addChildToFront(function);
// Create the `this` param.
String selfName = newMethodName + "$self";
Node paramList = function.getSecondChild();
paramList.addChildToFront(IR.name(selfName).useSourceInfoIfMissingFrom(function));
compiler.reportChangeToEnclosingScope(paramList);
// Eliminate `this`.
replaceReferencesToThis(function.getSecondChild(), selfName); // In default param values.
replaceReferencesToThis(function.getLastChild(), selfName); // In function body.
fixFunctionType(function);
// Clean up dangling AST.
NodeUtil.deleteNode(subtreeToRemove, compiler);
compiler.reportChangeToEnclosingScope(newVarNode);
} | [
"private",
"void",
"rewriteDefinition",
"(",
"Node",
"definitionSite",
",",
"String",
"newMethodName",
")",
"{",
"final",
"Node",
"function",
";",
"final",
"Node",
"subtreeToRemove",
";",
"final",
"Node",
"nameSource",
";",
"switch",
"(",
"definitionSite",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"GETPROP",
":",
"function",
"=",
"definitionSite",
".",
"getParent",
"(",
")",
".",
"getLastChild",
"(",
")",
";",
"nameSource",
"=",
"definitionSite",
".",
"getLastChild",
"(",
")",
";",
"subtreeToRemove",
"=",
"NodeUtil",
".",
"getEnclosingStatement",
"(",
"definitionSite",
")",
";",
"break",
";",
"case",
"STRING_KEY",
":",
"case",
"MEMBER_FUNCTION_DEF",
":",
"function",
"=",
"definitionSite",
".",
"getLastChild",
"(",
")",
";",
"nameSource",
"=",
"definitionSite",
";",
"subtreeToRemove",
"=",
"definitionSite",
";",
"break",
";",
"default",
":",
"throw",
"new",
"IllegalArgumentException",
"(",
"definitionSite",
".",
"toString",
"(",
")",
")",
";",
"}",
"// Define a new variable after the original declaration.",
"Node",
"statement",
"=",
"NodeUtil",
".",
"getEnclosingStatement",
"(",
"definitionSite",
")",
";",
"Node",
"newNameNode",
"=",
"IR",
".",
"name",
"(",
"newMethodName",
")",
".",
"useSourceInfoIfMissingFrom",
"(",
"nameSource",
")",
";",
"Node",
"newVarNode",
"=",
"IR",
".",
"var",
"(",
"newNameNode",
")",
".",
"useSourceInfoIfMissingFrom",
"(",
"nameSource",
")",
";",
"statement",
".",
"getParent",
"(",
")",
".",
"addChildBefore",
"(",
"newVarNode",
",",
"statement",
")",
";",
"// Attatch the function to the new variable.",
"function",
".",
"detach",
"(",
")",
";",
"newNameNode",
".",
"addChildToFront",
"(",
"function",
")",
";",
"// Create the `this` param.",
"String",
"selfName",
"=",
"newMethodName",
"+",
"\"$self\"",
";",
"Node",
"paramList",
"=",
"function",
".",
"getSecondChild",
"(",
")",
";",
"paramList",
".",
"addChildToFront",
"(",
"IR",
".",
"name",
"(",
"selfName",
")",
".",
"useSourceInfoIfMissingFrom",
"(",
"function",
")",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"paramList",
")",
";",
"// Eliminate `this`.",
"replaceReferencesToThis",
"(",
"function",
".",
"getSecondChild",
"(",
")",
",",
"selfName",
")",
";",
"// In default param values.",
"replaceReferencesToThis",
"(",
"function",
".",
"getLastChild",
"(",
")",
",",
"selfName",
")",
";",
"// In function body.",
"fixFunctionType",
"(",
"function",
")",
";",
"// Clean up dangling AST.",
"NodeUtil",
".",
"deleteNode",
"(",
"subtreeToRemove",
",",
"compiler",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"newVarNode",
")",
";",
"}"
] | Rewrites method definitions as global functions that take "this" as their first argument.
<p>Before: a.prototype.b = function(a, b, c) {...}
<p>After: var b = function(self, a, b, c) {...} | [
"Rewrites",
"method",
"definitions",
"as",
"global",
"functions",
"that",
"take",
"this",
"as",
"their",
"first",
"argument",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java#L397-L445 |
24,126 | google/closure-compiler | src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java | DevirtualizePrototypeMethods.fixFunctionType | private void fixFunctionType(Node functionNode) {
JSType t = functionNode.getJSType();
if (t == null) {
return;
}
FunctionType ft = t.toMaybeFunctionType();
if (ft != null) {
functionNode.setJSType(convertMethodToFunction(ft));
}
} | java | private void fixFunctionType(Node functionNode) {
JSType t = functionNode.getJSType();
if (t == null) {
return;
}
FunctionType ft = t.toMaybeFunctionType();
if (ft != null) {
functionNode.setJSType(convertMethodToFunction(ft));
}
} | [
"private",
"void",
"fixFunctionType",
"(",
"Node",
"functionNode",
")",
"{",
"JSType",
"t",
"=",
"functionNode",
".",
"getJSType",
"(",
")",
";",
"if",
"(",
"t",
"==",
"null",
")",
"{",
"return",
";",
"}",
"FunctionType",
"ft",
"=",
"t",
".",
"toMaybeFunctionType",
"(",
")",
";",
"if",
"(",
"ft",
"!=",
"null",
")",
"{",
"functionNode",
".",
"setJSType",
"(",
"convertMethodToFunction",
"(",
"ft",
")",
")",
";",
"}",
"}"
] | Creates a new type based on the original function type by
adding the original this pointer type to the beginning of the
argument type list and replacing the this pointer type with bottom. | [
"Creates",
"a",
"new",
"type",
"based",
"on",
"the",
"original",
"function",
"type",
"by",
"adding",
"the",
"original",
"this",
"pointer",
"type",
"to",
"the",
"beginning",
"of",
"the",
"argument",
"type",
"list",
"and",
"replacing",
"the",
"this",
"pointer",
"type",
"with",
"bottom",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java#L452-L461 |
24,127 | google/closure-compiler | src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java | DevirtualizePrototypeMethods.replaceReferencesToThis | private void replaceReferencesToThis(Node node, String name) {
if (node.isFunction() && !node.isArrowFunction()) {
// Functions (besides arrows) create a new binding for `this`.
return;
}
for (Node child : node.children()) {
if (child.isThis()) {
Node newName = IR.name(name).useSourceInfoFrom(child).setJSType(child.getJSType());
node.replaceChild(child, newName);
compiler.reportChangeToEnclosingScope(newName);
} else {
replaceReferencesToThis(child, name);
}
}
} | java | private void replaceReferencesToThis(Node node, String name) {
if (node.isFunction() && !node.isArrowFunction()) {
// Functions (besides arrows) create a new binding for `this`.
return;
}
for (Node child : node.children()) {
if (child.isThis()) {
Node newName = IR.name(name).useSourceInfoFrom(child).setJSType(child.getJSType());
node.replaceChild(child, newName);
compiler.reportChangeToEnclosingScope(newName);
} else {
replaceReferencesToThis(child, name);
}
}
} | [
"private",
"void",
"replaceReferencesToThis",
"(",
"Node",
"node",
",",
"String",
"name",
")",
"{",
"if",
"(",
"node",
".",
"isFunction",
"(",
")",
"&&",
"!",
"node",
".",
"isArrowFunction",
"(",
")",
")",
"{",
"// Functions (besides arrows) create a new binding for `this`.",
"return",
";",
"}",
"for",
"(",
"Node",
"child",
":",
"node",
".",
"children",
"(",
")",
")",
"{",
"if",
"(",
"child",
".",
"isThis",
"(",
")",
")",
"{",
"Node",
"newName",
"=",
"IR",
".",
"name",
"(",
"name",
")",
".",
"useSourceInfoFrom",
"(",
"child",
")",
".",
"setJSType",
"(",
"child",
".",
"getJSType",
"(",
")",
")",
";",
"node",
".",
"replaceChild",
"(",
"child",
",",
"newName",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"newName",
")",
";",
"}",
"else",
"{",
"replaceReferencesToThis",
"(",
"child",
",",
"name",
")",
";",
"}",
"}",
"}"
] | Replaces references to "this" with references to name. Do not traverse function boundaries. | [
"Replaces",
"references",
"to",
"this",
"with",
"references",
"to",
"name",
".",
"Do",
"not",
"traverse",
"function",
"boundaries",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DevirtualizePrototypeMethods.java#L475-L490 |
24,128 | google/closure-compiler | src/com/google/javascript/jscomp/TypedCodeGenerator.java | TypedCodeGenerator.getParameterJSDocName | private String getParameterJSDocName(Node paramNode, int paramIndex) {
Node nameNode = null;
if (paramNode != null) {
checkArgument(paramNode.getParent().isParamList(), paramNode);
if (paramNode.isRest()) {
// use `restParam` of `...restParam`
// restParam might still be a destructuring pattern
paramNode = paramNode.getOnlyChild();
} else if (paramNode.isDefaultValue()) {
// use `defaultParam` of `defaultParam = something`
// defaultParam might still be a destructuring pattern
paramNode = paramNode.getFirstChild();
}
if (paramNode.isName()) {
nameNode = paramNode;
} else {
checkState(paramNode.isObjectPattern() || paramNode.isArrayPattern(), paramNode);
nameNode = null; // must generate a fake name
}
}
if (nameNode == null) {
return "p" + paramIndex;
} else {
checkState(nameNode.isName(), nameNode);
return nameNode.getString();
}
} | java | private String getParameterJSDocName(Node paramNode, int paramIndex) {
Node nameNode = null;
if (paramNode != null) {
checkArgument(paramNode.getParent().isParamList(), paramNode);
if (paramNode.isRest()) {
// use `restParam` of `...restParam`
// restParam might still be a destructuring pattern
paramNode = paramNode.getOnlyChild();
} else if (paramNode.isDefaultValue()) {
// use `defaultParam` of `defaultParam = something`
// defaultParam might still be a destructuring pattern
paramNode = paramNode.getFirstChild();
}
if (paramNode.isName()) {
nameNode = paramNode;
} else {
checkState(paramNode.isObjectPattern() || paramNode.isArrayPattern(), paramNode);
nameNode = null; // must generate a fake name
}
}
if (nameNode == null) {
return "p" + paramIndex;
} else {
checkState(nameNode.isName(), nameNode);
return nameNode.getString();
}
} | [
"private",
"String",
"getParameterJSDocName",
"(",
"Node",
"paramNode",
",",
"int",
"paramIndex",
")",
"{",
"Node",
"nameNode",
"=",
"null",
";",
"if",
"(",
"paramNode",
"!=",
"null",
")",
"{",
"checkArgument",
"(",
"paramNode",
".",
"getParent",
"(",
")",
".",
"isParamList",
"(",
")",
",",
"paramNode",
")",
";",
"if",
"(",
"paramNode",
".",
"isRest",
"(",
")",
")",
"{",
"// use `restParam` of `...restParam`",
"// restParam might still be a destructuring pattern",
"paramNode",
"=",
"paramNode",
".",
"getOnlyChild",
"(",
")",
";",
"}",
"else",
"if",
"(",
"paramNode",
".",
"isDefaultValue",
"(",
")",
")",
"{",
"// use `defaultParam` of `defaultParam = something`",
"// defaultParam might still be a destructuring pattern",
"paramNode",
"=",
"paramNode",
".",
"getFirstChild",
"(",
")",
";",
"}",
"if",
"(",
"paramNode",
".",
"isName",
"(",
")",
")",
"{",
"nameNode",
"=",
"paramNode",
";",
"}",
"else",
"{",
"checkState",
"(",
"paramNode",
".",
"isObjectPattern",
"(",
")",
"||",
"paramNode",
".",
"isArrayPattern",
"(",
")",
",",
"paramNode",
")",
";",
"nameNode",
"=",
"null",
";",
"// must generate a fake name",
"}",
"}",
"if",
"(",
"nameNode",
"==",
"null",
")",
"{",
"return",
"\"p\"",
"+",
"paramIndex",
";",
"}",
"else",
"{",
"checkState",
"(",
"nameNode",
".",
"isName",
"(",
")",
",",
"nameNode",
")",
";",
"return",
"nameNode",
".",
"getString",
"(",
")",
";",
"}",
"}"
] | Return the name of the parameter to be used in JSDoc, generating one for destructuring
parameters.
@param paramNode child node of a parameter list
@param paramIndex position of child in the list
@return name to use in JSDoc | [
"Return",
"the",
"name",
"of",
"the",
"parameter",
"to",
"be",
"used",
"in",
"JSDoc",
"generating",
"one",
"for",
"destructuring",
"parameters",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedCodeGenerator.java#L308-L334 |
24,129 | google/closure-compiler | src/com/google/javascript/jscomp/TypedCodeGenerator.java | TypedCodeGenerator.appendClassAnnotations | private void appendClassAnnotations(StringBuilder sb, FunctionType funType) {
FunctionType superConstructor = funType.getInstanceType().getSuperClassConstructor();
if (superConstructor != null) {
ObjectType superInstance = superConstructor.getInstanceType();
if (!superInstance.toString().equals("Object")) {
sb.append(" * ");
appendAnnotation(sb, "extends", superInstance.toAnnotationString(Nullability.IMPLICIT));
sb.append("\n");
}
}
// Avoid duplicates, add implemented type to a set first
Set<String> interfaces = new TreeSet<>();
for (ObjectType interfaze : funType.getAncestorInterfaces()) {
interfaces.add(interfaze.toAnnotationString(Nullability.IMPLICIT));
}
for (String interfaze : interfaces) {
sb.append(" * ");
appendAnnotation(sb, "implements", interfaze);
sb.append("\n");
}
} | java | private void appendClassAnnotations(StringBuilder sb, FunctionType funType) {
FunctionType superConstructor = funType.getInstanceType().getSuperClassConstructor();
if (superConstructor != null) {
ObjectType superInstance = superConstructor.getInstanceType();
if (!superInstance.toString().equals("Object")) {
sb.append(" * ");
appendAnnotation(sb, "extends", superInstance.toAnnotationString(Nullability.IMPLICIT));
sb.append("\n");
}
}
// Avoid duplicates, add implemented type to a set first
Set<String> interfaces = new TreeSet<>();
for (ObjectType interfaze : funType.getAncestorInterfaces()) {
interfaces.add(interfaze.toAnnotationString(Nullability.IMPLICIT));
}
for (String interfaze : interfaces) {
sb.append(" * ");
appendAnnotation(sb, "implements", interfaze);
sb.append("\n");
}
} | [
"private",
"void",
"appendClassAnnotations",
"(",
"StringBuilder",
"sb",
",",
"FunctionType",
"funType",
")",
"{",
"FunctionType",
"superConstructor",
"=",
"funType",
".",
"getInstanceType",
"(",
")",
".",
"getSuperClassConstructor",
"(",
")",
";",
"if",
"(",
"superConstructor",
"!=",
"null",
")",
"{",
"ObjectType",
"superInstance",
"=",
"superConstructor",
".",
"getInstanceType",
"(",
")",
";",
"if",
"(",
"!",
"superInstance",
".",
"toString",
"(",
")",
".",
"equals",
"(",
"\"Object\"",
")",
")",
"{",
"sb",
".",
"append",
"(",
"\" * \"",
")",
";",
"appendAnnotation",
"(",
"sb",
",",
"\"extends\"",
",",
"superInstance",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"IMPLICIT",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"}",
"}",
"// Avoid duplicates, add implemented type to a set first",
"Set",
"<",
"String",
">",
"interfaces",
"=",
"new",
"TreeSet",
"<>",
"(",
")",
";",
"for",
"(",
"ObjectType",
"interfaze",
":",
"funType",
".",
"getAncestorInterfaces",
"(",
")",
")",
"{",
"interfaces",
".",
"add",
"(",
"interfaze",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"IMPLICIT",
")",
")",
";",
"}",
"for",
"(",
"String",
"interfaze",
":",
"interfaces",
")",
"{",
"sb",
".",
"append",
"(",
"\" * \"",
")",
";",
"appendAnnotation",
"(",
"sb",
",",
"\"implements\"",
",",
"interfaze",
")",
";",
"sb",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"}",
"}"
] | we should print it first, like users write it. Same for @interface and @record. | [
"we",
"should",
"print",
"it",
"first",
"like",
"users",
"write",
"it",
".",
"Same",
"for"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedCodeGenerator.java#L342-L362 |
24,130 | google/closure-compiler | src/com/google/javascript/jscomp/TypedCodeGenerator.java | TypedCodeGenerator.getParameterJSDocType | private String getParameterJSDocType(List<JSType> types, int index, int minArgs, int maxArgs) {
JSType type = types.get(index);
if (index < minArgs) {
return type.toAnnotationString(Nullability.EXPLICIT);
}
boolean isRestArgument = maxArgs == Integer.MAX_VALUE && index == types.size() - 1;
if (isRestArgument) {
return "..." + restrictByUndefined(type).toAnnotationString(Nullability.EXPLICIT);
}
return restrictByUndefined(type).toAnnotationString(Nullability.EXPLICIT) + "=";
} | java | private String getParameterJSDocType(List<JSType> types, int index, int minArgs, int maxArgs) {
JSType type = types.get(index);
if (index < minArgs) {
return type.toAnnotationString(Nullability.EXPLICIT);
}
boolean isRestArgument = maxArgs == Integer.MAX_VALUE && index == types.size() - 1;
if (isRestArgument) {
return "..." + restrictByUndefined(type).toAnnotationString(Nullability.EXPLICIT);
}
return restrictByUndefined(type).toAnnotationString(Nullability.EXPLICIT) + "=";
} | [
"private",
"String",
"getParameterJSDocType",
"(",
"List",
"<",
"JSType",
">",
"types",
",",
"int",
"index",
",",
"int",
"minArgs",
",",
"int",
"maxArgs",
")",
"{",
"JSType",
"type",
"=",
"types",
".",
"get",
"(",
"index",
")",
";",
"if",
"(",
"index",
"<",
"minArgs",
")",
"{",
"return",
"type",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"EXPLICIT",
")",
";",
"}",
"boolean",
"isRestArgument",
"=",
"maxArgs",
"==",
"Integer",
".",
"MAX_VALUE",
"&&",
"index",
"==",
"types",
".",
"size",
"(",
")",
"-",
"1",
";",
"if",
"(",
"isRestArgument",
")",
"{",
"return",
"\"...\"",
"+",
"restrictByUndefined",
"(",
"type",
")",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"EXPLICIT",
")",
";",
"}",
"return",
"restrictByUndefined",
"(",
"type",
")",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"EXPLICIT",
")",
"+",
"\"=\"",
";",
"}"
] | Creates a JSDoc-suitable String representation of the type of a parameter. | [
"Creates",
"a",
"JSDoc",
"-",
"suitable",
"String",
"representation",
"of",
"the",
"type",
"of",
"a",
"parameter",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedCodeGenerator.java#L412-L422 |
24,131 | google/closure-compiler | src/com/google/javascript/jscomp/TypedCodeGenerator.java | TypedCodeGenerator.restrictByUndefined | private JSType restrictByUndefined(JSType type) {
// If not voidable, there's nothing to do. If not nullable then the easiest
// thing is to simply remove both null and undefined. If nullable, then add
// null back into the union after removing null and undefined.
if (!type.isVoidable()) {
return type;
}
JSType restricted = type.restrictByNotNullOrUndefined();
if (type.isNullable()) {
JSType nullType = registry.getNativeType(JSTypeNative.NULL_TYPE);
return registry.createUnionType(ImmutableList.of(restricted, nullType));
}
// The bottom type cannot appear in a jsdoc
return restricted.isEmptyType() ? type : restricted;
} | java | private JSType restrictByUndefined(JSType type) {
// If not voidable, there's nothing to do. If not nullable then the easiest
// thing is to simply remove both null and undefined. If nullable, then add
// null back into the union after removing null and undefined.
if (!type.isVoidable()) {
return type;
}
JSType restricted = type.restrictByNotNullOrUndefined();
if (type.isNullable()) {
JSType nullType = registry.getNativeType(JSTypeNative.NULL_TYPE);
return registry.createUnionType(ImmutableList.of(restricted, nullType));
}
// The bottom type cannot appear in a jsdoc
return restricted.isEmptyType() ? type : restricted;
} | [
"private",
"JSType",
"restrictByUndefined",
"(",
"JSType",
"type",
")",
"{",
"// If not voidable, there's nothing to do. If not nullable then the easiest",
"// thing is to simply remove both null and undefined. If nullable, then add",
"// null back into the union after removing null and undefined.",
"if",
"(",
"!",
"type",
".",
"isVoidable",
"(",
")",
")",
"{",
"return",
"type",
";",
"}",
"JSType",
"restricted",
"=",
"type",
".",
"restrictByNotNullOrUndefined",
"(",
")",
";",
"if",
"(",
"type",
".",
"isNullable",
"(",
")",
")",
"{",
"JSType",
"nullType",
"=",
"registry",
".",
"getNativeType",
"(",
"JSTypeNative",
".",
"NULL_TYPE",
")",
";",
"return",
"registry",
".",
"createUnionType",
"(",
"ImmutableList",
".",
"of",
"(",
"restricted",
",",
"nullType",
")",
")",
";",
"}",
"// The bottom type cannot appear in a jsdoc",
"return",
"restricted",
".",
"isEmptyType",
"(",
")",
"?",
"type",
":",
"restricted",
";",
"}"
] | Removes undefined from a union type. | [
"Removes",
"undefined",
"from",
"a",
"union",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedCodeGenerator.java#L425-L439 |
24,132 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.validateClassLevelJsDoc | private void validateClassLevelJsDoc(Node n, JSDocInfo info) {
if (info != null && n.isMemberFunctionDef()
&& hasClassLevelJsDoc(info)) {
report(n, DISALLOWED_MEMBER_JSDOC);
}
} | java | private void validateClassLevelJsDoc(Node n, JSDocInfo info) {
if (info != null && n.isMemberFunctionDef()
&& hasClassLevelJsDoc(info)) {
report(n, DISALLOWED_MEMBER_JSDOC);
}
} | [
"private",
"void",
"validateClassLevelJsDoc",
"(",
"Node",
"n",
",",
"JSDocInfo",
"info",
")",
"{",
"if",
"(",
"info",
"!=",
"null",
"&&",
"n",
".",
"isMemberFunctionDef",
"(",
")",
"&&",
"hasClassLevelJsDoc",
"(",
"info",
")",
")",
"{",
"report",
"(",
"n",
",",
"DISALLOWED_MEMBER_JSDOC",
")",
";",
"}",
"}"
] | Checks that class-level annotations like @interface/@extends are not used on member functions. | [
"Checks",
"that",
"class",
"-",
"level",
"annotations",
"like"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L310-L315 |
24,133 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.validateDeprecatedJsDoc | private void validateDeprecatedJsDoc(Node n, JSDocInfo info) {
if (info != null && info.isExpose()) {
report(n, ANNOTATION_DEPRECATED, "@expose",
"Use @nocollapse or @export instead.");
}
} | java | private void validateDeprecatedJsDoc(Node n, JSDocInfo info) {
if (info != null && info.isExpose()) {
report(n, ANNOTATION_DEPRECATED, "@expose",
"Use @nocollapse or @export instead.");
}
} | [
"private",
"void",
"validateDeprecatedJsDoc",
"(",
"Node",
"n",
",",
"JSDocInfo",
"info",
")",
"{",
"if",
"(",
"info",
"!=",
"null",
"&&",
"info",
".",
"isExpose",
"(",
")",
")",
"{",
"report",
"(",
"n",
",",
"ANNOTATION_DEPRECATED",
",",
"\"@expose\"",
",",
"\"Use @nocollapse or @export instead.\"",
")",
";",
"}",
"}"
] | Checks that deprecated annotations such as @expose are not present | [
"Checks",
"that",
"deprecated",
"annotations",
"such",
"as"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L387-L392 |
24,134 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.validateNoCollapse | private void validateNoCollapse(Node n, JSDocInfo info) {
if (n.isFromExterns()) {
if (info != null && info.isNoCollapse()) {
// @nocollapse has no effect in externs
reportMisplaced(n, "nocollapse", "This JSDoc has no effect in externs.");
}
return;
}
if (!NodeUtil.isPrototypePropertyDeclaration(n.getParent())) {
return;
}
JSDocInfo jsdoc = n.getJSDocInfo();
if (jsdoc != null && jsdoc.isNoCollapse()) {
reportMisplaced(n, "nocollapse", "This JSDoc has no effect on prototype properties.");
}
} | java | private void validateNoCollapse(Node n, JSDocInfo info) {
if (n.isFromExterns()) {
if (info != null && info.isNoCollapse()) {
// @nocollapse has no effect in externs
reportMisplaced(n, "nocollapse", "This JSDoc has no effect in externs.");
}
return;
}
if (!NodeUtil.isPrototypePropertyDeclaration(n.getParent())) {
return;
}
JSDocInfo jsdoc = n.getJSDocInfo();
if (jsdoc != null && jsdoc.isNoCollapse()) {
reportMisplaced(n, "nocollapse", "This JSDoc has no effect on prototype properties.");
}
} | [
"private",
"void",
"validateNoCollapse",
"(",
"Node",
"n",
",",
"JSDocInfo",
"info",
")",
"{",
"if",
"(",
"n",
".",
"isFromExterns",
"(",
")",
")",
"{",
"if",
"(",
"info",
"!=",
"null",
"&&",
"info",
".",
"isNoCollapse",
"(",
")",
")",
"{",
"// @nocollapse has no effect in externs",
"reportMisplaced",
"(",
"n",
",",
"\"nocollapse\"",
",",
"\"This JSDoc has no effect in externs.\"",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"!",
"NodeUtil",
".",
"isPrototypePropertyDeclaration",
"(",
"n",
".",
"getParent",
"(",
")",
")",
")",
"{",
"return",
";",
"}",
"JSDocInfo",
"jsdoc",
"=",
"n",
".",
"getJSDocInfo",
"(",
")",
";",
"if",
"(",
"jsdoc",
"!=",
"null",
"&&",
"jsdoc",
".",
"isNoCollapse",
"(",
")",
")",
"{",
"reportMisplaced",
"(",
"n",
",",
"\"nocollapse\"",
",",
"\"This JSDoc has no effect on prototype properties.\"",
")",
";",
"}",
"}"
] | Warns when nocollapse annotations are present on nodes
which are not eligible for property collapsing. | [
"Warns",
"when",
"nocollapse",
"annotations",
"are",
"present",
"on",
"nodes",
"which",
"are",
"not",
"eligible",
"for",
"property",
"collapsing",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L398-L413 |
24,135 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.validateFunctionJsDoc | private void validateFunctionJsDoc(Node n, JSDocInfo info) {
if (info == null) {
return;
}
if (info.containsFunctionDeclaration() && !info.hasType() && !isJSDocOnFunctionNode(n, info)) {
// This JSDoc should be attached to a FUNCTION node, or an assignment
// with a function as the RHS, etc.
reportMisplaced(
n,
"function",
"This JSDoc is not attached to a function node. " + "Are you missing parentheses?");
}
} | java | private void validateFunctionJsDoc(Node n, JSDocInfo info) {
if (info == null) {
return;
}
if (info.containsFunctionDeclaration() && !info.hasType() && !isJSDocOnFunctionNode(n, info)) {
// This JSDoc should be attached to a FUNCTION node, or an assignment
// with a function as the RHS, etc.
reportMisplaced(
n,
"function",
"This JSDoc is not attached to a function node. " + "Are you missing parentheses?");
}
} | [
"private",
"void",
"validateFunctionJsDoc",
"(",
"Node",
"n",
",",
"JSDocInfo",
"info",
")",
"{",
"if",
"(",
"info",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"info",
".",
"containsFunctionDeclaration",
"(",
")",
"&&",
"!",
"info",
".",
"hasType",
"(",
")",
"&&",
"!",
"isJSDocOnFunctionNode",
"(",
"n",
",",
"info",
")",
")",
"{",
"// This JSDoc should be attached to a FUNCTION node, or an assignment",
"// with a function as the RHS, etc.",
"reportMisplaced",
"(",
"n",
",",
"\"function\"",
",",
"\"This JSDoc is not attached to a function node. \"",
"+",
"\"Are you missing parentheses?\"",
")",
";",
"}",
"}"
] | Checks that JSDoc intended for a function is actually attached to a
function. | [
"Checks",
"that",
"JSDoc",
"intended",
"for",
"a",
"function",
"is",
"actually",
"attached",
"to",
"a",
"function",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L419-L433 |
24,136 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.isJSDocOnFunctionNode | private boolean isJSDocOnFunctionNode(Node n, JSDocInfo info) {
switch (n.getToken()) {
case FUNCTION:
case GETTER_DEF:
case SETTER_DEF:
case MEMBER_FUNCTION_DEF:
case STRING_KEY:
case COMPUTED_PROP:
case EXPORT:
return true;
case GETELEM:
case GETPROP:
if (n.getFirstChild().isQualifiedName()) {
// assume qualified names may be function declarations
return true;
}
return false;
case VAR:
case LET:
case CONST:
case ASSIGN:
{
Node lhs = n.getFirstChild();
Node rhs = NodeUtil.getRValueOfLValue(lhs);
if (rhs != null && isClass(rhs) && !info.isConstructor()) {
return false;
}
// TODO(b/124081098): Check that the RHS of the assignment is a
// function. Note that it can be a FUNCTION node, but it can also be
// a call to goog.abstractMethod, goog.functions.constant, etc.
return true;
}
default:
return false;
}
} | java | private boolean isJSDocOnFunctionNode(Node n, JSDocInfo info) {
switch (n.getToken()) {
case FUNCTION:
case GETTER_DEF:
case SETTER_DEF:
case MEMBER_FUNCTION_DEF:
case STRING_KEY:
case COMPUTED_PROP:
case EXPORT:
return true;
case GETELEM:
case GETPROP:
if (n.getFirstChild().isQualifiedName()) {
// assume qualified names may be function declarations
return true;
}
return false;
case VAR:
case LET:
case CONST:
case ASSIGN:
{
Node lhs = n.getFirstChild();
Node rhs = NodeUtil.getRValueOfLValue(lhs);
if (rhs != null && isClass(rhs) && !info.isConstructor()) {
return false;
}
// TODO(b/124081098): Check that the RHS of the assignment is a
// function. Note that it can be a FUNCTION node, but it can also be
// a call to goog.abstractMethod, goog.functions.constant, etc.
return true;
}
default:
return false;
}
} | [
"private",
"boolean",
"isJSDocOnFunctionNode",
"(",
"Node",
"n",
",",
"JSDocInfo",
"info",
")",
"{",
"switch",
"(",
"n",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"FUNCTION",
":",
"case",
"GETTER_DEF",
":",
"case",
"SETTER_DEF",
":",
"case",
"MEMBER_FUNCTION_DEF",
":",
"case",
"STRING_KEY",
":",
"case",
"COMPUTED_PROP",
":",
"case",
"EXPORT",
":",
"return",
"true",
";",
"case",
"GETELEM",
":",
"case",
"GETPROP",
":",
"if",
"(",
"n",
".",
"getFirstChild",
"(",
")",
".",
"isQualifiedName",
"(",
")",
")",
"{",
"// assume qualified names may be function declarations",
"return",
"true",
";",
"}",
"return",
"false",
";",
"case",
"VAR",
":",
"case",
"LET",
":",
"case",
"CONST",
":",
"case",
"ASSIGN",
":",
"{",
"Node",
"lhs",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"Node",
"rhs",
"=",
"NodeUtil",
".",
"getRValueOfLValue",
"(",
"lhs",
")",
";",
"if",
"(",
"rhs",
"!=",
"null",
"&&",
"isClass",
"(",
"rhs",
")",
"&&",
"!",
"info",
".",
"isConstructor",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// TODO(b/124081098): Check that the RHS of the assignment is a",
"// function. Note that it can be a FUNCTION node, but it can also be",
"// a call to goog.abstractMethod, goog.functions.constant, etc.",
"return",
"true",
";",
"}",
"default",
":",
"return",
"false",
";",
"}",
"}"
] | Whether this node's JSDoc may apply to a function
<p>This has some false positive cases, to allow for patterns like goog.abstractMethod. | [
"Whether",
"this",
"node",
"s",
"JSDoc",
"may",
"apply",
"to",
"a",
"function"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L440-L476 |
24,137 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.isValidMsgName | private boolean isValidMsgName(Node nameNode) {
if (nameNode.isName() || nameNode.isStringKey()) {
return nameNode.getString().startsWith("MSG_");
} else if (nameNode.isQualifiedName()) {
return nameNode.getLastChild().getString().startsWith("MSG_");
} else {
return false;
}
} | java | private boolean isValidMsgName(Node nameNode) {
if (nameNode.isName() || nameNode.isStringKey()) {
return nameNode.getString().startsWith("MSG_");
} else if (nameNode.isQualifiedName()) {
return nameNode.getLastChild().getString().startsWith("MSG_");
} else {
return false;
}
} | [
"private",
"boolean",
"isValidMsgName",
"(",
"Node",
"nameNode",
")",
"{",
"if",
"(",
"nameNode",
".",
"isName",
"(",
")",
"||",
"nameNode",
".",
"isStringKey",
"(",
")",
")",
"{",
"return",
"nameNode",
".",
"getString",
"(",
")",
".",
"startsWith",
"(",
"\"MSG_\"",
")",
";",
"}",
"else",
"if",
"(",
"nameNode",
".",
"isQualifiedName",
"(",
")",
")",
"{",
"return",
"nameNode",
".",
"getLastChild",
"(",
")",
".",
"getString",
"(",
")",
".",
"startsWith",
"(",
"\"MSG_\"",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Returns whether of not the given name is valid target for the result of goog.getMsg | [
"Returns",
"whether",
"of",
"not",
"the",
"given",
"name",
"is",
"valid",
"target",
"for",
"the",
"result",
"of",
"goog",
".",
"getMsg"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L519-L527 |
24,138 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.isTypeAnnotationAllowedForName | private boolean isTypeAnnotationAllowedForName(Node n) {
checkState(n.isName(), n);
// Only allow type annotations on nodes used as an lvalue.
if (!NodeUtil.isLValue(n)) {
return false;
}
// Don't allow JSDoc on a name in an assignment. Simple names should only have JSDoc on them
// when originally declared.
Node rootTarget = NodeUtil.getRootTarget(n);
return !NodeUtil.isLhsOfAssign(rootTarget);
} | java | private boolean isTypeAnnotationAllowedForName(Node n) {
checkState(n.isName(), n);
// Only allow type annotations on nodes used as an lvalue.
if (!NodeUtil.isLValue(n)) {
return false;
}
// Don't allow JSDoc on a name in an assignment. Simple names should only have JSDoc on them
// when originally declared.
Node rootTarget = NodeUtil.getRootTarget(n);
return !NodeUtil.isLhsOfAssign(rootTarget);
} | [
"private",
"boolean",
"isTypeAnnotationAllowedForName",
"(",
"Node",
"n",
")",
"{",
"checkState",
"(",
"n",
".",
"isName",
"(",
")",
",",
"n",
")",
";",
"// Only allow type annotations on nodes used as an lvalue.",
"if",
"(",
"!",
"NodeUtil",
".",
"isLValue",
"(",
"n",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Don't allow JSDoc on a name in an assignment. Simple names should only have JSDoc on them",
"// when originally declared.",
"Node",
"rootTarget",
"=",
"NodeUtil",
".",
"getRootTarget",
"(",
"n",
")",
";",
"return",
"!",
"NodeUtil",
".",
"isLhsOfAssign",
"(",
"rootTarget",
")",
";",
"}"
] | Is it valid to have a type annotation on the given NAME node? | [
"Is",
"it",
"valid",
"to",
"have",
"a",
"type",
"annotation",
"on",
"the",
"given",
"NAME",
"node?"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L597-L607 |
24,139 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.validateImplicitCast | private void validateImplicitCast(Node n, JSDocInfo info) {
if (!inExterns && info != null && info.isImplicitCast()) {
report(n, TypeCheck.ILLEGAL_IMPLICIT_CAST);
}
} | java | private void validateImplicitCast(Node n, JSDocInfo info) {
if (!inExterns && info != null && info.isImplicitCast()) {
report(n, TypeCheck.ILLEGAL_IMPLICIT_CAST);
}
} | [
"private",
"void",
"validateImplicitCast",
"(",
"Node",
"n",
",",
"JSDocInfo",
"info",
")",
"{",
"if",
"(",
"!",
"inExterns",
"&&",
"info",
"!=",
"null",
"&&",
"info",
".",
"isImplicitCast",
"(",
")",
")",
"{",
"report",
"(",
"n",
",",
"TypeCheck",
".",
"ILLEGAL_IMPLICIT_CAST",
")",
";",
"}",
"}"
] | Checks that an @implicitCast annotation is in the externs | [
"Checks",
"that",
"an"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L685-L689 |
24,140 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.validateClosurePrimitive | private void validateClosurePrimitive(Node n, JSDocInfo info) {
if (info == null || !info.hasClosurePrimitiveId()) {
return;
}
if (!isJSDocOnFunctionNode(n, info)) {
report(n, MISPLACED_ANNOTATION, "closurePrimitive", "must be on a function node");
}
} | java | private void validateClosurePrimitive(Node n, JSDocInfo info) {
if (info == null || !info.hasClosurePrimitiveId()) {
return;
}
if (!isJSDocOnFunctionNode(n, info)) {
report(n, MISPLACED_ANNOTATION, "closurePrimitive", "must be on a function node");
}
} | [
"private",
"void",
"validateClosurePrimitive",
"(",
"Node",
"n",
",",
"JSDocInfo",
"info",
")",
"{",
"if",
"(",
"info",
"==",
"null",
"||",
"!",
"info",
".",
"hasClosurePrimitiveId",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"isJSDocOnFunctionNode",
"(",
"n",
",",
"info",
")",
")",
"{",
"report",
"(",
"n",
",",
"MISPLACED_ANNOTATION",
",",
"\"closurePrimitive\"",
",",
"\"must be on a function node\"",
")",
";",
"}",
"}"
] | Checks that a @closurePrimitive {id} is on a function | [
"Checks",
"that",
"a"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L692-L700 |
24,141 | google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.validateReturnJsDoc | private void validateReturnJsDoc(Node n, JSDocInfo info) {
if (!n.isReturn() || info == null) {
return;
}
// @type is handled in validateTypeAnnotations method.
if (info.containsDeclaration() && !info.hasType()) {
report(n, JSDOC_ON_RETURN);
}
} | java | private void validateReturnJsDoc(Node n, JSDocInfo info) {
if (!n.isReturn() || info == null) {
return;
}
// @type is handled in validateTypeAnnotations method.
if (info.containsDeclaration() && !info.hasType()) {
report(n, JSDOC_ON_RETURN);
}
} | [
"private",
"void",
"validateReturnJsDoc",
"(",
"Node",
"n",
",",
"JSDocInfo",
"info",
")",
"{",
"if",
"(",
"!",
"n",
".",
"isReturn",
"(",
")",
"||",
"info",
"==",
"null",
")",
"{",
"return",
";",
"}",
"// @type is handled in validateTypeAnnotations method.",
"if",
"(",
"info",
".",
"containsDeclaration",
"(",
")",
"&&",
"!",
"info",
".",
"hasType",
"(",
")",
")",
"{",
"report",
"(",
"n",
",",
"JSDOC_ON_RETURN",
")",
";",
"}",
"}"
] | Checks that there are no annotations on return. | [
"Checks",
"that",
"there",
"are",
"no",
"annotations",
"on",
"return",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L703-L711 |
24,142 | google/closure-compiler | src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java | DestructuringGlobalNameExtractor.addAfter | private static void addAfter(Node originalLvalue, Node newLvalue, Node newRvalue) {
Node parent = originalLvalue.getParent();
if (parent.isAssign()) {
// create `(<originalLvalue = ...>, <newLvalue = newRvalue>)`
Node newAssign = IR.assign(newLvalue, newRvalue).srcref(parent);
Node newComma = new Node(Token.COMMA, newAssign);
parent.replaceWith(newComma);
newComma.addChildToFront(parent);
return;
}
// This must have been in a var/let/const.
if (newLvalue.isDestructuringPattern()) {
newLvalue = new Node(Token.DESTRUCTURING_LHS, newLvalue, newRvalue).srcref(parent);
} else {
newLvalue.addChildToBack(newRvalue);
}
Node declaration = parent.isDestructuringLhs() ? originalLvalue.getGrandparent() : parent;
checkState(NodeUtil.isNameDeclaration(declaration), declaration);
if (NodeUtil.isStatementParent(declaration.getParent())) {
// `const {} = originalRvalue; const newLvalue = newRvalue;`
// create an entirely new statement
Node newDeclaration = new Node(declaration.getToken()).srcref(declaration);
newDeclaration.addChildToBack(newLvalue);
declaration.getParent().addChildAfter(newDeclaration, declaration);
} else {
// `const {} = originalRvalue, newLvalue = newRvalue;`
// The Normalize pass tries to ensure name declarations are always in statement blocks, but
// currently has not implemented normalization for `for (let x = 0; ...`
// so we can't add a new statement
declaration.addChildToBack(newLvalue);
}
} | java | private static void addAfter(Node originalLvalue, Node newLvalue, Node newRvalue) {
Node parent = originalLvalue.getParent();
if (parent.isAssign()) {
// create `(<originalLvalue = ...>, <newLvalue = newRvalue>)`
Node newAssign = IR.assign(newLvalue, newRvalue).srcref(parent);
Node newComma = new Node(Token.COMMA, newAssign);
parent.replaceWith(newComma);
newComma.addChildToFront(parent);
return;
}
// This must have been in a var/let/const.
if (newLvalue.isDestructuringPattern()) {
newLvalue = new Node(Token.DESTRUCTURING_LHS, newLvalue, newRvalue).srcref(parent);
} else {
newLvalue.addChildToBack(newRvalue);
}
Node declaration = parent.isDestructuringLhs() ? originalLvalue.getGrandparent() : parent;
checkState(NodeUtil.isNameDeclaration(declaration), declaration);
if (NodeUtil.isStatementParent(declaration.getParent())) {
// `const {} = originalRvalue; const newLvalue = newRvalue;`
// create an entirely new statement
Node newDeclaration = new Node(declaration.getToken()).srcref(declaration);
newDeclaration.addChildToBack(newLvalue);
declaration.getParent().addChildAfter(newDeclaration, declaration);
} else {
// `const {} = originalRvalue, newLvalue = newRvalue;`
// The Normalize pass tries to ensure name declarations are always in statement blocks, but
// currently has not implemented normalization for `for (let x = 0; ...`
// so we can't add a new statement
declaration.addChildToBack(newLvalue);
}
} | [
"private",
"static",
"void",
"addAfter",
"(",
"Node",
"originalLvalue",
",",
"Node",
"newLvalue",
",",
"Node",
"newRvalue",
")",
"{",
"Node",
"parent",
"=",
"originalLvalue",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"parent",
".",
"isAssign",
"(",
")",
")",
"{",
"// create `(<originalLvalue = ...>, <newLvalue = newRvalue>)`",
"Node",
"newAssign",
"=",
"IR",
".",
"assign",
"(",
"newLvalue",
",",
"newRvalue",
")",
".",
"srcref",
"(",
"parent",
")",
";",
"Node",
"newComma",
"=",
"new",
"Node",
"(",
"Token",
".",
"COMMA",
",",
"newAssign",
")",
";",
"parent",
".",
"replaceWith",
"(",
"newComma",
")",
";",
"newComma",
".",
"addChildToFront",
"(",
"parent",
")",
";",
"return",
";",
"}",
"// This must have been in a var/let/const.",
"if",
"(",
"newLvalue",
".",
"isDestructuringPattern",
"(",
")",
")",
"{",
"newLvalue",
"=",
"new",
"Node",
"(",
"Token",
".",
"DESTRUCTURING_LHS",
",",
"newLvalue",
",",
"newRvalue",
")",
".",
"srcref",
"(",
"parent",
")",
";",
"}",
"else",
"{",
"newLvalue",
".",
"addChildToBack",
"(",
"newRvalue",
")",
";",
"}",
"Node",
"declaration",
"=",
"parent",
".",
"isDestructuringLhs",
"(",
")",
"?",
"originalLvalue",
".",
"getGrandparent",
"(",
")",
":",
"parent",
";",
"checkState",
"(",
"NodeUtil",
".",
"isNameDeclaration",
"(",
"declaration",
")",
",",
"declaration",
")",
";",
"if",
"(",
"NodeUtil",
".",
"isStatementParent",
"(",
"declaration",
".",
"getParent",
"(",
")",
")",
")",
"{",
"// `const {} = originalRvalue; const newLvalue = newRvalue;`",
"// create an entirely new statement",
"Node",
"newDeclaration",
"=",
"new",
"Node",
"(",
"declaration",
".",
"getToken",
"(",
")",
")",
".",
"srcref",
"(",
"declaration",
")",
";",
"newDeclaration",
".",
"addChildToBack",
"(",
"newLvalue",
")",
";",
"declaration",
".",
"getParent",
"(",
")",
".",
"addChildAfter",
"(",
"newDeclaration",
",",
"declaration",
")",
";",
"}",
"else",
"{",
"// `const {} = originalRvalue, newLvalue = newRvalue;`",
"// The Normalize pass tries to ensure name declarations are always in statement blocks, but",
"// currently has not implemented normalization for `for (let x = 0; ...`",
"// so we can't add a new statement",
"declaration",
".",
"addChildToBack",
"(",
"newLvalue",
")",
";",
"}",
"}"
] | Adds the new assign or name declaration after the original assign or name declaration | [
"Adds",
"the",
"new",
"assign",
"or",
"name",
"declaration",
"after",
"the",
"original",
"assign",
"or",
"name",
"declaration"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java#L115-L146 |
24,143 | google/closure-compiler | src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java | DestructuringGlobalNameExtractor.makeNewRvalueForDestructuringKey | private static Node makeNewRvalueForDestructuringKey(
Node stringKey, Node rvalue, Set<AstChange> newNodes, Ref ref) {
if (stringKey.getOnlyChild().isDefaultValue()) {
Node defaultValue = stringKey.getFirstChild().getSecondChild().detach();
// Assume `rvalue` has no side effects since it's a qname, and we can create multiple
// references to it. This ignores getters/setters.
Node rvalueForSheq = rvalue.cloneTree();
if (newNodes != null) {
newNodes.add(new AstChange(ref.module, ref.scope, rvalueForSheq));
}
// `void 0 === rvalue ? defaultValue : rvalue`
rvalue =
IR.hook(IR.sheq(NodeUtil.newUndefinedNode(rvalue), rvalueForSheq), defaultValue, rvalue)
.srcrefTree(defaultValue);
}
return rvalue;
} | java | private static Node makeNewRvalueForDestructuringKey(
Node stringKey, Node rvalue, Set<AstChange> newNodes, Ref ref) {
if (stringKey.getOnlyChild().isDefaultValue()) {
Node defaultValue = stringKey.getFirstChild().getSecondChild().detach();
// Assume `rvalue` has no side effects since it's a qname, and we can create multiple
// references to it. This ignores getters/setters.
Node rvalueForSheq = rvalue.cloneTree();
if (newNodes != null) {
newNodes.add(new AstChange(ref.module, ref.scope, rvalueForSheq));
}
// `void 0 === rvalue ? defaultValue : rvalue`
rvalue =
IR.hook(IR.sheq(NodeUtil.newUndefinedNode(rvalue), rvalueForSheq), defaultValue, rvalue)
.srcrefTree(defaultValue);
}
return rvalue;
} | [
"private",
"static",
"Node",
"makeNewRvalueForDestructuringKey",
"(",
"Node",
"stringKey",
",",
"Node",
"rvalue",
",",
"Set",
"<",
"AstChange",
">",
"newNodes",
",",
"Ref",
"ref",
")",
"{",
"if",
"(",
"stringKey",
".",
"getOnlyChild",
"(",
")",
".",
"isDefaultValue",
"(",
")",
")",
"{",
"Node",
"defaultValue",
"=",
"stringKey",
".",
"getFirstChild",
"(",
")",
".",
"getSecondChild",
"(",
")",
".",
"detach",
"(",
")",
";",
"// Assume `rvalue` has no side effects since it's a qname, and we can create multiple",
"// references to it. This ignores getters/setters.",
"Node",
"rvalueForSheq",
"=",
"rvalue",
".",
"cloneTree",
"(",
")",
";",
"if",
"(",
"newNodes",
"!=",
"null",
")",
"{",
"newNodes",
".",
"add",
"(",
"new",
"AstChange",
"(",
"ref",
".",
"module",
",",
"ref",
".",
"scope",
",",
"rvalueForSheq",
")",
")",
";",
"}",
"// `void 0 === rvalue ? defaultValue : rvalue`",
"rvalue",
"=",
"IR",
".",
"hook",
"(",
"IR",
".",
"sheq",
"(",
"NodeUtil",
".",
"newUndefinedNode",
"(",
"rvalue",
")",
",",
"rvalueForSheq",
")",
",",
"defaultValue",
",",
"rvalue",
")",
".",
"srcrefTree",
"(",
"defaultValue",
")",
";",
"}",
"return",
"rvalue",
";",
"}"
] | Makes a default value expression from the rvalue, or otherwise just returns it
<p>e.g. for `const {x = defaultValue} = y;`, and the new rvalue `rvalue`, returns `void 0 ===
rvalue ? defaultValue : rvalue` | [
"Makes",
"a",
"default",
"value",
"expression",
"from",
"the",
"rvalue",
"or",
"otherwise",
"just",
"returns",
"it"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java#L176-L192 |
24,144 | google/closure-compiler | src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java | DestructuringGlobalNameExtractor.createNewObjectPatternFromSuccessiveKeys | private static Node createNewObjectPatternFromSuccessiveKeys(Node stringKey) {
Node newPattern = stringKey.getParent().cloneNode(); // copies the JSType
for (Node next = stringKey.getNext(); next != null; ) {
Node newKey = next;
next = newKey.getNext();
newPattern.addChildToBack(newKey.detach());
}
return newPattern;
} | java | private static Node createNewObjectPatternFromSuccessiveKeys(Node stringKey) {
Node newPattern = stringKey.getParent().cloneNode(); // copies the JSType
for (Node next = stringKey.getNext(); next != null; ) {
Node newKey = next;
next = newKey.getNext();
newPattern.addChildToBack(newKey.detach());
}
return newPattern;
} | [
"private",
"static",
"Node",
"createNewObjectPatternFromSuccessiveKeys",
"(",
"Node",
"stringKey",
")",
"{",
"Node",
"newPattern",
"=",
"stringKey",
".",
"getParent",
"(",
")",
".",
"cloneNode",
"(",
")",
";",
"// copies the JSType",
"for",
"(",
"Node",
"next",
"=",
"stringKey",
".",
"getNext",
"(",
")",
";",
"next",
"!=",
"null",
";",
")",
"{",
"Node",
"newKey",
"=",
"next",
";",
"next",
"=",
"newKey",
".",
"getNext",
"(",
")",
";",
"newPattern",
".",
"addChildToBack",
"(",
"newKey",
".",
"detach",
"(",
")",
")",
";",
"}",
"return",
"newPattern",
";",
"}"
] | Removes any keys after the given key, and adds them in order to a new object pattern | [
"Removes",
"any",
"keys",
"after",
"the",
"given",
"key",
"and",
"adds",
"them",
"in",
"order",
"to",
"a",
"new",
"object",
"pattern"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java#L195-L203 |
24,145 | google/closure-compiler | src/com/google/javascript/rhino/jstype/UnionType.java | UnionType.rebuildAlternates | private void rebuildAlternates() {
UnionTypeBuilder builder = UnionTypeBuilder.create(registry);
builder.addAlternates(alternates);
alternates = builder.getAlternates();
} | java | private void rebuildAlternates() {
UnionTypeBuilder builder = UnionTypeBuilder.create(registry);
builder.addAlternates(alternates);
alternates = builder.getAlternates();
} | [
"private",
"void",
"rebuildAlternates",
"(",
")",
"{",
"UnionTypeBuilder",
"builder",
"=",
"UnionTypeBuilder",
".",
"create",
"(",
"registry",
")",
";",
"builder",
".",
"addAlternates",
"(",
"alternates",
")",
";",
"alternates",
"=",
"builder",
".",
"getAlternates",
"(",
")",
";",
"}"
] | Use UnionTypeBuilder to rebuild the list of alternates and hashcode of the current UnionType. | [
"Use",
"UnionTypeBuilder",
"to",
"rebuild",
"the",
"list",
"of",
"alternates",
"and",
"hashcode",
"of",
"the",
"current",
"UnionType",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/UnionType.java#L107-L111 |
24,146 | google/closure-compiler | src/com/google/javascript/rhino/jstype/UnionType.java | UnionType.checkUnionEquivalenceHelper | boolean checkUnionEquivalenceHelper(UnionType that, EquivalenceMethod eqMethod, EqCache eqCache) {
List<JSType> thatAlternates = that.getAlternates();
if (eqMethod == EquivalenceMethod.IDENTITY && alternates.size() != thatAlternates.size()) {
return false;
}
for (int i = 0; i < thatAlternates.size(); i++) {
JSType thatAlternate = thatAlternates.get(i);
if (!hasAlternate(thatAlternate, eqMethod, eqCache)) {
return false;
}
}
return true;
} | java | boolean checkUnionEquivalenceHelper(UnionType that, EquivalenceMethod eqMethod, EqCache eqCache) {
List<JSType> thatAlternates = that.getAlternates();
if (eqMethod == EquivalenceMethod.IDENTITY && alternates.size() != thatAlternates.size()) {
return false;
}
for (int i = 0; i < thatAlternates.size(); i++) {
JSType thatAlternate = thatAlternates.get(i);
if (!hasAlternate(thatAlternate, eqMethod, eqCache)) {
return false;
}
}
return true;
} | [
"boolean",
"checkUnionEquivalenceHelper",
"(",
"UnionType",
"that",
",",
"EquivalenceMethod",
"eqMethod",
",",
"EqCache",
"eqCache",
")",
"{",
"List",
"<",
"JSType",
">",
"thatAlternates",
"=",
"that",
".",
"getAlternates",
"(",
")",
";",
"if",
"(",
"eqMethod",
"==",
"EquivalenceMethod",
".",
"IDENTITY",
"&&",
"alternates",
".",
"size",
"(",
")",
"!=",
"thatAlternates",
".",
"size",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"thatAlternates",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"JSType",
"thatAlternate",
"=",
"thatAlternates",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"!",
"hasAlternate",
"(",
"thatAlternate",
",",
"eqMethod",
",",
"eqCache",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Two union types are equal if, after flattening nested union types, they have the same number of
alternates and all alternates are equal. | [
"Two",
"union",
"types",
"are",
"equal",
"if",
"after",
"flattening",
"nested",
"union",
"types",
"they",
"have",
"the",
"same",
"number",
"of",
"alternates",
"and",
"all",
"alternates",
"are",
"equal",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/UnionType.java#L339-L351 |
24,147 | google/closure-compiler | src/com/google/javascript/jscomp/RewritePolyfills.java | RewritePolyfills.removeUnneededPolyfills | private void removeUnneededPolyfills(Node parent, Node runtimeEnd) {
Node node = parent.getFirstChild();
while (node != null && node != runtimeEnd) {
Node next = node.getNext();
if (NodeUtil.isExprCall(node)) {
Node call = node.getFirstChild();
Node name = call.getFirstChild();
if (name.matchesQualifiedName("$jscomp.polyfill")) {
FeatureSet nativeVersion =
FeatureSet.valueOf(name.getNext().getNext().getNext().getString());
if (languageOutIsAtLeast(nativeVersion)) {
NodeUtil.removeChild(parent, node);
}
}
}
node = next;
}
} | java | private void removeUnneededPolyfills(Node parent, Node runtimeEnd) {
Node node = parent.getFirstChild();
while (node != null && node != runtimeEnd) {
Node next = node.getNext();
if (NodeUtil.isExprCall(node)) {
Node call = node.getFirstChild();
Node name = call.getFirstChild();
if (name.matchesQualifiedName("$jscomp.polyfill")) {
FeatureSet nativeVersion =
FeatureSet.valueOf(name.getNext().getNext().getNext().getString());
if (languageOutIsAtLeast(nativeVersion)) {
NodeUtil.removeChild(parent, node);
}
}
}
node = next;
}
} | [
"private",
"void",
"removeUnneededPolyfills",
"(",
"Node",
"parent",
",",
"Node",
"runtimeEnd",
")",
"{",
"Node",
"node",
"=",
"parent",
".",
"getFirstChild",
"(",
")",
";",
"while",
"(",
"node",
"!=",
"null",
"&&",
"node",
"!=",
"runtimeEnd",
")",
"{",
"Node",
"next",
"=",
"node",
".",
"getNext",
"(",
")",
";",
"if",
"(",
"NodeUtil",
".",
"isExprCall",
"(",
"node",
")",
")",
"{",
"Node",
"call",
"=",
"node",
".",
"getFirstChild",
"(",
")",
";",
"Node",
"name",
"=",
"call",
".",
"getFirstChild",
"(",
")",
";",
"if",
"(",
"name",
".",
"matchesQualifiedName",
"(",
"\"$jscomp.polyfill\"",
")",
")",
"{",
"FeatureSet",
"nativeVersion",
"=",
"FeatureSet",
".",
"valueOf",
"(",
"name",
".",
"getNext",
"(",
")",
".",
"getNext",
"(",
")",
".",
"getNext",
"(",
")",
".",
"getString",
"(",
")",
")",
";",
"if",
"(",
"languageOutIsAtLeast",
"(",
"nativeVersion",
")",
")",
"{",
"NodeUtil",
".",
"removeChild",
"(",
"parent",
",",
"node",
")",
";",
"}",
"}",
"}",
"node",
"=",
"next",
";",
"}",
"}"
] | that already contains the library) is the same or lower than languageOut. | [
"that",
"already",
"contains",
"the",
"library",
")",
"is",
"the",
"same",
"or",
"lower",
"than",
"languageOut",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RewritePolyfills.java#L188-L205 |
24,148 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerPass.java | PolymerPass.rewritePolymer1ClassDefinition | private void rewritePolymer1ClassDefinition(Node node, Node parent, NodeTraversal traversal) {
Node grandparent = parent.getParent();
if (grandparent.isConst()) {
compiler.report(JSError.make(node, POLYMER_INVALID_DECLARATION));
return;
}
PolymerClassDefinition def = PolymerClassDefinition.extractFromCallNode(
node, compiler, globalNames);
if (def != null) {
if (def.nativeBaseElement != null) {
appendPolymerElementExterns(def);
}
PolymerClassRewriter rewriter =
new PolymerClassRewriter(
compiler,
getExtensInsertionRef(),
polymerVersion,
polymerExportPolicy,
this.propertyRenamingEnabled);
if (NodeUtil.isNameDeclaration(grandparent) || parent.isAssign()) {
rewriter.rewritePolymerCall(grandparent, def, traversal.inGlobalScope());
} else {
rewriter.rewritePolymerCall(parent, def, traversal.inGlobalScope());
}
}
} | java | private void rewritePolymer1ClassDefinition(Node node, Node parent, NodeTraversal traversal) {
Node grandparent = parent.getParent();
if (grandparent.isConst()) {
compiler.report(JSError.make(node, POLYMER_INVALID_DECLARATION));
return;
}
PolymerClassDefinition def = PolymerClassDefinition.extractFromCallNode(
node, compiler, globalNames);
if (def != null) {
if (def.nativeBaseElement != null) {
appendPolymerElementExterns(def);
}
PolymerClassRewriter rewriter =
new PolymerClassRewriter(
compiler,
getExtensInsertionRef(),
polymerVersion,
polymerExportPolicy,
this.propertyRenamingEnabled);
if (NodeUtil.isNameDeclaration(grandparent) || parent.isAssign()) {
rewriter.rewritePolymerCall(grandparent, def, traversal.inGlobalScope());
} else {
rewriter.rewritePolymerCall(parent, def, traversal.inGlobalScope());
}
}
} | [
"private",
"void",
"rewritePolymer1ClassDefinition",
"(",
"Node",
"node",
",",
"Node",
"parent",
",",
"NodeTraversal",
"traversal",
")",
"{",
"Node",
"grandparent",
"=",
"parent",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"grandparent",
".",
"isConst",
"(",
")",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"node",
",",
"POLYMER_INVALID_DECLARATION",
")",
")",
";",
"return",
";",
"}",
"PolymerClassDefinition",
"def",
"=",
"PolymerClassDefinition",
".",
"extractFromCallNode",
"(",
"node",
",",
"compiler",
",",
"globalNames",
")",
";",
"if",
"(",
"def",
"!=",
"null",
")",
"{",
"if",
"(",
"def",
".",
"nativeBaseElement",
"!=",
"null",
")",
"{",
"appendPolymerElementExterns",
"(",
"def",
")",
";",
"}",
"PolymerClassRewriter",
"rewriter",
"=",
"new",
"PolymerClassRewriter",
"(",
"compiler",
",",
"getExtensInsertionRef",
"(",
")",
",",
"polymerVersion",
",",
"polymerExportPolicy",
",",
"this",
".",
"propertyRenamingEnabled",
")",
";",
"if",
"(",
"NodeUtil",
".",
"isNameDeclaration",
"(",
"grandparent",
")",
"||",
"parent",
".",
"isAssign",
"(",
")",
")",
"{",
"rewriter",
".",
"rewritePolymerCall",
"(",
"grandparent",
",",
"def",
",",
"traversal",
".",
"inGlobalScope",
"(",
")",
")",
";",
"}",
"else",
"{",
"rewriter",
".",
"rewritePolymerCall",
"(",
"parent",
",",
"def",
",",
"traversal",
".",
"inGlobalScope",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Polymer 1.x and Polymer 2 Legacy Element Definitions | [
"Polymer",
"1",
".",
"x",
"and",
"Polymer",
"2",
"Legacy",
"Element",
"Definitions"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerPass.java#L130-L155 |
24,149 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerPass.java | PolymerPass.rewritePolymer2ClassDefinition | private void rewritePolymer2ClassDefinition(Node node, NodeTraversal traversal) {
PolymerClassDefinition def =
PolymerClassDefinition.extractFromClassNode(node, compiler, globalNames);
if (def != null) {
PolymerClassRewriter rewriter =
new PolymerClassRewriter(
compiler,
getExtensInsertionRef(),
polymerVersion,
polymerExportPolicy,
this.propertyRenamingEnabled);
rewriter.propertySinkExternInjected = propertySinkExternInjected;
rewriter.rewritePolymerClassDeclaration(node, traversal, def);
propertySinkExternInjected = rewriter.propertySinkExternInjected;
}
} | java | private void rewritePolymer2ClassDefinition(Node node, NodeTraversal traversal) {
PolymerClassDefinition def =
PolymerClassDefinition.extractFromClassNode(node, compiler, globalNames);
if (def != null) {
PolymerClassRewriter rewriter =
new PolymerClassRewriter(
compiler,
getExtensInsertionRef(),
polymerVersion,
polymerExportPolicy,
this.propertyRenamingEnabled);
rewriter.propertySinkExternInjected = propertySinkExternInjected;
rewriter.rewritePolymerClassDeclaration(node, traversal, def);
propertySinkExternInjected = rewriter.propertySinkExternInjected;
}
} | [
"private",
"void",
"rewritePolymer2ClassDefinition",
"(",
"Node",
"node",
",",
"NodeTraversal",
"traversal",
")",
"{",
"PolymerClassDefinition",
"def",
"=",
"PolymerClassDefinition",
".",
"extractFromClassNode",
"(",
"node",
",",
"compiler",
",",
"globalNames",
")",
";",
"if",
"(",
"def",
"!=",
"null",
")",
"{",
"PolymerClassRewriter",
"rewriter",
"=",
"new",
"PolymerClassRewriter",
"(",
"compiler",
",",
"getExtensInsertionRef",
"(",
")",
",",
"polymerVersion",
",",
"polymerExportPolicy",
",",
"this",
".",
"propertyRenamingEnabled",
")",
";",
"rewriter",
".",
"propertySinkExternInjected",
"=",
"propertySinkExternInjected",
";",
"rewriter",
".",
"rewritePolymerClassDeclaration",
"(",
"node",
",",
"traversal",
",",
"def",
")",
";",
"propertySinkExternInjected",
"=",
"rewriter",
".",
"propertySinkExternInjected",
";",
"}",
"}"
] | Polymer 2.x Class Nodes | [
"Polymer",
"2",
".",
"x",
"Class",
"Nodes"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerPass.java#L158-L173 |
24,150 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerPass.java | PolymerPass.appendPolymerElementExterns | private void appendPolymerElementExterns(final PolymerClassDefinition def) {
if (!nativeExternsAdded.add(def.nativeBaseElement)) {
return;
}
Node block = IR.block();
Node baseExterns = polymerElementExterns.cloneTree();
String polymerElementType = PolymerPassStaticUtils.getPolymerElementType(def);
baseExterns.getFirstChild().setString(polymerElementType);
String elementType = tagNameMap.get(def.nativeBaseElement);
if (elementType == null) {
compiler.report(JSError.make(def.descriptor, POLYMER_INVALID_EXTENDS, def.nativeBaseElement));
return;
}
JSTypeExpression elementBaseType =
new JSTypeExpression(new Node(Token.BANG, IR.string(elementType)), VIRTUAL_FILE);
JSDocInfoBuilder baseDocs = JSDocInfoBuilder.copyFrom(baseExterns.getJSDocInfo());
baseDocs.changeBaseType(elementBaseType);
baseExterns.setJSDocInfo(baseDocs.build());
block.addChildToBack(baseExterns);
for (Node baseProp : polymerElementProps) {
Node newProp = baseProp.cloneTree();
Node newPropRootName =
NodeUtil.getRootOfQualifiedName(newProp.getFirstFirstChild());
newPropRootName.setString(polymerElementType);
block.addChildToBack(newProp);
}
block.useSourceInfoIfMissingFromForTree(polymerElementExterns);
Node parent = polymerElementExterns.getParent();
Node stmts = block.removeChildren();
parent.addChildrenAfter(stmts, polymerElementExterns);
compiler.reportChangeToEnclosingScope(stmts);
} | java | private void appendPolymerElementExterns(final PolymerClassDefinition def) {
if (!nativeExternsAdded.add(def.nativeBaseElement)) {
return;
}
Node block = IR.block();
Node baseExterns = polymerElementExterns.cloneTree();
String polymerElementType = PolymerPassStaticUtils.getPolymerElementType(def);
baseExterns.getFirstChild().setString(polymerElementType);
String elementType = tagNameMap.get(def.nativeBaseElement);
if (elementType == null) {
compiler.report(JSError.make(def.descriptor, POLYMER_INVALID_EXTENDS, def.nativeBaseElement));
return;
}
JSTypeExpression elementBaseType =
new JSTypeExpression(new Node(Token.BANG, IR.string(elementType)), VIRTUAL_FILE);
JSDocInfoBuilder baseDocs = JSDocInfoBuilder.copyFrom(baseExterns.getJSDocInfo());
baseDocs.changeBaseType(elementBaseType);
baseExterns.setJSDocInfo(baseDocs.build());
block.addChildToBack(baseExterns);
for (Node baseProp : polymerElementProps) {
Node newProp = baseProp.cloneTree();
Node newPropRootName =
NodeUtil.getRootOfQualifiedName(newProp.getFirstFirstChild());
newPropRootName.setString(polymerElementType);
block.addChildToBack(newProp);
}
block.useSourceInfoIfMissingFromForTree(polymerElementExterns);
Node parent = polymerElementExterns.getParent();
Node stmts = block.removeChildren();
parent.addChildrenAfter(stmts, polymerElementExterns);
compiler.reportChangeToEnclosingScope(stmts);
} | [
"private",
"void",
"appendPolymerElementExterns",
"(",
"final",
"PolymerClassDefinition",
"def",
")",
"{",
"if",
"(",
"!",
"nativeExternsAdded",
".",
"add",
"(",
"def",
".",
"nativeBaseElement",
")",
")",
"{",
"return",
";",
"}",
"Node",
"block",
"=",
"IR",
".",
"block",
"(",
")",
";",
"Node",
"baseExterns",
"=",
"polymerElementExterns",
".",
"cloneTree",
"(",
")",
";",
"String",
"polymerElementType",
"=",
"PolymerPassStaticUtils",
".",
"getPolymerElementType",
"(",
"def",
")",
";",
"baseExterns",
".",
"getFirstChild",
"(",
")",
".",
"setString",
"(",
"polymerElementType",
")",
";",
"String",
"elementType",
"=",
"tagNameMap",
".",
"get",
"(",
"def",
".",
"nativeBaseElement",
")",
";",
"if",
"(",
"elementType",
"==",
"null",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"def",
".",
"descriptor",
",",
"POLYMER_INVALID_EXTENDS",
",",
"def",
".",
"nativeBaseElement",
")",
")",
";",
"return",
";",
"}",
"JSTypeExpression",
"elementBaseType",
"=",
"new",
"JSTypeExpression",
"(",
"new",
"Node",
"(",
"Token",
".",
"BANG",
",",
"IR",
".",
"string",
"(",
"elementType",
")",
")",
",",
"VIRTUAL_FILE",
")",
";",
"JSDocInfoBuilder",
"baseDocs",
"=",
"JSDocInfoBuilder",
".",
"copyFrom",
"(",
"baseExterns",
".",
"getJSDocInfo",
"(",
")",
")",
";",
"baseDocs",
".",
"changeBaseType",
"(",
"elementBaseType",
")",
";",
"baseExterns",
".",
"setJSDocInfo",
"(",
"baseDocs",
".",
"build",
"(",
")",
")",
";",
"block",
".",
"addChildToBack",
"(",
"baseExterns",
")",
";",
"for",
"(",
"Node",
"baseProp",
":",
"polymerElementProps",
")",
"{",
"Node",
"newProp",
"=",
"baseProp",
".",
"cloneTree",
"(",
")",
";",
"Node",
"newPropRootName",
"=",
"NodeUtil",
".",
"getRootOfQualifiedName",
"(",
"newProp",
".",
"getFirstFirstChild",
"(",
")",
")",
";",
"newPropRootName",
".",
"setString",
"(",
"polymerElementType",
")",
";",
"block",
".",
"addChildToBack",
"(",
"newProp",
")",
";",
"}",
"block",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"polymerElementExterns",
")",
";",
"Node",
"parent",
"=",
"polymerElementExterns",
".",
"getParent",
"(",
")",
";",
"Node",
"stmts",
"=",
"block",
".",
"removeChildren",
"(",
")",
";",
"parent",
".",
"addChildrenAfter",
"(",
"stmts",
",",
"polymerElementExterns",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"stmts",
")",
";",
"}"
] | Duplicates the PolymerElement externs with a different element base class if needed.
For example, if the base class is HTMLInputElement, then a class PolymerInputElement will be
added. If the element does not extend a native HTML element, this method is a no-op. | [
"Duplicates",
"the",
"PolymerElement",
"externs",
"with",
"a",
"different",
"element",
"base",
"class",
"if",
"needed",
".",
"For",
"example",
"if",
"the",
"base",
"class",
"is",
"HTMLInputElement",
"then",
"a",
"class",
"PolymerInputElement",
"will",
"be",
"added",
".",
"If",
"the",
"element",
"does",
"not",
"extend",
"a",
"native",
"HTML",
"element",
"this",
"method",
"is",
"a",
"no",
"-",
"op",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerPass.java#L192-L230 |
24,151 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | JsDocInfoParser.validTemplateTypeName | private static boolean validTemplateTypeName(String name) {
return !name.isEmpty()
&& CharMatcher.javaLetterOrDigit().or(CharMatcher.is('_')).matchesAllOf(name);
} | java | private static boolean validTemplateTypeName(String name) {
return !name.isEmpty()
&& CharMatcher.javaLetterOrDigit().or(CharMatcher.is('_')).matchesAllOf(name);
} | [
"private",
"static",
"boolean",
"validTemplateTypeName",
"(",
"String",
"name",
")",
"{",
"return",
"!",
"name",
".",
"isEmpty",
"(",
")",
"&&",
"CharMatcher",
".",
"javaLetterOrDigit",
"(",
")",
".",
"or",
"(",
"CharMatcher",
".",
"is",
"(",
"'",
"'",
")",
")",
".",
"matchesAllOf",
"(",
"name",
")",
";",
"}"
] | The types in @template annotations must contain only letters, digits, and underscores. | [
"The",
"types",
"in"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L1276-L1279 |
24,152 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | JsDocInfoParser.recordDescription | private JsDocToken recordDescription(JsDocToken token) {
// Find marker's description (if applicable).
if (jsdocBuilder.shouldParseDocumentation()) {
ExtractionInfo descriptionInfo = extractMultilineTextualBlock(token);
token = descriptionInfo.token;
} else {
token = eatTokensUntilEOL(token);
}
return token;
} | java | private JsDocToken recordDescription(JsDocToken token) {
// Find marker's description (if applicable).
if (jsdocBuilder.shouldParseDocumentation()) {
ExtractionInfo descriptionInfo = extractMultilineTextualBlock(token);
token = descriptionInfo.token;
} else {
token = eatTokensUntilEOL(token);
}
return token;
} | [
"private",
"JsDocToken",
"recordDescription",
"(",
"JsDocToken",
"token",
")",
"{",
"// Find marker's description (if applicable).",
"if",
"(",
"jsdocBuilder",
".",
"shouldParseDocumentation",
"(",
")",
")",
"{",
"ExtractionInfo",
"descriptionInfo",
"=",
"extractMultilineTextualBlock",
"(",
"token",
")",
";",
"token",
"=",
"descriptionInfo",
".",
"token",
";",
"}",
"else",
"{",
"token",
"=",
"eatTokensUntilEOL",
"(",
"token",
")",
";",
"}",
"return",
"token",
";",
"}"
] | Records a marker's description if there is one available and record it in
the current marker. | [
"Records",
"a",
"marker",
"s",
"description",
"if",
"there",
"is",
"one",
"available",
"and",
"record",
"it",
"in",
"the",
"current",
"marker",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L1285-L1294 |
24,153 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | JsDocInfoParser.parseAndRecordTypeNode | private Node parseAndRecordTypeNode(
JsDocToken token,
int lineno,
int startCharno,
boolean matchingLC,
boolean onlyParseSimpleNames) {
Node typeNode;
if (onlyParseSimpleNames) {
typeNode = parseTypeNameAnnotation(token);
} else {
typeNode = parseTypeExpressionAnnotation(token);
}
recordTypeNode(lineno, startCharno, typeNode, matchingLC);
return typeNode;
} | java | private Node parseAndRecordTypeNode(
JsDocToken token,
int lineno,
int startCharno,
boolean matchingLC,
boolean onlyParseSimpleNames) {
Node typeNode;
if (onlyParseSimpleNames) {
typeNode = parseTypeNameAnnotation(token);
} else {
typeNode = parseTypeExpressionAnnotation(token);
}
recordTypeNode(lineno, startCharno, typeNode, matchingLC);
return typeNode;
} | [
"private",
"Node",
"parseAndRecordTypeNode",
"(",
"JsDocToken",
"token",
",",
"int",
"lineno",
",",
"int",
"startCharno",
",",
"boolean",
"matchingLC",
",",
"boolean",
"onlyParseSimpleNames",
")",
"{",
"Node",
"typeNode",
";",
"if",
"(",
"onlyParseSimpleNames",
")",
"{",
"typeNode",
"=",
"parseTypeNameAnnotation",
"(",
"token",
")",
";",
"}",
"else",
"{",
"typeNode",
"=",
"parseTypeExpressionAnnotation",
"(",
"token",
")",
";",
"}",
"recordTypeNode",
"(",
"lineno",
",",
"startCharno",
",",
"typeNode",
",",
"matchingLC",
")",
";",
"return",
"typeNode",
";",
"}"
] | Looks for a parameter type expression at the current token and if found, returns it. Note that
this method consumes input.
@param token The current token.
@param lineno The line of the type expression.
@param startCharno The starting character position of the type expression.
@param matchingLC Whether the type expression starts with a "{".
@param onlyParseSimpleNames If true, only simple type names are parsed (via a call to
parseTypeNameAnnotation instead of parseTypeExpressionAnnotation).
@return The type expression found or null if none. | [
"Looks",
"for",
"a",
"parameter",
"type",
"expression",
"at",
"the",
"current",
"token",
"and",
"if",
"found",
"returns",
"it",
".",
"Note",
"that",
"this",
"method",
"consumes",
"input",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L1513-L1529 |
24,154 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | JsDocInfoParser.extractSingleLineBlock | private ExtractionInfo extractSingleLineBlock() {
// Get the current starting point.
stream.update();
int lineno = stream.getLineno();
int charno = stream.getCharno() + 1;
String line = getRemainingJSDocLine().trim();
// Record the textual description.
if (line.length() > 0) {
jsdocBuilder.markText(line, lineno, charno, lineno,
charno + line.length());
}
return new ExtractionInfo(line, next());
} | java | private ExtractionInfo extractSingleLineBlock() {
// Get the current starting point.
stream.update();
int lineno = stream.getLineno();
int charno = stream.getCharno() + 1;
String line = getRemainingJSDocLine().trim();
// Record the textual description.
if (line.length() > 0) {
jsdocBuilder.markText(line, lineno, charno, lineno,
charno + line.length());
}
return new ExtractionInfo(line, next());
} | [
"private",
"ExtractionInfo",
"extractSingleLineBlock",
"(",
")",
"{",
"// Get the current starting point.",
"stream",
".",
"update",
"(",
")",
";",
"int",
"lineno",
"=",
"stream",
".",
"getLineno",
"(",
")",
";",
"int",
"charno",
"=",
"stream",
".",
"getCharno",
"(",
")",
"+",
"1",
";",
"String",
"line",
"=",
"getRemainingJSDocLine",
"(",
")",
".",
"trim",
"(",
")",
";",
"// Record the textual description.",
"if",
"(",
"line",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"jsdocBuilder",
".",
"markText",
"(",
"line",
",",
"lineno",
",",
"charno",
",",
"lineno",
",",
"charno",
"+",
"line",
".",
"length",
"(",
")",
")",
";",
"}",
"return",
"new",
"ExtractionInfo",
"(",
"line",
",",
"next",
"(",
")",
")",
";",
"}"
] | Extracts the text found on the current line starting at token. Note that
token = token.info; should be called after this method is used to update
the token properly in the parser.
@return The extraction information. | [
"Extracts",
"the",
"text",
"found",
"on",
"the",
"current",
"line",
"starting",
"at",
"token",
".",
"Note",
"that",
"token",
"=",
"token",
".",
"info",
";",
"should",
"be",
"called",
"after",
"this",
"method",
"is",
"used",
"to",
"update",
"the",
"token",
"properly",
"in",
"the",
"parser",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L1679-L1695 |
24,155 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | JsDocInfoParser.extractMultilineComment | private ExtractionInfo extractMultilineComment(
JsDocToken token, WhitespaceOption option, boolean isMarker, boolean includeAnnotations) {
StringBuilder builder = new StringBuilder();
int startLineno = -1;
int startCharno = -1;
if (isMarker) {
stream.update();
startLineno = stream.getLineno();
startCharno = stream.getCharno() + 1;
String line = getRemainingJSDocLine();
if (option != WhitespaceOption.PRESERVE) {
line = line.trim();
}
builder.append(line);
state = State.SEARCHING_ANNOTATION;
token = next();
}
boolean ignoreStar = false;
// Track the start of the line to count whitespace that
// the tokenizer skipped. Because this case is rare, it's easier
// to do this here than in the tokenizer.
int lineStartChar = -1;
do {
switch (token) {
case STAR:
if (ignoreStar) {
// Mark the position after the star as the new start of the line.
lineStartChar = stream.getCharno() + 1;
ignoreStar = false;
} else {
// The star is part of the comment.
padLine(builder, lineStartChar, option);
lineStartChar = -1;
builder.append('*');
}
token = next();
while (token == JsDocToken.STAR) {
if (lineStartChar != -1) {
padLine(builder, lineStartChar, option);
lineStartChar = -1;
}
builder.append('*');
token = next();
}
continue;
case EOL:
if (option != WhitespaceOption.SINGLE_LINE) {
builder.append('\n');
}
ignoreStar = true;
lineStartChar = 0;
token = next();
continue;
default:
ignoreStar = false;
state = State.SEARCHING_ANNOTATION;
boolean isEOC = token == JsDocToken.EOC;
if (!isEOC) {
padLine(builder, lineStartChar, option);
lineStartChar = -1;
}
if (token == JsDocToken.EOC ||
token == JsDocToken.EOF ||
// When we're capturing a license block, annotations
// in the block are OK.
(token == JsDocToken.ANNOTATION && !includeAnnotations)) {
String multilineText = builder.toString();
if (option != WhitespaceOption.PRESERVE) {
multilineText = multilineText.trim();
}
if (isMarker && !multilineText.isEmpty()) {
int endLineno = stream.getLineno();
int endCharno = stream.getCharno();
jsdocBuilder.markText(multilineText, startLineno, startCharno,
endLineno, endCharno);
}
return new ExtractionInfo(multilineText, token);
}
builder.append(toString(token));
String line = getRemainingJSDocLine();
if (option != WhitespaceOption.PRESERVE) {
line = trimEnd(line);
}
builder.append(line);
token = next();
}
} while (true);
} | java | private ExtractionInfo extractMultilineComment(
JsDocToken token, WhitespaceOption option, boolean isMarker, boolean includeAnnotations) {
StringBuilder builder = new StringBuilder();
int startLineno = -1;
int startCharno = -1;
if (isMarker) {
stream.update();
startLineno = stream.getLineno();
startCharno = stream.getCharno() + 1;
String line = getRemainingJSDocLine();
if (option != WhitespaceOption.PRESERVE) {
line = line.trim();
}
builder.append(line);
state = State.SEARCHING_ANNOTATION;
token = next();
}
boolean ignoreStar = false;
// Track the start of the line to count whitespace that
// the tokenizer skipped. Because this case is rare, it's easier
// to do this here than in the tokenizer.
int lineStartChar = -1;
do {
switch (token) {
case STAR:
if (ignoreStar) {
// Mark the position after the star as the new start of the line.
lineStartChar = stream.getCharno() + 1;
ignoreStar = false;
} else {
// The star is part of the comment.
padLine(builder, lineStartChar, option);
lineStartChar = -1;
builder.append('*');
}
token = next();
while (token == JsDocToken.STAR) {
if (lineStartChar != -1) {
padLine(builder, lineStartChar, option);
lineStartChar = -1;
}
builder.append('*');
token = next();
}
continue;
case EOL:
if (option != WhitespaceOption.SINGLE_LINE) {
builder.append('\n');
}
ignoreStar = true;
lineStartChar = 0;
token = next();
continue;
default:
ignoreStar = false;
state = State.SEARCHING_ANNOTATION;
boolean isEOC = token == JsDocToken.EOC;
if (!isEOC) {
padLine(builder, lineStartChar, option);
lineStartChar = -1;
}
if (token == JsDocToken.EOC ||
token == JsDocToken.EOF ||
// When we're capturing a license block, annotations
// in the block are OK.
(token == JsDocToken.ANNOTATION && !includeAnnotations)) {
String multilineText = builder.toString();
if (option != WhitespaceOption.PRESERVE) {
multilineText = multilineText.trim();
}
if (isMarker && !multilineText.isEmpty()) {
int endLineno = stream.getLineno();
int endCharno = stream.getCharno();
jsdocBuilder.markText(multilineText, startLineno, startCharno,
endLineno, endCharno);
}
return new ExtractionInfo(multilineText, token);
}
builder.append(toString(token));
String line = getRemainingJSDocLine();
if (option != WhitespaceOption.PRESERVE) {
line = trimEnd(line);
}
builder.append(line);
token = next();
}
} while (true);
} | [
"private",
"ExtractionInfo",
"extractMultilineComment",
"(",
"JsDocToken",
"token",
",",
"WhitespaceOption",
"option",
",",
"boolean",
"isMarker",
",",
"boolean",
"includeAnnotations",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"int",
"startLineno",
"=",
"-",
"1",
";",
"int",
"startCharno",
"=",
"-",
"1",
";",
"if",
"(",
"isMarker",
")",
"{",
"stream",
".",
"update",
"(",
")",
";",
"startLineno",
"=",
"stream",
".",
"getLineno",
"(",
")",
";",
"startCharno",
"=",
"stream",
".",
"getCharno",
"(",
")",
"+",
"1",
";",
"String",
"line",
"=",
"getRemainingJSDocLine",
"(",
")",
";",
"if",
"(",
"option",
"!=",
"WhitespaceOption",
".",
"PRESERVE",
")",
"{",
"line",
"=",
"line",
".",
"trim",
"(",
")",
";",
"}",
"builder",
".",
"append",
"(",
"line",
")",
";",
"state",
"=",
"State",
".",
"SEARCHING_ANNOTATION",
";",
"token",
"=",
"next",
"(",
")",
";",
"}",
"boolean",
"ignoreStar",
"=",
"false",
";",
"// Track the start of the line to count whitespace that",
"// the tokenizer skipped. Because this case is rare, it's easier",
"// to do this here than in the tokenizer.",
"int",
"lineStartChar",
"=",
"-",
"1",
";",
"do",
"{",
"switch",
"(",
"token",
")",
"{",
"case",
"STAR",
":",
"if",
"(",
"ignoreStar",
")",
"{",
"// Mark the position after the star as the new start of the line.",
"lineStartChar",
"=",
"stream",
".",
"getCharno",
"(",
")",
"+",
"1",
";",
"ignoreStar",
"=",
"false",
";",
"}",
"else",
"{",
"// The star is part of the comment.",
"padLine",
"(",
"builder",
",",
"lineStartChar",
",",
"option",
")",
";",
"lineStartChar",
"=",
"-",
"1",
";",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"token",
"=",
"next",
"(",
")",
";",
"while",
"(",
"token",
"==",
"JsDocToken",
".",
"STAR",
")",
"{",
"if",
"(",
"lineStartChar",
"!=",
"-",
"1",
")",
"{",
"padLine",
"(",
"builder",
",",
"lineStartChar",
",",
"option",
")",
";",
"lineStartChar",
"=",
"-",
"1",
";",
"}",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"token",
"=",
"next",
"(",
")",
";",
"}",
"continue",
";",
"case",
"EOL",
":",
"if",
"(",
"option",
"!=",
"WhitespaceOption",
".",
"SINGLE_LINE",
")",
"{",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"ignoreStar",
"=",
"true",
";",
"lineStartChar",
"=",
"0",
";",
"token",
"=",
"next",
"(",
")",
";",
"continue",
";",
"default",
":",
"ignoreStar",
"=",
"false",
";",
"state",
"=",
"State",
".",
"SEARCHING_ANNOTATION",
";",
"boolean",
"isEOC",
"=",
"token",
"==",
"JsDocToken",
".",
"EOC",
";",
"if",
"(",
"!",
"isEOC",
")",
"{",
"padLine",
"(",
"builder",
",",
"lineStartChar",
",",
"option",
")",
";",
"lineStartChar",
"=",
"-",
"1",
";",
"}",
"if",
"(",
"token",
"==",
"JsDocToken",
".",
"EOC",
"||",
"token",
"==",
"JsDocToken",
".",
"EOF",
"||",
"// When we're capturing a license block, annotations",
"// in the block are OK.",
"(",
"token",
"==",
"JsDocToken",
".",
"ANNOTATION",
"&&",
"!",
"includeAnnotations",
")",
")",
"{",
"String",
"multilineText",
"=",
"builder",
".",
"toString",
"(",
")",
";",
"if",
"(",
"option",
"!=",
"WhitespaceOption",
".",
"PRESERVE",
")",
"{",
"multilineText",
"=",
"multilineText",
".",
"trim",
"(",
")",
";",
"}",
"if",
"(",
"isMarker",
"&&",
"!",
"multilineText",
".",
"isEmpty",
"(",
")",
")",
"{",
"int",
"endLineno",
"=",
"stream",
".",
"getLineno",
"(",
")",
";",
"int",
"endCharno",
"=",
"stream",
".",
"getCharno",
"(",
")",
";",
"jsdocBuilder",
".",
"markText",
"(",
"multilineText",
",",
"startLineno",
",",
"startCharno",
",",
"endLineno",
",",
"endCharno",
")",
";",
"}",
"return",
"new",
"ExtractionInfo",
"(",
"multilineText",
",",
"token",
")",
";",
"}",
"builder",
".",
"append",
"(",
"toString",
"(",
"token",
")",
")",
";",
"String",
"line",
"=",
"getRemainingJSDocLine",
"(",
")",
";",
"if",
"(",
"option",
"!=",
"WhitespaceOption",
".",
"PRESERVE",
")",
"{",
"line",
"=",
"trimEnd",
"(",
"line",
")",
";",
"}",
"builder",
".",
"append",
"(",
"line",
")",
";",
"token",
"=",
"next",
"(",
")",
";",
"}",
"}",
"while",
"(",
"true",
")",
";",
"}"
] | Extracts text from the stream until the end of the comment, end of the
file, or an annotation token is encountered. If the text is being
extracted for a JSDoc marker, the first line in the stream will always be
included in the extract text.
@param token The starting token.
@param option How to handle whitespace.
@param isMarker Whether the extracted text is for a JSDoc marker or a
block comment.
@param includeAnnotations Whether the extracted text may include
annotations. If set to false, text extraction will stop on the first
encountered annotation token.
@return The extraction information. | [
"Extracts",
"text",
"from",
"the",
"stream",
"until",
"the",
"end",
"of",
"the",
"comment",
"end",
"of",
"the",
"file",
"or",
"an",
"annotation",
"token",
"is",
"encountered",
".",
"If",
"the",
"text",
"is",
"being",
"extracted",
"for",
"a",
"JSDoc",
"marker",
"the",
"first",
"line",
"in",
"the",
"stream",
"will",
"always",
"be",
"included",
"in",
"the",
"extract",
"text",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L1773-L1880 |
24,156 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | JsDocInfoParser.parseParametersType | private Node parseParametersType(JsDocToken token) {
Node paramsType = newNode(Token.PARAM_LIST);
boolean isVarArgs = false;
Node paramType = null;
if (token != JsDocToken.RIGHT_PAREN) {
do {
if (paramType != null) {
// skip past the comma
next();
skipEOLs();
token = next();
}
if (token == JsDocToken.ELLIPSIS) {
// In the latest ES4 proposal, there are no type constraints allowed
// on variable arguments. We support the old syntax for backwards
// compatibility, but we should gradually tear it out.
skipEOLs();
if (match(JsDocToken.RIGHT_PAREN)) {
paramType = newNode(Token.ELLIPSIS);
} else {
skipEOLs();
paramType = wrapNode(Token.ELLIPSIS, parseTypeExpression(next()));
skipEOLs();
}
isVarArgs = true;
} else {
paramType = parseTypeExpression(token);
if (match(JsDocToken.EQUALS)) {
skipEOLs();
next();
paramType = wrapNode(Token.EQUALS, paramType);
}
}
if (paramType == null) {
return null;
}
paramsType.addChildToBack(paramType);
if (isVarArgs) {
break;
}
} while (match(JsDocToken.COMMA));
}
if (isVarArgs && match(JsDocToken.COMMA)) {
return reportTypeSyntaxWarning("msg.jsdoc.function.varargs");
}
// The right paren will be checked by parseFunctionType
return paramsType;
} | java | private Node parseParametersType(JsDocToken token) {
Node paramsType = newNode(Token.PARAM_LIST);
boolean isVarArgs = false;
Node paramType = null;
if (token != JsDocToken.RIGHT_PAREN) {
do {
if (paramType != null) {
// skip past the comma
next();
skipEOLs();
token = next();
}
if (token == JsDocToken.ELLIPSIS) {
// In the latest ES4 proposal, there are no type constraints allowed
// on variable arguments. We support the old syntax for backwards
// compatibility, but we should gradually tear it out.
skipEOLs();
if (match(JsDocToken.RIGHT_PAREN)) {
paramType = newNode(Token.ELLIPSIS);
} else {
skipEOLs();
paramType = wrapNode(Token.ELLIPSIS, parseTypeExpression(next()));
skipEOLs();
}
isVarArgs = true;
} else {
paramType = parseTypeExpression(token);
if (match(JsDocToken.EQUALS)) {
skipEOLs();
next();
paramType = wrapNode(Token.EQUALS, paramType);
}
}
if (paramType == null) {
return null;
}
paramsType.addChildToBack(paramType);
if (isVarArgs) {
break;
}
} while (match(JsDocToken.COMMA));
}
if (isVarArgs && match(JsDocToken.COMMA)) {
return reportTypeSyntaxWarning("msg.jsdoc.function.varargs");
}
// The right paren will be checked by parseFunctionType
return paramsType;
} | [
"private",
"Node",
"parseParametersType",
"(",
"JsDocToken",
"token",
")",
"{",
"Node",
"paramsType",
"=",
"newNode",
"(",
"Token",
".",
"PARAM_LIST",
")",
";",
"boolean",
"isVarArgs",
"=",
"false",
";",
"Node",
"paramType",
"=",
"null",
";",
"if",
"(",
"token",
"!=",
"JsDocToken",
".",
"RIGHT_PAREN",
")",
"{",
"do",
"{",
"if",
"(",
"paramType",
"!=",
"null",
")",
"{",
"// skip past the comma",
"next",
"(",
")",
";",
"skipEOLs",
"(",
")",
";",
"token",
"=",
"next",
"(",
")",
";",
"}",
"if",
"(",
"token",
"==",
"JsDocToken",
".",
"ELLIPSIS",
")",
"{",
"// In the latest ES4 proposal, there are no type constraints allowed",
"// on variable arguments. We support the old syntax for backwards",
"// compatibility, but we should gradually tear it out.",
"skipEOLs",
"(",
")",
";",
"if",
"(",
"match",
"(",
"JsDocToken",
".",
"RIGHT_PAREN",
")",
")",
"{",
"paramType",
"=",
"newNode",
"(",
"Token",
".",
"ELLIPSIS",
")",
";",
"}",
"else",
"{",
"skipEOLs",
"(",
")",
";",
"paramType",
"=",
"wrapNode",
"(",
"Token",
".",
"ELLIPSIS",
",",
"parseTypeExpression",
"(",
"next",
"(",
")",
")",
")",
";",
"skipEOLs",
"(",
")",
";",
"}",
"isVarArgs",
"=",
"true",
";",
"}",
"else",
"{",
"paramType",
"=",
"parseTypeExpression",
"(",
"token",
")",
";",
"if",
"(",
"match",
"(",
"JsDocToken",
".",
"EQUALS",
")",
")",
"{",
"skipEOLs",
"(",
")",
";",
"next",
"(",
")",
";",
"paramType",
"=",
"wrapNode",
"(",
"Token",
".",
"EQUALS",
",",
"paramType",
")",
";",
"}",
"}",
"if",
"(",
"paramType",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"paramsType",
".",
"addChildToBack",
"(",
"paramType",
")",
";",
"if",
"(",
"isVarArgs",
")",
"{",
"break",
";",
"}",
"}",
"while",
"(",
"match",
"(",
"JsDocToken",
".",
"COMMA",
")",
")",
";",
"}",
"if",
"(",
"isVarArgs",
"&&",
"match",
"(",
"JsDocToken",
".",
"COMMA",
")",
")",
"{",
"return",
"reportTypeSyntaxWarning",
"(",
"\"msg.jsdoc.function.varargs\"",
")",
";",
"}",
"// The right paren will be checked by parseFunctionType",
"return",
"paramsType",
";",
"}"
] | order-checking in two places, we just do all of it in type resolution. | [
"order",
"-",
"checking",
"in",
"two",
"places",
"we",
"just",
"do",
"all",
"of",
"it",
"in",
"type",
"resolution",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L2371-L2424 |
24,157 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | JsDocInfoParser.parseUnionTypeWithAlternate | private Node parseUnionTypeWithAlternate(JsDocToken token, Node alternate) {
Node union = newNode(Token.PIPE);
if (alternate != null) {
union.addChildToBack(alternate);
}
Node expr = null;
do {
if (expr != null) {
skipEOLs();
token = next();
checkState(token == JsDocToken.PIPE);
skipEOLs();
token = next();
}
expr = parseTypeExpression(token);
if (expr == null) {
return null;
}
union.addChildToBack(expr);
} while (match(JsDocToken.PIPE));
if (alternate == null) {
skipEOLs();
if (!match(JsDocToken.RIGHT_PAREN)) {
return reportTypeSyntaxWarning("msg.jsdoc.missing.rp");
}
next();
}
if (union.hasOneChild()) {
Node firstChild = union.getFirstChild();
union.removeChild(firstChild);
return firstChild;
}
return union;
} | java | private Node parseUnionTypeWithAlternate(JsDocToken token, Node alternate) {
Node union = newNode(Token.PIPE);
if (alternate != null) {
union.addChildToBack(alternate);
}
Node expr = null;
do {
if (expr != null) {
skipEOLs();
token = next();
checkState(token == JsDocToken.PIPE);
skipEOLs();
token = next();
}
expr = parseTypeExpression(token);
if (expr == null) {
return null;
}
union.addChildToBack(expr);
} while (match(JsDocToken.PIPE));
if (alternate == null) {
skipEOLs();
if (!match(JsDocToken.RIGHT_PAREN)) {
return reportTypeSyntaxWarning("msg.jsdoc.missing.rp");
}
next();
}
if (union.hasOneChild()) {
Node firstChild = union.getFirstChild();
union.removeChild(firstChild);
return firstChild;
}
return union;
} | [
"private",
"Node",
"parseUnionTypeWithAlternate",
"(",
"JsDocToken",
"token",
",",
"Node",
"alternate",
")",
"{",
"Node",
"union",
"=",
"newNode",
"(",
"Token",
".",
"PIPE",
")",
";",
"if",
"(",
"alternate",
"!=",
"null",
")",
"{",
"union",
".",
"addChildToBack",
"(",
"alternate",
")",
";",
"}",
"Node",
"expr",
"=",
"null",
";",
"do",
"{",
"if",
"(",
"expr",
"!=",
"null",
")",
"{",
"skipEOLs",
"(",
")",
";",
"token",
"=",
"next",
"(",
")",
";",
"checkState",
"(",
"token",
"==",
"JsDocToken",
".",
"PIPE",
")",
";",
"skipEOLs",
"(",
")",
";",
"token",
"=",
"next",
"(",
")",
";",
"}",
"expr",
"=",
"parseTypeExpression",
"(",
"token",
")",
";",
"if",
"(",
"expr",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"union",
".",
"addChildToBack",
"(",
"expr",
")",
";",
"}",
"while",
"(",
"match",
"(",
"JsDocToken",
".",
"PIPE",
")",
")",
";",
"if",
"(",
"alternate",
"==",
"null",
")",
"{",
"skipEOLs",
"(",
")",
";",
"if",
"(",
"!",
"match",
"(",
"JsDocToken",
".",
"RIGHT_PAREN",
")",
")",
"{",
"return",
"reportTypeSyntaxWarning",
"(",
"\"msg.jsdoc.missing.rp\"",
")",
";",
"}",
"next",
"(",
")",
";",
"}",
"if",
"(",
"union",
".",
"hasOneChild",
"(",
")",
")",
"{",
"Node",
"firstChild",
"=",
"union",
".",
"getFirstChild",
"(",
")",
";",
"union",
".",
"removeChild",
"(",
"firstChild",
")",
";",
"return",
"firstChild",
";",
"}",
"return",
"union",
";",
"}"
] | Create a new union type, with an alternate that has already been
parsed. The alternate may be null. | [
"Create",
"a",
"new",
"union",
"type",
"with",
"an",
"alternate",
"that",
"has",
"already",
"been",
"parsed",
".",
"The",
"alternate",
"may",
"be",
"null",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L2459-L2496 |
24,158 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | JsDocInfoParser.match | private boolean match(JsDocToken token1, JsDocToken token2) {
unreadToken = next();
return unreadToken == token1 || unreadToken == token2;
} | java | private boolean match(JsDocToken token1, JsDocToken token2) {
unreadToken = next();
return unreadToken == token1 || unreadToken == token2;
} | [
"private",
"boolean",
"match",
"(",
"JsDocToken",
"token1",
",",
"JsDocToken",
"token2",
")",
"{",
"unreadToken",
"=",
"next",
"(",
")",
";",
"return",
"unreadToken",
"==",
"token1",
"||",
"unreadToken",
"==",
"token2",
";",
"}"
] | Tests that the next symbol of the token stream matches one of the specified
tokens. | [
"Tests",
"that",
"the",
"next",
"symbol",
"of",
"the",
"token",
"stream",
"matches",
"one",
"of",
"the",
"specified",
"tokens",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L2712-L2715 |
24,159 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | JsDocInfoParser.lookAheadFor | private boolean lookAheadFor(char expect) {
boolean matched = false;
int c;
while (true) {
c = stream.getChar();
if (c == ' ') {
continue;
} else if (c == expect) {
matched = true;
break;
} else {
break;
}
}
stream.ungetChar(c);
return matched;
} | java | private boolean lookAheadFor(char expect) {
boolean matched = false;
int c;
while (true) {
c = stream.getChar();
if (c == ' ') {
continue;
} else if (c == expect) {
matched = true;
break;
} else {
break;
}
}
stream.ungetChar(c);
return matched;
} | [
"private",
"boolean",
"lookAheadFor",
"(",
"char",
"expect",
")",
"{",
"boolean",
"matched",
"=",
"false",
";",
"int",
"c",
";",
"while",
"(",
"true",
")",
"{",
"c",
"=",
"stream",
".",
"getChar",
"(",
")",
";",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"continue",
";",
"}",
"else",
"if",
"(",
"c",
"==",
"expect",
")",
"{",
"matched",
"=",
"true",
";",
"break",
";",
"}",
"else",
"{",
"break",
";",
"}",
"}",
"stream",
".",
"ungetChar",
"(",
"c",
")",
";",
"return",
"matched",
";",
"}"
] | Look ahead by advancing the character stream.
Does not modify the token stream.
@return Whether we found the char. | [
"Look",
"ahead",
"by",
"advancing",
"the",
"character",
"stream",
".",
"Does",
"not",
"modify",
"the",
"token",
"stream",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L2800-L2816 |
24,160 | google/closure-compiler | src/com/google/javascript/jscomp/TypeTransformation.java | TypeTransformation.getCallParams | private ImmutableList<Node> getCallParams(Node n) {
Preconditions.checkArgument(n.isCall(), "Expected a call node, found %s", n);
ImmutableList.Builder<Node> builder = new ImmutableList.Builder<>();
for (int i = 0; i < getCallParamCount(n); i++) {
builder.add(getCallArgument(n, i));
}
return builder.build();
} | java | private ImmutableList<Node> getCallParams(Node n) {
Preconditions.checkArgument(n.isCall(), "Expected a call node, found %s", n);
ImmutableList.Builder<Node> builder = new ImmutableList.Builder<>();
for (int i = 0; i < getCallParamCount(n); i++) {
builder.add(getCallArgument(n, i));
}
return builder.build();
} | [
"private",
"ImmutableList",
"<",
"Node",
">",
"getCallParams",
"(",
"Node",
"n",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"n",
".",
"isCall",
"(",
")",
",",
"\"Expected a call node, found %s\"",
",",
"n",
")",
";",
"ImmutableList",
".",
"Builder",
"<",
"Node",
">",
"builder",
"=",
"new",
"ImmutableList",
".",
"Builder",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"getCallParamCount",
"(",
"n",
")",
";",
"i",
"++",
")",
"{",
"builder",
".",
"add",
"(",
"getCallArgument",
"(",
"n",
",",
"i",
")",
")",
";",
"}",
"return",
"builder",
".",
"build",
"(",
")",
";",
"}"
] | Copying is unnecessarily inefficient. | [
"Copying",
"is",
"unnecessarily",
"inefficient",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeTransformation.java#L220-L227 |
24,161 | google/closure-compiler | src/com/google/javascript/jscomp/AliasStrings.java | AliasStrings.replaceStringsWithAliases | private void replaceStringsWithAliases() {
for (Entry<String, StringInfo> entry : stringInfoMap.entrySet()) {
String literal = entry.getKey();
StringInfo info = entry.getValue();
if (shouldReplaceWithAlias(literal, info)) {
for (StringOccurrence occurrence : info.occurrences) {
replaceStringWithAliasName(
occurrence, info.getVariableName(literal), info);
}
}
}
} | java | private void replaceStringsWithAliases() {
for (Entry<String, StringInfo> entry : stringInfoMap.entrySet()) {
String literal = entry.getKey();
StringInfo info = entry.getValue();
if (shouldReplaceWithAlias(literal, info)) {
for (StringOccurrence occurrence : info.occurrences) {
replaceStringWithAliasName(
occurrence, info.getVariableName(literal), info);
}
}
}
} | [
"private",
"void",
"replaceStringsWithAliases",
"(",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"StringInfo",
">",
"entry",
":",
"stringInfoMap",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"literal",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"StringInfo",
"info",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"shouldReplaceWithAlias",
"(",
"literal",
",",
"info",
")",
")",
"{",
"for",
"(",
"StringOccurrence",
"occurrence",
":",
"info",
".",
"occurrences",
")",
"{",
"replaceStringWithAliasName",
"(",
"occurrence",
",",
"info",
".",
"getVariableName",
"(",
"literal",
")",
",",
"info",
")",
";",
"}",
"}",
"}",
"}"
] | Replace strings with references to alias variables. | [
"Replace",
"strings",
"with",
"references",
"to",
"alias",
"variables",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AliasStrings.java#L215-L226 |
24,162 | google/closure-compiler | src/com/google/javascript/jscomp/AliasStrings.java | AliasStrings.addAliasDeclarationNodes | private void addAliasDeclarationNodes() {
for (Entry<String, StringInfo> entry : stringInfoMap.entrySet()) {
StringInfo info = entry.getValue();
if (!info.isAliased) {
continue;
}
String alias = info.getVariableName(entry.getKey());
Node var = IR.var(IR.name(alias), IR.string(entry.getKey()));
var.useSourceInfoFromForTree(info.parentForNewVarDecl);
if (info.siblingToInsertVarDeclBefore == null) {
info.parentForNewVarDecl.addChildToFront(var);
} else {
info.parentForNewVarDecl.addChildBefore(
var, info.siblingToInsertVarDeclBefore);
}
compiler.reportChangeToEnclosingScope(var);
}
} | java | private void addAliasDeclarationNodes() {
for (Entry<String, StringInfo> entry : stringInfoMap.entrySet()) {
StringInfo info = entry.getValue();
if (!info.isAliased) {
continue;
}
String alias = info.getVariableName(entry.getKey());
Node var = IR.var(IR.name(alias), IR.string(entry.getKey()));
var.useSourceInfoFromForTree(info.parentForNewVarDecl);
if (info.siblingToInsertVarDeclBefore == null) {
info.parentForNewVarDecl.addChildToFront(var);
} else {
info.parentForNewVarDecl.addChildBefore(
var, info.siblingToInsertVarDeclBefore);
}
compiler.reportChangeToEnclosingScope(var);
}
} | [
"private",
"void",
"addAliasDeclarationNodes",
"(",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"StringInfo",
">",
"entry",
":",
"stringInfoMap",
".",
"entrySet",
"(",
")",
")",
"{",
"StringInfo",
"info",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"!",
"info",
".",
"isAliased",
")",
"{",
"continue",
";",
"}",
"String",
"alias",
"=",
"info",
".",
"getVariableName",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"Node",
"var",
"=",
"IR",
".",
"var",
"(",
"IR",
".",
"name",
"(",
"alias",
")",
",",
"IR",
".",
"string",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
")",
";",
"var",
".",
"useSourceInfoFromForTree",
"(",
"info",
".",
"parentForNewVarDecl",
")",
";",
"if",
"(",
"info",
".",
"siblingToInsertVarDeclBefore",
"==",
"null",
")",
"{",
"info",
".",
"parentForNewVarDecl",
".",
"addChildToFront",
"(",
"var",
")",
";",
"}",
"else",
"{",
"info",
".",
"parentForNewVarDecl",
".",
"addChildBefore",
"(",
"var",
",",
"info",
".",
"siblingToInsertVarDeclBefore",
")",
";",
"}",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"var",
")",
";",
"}",
"}"
] | Creates a var declaration for each aliased string. Var declarations are
inserted as close to the first use of the string as possible. | [
"Creates",
"a",
"var",
"declaration",
"for",
"each",
"aliased",
"string",
".",
"Var",
"declarations",
"are",
"inserted",
"as",
"close",
"to",
"the",
"first",
"use",
"of",
"the",
"string",
"as",
"possible",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AliasStrings.java#L232-L249 |
24,163 | google/closure-compiler | src/com/google/javascript/jscomp/AliasStrings.java | AliasStrings.shouldReplaceWithAlias | private static boolean shouldReplaceWithAlias(String str, StringInfo info) {
// Optimize for code size. Are aliases smaller than strings?
//
// This logic optimizes for the size of uncompressed code, but it tends to
// get good results for the size of the gzipped code too.
//
// gzip actually prefers that strings are not aliased - it compresses N
// string literals better than 1 string literal and N+1 short variable
// names, provided each string is within 32k of the previous copy. We
// follow the uncompressed logic as insurance against there being multiple
// strings more than 32k apart.
int sizeOfLiteral = 2 + str.length();
int sizeOfStrings = info.numOccurrences * sizeOfLiteral;
int sizeOfVariable = 3;
// '6' comes from: 'var =;' in var XXX="...";
int sizeOfAliases = 6 + sizeOfVariable + sizeOfLiteral // declaration
+ info.numOccurrences * sizeOfVariable; // + uses
return sizeOfAliases < sizeOfStrings;
} | java | private static boolean shouldReplaceWithAlias(String str, StringInfo info) {
// Optimize for code size. Are aliases smaller than strings?
//
// This logic optimizes for the size of uncompressed code, but it tends to
// get good results for the size of the gzipped code too.
//
// gzip actually prefers that strings are not aliased - it compresses N
// string literals better than 1 string literal and N+1 short variable
// names, provided each string is within 32k of the previous copy. We
// follow the uncompressed logic as insurance against there being multiple
// strings more than 32k apart.
int sizeOfLiteral = 2 + str.length();
int sizeOfStrings = info.numOccurrences * sizeOfLiteral;
int sizeOfVariable = 3;
// '6' comes from: 'var =;' in var XXX="...";
int sizeOfAliases = 6 + sizeOfVariable + sizeOfLiteral // declaration
+ info.numOccurrences * sizeOfVariable; // + uses
return sizeOfAliases < sizeOfStrings;
} | [
"private",
"static",
"boolean",
"shouldReplaceWithAlias",
"(",
"String",
"str",
",",
"StringInfo",
"info",
")",
"{",
"// Optimize for code size. Are aliases smaller than strings?",
"//",
"// This logic optimizes for the size of uncompressed code, but it tends to",
"// get good results for the size of the gzipped code too.",
"//",
"// gzip actually prefers that strings are not aliased - it compresses N",
"// string literals better than 1 string literal and N+1 short variable",
"// names, provided each string is within 32k of the previous copy. We",
"// follow the uncompressed logic as insurance against there being multiple",
"// strings more than 32k apart.",
"int",
"sizeOfLiteral",
"=",
"2",
"+",
"str",
".",
"length",
"(",
")",
";",
"int",
"sizeOfStrings",
"=",
"info",
".",
"numOccurrences",
"*",
"sizeOfLiteral",
";",
"int",
"sizeOfVariable",
"=",
"3",
";",
"// '6' comes from: 'var =;' in var XXX=\"...\";",
"int",
"sizeOfAliases",
"=",
"6",
"+",
"sizeOfVariable",
"+",
"sizeOfLiteral",
"// declaration",
"+",
"info",
".",
"numOccurrences",
"*",
"sizeOfVariable",
";",
"// + uses",
"return",
"sizeOfAliases",
"<",
"sizeOfStrings",
";",
"}"
] | Dictates the policy for replacing a string with an alias.
@param str The string literal
@param info Accumulated information about a string | [
"Dictates",
"the",
"policy",
"for",
"replacing",
"a",
"string",
"with",
"an",
"alias",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AliasStrings.java#L257-L277 |
24,164 | google/closure-compiler | src/com/google/javascript/jscomp/AliasStrings.java | AliasStrings.replaceStringWithAliasName | private void replaceStringWithAliasName(StringOccurrence occurrence,
String name,
StringInfo info) {
Node nameNode = IR.name(name);
occurrence.parent.replaceChild(occurrence.node,
nameNode);
info.isAliased = true;
compiler.reportChangeToEnclosingScope(nameNode);
} | java | private void replaceStringWithAliasName(StringOccurrence occurrence,
String name,
StringInfo info) {
Node nameNode = IR.name(name);
occurrence.parent.replaceChild(occurrence.node,
nameNode);
info.isAliased = true;
compiler.reportChangeToEnclosingScope(nameNode);
} | [
"private",
"void",
"replaceStringWithAliasName",
"(",
"StringOccurrence",
"occurrence",
",",
"String",
"name",
",",
"StringInfo",
"info",
")",
"{",
"Node",
"nameNode",
"=",
"IR",
".",
"name",
"(",
"name",
")",
";",
"occurrence",
".",
"parent",
".",
"replaceChild",
"(",
"occurrence",
".",
"node",
",",
"nameNode",
")",
";",
"info",
".",
"isAliased",
"=",
"true",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"nameNode",
")",
";",
"}"
] | Replaces a string literal with a reference to the string's alias variable. | [
"Replaces",
"a",
"string",
"literal",
"with",
"a",
"reference",
"to",
"the",
"string",
"s",
"alias",
"variable",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AliasStrings.java#L282-L290 |
24,165 | google/closure-compiler | src/com/google/javascript/jscomp/AliasStrings.java | AliasStrings.outputStringUsage | private void outputStringUsage() {
StringBuilder sb = new StringBuilder("Strings used more than once:\n");
for (Entry<String, StringInfo> stringInfoEntry : stringInfoMap.entrySet()) {
StringInfo info = stringInfoEntry.getValue();
if (info.numOccurrences > 1) {
sb.append(info.numOccurrences);
sb.append(": ");
sb.append(stringInfoEntry.getKey());
sb.append('\n');
}
}
// TODO(user): Make this save to file OR output to the application
logger.fine(sb.toString());
} | java | private void outputStringUsage() {
StringBuilder sb = new StringBuilder("Strings used more than once:\n");
for (Entry<String, StringInfo> stringInfoEntry : stringInfoMap.entrySet()) {
StringInfo info = stringInfoEntry.getValue();
if (info.numOccurrences > 1) {
sb.append(info.numOccurrences);
sb.append(": ");
sb.append(stringInfoEntry.getKey());
sb.append('\n');
}
}
// TODO(user): Make this save to file OR output to the application
logger.fine(sb.toString());
} | [
"private",
"void",
"outputStringUsage",
"(",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"\"Strings used more than once:\\n\"",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"StringInfo",
">",
"stringInfoEntry",
":",
"stringInfoMap",
".",
"entrySet",
"(",
")",
")",
"{",
"StringInfo",
"info",
"=",
"stringInfoEntry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"info",
".",
"numOccurrences",
">",
"1",
")",
"{",
"sb",
".",
"append",
"(",
"info",
".",
"numOccurrences",
")",
";",
"sb",
".",
"append",
"(",
"\": \"",
")",
";",
"sb",
".",
"append",
"(",
"stringInfoEntry",
".",
"getKey",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"}",
"// TODO(user): Make this save to file OR output to the application",
"logger",
".",
"fine",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Outputs a log of all strings used more than once in the code. | [
"Outputs",
"a",
"log",
"of",
"all",
"strings",
"used",
"more",
"than",
"once",
"in",
"the",
"code",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AliasStrings.java#L295-L308 |
24,166 | google/closure-compiler | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | ProcessClosurePrimitives.processDefineCall | private void processDefineCall(NodeTraversal t, Node n, Node parent) {
Node left = n.getFirstChild();
Node args = left.getNext();
if (verifyDefine(t, parent, left, args)) {
Node nameNode = args;
maybeAddNameToSymbolTable(left);
maybeAddStringToSymbolTable(nameNode);
this.defineCalls.add(n);
}
} | java | private void processDefineCall(NodeTraversal t, Node n, Node parent) {
Node left = n.getFirstChild();
Node args = left.getNext();
if (verifyDefine(t, parent, left, args)) {
Node nameNode = args;
maybeAddNameToSymbolTable(left);
maybeAddStringToSymbolTable(nameNode);
this.defineCalls.add(n);
}
} | [
"private",
"void",
"processDefineCall",
"(",
"NodeTraversal",
"t",
",",
"Node",
"n",
",",
"Node",
"parent",
")",
"{",
"Node",
"left",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"Node",
"args",
"=",
"left",
".",
"getNext",
"(",
")",
";",
"if",
"(",
"verifyDefine",
"(",
"t",
",",
"parent",
",",
"left",
",",
"args",
")",
")",
"{",
"Node",
"nameNode",
"=",
"args",
";",
"maybeAddNameToSymbolTable",
"(",
"left",
")",
";",
"maybeAddStringToSymbolTable",
"(",
"nameNode",
")",
";",
"this",
".",
"defineCalls",
".",
"add",
"(",
"n",
")",
";",
"}",
"}"
] | Handles a goog.define call. | [
"Handles",
"a",
"goog",
".",
"define",
"call",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L385-L396 |
24,167 | google/closure-compiler | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | ProcessClosurePrimitives.processBaseClassCall | private void processBaseClassCall(NodeTraversal t, Node n) {
// Two things must hold for every goog.base call:
// 1) We must be calling it on "this".
// 2) We must be calling it on a prototype method of the same name as
// the one we're in, OR we must be calling it from a constructor.
// If both of those things are true, then we can rewrite:
// <pre>
// function Foo() {
// goog.base(this);
// }
// goog.inherits(Foo, BaseFoo);
// Foo.prototype.bar = function() {
// goog.base(this, 'bar', 1);
// };
// </pre>
// as the easy-to-optimize:
// <pre>
// function Foo() {
// BaseFoo.call(this);
// }
// goog.inherits(Foo, BaseFoo);
// Foo.prototype.bar = function() {
// Foo.superClass_.bar.call(this, 1);
// };
//
// Most of the logic here is just to make sure the AST's
// structure is what we expect it to be.
// If requested report uses of goog.base.
t.report(n, USE_OF_GOOG_BASE);
if (baseUsedInClass(n)){
reportBadGoogBaseUse(n, "goog.base in ES6 class is not allowed. Use super instead.");
return;
}
Node callee = n.getFirstChild();
Node thisArg = callee.getNext();
if (thisArg == null || !thisArg.isThis()) {
reportBadGoogBaseUse(n, "First argument must be 'this'.");
return;
}
Node enclosingFnNameNode = getEnclosingDeclNameNode(n);
if (enclosingFnNameNode == null) {
reportBadGoogBaseUse(n, "Could not find enclosing method.");
return;
}
String enclosingQname = enclosingFnNameNode.getQualifiedName();
if (!enclosingQname.contains(".prototype.")) {
// Handle constructors.
Node enclosingParent = enclosingFnNameNode.getParent();
Node maybeInheritsExpr =
(enclosingParent.isAssign() ? enclosingParent.getParent() : enclosingParent).getNext();
Node baseClassNode = null;
if (maybeInheritsExpr != null
&& maybeInheritsExpr.isExprResult()
&& maybeInheritsExpr.getFirstChild().isCall()) {
Node callNode = maybeInheritsExpr.getFirstChild();
if (callNode.getFirstChild().matchesQualifiedName("goog.inherits")
&& callNode.getLastChild().isQualifiedName()) {
baseClassNode = callNode.getLastChild();
}
}
if (baseClassNode == null) {
reportBadGoogBaseUse(n, "Could not find goog.inherits for base class");
return;
}
// We're good to go.
Node newCallee =
NodeUtil.newQName(
compiler, baseClassNode.getQualifiedName() + ".call", callee, "goog.base");
n.replaceChild(callee, newCallee);
compiler.reportChangeToEnclosingScope(newCallee);
} else {
// Handle methods.
Node methodNameNode = thisArg.getNext();
if (methodNameNode == null || !methodNameNode.isString()) {
reportBadGoogBaseUse(n, "Second argument must name a method.");
return;
}
String methodName = methodNameNode.getString();
String ending = ".prototype." + methodName;
if (enclosingQname == null || !enclosingQname.endsWith(ending)) {
reportBadGoogBaseUse(n, "Enclosing method does not match " + methodName);
return;
}
// We're good to go.
Node className =
enclosingFnNameNode.getFirstFirstChild();
n.replaceChild(
callee,
NodeUtil.newQName(
compiler,
className.getQualifiedName() + ".superClass_." + methodName + ".call",
callee, "goog.base"));
n.removeChild(methodNameNode);
compiler.reportChangeToEnclosingScope(n);
}
} | java | private void processBaseClassCall(NodeTraversal t, Node n) {
// Two things must hold for every goog.base call:
// 1) We must be calling it on "this".
// 2) We must be calling it on a prototype method of the same name as
// the one we're in, OR we must be calling it from a constructor.
// If both of those things are true, then we can rewrite:
// <pre>
// function Foo() {
// goog.base(this);
// }
// goog.inherits(Foo, BaseFoo);
// Foo.prototype.bar = function() {
// goog.base(this, 'bar', 1);
// };
// </pre>
// as the easy-to-optimize:
// <pre>
// function Foo() {
// BaseFoo.call(this);
// }
// goog.inherits(Foo, BaseFoo);
// Foo.prototype.bar = function() {
// Foo.superClass_.bar.call(this, 1);
// };
//
// Most of the logic here is just to make sure the AST's
// structure is what we expect it to be.
// If requested report uses of goog.base.
t.report(n, USE_OF_GOOG_BASE);
if (baseUsedInClass(n)){
reportBadGoogBaseUse(n, "goog.base in ES6 class is not allowed. Use super instead.");
return;
}
Node callee = n.getFirstChild();
Node thisArg = callee.getNext();
if (thisArg == null || !thisArg.isThis()) {
reportBadGoogBaseUse(n, "First argument must be 'this'.");
return;
}
Node enclosingFnNameNode = getEnclosingDeclNameNode(n);
if (enclosingFnNameNode == null) {
reportBadGoogBaseUse(n, "Could not find enclosing method.");
return;
}
String enclosingQname = enclosingFnNameNode.getQualifiedName();
if (!enclosingQname.contains(".prototype.")) {
// Handle constructors.
Node enclosingParent = enclosingFnNameNode.getParent();
Node maybeInheritsExpr =
(enclosingParent.isAssign() ? enclosingParent.getParent() : enclosingParent).getNext();
Node baseClassNode = null;
if (maybeInheritsExpr != null
&& maybeInheritsExpr.isExprResult()
&& maybeInheritsExpr.getFirstChild().isCall()) {
Node callNode = maybeInheritsExpr.getFirstChild();
if (callNode.getFirstChild().matchesQualifiedName("goog.inherits")
&& callNode.getLastChild().isQualifiedName()) {
baseClassNode = callNode.getLastChild();
}
}
if (baseClassNode == null) {
reportBadGoogBaseUse(n, "Could not find goog.inherits for base class");
return;
}
// We're good to go.
Node newCallee =
NodeUtil.newQName(
compiler, baseClassNode.getQualifiedName() + ".call", callee, "goog.base");
n.replaceChild(callee, newCallee);
compiler.reportChangeToEnclosingScope(newCallee);
} else {
// Handle methods.
Node methodNameNode = thisArg.getNext();
if (methodNameNode == null || !methodNameNode.isString()) {
reportBadGoogBaseUse(n, "Second argument must name a method.");
return;
}
String methodName = methodNameNode.getString();
String ending = ".prototype." + methodName;
if (enclosingQname == null || !enclosingQname.endsWith(ending)) {
reportBadGoogBaseUse(n, "Enclosing method does not match " + methodName);
return;
}
// We're good to go.
Node className =
enclosingFnNameNode.getFirstFirstChild();
n.replaceChild(
callee,
NodeUtil.newQName(
compiler,
className.getQualifiedName() + ".superClass_." + methodName + ".call",
callee, "goog.base"));
n.removeChild(methodNameNode);
compiler.reportChangeToEnclosingScope(n);
}
} | [
"private",
"void",
"processBaseClassCall",
"(",
"NodeTraversal",
"t",
",",
"Node",
"n",
")",
"{",
"// Two things must hold for every goog.base call:",
"// 1) We must be calling it on \"this\".",
"// 2) We must be calling it on a prototype method of the same name as",
"// the one we're in, OR we must be calling it from a constructor.",
"// If both of those things are true, then we can rewrite:",
"// <pre>",
"// function Foo() {",
"// goog.base(this);",
"// }",
"// goog.inherits(Foo, BaseFoo);",
"// Foo.prototype.bar = function() {",
"// goog.base(this, 'bar', 1);",
"// };",
"// </pre>",
"// as the easy-to-optimize:",
"// <pre>",
"// function Foo() {",
"// BaseFoo.call(this);",
"// }",
"// goog.inherits(Foo, BaseFoo);",
"// Foo.prototype.bar = function() {",
"// Foo.superClass_.bar.call(this, 1);",
"// };",
"//",
"// Most of the logic here is just to make sure the AST's",
"// structure is what we expect it to be.",
"// If requested report uses of goog.base.",
"t",
".",
"report",
"(",
"n",
",",
"USE_OF_GOOG_BASE",
")",
";",
"if",
"(",
"baseUsedInClass",
"(",
"n",
")",
")",
"{",
"reportBadGoogBaseUse",
"(",
"n",
",",
"\"goog.base in ES6 class is not allowed. Use super instead.\"",
")",
";",
"return",
";",
"}",
"Node",
"callee",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"Node",
"thisArg",
"=",
"callee",
".",
"getNext",
"(",
")",
";",
"if",
"(",
"thisArg",
"==",
"null",
"||",
"!",
"thisArg",
".",
"isThis",
"(",
")",
")",
"{",
"reportBadGoogBaseUse",
"(",
"n",
",",
"\"First argument must be 'this'.\"",
")",
";",
"return",
";",
"}",
"Node",
"enclosingFnNameNode",
"=",
"getEnclosingDeclNameNode",
"(",
"n",
")",
";",
"if",
"(",
"enclosingFnNameNode",
"==",
"null",
")",
"{",
"reportBadGoogBaseUse",
"(",
"n",
",",
"\"Could not find enclosing method.\"",
")",
";",
"return",
";",
"}",
"String",
"enclosingQname",
"=",
"enclosingFnNameNode",
".",
"getQualifiedName",
"(",
")",
";",
"if",
"(",
"!",
"enclosingQname",
".",
"contains",
"(",
"\".prototype.\"",
")",
")",
"{",
"// Handle constructors.",
"Node",
"enclosingParent",
"=",
"enclosingFnNameNode",
".",
"getParent",
"(",
")",
";",
"Node",
"maybeInheritsExpr",
"=",
"(",
"enclosingParent",
".",
"isAssign",
"(",
")",
"?",
"enclosingParent",
".",
"getParent",
"(",
")",
":",
"enclosingParent",
")",
".",
"getNext",
"(",
")",
";",
"Node",
"baseClassNode",
"=",
"null",
";",
"if",
"(",
"maybeInheritsExpr",
"!=",
"null",
"&&",
"maybeInheritsExpr",
".",
"isExprResult",
"(",
")",
"&&",
"maybeInheritsExpr",
".",
"getFirstChild",
"(",
")",
".",
"isCall",
"(",
")",
")",
"{",
"Node",
"callNode",
"=",
"maybeInheritsExpr",
".",
"getFirstChild",
"(",
")",
";",
"if",
"(",
"callNode",
".",
"getFirstChild",
"(",
")",
".",
"matchesQualifiedName",
"(",
"\"goog.inherits\"",
")",
"&&",
"callNode",
".",
"getLastChild",
"(",
")",
".",
"isQualifiedName",
"(",
")",
")",
"{",
"baseClassNode",
"=",
"callNode",
".",
"getLastChild",
"(",
")",
";",
"}",
"}",
"if",
"(",
"baseClassNode",
"==",
"null",
")",
"{",
"reportBadGoogBaseUse",
"(",
"n",
",",
"\"Could not find goog.inherits for base class\"",
")",
";",
"return",
";",
"}",
"// We're good to go.",
"Node",
"newCallee",
"=",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"baseClassNode",
".",
"getQualifiedName",
"(",
")",
"+",
"\".call\"",
",",
"callee",
",",
"\"goog.base\"",
")",
";",
"n",
".",
"replaceChild",
"(",
"callee",
",",
"newCallee",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"newCallee",
")",
";",
"}",
"else",
"{",
"// Handle methods.",
"Node",
"methodNameNode",
"=",
"thisArg",
".",
"getNext",
"(",
")",
";",
"if",
"(",
"methodNameNode",
"==",
"null",
"||",
"!",
"methodNameNode",
".",
"isString",
"(",
")",
")",
"{",
"reportBadGoogBaseUse",
"(",
"n",
",",
"\"Second argument must name a method.\"",
")",
";",
"return",
";",
"}",
"String",
"methodName",
"=",
"methodNameNode",
".",
"getString",
"(",
")",
";",
"String",
"ending",
"=",
"\".prototype.\"",
"+",
"methodName",
";",
"if",
"(",
"enclosingQname",
"==",
"null",
"||",
"!",
"enclosingQname",
".",
"endsWith",
"(",
"ending",
")",
")",
"{",
"reportBadGoogBaseUse",
"(",
"n",
",",
"\"Enclosing method does not match \"",
"+",
"methodName",
")",
";",
"return",
";",
"}",
"// We're good to go.",
"Node",
"className",
"=",
"enclosingFnNameNode",
".",
"getFirstFirstChild",
"(",
")",
";",
"n",
".",
"replaceChild",
"(",
"callee",
",",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"className",
".",
"getQualifiedName",
"(",
")",
"+",
"\".superClass_.\"",
"+",
"methodName",
"+",
"\".call\"",
",",
"callee",
",",
"\"goog.base\"",
")",
")",
";",
"n",
".",
"removeChild",
"(",
"methodNameNode",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"n",
")",
";",
"}",
"}"
] | Processes the base class call. | [
"Processes",
"the",
"base",
"class",
"call",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L399-L503 |
24,168 | google/closure-compiler | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | ProcessClosurePrimitives.processInheritsCall | private void processInheritsCall(Node n) {
if (n.getChildCount() == 3) {
Node subClass = n.getSecondChild();
Node superClass = subClass.getNext();
if (subClass.isUnscopedQualifiedName() && superClass.isUnscopedQualifiedName()) {
knownClosureSubclasses.add(subClass.getQualifiedName());
}
}
} | java | private void processInheritsCall(Node n) {
if (n.getChildCount() == 3) {
Node subClass = n.getSecondChild();
Node superClass = subClass.getNext();
if (subClass.isUnscopedQualifiedName() && superClass.isUnscopedQualifiedName()) {
knownClosureSubclasses.add(subClass.getQualifiedName());
}
}
} | [
"private",
"void",
"processInheritsCall",
"(",
"Node",
"n",
")",
"{",
"if",
"(",
"n",
".",
"getChildCount",
"(",
")",
"==",
"3",
")",
"{",
"Node",
"subClass",
"=",
"n",
".",
"getSecondChild",
"(",
")",
";",
"Node",
"superClass",
"=",
"subClass",
".",
"getNext",
"(",
")",
";",
"if",
"(",
"subClass",
".",
"isUnscopedQualifiedName",
"(",
")",
"&&",
"superClass",
".",
"isUnscopedQualifiedName",
"(",
")",
")",
"{",
"knownClosureSubclasses",
".",
"add",
"(",
"subClass",
".",
"getQualifiedName",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Processes the goog.inherits call. | [
"Processes",
"the",
"goog",
".",
"inherits",
"call",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L686-L694 |
24,169 | google/closure-compiler | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | ProcessClosurePrimitives.getEnclosingDeclNameNode | private static Node getEnclosingDeclNameNode(Node n) {
Node fn = NodeUtil.getEnclosingFunction(n);
return fn == null ? null : NodeUtil.getNameNode(fn);
} | java | private static Node getEnclosingDeclNameNode(Node n) {
Node fn = NodeUtil.getEnclosingFunction(n);
return fn == null ? null : NodeUtil.getNameNode(fn);
} | [
"private",
"static",
"Node",
"getEnclosingDeclNameNode",
"(",
"Node",
"n",
")",
"{",
"Node",
"fn",
"=",
"NodeUtil",
".",
"getEnclosingFunction",
"(",
"n",
")",
";",
"return",
"fn",
"==",
"null",
"?",
"null",
":",
"NodeUtil",
".",
"getNameNode",
"(",
"fn",
")",
";",
"}"
] | Returns the qualified name node of the function whose scope we're in,
or null if it cannot be found. | [
"Returns",
"the",
"qualified",
"name",
"node",
"of",
"the",
"function",
"whose",
"scope",
"we",
"re",
"in",
"or",
"null",
"if",
"it",
"cannot",
"be",
"found",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L700-L703 |
24,170 | google/closure-compiler | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | ProcessClosurePrimitives.baseUsedInClass | private boolean baseUsedInClass(Node n){
for (Node curr = n; curr != null; curr = curr.getParent()){
if (curr.isClassMembers()) {
return true;
}
}
return false;
} | java | private boolean baseUsedInClass(Node n){
for (Node curr = n; curr != null; curr = curr.getParent()){
if (curr.isClassMembers()) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"baseUsedInClass",
"(",
"Node",
"n",
")",
"{",
"for",
"(",
"Node",
"curr",
"=",
"n",
";",
"curr",
"!=",
"null",
";",
"curr",
"=",
"curr",
".",
"getParent",
"(",
")",
")",
"{",
"if",
"(",
"curr",
".",
"isClassMembers",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Verify if goog.base call is used in a class | [
"Verify",
"if",
"goog",
".",
"base",
"call",
"is",
"used",
"in",
"a",
"class"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L706-L713 |
24,171 | google/closure-compiler | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | ProcessClosurePrimitives.verifyProvide | private boolean verifyProvide(Node methodName, Node arg) {
if (!verifyLastArgumentIsString(methodName, arg)) {
return false;
}
if (!NodeUtil.isValidQualifiedName(
compiler.getOptions().getLanguageIn().toFeatureSet(), arg.getString())) {
compiler.report(
JSError.make(
arg,
INVALID_PROVIDE_ERROR,
arg.getString(),
compiler.getOptions().getLanguageIn().toString()));
return false;
}
return true;
} | java | private boolean verifyProvide(Node methodName, Node arg) {
if (!verifyLastArgumentIsString(methodName, arg)) {
return false;
}
if (!NodeUtil.isValidQualifiedName(
compiler.getOptions().getLanguageIn().toFeatureSet(), arg.getString())) {
compiler.report(
JSError.make(
arg,
INVALID_PROVIDE_ERROR,
arg.getString(),
compiler.getOptions().getLanguageIn().toString()));
return false;
}
return true;
} | [
"private",
"boolean",
"verifyProvide",
"(",
"Node",
"methodName",
",",
"Node",
"arg",
")",
"{",
"if",
"(",
"!",
"verifyLastArgumentIsString",
"(",
"methodName",
",",
"arg",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"NodeUtil",
".",
"isValidQualifiedName",
"(",
"compiler",
".",
"getOptions",
"(",
")",
".",
"getLanguageIn",
"(",
")",
".",
"toFeatureSet",
"(",
")",
",",
"arg",
".",
"getString",
"(",
")",
")",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"arg",
",",
"INVALID_PROVIDE_ERROR",
",",
"arg",
".",
"getString",
"(",
")",
",",
"compiler",
".",
"getOptions",
"(",
")",
".",
"getLanguageIn",
"(",
")",
".",
"toString",
"(",
")",
")",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Verifies that a provide method call has exactly one argument, and that it's a string literal
and that the contents of the string are valid JS tokens. Reports a compile error if it doesn't.
@return Whether the argument checked out okay | [
"Verifies",
"that",
"a",
"provide",
"method",
"call",
"has",
"exactly",
"one",
"argument",
"and",
"that",
"it",
"s",
"a",
"string",
"literal",
"and",
"that",
"the",
"contents",
"of",
"the",
"string",
"are",
"valid",
"JS",
"tokens",
".",
"Reports",
"a",
"compile",
"error",
"if",
"it",
"doesn",
"t",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L831-L848 |
24,172 | google/closure-compiler | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | ProcessClosurePrimitives.verifyDefine | private boolean verifyDefine(NodeTraversal t, Node parent, Node methodName, Node args) {
// Calls to goog.define must be in the global hoist scope. This is copied from
// validate(Un)aliasablePrimitiveCall.
// TODO(sdh): loosen this restriction if the results are assigned?
if (!compiler.getOptions().shouldPreserveGoogModule() && !t.inGlobalHoistScope()) {
compiler.report(JSError.make(methodName.getParent(), INVALID_CLOSURE_CALL_SCOPE_ERROR));
return false;
}
// It is an error for goog.define to show up anywhere except on its own or immediately after =.
if (parent.isAssign() && parent.getParent().isExprResult()) {
parent = parent.getParent();
} else if (parent.isName() && NodeUtil.isNameDeclaration(parent.getParent())) {
parent = parent.getParent();
} else if (!parent.isExprResult()) {
compiler.report(JSError.make(methodName.getParent(), INVALID_CLOSURE_CALL_SCOPE_ERROR));
return false;
}
// Verify first arg
Node arg = args;
if (!verifyNotNull(methodName, arg) || !verifyOfType(methodName, arg, Token.STRING)) {
return false;
}
// Verify second arg
arg = arg.getNext();
if (!args.isFromExterns()
&& (!verifyNotNull(methodName, arg) || !verifyIsLast(methodName, arg))) {
return false;
}
String name = args.getString();
if (!NodeUtil.isValidQualifiedName(
compiler.getOptions().getLanguageIn().toFeatureSet(), name)) {
compiler.report(JSError.make(args, INVALID_DEFINE_NAME_ERROR, name));
return false;
}
JSDocInfo info = (parent.isExprResult() ? parent.getFirstChild() : parent).getJSDocInfo();
if (info == null || !info.isDefine()) {
compiler.report(JSError.make(parent, MISSING_DEFINE_ANNOTATION));
return false;
}
return true;
} | java | private boolean verifyDefine(NodeTraversal t, Node parent, Node methodName, Node args) {
// Calls to goog.define must be in the global hoist scope. This is copied from
// validate(Un)aliasablePrimitiveCall.
// TODO(sdh): loosen this restriction if the results are assigned?
if (!compiler.getOptions().shouldPreserveGoogModule() && !t.inGlobalHoistScope()) {
compiler.report(JSError.make(methodName.getParent(), INVALID_CLOSURE_CALL_SCOPE_ERROR));
return false;
}
// It is an error for goog.define to show up anywhere except on its own or immediately after =.
if (parent.isAssign() && parent.getParent().isExprResult()) {
parent = parent.getParent();
} else if (parent.isName() && NodeUtil.isNameDeclaration(parent.getParent())) {
parent = parent.getParent();
} else if (!parent.isExprResult()) {
compiler.report(JSError.make(methodName.getParent(), INVALID_CLOSURE_CALL_SCOPE_ERROR));
return false;
}
// Verify first arg
Node arg = args;
if (!verifyNotNull(methodName, arg) || !verifyOfType(methodName, arg, Token.STRING)) {
return false;
}
// Verify second arg
arg = arg.getNext();
if (!args.isFromExterns()
&& (!verifyNotNull(methodName, arg) || !verifyIsLast(methodName, arg))) {
return false;
}
String name = args.getString();
if (!NodeUtil.isValidQualifiedName(
compiler.getOptions().getLanguageIn().toFeatureSet(), name)) {
compiler.report(JSError.make(args, INVALID_DEFINE_NAME_ERROR, name));
return false;
}
JSDocInfo info = (parent.isExprResult() ? parent.getFirstChild() : parent).getJSDocInfo();
if (info == null || !info.isDefine()) {
compiler.report(JSError.make(parent, MISSING_DEFINE_ANNOTATION));
return false;
}
return true;
} | [
"private",
"boolean",
"verifyDefine",
"(",
"NodeTraversal",
"t",
",",
"Node",
"parent",
",",
"Node",
"methodName",
",",
"Node",
"args",
")",
"{",
"// Calls to goog.define must be in the global hoist scope. This is copied from",
"// validate(Un)aliasablePrimitiveCall.",
"// TODO(sdh): loosen this restriction if the results are assigned?",
"if",
"(",
"!",
"compiler",
".",
"getOptions",
"(",
")",
".",
"shouldPreserveGoogModule",
"(",
")",
"&&",
"!",
"t",
".",
"inGlobalHoistScope",
"(",
")",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"methodName",
".",
"getParent",
"(",
")",
",",
"INVALID_CLOSURE_CALL_SCOPE_ERROR",
")",
")",
";",
"return",
"false",
";",
"}",
"// It is an error for goog.define to show up anywhere except on its own or immediately after =.",
"if",
"(",
"parent",
".",
"isAssign",
"(",
")",
"&&",
"parent",
".",
"getParent",
"(",
")",
".",
"isExprResult",
"(",
")",
")",
"{",
"parent",
"=",
"parent",
".",
"getParent",
"(",
")",
";",
"}",
"else",
"if",
"(",
"parent",
".",
"isName",
"(",
")",
"&&",
"NodeUtil",
".",
"isNameDeclaration",
"(",
"parent",
".",
"getParent",
"(",
")",
")",
")",
"{",
"parent",
"=",
"parent",
".",
"getParent",
"(",
")",
";",
"}",
"else",
"if",
"(",
"!",
"parent",
".",
"isExprResult",
"(",
")",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"methodName",
".",
"getParent",
"(",
")",
",",
"INVALID_CLOSURE_CALL_SCOPE_ERROR",
")",
")",
";",
"return",
"false",
";",
"}",
"// Verify first arg",
"Node",
"arg",
"=",
"args",
";",
"if",
"(",
"!",
"verifyNotNull",
"(",
"methodName",
",",
"arg",
")",
"||",
"!",
"verifyOfType",
"(",
"methodName",
",",
"arg",
",",
"Token",
".",
"STRING",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Verify second arg",
"arg",
"=",
"arg",
".",
"getNext",
"(",
")",
";",
"if",
"(",
"!",
"args",
".",
"isFromExterns",
"(",
")",
"&&",
"(",
"!",
"verifyNotNull",
"(",
"methodName",
",",
"arg",
")",
"||",
"!",
"verifyIsLast",
"(",
"methodName",
",",
"arg",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"String",
"name",
"=",
"args",
".",
"getString",
"(",
")",
";",
"if",
"(",
"!",
"NodeUtil",
".",
"isValidQualifiedName",
"(",
"compiler",
".",
"getOptions",
"(",
")",
".",
"getLanguageIn",
"(",
")",
".",
"toFeatureSet",
"(",
")",
",",
"name",
")",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"args",
",",
"INVALID_DEFINE_NAME_ERROR",
",",
"name",
")",
")",
";",
"return",
"false",
";",
"}",
"JSDocInfo",
"info",
"=",
"(",
"parent",
".",
"isExprResult",
"(",
")",
"?",
"parent",
".",
"getFirstChild",
"(",
")",
":",
"parent",
")",
".",
"getJSDocInfo",
"(",
")",
";",
"if",
"(",
"info",
"==",
"null",
"||",
"!",
"info",
".",
"isDefine",
"(",
")",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"parent",
",",
"MISSING_DEFINE_ANNOTATION",
")",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Verifies that a goog.define method call has exactly two arguments, with the first a string
literal whose contents is a valid JS qualified name. Reports a compile error if it doesn't.
@return Whether the argument checked out okay | [
"Verifies",
"that",
"a",
"goog",
".",
"define",
"method",
"call",
"has",
"exactly",
"two",
"arguments",
"with",
"the",
"first",
"a",
"string",
"literal",
"whose",
"contents",
"is",
"a",
"valid",
"JS",
"qualified",
"name",
".",
"Reports",
"a",
"compile",
"error",
"if",
"it",
"doesn",
"t",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L856-L901 |
24,173 | google/closure-compiler | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | ProcessClosurePrimitives.verifyLastArgumentIsString | private boolean verifyLastArgumentIsString(Node methodName, Node arg) {
return verifyNotNull(methodName, arg)
&& verifyOfType(methodName, arg, Token.STRING)
&& verifyIsLast(methodName, arg);
} | java | private boolean verifyLastArgumentIsString(Node methodName, Node arg) {
return verifyNotNull(methodName, arg)
&& verifyOfType(methodName, arg, Token.STRING)
&& verifyIsLast(methodName, arg);
} | [
"private",
"boolean",
"verifyLastArgumentIsString",
"(",
"Node",
"methodName",
",",
"Node",
"arg",
")",
"{",
"return",
"verifyNotNull",
"(",
"methodName",
",",
"arg",
")",
"&&",
"verifyOfType",
"(",
"methodName",
",",
"arg",
",",
"Token",
".",
"STRING",
")",
"&&",
"verifyIsLast",
"(",
"methodName",
",",
"arg",
")",
";",
"}"
] | Verifies that a method call has exactly one argument, and that it's a string literal. Reports a
compile error if it doesn't.
@return Whether the argument checked out okay | [
"Verifies",
"that",
"a",
"method",
"call",
"has",
"exactly",
"one",
"argument",
"and",
"that",
"it",
"s",
"a",
"string",
"literal",
".",
"Reports",
"a",
"compile",
"error",
"if",
"it",
"doesn",
"t",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L956-L960 |
24,174 | google/closure-compiler | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | ProcessClosurePrimitives.verifySetCssNameMapping | private boolean verifySetCssNameMapping(Node methodName, Node firstArg) {
DiagnosticType diagnostic = null;
if (firstArg == null) {
diagnostic = NULL_ARGUMENT_ERROR;
} else if (!firstArg.isObjectLit()) {
diagnostic = EXPECTED_OBJECTLIT_ERROR;
} else if (firstArg.getNext() != null) {
Node secondArg = firstArg.getNext();
if (!secondArg.isString()) {
diagnostic = EXPECTED_STRING_ERROR;
} else if (secondArg.getNext() != null) {
diagnostic = TOO_MANY_ARGUMENTS_ERROR;
}
}
if (diagnostic != null) {
compiler.report(JSError.make(methodName, diagnostic, methodName.getQualifiedName()));
return false;
}
return true;
} | java | private boolean verifySetCssNameMapping(Node methodName, Node firstArg) {
DiagnosticType diagnostic = null;
if (firstArg == null) {
diagnostic = NULL_ARGUMENT_ERROR;
} else if (!firstArg.isObjectLit()) {
diagnostic = EXPECTED_OBJECTLIT_ERROR;
} else if (firstArg.getNext() != null) {
Node secondArg = firstArg.getNext();
if (!secondArg.isString()) {
diagnostic = EXPECTED_STRING_ERROR;
} else if (secondArg.getNext() != null) {
diagnostic = TOO_MANY_ARGUMENTS_ERROR;
}
}
if (diagnostic != null) {
compiler.report(JSError.make(methodName, diagnostic, methodName.getQualifiedName()));
return false;
}
return true;
} | [
"private",
"boolean",
"verifySetCssNameMapping",
"(",
"Node",
"methodName",
",",
"Node",
"firstArg",
")",
"{",
"DiagnosticType",
"diagnostic",
"=",
"null",
";",
"if",
"(",
"firstArg",
"==",
"null",
")",
"{",
"diagnostic",
"=",
"NULL_ARGUMENT_ERROR",
";",
"}",
"else",
"if",
"(",
"!",
"firstArg",
".",
"isObjectLit",
"(",
")",
")",
"{",
"diagnostic",
"=",
"EXPECTED_OBJECTLIT_ERROR",
";",
"}",
"else",
"if",
"(",
"firstArg",
".",
"getNext",
"(",
")",
"!=",
"null",
")",
"{",
"Node",
"secondArg",
"=",
"firstArg",
".",
"getNext",
"(",
")",
";",
"if",
"(",
"!",
"secondArg",
".",
"isString",
"(",
")",
")",
"{",
"diagnostic",
"=",
"EXPECTED_STRING_ERROR",
";",
"}",
"else",
"if",
"(",
"secondArg",
".",
"getNext",
"(",
")",
"!=",
"null",
")",
"{",
"diagnostic",
"=",
"TOO_MANY_ARGUMENTS_ERROR",
";",
"}",
"}",
"if",
"(",
"diagnostic",
"!=",
"null",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"methodName",
",",
"diagnostic",
",",
"methodName",
".",
"getQualifiedName",
"(",
")",
")",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Verifies that setCssNameMapping is called with the correct methods.
@return Whether the arguments checked out okay | [
"Verifies",
"that",
"setCssNameMapping",
"is",
"called",
"with",
"the",
"correct",
"methods",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessClosurePrimitives.java#L996-L1015 |
24,175 | google/closure-compiler | src/com/google/javascript/rhino/JSTypeExpression.java | JSTypeExpression.makeOptionalArg | public static JSTypeExpression makeOptionalArg(JSTypeExpression expr) {
if (expr.isOptionalArg() || expr.isVarArgs()) {
return expr;
} else {
return new JSTypeExpression(
new Node(Token.EQUALS, expr.root), expr.sourceName);
}
} | java | public static JSTypeExpression makeOptionalArg(JSTypeExpression expr) {
if (expr.isOptionalArg() || expr.isVarArgs()) {
return expr;
} else {
return new JSTypeExpression(
new Node(Token.EQUALS, expr.root), expr.sourceName);
}
} | [
"public",
"static",
"JSTypeExpression",
"makeOptionalArg",
"(",
"JSTypeExpression",
"expr",
")",
"{",
"if",
"(",
"expr",
".",
"isOptionalArg",
"(",
")",
"||",
"expr",
".",
"isVarArgs",
"(",
")",
")",
"{",
"return",
"expr",
";",
"}",
"else",
"{",
"return",
"new",
"JSTypeExpression",
"(",
"new",
"Node",
"(",
"Token",
".",
"EQUALS",
",",
"expr",
".",
"root",
")",
",",
"expr",
".",
"sourceName",
")",
";",
"}",
"}"
] | Make the given type expression into an optional type expression,
if possible. | [
"Make",
"the",
"given",
"type",
"expression",
"into",
"an",
"optional",
"type",
"expression",
"if",
"possible",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSTypeExpression.java#L73-L80 |
24,176 | google/closure-compiler | src/com/google/javascript/rhino/TypeDeclarationsIR.java | TypeDeclarationsIR.namedType | public static TypeDeclarationNode namedType(Iterable<String> segments) {
Iterator<String> segmentsIt = segments.iterator();
Node node = IR.name(segmentsIt.next());
while (segmentsIt.hasNext()) {
node = IR.getprop(node, IR.string(segmentsIt.next()));
}
return new TypeDeclarationNode(Token.NAMED_TYPE, node);
} | java | public static TypeDeclarationNode namedType(Iterable<String> segments) {
Iterator<String> segmentsIt = segments.iterator();
Node node = IR.name(segmentsIt.next());
while (segmentsIt.hasNext()) {
node = IR.getprop(node, IR.string(segmentsIt.next()));
}
return new TypeDeclarationNode(Token.NAMED_TYPE, node);
} | [
"public",
"static",
"TypeDeclarationNode",
"namedType",
"(",
"Iterable",
"<",
"String",
">",
"segments",
")",
"{",
"Iterator",
"<",
"String",
">",
"segmentsIt",
"=",
"segments",
".",
"iterator",
"(",
")",
";",
"Node",
"node",
"=",
"IR",
".",
"name",
"(",
"segmentsIt",
".",
"next",
"(",
")",
")",
";",
"while",
"(",
"segmentsIt",
".",
"hasNext",
"(",
")",
")",
"{",
"node",
"=",
"IR",
".",
"getprop",
"(",
"node",
",",
"IR",
".",
"string",
"(",
"segmentsIt",
".",
"next",
"(",
")",
")",
")",
";",
"}",
"return",
"new",
"TypeDeclarationNode",
"(",
"Token",
".",
"NAMED_TYPE",
",",
"node",
")",
";",
"}"
] | Produces a tree structure similar to the Rhino AST of a qualified name
expression, under a top-level NAMED_TYPE node.
<p>Example:
<pre>
NAMED_TYPE
NAME goog
STRING ui
STRING Window
</pre> | [
"Produces",
"a",
"tree",
"structure",
"similar",
"to",
"the",
"Rhino",
"AST",
"of",
"a",
"qualified",
"name",
"expression",
"under",
"a",
"top",
"-",
"level",
"NAMED_TYPE",
"node",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/TypeDeclarationsIR.java#L125-L132 |
24,177 | google/closure-compiler | src/com/google/javascript/jscomp/InlineFunctions.java | InlineFunctions.maybeAddFunction | void maybeAddFunction(Function fn, JSModule module) {
String name = fn.getName();
FunctionState functionState = getOrCreateFunctionState(name);
// TODO(johnlenz): Maybe "smarten" FunctionState by adding this logic to it?
// If the function has multiple definitions, don't inline it.
if (functionState.hasExistingFunctionDefinition()) {
functionState.disallowInlining();
return;
}
Node fnNode = fn.getFunctionNode();
if (hasNoInlineAnnotation(fnNode)) {
functionState.disallowInlining();
return;
}
if (enforceMaxSizeAfterInlining
&& !isAlwaysInlinable(fnNode)
&& maxSizeAfterInlining <= NodeUtil.countAstSizeUpToLimit(fnNode, maxSizeAfterInlining)) {
functionState.disallowInlining();
return;
}
// verify the function hasn't already been marked as "don't inline"
if (functionState.canInline()) {
// store it for use when inlining.
functionState.setFn(fn);
if (FunctionInjector.isDirectCallNodeReplacementPossible(fn.getFunctionNode())) {
functionState.inlineDirectly(true);
}
if (hasNonInlinableParam(NodeUtil.getFunctionParameters(fnNode))) {
functionState.disallowInlining();
}
// verify the function meets all the requirements.
// TODO(johnlenz): Minimum requirement checks are about 5% of the
// run-time cost of this pass.
if (!isCandidateFunction(fn)) {
// It doesn't meet the requirements.
functionState.disallowInlining();
}
// Set the module and gather names that need temporaries.
if (functionState.canInline()) {
functionState.setModule(module);
Set<String> namesToAlias = FunctionArgumentInjector.findModifiedParameters(fnNode);
if (!namesToAlias.isEmpty()) {
functionState.inlineDirectly(false);
functionState.setNamesToAlias(namesToAlias);
}
Node block = NodeUtil.getFunctionBody(fnNode);
if (NodeUtil.referencesThis(block)) {
functionState.setReferencesThis(true);
}
if (NodeUtil.containsFunction(block)) {
functionState.setHasInnerFunctions(true);
// If there are inner functions, we can inline into global scope
// if there are no local vars or named functions.
// TODO(johnlenz): this can be improved by looking at the possible
// values for locals. If there are simple values, or constants
// we could still inline.
if (!assumeMinimumCapture && hasLocalNames(fnNode)) {
functionState.disallowInlining();
}
}
}
if (fnNode.getGrandparent().isVar()) {
Node block = functionState.getFn().getDeclaringBlock();
if (block.isBlock()
&& !block.getParent().isFunction()
&& (NodeUtil.containsType(block, Token.LET)
|| NodeUtil.containsType(block, Token.CONST))) {
// The function might capture a variable that's not in scope at the call site,
// so don't inline.
functionState.disallowInlining();
}
}
if (fnNode.isGeneratorFunction()) {
functionState.disallowInlining();
}
if (fnNode.isAsyncFunction()) {
functionState.disallowInlining();
}
}
} | java | void maybeAddFunction(Function fn, JSModule module) {
String name = fn.getName();
FunctionState functionState = getOrCreateFunctionState(name);
// TODO(johnlenz): Maybe "smarten" FunctionState by adding this logic to it?
// If the function has multiple definitions, don't inline it.
if (functionState.hasExistingFunctionDefinition()) {
functionState.disallowInlining();
return;
}
Node fnNode = fn.getFunctionNode();
if (hasNoInlineAnnotation(fnNode)) {
functionState.disallowInlining();
return;
}
if (enforceMaxSizeAfterInlining
&& !isAlwaysInlinable(fnNode)
&& maxSizeAfterInlining <= NodeUtil.countAstSizeUpToLimit(fnNode, maxSizeAfterInlining)) {
functionState.disallowInlining();
return;
}
// verify the function hasn't already been marked as "don't inline"
if (functionState.canInline()) {
// store it for use when inlining.
functionState.setFn(fn);
if (FunctionInjector.isDirectCallNodeReplacementPossible(fn.getFunctionNode())) {
functionState.inlineDirectly(true);
}
if (hasNonInlinableParam(NodeUtil.getFunctionParameters(fnNode))) {
functionState.disallowInlining();
}
// verify the function meets all the requirements.
// TODO(johnlenz): Minimum requirement checks are about 5% of the
// run-time cost of this pass.
if (!isCandidateFunction(fn)) {
// It doesn't meet the requirements.
functionState.disallowInlining();
}
// Set the module and gather names that need temporaries.
if (functionState.canInline()) {
functionState.setModule(module);
Set<String> namesToAlias = FunctionArgumentInjector.findModifiedParameters(fnNode);
if (!namesToAlias.isEmpty()) {
functionState.inlineDirectly(false);
functionState.setNamesToAlias(namesToAlias);
}
Node block = NodeUtil.getFunctionBody(fnNode);
if (NodeUtil.referencesThis(block)) {
functionState.setReferencesThis(true);
}
if (NodeUtil.containsFunction(block)) {
functionState.setHasInnerFunctions(true);
// If there are inner functions, we can inline into global scope
// if there are no local vars or named functions.
// TODO(johnlenz): this can be improved by looking at the possible
// values for locals. If there are simple values, or constants
// we could still inline.
if (!assumeMinimumCapture && hasLocalNames(fnNode)) {
functionState.disallowInlining();
}
}
}
if (fnNode.getGrandparent().isVar()) {
Node block = functionState.getFn().getDeclaringBlock();
if (block.isBlock()
&& !block.getParent().isFunction()
&& (NodeUtil.containsType(block, Token.LET)
|| NodeUtil.containsType(block, Token.CONST))) {
// The function might capture a variable that's not in scope at the call site,
// so don't inline.
functionState.disallowInlining();
}
}
if (fnNode.isGeneratorFunction()) {
functionState.disallowInlining();
}
if (fnNode.isAsyncFunction()) {
functionState.disallowInlining();
}
}
} | [
"void",
"maybeAddFunction",
"(",
"Function",
"fn",
",",
"JSModule",
"module",
")",
"{",
"String",
"name",
"=",
"fn",
".",
"getName",
"(",
")",
";",
"FunctionState",
"functionState",
"=",
"getOrCreateFunctionState",
"(",
"name",
")",
";",
"// TODO(johnlenz): Maybe \"smarten\" FunctionState by adding this logic to it?",
"// If the function has multiple definitions, don't inline it.",
"if",
"(",
"functionState",
".",
"hasExistingFunctionDefinition",
"(",
")",
")",
"{",
"functionState",
".",
"disallowInlining",
"(",
")",
";",
"return",
";",
"}",
"Node",
"fnNode",
"=",
"fn",
".",
"getFunctionNode",
"(",
")",
";",
"if",
"(",
"hasNoInlineAnnotation",
"(",
"fnNode",
")",
")",
"{",
"functionState",
".",
"disallowInlining",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"enforceMaxSizeAfterInlining",
"&&",
"!",
"isAlwaysInlinable",
"(",
"fnNode",
")",
"&&",
"maxSizeAfterInlining",
"<=",
"NodeUtil",
".",
"countAstSizeUpToLimit",
"(",
"fnNode",
",",
"maxSizeAfterInlining",
")",
")",
"{",
"functionState",
".",
"disallowInlining",
"(",
")",
";",
"return",
";",
"}",
"// verify the function hasn't already been marked as \"don't inline\"",
"if",
"(",
"functionState",
".",
"canInline",
"(",
")",
")",
"{",
"// store it for use when inlining.",
"functionState",
".",
"setFn",
"(",
"fn",
")",
";",
"if",
"(",
"FunctionInjector",
".",
"isDirectCallNodeReplacementPossible",
"(",
"fn",
".",
"getFunctionNode",
"(",
")",
")",
")",
"{",
"functionState",
".",
"inlineDirectly",
"(",
"true",
")",
";",
"}",
"if",
"(",
"hasNonInlinableParam",
"(",
"NodeUtil",
".",
"getFunctionParameters",
"(",
"fnNode",
")",
")",
")",
"{",
"functionState",
".",
"disallowInlining",
"(",
")",
";",
"}",
"// verify the function meets all the requirements.",
"// TODO(johnlenz): Minimum requirement checks are about 5% of the",
"// run-time cost of this pass.",
"if",
"(",
"!",
"isCandidateFunction",
"(",
"fn",
")",
")",
"{",
"// It doesn't meet the requirements.",
"functionState",
".",
"disallowInlining",
"(",
")",
";",
"}",
"// Set the module and gather names that need temporaries.",
"if",
"(",
"functionState",
".",
"canInline",
"(",
")",
")",
"{",
"functionState",
".",
"setModule",
"(",
"module",
")",
";",
"Set",
"<",
"String",
">",
"namesToAlias",
"=",
"FunctionArgumentInjector",
".",
"findModifiedParameters",
"(",
"fnNode",
")",
";",
"if",
"(",
"!",
"namesToAlias",
".",
"isEmpty",
"(",
")",
")",
"{",
"functionState",
".",
"inlineDirectly",
"(",
"false",
")",
";",
"functionState",
".",
"setNamesToAlias",
"(",
"namesToAlias",
")",
";",
"}",
"Node",
"block",
"=",
"NodeUtil",
".",
"getFunctionBody",
"(",
"fnNode",
")",
";",
"if",
"(",
"NodeUtil",
".",
"referencesThis",
"(",
"block",
")",
")",
"{",
"functionState",
".",
"setReferencesThis",
"(",
"true",
")",
";",
"}",
"if",
"(",
"NodeUtil",
".",
"containsFunction",
"(",
"block",
")",
")",
"{",
"functionState",
".",
"setHasInnerFunctions",
"(",
"true",
")",
";",
"// If there are inner functions, we can inline into global scope",
"// if there are no local vars or named functions.",
"// TODO(johnlenz): this can be improved by looking at the possible",
"// values for locals. If there are simple values, or constants",
"// we could still inline.",
"if",
"(",
"!",
"assumeMinimumCapture",
"&&",
"hasLocalNames",
"(",
"fnNode",
")",
")",
"{",
"functionState",
".",
"disallowInlining",
"(",
")",
";",
"}",
"}",
"}",
"if",
"(",
"fnNode",
".",
"getGrandparent",
"(",
")",
".",
"isVar",
"(",
")",
")",
"{",
"Node",
"block",
"=",
"functionState",
".",
"getFn",
"(",
")",
".",
"getDeclaringBlock",
"(",
")",
";",
"if",
"(",
"block",
".",
"isBlock",
"(",
")",
"&&",
"!",
"block",
".",
"getParent",
"(",
")",
".",
"isFunction",
"(",
")",
"&&",
"(",
"NodeUtil",
".",
"containsType",
"(",
"block",
",",
"Token",
".",
"LET",
")",
"||",
"NodeUtil",
".",
"containsType",
"(",
"block",
",",
"Token",
".",
"CONST",
")",
")",
")",
"{",
"// The function might capture a variable that's not in scope at the call site,",
"// so don't inline.",
"functionState",
".",
"disallowInlining",
"(",
")",
";",
"}",
"}",
"if",
"(",
"fnNode",
".",
"isGeneratorFunction",
"(",
")",
")",
"{",
"functionState",
".",
"disallowInlining",
"(",
")",
";",
"}",
"if",
"(",
"fnNode",
".",
"isAsyncFunction",
"(",
")",
")",
"{",
"functionState",
".",
"disallowInlining",
"(",
")",
";",
"}",
"}",
"}"
] | Updates the FunctionState object for the given function. Checks if the given function matches
the criteria for an inlinable function. | [
"Updates",
"the",
"FunctionState",
"object",
"for",
"the",
"given",
"function",
".",
"Checks",
"if",
"the",
"given",
"function",
"matches",
"the",
"criteria",
"for",
"an",
"inlinable",
"function",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/InlineFunctions.java#L265-L359 |
24,178 | google/closure-compiler | src/com/google/javascript/jscomp/InlineFunctions.java | InlineFunctions.isCandidateFunction | private boolean isCandidateFunction(Function fn) {
// Don't inline exported functions.
String fnName = fn.getName();
if (compiler.getCodingConvention().isExported(fnName)) {
// TODO(johnlenz): Should we allow internal references to be inlined?
// An exported name can be replaced externally, any inlined instance
// would not reflect this change.
// To allow inlining we need to be able to distinguish between exports
// that are used in a read-only fashion and those that can be replaced
// by external definitions.
return false;
}
// Don't inline this special function
if (compiler.getCodingConvention().isPropertyRenameFunction(fnName)) {
return false;
}
Node fnNode = fn.getFunctionNode();
return injector.doesFunctionMeetMinimumRequirements(fnName, fnNode);
} | java | private boolean isCandidateFunction(Function fn) {
// Don't inline exported functions.
String fnName = fn.getName();
if (compiler.getCodingConvention().isExported(fnName)) {
// TODO(johnlenz): Should we allow internal references to be inlined?
// An exported name can be replaced externally, any inlined instance
// would not reflect this change.
// To allow inlining we need to be able to distinguish between exports
// that are used in a read-only fashion and those that can be replaced
// by external definitions.
return false;
}
// Don't inline this special function
if (compiler.getCodingConvention().isPropertyRenameFunction(fnName)) {
return false;
}
Node fnNode = fn.getFunctionNode();
return injector.doesFunctionMeetMinimumRequirements(fnName, fnNode);
} | [
"private",
"boolean",
"isCandidateFunction",
"(",
"Function",
"fn",
")",
"{",
"// Don't inline exported functions.",
"String",
"fnName",
"=",
"fn",
".",
"getName",
"(",
")",
";",
"if",
"(",
"compiler",
".",
"getCodingConvention",
"(",
")",
".",
"isExported",
"(",
"fnName",
")",
")",
"{",
"// TODO(johnlenz): Should we allow internal references to be inlined?",
"// An exported name can be replaced externally, any inlined instance",
"// would not reflect this change.",
"// To allow inlining we need to be able to distinguish between exports",
"// that are used in a read-only fashion and those that can be replaced",
"// by external definitions.",
"return",
"false",
";",
"}",
"// Don't inline this special function",
"if",
"(",
"compiler",
".",
"getCodingConvention",
"(",
")",
".",
"isPropertyRenameFunction",
"(",
"fnName",
")",
")",
"{",
"return",
"false",
";",
"}",
"Node",
"fnNode",
"=",
"fn",
".",
"getFunctionNode",
"(",
")",
";",
"return",
"injector",
".",
"doesFunctionMeetMinimumRequirements",
"(",
"fnName",
",",
"fnNode",
")",
";",
"}"
] | Checks if the given function matches the criteria for an inlinable function. | [
"Checks",
"if",
"the",
"given",
"function",
"matches",
"the",
"criteria",
"for",
"an",
"inlinable",
"function",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/InlineFunctions.java#L378-L398 |
24,179 | google/closure-compiler | src/com/google/javascript/jscomp/InlineFunctions.java | InlineFunctions.trimCandidatesNotMeetingMinimumRequirements | private void trimCandidatesNotMeetingMinimumRequirements() {
Iterator<Entry<String, FunctionState>> i;
for (i = fns.entrySet().iterator(); i.hasNext(); ) {
FunctionState functionState = i.next().getValue();
if (!functionState.hasExistingFunctionDefinition() || !functionState.canInline()) {
i.remove();
}
}
} | java | private void trimCandidatesNotMeetingMinimumRequirements() {
Iterator<Entry<String, FunctionState>> i;
for (i = fns.entrySet().iterator(); i.hasNext(); ) {
FunctionState functionState = i.next().getValue();
if (!functionState.hasExistingFunctionDefinition() || !functionState.canInline()) {
i.remove();
}
}
} | [
"private",
"void",
"trimCandidatesNotMeetingMinimumRequirements",
"(",
")",
"{",
"Iterator",
"<",
"Entry",
"<",
"String",
",",
"FunctionState",
">",
">",
"i",
";",
"for",
"(",
"i",
"=",
"fns",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"i",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"FunctionState",
"functionState",
"=",
"i",
".",
"next",
"(",
")",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"!",
"functionState",
".",
"hasExistingFunctionDefinition",
"(",
")",
"||",
"!",
"functionState",
".",
"canInline",
"(",
")",
")",
"{",
"i",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}"
] | Remove entries that aren't a valid inline candidates, from the list of encountered names. | [
"Remove",
"entries",
"that",
"aren",
"t",
"a",
"valid",
"inline",
"candidates",
"from",
"the",
"list",
"of",
"encountered",
"names",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/InlineFunctions.java#L638-L646 |
24,180 | google/closure-compiler | src/com/google/javascript/jscomp/InlineFunctions.java | InlineFunctions.trimCandidatesUsingOnCost | private void trimCandidatesUsingOnCost() {
Iterator<Entry<String, FunctionState>> i;
for (i = fns.entrySet().iterator(); i.hasNext(); ) {
FunctionState functionState = i.next().getValue();
if (functionState.hasReferences()) {
// Only inline function if it decreases the code size.
boolean lowersCost = minimizeCost(functionState);
if (!lowersCost) {
// It shouldn't be inlined; remove it from the list.
i.remove();
}
} else if (!functionState.canRemove()) {
// Don't bother tracking functions without references that can't be
// removed.
i.remove();
}
}
} | java | private void trimCandidatesUsingOnCost() {
Iterator<Entry<String, FunctionState>> i;
for (i = fns.entrySet().iterator(); i.hasNext(); ) {
FunctionState functionState = i.next().getValue();
if (functionState.hasReferences()) {
// Only inline function if it decreases the code size.
boolean lowersCost = minimizeCost(functionState);
if (!lowersCost) {
// It shouldn't be inlined; remove it from the list.
i.remove();
}
} else if (!functionState.canRemove()) {
// Don't bother tracking functions without references that can't be
// removed.
i.remove();
}
}
} | [
"private",
"void",
"trimCandidatesUsingOnCost",
"(",
")",
"{",
"Iterator",
"<",
"Entry",
"<",
"String",
",",
"FunctionState",
">",
">",
"i",
";",
"for",
"(",
"i",
"=",
"fns",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"i",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"FunctionState",
"functionState",
"=",
"i",
".",
"next",
"(",
")",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"functionState",
".",
"hasReferences",
"(",
")",
")",
"{",
"// Only inline function if it decreases the code size.",
"boolean",
"lowersCost",
"=",
"minimizeCost",
"(",
"functionState",
")",
";",
"if",
"(",
"!",
"lowersCost",
")",
"{",
"// It shouldn't be inlined; remove it from the list.",
"i",
".",
"remove",
"(",
")",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"functionState",
".",
"canRemove",
"(",
")",
")",
"{",
"// Don't bother tracking functions without references that can't be",
"// removed.",
"i",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}"
] | Remove entries from the list of candidates that can't be inlined. | [
"Remove",
"entries",
"from",
"the",
"list",
"of",
"candidates",
"that",
"can",
"t",
"be",
"inlined",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/InlineFunctions.java#L649-L666 |
24,181 | google/closure-compiler | src/com/google/javascript/jscomp/InlineFunctions.java | InlineFunctions.minimizeCost | private boolean minimizeCost(FunctionState functionState) {
if (!inliningLowersCost(functionState)) {
// Try again without Block inlining references
if (functionState.hasBlockInliningReferences()) {
functionState.setRemove(false);
functionState.removeBlockInliningReferences();
if (!functionState.hasReferences() || !inliningLowersCost(functionState)) {
return false;
}
} else {
return false;
}
}
return true;
} | java | private boolean minimizeCost(FunctionState functionState) {
if (!inliningLowersCost(functionState)) {
// Try again without Block inlining references
if (functionState.hasBlockInliningReferences()) {
functionState.setRemove(false);
functionState.removeBlockInliningReferences();
if (!functionState.hasReferences() || !inliningLowersCost(functionState)) {
return false;
}
} else {
return false;
}
}
return true;
} | [
"private",
"boolean",
"minimizeCost",
"(",
"FunctionState",
"functionState",
")",
"{",
"if",
"(",
"!",
"inliningLowersCost",
"(",
"functionState",
")",
")",
"{",
"// Try again without Block inlining references",
"if",
"(",
"functionState",
".",
"hasBlockInliningReferences",
"(",
")",
")",
"{",
"functionState",
".",
"setRemove",
"(",
"false",
")",
";",
"functionState",
".",
"removeBlockInliningReferences",
"(",
")",
";",
"if",
"(",
"!",
"functionState",
".",
"hasReferences",
"(",
")",
"||",
"!",
"inliningLowersCost",
"(",
"functionState",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Determines if the function is worth inlining and potentially trims references that increase the
cost.
@return Whether inlining the references lowers the overall cost. | [
"Determines",
"if",
"the",
"function",
"is",
"worth",
"inlining",
"and",
"potentially",
"trims",
"references",
"that",
"increase",
"the",
"cost",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/InlineFunctions.java#L674-L688 |
24,182 | google/closure-compiler | src/com/google/javascript/jscomp/InlineFunctions.java | InlineFunctions.findCalledFunctions | private Set<String> findCalledFunctions(Node node) {
Set<String> changed = new HashSet<>();
findCalledFunctions(NodeUtil.getFunctionBody(node), changed);
return changed;
} | java | private Set<String> findCalledFunctions(Node node) {
Set<String> changed = new HashSet<>();
findCalledFunctions(NodeUtil.getFunctionBody(node), changed);
return changed;
} | [
"private",
"Set",
"<",
"String",
">",
"findCalledFunctions",
"(",
"Node",
"node",
")",
"{",
"Set",
"<",
"String",
">",
"changed",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"findCalledFunctions",
"(",
"NodeUtil",
".",
"getFunctionBody",
"(",
"node",
")",
",",
"changed",
")",
";",
"return",
"changed",
";",
"}"
] | This functions that may be called directly. | [
"This",
"functions",
"that",
"may",
"be",
"called",
"directly",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/InlineFunctions.java#L767-L771 |
24,183 | google/closure-compiler | src/com/google/javascript/jscomp/InlineFunctions.java | InlineFunctions.decomposeExpressions | private void decomposeExpressions() {
for (FunctionState functionState : fns.values()) {
if (functionState.canInline()) {
for (Reference ref : functionState.getReferences()) {
if (ref.requiresDecomposition) {
injector.maybePrepareCall(ref);
}
}
}
}
} | java | private void decomposeExpressions() {
for (FunctionState functionState : fns.values()) {
if (functionState.canInline()) {
for (Reference ref : functionState.getReferences()) {
if (ref.requiresDecomposition) {
injector.maybePrepareCall(ref);
}
}
}
}
} | [
"private",
"void",
"decomposeExpressions",
"(",
")",
"{",
"for",
"(",
"FunctionState",
"functionState",
":",
"fns",
".",
"values",
"(",
")",
")",
"{",
"if",
"(",
"functionState",
".",
"canInline",
"(",
")",
")",
"{",
"for",
"(",
"Reference",
"ref",
":",
"functionState",
".",
"getReferences",
"(",
")",
")",
"{",
"if",
"(",
"ref",
".",
"requiresDecomposition",
")",
"{",
"injector",
".",
"maybePrepareCall",
"(",
"ref",
")",
";",
"}",
"}",
"}",
"}",
"}"
] | For any call-site that needs it, prepare the call-site for inlining by rewriting the containing
expression. | [
"For",
"any",
"call",
"-",
"site",
"that",
"needs",
"it",
"prepare",
"the",
"call",
"-",
"site",
"for",
"inlining",
"by",
"rewriting",
"the",
"containing",
"expression",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/InlineFunctions.java#L790-L800 |
24,184 | google/closure-compiler | src/com/google/javascript/jscomp/InlineFunctions.java | InlineFunctions.removeInlinedFunctions | void removeInlinedFunctions() {
for (Map.Entry<String, FunctionState> entry : fns.entrySet()) {
String name = entry.getKey();
FunctionState functionState = entry.getValue();
if (functionState.canRemove()) {
Function fn = functionState.getFn();
checkState(functionState.canInline());
checkState(fn != null);
verifyAllReferencesInlined(name, functionState);
fn.remove();
NodeUtil.markFunctionsDeleted(fn.getFunctionNode(), compiler);
}
}
} | java | void removeInlinedFunctions() {
for (Map.Entry<String, FunctionState> entry : fns.entrySet()) {
String name = entry.getKey();
FunctionState functionState = entry.getValue();
if (functionState.canRemove()) {
Function fn = functionState.getFn();
checkState(functionState.canInline());
checkState(fn != null);
verifyAllReferencesInlined(name, functionState);
fn.remove();
NodeUtil.markFunctionsDeleted(fn.getFunctionNode(), compiler);
}
}
} | [
"void",
"removeInlinedFunctions",
"(",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"FunctionState",
">",
"entry",
":",
"fns",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"name",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"FunctionState",
"functionState",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"functionState",
".",
"canRemove",
"(",
")",
")",
"{",
"Function",
"fn",
"=",
"functionState",
".",
"getFn",
"(",
")",
";",
"checkState",
"(",
"functionState",
".",
"canInline",
"(",
")",
")",
";",
"checkState",
"(",
"fn",
"!=",
"null",
")",
";",
"verifyAllReferencesInlined",
"(",
"name",
",",
"functionState",
")",
";",
"fn",
".",
"remove",
"(",
")",
";",
"NodeUtil",
".",
"markFunctionsDeleted",
"(",
"fn",
".",
"getFunctionNode",
"(",
")",
",",
"compiler",
")",
";",
"}",
"}",
"}"
] | Removed inlined functions that no longer have any references. | [
"Removed",
"inlined",
"functions",
"that",
"no",
"longer",
"have",
"any",
"references",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/InlineFunctions.java#L803-L816 |
24,185 | google/closure-compiler | src/com/google/javascript/jscomp/InlineFunctions.java | InlineFunctions.verifyAllReferencesInlined | void verifyAllReferencesInlined(String name, FunctionState functionState) {
for (Reference ref : functionState.getReferences()) {
if (!ref.inlined) {
Node parent = ref.callNode.getParent();
throw new IllegalStateException(
"Call site missed ("
+ name
+ ").\n call: "
+ ref.callNode.toStringTree()
+ "\n parent: "
+ ((parent == null) ? "null" : parent.toStringTree()));
}
}
} | java | void verifyAllReferencesInlined(String name, FunctionState functionState) {
for (Reference ref : functionState.getReferences()) {
if (!ref.inlined) {
Node parent = ref.callNode.getParent();
throw new IllegalStateException(
"Call site missed ("
+ name
+ ").\n call: "
+ ref.callNode.toStringTree()
+ "\n parent: "
+ ((parent == null) ? "null" : parent.toStringTree()));
}
}
} | [
"void",
"verifyAllReferencesInlined",
"(",
"String",
"name",
",",
"FunctionState",
"functionState",
")",
"{",
"for",
"(",
"Reference",
"ref",
":",
"functionState",
".",
"getReferences",
"(",
")",
")",
"{",
"if",
"(",
"!",
"ref",
".",
"inlined",
")",
"{",
"Node",
"parent",
"=",
"ref",
".",
"callNode",
".",
"getParent",
"(",
")",
";",
"throw",
"new",
"IllegalStateException",
"(",
"\"Call site missed (\"",
"+",
"name",
"+",
"\").\\n call: \"",
"+",
"ref",
".",
"callNode",
".",
"toStringTree",
"(",
")",
"+",
"\"\\n parent: \"",
"+",
"(",
"(",
"parent",
"==",
"null",
")",
"?",
"\"null\"",
":",
"parent",
".",
"toStringTree",
"(",
")",
")",
")",
";",
"}",
"}",
"}"
] | Check to verify that expression rewriting didn't make a call inaccessible. | [
"Check",
"to",
"verify",
"that",
"expression",
"rewriting",
"didn",
"t",
"make",
"a",
"call",
"inaccessible",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/InlineFunctions.java#L819-L832 |
24,186 | google/closure-compiler | src/com/google/javascript/jscomp/DiagnosticType.java | DiagnosticType.error | public static DiagnosticType error(String name, String descriptionFormat) {
return make(name, CheckLevel.ERROR, descriptionFormat);
} | java | public static DiagnosticType error(String name, String descriptionFormat) {
return make(name, CheckLevel.ERROR, descriptionFormat);
} | [
"public",
"static",
"DiagnosticType",
"error",
"(",
"String",
"name",
",",
"String",
"descriptionFormat",
")",
"{",
"return",
"make",
"(",
"name",
",",
"CheckLevel",
".",
"ERROR",
",",
"descriptionFormat",
")",
";",
"}"
] | Create a DiagnosticType at level CheckLevel.ERROR
@param name An identifier
@param descriptionFormat A format string
@return A new DiagnosticType | [
"Create",
"a",
"DiagnosticType",
"at",
"level",
"CheckLevel",
".",
"ERROR"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DiagnosticType.java#L49-L51 |
24,187 | google/closure-compiler | src/com/google/javascript/jscomp/DiagnosticType.java | DiagnosticType.warning | public static DiagnosticType warning(String name, String descriptionFormat) {
return make(name, CheckLevel.WARNING, descriptionFormat);
} | java | public static DiagnosticType warning(String name, String descriptionFormat) {
return make(name, CheckLevel.WARNING, descriptionFormat);
} | [
"public",
"static",
"DiagnosticType",
"warning",
"(",
"String",
"name",
",",
"String",
"descriptionFormat",
")",
"{",
"return",
"make",
"(",
"name",
",",
"CheckLevel",
".",
"WARNING",
",",
"descriptionFormat",
")",
";",
"}"
] | Create a DiagnosticType at level CheckLevel.WARNING
@param name An identifier
@param descriptionFormat A format string
@return A new DiagnosticType | [
"Create",
"a",
"DiagnosticType",
"at",
"level",
"CheckLevel",
".",
"WARNING"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DiagnosticType.java#L60-L62 |
24,188 | google/closure-compiler | src/com/google/javascript/jscomp/DiagnosticType.java | DiagnosticType.disabled | public static DiagnosticType disabled(String name,
String descriptionFormat) {
return make(name, CheckLevel.OFF, descriptionFormat);
} | java | public static DiagnosticType disabled(String name,
String descriptionFormat) {
return make(name, CheckLevel.OFF, descriptionFormat);
} | [
"public",
"static",
"DiagnosticType",
"disabled",
"(",
"String",
"name",
",",
"String",
"descriptionFormat",
")",
"{",
"return",
"make",
"(",
"name",
",",
"CheckLevel",
".",
"OFF",
",",
"descriptionFormat",
")",
";",
"}"
] | Create a DiagnosticType at level CheckLevel.OFF
@param name An identifier
@param descriptionFormat A format string
@return A new DiagnosticType | [
"Create",
"a",
"DiagnosticType",
"at",
"level",
"CheckLevel",
".",
"OFF"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DiagnosticType.java#L71-L74 |
24,189 | google/closure-compiler | src/com/google/javascript/jscomp/DiagnosticType.java | DiagnosticType.make | public static DiagnosticType make(String name, CheckLevel level,
String descriptionFormat) {
return
new DiagnosticType(name, level, new MessageFormat(descriptionFormat));
} | java | public static DiagnosticType make(String name, CheckLevel level,
String descriptionFormat) {
return
new DiagnosticType(name, level, new MessageFormat(descriptionFormat));
} | [
"public",
"static",
"DiagnosticType",
"make",
"(",
"String",
"name",
",",
"CheckLevel",
"level",
",",
"String",
"descriptionFormat",
")",
"{",
"return",
"new",
"DiagnosticType",
"(",
"name",
",",
"level",
",",
"new",
"MessageFormat",
"(",
"descriptionFormat",
")",
")",
";",
"}"
] | Create a DiagnosticType at a given CheckLevel.
@param name An identifier
@param level Either CheckLevel.ERROR or CheckLevel.WARNING
@param descriptionFormat A format string
@return A new DiagnosticType | [
"Create",
"a",
"DiagnosticType",
"at",
"a",
"given",
"CheckLevel",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DiagnosticType.java#L84-L88 |
24,190 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInferencePass.java | TypeInferencePass.process | @Override
public void process(Node externsRoot, Node jsRoot) {
Node externsAndJs = jsRoot.getParent();
checkState(externsAndJs != null);
checkState(externsRoot == null || externsAndJs.hasChild(externsRoot));
inferAllScopes(externsAndJs);
} | java | @Override
public void process(Node externsRoot, Node jsRoot) {
Node externsAndJs = jsRoot.getParent();
checkState(externsAndJs != null);
checkState(externsRoot == null || externsAndJs.hasChild(externsRoot));
inferAllScopes(externsAndJs);
} | [
"@",
"Override",
"public",
"void",
"process",
"(",
"Node",
"externsRoot",
",",
"Node",
"jsRoot",
")",
"{",
"Node",
"externsAndJs",
"=",
"jsRoot",
".",
"getParent",
"(",
")",
";",
"checkState",
"(",
"externsAndJs",
"!=",
"null",
")",
";",
"checkState",
"(",
"externsRoot",
"==",
"null",
"||",
"externsAndJs",
".",
"hasChild",
"(",
"externsRoot",
")",
")",
";",
"inferAllScopes",
"(",
"externsAndJs",
")",
";",
"}"
] | Main entry point for type inference when running over the whole tree.
@param externsRoot The root of the externs parse tree.
@param jsRoot The root of the input parse tree to be checked. | [
"Main",
"entry",
"point",
"for",
"type",
"inference",
"when",
"running",
"over",
"the",
"whole",
"tree",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInferencePass.java#L61-L68 |
24,191 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInferencePass.java | TypeInferencePass.inferAllScopes | void inferAllScopes(Node node) {
// Type analysis happens in two major phases.
// 1) Finding all the symbols.
// 2) Propagating all the inferred types.
//
// The order of this analysis is non-obvious. In a complete inference
// system, we may need to backtrack arbitrarily far. But the compile-time
// costs would be unacceptable.
//
// We do one pass where we do typed scope creation for all scopes
// in pre-order.
//
// Then we do a second pass where we do all type inference
// (type propagation) in pre-order.
//
// We use a memoized scope creator so that we never create a scope
// more than once.
//
// This will allow us to handle cases like:
// var ns = {};
// (function() { /** JSDoc */ ns.method = function() {}; })();
// ns.method();
// In this code, we need to build the symbol table for the inner scope in
// order to propagate the type of ns.method in the outer scope.
(new NodeTraversal(
compiler, new FirstScopeBuildingCallback(), scopeCreator))
.traverseWithScope(node, topScope);
scopeCreator.resolveTypes();
(new NodeTraversal(
compiler, new SecondScopeBuildingCallback(), scopeCreator))
.traverseWithScope(node, topScope);
// Resolve any new type names found during the inference.
// This runs for nested block scopes after infer runs on the CFG root.
compiler.getTypeRegistry().resolveTypes();
} | java | void inferAllScopes(Node node) {
// Type analysis happens in two major phases.
// 1) Finding all the symbols.
// 2) Propagating all the inferred types.
//
// The order of this analysis is non-obvious. In a complete inference
// system, we may need to backtrack arbitrarily far. But the compile-time
// costs would be unacceptable.
//
// We do one pass where we do typed scope creation for all scopes
// in pre-order.
//
// Then we do a second pass where we do all type inference
// (type propagation) in pre-order.
//
// We use a memoized scope creator so that we never create a scope
// more than once.
//
// This will allow us to handle cases like:
// var ns = {};
// (function() { /** JSDoc */ ns.method = function() {}; })();
// ns.method();
// In this code, we need to build the symbol table for the inner scope in
// order to propagate the type of ns.method in the outer scope.
(new NodeTraversal(
compiler, new FirstScopeBuildingCallback(), scopeCreator))
.traverseWithScope(node, topScope);
scopeCreator.resolveTypes();
(new NodeTraversal(
compiler, new SecondScopeBuildingCallback(), scopeCreator))
.traverseWithScope(node, topScope);
// Resolve any new type names found during the inference.
// This runs for nested block scopes after infer runs on the CFG root.
compiler.getTypeRegistry().resolveTypes();
} | [
"void",
"inferAllScopes",
"(",
"Node",
"node",
")",
"{",
"// Type analysis happens in two major phases.",
"// 1) Finding all the symbols.",
"// 2) Propagating all the inferred types.",
"//",
"// The order of this analysis is non-obvious. In a complete inference",
"// system, we may need to backtrack arbitrarily far. But the compile-time",
"// costs would be unacceptable.",
"//",
"// We do one pass where we do typed scope creation for all scopes",
"// in pre-order.",
"//",
"// Then we do a second pass where we do all type inference",
"// (type propagation) in pre-order.",
"//",
"// We use a memoized scope creator so that we never create a scope",
"// more than once.",
"//",
"// This will allow us to handle cases like:",
"// var ns = {};",
"// (function() { /** JSDoc */ ns.method = function() {}; })();",
"// ns.method();",
"// In this code, we need to build the symbol table for the inner scope in",
"// order to propagate the type of ns.method in the outer scope.",
"(",
"new",
"NodeTraversal",
"(",
"compiler",
",",
"new",
"FirstScopeBuildingCallback",
"(",
")",
",",
"scopeCreator",
")",
")",
".",
"traverseWithScope",
"(",
"node",
",",
"topScope",
")",
";",
"scopeCreator",
".",
"resolveTypes",
"(",
")",
";",
"(",
"new",
"NodeTraversal",
"(",
"compiler",
",",
"new",
"SecondScopeBuildingCallback",
"(",
")",
",",
"scopeCreator",
")",
")",
".",
"traverseWithScope",
"(",
"node",
",",
"topScope",
")",
";",
"// Resolve any new type names found during the inference.",
"// This runs for nested block scopes after infer runs on the CFG root.",
"compiler",
".",
"getTypeRegistry",
"(",
")",
".",
"resolveTypes",
"(",
")",
";",
"}"
] | Entry point for type inference when running over part of the tree. | [
"Entry",
"point",
"for",
"type",
"inference",
"when",
"running",
"over",
"part",
"of",
"the",
"tree",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInferencePass.java#L71-L108 |
24,192 | google/closure-compiler | src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java | PeepholeMinimizeConditions.optimizeSubtree | @Override
@SuppressWarnings("fallthrough")
public Node optimizeSubtree(Node node) {
switch (node.getToken()) {
case THROW:
case RETURN: {
Node result = tryRemoveRedundantExit(node);
if (result != node) {
return result;
}
return tryReplaceExitWithBreak(node);
}
// TODO(johnlenz): Maybe remove redundant BREAK and CONTINUE. Overlaps
// with MinimizeExitPoints.
case NOT:
tryMinimizeCondition(node.getFirstChild());
return tryMinimizeNot(node);
case IF:
performConditionSubstitutions(node.getFirstChild());
return tryMinimizeIf(node);
case EXPR_RESULT:
performConditionSubstitutions(node.getFirstChild());
return tryMinimizeExprResult(node);
case HOOK:
performConditionSubstitutions(node.getFirstChild());
return tryMinimizeHook(node);
case WHILE:
case DO:
tryMinimizeCondition(NodeUtil.getConditionExpression(node));
return node;
case FOR:
tryJoinForCondition(node);
tryMinimizeCondition(NodeUtil.getConditionExpression(node));
return node;
case BLOCK:
return tryReplaceIf(node);
default:
return node; //Nothing changed
}
} | java | @Override
@SuppressWarnings("fallthrough")
public Node optimizeSubtree(Node node) {
switch (node.getToken()) {
case THROW:
case RETURN: {
Node result = tryRemoveRedundantExit(node);
if (result != node) {
return result;
}
return tryReplaceExitWithBreak(node);
}
// TODO(johnlenz): Maybe remove redundant BREAK and CONTINUE. Overlaps
// with MinimizeExitPoints.
case NOT:
tryMinimizeCondition(node.getFirstChild());
return tryMinimizeNot(node);
case IF:
performConditionSubstitutions(node.getFirstChild());
return tryMinimizeIf(node);
case EXPR_RESULT:
performConditionSubstitutions(node.getFirstChild());
return tryMinimizeExprResult(node);
case HOOK:
performConditionSubstitutions(node.getFirstChild());
return tryMinimizeHook(node);
case WHILE:
case DO:
tryMinimizeCondition(NodeUtil.getConditionExpression(node));
return node;
case FOR:
tryJoinForCondition(node);
tryMinimizeCondition(NodeUtil.getConditionExpression(node));
return node;
case BLOCK:
return tryReplaceIf(node);
default:
return node; //Nothing changed
}
} | [
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"fallthrough\"",
")",
"public",
"Node",
"optimizeSubtree",
"(",
"Node",
"node",
")",
"{",
"switch",
"(",
"node",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"THROW",
":",
"case",
"RETURN",
":",
"{",
"Node",
"result",
"=",
"tryRemoveRedundantExit",
"(",
"node",
")",
";",
"if",
"(",
"result",
"!=",
"node",
")",
"{",
"return",
"result",
";",
"}",
"return",
"tryReplaceExitWithBreak",
"(",
"node",
")",
";",
"}",
"// TODO(johnlenz): Maybe remove redundant BREAK and CONTINUE. Overlaps",
"// with MinimizeExitPoints.",
"case",
"NOT",
":",
"tryMinimizeCondition",
"(",
"node",
".",
"getFirstChild",
"(",
")",
")",
";",
"return",
"tryMinimizeNot",
"(",
"node",
")",
";",
"case",
"IF",
":",
"performConditionSubstitutions",
"(",
"node",
".",
"getFirstChild",
"(",
")",
")",
";",
"return",
"tryMinimizeIf",
"(",
"node",
")",
";",
"case",
"EXPR_RESULT",
":",
"performConditionSubstitutions",
"(",
"node",
".",
"getFirstChild",
"(",
")",
")",
";",
"return",
"tryMinimizeExprResult",
"(",
"node",
")",
";",
"case",
"HOOK",
":",
"performConditionSubstitutions",
"(",
"node",
".",
"getFirstChild",
"(",
")",
")",
";",
"return",
"tryMinimizeHook",
"(",
"node",
")",
";",
"case",
"WHILE",
":",
"case",
"DO",
":",
"tryMinimizeCondition",
"(",
"NodeUtil",
".",
"getConditionExpression",
"(",
"node",
")",
")",
";",
"return",
"node",
";",
"case",
"FOR",
":",
"tryJoinForCondition",
"(",
"node",
")",
";",
"tryMinimizeCondition",
"(",
"NodeUtil",
".",
"getConditionExpression",
"(",
"node",
")",
")",
";",
"return",
"node",
";",
"case",
"BLOCK",
":",
"return",
"tryReplaceIf",
"(",
"node",
")",
";",
"default",
":",
"return",
"node",
";",
"//Nothing changed",
"}",
"}"
] | Tries to apply our various peephole minimizations on the passed in node. | [
"Tries",
"to",
"apply",
"our",
"various",
"peephole",
"minimizations",
"on",
"the",
"passed",
"in",
"node",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java#L60-L108 |
24,193 | google/closure-compiler | src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java | PeepholeMinimizeConditions.tryMinimizeExprResult | private Node tryMinimizeExprResult(Node n) {
Node originalExpr = n.getFirstChild();
MinimizedCondition minCond = MinimizedCondition.fromConditionNode(originalExpr);
MeasuredNode mNode =
minCond.getMinimized(MinimizationStyle.ALLOW_LEADING_NOT);
if (mNode.isNot()) {
// Remove the leading NOT in the EXPR_RESULT.
replaceNode(originalExpr, mNode.withoutNot());
} else {
replaceNode(originalExpr, mNode);
}
return n;
} | java | private Node tryMinimizeExprResult(Node n) {
Node originalExpr = n.getFirstChild();
MinimizedCondition minCond = MinimizedCondition.fromConditionNode(originalExpr);
MeasuredNode mNode =
minCond.getMinimized(MinimizationStyle.ALLOW_LEADING_NOT);
if (mNode.isNot()) {
// Remove the leading NOT in the EXPR_RESULT.
replaceNode(originalExpr, mNode.withoutNot());
} else {
replaceNode(originalExpr, mNode);
}
return n;
} | [
"private",
"Node",
"tryMinimizeExprResult",
"(",
"Node",
"n",
")",
"{",
"Node",
"originalExpr",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"MinimizedCondition",
"minCond",
"=",
"MinimizedCondition",
".",
"fromConditionNode",
"(",
"originalExpr",
")",
";",
"MeasuredNode",
"mNode",
"=",
"minCond",
".",
"getMinimized",
"(",
"MinimizationStyle",
".",
"ALLOW_LEADING_NOT",
")",
";",
"if",
"(",
"mNode",
".",
"isNot",
"(",
")",
")",
"{",
"// Remove the leading NOT in the EXPR_RESULT.",
"replaceNode",
"(",
"originalExpr",
",",
"mNode",
".",
"withoutNot",
"(",
")",
")",
";",
"}",
"else",
"{",
"replaceNode",
"(",
"originalExpr",
",",
"mNode",
")",
";",
"}",
"return",
"n",
";",
"}"
] | Try to remove leading NOTs from EXPR_RESULTS.
Returns the replacement for n or the original if no replacement was
necessary. | [
"Try",
"to",
"remove",
"leading",
"NOTs",
"from",
"EXPR_RESULTS",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java#L444-L456 |
24,194 | google/closure-compiler | src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java | PeepholeMinimizeConditions.tryMinimizeHook | private Node tryMinimizeHook(Node n) {
Node originalCond = n.getFirstChild();
MinimizedCondition minCond = MinimizedCondition.fromConditionNode(originalCond);
MeasuredNode mNode =
minCond.getMinimized(MinimizationStyle.ALLOW_LEADING_NOT);
if (mNode.isNot()) {
// Swap the HOOK
Node thenBranch = n.getSecondChild();
replaceNode(originalCond, mNode.withoutNot());
n.removeChild(thenBranch);
n.addChildToBack(thenBranch);
reportChangeToEnclosingScope(n);
} else {
replaceNode(originalCond, mNode);
}
return n;
} | java | private Node tryMinimizeHook(Node n) {
Node originalCond = n.getFirstChild();
MinimizedCondition minCond = MinimizedCondition.fromConditionNode(originalCond);
MeasuredNode mNode =
minCond.getMinimized(MinimizationStyle.ALLOW_LEADING_NOT);
if (mNode.isNot()) {
// Swap the HOOK
Node thenBranch = n.getSecondChild();
replaceNode(originalCond, mNode.withoutNot());
n.removeChild(thenBranch);
n.addChildToBack(thenBranch);
reportChangeToEnclosingScope(n);
} else {
replaceNode(originalCond, mNode);
}
return n;
} | [
"private",
"Node",
"tryMinimizeHook",
"(",
"Node",
"n",
")",
"{",
"Node",
"originalCond",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"MinimizedCondition",
"minCond",
"=",
"MinimizedCondition",
".",
"fromConditionNode",
"(",
"originalCond",
")",
";",
"MeasuredNode",
"mNode",
"=",
"minCond",
".",
"getMinimized",
"(",
"MinimizationStyle",
".",
"ALLOW_LEADING_NOT",
")",
";",
"if",
"(",
"mNode",
".",
"isNot",
"(",
")",
")",
"{",
"// Swap the HOOK",
"Node",
"thenBranch",
"=",
"n",
".",
"getSecondChild",
"(",
")",
";",
"replaceNode",
"(",
"originalCond",
",",
"mNode",
".",
"withoutNot",
"(",
")",
")",
";",
"n",
".",
"removeChild",
"(",
"thenBranch",
")",
";",
"n",
".",
"addChildToBack",
"(",
"thenBranch",
")",
";",
"reportChangeToEnclosingScope",
"(",
"n",
")",
";",
"}",
"else",
"{",
"replaceNode",
"(",
"originalCond",
",",
"mNode",
")",
";",
"}",
"return",
"n",
";",
"}"
] | Try flipping HOOKs that have negated conditions.
Returns the replacement for n or the original if no replacement was
necessary. | [
"Try",
"flipping",
"HOOKs",
"that",
"have",
"negated",
"conditions",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java#L464-L480 |
24,195 | google/closure-compiler | src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java | PeepholeMinimizeConditions.consumesDanglingElse | private static boolean consumesDanglingElse(Node n) {
while (true) {
switch (n.getToken()) {
case IF:
if (n.getChildCount() < 3) {
return true;
}
// This IF node has no else clause.
n = n.getLastChild();
continue;
case BLOCK:
if (!n.hasOneChild()) {
return false;
}
// This BLOCK has no curly braces.
n = n.getLastChild();
continue;
case WITH:
case WHILE:
case FOR:
case FOR_IN:
n = n.getLastChild();
continue;
default:
return false;
}
}
} | java | private static boolean consumesDanglingElse(Node n) {
while (true) {
switch (n.getToken()) {
case IF:
if (n.getChildCount() < 3) {
return true;
}
// This IF node has no else clause.
n = n.getLastChild();
continue;
case BLOCK:
if (!n.hasOneChild()) {
return false;
}
// This BLOCK has no curly braces.
n = n.getLastChild();
continue;
case WITH:
case WHILE:
case FOR:
case FOR_IN:
n = n.getLastChild();
continue;
default:
return false;
}
}
} | [
"private",
"static",
"boolean",
"consumesDanglingElse",
"(",
"Node",
"n",
")",
"{",
"while",
"(",
"true",
")",
"{",
"switch",
"(",
"n",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"IF",
":",
"if",
"(",
"n",
".",
"getChildCount",
"(",
")",
"<",
"3",
")",
"{",
"return",
"true",
";",
"}",
"// This IF node has no else clause.",
"n",
"=",
"n",
".",
"getLastChild",
"(",
")",
";",
"continue",
";",
"case",
"BLOCK",
":",
"if",
"(",
"!",
"n",
".",
"hasOneChild",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// This BLOCK has no curly braces.",
"n",
"=",
"n",
".",
"getLastChild",
"(",
")",
";",
"continue",
";",
"case",
"WITH",
":",
"case",
"WHILE",
":",
"case",
"FOR",
":",
"case",
"FOR_IN",
":",
"n",
"=",
"n",
".",
"getLastChild",
"(",
")",
";",
"continue",
";",
"default",
":",
"return",
"false",
";",
"}",
"}",
"}"
] | Does a statement consume a 'dangling else'? A statement consumes
a 'dangling else' if an 'else' token following the statement
would be considered by the parser to be part of the statement. | [
"Does",
"a",
"statement",
"consume",
"a",
"dangling",
"else",
"?",
"A",
"statement",
"consumes",
"a",
"dangling",
"else",
"if",
"an",
"else",
"token",
"following",
"the",
"statement",
"would",
"be",
"considered",
"by",
"the",
"parser",
"to",
"be",
"part",
"of",
"the",
"statement",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java#L915-L942 |
24,196 | google/closure-compiler | src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java | PeepholeMinimizeConditions.isPropertyAssignmentInExpression | private static boolean isPropertyAssignmentInExpression(Node n) {
Predicate<Node> isPropertyAssignmentInExpressionPredicate =
new Predicate<Node>() {
@Override
public boolean apply(Node input) {
return (input.isGetProp()
&& input.getParent().isAssign());
}
};
return NodeUtil.has(n, isPropertyAssignmentInExpressionPredicate,
NodeUtil.MATCH_NOT_FUNCTION);
} | java | private static boolean isPropertyAssignmentInExpression(Node n) {
Predicate<Node> isPropertyAssignmentInExpressionPredicate =
new Predicate<Node>() {
@Override
public boolean apply(Node input) {
return (input.isGetProp()
&& input.getParent().isAssign());
}
};
return NodeUtil.has(n, isPropertyAssignmentInExpressionPredicate,
NodeUtil.MATCH_NOT_FUNCTION);
} | [
"private",
"static",
"boolean",
"isPropertyAssignmentInExpression",
"(",
"Node",
"n",
")",
"{",
"Predicate",
"<",
"Node",
">",
"isPropertyAssignmentInExpressionPredicate",
"=",
"new",
"Predicate",
"<",
"Node",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"Node",
"input",
")",
"{",
"return",
"(",
"input",
".",
"isGetProp",
"(",
")",
"&&",
"input",
".",
"getParent",
"(",
")",
".",
"isAssign",
"(",
")",
")",
";",
"}",
"}",
";",
"return",
"NodeUtil",
".",
"has",
"(",
"n",
",",
"isPropertyAssignmentInExpressionPredicate",
",",
"NodeUtil",
".",
"MATCH_NOT_FUNCTION",
")",
";",
"}"
] | Does the expression contain a property assignment? | [
"Does",
"the",
"expression",
"contain",
"a",
"property",
"assignment?"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java#L954-L966 |
24,197 | google/closure-compiler | src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java | PeepholeMinimizeConditions.tryMinimizeCondition | private Node tryMinimizeCondition(Node n) {
n = performConditionSubstitutions(n);
MinimizedCondition minCond = MinimizedCondition.fromConditionNode(n);
return replaceNode(
n,
minCond.getMinimized(MinimizationStyle.PREFER_UNNEGATED));
} | java | private Node tryMinimizeCondition(Node n) {
n = performConditionSubstitutions(n);
MinimizedCondition minCond = MinimizedCondition.fromConditionNode(n);
return replaceNode(
n,
minCond.getMinimized(MinimizationStyle.PREFER_UNNEGATED));
} | [
"private",
"Node",
"tryMinimizeCondition",
"(",
"Node",
"n",
")",
"{",
"n",
"=",
"performConditionSubstitutions",
"(",
"n",
")",
";",
"MinimizedCondition",
"minCond",
"=",
"MinimizedCondition",
".",
"fromConditionNode",
"(",
"n",
")",
";",
"return",
"replaceNode",
"(",
"n",
",",
"minCond",
".",
"getMinimized",
"(",
"MinimizationStyle",
".",
"PREFER_UNNEGATED",
")",
")",
";",
"}"
] | Try to minimize condition expression, as there are additional
assumptions that can be made when it is known that the final result
is a boolean.
@return The replacement for n, or the original if no change was made. | [
"Try",
"to",
"minimize",
"condition",
"expression",
"as",
"there",
"are",
"additional",
"assumptions",
"that",
"can",
"be",
"made",
"when",
"it",
"is",
"known",
"that",
"the",
"final",
"result",
"is",
"a",
"boolean",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java#L975-L981 |
24,198 | google/closure-compiler | src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java | PeepholeMinimizeConditions.maybeReplaceChildWithNumber | private Node maybeReplaceChildWithNumber(Node n, Node parent, int num) {
Node newNode = IR.number(num);
if (!newNode.isEquivalentTo(n)) {
parent.replaceChild(n, newNode);
reportChangeToEnclosingScope(newNode);
markFunctionsDeleted(n);
return newNode;
}
return n;
} | java | private Node maybeReplaceChildWithNumber(Node n, Node parent, int num) {
Node newNode = IR.number(num);
if (!newNode.isEquivalentTo(n)) {
parent.replaceChild(n, newNode);
reportChangeToEnclosingScope(newNode);
markFunctionsDeleted(n);
return newNode;
}
return n;
} | [
"private",
"Node",
"maybeReplaceChildWithNumber",
"(",
"Node",
"n",
",",
"Node",
"parent",
",",
"int",
"num",
")",
"{",
"Node",
"newNode",
"=",
"IR",
".",
"number",
"(",
"num",
")",
";",
"if",
"(",
"!",
"newNode",
".",
"isEquivalentTo",
"(",
"n",
")",
")",
"{",
"parent",
".",
"replaceChild",
"(",
"n",
",",
"newNode",
")",
";",
"reportChangeToEnclosingScope",
"(",
"newNode",
")",
";",
"markFunctionsDeleted",
"(",
"n",
")",
";",
"return",
"newNode",
";",
"}",
"return",
"n",
";",
"}"
] | Replaces a node with a number node if the new number node is not equivalent
to the current node.
Returns the replacement for n if it was replaced, otherwise returns n. | [
"Replaces",
"a",
"node",
"with",
"a",
"number",
"node",
"if",
"the",
"new",
"number",
"node",
"is",
"not",
"equivalent",
"to",
"the",
"current",
"node",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeMinimizeConditions.java#L1140-L1151 |
24,199 | google/closure-compiler | src/com/google/javascript/jscomp/ComposeWarningsGuard.java | ComposeWarningsGuard.enables | @Override
public boolean enables(DiagnosticGroup group) {
for (WarningsGuard guard : guards) {
if (guard.enables(group)) {
return true;
} else if (guard.disables(group)) {
return false;
}
}
return false;
} | java | @Override
public boolean enables(DiagnosticGroup group) {
for (WarningsGuard guard : guards) {
if (guard.enables(group)) {
return true;
} else if (guard.disables(group)) {
return false;
}
}
return false;
} | [
"@",
"Override",
"public",
"boolean",
"enables",
"(",
"DiagnosticGroup",
"group",
")",
"{",
"for",
"(",
"WarningsGuard",
"guard",
":",
"guards",
")",
"{",
"if",
"(",
"guard",
".",
"enables",
"(",
"group",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"guard",
".",
"disables",
"(",
"group",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Determines whether this guard will "elevate" the status of any disabled
diagnostic type in the group to a warning or an error. | [
"Determines",
"whether",
"this",
"guard",
"will",
"elevate",
"the",
"status",
"of",
"any",
"disabled",
"diagnostic",
"type",
"in",
"the",
"group",
"to",
"a",
"warning",
"or",
"an",
"error",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ComposeWarningsGuard.java#L146-L157 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.