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,500 | google/closure-compiler | src/com/google/javascript/jscomp/modules/Binding.java | Binding.from | static Binding from(Export boundExport, Node sourceNode) {
return new AutoValue_Binding(
boundExport.moduleMetadata(),
sourceNode,
boundExport,
/* isModuleNamespace= */ false,
/* closureNamespace= */ null,
CreatedBy.EXPORT);
} | java | static Binding from(Export boundExport, Node sourceNode) {
return new AutoValue_Binding(
boundExport.moduleMetadata(),
sourceNode,
boundExport,
/* isModuleNamespace= */ false,
/* closureNamespace= */ null,
CreatedBy.EXPORT);
} | [
"static",
"Binding",
"from",
"(",
"Export",
"boundExport",
",",
"Node",
"sourceNode",
")",
"{",
"return",
"new",
"AutoValue_Binding",
"(",
"boundExport",
".",
"moduleMetadata",
"(",
")",
",",
"sourceNode",
",",
"boundExport",
",",
"/* isModuleNamespace= */",
"false",
",",
"/* closureNamespace= */",
"null",
",",
"CreatedBy",
".",
"EXPORT",
")",
";",
"}"
] | Binding for an exported value that is not a module namespace object. | [
"Binding",
"for",
"an",
"exported",
"value",
"that",
"is",
"not",
"a",
"module",
"namespace",
"object",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/modules/Binding.java#L93-L101 |
24,501 | google/closure-compiler | src/com/google/javascript/jscomp/modules/Binding.java | Binding.copy | Binding copy(Node sourceNode, CreatedBy createdBy) {
checkNotNull(sourceNode);
return new AutoValue_Binding(
metadata(),
sourceNode,
originatingExport(),
isModuleNamespace(),
closureNamespace(),
createdBy);
} | java | Binding copy(Node sourceNode, CreatedBy createdBy) {
checkNotNull(sourceNode);
return new AutoValue_Binding(
metadata(),
sourceNode,
originatingExport(),
isModuleNamespace(),
closureNamespace(),
createdBy);
} | [
"Binding",
"copy",
"(",
"Node",
"sourceNode",
",",
"CreatedBy",
"createdBy",
")",
"{",
"checkNotNull",
"(",
"sourceNode",
")",
";",
"return",
"new",
"AutoValue_Binding",
"(",
"metadata",
"(",
")",
",",
"sourceNode",
",",
"originatingExport",
"(",
")",
",",
"isModuleNamespace",
"(",
")",
",",
"closureNamespace",
"(",
")",
",",
"createdBy",
")",
";",
"}"
] | Copies the binding with a new source node and CreatedBy binding. | [
"Copies",
"the",
"binding",
"with",
"a",
"new",
"source",
"node",
"and",
"CreatedBy",
"binding",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/modules/Binding.java#L131-L141 |
24,502 | google/closure-compiler | src/com/google/javascript/jscomp/ConstCheck.java | ConstCheck.reportError | void reportError(Node n, Var var, String name) {
JSDocInfo info = NodeUtil.getBestJSDocInfo(n);
if (info == null || !info.getSuppressions().contains("const")) {
Node declNode = var.getNode();
String declaredPosition = declNode.getSourceFileName() + ":" + declNode.getLineno();
compiler.report(JSError.make(n, CONST_REASSIGNED_VALUE_ERROR, name, declaredPosition));
}
} | java | void reportError(Node n, Var var, String name) {
JSDocInfo info = NodeUtil.getBestJSDocInfo(n);
if (info == null || !info.getSuppressions().contains("const")) {
Node declNode = var.getNode();
String declaredPosition = declNode.getSourceFileName() + ":" + declNode.getLineno();
compiler.report(JSError.make(n, CONST_REASSIGNED_VALUE_ERROR, name, declaredPosition));
}
} | [
"void",
"reportError",
"(",
"Node",
"n",
",",
"Var",
"var",
",",
"String",
"name",
")",
"{",
"JSDocInfo",
"info",
"=",
"NodeUtil",
".",
"getBestJSDocInfo",
"(",
"n",
")",
";",
"if",
"(",
"info",
"==",
"null",
"||",
"!",
"info",
".",
"getSuppressions",
"(",
")",
".",
"contains",
"(",
"\"const\"",
")",
")",
"{",
"Node",
"declNode",
"=",
"var",
".",
"getNode",
"(",
")",
";",
"String",
"declaredPosition",
"=",
"declNode",
".",
"getSourceFileName",
"(",
")",
"+",
"\":\"",
"+",
"declNode",
".",
"getLineno",
"(",
")",
";",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"n",
",",
"CONST_REASSIGNED_VALUE_ERROR",
",",
"name",
",",
"declaredPosition",
")",
")",
";",
"}",
"}"
] | Reports a reassigned constant error. | [
"Reports",
"a",
"reassigned",
"constant",
"error",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ConstCheck.java#L132-L139 |
24,503 | google/closure-compiler | src/com/google/javascript/jscomp/JsIterables.java | JsIterables.getElementType | static final JSType getElementType(JSType iterableOrIterator, JSTypeRegistry typeRegistry) {
TemplateTypeMap templateTypeMap =
iterableOrIterator
// Remember that `string` will box to a `Iterable`.
.autobox()
.getTemplateTypeMap();
if (templateTypeMap.hasTemplateKey(typeRegistry.getIterableTemplate())) {
// `Iterable<SomeElementType>` or `Generator<SomeElementType>`
return templateTypeMap.getResolvedTemplateType(typeRegistry.getIterableTemplate());
} else if (templateTypeMap.hasTemplateKey(typeRegistry.getIteratorTemplate())) {
// `Iterator<SomeElementType>`
return templateTypeMap.getResolvedTemplateType(typeRegistry.getIteratorTemplate());
} else if (templateTypeMap.hasTemplateKey(typeRegistry.getAsyncIterableTemplate())) {
// `AsyncIterable<SomeElementType>` or `AsyncGenerator<SomeElementType>`
return templateTypeMap.getResolvedTemplateType(typeRegistry.getAsyncIterableTemplate());
} else if (templateTypeMap.hasTemplateKey(typeRegistry.getAsyncIteratorTemplate())) {
// `AsyncIterator<SomeElementType>`
return templateTypeMap.getResolvedTemplateType(typeRegistry.getAsyncIteratorTemplate());
}
return typeRegistry.getNativeType(UNKNOWN_TYPE);
} | java | static final JSType getElementType(JSType iterableOrIterator, JSTypeRegistry typeRegistry) {
TemplateTypeMap templateTypeMap =
iterableOrIterator
// Remember that `string` will box to a `Iterable`.
.autobox()
.getTemplateTypeMap();
if (templateTypeMap.hasTemplateKey(typeRegistry.getIterableTemplate())) {
// `Iterable<SomeElementType>` or `Generator<SomeElementType>`
return templateTypeMap.getResolvedTemplateType(typeRegistry.getIterableTemplate());
} else if (templateTypeMap.hasTemplateKey(typeRegistry.getIteratorTemplate())) {
// `Iterator<SomeElementType>`
return templateTypeMap.getResolvedTemplateType(typeRegistry.getIteratorTemplate());
} else if (templateTypeMap.hasTemplateKey(typeRegistry.getAsyncIterableTemplate())) {
// `AsyncIterable<SomeElementType>` or `AsyncGenerator<SomeElementType>`
return templateTypeMap.getResolvedTemplateType(typeRegistry.getAsyncIterableTemplate());
} else if (templateTypeMap.hasTemplateKey(typeRegistry.getAsyncIteratorTemplate())) {
// `AsyncIterator<SomeElementType>`
return templateTypeMap.getResolvedTemplateType(typeRegistry.getAsyncIteratorTemplate());
}
return typeRegistry.getNativeType(UNKNOWN_TYPE);
} | [
"static",
"final",
"JSType",
"getElementType",
"(",
"JSType",
"iterableOrIterator",
",",
"JSTypeRegistry",
"typeRegistry",
")",
"{",
"TemplateTypeMap",
"templateTypeMap",
"=",
"iterableOrIterator",
"// Remember that `string` will box to a `Iterable`.",
".",
"autobox",
"(",
")",
".",
"getTemplateTypeMap",
"(",
")",
";",
"if",
"(",
"templateTypeMap",
".",
"hasTemplateKey",
"(",
"typeRegistry",
".",
"getIterableTemplate",
"(",
")",
")",
")",
"{",
"// `Iterable<SomeElementType>` or `Generator<SomeElementType>`",
"return",
"templateTypeMap",
".",
"getResolvedTemplateType",
"(",
"typeRegistry",
".",
"getIterableTemplate",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"templateTypeMap",
".",
"hasTemplateKey",
"(",
"typeRegistry",
".",
"getIteratorTemplate",
"(",
")",
")",
")",
"{",
"// `Iterator<SomeElementType>`",
"return",
"templateTypeMap",
".",
"getResolvedTemplateType",
"(",
"typeRegistry",
".",
"getIteratorTemplate",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"templateTypeMap",
".",
"hasTemplateKey",
"(",
"typeRegistry",
".",
"getAsyncIterableTemplate",
"(",
")",
")",
")",
"{",
"// `AsyncIterable<SomeElementType>` or `AsyncGenerator<SomeElementType>`",
"return",
"templateTypeMap",
".",
"getResolvedTemplateType",
"(",
"typeRegistry",
".",
"getAsyncIterableTemplate",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"templateTypeMap",
".",
"hasTemplateKey",
"(",
"typeRegistry",
".",
"getAsyncIteratorTemplate",
"(",
")",
")",
")",
"{",
"// `AsyncIterator<SomeElementType>`",
"return",
"templateTypeMap",
".",
"getResolvedTemplateType",
"(",
"typeRegistry",
".",
"getAsyncIteratorTemplate",
"(",
")",
")",
";",
"}",
"return",
"typeRegistry",
".",
"getNativeType",
"(",
"UNKNOWN_TYPE",
")",
";",
"}"
] | Returns the given `Iterable`s element type.
<p>If the given type is not an `Iterator`, `Iterable`, `AsyncIterator`, or `AsyncIterable`,
returns the unknown type. | [
"Returns",
"the",
"given",
"Iterable",
"s",
"element",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsIterables.java#L43-L64 |
24,504 | google/closure-compiler | src/com/google/javascript/jscomp/FileInstrumentationData.java | FileInstrumentationData.putBranchNode | void putBranchNode(int lineNumber, int branchNumber, Node block) {
Preconditions.checkArgument(
lineNumber > 0, "Expected non-zero positive integer as line number: %s", lineNumber);
Preconditions.checkArgument(
branchNumber > 0, "Expected non-zero positive integer as branch number: %s", branchNumber);
branchNodes.put(BranchIndexPair.of(lineNumber - 1, branchNumber - 1), block);
} | java | void putBranchNode(int lineNumber, int branchNumber, Node block) {
Preconditions.checkArgument(
lineNumber > 0, "Expected non-zero positive integer as line number: %s", lineNumber);
Preconditions.checkArgument(
branchNumber > 0, "Expected non-zero positive integer as branch number: %s", branchNumber);
branchNodes.put(BranchIndexPair.of(lineNumber - 1, branchNumber - 1), block);
} | [
"void",
"putBranchNode",
"(",
"int",
"lineNumber",
",",
"int",
"branchNumber",
",",
"Node",
"block",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"lineNumber",
">",
"0",
",",
"\"Expected non-zero positive integer as line number: %s\"",
",",
"lineNumber",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"branchNumber",
">",
"0",
",",
"\"Expected non-zero positive integer as branch number: %s\"",
",",
"branchNumber",
")",
";",
"branchNodes",
".",
"put",
"(",
"BranchIndexPair",
".",
"of",
"(",
"lineNumber",
"-",
"1",
",",
"branchNumber",
"-",
"1",
")",
",",
"block",
")",
";",
"}"
] | Store a node to be instrumented later for branch coverage.
@param lineNumber 1-based line number
@param branchNumber 1-based branch number
@param block the node of the conditional block. | [
"Store",
"a",
"node",
"to",
"be",
"instrumented",
"later",
"for",
"branch",
"coverage",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FileInstrumentationData.java#L124-L131 |
24,505 | google/closure-compiler | src/com/google/javascript/jscomp/FileInstrumentationData.java | FileInstrumentationData.getBranchNode | Node getBranchNode(int lineNumber, int branchNumber) {
Preconditions.checkArgument(
lineNumber > 0, "Expected non-zero positive integer as line number: %s", lineNumber);
Preconditions.checkArgument(
branchNumber > 0, "Expected non-zero positive integer as branch number: %s", branchNumber);
return branchNodes.get(BranchIndexPair.of(lineNumber - 1, branchNumber - 1));
} | java | Node getBranchNode(int lineNumber, int branchNumber) {
Preconditions.checkArgument(
lineNumber > 0, "Expected non-zero positive integer as line number: %s", lineNumber);
Preconditions.checkArgument(
branchNumber > 0, "Expected non-zero positive integer as branch number: %s", branchNumber);
return branchNodes.get(BranchIndexPair.of(lineNumber - 1, branchNumber - 1));
} | [
"Node",
"getBranchNode",
"(",
"int",
"lineNumber",
",",
"int",
"branchNumber",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"lineNumber",
">",
"0",
",",
"\"Expected non-zero positive integer as line number: %s\"",
",",
"lineNumber",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"branchNumber",
">",
"0",
",",
"\"Expected non-zero positive integer as branch number: %s\"",
",",
"branchNumber",
")",
";",
"return",
"branchNodes",
".",
"get",
"(",
"BranchIndexPair",
".",
"of",
"(",
"lineNumber",
"-",
"1",
",",
"branchNumber",
"-",
"1",
")",
")",
";",
"}"
] | Get the block node to be instrumented for branch coverage.
@param lineNumber 1-based line number
@param branchNumber 1-based branch number
@return the node of the conditional block. | [
"Get",
"the",
"block",
"node",
"to",
"be",
"instrumented",
"for",
"branch",
"coverage",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FileInstrumentationData.java#L139-L146 |
24,506 | google/closure-compiler | src/com/google/javascript/jscomp/FileInstrumentationData.java | FileInstrumentationData.addBranches | void addBranches(int lineNumber, int numberOfBranches) {
int lineIdx = lineNumber - 1;
Integer currentValue = branchesInLine.get(Integer.valueOf(lineIdx));
if (currentValue == null) {
branchesInLine.put(lineIdx, numberOfBranches);
} else {
branchesInLine.put(lineIdx, currentValue + numberOfBranches);
}
} | java | void addBranches(int lineNumber, int numberOfBranches) {
int lineIdx = lineNumber - 1;
Integer currentValue = branchesInLine.get(Integer.valueOf(lineIdx));
if (currentValue == null) {
branchesInLine.put(lineIdx, numberOfBranches);
} else {
branchesInLine.put(lineIdx, currentValue + numberOfBranches);
}
} | [
"void",
"addBranches",
"(",
"int",
"lineNumber",
",",
"int",
"numberOfBranches",
")",
"{",
"int",
"lineIdx",
"=",
"lineNumber",
"-",
"1",
";",
"Integer",
"currentValue",
"=",
"branchesInLine",
".",
"get",
"(",
"Integer",
".",
"valueOf",
"(",
"lineIdx",
")",
")",
";",
"if",
"(",
"currentValue",
"==",
"null",
")",
"{",
"branchesInLine",
".",
"put",
"(",
"lineIdx",
",",
"numberOfBranches",
")",
";",
"}",
"else",
"{",
"branchesInLine",
".",
"put",
"(",
"lineIdx",
",",
"currentValue",
"+",
"numberOfBranches",
")",
";",
"}",
"}"
] | Add a number of branches to a line.
@param lineNumber the line number that contains the branch statement.
@param numberOfBranches the number of branches to add to the record. | [
"Add",
"a",
"number",
"of",
"branches",
"to",
"a",
"line",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FileInstrumentationData.java#L214-L222 |
24,507 | google/closure-compiler | src/com/google/javascript/jscomp/FileInstrumentationData.java | FileInstrumentationData.getNumBranches | int getNumBranches(int lineNumber) {
Integer numBranches = branchesInLine.get(lineNumber - 1);
if (numBranches == null) {
return 0;
} else {
return numBranches;
}
} | java | int getNumBranches(int lineNumber) {
Integer numBranches = branchesInLine.get(lineNumber - 1);
if (numBranches == null) {
return 0;
} else {
return numBranches;
}
} | [
"int",
"getNumBranches",
"(",
"int",
"lineNumber",
")",
"{",
"Integer",
"numBranches",
"=",
"branchesInLine",
".",
"get",
"(",
"lineNumber",
"-",
"1",
")",
";",
"if",
"(",
"numBranches",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"else",
"{",
"return",
"numBranches",
";",
"}",
"}"
] | Get the number of branches on a line
@param lineNumber - the 1-based line number
@return the number of branches on the line. | [
"Get",
"the",
"number",
"of",
"branches",
"on",
"a",
"line"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FileInstrumentationData.java#L229-L236 |
24,508 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.populateDefaults | private static void populateDefaults(JSDocInfo info) {
if (info.getVisibility() == null) {
info.setVisibility(Visibility.INHERITED);
}
} | java | private static void populateDefaults(JSDocInfo info) {
if (info.getVisibility() == null) {
info.setVisibility(Visibility.INHERITED);
}
} | [
"private",
"static",
"void",
"populateDefaults",
"(",
"JSDocInfo",
"info",
")",
"{",
"if",
"(",
"info",
".",
"getVisibility",
"(",
")",
"==",
"null",
")",
"{",
"info",
".",
"setVisibility",
"(",
"Visibility",
".",
"INHERITED",
")",
";",
"}",
"}"
] | Generate defaults when certain parameters are not specified. | [
"Generate",
"defaults",
"when",
"certain",
"parameters",
"are",
"not",
"specified",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L201-L205 |
24,509 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.markAnnotation | public void markAnnotation(String annotation, int lineno, int charno) {
JSDocInfo.Marker marker = currentInfo.addMarker();
if (marker != null) {
JSDocInfo.TrimmedStringPosition position =
new JSDocInfo.TrimmedStringPosition();
position.setItem(annotation);
position.setPositionInformation(lineno, charno, lineno,
charno + annotation.length());
marker.setAnnotation(position);
populated = true;
}
currentMarker = marker;
} | java | public void markAnnotation(String annotation, int lineno, int charno) {
JSDocInfo.Marker marker = currentInfo.addMarker();
if (marker != null) {
JSDocInfo.TrimmedStringPosition position =
new JSDocInfo.TrimmedStringPosition();
position.setItem(annotation);
position.setPositionInformation(lineno, charno, lineno,
charno + annotation.length());
marker.setAnnotation(position);
populated = true;
}
currentMarker = marker;
} | [
"public",
"void",
"markAnnotation",
"(",
"String",
"annotation",
",",
"int",
"lineno",
",",
"int",
"charno",
")",
"{",
"JSDocInfo",
".",
"Marker",
"marker",
"=",
"currentInfo",
".",
"addMarker",
"(",
")",
";",
"if",
"(",
"marker",
"!=",
"null",
")",
"{",
"JSDocInfo",
".",
"TrimmedStringPosition",
"position",
"=",
"new",
"JSDocInfo",
".",
"TrimmedStringPosition",
"(",
")",
";",
"position",
".",
"setItem",
"(",
"annotation",
")",
";",
"position",
".",
"setPositionInformation",
"(",
"lineno",
",",
"charno",
",",
"lineno",
",",
"charno",
"+",
"annotation",
".",
"length",
"(",
")",
")",
";",
"marker",
".",
"setAnnotation",
"(",
"position",
")",
";",
"populated",
"=",
"true",
";",
"}",
"currentMarker",
"=",
"marker",
";",
"}"
] | Adds a marker to the current JSDocInfo and populates the marker with the
annotation information. | [
"Adds",
"a",
"marker",
"to",
"the",
"current",
"JSDocInfo",
"and",
"populates",
"the",
"marker",
"with",
"the",
"annotation",
"information",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L211-L225 |
24,510 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.markText | public void markText(String text, int startLineno, int startCharno,
int endLineno, int endCharno) {
if (currentMarker != null) {
JSDocInfo.StringPosition position = new JSDocInfo.StringPosition();
position.setItem(text);
position.setPositionInformation(startLineno, startCharno,
endLineno, endCharno);
currentMarker.setDescription(position);
}
} | java | public void markText(String text, int startLineno, int startCharno,
int endLineno, int endCharno) {
if (currentMarker != null) {
JSDocInfo.StringPosition position = new JSDocInfo.StringPosition();
position.setItem(text);
position.setPositionInformation(startLineno, startCharno,
endLineno, endCharno);
currentMarker.setDescription(position);
}
} | [
"public",
"void",
"markText",
"(",
"String",
"text",
",",
"int",
"startLineno",
",",
"int",
"startCharno",
",",
"int",
"endLineno",
",",
"int",
"endCharno",
")",
"{",
"if",
"(",
"currentMarker",
"!=",
"null",
")",
"{",
"JSDocInfo",
".",
"StringPosition",
"position",
"=",
"new",
"JSDocInfo",
".",
"StringPosition",
"(",
")",
";",
"position",
".",
"setItem",
"(",
"text",
")",
";",
"position",
".",
"setPositionInformation",
"(",
"startLineno",
",",
"startCharno",
",",
"endLineno",
",",
"endCharno",
")",
";",
"currentMarker",
".",
"setDescription",
"(",
"position",
")",
";",
"}",
"}"
] | Adds a textual block to the current marker. | [
"Adds",
"a",
"textual",
"block",
"to",
"the",
"current",
"marker",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L230-L239 |
24,511 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.markTypeNode | public void markTypeNode(Node typeNode, int lineno, int startCharno,
int endLineno, int endCharno, boolean hasLC) {
if (currentMarker != null) {
JSDocInfo.TypePosition position = new JSDocInfo.TypePosition();
position.setItem(typeNode);
position.setHasBrackets(hasLC);
position.setPositionInformation(lineno, startCharno,
endLineno, endCharno);
currentMarker.setType(position);
}
} | java | public void markTypeNode(Node typeNode, int lineno, int startCharno,
int endLineno, int endCharno, boolean hasLC) {
if (currentMarker != null) {
JSDocInfo.TypePosition position = new JSDocInfo.TypePosition();
position.setItem(typeNode);
position.setHasBrackets(hasLC);
position.setPositionInformation(lineno, startCharno,
endLineno, endCharno);
currentMarker.setType(position);
}
} | [
"public",
"void",
"markTypeNode",
"(",
"Node",
"typeNode",
",",
"int",
"lineno",
",",
"int",
"startCharno",
",",
"int",
"endLineno",
",",
"int",
"endCharno",
",",
"boolean",
"hasLC",
")",
"{",
"if",
"(",
"currentMarker",
"!=",
"null",
")",
"{",
"JSDocInfo",
".",
"TypePosition",
"position",
"=",
"new",
"JSDocInfo",
".",
"TypePosition",
"(",
")",
";",
"position",
".",
"setItem",
"(",
"typeNode",
")",
";",
"position",
".",
"setHasBrackets",
"(",
"hasLC",
")",
";",
"position",
".",
"setPositionInformation",
"(",
"lineno",
",",
"startCharno",
",",
"endLineno",
",",
"endCharno",
")",
";",
"currentMarker",
".",
"setType",
"(",
"position",
")",
";",
"}",
"}"
] | Adds a type declaration to the current marker. | [
"Adds",
"a",
"type",
"declaration",
"to",
"the",
"current",
"marker",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L244-L254 |
24,512 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.markName | public void markName(String name, Node templateNode,
int lineno, int charno) {
if (currentMarker != null) {
// Record the name as both a SourcePosition<String> and a
// SourcePosition<Node>. The <String> form is deprecated,
// because <Node> is more consistent with how other name
// references are handled (see #markTypeNode)
//
// TODO(nicksantos): Remove all uses of the Name position
// and replace them with the NameNode position.
JSDocInfo.TrimmedStringPosition position =
new JSDocInfo.TrimmedStringPosition();
position.setItem(name);
position.setPositionInformation(lineno, charno,
lineno, charno + name.length());
JSDocInfo.NamePosition nodePos = new JSDocInfo.NamePosition();
Node node = Node.newString(Token.NAME, name, lineno, charno);
node.setLength(name.length());
if (templateNode != null) {
node.setStaticSourceFileFrom(templateNode);
}
nodePos.setItem(node);
nodePos.setPositionInformation(lineno, charno,
lineno, charno + name.length());
currentMarker.setNameNode(nodePos);
}
} | java | public void markName(String name, Node templateNode,
int lineno, int charno) {
if (currentMarker != null) {
// Record the name as both a SourcePosition<String> and a
// SourcePosition<Node>. The <String> form is deprecated,
// because <Node> is more consistent with how other name
// references are handled (see #markTypeNode)
//
// TODO(nicksantos): Remove all uses of the Name position
// and replace them with the NameNode position.
JSDocInfo.TrimmedStringPosition position =
new JSDocInfo.TrimmedStringPosition();
position.setItem(name);
position.setPositionInformation(lineno, charno,
lineno, charno + name.length());
JSDocInfo.NamePosition nodePos = new JSDocInfo.NamePosition();
Node node = Node.newString(Token.NAME, name, lineno, charno);
node.setLength(name.length());
if (templateNode != null) {
node.setStaticSourceFileFrom(templateNode);
}
nodePos.setItem(node);
nodePos.setPositionInformation(lineno, charno,
lineno, charno + name.length());
currentMarker.setNameNode(nodePos);
}
} | [
"public",
"void",
"markName",
"(",
"String",
"name",
",",
"Node",
"templateNode",
",",
"int",
"lineno",
",",
"int",
"charno",
")",
"{",
"if",
"(",
"currentMarker",
"!=",
"null",
")",
"{",
"// Record the name as both a SourcePosition<String> and a",
"// SourcePosition<Node>. The <String> form is deprecated,",
"// because <Node> is more consistent with how other name",
"// references are handled (see #markTypeNode)",
"//",
"// TODO(nicksantos): Remove all uses of the Name position",
"// and replace them with the NameNode position.",
"JSDocInfo",
".",
"TrimmedStringPosition",
"position",
"=",
"new",
"JSDocInfo",
".",
"TrimmedStringPosition",
"(",
")",
";",
"position",
".",
"setItem",
"(",
"name",
")",
";",
"position",
".",
"setPositionInformation",
"(",
"lineno",
",",
"charno",
",",
"lineno",
",",
"charno",
"+",
"name",
".",
"length",
"(",
")",
")",
";",
"JSDocInfo",
".",
"NamePosition",
"nodePos",
"=",
"new",
"JSDocInfo",
".",
"NamePosition",
"(",
")",
";",
"Node",
"node",
"=",
"Node",
".",
"newString",
"(",
"Token",
".",
"NAME",
",",
"name",
",",
"lineno",
",",
"charno",
")",
";",
"node",
".",
"setLength",
"(",
"name",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"templateNode",
"!=",
"null",
")",
"{",
"node",
".",
"setStaticSourceFileFrom",
"(",
"templateNode",
")",
";",
"}",
"nodePos",
".",
"setItem",
"(",
"node",
")",
";",
"nodePos",
".",
"setPositionInformation",
"(",
"lineno",
",",
"charno",
",",
"lineno",
",",
"charno",
"+",
"name",
".",
"length",
"(",
")",
")",
";",
"currentMarker",
".",
"setNameNode",
"(",
"nodePos",
")",
";",
"}",
"}"
] | Adds a name declaration to the current marker. | [
"Adds",
"a",
"name",
"declaration",
"to",
"the",
"current",
"marker",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L259-L286 |
24,513 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordVisibility | public boolean recordVisibility(Visibility visibility) {
if (currentInfo.getVisibility() == null) {
populated = true;
currentInfo.setVisibility(visibility);
return true;
} else {
return false;
}
} | java | public boolean recordVisibility(Visibility visibility) {
if (currentInfo.getVisibility() == null) {
populated = true;
currentInfo.setVisibility(visibility);
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordVisibility",
"(",
"Visibility",
"visibility",
")",
"{",
"if",
"(",
"currentInfo",
".",
"getVisibility",
"(",
")",
"==",
"null",
")",
"{",
"populated",
"=",
"true",
";",
"currentInfo",
".",
"setVisibility",
"(",
"visibility",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a visibility.
@return {@code true} if the visibility was recorded and {@code false}
if it was already defined | [
"Records",
"a",
"visibility",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L304-L312 |
24,514 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordParameter | public boolean recordParameter(String parameterName, JSTypeExpression type) {
if (!hasAnySingletonTypeTags()
&& currentInfo.declareParam(type, parameterName)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordParameter(String parameterName, JSTypeExpression type) {
if (!hasAnySingletonTypeTags()
&& currentInfo.declareParam(type, parameterName)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordParameter",
"(",
"String",
"parameterName",
",",
"JSTypeExpression",
"type",
")",
"{",
"if",
"(",
"!",
"hasAnySingletonTypeTags",
"(",
")",
"&&",
"currentInfo",
".",
"declareParam",
"(",
"type",
",",
"parameterName",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a typed parameter.
@return {@code true} if the typed parameter was recorded and
{@code false} if a parameter with the same name was already defined | [
"Records",
"a",
"typed",
"parameter",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L325-L333 |
24,515 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordParameterDescription | public boolean recordParameterDescription(
String parameterName, String description) {
if (currentInfo.documentParam(parameterName, description)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordParameterDescription(
String parameterName, String description) {
if (currentInfo.documentParam(parameterName, description)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordParameterDescription",
"(",
"String",
"parameterName",
",",
"String",
"description",
")",
"{",
"if",
"(",
"currentInfo",
".",
"documentParam",
"(",
"parameterName",
",",
"description",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a parameter's description.
@return {@code true} if the parameter's description was recorded and
{@code false} if a parameter with the same name was already defined | [
"Records",
"a",
"parameter",
"s",
"description",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L341-L349 |
24,516 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordTemplateTypeName | public boolean recordTemplateTypeName(String name) {
if (currentInfo.declareTemplateTypeName(name)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordTemplateTypeName(String name) {
if (currentInfo.declareTemplateTypeName(name)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordTemplateTypeName",
"(",
"String",
"name",
")",
"{",
"if",
"(",
"currentInfo",
".",
"declareTemplateTypeName",
"(",
"name",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a template type name.
@return {@code true} if the template type name was recorded and
{@code false} if the input template type name was already defined. | [
"Records",
"a",
"template",
"type",
"name",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L357-L364 |
24,517 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordTypeTransformation | public boolean recordTypeTransformation(String name, Node expr) {
if (currentInfo.declareTypeTransformation(name, expr)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordTypeTransformation(String name, Node expr) {
if (currentInfo.declareTypeTransformation(name, expr)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordTypeTransformation",
"(",
"String",
"name",
",",
"Node",
"expr",
")",
"{",
"if",
"(",
"currentInfo",
".",
"declareTypeTransformation",
"(",
"name",
",",
"expr",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a type transformation expression together with its template
type name. | [
"Records",
"a",
"type",
"transformation",
"expression",
"together",
"with",
"its",
"template",
"type",
"name",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L370-L377 |
24,518 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordThrowType | public boolean recordThrowType(JSTypeExpression type) {
if (type != null && !hasAnySingletonTypeTags()) {
currentInfo.declareThrows(type);
populated = true;
return true;
}
return false;
} | java | public boolean recordThrowType(JSTypeExpression type) {
if (type != null && !hasAnySingletonTypeTags()) {
currentInfo.declareThrows(type);
populated = true;
return true;
}
return false;
} | [
"public",
"boolean",
"recordThrowType",
"(",
"JSTypeExpression",
"type",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
"&&",
"!",
"hasAnySingletonTypeTags",
"(",
")",
")",
"{",
"currentInfo",
".",
"declareThrows",
"(",
"type",
")",
";",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Records a thrown type. | [
"Records",
"a",
"thrown",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L382-L389 |
24,519 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordThrowDescription | public boolean recordThrowDescription(
JSTypeExpression type, String description) {
if (currentInfo.documentThrows(type, description)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordThrowDescription(
JSTypeExpression type, String description) {
if (currentInfo.documentThrows(type, description)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordThrowDescription",
"(",
"JSTypeExpression",
"type",
",",
"String",
"description",
")",
"{",
"if",
"(",
"currentInfo",
".",
"documentThrows",
"(",
"type",
",",
"description",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a throw type's description.
@return {@code true} if the type's description was recorded and
{@code false} if a description with the same type was already defined | [
"Records",
"a",
"throw",
"type",
"s",
"description",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L397-L405 |
24,520 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.addAuthor | public boolean addAuthor(String author) {
if (currentInfo.documentAuthor(author)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean addAuthor(String author) {
if (currentInfo.documentAuthor(author)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"addAuthor",
"(",
"String",
"author",
")",
"{",
"if",
"(",
"currentInfo",
".",
"documentAuthor",
"(",
"author",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Adds an author to the current information. | [
"Adds",
"an",
"author",
"to",
"the",
"current",
"information",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L411-L418 |
24,521 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.addReference | public boolean addReference(String reference) {
if (currentInfo.documentReference(reference)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean addReference(String reference) {
if (currentInfo.documentReference(reference)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"addReference",
"(",
"String",
"reference",
")",
"{",
"if",
"(",
"currentInfo",
".",
"documentReference",
"(",
"reference",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Adds a reference ("@see") to the current information. | [
"Adds",
"a",
"reference",
"("
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L424-L431 |
24,522 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordVersion | public boolean recordVersion(String version) {
if (currentInfo.documentVersion(version)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordVersion(String version) {
if (currentInfo.documentVersion(version)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordVersion",
"(",
"String",
"version",
")",
"{",
"if",
"(",
"currentInfo",
".",
"documentVersion",
"(",
"version",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records the version. | [
"Records",
"the",
"version",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L505-L512 |
24,523 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordDeprecationReason | public boolean recordDeprecationReason(String reason) {
if (currentInfo.setDeprecationReason(reason)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordDeprecationReason(String reason) {
if (currentInfo.setDeprecationReason(reason)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordDeprecationReason",
"(",
"String",
"reason",
")",
"{",
"if",
"(",
"currentInfo",
".",
"setDeprecationReason",
"(",
"reason",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records the deprecation reason. | [
"Records",
"the",
"deprecation",
"reason",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L517-L524 |
24,524 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordModifies | public boolean recordModifies(Set<String> modifies) {
if (!hasAnySingletonSideEffectTags()
&& currentInfo.setModifies(modifies)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordModifies(Set<String> modifies) {
if (!hasAnySingletonSideEffectTags()
&& currentInfo.setModifies(modifies)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordModifies",
"(",
"Set",
"<",
"String",
">",
"modifies",
")",
"{",
"if",
"(",
"!",
"hasAnySingletonSideEffectTags",
"(",
")",
"&&",
"currentInfo",
".",
"setModifies",
"(",
"modifies",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records the list of modifies warnings. | [
"Records",
"the",
"list",
"of",
"modifies",
"warnings",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L550-L558 |
24,525 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordType | public boolean recordType(JSTypeExpression type) {
if (type != null && !hasAnyTypeRelatedTags()) {
currentInfo.setType(type);
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordType(JSTypeExpression type) {
if (type != null && !hasAnyTypeRelatedTags()) {
currentInfo.setType(type);
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordType",
"(",
"JSTypeExpression",
"type",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
"&&",
"!",
"hasAnyTypeRelatedTags",
"(",
")",
")",
"{",
"currentInfo",
".",
"setType",
"(",
"type",
")",
";",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a type.
@return {@code true} if the type was recorded and {@code false} if
it is invalid or was already defined | [
"Records",
"a",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L566-L574 |
24,526 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordReturnType | public boolean recordReturnType(JSTypeExpression jsType) {
if (jsType != null && currentInfo.getReturnType() == null
&& !hasAnySingletonTypeTags()) {
currentInfo.setReturnType(jsType);
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordReturnType(JSTypeExpression jsType) {
if (jsType != null && currentInfo.getReturnType() == null
&& !hasAnySingletonTypeTags()) {
currentInfo.setReturnType(jsType);
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordReturnType",
"(",
"JSTypeExpression",
"jsType",
")",
"{",
"if",
"(",
"jsType",
"!=",
"null",
"&&",
"currentInfo",
".",
"getReturnType",
"(",
")",
"==",
"null",
"&&",
"!",
"hasAnySingletonTypeTags",
"(",
")",
")",
"{",
"currentInfo",
".",
"setReturnType",
"(",
"jsType",
")",
";",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a return type.
@return {@code true} if the return type was recorded and {@code false} if
it is invalid or was already defined | [
"Records",
"a",
"return",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L616-L625 |
24,527 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordReturnDescription | public boolean recordReturnDescription(String description) {
if (currentInfo.documentReturn(description)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordReturnDescription(String description) {
if (currentInfo.documentReturn(description)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordReturnDescription",
"(",
"String",
"description",
")",
"{",
"if",
"(",
"currentInfo",
".",
"documentReturn",
"(",
"description",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a return description
@return {@code true} if the return description was recorded and
{@code false} if it is invalid or was already defined | [
"Records",
"a",
"return",
"description"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L633-L640 |
24,528 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordDefineType | public boolean recordDefineType(JSTypeExpression type) {
if (type != null &&
!currentInfo.isConstant() &&
!currentInfo.isDefine() &&
recordType(type)) {
currentInfo.setDefine(true);
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordDefineType(JSTypeExpression type) {
if (type != null &&
!currentInfo.isConstant() &&
!currentInfo.isDefine() &&
recordType(type)) {
currentInfo.setDefine(true);
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordDefineType",
"(",
"JSTypeExpression",
"type",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
"&&",
"!",
"currentInfo",
".",
"isConstant",
"(",
")",
"&&",
"!",
"currentInfo",
".",
"isDefine",
"(",
")",
"&&",
"recordType",
"(",
"type",
")",
")",
"{",
"currentInfo",
".",
"setDefine",
"(",
"true",
")",
";",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records the type of a define.
'Define' values are special constants that may be manipulated by
the compiler. They are designed to mimic the #define command in
the C preprocessor. | [
"Records",
"the",
"type",
"of",
"a",
"define",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L649-L660 |
24,529 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordEnumParameterType | public boolean recordEnumParameterType(JSTypeExpression type) {
if (type != null && !hasAnyTypeRelatedTags()) {
currentInfo.setEnumParameterType(type);
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordEnumParameterType(JSTypeExpression type) {
if (type != null && !hasAnyTypeRelatedTags()) {
currentInfo.setEnumParameterType(type);
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordEnumParameterType",
"(",
"JSTypeExpression",
"type",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
"&&",
"!",
"hasAnyTypeRelatedTags",
"(",
")",
")",
"{",
"currentInfo",
".",
"setEnumParameterType",
"(",
"type",
")",
";",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a parameter type to an enum.
@return {@code true} if the enum's parameter type was recorded and
{@code false} if it was invalid or already defined | [
"Records",
"a",
"parameter",
"type",
"to",
"an",
"enum",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L668-L676 |
24,530 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordBaseType | public boolean recordBaseType(JSTypeExpression jsType) {
if (jsType != null && !hasAnySingletonTypeTags() &&
!currentInfo.hasBaseType()) {
currentInfo.setBaseType(jsType);
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordBaseType(JSTypeExpression jsType) {
if (jsType != null && !hasAnySingletonTypeTags() &&
!currentInfo.hasBaseType()) {
currentInfo.setBaseType(jsType);
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordBaseType",
"(",
"JSTypeExpression",
"jsType",
")",
"{",
"if",
"(",
"jsType",
"!=",
"null",
"&&",
"!",
"hasAnySingletonTypeTags",
"(",
")",
"&&",
"!",
"currentInfo",
".",
"hasBaseType",
"(",
")",
")",
"{",
"currentInfo",
".",
"setBaseType",
"(",
"jsType",
")",
";",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a base type.
@return {@code true} if the base type was recorded and {@code false}
if it was already defined | [
"Records",
"a",
"base",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L706-L715 |
24,531 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.changeBaseType | public boolean changeBaseType(JSTypeExpression jsType) {
if (jsType != null && !hasAnySingletonTypeTags()) {
currentInfo.setBaseType(jsType);
populated = true;
return true;
} else {
return false;
}
} | java | public boolean changeBaseType(JSTypeExpression jsType) {
if (jsType != null && !hasAnySingletonTypeTags()) {
currentInfo.setBaseType(jsType);
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"changeBaseType",
"(",
"JSTypeExpression",
"jsType",
")",
"{",
"if",
"(",
"jsType",
"!=",
"null",
"&&",
"!",
"hasAnySingletonTypeTags",
"(",
")",
")",
"{",
"currentInfo",
".",
"setBaseType",
"(",
"jsType",
")",
";",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Changes a base type, even if one has already been set on currentInfo.
@return {@code true} if the base type was changed successfully. | [
"Changes",
"a",
"base",
"type",
"even",
"if",
"one",
"has",
"already",
"been",
"set",
"on",
"currentInfo",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L722-L730 |
24,532 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordClosurePrimitiveId | public boolean recordClosurePrimitiveId(String closurePrimitiveId) {
if (closurePrimitiveId != null && currentInfo.getClosurePrimitiveId() == null) {
currentInfo.setClosurePrimitiveId(closurePrimitiveId);
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordClosurePrimitiveId(String closurePrimitiveId) {
if (closurePrimitiveId != null && currentInfo.getClosurePrimitiveId() == null) {
currentInfo.setClosurePrimitiveId(closurePrimitiveId);
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordClosurePrimitiveId",
"(",
"String",
"closurePrimitiveId",
")",
"{",
"if",
"(",
"closurePrimitiveId",
"!=",
"null",
"&&",
"currentInfo",
".",
"getClosurePrimitiveId",
"(",
")",
"==",
"null",
")",
"{",
"currentInfo",
".",
"setClosurePrimitiveId",
"(",
"closurePrimitiveId",
")",
";",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records an identifier for a Closure Primitive. function.
@return {@code true} If the id was successfully updated. | [
"Records",
"an",
"identifier",
"for",
"a",
"Closure",
"Primitive",
".",
"function",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L802-L810 |
24,533 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordFileOverview | public boolean recordFileOverview(String description) {
if (currentInfo.documentFileOverview(description)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordFileOverview(String description) {
if (currentInfo.documentFileOverview(description)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordFileOverview",
"(",
"String",
"description",
")",
"{",
"if",
"(",
"currentInfo",
".",
"documentFileOverview",
"(",
"description",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records a fileoverview description.
@return {@code true} if the description was recorded and {@code false}
if the description was invalid or was already defined. | [
"Records",
"a",
"fileoverview",
"description",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L818-L825 |
24,534 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordImplementedInterface | public boolean recordImplementedInterface(JSTypeExpression interfaceName) {
if (interfaceName != null && currentInfo.addImplementedInterface(interfaceName)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordImplementedInterface(JSTypeExpression interfaceName) {
if (interfaceName != null && currentInfo.addImplementedInterface(interfaceName)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordImplementedInterface",
"(",
"JSTypeExpression",
"interfaceName",
")",
"{",
"if",
"(",
"interfaceName",
"!=",
"null",
"&&",
"currentInfo",
".",
"addImplementedInterface",
"(",
"interfaceName",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records an implemented interface. | [
"Records",
"an",
"implemented",
"interface",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L1202-L1209 |
24,535 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordExtendedInterface | public boolean recordExtendedInterface(JSTypeExpression interfaceType) {
if (interfaceType != null && currentInfo.addExtendedInterface(interfaceType)) {
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordExtendedInterface(JSTypeExpression interfaceType) {
if (interfaceType != null && currentInfo.addExtendedInterface(interfaceType)) {
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordExtendedInterface",
"(",
"JSTypeExpression",
"interfaceType",
")",
"{",
"if",
"(",
"interfaceType",
"!=",
"null",
"&&",
"currentInfo",
".",
"addExtendedInterface",
"(",
"interfaceType",
")",
")",
"{",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records an extended interface type. | [
"Records",
"an",
"extended",
"interface",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L1214-L1221 |
24,536 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordLends | public boolean recordLends(JSTypeExpression name) {
if (!hasAnyTypeRelatedTags()) {
currentInfo.setLendsName(name);
populated = true;
return true;
} else {
return false;
}
} | java | public boolean recordLends(JSTypeExpression name) {
if (!hasAnyTypeRelatedTags()) {
currentInfo.setLendsName(name);
populated = true;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"recordLends",
"(",
"JSTypeExpression",
"name",
")",
"{",
"if",
"(",
"!",
"hasAnyTypeRelatedTags",
"(",
")",
")",
"{",
"currentInfo",
".",
"setLendsName",
"(",
"name",
")",
";",
"populated",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Records that we're lending to another name. | [
"Records",
"that",
"we",
"re",
"lending",
"to",
"another",
"name",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L1224-L1232 |
24,537 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfoBuilder.java | JSDocInfoBuilder.recordDisposesParameter | public boolean recordDisposesParameter(List<String> parameterNames) {
for (String parameterName : parameterNames) {
if ((currentInfo.hasParameter(parameterName) ||
parameterName.equals("*")) &&
currentInfo.setDisposedParameter(parameterName)) {
populated = true;
} else {
return false;
}
}
return true;
} | java | public boolean recordDisposesParameter(List<String> parameterNames) {
for (String parameterName : parameterNames) {
if ((currentInfo.hasParameter(parameterName) ||
parameterName.equals("*")) &&
currentInfo.setDisposedParameter(parameterName)) {
populated = true;
} else {
return false;
}
}
return true;
} | [
"public",
"boolean",
"recordDisposesParameter",
"(",
"List",
"<",
"String",
">",
"parameterNames",
")",
"{",
"for",
"(",
"String",
"parameterName",
":",
"parameterNames",
")",
"{",
"if",
"(",
"(",
"currentInfo",
".",
"hasParameter",
"(",
"parameterName",
")",
"||",
"parameterName",
".",
"equals",
"(",
"\"*\"",
")",
")",
"&&",
"currentInfo",
".",
"setDisposedParameter",
"(",
"parameterName",
")",
")",
"{",
"populated",
"=",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Records a parameter that gets disposed.
@return {@code true} if all the parameters was recorded and
{@code false} if a parameter with the same name was already defined | [
"Records",
"a",
"parameter",
"that",
"gets",
"disposed",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfoBuilder.java#L1367-L1378 |
24,538 | google/closure-compiler | src/com/google/javascript/jscomp/RenameVars.java | RenameVars.reusePreviouslyUsedVariableMap | private void reusePreviouslyUsedVariableMap(SortedSet<Assignment> varsToRename) {
// If prevUsedRenameMap had duplicate values then this pass would be
// non-deterministic.
// In such a case, the following will throw an IllegalArgumentException.
checkNotNull(prevUsedRenameMap.getNewNameToOriginalNameMap());
for (Assignment a : varsToRename) {
String prevNewName = prevUsedRenameMap.lookupNewName(a.oldName);
if (prevNewName == null || reservedNames.contains(prevNewName)) {
continue;
}
if (a.isLocal
|| (!externNames.contains(a.oldName)
&& prevNewName.startsWith(prefix))) {
reservedNames.add(prevNewName);
finalizeNameAssignment(a, prevNewName);
}
}
} | java | private void reusePreviouslyUsedVariableMap(SortedSet<Assignment> varsToRename) {
// If prevUsedRenameMap had duplicate values then this pass would be
// non-deterministic.
// In such a case, the following will throw an IllegalArgumentException.
checkNotNull(prevUsedRenameMap.getNewNameToOriginalNameMap());
for (Assignment a : varsToRename) {
String prevNewName = prevUsedRenameMap.lookupNewName(a.oldName);
if (prevNewName == null || reservedNames.contains(prevNewName)) {
continue;
}
if (a.isLocal
|| (!externNames.contains(a.oldName)
&& prevNewName.startsWith(prefix))) {
reservedNames.add(prevNewName);
finalizeNameAssignment(a, prevNewName);
}
}
} | [
"private",
"void",
"reusePreviouslyUsedVariableMap",
"(",
"SortedSet",
"<",
"Assignment",
">",
"varsToRename",
")",
"{",
"// If prevUsedRenameMap had duplicate values then this pass would be",
"// non-deterministic.",
"// In such a case, the following will throw an IllegalArgumentException.",
"checkNotNull",
"(",
"prevUsedRenameMap",
".",
"getNewNameToOriginalNameMap",
"(",
")",
")",
";",
"for",
"(",
"Assignment",
"a",
":",
"varsToRename",
")",
"{",
"String",
"prevNewName",
"=",
"prevUsedRenameMap",
".",
"lookupNewName",
"(",
"a",
".",
"oldName",
")",
";",
"if",
"(",
"prevNewName",
"==",
"null",
"||",
"reservedNames",
".",
"contains",
"(",
"prevNewName",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"a",
".",
"isLocal",
"||",
"(",
"!",
"externNames",
".",
"contains",
"(",
"a",
".",
"oldName",
")",
"&&",
"prevNewName",
".",
"startsWith",
"(",
"prefix",
")",
")",
")",
"{",
"reservedNames",
".",
"add",
"(",
"prevNewName",
")",
";",
"finalizeNameAssignment",
"(",
"a",
",",
"prevNewName",
")",
";",
"}",
"}",
"}"
] | Runs through the assignments and reuses as many names as possible from the previously used
variable map. Updates reservedNames with the set of names that were reused. | [
"Runs",
"through",
"the",
"assignments",
"and",
"reuses",
"as",
"many",
"names",
"as",
"possible",
"from",
"the",
"previously",
"used",
"variable",
"map",
".",
"Updates",
"reservedNames",
"with",
"the",
"set",
"of",
"names",
"that",
"were",
"reused",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RenameVars.java#L440-L458 |
24,539 | google/closure-compiler | src/com/google/javascript/jscomp/RenameVars.java | RenameVars.assignNames | private void assignNames(SortedSet<Assignment> varsToRename) {
NameGenerator globalNameGenerator = null;
NameGenerator localNameGenerator = null;
globalNameGenerator = nameGenerator;
nameGenerator.reset(reservedNames, prefix, reservedCharacters);
// Local variables never need a prefix.
// Also, we need to avoid conflicts between global and local variable
// names; we do this by having using the same generator (not two
// instances). The case where global variables have a prefix (and
// therefore we use two different generators) but a local variable name
// might nevertheless conflict with a global one is not handled.
localNameGenerator =
prefix.isEmpty()
? globalNameGenerator
: nameGenerator.clone(reservedNames, "", reservedCharacters);
// Generated names and the assignments for non-local vars.
List<Assignment> pendingAssignments = new ArrayList<>();
List<String> generatedNamesForAssignments = new ArrayList<>();
for (Assignment a : varsToRename) {
if (a.newName != null) {
continue;
}
if (externNames.contains(a.oldName)) {
continue;
}
String newName;
if (a.isLocal) {
// For local variable, we make the assignment right away.
newName = localNameGenerator.generateNextName();
finalizeNameAssignment(a, newName);
} else {
// For non-local variable, delay finalizing the name assignment
// until we know how many new names we'll have of length 2, 3, etc.
newName = globalNameGenerator.generateNextName();
pendingAssignments.add(a);
generatedNamesForAssignments.add(newName);
}
reservedNames.add(newName);
}
// Now that we have a list of generated names, and a list of variable
// Assignment objects, we assign the generated names to the vars as
// follows:
// 1) The most frequent vars get the shorter names.
// 2) If N number of vars are going to be assigned names of the same
// length, we assign the N names based on the order at which the vars
// first appear in the source. This makes the output somewhat less
// random, because symbols declared close together are assigned names
// that are quite similar. With this heuristic, the output is more
// compressible.
// For instance, the output may look like:
// var da = "..", ea = "..";
// function fa() { .. } function ga() { .. }
int numPendingAssignments = generatedNamesForAssignments.size();
for (int i = 0; i < numPendingAssignments;) {
SortedSet<Assignment> varsByOrderOfOccurrence =
new TreeSet<>(ORDER_OF_OCCURRENCE_COMPARATOR);
// Add k number of Assignment to the set, where k is the number of
// generated names of the same length.
int len = generatedNamesForAssignments.get(i).length();
for (int j = i; j < numPendingAssignments
&& generatedNamesForAssignments.get(j).length() == len; j++) {
varsByOrderOfOccurrence.add(pendingAssignments.get(j));
}
// Now, make the assignments
for (Assignment a : varsByOrderOfOccurrence) {
finalizeNameAssignment(a, generatedNamesForAssignments.get(i));
++i;
}
}
} | java | private void assignNames(SortedSet<Assignment> varsToRename) {
NameGenerator globalNameGenerator = null;
NameGenerator localNameGenerator = null;
globalNameGenerator = nameGenerator;
nameGenerator.reset(reservedNames, prefix, reservedCharacters);
// Local variables never need a prefix.
// Also, we need to avoid conflicts between global and local variable
// names; we do this by having using the same generator (not two
// instances). The case where global variables have a prefix (and
// therefore we use two different generators) but a local variable name
// might nevertheless conflict with a global one is not handled.
localNameGenerator =
prefix.isEmpty()
? globalNameGenerator
: nameGenerator.clone(reservedNames, "", reservedCharacters);
// Generated names and the assignments for non-local vars.
List<Assignment> pendingAssignments = new ArrayList<>();
List<String> generatedNamesForAssignments = new ArrayList<>();
for (Assignment a : varsToRename) {
if (a.newName != null) {
continue;
}
if (externNames.contains(a.oldName)) {
continue;
}
String newName;
if (a.isLocal) {
// For local variable, we make the assignment right away.
newName = localNameGenerator.generateNextName();
finalizeNameAssignment(a, newName);
} else {
// For non-local variable, delay finalizing the name assignment
// until we know how many new names we'll have of length 2, 3, etc.
newName = globalNameGenerator.generateNextName();
pendingAssignments.add(a);
generatedNamesForAssignments.add(newName);
}
reservedNames.add(newName);
}
// Now that we have a list of generated names, and a list of variable
// Assignment objects, we assign the generated names to the vars as
// follows:
// 1) The most frequent vars get the shorter names.
// 2) If N number of vars are going to be assigned names of the same
// length, we assign the N names based on the order at which the vars
// first appear in the source. This makes the output somewhat less
// random, because symbols declared close together are assigned names
// that are quite similar. With this heuristic, the output is more
// compressible.
// For instance, the output may look like:
// var da = "..", ea = "..";
// function fa() { .. } function ga() { .. }
int numPendingAssignments = generatedNamesForAssignments.size();
for (int i = 0; i < numPendingAssignments;) {
SortedSet<Assignment> varsByOrderOfOccurrence =
new TreeSet<>(ORDER_OF_OCCURRENCE_COMPARATOR);
// Add k number of Assignment to the set, where k is the number of
// generated names of the same length.
int len = generatedNamesForAssignments.get(i).length();
for (int j = i; j < numPendingAssignments
&& generatedNamesForAssignments.get(j).length() == len; j++) {
varsByOrderOfOccurrence.add(pendingAssignments.get(j));
}
// Now, make the assignments
for (Assignment a : varsByOrderOfOccurrence) {
finalizeNameAssignment(a, generatedNamesForAssignments.get(i));
++i;
}
}
} | [
"private",
"void",
"assignNames",
"(",
"SortedSet",
"<",
"Assignment",
">",
"varsToRename",
")",
"{",
"NameGenerator",
"globalNameGenerator",
"=",
"null",
";",
"NameGenerator",
"localNameGenerator",
"=",
"null",
";",
"globalNameGenerator",
"=",
"nameGenerator",
";",
"nameGenerator",
".",
"reset",
"(",
"reservedNames",
",",
"prefix",
",",
"reservedCharacters",
")",
";",
"// Local variables never need a prefix.",
"// Also, we need to avoid conflicts between global and local variable",
"// names; we do this by having using the same generator (not two",
"// instances). The case where global variables have a prefix (and",
"// therefore we use two different generators) but a local variable name",
"// might nevertheless conflict with a global one is not handled.",
"localNameGenerator",
"=",
"prefix",
".",
"isEmpty",
"(",
")",
"?",
"globalNameGenerator",
":",
"nameGenerator",
".",
"clone",
"(",
"reservedNames",
",",
"\"\"",
",",
"reservedCharacters",
")",
";",
"// Generated names and the assignments for non-local vars.",
"List",
"<",
"Assignment",
">",
"pendingAssignments",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"List",
"<",
"String",
">",
"generatedNamesForAssignments",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"Assignment",
"a",
":",
"varsToRename",
")",
"{",
"if",
"(",
"a",
".",
"newName",
"!=",
"null",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"externNames",
".",
"contains",
"(",
"a",
".",
"oldName",
")",
")",
"{",
"continue",
";",
"}",
"String",
"newName",
";",
"if",
"(",
"a",
".",
"isLocal",
")",
"{",
"// For local variable, we make the assignment right away.",
"newName",
"=",
"localNameGenerator",
".",
"generateNextName",
"(",
")",
";",
"finalizeNameAssignment",
"(",
"a",
",",
"newName",
")",
";",
"}",
"else",
"{",
"// For non-local variable, delay finalizing the name assignment",
"// until we know how many new names we'll have of length 2, 3, etc.",
"newName",
"=",
"globalNameGenerator",
".",
"generateNextName",
"(",
")",
";",
"pendingAssignments",
".",
"add",
"(",
"a",
")",
";",
"generatedNamesForAssignments",
".",
"add",
"(",
"newName",
")",
";",
"}",
"reservedNames",
".",
"add",
"(",
"newName",
")",
";",
"}",
"// Now that we have a list of generated names, and a list of variable",
"// Assignment objects, we assign the generated names to the vars as",
"// follows:",
"// 1) The most frequent vars get the shorter names.",
"// 2) If N number of vars are going to be assigned names of the same",
"// length, we assign the N names based on the order at which the vars",
"// first appear in the source. This makes the output somewhat less",
"// random, because symbols declared close together are assigned names",
"// that are quite similar. With this heuristic, the output is more",
"// compressible.",
"// For instance, the output may look like:",
"// var da = \"..\", ea = \"..\";",
"// function fa() { .. } function ga() { .. }",
"int",
"numPendingAssignments",
"=",
"generatedNamesForAssignments",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numPendingAssignments",
";",
")",
"{",
"SortedSet",
"<",
"Assignment",
">",
"varsByOrderOfOccurrence",
"=",
"new",
"TreeSet",
"<>",
"(",
"ORDER_OF_OCCURRENCE_COMPARATOR",
")",
";",
"// Add k number of Assignment to the set, where k is the number of",
"// generated names of the same length.",
"int",
"len",
"=",
"generatedNamesForAssignments",
".",
"get",
"(",
"i",
")",
".",
"length",
"(",
")",
";",
"for",
"(",
"int",
"j",
"=",
"i",
";",
"j",
"<",
"numPendingAssignments",
"&&",
"generatedNamesForAssignments",
".",
"get",
"(",
"j",
")",
".",
"length",
"(",
")",
"==",
"len",
";",
"j",
"++",
")",
"{",
"varsByOrderOfOccurrence",
".",
"add",
"(",
"pendingAssignments",
".",
"get",
"(",
"j",
")",
")",
";",
"}",
"// Now, make the assignments",
"for",
"(",
"Assignment",
"a",
":",
"varsByOrderOfOccurrence",
")",
"{",
"finalizeNameAssignment",
"(",
"a",
",",
"generatedNamesForAssignments",
".",
"get",
"(",
"i",
")",
")",
";",
"++",
"i",
";",
"}",
"}",
"}"
] | Determines which new names to substitute for the original names. | [
"Determines",
"which",
"new",
"names",
"to",
"substitute",
"for",
"the",
"original",
"names",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RenameVars.java#L463-L542 |
24,540 | google/closure-compiler | src/com/google/javascript/jscomp/RenameVars.java | RenameVars.finalizeNameAssignment | private void finalizeNameAssignment(Assignment a, String newName) {
a.setNewName(newName);
// Keep track of the mapping
renameMap.put(a.oldName, newName);
} | java | private void finalizeNameAssignment(Assignment a, String newName) {
a.setNewName(newName);
// Keep track of the mapping
renameMap.put(a.oldName, newName);
} | [
"private",
"void",
"finalizeNameAssignment",
"(",
"Assignment",
"a",
",",
"String",
"newName",
")",
"{",
"a",
".",
"setNewName",
"(",
"newName",
")",
";",
"// Keep track of the mapping",
"renameMap",
".",
"put",
"(",
"a",
".",
"oldName",
",",
"newName",
")",
";",
"}"
] | Makes a final name assignment. | [
"Makes",
"a",
"final",
"name",
"assignment",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RenameVars.java#L547-L552 |
24,541 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java | FeatureSet.version | public String version() {
if (ES3.contains(this)) {
return "es3";
}
if (ES5.contains(this)) {
return "es5";
}
if (ES6_MODULES.contains(this)) {
return "es6";
}
if (ES7_MODULES.contains(this)) {
return "es7";
}
if (ES8_MODULES.contains(this)) {
return "es8";
}
if (ES2018_MODULES.contains(this)) {
return "es9";
}
if (ES2019_MODULES.contains(this)) {
return "es_2019";
}
if (ES_NEXT.contains(this)) {
return "es_next";
}
if (ES_UNSUPPORTED.contains(this)) {
return "es_unsupported";
}
if (TYPESCRIPT.contains(this)) {
return "ts";
}
throw new IllegalStateException(this.toString());
} | java | public String version() {
if (ES3.contains(this)) {
return "es3";
}
if (ES5.contains(this)) {
return "es5";
}
if (ES6_MODULES.contains(this)) {
return "es6";
}
if (ES7_MODULES.contains(this)) {
return "es7";
}
if (ES8_MODULES.contains(this)) {
return "es8";
}
if (ES2018_MODULES.contains(this)) {
return "es9";
}
if (ES2019_MODULES.contains(this)) {
return "es_2019";
}
if (ES_NEXT.contains(this)) {
return "es_next";
}
if (ES_UNSUPPORTED.contains(this)) {
return "es_unsupported";
}
if (TYPESCRIPT.contains(this)) {
return "ts";
}
throw new IllegalStateException(this.toString());
} | [
"public",
"String",
"version",
"(",
")",
"{",
"if",
"(",
"ES3",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"es3\"",
";",
"}",
"if",
"(",
"ES5",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"es5\"",
";",
"}",
"if",
"(",
"ES6_MODULES",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"es6\"",
";",
"}",
"if",
"(",
"ES7_MODULES",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"es7\"",
";",
"}",
"if",
"(",
"ES8_MODULES",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"es8\"",
";",
"}",
"if",
"(",
"ES2018_MODULES",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"es9\"",
";",
"}",
"if",
"(",
"ES2019_MODULES",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"es_2019\"",
";",
"}",
"if",
"(",
"ES_NEXT",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"es_next\"",
";",
"}",
"if",
"(",
"ES_UNSUPPORTED",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"es_unsupported\"",
";",
"}",
"if",
"(",
"TYPESCRIPT",
".",
"contains",
"(",
"this",
")",
")",
"{",
"return",
"\"ts\"",
";",
"}",
"throw",
"new",
"IllegalStateException",
"(",
"this",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Returns a string representation suitable for encoding in depgraph and deps.js files. | [
"Returns",
"a",
"string",
"representation",
"suitable",
"for",
"encoding",
"in",
"depgraph",
"and",
"deps",
".",
"js",
"files",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java#L222-L254 |
24,542 | google/closure-compiler | src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java | FeatureSet.valueOf | public static FeatureSet valueOf(String name) {
switch (name) {
case "es3":
return ES3;
case "es5":
return ES5;
case "es6-impl":
case "es6":
return ES6;
case "typeCheckSupported":
return TYPE_CHECK_SUPPORTED;
case "es7":
return ES7;
case "es8":
return ES8;
case "es2018":
case "es9":
return ES2018;
case "es_2019":
return ES2019;
case "es_next":
return ES_NEXT;
case "ts":
return TYPESCRIPT;
default:
throw new IllegalArgumentException("No such FeatureSet: " + name);
}
} | java | public static FeatureSet valueOf(String name) {
switch (name) {
case "es3":
return ES3;
case "es5":
return ES5;
case "es6-impl":
case "es6":
return ES6;
case "typeCheckSupported":
return TYPE_CHECK_SUPPORTED;
case "es7":
return ES7;
case "es8":
return ES8;
case "es2018":
case "es9":
return ES2018;
case "es_2019":
return ES2019;
case "es_next":
return ES_NEXT;
case "ts":
return TYPESCRIPT;
default:
throw new IllegalArgumentException("No such FeatureSet: " + name);
}
} | [
"public",
"static",
"FeatureSet",
"valueOf",
"(",
"String",
"name",
")",
"{",
"switch",
"(",
"name",
")",
"{",
"case",
"\"es3\"",
":",
"return",
"ES3",
";",
"case",
"\"es5\"",
":",
"return",
"ES5",
";",
"case",
"\"es6-impl\"",
":",
"case",
"\"es6\"",
":",
"return",
"ES6",
";",
"case",
"\"typeCheckSupported\"",
":",
"return",
"TYPE_CHECK_SUPPORTED",
";",
"case",
"\"es7\"",
":",
"return",
"ES7",
";",
"case",
"\"es8\"",
":",
"return",
"ES8",
";",
"case",
"\"es2018\"",
":",
"case",
"\"es9\"",
":",
"return",
"ES2018",
";",
"case",
"\"es_2019\"",
":",
"return",
"ES2019",
";",
"case",
"\"es_next\"",
":",
"return",
"ES_NEXT",
";",
"case",
"\"ts\"",
":",
"return",
"TYPESCRIPT",
";",
"default",
":",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"No such FeatureSet: \"",
"+",
"name",
")",
";",
"}",
"}"
] | Parses known strings into feature sets. | [
"Parses",
"known",
"strings",
"into",
"feature",
"sets",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java#L411-L438 |
24,543 | google/closure-compiler | src/com/google/javascript/jscomp/deps/DepsGenerator.java | DepsGenerator.computeDependencyCalls | public String computeDependencyCalls() throws IOException {
// Build a map of closure-relative path -> DepInfo.
Map<String, DependencyInfo> depsFiles = parseDepsFiles();
if (logger.isLoggable(Level.FINE)) {
logger.fine("preparsedFiles: " + depsFiles);
}
// Find all goog.provides & goog.requires in src files
Map<String, DependencyInfo> jsFiles = parseSources(depsFiles.keySet());
// Check if there were any parse errors.
if (errorManager.getErrorCount() > 0) {
return null;
}
cleanUpDuplicatedFiles(depsFiles, jsFiles);
jsFiles = removeMungedSymbols(depsFiles, jsFiles);
// Check for missing provides or other semantic inconsistencies.
validateDependencies(depsFiles.values(), jsFiles.values());
if (errorManager.getErrorCount() > 0) {
return null;
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
writeDepsContent(depsFiles, jsFiles, new PrintStream(output));
return new String(output.toByteArray(), UTF_8);
} | java | public String computeDependencyCalls() throws IOException {
// Build a map of closure-relative path -> DepInfo.
Map<String, DependencyInfo> depsFiles = parseDepsFiles();
if (logger.isLoggable(Level.FINE)) {
logger.fine("preparsedFiles: " + depsFiles);
}
// Find all goog.provides & goog.requires in src files
Map<String, DependencyInfo> jsFiles = parseSources(depsFiles.keySet());
// Check if there were any parse errors.
if (errorManager.getErrorCount() > 0) {
return null;
}
cleanUpDuplicatedFiles(depsFiles, jsFiles);
jsFiles = removeMungedSymbols(depsFiles, jsFiles);
// Check for missing provides or other semantic inconsistencies.
validateDependencies(depsFiles.values(), jsFiles.values());
if (errorManager.getErrorCount() > 0) {
return null;
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
writeDepsContent(depsFiles, jsFiles, new PrintStream(output));
return new String(output.toByteArray(), UTF_8);
} | [
"public",
"String",
"computeDependencyCalls",
"(",
")",
"throws",
"IOException",
"{",
"// Build a map of closure-relative path -> DepInfo.",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"depsFiles",
"=",
"parseDepsFiles",
"(",
")",
";",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"FINE",
")",
")",
"{",
"logger",
".",
"fine",
"(",
"\"preparsedFiles: \"",
"+",
"depsFiles",
")",
";",
"}",
"// Find all goog.provides & goog.requires in src files",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"jsFiles",
"=",
"parseSources",
"(",
"depsFiles",
".",
"keySet",
"(",
")",
")",
";",
"// Check if there were any parse errors.",
"if",
"(",
"errorManager",
".",
"getErrorCount",
"(",
")",
">",
"0",
")",
"{",
"return",
"null",
";",
"}",
"cleanUpDuplicatedFiles",
"(",
"depsFiles",
",",
"jsFiles",
")",
";",
"jsFiles",
"=",
"removeMungedSymbols",
"(",
"depsFiles",
",",
"jsFiles",
")",
";",
"// Check for missing provides or other semantic inconsistencies.",
"validateDependencies",
"(",
"depsFiles",
".",
"values",
"(",
")",
",",
"jsFiles",
".",
"values",
"(",
")",
")",
";",
"if",
"(",
"errorManager",
".",
"getErrorCount",
"(",
")",
">",
"0",
")",
"{",
"return",
"null",
";",
"}",
"ByteArrayOutputStream",
"output",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"writeDepsContent",
"(",
"depsFiles",
",",
"jsFiles",
",",
"new",
"PrintStream",
"(",
"output",
")",
")",
";",
"return",
"new",
"String",
"(",
"output",
".",
"toByteArray",
"(",
")",
",",
"UTF_8",
")",
";",
"}"
] | Performs the parsing inputs and writing of outputs.
@throws IOException Occurs upon an IO error.
@return Returns a String of goog.addDependency calls that will build
the dependency graph. Returns null if there was an error. | [
"Performs",
"the",
"parsing",
"inputs",
"and",
"writing",
"of",
"outputs",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DepsGenerator.java#L134-L162 |
24,544 | google/closure-compiler | src/com/google/javascript/jscomp/deps/DepsGenerator.java | DepsGenerator.cleanUpDuplicatedFiles | protected void cleanUpDuplicatedFiles(Map<String, DependencyInfo> depsFiles,
Map<String, DependencyInfo> jsFiles) {
Set<String> depsPathsCopy = new HashSet<>(depsFiles.keySet());
for (String path : depsPathsCopy) {
if (mergeStrategy != InclusionStrategy.WHEN_IN_SRCS) {
jsFiles.remove(path);
}
}
for (String path : jsFiles.keySet()) {
// If a generated file appears in both the jsFiles and in depsFiles, then
// remove it from depsFiles in order to get the full path the generated
// file.
depsFiles.remove(path);
}
} | java | protected void cleanUpDuplicatedFiles(Map<String, DependencyInfo> depsFiles,
Map<String, DependencyInfo> jsFiles) {
Set<String> depsPathsCopy = new HashSet<>(depsFiles.keySet());
for (String path : depsPathsCopy) {
if (mergeStrategy != InclusionStrategy.WHEN_IN_SRCS) {
jsFiles.remove(path);
}
}
for (String path : jsFiles.keySet()) {
// If a generated file appears in both the jsFiles and in depsFiles, then
// remove it from depsFiles in order to get the full path the generated
// file.
depsFiles.remove(path);
}
} | [
"protected",
"void",
"cleanUpDuplicatedFiles",
"(",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"depsFiles",
",",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"jsFiles",
")",
"{",
"Set",
"<",
"String",
">",
"depsPathsCopy",
"=",
"new",
"HashSet",
"<>",
"(",
"depsFiles",
".",
"keySet",
"(",
")",
")",
";",
"for",
"(",
"String",
"path",
":",
"depsPathsCopy",
")",
"{",
"if",
"(",
"mergeStrategy",
"!=",
"InclusionStrategy",
".",
"WHEN_IN_SRCS",
")",
"{",
"jsFiles",
".",
"remove",
"(",
"path",
")",
";",
"}",
"}",
"for",
"(",
"String",
"path",
":",
"jsFiles",
".",
"keySet",
"(",
")",
")",
"{",
"// If a generated file appears in both the jsFiles and in depsFiles, then",
"// remove it from depsFiles in order to get the full path the generated",
"// file.",
"depsFiles",
".",
"remove",
"(",
"path",
")",
";",
"}",
"}"
] | Removes duplicated depsInfo from jsFiles if this info already present in
some of the parsed deps.js
@param depsFiles DepsInfo from deps.js dependencies
@param jsFiles DepsInfo from some of jsSources | [
"Removes",
"duplicated",
"depsInfo",
"from",
"jsFiles",
"if",
"this",
"info",
"already",
"present",
"in",
"some",
"of",
"the",
"parsed",
"deps",
".",
"js"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DepsGenerator.java#L171-L186 |
24,545 | google/closure-compiler | src/com/google/javascript/jscomp/deps/DepsGenerator.java | DepsGenerator.addToProvideMap | private void addToProvideMap(
Iterable<DependencyInfo> depInfos,
Map<String, DependencyInfo> providesMap,
boolean isFromDepsFile) {
for (DependencyInfo depInfo : depInfos) {
List<String> provides = new ArrayList<>(depInfo.getProvides());
// Add a munged symbol to the provides map so that lookups by path requires work as intended.
if (isFromDepsFile) {
// Don't add the dependency file itself but every file it says exists instead.
provides.add(
loader
.resolve(
PathUtil.makeAbsolute(depInfo.getPathRelativeToClosureBase(), closurePathAbs))
.toModuleName());
} else {
// ES6 modules already provide these munged symbols.
if (!"es6".equals(depInfo.getLoadFlags().get("module"))) {
provides.add(loader.resolve(depInfo.getName()).toModuleName());
}
}
// Also add the relative closure path as a provide. At some point we'll swap out the munged
// symbols for these relative paths. So looks ups by either need to work.
provides.add(depInfo.getPathRelativeToClosureBase());
for (String provide : provides) {
DependencyInfo prevValue = providesMap.put(provide, depInfo);
// Check for duplicate provides.
if (prevValue != null) {
reportDuplicateProvide(provide, prevValue, depInfo);
}
}
}
} | java | private void addToProvideMap(
Iterable<DependencyInfo> depInfos,
Map<String, DependencyInfo> providesMap,
boolean isFromDepsFile) {
for (DependencyInfo depInfo : depInfos) {
List<String> provides = new ArrayList<>(depInfo.getProvides());
// Add a munged symbol to the provides map so that lookups by path requires work as intended.
if (isFromDepsFile) {
// Don't add the dependency file itself but every file it says exists instead.
provides.add(
loader
.resolve(
PathUtil.makeAbsolute(depInfo.getPathRelativeToClosureBase(), closurePathAbs))
.toModuleName());
} else {
// ES6 modules already provide these munged symbols.
if (!"es6".equals(depInfo.getLoadFlags().get("module"))) {
provides.add(loader.resolve(depInfo.getName()).toModuleName());
}
}
// Also add the relative closure path as a provide. At some point we'll swap out the munged
// symbols for these relative paths. So looks ups by either need to work.
provides.add(depInfo.getPathRelativeToClosureBase());
for (String provide : provides) {
DependencyInfo prevValue = providesMap.put(provide, depInfo);
// Check for duplicate provides.
if (prevValue != null) {
reportDuplicateProvide(provide, prevValue, depInfo);
}
}
}
} | [
"private",
"void",
"addToProvideMap",
"(",
"Iterable",
"<",
"DependencyInfo",
">",
"depInfos",
",",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"providesMap",
",",
"boolean",
"isFromDepsFile",
")",
"{",
"for",
"(",
"DependencyInfo",
"depInfo",
":",
"depInfos",
")",
"{",
"List",
"<",
"String",
">",
"provides",
"=",
"new",
"ArrayList",
"<>",
"(",
"depInfo",
".",
"getProvides",
"(",
")",
")",
";",
"// Add a munged symbol to the provides map so that lookups by path requires work as intended.",
"if",
"(",
"isFromDepsFile",
")",
"{",
"// Don't add the dependency file itself but every file it says exists instead.",
"provides",
".",
"add",
"(",
"loader",
".",
"resolve",
"(",
"PathUtil",
".",
"makeAbsolute",
"(",
"depInfo",
".",
"getPathRelativeToClosureBase",
"(",
")",
",",
"closurePathAbs",
")",
")",
".",
"toModuleName",
"(",
")",
")",
";",
"}",
"else",
"{",
"// ES6 modules already provide these munged symbols.",
"if",
"(",
"!",
"\"es6\"",
".",
"equals",
"(",
"depInfo",
".",
"getLoadFlags",
"(",
")",
".",
"get",
"(",
"\"module\"",
")",
")",
")",
"{",
"provides",
".",
"add",
"(",
"loader",
".",
"resolve",
"(",
"depInfo",
".",
"getName",
"(",
")",
")",
".",
"toModuleName",
"(",
")",
")",
";",
"}",
"}",
"// Also add the relative closure path as a provide. At some point we'll swap out the munged",
"// symbols for these relative paths. So looks ups by either need to work.",
"provides",
".",
"add",
"(",
"depInfo",
".",
"getPathRelativeToClosureBase",
"(",
")",
")",
";",
"for",
"(",
"String",
"provide",
":",
"provides",
")",
"{",
"DependencyInfo",
"prevValue",
"=",
"providesMap",
".",
"put",
"(",
"provide",
",",
"depInfo",
")",
";",
"// Check for duplicate provides.",
"if",
"(",
"prevValue",
"!=",
"null",
")",
"{",
"reportDuplicateProvide",
"(",
"provide",
",",
"prevValue",
",",
"depInfo",
")",
";",
"}",
"}",
"}",
"}"
] | Adds the given DependencyInfos to the given providesMap. Also checks for and reports duplicate
provides. | [
"Adds",
"the",
"given",
"DependencyInfos",
"to",
"the",
"given",
"providesMap",
".",
"Also",
"checks",
"for",
"and",
"reports",
"duplicate",
"provides",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DepsGenerator.java#L370-L404 |
24,546 | google/closure-compiler | src/com/google/javascript/jscomp/deps/DepsGenerator.java | DepsGenerator.parseDepsFiles | private Map<String, DependencyInfo> parseDepsFiles() throws IOException {
DepsFileParser depsParser = createDepsFileParser();
Map<String, DependencyInfo> depsFiles = new LinkedHashMap<>();
for (SourceFile file : deps) {
if (!shouldSkipDepsFile(file)) {
List<DependencyInfo>
depInfos = depsParser.parseFileReader(
file.getName(), file.getCodeReader());
if (depInfos.isEmpty()) {
reportNoDepsInDepsFile(file.getName());
} else {
for (DependencyInfo info : depInfos) {
depsFiles.put(info.getPathRelativeToClosureBase(), removeRelativePathProvide(info));
}
}
}
}
// If a deps file also appears in srcs, our build tools will move it
// into srcs. So we need to scan all the src files for addDependency
// calls as well.
for (SourceFile src : srcs) {
if (!shouldSkipDepsFile(src)) {
List<DependencyInfo> srcInfos =
depsParser.parseFileReader(src.getName(), src.getCodeReader());
for (DependencyInfo info : srcInfos) {
depsFiles.put(info.getPathRelativeToClosureBase(), removeRelativePathProvide(info));
}
}
}
return depsFiles;
} | java | private Map<String, DependencyInfo> parseDepsFiles() throws IOException {
DepsFileParser depsParser = createDepsFileParser();
Map<String, DependencyInfo> depsFiles = new LinkedHashMap<>();
for (SourceFile file : deps) {
if (!shouldSkipDepsFile(file)) {
List<DependencyInfo>
depInfos = depsParser.parseFileReader(
file.getName(), file.getCodeReader());
if (depInfos.isEmpty()) {
reportNoDepsInDepsFile(file.getName());
} else {
for (DependencyInfo info : depInfos) {
depsFiles.put(info.getPathRelativeToClosureBase(), removeRelativePathProvide(info));
}
}
}
}
// If a deps file also appears in srcs, our build tools will move it
// into srcs. So we need to scan all the src files for addDependency
// calls as well.
for (SourceFile src : srcs) {
if (!shouldSkipDepsFile(src)) {
List<DependencyInfo> srcInfos =
depsParser.parseFileReader(src.getName(), src.getCodeReader());
for (DependencyInfo info : srcInfos) {
depsFiles.put(info.getPathRelativeToClosureBase(), removeRelativePathProvide(info));
}
}
}
return depsFiles;
} | [
"private",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"parseDepsFiles",
"(",
")",
"throws",
"IOException",
"{",
"DepsFileParser",
"depsParser",
"=",
"createDepsFileParser",
"(",
")",
";",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"depsFiles",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"for",
"(",
"SourceFile",
"file",
":",
"deps",
")",
"{",
"if",
"(",
"!",
"shouldSkipDepsFile",
"(",
"file",
")",
")",
"{",
"List",
"<",
"DependencyInfo",
">",
"depInfos",
"=",
"depsParser",
".",
"parseFileReader",
"(",
"file",
".",
"getName",
"(",
")",
",",
"file",
".",
"getCodeReader",
"(",
")",
")",
";",
"if",
"(",
"depInfos",
".",
"isEmpty",
"(",
")",
")",
"{",
"reportNoDepsInDepsFile",
"(",
"file",
".",
"getName",
"(",
")",
")",
";",
"}",
"else",
"{",
"for",
"(",
"DependencyInfo",
"info",
":",
"depInfos",
")",
"{",
"depsFiles",
".",
"put",
"(",
"info",
".",
"getPathRelativeToClosureBase",
"(",
")",
",",
"removeRelativePathProvide",
"(",
"info",
")",
")",
";",
"}",
"}",
"}",
"}",
"// If a deps file also appears in srcs, our build tools will move it",
"// into srcs. So we need to scan all the src files for addDependency",
"// calls as well.",
"for",
"(",
"SourceFile",
"src",
":",
"srcs",
")",
"{",
"if",
"(",
"!",
"shouldSkipDepsFile",
"(",
"src",
")",
")",
"{",
"List",
"<",
"DependencyInfo",
">",
"srcInfos",
"=",
"depsParser",
".",
"parseFileReader",
"(",
"src",
".",
"getName",
"(",
")",
",",
"src",
".",
"getCodeReader",
"(",
")",
")",
";",
"for",
"(",
"DependencyInfo",
"info",
":",
"srcInfos",
")",
"{",
"depsFiles",
".",
"put",
"(",
"info",
".",
"getPathRelativeToClosureBase",
"(",
")",
",",
"removeRelativePathProvide",
"(",
"info",
")",
")",
";",
"}",
"}",
"}",
"return",
"depsFiles",
";",
"}"
] | Parses all deps.js files in the deps list and creates a map of
closure-relative path -> DependencyInfo. | [
"Parses",
"all",
"deps",
".",
"js",
"files",
"in",
"the",
"deps",
"list",
"and",
"creates",
"a",
"map",
"of",
"closure",
"-",
"relative",
"path",
"-",
">",
"DependencyInfo",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DepsGenerator.java#L423-L455 |
24,547 | google/closure-compiler | src/com/google/javascript/jscomp/deps/DepsGenerator.java | DepsGenerator.parseSources | private Map<String, DependencyInfo> parseSources(
Set<String> preparsedFiles) throws IOException {
Map<String, DependencyInfo> parsedFiles = new LinkedHashMap<>();
JsFileParser jsParser = new JsFileParser(errorManager).setModuleLoader(loader);
Compiler compiler = new Compiler();
compiler.init(ImmutableList.of(), ImmutableList.of(), new CompilerOptions());
for (SourceFile file : srcs) {
String closureRelativePath =
PathUtil.makeRelative(
closurePathAbs, PathUtil.makeAbsolute(file.getName()));
if (logger.isLoggable(Level.FINE)) {
logger.fine("Closure-relative path: " + closureRelativePath);
}
if (InclusionStrategy.WHEN_IN_SRCS == mergeStrategy ||
!preparsedFiles.contains(closureRelativePath)) {
DependencyInfo depInfo =
jsParser.parseFile(
file.getName(), closureRelativePath,
file.getCode());
depInfo = new LazyParsedDependencyInfo(depInfo, new JsAst(file), compiler);
// Kick the source out of memory.
file.clearCachedSource();
parsedFiles.put(closureRelativePath, depInfo);
}
}
return parsedFiles;
} | java | private Map<String, DependencyInfo> parseSources(
Set<String> preparsedFiles) throws IOException {
Map<String, DependencyInfo> parsedFiles = new LinkedHashMap<>();
JsFileParser jsParser = new JsFileParser(errorManager).setModuleLoader(loader);
Compiler compiler = new Compiler();
compiler.init(ImmutableList.of(), ImmutableList.of(), new CompilerOptions());
for (SourceFile file : srcs) {
String closureRelativePath =
PathUtil.makeRelative(
closurePathAbs, PathUtil.makeAbsolute(file.getName()));
if (logger.isLoggable(Level.FINE)) {
logger.fine("Closure-relative path: " + closureRelativePath);
}
if (InclusionStrategy.WHEN_IN_SRCS == mergeStrategy ||
!preparsedFiles.contains(closureRelativePath)) {
DependencyInfo depInfo =
jsParser.parseFile(
file.getName(), closureRelativePath,
file.getCode());
depInfo = new LazyParsedDependencyInfo(depInfo, new JsAst(file), compiler);
// Kick the source out of memory.
file.clearCachedSource();
parsedFiles.put(closureRelativePath, depInfo);
}
}
return parsedFiles;
} | [
"private",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"parseSources",
"(",
"Set",
"<",
"String",
">",
"preparsedFiles",
")",
"throws",
"IOException",
"{",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"parsedFiles",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"JsFileParser",
"jsParser",
"=",
"new",
"JsFileParser",
"(",
"errorManager",
")",
".",
"setModuleLoader",
"(",
"loader",
")",
";",
"Compiler",
"compiler",
"=",
"new",
"Compiler",
"(",
")",
";",
"compiler",
".",
"init",
"(",
"ImmutableList",
".",
"of",
"(",
")",
",",
"ImmutableList",
".",
"of",
"(",
")",
",",
"new",
"CompilerOptions",
"(",
")",
")",
";",
"for",
"(",
"SourceFile",
"file",
":",
"srcs",
")",
"{",
"String",
"closureRelativePath",
"=",
"PathUtil",
".",
"makeRelative",
"(",
"closurePathAbs",
",",
"PathUtil",
".",
"makeAbsolute",
"(",
"file",
".",
"getName",
"(",
")",
")",
")",
";",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"FINE",
")",
")",
"{",
"logger",
".",
"fine",
"(",
"\"Closure-relative path: \"",
"+",
"closureRelativePath",
")",
";",
"}",
"if",
"(",
"InclusionStrategy",
".",
"WHEN_IN_SRCS",
"==",
"mergeStrategy",
"||",
"!",
"preparsedFiles",
".",
"contains",
"(",
"closureRelativePath",
")",
")",
"{",
"DependencyInfo",
"depInfo",
"=",
"jsParser",
".",
"parseFile",
"(",
"file",
".",
"getName",
"(",
")",
",",
"closureRelativePath",
",",
"file",
".",
"getCode",
"(",
")",
")",
";",
"depInfo",
"=",
"new",
"LazyParsedDependencyInfo",
"(",
"depInfo",
",",
"new",
"JsAst",
"(",
"file",
")",
",",
"compiler",
")",
";",
"// Kick the source out of memory.",
"file",
".",
"clearCachedSource",
"(",
")",
";",
"parsedFiles",
".",
"put",
"(",
"closureRelativePath",
",",
"depInfo",
")",
";",
"}",
"}",
"return",
"parsedFiles",
";",
"}"
] | Parses all source files for dependency information.
@param preparsedFiles A set of closure-relative paths.
Files in this set are not parsed if they are encountered in srcs.
@return Returns a map of closure-relative paths -> DependencyInfo for the
newly parsed files.
@throws IOException Occurs upon an IO error. | [
"Parses",
"all",
"source",
"files",
"for",
"dependency",
"information",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DepsGenerator.java#L477-L506 |
24,548 | google/closure-compiler | src/com/google/javascript/jscomp/deps/DepsGenerator.java | DepsGenerator.writeDepsContent | private void writeDepsContent(Map<String, DependencyInfo> depsFiles,
Map<String, DependencyInfo> jsFiles, PrintStream out)
throws IOException {
// Print all dependencies extracted from srcs.
writeDepInfos(out, jsFiles.values());
// Print all dependencies extracted from deps.
if (mergeStrategy == InclusionStrategy.ALWAYS) {
// This multimap is just for splitting DepsInfo objects by
// it's definition deps.js file
Multimap<String, DependencyInfo> infosIndex =
Multimaps.index(depsFiles.values(), DependencyInfo::getName);
for (String depsPath : infosIndex.keySet()) {
String path = formatPathToDepsFile(depsPath);
out.println("\n// Included from: " + path);
writeDepInfos(out, infosIndex.get(depsPath));
}
}
} | java | private void writeDepsContent(Map<String, DependencyInfo> depsFiles,
Map<String, DependencyInfo> jsFiles, PrintStream out)
throws IOException {
// Print all dependencies extracted from srcs.
writeDepInfos(out, jsFiles.values());
// Print all dependencies extracted from deps.
if (mergeStrategy == InclusionStrategy.ALWAYS) {
// This multimap is just for splitting DepsInfo objects by
// it's definition deps.js file
Multimap<String, DependencyInfo> infosIndex =
Multimaps.index(depsFiles.values(), DependencyInfo::getName);
for (String depsPath : infosIndex.keySet()) {
String path = formatPathToDepsFile(depsPath);
out.println("\n// Included from: " + path);
writeDepInfos(out, infosIndex.get(depsPath));
}
}
} | [
"private",
"void",
"writeDepsContent",
"(",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"depsFiles",
",",
"Map",
"<",
"String",
",",
"DependencyInfo",
">",
"jsFiles",
",",
"PrintStream",
"out",
")",
"throws",
"IOException",
"{",
"// Print all dependencies extracted from srcs.",
"writeDepInfos",
"(",
"out",
",",
"jsFiles",
".",
"values",
"(",
")",
")",
";",
"// Print all dependencies extracted from deps.",
"if",
"(",
"mergeStrategy",
"==",
"InclusionStrategy",
".",
"ALWAYS",
")",
"{",
"// This multimap is just for splitting DepsInfo objects by",
"// it's definition deps.js file",
"Multimap",
"<",
"String",
",",
"DependencyInfo",
">",
"infosIndex",
"=",
"Multimaps",
".",
"index",
"(",
"depsFiles",
".",
"values",
"(",
")",
",",
"DependencyInfo",
"::",
"getName",
")",
";",
"for",
"(",
"String",
"depsPath",
":",
"infosIndex",
".",
"keySet",
"(",
")",
")",
"{",
"String",
"path",
"=",
"formatPathToDepsFile",
"(",
"depsPath",
")",
";",
"out",
".",
"println",
"(",
"\"\\n// Included from: \"",
"+",
"path",
")",
";",
"writeDepInfos",
"(",
"out",
",",
"infosIndex",
".",
"get",
"(",
"depsPath",
")",
")",
";",
"}",
"}",
"}"
] | Creates the content to put into the output deps.js file. If mergeDeps is
true, then all of the dependency information in the providedDeps will be
included in the output.
@throws IOException Occurs upon an IO error. | [
"Creates",
"the",
"content",
"to",
"put",
"into",
"the",
"output",
"deps",
".",
"js",
"file",
".",
"If",
"mergeDeps",
"is",
"true",
"then",
"all",
"of",
"the",
"dependency",
"information",
"in",
"the",
"providedDeps",
"will",
"be",
"included",
"in",
"the",
"output",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/deps/DepsGenerator.java#L514-L533 |
24,549 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.addReturnTypeIfMissing | private void addReturnTypeIfMissing(
PolymerClassDefinition cls, String getterPropName, JSTypeExpression jsType) {
Node classMembers = NodeUtil.getClassMembers(cls.definition);
Node getter = NodeUtil.getFirstGetterMatchingKey(classMembers, getterPropName);
if (getter != null) {
JSDocInfo info = NodeUtil.getBestJSDocInfo(getter);
if (info == null || !info.hasReturnType()) {
JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(info);
builder.recordReturnType(jsType);
getter.setJSDocInfo(builder.build());
}
}
} | java | private void addReturnTypeIfMissing(
PolymerClassDefinition cls, String getterPropName, JSTypeExpression jsType) {
Node classMembers = NodeUtil.getClassMembers(cls.definition);
Node getter = NodeUtil.getFirstGetterMatchingKey(classMembers, getterPropName);
if (getter != null) {
JSDocInfo info = NodeUtil.getBestJSDocInfo(getter);
if (info == null || !info.hasReturnType()) {
JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(info);
builder.recordReturnType(jsType);
getter.setJSDocInfo(builder.build());
}
}
} | [
"private",
"void",
"addReturnTypeIfMissing",
"(",
"PolymerClassDefinition",
"cls",
",",
"String",
"getterPropName",
",",
"JSTypeExpression",
"jsType",
")",
"{",
"Node",
"classMembers",
"=",
"NodeUtil",
".",
"getClassMembers",
"(",
"cls",
".",
"definition",
")",
";",
"Node",
"getter",
"=",
"NodeUtil",
".",
"getFirstGetterMatchingKey",
"(",
"classMembers",
",",
"getterPropName",
")",
";",
"if",
"(",
"getter",
"!=",
"null",
")",
"{",
"JSDocInfo",
"info",
"=",
"NodeUtil",
".",
"getBestJSDocInfo",
"(",
"getter",
")",
";",
"if",
"(",
"info",
"==",
"null",
"||",
"!",
"info",
".",
"hasReturnType",
"(",
")",
")",
"{",
"JSDocInfoBuilder",
"builder",
"=",
"JSDocInfoBuilder",
".",
"maybeCopyFrom",
"(",
"info",
")",
";",
"builder",
".",
"recordReturnType",
"(",
"jsType",
")",
";",
"getter",
".",
"setJSDocInfo",
"(",
"builder",
".",
"build",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Adds return type information to class getters | [
"Adds",
"return",
"type",
"information",
"to",
"class",
"getters"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L300-L312 |
24,550 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.addPropertiesConfigObjectReflection | private void addPropertiesConfigObjectReflection(
PolymerClassDefinition cls, Node propertiesLiteral) {
checkNotNull(propertiesLiteral);
checkState(propertiesLiteral.isObjectLit());
Node parent = propertiesLiteral.getParent();
Node objReflectCall =
IR.call(
NodeUtil.newQName(compiler, "$jscomp.reflectObject"),
cls.target.cloneTree(),
propertiesLiteral.detach())
.useSourceInfoIfMissingFromForTree(propertiesLiteral);
parent.addChildToFront(objReflectCall);
compiler.reportChangeToEnclosingScope(parent);
} | java | private void addPropertiesConfigObjectReflection(
PolymerClassDefinition cls, Node propertiesLiteral) {
checkNotNull(propertiesLiteral);
checkState(propertiesLiteral.isObjectLit());
Node parent = propertiesLiteral.getParent();
Node objReflectCall =
IR.call(
NodeUtil.newQName(compiler, "$jscomp.reflectObject"),
cls.target.cloneTree(),
propertiesLiteral.detach())
.useSourceInfoIfMissingFromForTree(propertiesLiteral);
parent.addChildToFront(objReflectCall);
compiler.reportChangeToEnclosingScope(parent);
} | [
"private",
"void",
"addPropertiesConfigObjectReflection",
"(",
"PolymerClassDefinition",
"cls",
",",
"Node",
"propertiesLiteral",
")",
"{",
"checkNotNull",
"(",
"propertiesLiteral",
")",
";",
"checkState",
"(",
"propertiesLiteral",
".",
"isObjectLit",
"(",
")",
")",
";",
"Node",
"parent",
"=",
"propertiesLiteral",
".",
"getParent",
"(",
")",
";",
"Node",
"objReflectCall",
"=",
"IR",
".",
"call",
"(",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"\"$jscomp.reflectObject\"",
")",
",",
"cls",
".",
"target",
".",
"cloneTree",
"(",
")",
",",
"propertiesLiteral",
".",
"detach",
"(",
")",
")",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"propertiesLiteral",
")",
";",
"parent",
".",
"addChildToFront",
"(",
"objReflectCall",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"parent",
")",
";",
"}"
] | Wrap the properties config object in an objectReflect call | [
"Wrap",
"the",
"properties",
"config",
"object",
"in",
"an",
"objectReflect",
"call"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L315-L330 |
24,551 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.appendPropertiesToBlock | private void appendPropertiesToBlock(List<MemberDefinition> props, Node block, String basePath) {
for (MemberDefinition prop : props) {
Node propertyNode =
IR.exprResult(NodeUtil.newQName(compiler, basePath + prop.name.getString()));
// If a property string is quoted, make sure the added prototype properties are also quoted
if (prop.name.isQuotedString()) {
continue;
}
propertyNode.useSourceInfoIfMissingFromForTree(prop.name);
JSDocInfoBuilder info = JSDocInfoBuilder.maybeCopyFrom(prop.info);
JSTypeExpression propType = PolymerPassStaticUtils.getTypeFromProperty(prop, compiler);
if (propType == null) {
return;
}
info.recordType(propType);
propertyNode.getFirstChild().setJSDocInfo(info.build());
block.addChildToBack(propertyNode);
}
} | java | private void appendPropertiesToBlock(List<MemberDefinition> props, Node block, String basePath) {
for (MemberDefinition prop : props) {
Node propertyNode =
IR.exprResult(NodeUtil.newQName(compiler, basePath + prop.name.getString()));
// If a property string is quoted, make sure the added prototype properties are also quoted
if (prop.name.isQuotedString()) {
continue;
}
propertyNode.useSourceInfoIfMissingFromForTree(prop.name);
JSDocInfoBuilder info = JSDocInfoBuilder.maybeCopyFrom(prop.info);
JSTypeExpression propType = PolymerPassStaticUtils.getTypeFromProperty(prop, compiler);
if (propType == null) {
return;
}
info.recordType(propType);
propertyNode.getFirstChild().setJSDocInfo(info.build());
block.addChildToBack(propertyNode);
}
} | [
"private",
"void",
"appendPropertiesToBlock",
"(",
"List",
"<",
"MemberDefinition",
">",
"props",
",",
"Node",
"block",
",",
"String",
"basePath",
")",
"{",
"for",
"(",
"MemberDefinition",
"prop",
":",
"props",
")",
"{",
"Node",
"propertyNode",
"=",
"IR",
".",
"exprResult",
"(",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"basePath",
"+",
"prop",
".",
"name",
".",
"getString",
"(",
")",
")",
")",
";",
"// If a property string is quoted, make sure the added prototype properties are also quoted",
"if",
"(",
"prop",
".",
"name",
".",
"isQuotedString",
"(",
")",
")",
"{",
"continue",
";",
"}",
"propertyNode",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"prop",
".",
"name",
")",
";",
"JSDocInfoBuilder",
"info",
"=",
"JSDocInfoBuilder",
".",
"maybeCopyFrom",
"(",
"prop",
".",
"info",
")",
";",
"JSTypeExpression",
"propType",
"=",
"PolymerPassStaticUtils",
".",
"getTypeFromProperty",
"(",
"prop",
",",
"compiler",
")",
";",
"if",
"(",
"propType",
"==",
"null",
")",
"{",
"return",
";",
"}",
"info",
".",
"recordType",
"(",
"propType",
")",
";",
"propertyNode",
".",
"getFirstChild",
"(",
")",
".",
"setJSDocInfo",
"(",
"info",
".",
"build",
"(",
")",
")",
";",
"block",
".",
"addChildToBack",
"(",
"propertyNode",
")",
";",
"}",
"}"
] | Appends all of the given properties to the given block. | [
"Appends",
"all",
"of",
"the",
"given",
"properties",
"to",
"the",
"given",
"block",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L439-L461 |
24,552 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.removePropertyDocs | private void removePropertyDocs(
final Node objLit, PolymerClassDefinition.DefinitionType defType) {
for (MemberDefinition prop :
PolymerPassStaticUtils.extractProperties(
objLit,
defType,
compiler,
/** constructor= */
null)) {
prop.name.removeProp(Node.JSDOC_INFO_PROP);
}
} | java | private void removePropertyDocs(
final Node objLit, PolymerClassDefinition.DefinitionType defType) {
for (MemberDefinition prop :
PolymerPassStaticUtils.extractProperties(
objLit,
defType,
compiler,
/** constructor= */
null)) {
prop.name.removeProp(Node.JSDOC_INFO_PROP);
}
} | [
"private",
"void",
"removePropertyDocs",
"(",
"final",
"Node",
"objLit",
",",
"PolymerClassDefinition",
".",
"DefinitionType",
"defType",
")",
"{",
"for",
"(",
"MemberDefinition",
"prop",
":",
"PolymerPassStaticUtils",
".",
"extractProperties",
"(",
"objLit",
",",
"defType",
",",
"compiler",
",",
"/** constructor= */",
"null",
")",
")",
"{",
"prop",
".",
"name",
".",
"removeProp",
"(",
"Node",
".",
"JSDOC_INFO_PROP",
")",
";",
"}",
"}"
] | Remove all JSDocs from properties of a class definition | [
"Remove",
"all",
"JSDocs",
"from",
"properties",
"of",
"a",
"class",
"definition"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L464-L475 |
24,553 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.appendBehaviorMembersToBlock | private void appendBehaviorMembersToBlock(final PolymerClassDefinition cls, Node block) {
String qualifiedPath = cls.target.getQualifiedName() + ".prototype.";
Map<String, Node> nameToExprResult = new HashMap<>();
for (BehaviorDefinition behavior : cls.behaviors) {
for (MemberDefinition behaviorFunction : behavior.functionsToCopy) {
String fnName = behaviorFunction.name.getString();
// Don't copy functions already defined by the element itself.
if (NodeUtil.getFirstPropMatchingKey(cls.descriptor, fnName) != null) {
continue;
}
// Avoid copying over the same function twice. The last definition always wins.
if (nameToExprResult.containsKey(fnName)) {
block.removeChild(nameToExprResult.get(fnName));
}
Node fnValue = behaviorFunction.value.cloneTree();
NodeUtil.markNewScopesChanged(fnValue, compiler);
Node exprResult =
IR.exprResult(IR.assign(NodeUtil.newQName(compiler, qualifiedPath + fnName), fnValue));
exprResult.useSourceInfoIfMissingFromForTree(behaviorFunction.name);
JSDocInfoBuilder info = JSDocInfoBuilder.maybeCopyFrom(behaviorFunction.info);
// Uses of private members that come from behaviors are not recognized correctly,
// so just suppress that warning.
info.addSuppression("unusedPrivateMembers");
// If the function in the behavior is @protected, switch it to @public so that
// we don't get a visibility warning. This is a bit of a hack but easier than
// making the type system understand that methods are "inherited" from behaviors.
if (behaviorFunction.info != null
&& behaviorFunction.info.getVisibility() == Visibility.PROTECTED) {
info.overwriteVisibility(Visibility.PUBLIC);
}
// Behaviors whose declarations are not in the global scope may contain references to
// symbols which do not exist in the element's scope. Only copy a function stub.
if (!behavior.isGlobalDeclaration) {
NodeUtil.getFunctionBody(fnValue).removeChildren();
}
exprResult.getFirstChild().setJSDocInfo(info.build());
block.addChildToBack(exprResult);
nameToExprResult.put(fnName, exprResult);
}
// Copy other members.
for (MemberDefinition behaviorProp : behavior.nonPropertyMembersToCopy) {
String propName = behaviorProp.name.getString();
if (nameToExprResult.containsKey(propName)) {
block.removeChild(nameToExprResult.get(propName));
}
Node exprResult = IR.exprResult(NodeUtil.newQName(compiler, qualifiedPath + propName));
exprResult.useSourceInfoFromForTree(behaviorProp.name);
JSDocInfoBuilder info = JSDocInfoBuilder.maybeCopyFrom(behaviorProp.info);
if (behaviorProp.name.isGetterDef()) {
info = new JSDocInfoBuilder(true);
if (behaviorProp.info != null && behaviorProp.info.getReturnType() != null) {
info.recordType(behaviorProp.info.getReturnType());
}
}
exprResult.getFirstChild().setJSDocInfo(info.build());
block.addChildToBack(exprResult);
nameToExprResult.put(propName, exprResult);
}
}
} | java | private void appendBehaviorMembersToBlock(final PolymerClassDefinition cls, Node block) {
String qualifiedPath = cls.target.getQualifiedName() + ".prototype.";
Map<String, Node> nameToExprResult = new HashMap<>();
for (BehaviorDefinition behavior : cls.behaviors) {
for (MemberDefinition behaviorFunction : behavior.functionsToCopy) {
String fnName = behaviorFunction.name.getString();
// Don't copy functions already defined by the element itself.
if (NodeUtil.getFirstPropMatchingKey(cls.descriptor, fnName) != null) {
continue;
}
// Avoid copying over the same function twice. The last definition always wins.
if (nameToExprResult.containsKey(fnName)) {
block.removeChild(nameToExprResult.get(fnName));
}
Node fnValue = behaviorFunction.value.cloneTree();
NodeUtil.markNewScopesChanged(fnValue, compiler);
Node exprResult =
IR.exprResult(IR.assign(NodeUtil.newQName(compiler, qualifiedPath + fnName), fnValue));
exprResult.useSourceInfoIfMissingFromForTree(behaviorFunction.name);
JSDocInfoBuilder info = JSDocInfoBuilder.maybeCopyFrom(behaviorFunction.info);
// Uses of private members that come from behaviors are not recognized correctly,
// so just suppress that warning.
info.addSuppression("unusedPrivateMembers");
// If the function in the behavior is @protected, switch it to @public so that
// we don't get a visibility warning. This is a bit of a hack but easier than
// making the type system understand that methods are "inherited" from behaviors.
if (behaviorFunction.info != null
&& behaviorFunction.info.getVisibility() == Visibility.PROTECTED) {
info.overwriteVisibility(Visibility.PUBLIC);
}
// Behaviors whose declarations are not in the global scope may contain references to
// symbols which do not exist in the element's scope. Only copy a function stub.
if (!behavior.isGlobalDeclaration) {
NodeUtil.getFunctionBody(fnValue).removeChildren();
}
exprResult.getFirstChild().setJSDocInfo(info.build());
block.addChildToBack(exprResult);
nameToExprResult.put(fnName, exprResult);
}
// Copy other members.
for (MemberDefinition behaviorProp : behavior.nonPropertyMembersToCopy) {
String propName = behaviorProp.name.getString();
if (nameToExprResult.containsKey(propName)) {
block.removeChild(nameToExprResult.get(propName));
}
Node exprResult = IR.exprResult(NodeUtil.newQName(compiler, qualifiedPath + propName));
exprResult.useSourceInfoFromForTree(behaviorProp.name);
JSDocInfoBuilder info = JSDocInfoBuilder.maybeCopyFrom(behaviorProp.info);
if (behaviorProp.name.isGetterDef()) {
info = new JSDocInfoBuilder(true);
if (behaviorProp.info != null && behaviorProp.info.getReturnType() != null) {
info.recordType(behaviorProp.info.getReturnType());
}
}
exprResult.getFirstChild().setJSDocInfo(info.build());
block.addChildToBack(exprResult);
nameToExprResult.put(propName, exprResult);
}
}
} | [
"private",
"void",
"appendBehaviorMembersToBlock",
"(",
"final",
"PolymerClassDefinition",
"cls",
",",
"Node",
"block",
")",
"{",
"String",
"qualifiedPath",
"=",
"cls",
".",
"target",
".",
"getQualifiedName",
"(",
")",
"+",
"\".prototype.\"",
";",
"Map",
"<",
"String",
",",
"Node",
">",
"nameToExprResult",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"for",
"(",
"BehaviorDefinition",
"behavior",
":",
"cls",
".",
"behaviors",
")",
"{",
"for",
"(",
"MemberDefinition",
"behaviorFunction",
":",
"behavior",
".",
"functionsToCopy",
")",
"{",
"String",
"fnName",
"=",
"behaviorFunction",
".",
"name",
".",
"getString",
"(",
")",
";",
"// Don't copy functions already defined by the element itself.",
"if",
"(",
"NodeUtil",
".",
"getFirstPropMatchingKey",
"(",
"cls",
".",
"descriptor",
",",
"fnName",
")",
"!=",
"null",
")",
"{",
"continue",
";",
"}",
"// Avoid copying over the same function twice. The last definition always wins.",
"if",
"(",
"nameToExprResult",
".",
"containsKey",
"(",
"fnName",
")",
")",
"{",
"block",
".",
"removeChild",
"(",
"nameToExprResult",
".",
"get",
"(",
"fnName",
")",
")",
";",
"}",
"Node",
"fnValue",
"=",
"behaviorFunction",
".",
"value",
".",
"cloneTree",
"(",
")",
";",
"NodeUtil",
".",
"markNewScopesChanged",
"(",
"fnValue",
",",
"compiler",
")",
";",
"Node",
"exprResult",
"=",
"IR",
".",
"exprResult",
"(",
"IR",
".",
"assign",
"(",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"qualifiedPath",
"+",
"fnName",
")",
",",
"fnValue",
")",
")",
";",
"exprResult",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"behaviorFunction",
".",
"name",
")",
";",
"JSDocInfoBuilder",
"info",
"=",
"JSDocInfoBuilder",
".",
"maybeCopyFrom",
"(",
"behaviorFunction",
".",
"info",
")",
";",
"// Uses of private members that come from behaviors are not recognized correctly,",
"// so just suppress that warning.",
"info",
".",
"addSuppression",
"(",
"\"unusedPrivateMembers\"",
")",
";",
"// If the function in the behavior is @protected, switch it to @public so that",
"// we don't get a visibility warning. This is a bit of a hack but easier than",
"// making the type system understand that methods are \"inherited\" from behaviors.",
"if",
"(",
"behaviorFunction",
".",
"info",
"!=",
"null",
"&&",
"behaviorFunction",
".",
"info",
".",
"getVisibility",
"(",
")",
"==",
"Visibility",
".",
"PROTECTED",
")",
"{",
"info",
".",
"overwriteVisibility",
"(",
"Visibility",
".",
"PUBLIC",
")",
";",
"}",
"// Behaviors whose declarations are not in the global scope may contain references to",
"// symbols which do not exist in the element's scope. Only copy a function stub.",
"if",
"(",
"!",
"behavior",
".",
"isGlobalDeclaration",
")",
"{",
"NodeUtil",
".",
"getFunctionBody",
"(",
"fnValue",
")",
".",
"removeChildren",
"(",
")",
";",
"}",
"exprResult",
".",
"getFirstChild",
"(",
")",
".",
"setJSDocInfo",
"(",
"info",
".",
"build",
"(",
")",
")",
";",
"block",
".",
"addChildToBack",
"(",
"exprResult",
")",
";",
"nameToExprResult",
".",
"put",
"(",
"fnName",
",",
"exprResult",
")",
";",
"}",
"// Copy other members.",
"for",
"(",
"MemberDefinition",
"behaviorProp",
":",
"behavior",
".",
"nonPropertyMembersToCopy",
")",
"{",
"String",
"propName",
"=",
"behaviorProp",
".",
"name",
".",
"getString",
"(",
")",
";",
"if",
"(",
"nameToExprResult",
".",
"containsKey",
"(",
"propName",
")",
")",
"{",
"block",
".",
"removeChild",
"(",
"nameToExprResult",
".",
"get",
"(",
"propName",
")",
")",
";",
"}",
"Node",
"exprResult",
"=",
"IR",
".",
"exprResult",
"(",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"qualifiedPath",
"+",
"propName",
")",
")",
";",
"exprResult",
".",
"useSourceInfoFromForTree",
"(",
"behaviorProp",
".",
"name",
")",
";",
"JSDocInfoBuilder",
"info",
"=",
"JSDocInfoBuilder",
".",
"maybeCopyFrom",
"(",
"behaviorProp",
".",
"info",
")",
";",
"if",
"(",
"behaviorProp",
".",
"name",
".",
"isGetterDef",
"(",
")",
")",
"{",
"info",
"=",
"new",
"JSDocInfoBuilder",
"(",
"true",
")",
";",
"if",
"(",
"behaviorProp",
".",
"info",
"!=",
"null",
"&&",
"behaviorProp",
".",
"info",
".",
"getReturnType",
"(",
")",
"!=",
"null",
")",
"{",
"info",
".",
"recordType",
"(",
"behaviorProp",
".",
"info",
".",
"getReturnType",
"(",
")",
")",
";",
"}",
"}",
"exprResult",
".",
"getFirstChild",
"(",
")",
".",
"setJSDocInfo",
"(",
"info",
".",
"build",
"(",
")",
")",
";",
"block",
".",
"addChildToBack",
"(",
"exprResult",
")",
";",
"nameToExprResult",
".",
"put",
"(",
"propName",
",",
"exprResult",
")",
";",
"}",
"}",
"}"
] | Appends all required behavior functions and non-property members to the given block. | [
"Appends",
"all",
"required",
"behavior",
"functions",
"and",
"non",
"-",
"property",
"members",
"to",
"the",
"given",
"block",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L478-L546 |
24,554 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.makeReadOnlySetter | private Node makeReadOnlySetter(String propName, String qualifiedPath) {
String setterName = "_set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
Node fnNode = IR.function(IR.name(""), IR.paramList(IR.name(propName)), IR.block());
compiler.reportChangeToChangeScope(fnNode);
Node exprResNode =
IR.exprResult(IR.assign(NodeUtil.newQName(compiler, qualifiedPath + setterName), fnNode));
JSDocInfoBuilder info = new JSDocInfoBuilder(true);
// This is overriding a generated function which was added to the interface in
// {@code createExportsAndExterns}.
info.recordOverride();
exprResNode.getFirstChild().setJSDocInfo(info.build());
return exprResNode;
} | java | private Node makeReadOnlySetter(String propName, String qualifiedPath) {
String setterName = "_set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
Node fnNode = IR.function(IR.name(""), IR.paramList(IR.name(propName)), IR.block());
compiler.reportChangeToChangeScope(fnNode);
Node exprResNode =
IR.exprResult(IR.assign(NodeUtil.newQName(compiler, qualifiedPath + setterName), fnNode));
JSDocInfoBuilder info = new JSDocInfoBuilder(true);
// This is overriding a generated function which was added to the interface in
// {@code createExportsAndExterns}.
info.recordOverride();
exprResNode.getFirstChild().setJSDocInfo(info.build());
return exprResNode;
} | [
"private",
"Node",
"makeReadOnlySetter",
"(",
"String",
"propName",
",",
"String",
"qualifiedPath",
")",
"{",
"String",
"setterName",
"=",
"\"_set\"",
"+",
"propName",
".",
"substring",
"(",
"0",
",",
"1",
")",
".",
"toUpperCase",
"(",
")",
"+",
"propName",
".",
"substring",
"(",
"1",
")",
";",
"Node",
"fnNode",
"=",
"IR",
".",
"function",
"(",
"IR",
".",
"name",
"(",
"\"\"",
")",
",",
"IR",
".",
"paramList",
"(",
"IR",
".",
"name",
"(",
"propName",
")",
")",
",",
"IR",
".",
"block",
"(",
")",
")",
";",
"compiler",
".",
"reportChangeToChangeScope",
"(",
"fnNode",
")",
";",
"Node",
"exprResNode",
"=",
"IR",
".",
"exprResult",
"(",
"IR",
".",
"assign",
"(",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"qualifiedPath",
"+",
"setterName",
")",
",",
"fnNode",
")",
")",
";",
"JSDocInfoBuilder",
"info",
"=",
"new",
"JSDocInfoBuilder",
"(",
"true",
")",
";",
"// This is overriding a generated function which was added to the interface in",
"// {@code createExportsAndExterns}.",
"info",
".",
"recordOverride",
"(",
")",
";",
"exprResNode",
".",
"getFirstChild",
"(",
")",
".",
"setJSDocInfo",
"(",
"info",
".",
"build",
"(",
")",
")",
";",
"return",
"exprResNode",
";",
"}"
] | Adds the generated setter for a readonly property.
@see https://www.polymer-project.org/0.8/docs/devguide/properties.html#read-only | [
"Adds",
"the",
"generated",
"setter",
"for",
"a",
"readonly",
"property",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L553-L567 |
24,555 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.createExportsAndExterns | private void createExportsAndExterns(
final PolymerClassDefinition cls,
List<MemberDefinition> readOnlyProps,
List<MemberDefinition> attributeReflectedProps) {
Node block = IR.block();
String interfaceName = getInterfaceName(cls);
Node fnNode = NodeUtil.emptyFunction();
compiler.reportChangeToChangeScope(fnNode);
Node varNode = IR.var(NodeUtil.newQName(compiler, interfaceName), fnNode);
JSDocInfoBuilder info = new JSDocInfoBuilder(true);
info.recordInterface();
varNode.setJSDocInfo(info.build());
block.addChildToBack(varNode);
String interfaceBasePath = interfaceName + ".prototype.";
if (polymerExportPolicy == PolymerExportPolicy.EXPORT_ALL) {
// Properties from behaviors were added to our element definition earlier.
appendPropertiesToBlock(cls.props, block, interfaceBasePath);
// Methods from behaviors were not already added to our element definition, so we need to
// export those in addition to methods defined directly on the element. Note it's possible
// and valid for two behaviors, or a behavior and an element, to implement the same method,
// so we de-dupe by name. We're not checking that the signatures are compatible in the way
// that normal class inheritance would, but that's not easy to do since these aren't classes.
// Class mixins replace Polymer behaviors and are supported directly by Closure, so new code
// should use those instead.
LinkedHashMap<String, MemberDefinition> uniqueMethods = new LinkedHashMap<>();
if (cls.behaviors != null) {
for (BehaviorDefinition behavior : cls.behaviors) {
for (MemberDefinition method : behavior.functionsToCopy) {
uniqueMethods.put(method.name.getString(), method);
}
}
}
for (MemberDefinition method : cls.methods) {
uniqueMethods.put(method.name.getString(), method);
}
for (MemberDefinition method : uniqueMethods.values()) {
addMethodToObjectExternsUsingExportAnnotation(cls, method);
}
} else if (polymerVersion == 1) {
// For Polymer 1, all declared properties are non-renameable
appendPropertiesToBlock(cls.props, block, interfaceBasePath);
} else {
// For Polymer 2, only read-only properties and reflectToAttribute properties are
// non-renameable. Other properties follow the ALL_UNQUOTED renaming rules.
List<MemberDefinition> interfaceProperties = new ArrayList<>();
interfaceProperties.addAll(readOnlyProps);
if (attributeReflectedProps != null) {
interfaceProperties.addAll(attributeReflectedProps);
}
appendPropertiesToBlock(interfaceProperties, block, interfaceBasePath);
}
for (MemberDefinition prop : readOnlyProps) {
// Add all _set* functions to avoid renaming.
String propName = prop.name.getString();
String setterName = "_set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
Node setterExprNode =
IR.exprResult(NodeUtil.newQName(compiler, interfaceBasePath + setterName));
JSDocInfoBuilder setterInfo = new JSDocInfoBuilder(true);
JSTypeExpression propType = PolymerPassStaticUtils.getTypeFromProperty(prop, compiler);
setterInfo.recordParameter(propName, propType);
setterExprNode.getFirstChild().setJSDocInfo(setterInfo.build());
block.addChildToBack(setterExprNode);
}
block.useSourceInfoIfMissingFromForTree(polymerElementExterns);
Node scopeRoot = polymerElementExterns;
if (!scopeRoot.isScript()) {
scopeRoot = scopeRoot.getParent();
}
Node stmts = block.removeChildren();
scopeRoot.addChildrenToBack(stmts);
compiler.reportChangeToEnclosingScope(stmts);
} | java | private void createExportsAndExterns(
final PolymerClassDefinition cls,
List<MemberDefinition> readOnlyProps,
List<MemberDefinition> attributeReflectedProps) {
Node block = IR.block();
String interfaceName = getInterfaceName(cls);
Node fnNode = NodeUtil.emptyFunction();
compiler.reportChangeToChangeScope(fnNode);
Node varNode = IR.var(NodeUtil.newQName(compiler, interfaceName), fnNode);
JSDocInfoBuilder info = new JSDocInfoBuilder(true);
info.recordInterface();
varNode.setJSDocInfo(info.build());
block.addChildToBack(varNode);
String interfaceBasePath = interfaceName + ".prototype.";
if (polymerExportPolicy == PolymerExportPolicy.EXPORT_ALL) {
// Properties from behaviors were added to our element definition earlier.
appendPropertiesToBlock(cls.props, block, interfaceBasePath);
// Methods from behaviors were not already added to our element definition, so we need to
// export those in addition to methods defined directly on the element. Note it's possible
// and valid for two behaviors, or a behavior and an element, to implement the same method,
// so we de-dupe by name. We're not checking that the signatures are compatible in the way
// that normal class inheritance would, but that's not easy to do since these aren't classes.
// Class mixins replace Polymer behaviors and are supported directly by Closure, so new code
// should use those instead.
LinkedHashMap<String, MemberDefinition> uniqueMethods = new LinkedHashMap<>();
if (cls.behaviors != null) {
for (BehaviorDefinition behavior : cls.behaviors) {
for (MemberDefinition method : behavior.functionsToCopy) {
uniqueMethods.put(method.name.getString(), method);
}
}
}
for (MemberDefinition method : cls.methods) {
uniqueMethods.put(method.name.getString(), method);
}
for (MemberDefinition method : uniqueMethods.values()) {
addMethodToObjectExternsUsingExportAnnotation(cls, method);
}
} else if (polymerVersion == 1) {
// For Polymer 1, all declared properties are non-renameable
appendPropertiesToBlock(cls.props, block, interfaceBasePath);
} else {
// For Polymer 2, only read-only properties and reflectToAttribute properties are
// non-renameable. Other properties follow the ALL_UNQUOTED renaming rules.
List<MemberDefinition> interfaceProperties = new ArrayList<>();
interfaceProperties.addAll(readOnlyProps);
if (attributeReflectedProps != null) {
interfaceProperties.addAll(attributeReflectedProps);
}
appendPropertiesToBlock(interfaceProperties, block, interfaceBasePath);
}
for (MemberDefinition prop : readOnlyProps) {
// Add all _set* functions to avoid renaming.
String propName = prop.name.getString();
String setterName = "_set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
Node setterExprNode =
IR.exprResult(NodeUtil.newQName(compiler, interfaceBasePath + setterName));
JSDocInfoBuilder setterInfo = new JSDocInfoBuilder(true);
JSTypeExpression propType = PolymerPassStaticUtils.getTypeFromProperty(prop, compiler);
setterInfo.recordParameter(propName, propType);
setterExprNode.getFirstChild().setJSDocInfo(setterInfo.build());
block.addChildToBack(setterExprNode);
}
block.useSourceInfoIfMissingFromForTree(polymerElementExterns);
Node scopeRoot = polymerElementExterns;
if (!scopeRoot.isScript()) {
scopeRoot = scopeRoot.getParent();
}
Node stmts = block.removeChildren();
scopeRoot.addChildrenToBack(stmts);
compiler.reportChangeToEnclosingScope(stmts);
} | [
"private",
"void",
"createExportsAndExterns",
"(",
"final",
"PolymerClassDefinition",
"cls",
",",
"List",
"<",
"MemberDefinition",
">",
"readOnlyProps",
",",
"List",
"<",
"MemberDefinition",
">",
"attributeReflectedProps",
")",
"{",
"Node",
"block",
"=",
"IR",
".",
"block",
"(",
")",
";",
"String",
"interfaceName",
"=",
"getInterfaceName",
"(",
"cls",
")",
";",
"Node",
"fnNode",
"=",
"NodeUtil",
".",
"emptyFunction",
"(",
")",
";",
"compiler",
".",
"reportChangeToChangeScope",
"(",
"fnNode",
")",
";",
"Node",
"varNode",
"=",
"IR",
".",
"var",
"(",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"interfaceName",
")",
",",
"fnNode",
")",
";",
"JSDocInfoBuilder",
"info",
"=",
"new",
"JSDocInfoBuilder",
"(",
"true",
")",
";",
"info",
".",
"recordInterface",
"(",
")",
";",
"varNode",
".",
"setJSDocInfo",
"(",
"info",
".",
"build",
"(",
")",
")",
";",
"block",
".",
"addChildToBack",
"(",
"varNode",
")",
";",
"String",
"interfaceBasePath",
"=",
"interfaceName",
"+",
"\".prototype.\"",
";",
"if",
"(",
"polymerExportPolicy",
"==",
"PolymerExportPolicy",
".",
"EXPORT_ALL",
")",
"{",
"// Properties from behaviors were added to our element definition earlier.",
"appendPropertiesToBlock",
"(",
"cls",
".",
"props",
",",
"block",
",",
"interfaceBasePath",
")",
";",
"// Methods from behaviors were not already added to our element definition, so we need to",
"// export those in addition to methods defined directly on the element. Note it's possible",
"// and valid for two behaviors, or a behavior and an element, to implement the same method,",
"// so we de-dupe by name. We're not checking that the signatures are compatible in the way",
"// that normal class inheritance would, but that's not easy to do since these aren't classes.",
"// Class mixins replace Polymer behaviors and are supported directly by Closure, so new code",
"// should use those instead.",
"LinkedHashMap",
"<",
"String",
",",
"MemberDefinition",
">",
"uniqueMethods",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"if",
"(",
"cls",
".",
"behaviors",
"!=",
"null",
")",
"{",
"for",
"(",
"BehaviorDefinition",
"behavior",
":",
"cls",
".",
"behaviors",
")",
"{",
"for",
"(",
"MemberDefinition",
"method",
":",
"behavior",
".",
"functionsToCopy",
")",
"{",
"uniqueMethods",
".",
"put",
"(",
"method",
".",
"name",
".",
"getString",
"(",
")",
",",
"method",
")",
";",
"}",
"}",
"}",
"for",
"(",
"MemberDefinition",
"method",
":",
"cls",
".",
"methods",
")",
"{",
"uniqueMethods",
".",
"put",
"(",
"method",
".",
"name",
".",
"getString",
"(",
")",
",",
"method",
")",
";",
"}",
"for",
"(",
"MemberDefinition",
"method",
":",
"uniqueMethods",
".",
"values",
"(",
")",
")",
"{",
"addMethodToObjectExternsUsingExportAnnotation",
"(",
"cls",
",",
"method",
")",
";",
"}",
"}",
"else",
"if",
"(",
"polymerVersion",
"==",
"1",
")",
"{",
"// For Polymer 1, all declared properties are non-renameable",
"appendPropertiesToBlock",
"(",
"cls",
".",
"props",
",",
"block",
",",
"interfaceBasePath",
")",
";",
"}",
"else",
"{",
"// For Polymer 2, only read-only properties and reflectToAttribute properties are",
"// non-renameable. Other properties follow the ALL_UNQUOTED renaming rules.",
"List",
"<",
"MemberDefinition",
">",
"interfaceProperties",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"interfaceProperties",
".",
"addAll",
"(",
"readOnlyProps",
")",
";",
"if",
"(",
"attributeReflectedProps",
"!=",
"null",
")",
"{",
"interfaceProperties",
".",
"addAll",
"(",
"attributeReflectedProps",
")",
";",
"}",
"appendPropertiesToBlock",
"(",
"interfaceProperties",
",",
"block",
",",
"interfaceBasePath",
")",
";",
"}",
"for",
"(",
"MemberDefinition",
"prop",
":",
"readOnlyProps",
")",
"{",
"// Add all _set* functions to avoid renaming.",
"String",
"propName",
"=",
"prop",
".",
"name",
".",
"getString",
"(",
")",
";",
"String",
"setterName",
"=",
"\"_set\"",
"+",
"propName",
".",
"substring",
"(",
"0",
",",
"1",
")",
".",
"toUpperCase",
"(",
")",
"+",
"propName",
".",
"substring",
"(",
"1",
")",
";",
"Node",
"setterExprNode",
"=",
"IR",
".",
"exprResult",
"(",
"NodeUtil",
".",
"newQName",
"(",
"compiler",
",",
"interfaceBasePath",
"+",
"setterName",
")",
")",
";",
"JSDocInfoBuilder",
"setterInfo",
"=",
"new",
"JSDocInfoBuilder",
"(",
"true",
")",
";",
"JSTypeExpression",
"propType",
"=",
"PolymerPassStaticUtils",
".",
"getTypeFromProperty",
"(",
"prop",
",",
"compiler",
")",
";",
"setterInfo",
".",
"recordParameter",
"(",
"propName",
",",
"propType",
")",
";",
"setterExprNode",
".",
"getFirstChild",
"(",
")",
".",
"setJSDocInfo",
"(",
"setterInfo",
".",
"build",
"(",
")",
")",
";",
"block",
".",
"addChildToBack",
"(",
"setterExprNode",
")",
";",
"}",
"block",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"polymerElementExterns",
")",
";",
"Node",
"scopeRoot",
"=",
"polymerElementExterns",
";",
"if",
"(",
"!",
"scopeRoot",
".",
"isScript",
"(",
")",
")",
"{",
"scopeRoot",
"=",
"scopeRoot",
".",
"getParent",
"(",
")",
";",
"}",
"Node",
"stmts",
"=",
"block",
".",
"removeChildren",
"(",
")",
";",
"scopeRoot",
".",
"addChildrenToBack",
"(",
"stmts",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"stmts",
")",
";",
"}"
] | Create exports and externs to protect element properties and methods from renaming and dead
code removal.
<p>Since Polymer templates, observers, and computed properties rely on string references to
element properties and methods, and because we don't yet have a way to update those references
reliably, we instead export or extern them.
<p>For properties, we create a new interface called {@code Polymer<ElementName>Interface}, add
all element properties to it, mark that the element class {@code @implements} this interface,
and add the interface to the Closure externs. The specific set of properties we add to this
interface is determined by the value of {@code polymerExportPolicy}.
<p>For methods, when {@code polymerExportPolicy = EXPORT_ALL}, we instead append to {@code
Object.prototype} in the externs using {@code @export} annotations. This approach is a
compromise, with the following alternatives considered:
<p>Alternative 1: Add methods to our generated {@code Polymer<ElementName>Interface} in the
externs. Pro: More optimal than {@code Object.prototype} when type-aware optimizations are
enabled. Con 1: When a class {@code @implements} an interface, and when {@code
report_missing_override} is enabled, any method on the class that is also in the interface must
have an {@code @override} annotation, which means we generate a spurious warning for all
methods. Con 2: An unresolved bug was encountered (b/115942961) relating to a mismatch between
the signatures of the class and the generated interface.
<p>Alternative 2: Generate goog.exportProperty calls, which causes aliases on the prototype
from original to optimized names to be set. Pro: Compiled code can still use the optimized
name. Con: In practice, for Polymer applications, we see a net increase in bundle size due to
the high number of new {@code Foo.prototype.originalName = Foo.prototype.z} expressions.
<p>Alternative 3: Append directly to the {@code Object.prototype} externs, instead of using
{@code @export} annotations for the {@link GenerateExports} pass. Pro: Doesn't depend on the
{@code generate_exports} and {@code export_local_property_definitions} flags. Con: The
PolymerPass runs in the type checking phase, so modifying {@code Object.prototype} here causes
unwanted type checking effects, such as allowing the method to be called on any object, and
generating incorrect warnings when {@code report_missing_override} is enabled. | [
"Create",
"exports",
"and",
"externs",
"to",
"protect",
"element",
"properties",
"and",
"methods",
"from",
"renaming",
"and",
"dead",
"code",
"removal",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L606-L688 |
24,556 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.varToAssign | private static Node varToAssign(Node var) {
Node assign =
IR.assign(var.getFirstChild().cloneNode(), var.getFirstChild().removeFirstChild());
return IR.exprResult(assign).useSourceInfoIfMissingFromForTree(var);
} | java | private static Node varToAssign(Node var) {
Node assign =
IR.assign(var.getFirstChild().cloneNode(), var.getFirstChild().removeFirstChild());
return IR.exprResult(assign).useSourceInfoIfMissingFromForTree(var);
} | [
"private",
"static",
"Node",
"varToAssign",
"(",
"Node",
"var",
")",
"{",
"Node",
"assign",
"=",
"IR",
".",
"assign",
"(",
"var",
".",
"getFirstChild",
"(",
")",
".",
"cloneNode",
"(",
")",
",",
"var",
".",
"getFirstChild",
"(",
")",
".",
"removeFirstChild",
"(",
")",
")",
";",
"return",
"IR",
".",
"exprResult",
"(",
"assign",
")",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"var",
")",
";",
"}"
] | Returns an assign replacing the equivalent var or let declaration. | [
"Returns",
"an",
"assign",
"replacing",
"the",
"equivalent",
"var",
"or",
"let",
"declaration",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L732-L736 |
24,557 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.convertSimpleObserverStringsToReferences | private void convertSimpleObserverStringsToReferences(final PolymerClassDefinition cls) {
for (MemberDefinition prop : cls.props) {
if (prop.value.isObjectLit()) {
Node observer = NodeUtil.getFirstPropMatchingKey(prop.value, "observer");
if (observer != null && observer.isString()) {
Node observerDirectReference =
IR.getprop(cls.target.cloneTree(), "prototype", observer.getString())
.useSourceInfoFrom(observer);
observer.replaceWith(observerDirectReference);
compiler.reportChangeToEnclosingScope(observerDirectReference);
}
}
}
} | java | private void convertSimpleObserverStringsToReferences(final PolymerClassDefinition cls) {
for (MemberDefinition prop : cls.props) {
if (prop.value.isObjectLit()) {
Node observer = NodeUtil.getFirstPropMatchingKey(prop.value, "observer");
if (observer != null && observer.isString()) {
Node observerDirectReference =
IR.getprop(cls.target.cloneTree(), "prototype", observer.getString())
.useSourceInfoFrom(observer);
observer.replaceWith(observerDirectReference);
compiler.reportChangeToEnclosingScope(observerDirectReference);
}
}
}
} | [
"private",
"void",
"convertSimpleObserverStringsToReferences",
"(",
"final",
"PolymerClassDefinition",
"cls",
")",
"{",
"for",
"(",
"MemberDefinition",
"prop",
":",
"cls",
".",
"props",
")",
"{",
"if",
"(",
"prop",
".",
"value",
".",
"isObjectLit",
"(",
")",
")",
"{",
"Node",
"observer",
"=",
"NodeUtil",
".",
"getFirstPropMatchingKey",
"(",
"prop",
".",
"value",
",",
"\"observer\"",
")",
";",
"if",
"(",
"observer",
"!=",
"null",
"&&",
"observer",
".",
"isString",
"(",
")",
")",
"{",
"Node",
"observerDirectReference",
"=",
"IR",
".",
"getprop",
"(",
"cls",
".",
"target",
".",
"cloneTree",
"(",
")",
",",
"\"prototype\"",
",",
"observer",
".",
"getString",
"(",
")",
")",
".",
"useSourceInfoFrom",
"(",
"observer",
")",
";",
"observer",
".",
"replaceWith",
"(",
"observerDirectReference",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"observerDirectReference",
")",
";",
"}",
"}",
"}",
"}"
] | Converts property observer strings to direct function references.
<p>From: <code>observer: '_observerName'</code> To: <code>
observer: ClassName.prototype._observerName</code> | [
"Converts",
"property",
"observer",
"strings",
"to",
"direct",
"function",
"references",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L744-L758 |
24,558 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.addComputedPropertiesReflectionCalls | private List<Node> addComputedPropertiesReflectionCalls(final PolymerClassDefinition cls) {
List<Node> propertySinkStatements = new ArrayList<>();
for (MemberDefinition prop : cls.props) {
if (prop.value.isObjectLit()) {
Node computed = NodeUtil.getFirstPropMatchingKey(prop.value, "computed");
if (computed != null && computed.isString()) {
propertySinkStatements.addAll(
replaceMethodStringWithReflectedCalls(cls.target, computed));
}
}
}
return propertySinkStatements;
} | java | private List<Node> addComputedPropertiesReflectionCalls(final PolymerClassDefinition cls) {
List<Node> propertySinkStatements = new ArrayList<>();
for (MemberDefinition prop : cls.props) {
if (prop.value.isObjectLit()) {
Node computed = NodeUtil.getFirstPropMatchingKey(prop.value, "computed");
if (computed != null && computed.isString()) {
propertySinkStatements.addAll(
replaceMethodStringWithReflectedCalls(cls.target, computed));
}
}
}
return propertySinkStatements;
} | [
"private",
"List",
"<",
"Node",
">",
"addComputedPropertiesReflectionCalls",
"(",
"final",
"PolymerClassDefinition",
"cls",
")",
"{",
"List",
"<",
"Node",
">",
"propertySinkStatements",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"MemberDefinition",
"prop",
":",
"cls",
".",
"props",
")",
"{",
"if",
"(",
"prop",
".",
"value",
".",
"isObjectLit",
"(",
")",
")",
"{",
"Node",
"computed",
"=",
"NodeUtil",
".",
"getFirstPropMatchingKey",
"(",
"prop",
".",
"value",
",",
"\"computed\"",
")",
";",
"if",
"(",
"computed",
"!=",
"null",
"&&",
"computed",
".",
"isString",
"(",
")",
")",
"{",
"propertySinkStatements",
".",
"addAll",
"(",
"replaceMethodStringWithReflectedCalls",
"(",
"cls",
".",
"target",
",",
"computed",
")",
")",
";",
"}",
"}",
"}",
"return",
"propertySinkStatements",
";",
"}"
] | For any property in the Polymer property configuration object with a `computed` key, parse the
method call and path arguments and replace them with property reflection calls.
<p>Returns a list of property sink statements to guard against dead code elimination since the
compiler may not see these methods as being used. | [
"For",
"any",
"property",
"in",
"the",
"Polymer",
"property",
"configuration",
"object",
"with",
"a",
"computed",
"key",
"parse",
"the",
"method",
"call",
"and",
"path",
"arguments",
"and",
"replace",
"them",
"with",
"property",
"reflection",
"calls",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L767-L779 |
24,559 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.addComplexObserverReflectionCalls | private List<Node> addComplexObserverReflectionCalls(final PolymerClassDefinition cls) {
List<Node> propertySinkStatements = new ArrayList<>();
Node classMembers = NodeUtil.getClassMembers(cls.definition);
Node getter = NodeUtil.getFirstGetterMatchingKey(classMembers, "observers");
if (getter != null) {
Node complexObservers = null;
for (Node child : NodeUtil.getFunctionBody(getter.getFirstChild()).children()) {
if (child.isReturn()) {
if (child.hasChildren() && child.getFirstChild().isArrayLit()) {
complexObservers = child.getFirstChild();
break;
}
}
}
if (complexObservers != null) {
for (Node complexObserver : complexObservers.children()) {
if (complexObserver.isString()) {
propertySinkStatements.addAll(
replaceMethodStringWithReflectedCalls(cls.target, complexObserver));
}
}
}
}
return propertySinkStatements;
} | java | private List<Node> addComplexObserverReflectionCalls(final PolymerClassDefinition cls) {
List<Node> propertySinkStatements = new ArrayList<>();
Node classMembers = NodeUtil.getClassMembers(cls.definition);
Node getter = NodeUtil.getFirstGetterMatchingKey(classMembers, "observers");
if (getter != null) {
Node complexObservers = null;
for (Node child : NodeUtil.getFunctionBody(getter.getFirstChild()).children()) {
if (child.isReturn()) {
if (child.hasChildren() && child.getFirstChild().isArrayLit()) {
complexObservers = child.getFirstChild();
break;
}
}
}
if (complexObservers != null) {
for (Node complexObserver : complexObservers.children()) {
if (complexObserver.isString()) {
propertySinkStatements.addAll(
replaceMethodStringWithReflectedCalls(cls.target, complexObserver));
}
}
}
}
return propertySinkStatements;
} | [
"private",
"List",
"<",
"Node",
">",
"addComplexObserverReflectionCalls",
"(",
"final",
"PolymerClassDefinition",
"cls",
")",
"{",
"List",
"<",
"Node",
">",
"propertySinkStatements",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Node",
"classMembers",
"=",
"NodeUtil",
".",
"getClassMembers",
"(",
"cls",
".",
"definition",
")",
";",
"Node",
"getter",
"=",
"NodeUtil",
".",
"getFirstGetterMatchingKey",
"(",
"classMembers",
",",
"\"observers\"",
")",
";",
"if",
"(",
"getter",
"!=",
"null",
")",
"{",
"Node",
"complexObservers",
"=",
"null",
";",
"for",
"(",
"Node",
"child",
":",
"NodeUtil",
".",
"getFunctionBody",
"(",
"getter",
".",
"getFirstChild",
"(",
")",
")",
".",
"children",
"(",
")",
")",
"{",
"if",
"(",
"child",
".",
"isReturn",
"(",
")",
")",
"{",
"if",
"(",
"child",
".",
"hasChildren",
"(",
")",
"&&",
"child",
".",
"getFirstChild",
"(",
")",
".",
"isArrayLit",
"(",
")",
")",
"{",
"complexObservers",
"=",
"child",
".",
"getFirstChild",
"(",
")",
";",
"break",
";",
"}",
"}",
"}",
"if",
"(",
"complexObservers",
"!=",
"null",
")",
"{",
"for",
"(",
"Node",
"complexObserver",
":",
"complexObservers",
".",
"children",
"(",
")",
")",
"{",
"if",
"(",
"complexObserver",
".",
"isString",
"(",
")",
")",
"{",
"propertySinkStatements",
".",
"addAll",
"(",
"replaceMethodStringWithReflectedCalls",
"(",
"cls",
".",
"target",
",",
"complexObserver",
")",
")",
";",
"}",
"}",
"}",
"}",
"return",
"propertySinkStatements",
";",
"}"
] | For any strings returned in the array from the Polymer static observers property, parse the
method call and path arguments and replace them with property reflection calls.
<p>Returns a list of property sink statements to guard against dead code elimination since the
compiler may not see these methods as being used. | [
"For",
"any",
"strings",
"returned",
"in",
"the",
"array",
"from",
"the",
"Polymer",
"static",
"observers",
"property",
"parse",
"the",
"method",
"call",
"and",
"path",
"arguments",
"and",
"replace",
"them",
"with",
"property",
"reflection",
"calls",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L788-L812 |
24,560 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.parseMethodParams | private List<String> parseMethodParams(String methodParameters, Node methodSignature) {
List<String> parsedParameters = new ArrayList<>();
char nextDelimeter = ',';
String currentTerm = "";
for (int i = 0; i < methodParameters.length(); i++) {
if (methodParameters.charAt(i) == nextDelimeter) {
if (nextDelimeter == ',') {
parsedParameters.add(currentTerm.trim());
currentTerm = "";
} else {
currentTerm += nextDelimeter;
nextDelimeter = ',';
}
} else {
currentTerm += methodParameters.charAt(i);
if (methodParameters.charAt(i) == '"' || methodParameters.charAt(i) == '\'') {
nextDelimeter = methodParameters.charAt(i);
}
}
}
if (nextDelimeter != ',') {
compiler.report(JSError.make(methodSignature, PolymerPassErrors.POLYMER_UNPARSABLE_STRING));
return parsedParameters;
}
if (currentTerm.length() > 0) {
parsedParameters.add(currentTerm.trim());
}
return parsedParameters;
} | java | private List<String> parseMethodParams(String methodParameters, Node methodSignature) {
List<String> parsedParameters = new ArrayList<>();
char nextDelimeter = ',';
String currentTerm = "";
for (int i = 0; i < methodParameters.length(); i++) {
if (methodParameters.charAt(i) == nextDelimeter) {
if (nextDelimeter == ',') {
parsedParameters.add(currentTerm.trim());
currentTerm = "";
} else {
currentTerm += nextDelimeter;
nextDelimeter = ',';
}
} else {
currentTerm += methodParameters.charAt(i);
if (methodParameters.charAt(i) == '"' || methodParameters.charAt(i) == '\'') {
nextDelimeter = methodParameters.charAt(i);
}
}
}
if (nextDelimeter != ',') {
compiler.report(JSError.make(methodSignature, PolymerPassErrors.POLYMER_UNPARSABLE_STRING));
return parsedParameters;
}
if (currentTerm.length() > 0) {
parsedParameters.add(currentTerm.trim());
}
return parsedParameters;
} | [
"private",
"List",
"<",
"String",
">",
"parseMethodParams",
"(",
"String",
"methodParameters",
",",
"Node",
"methodSignature",
")",
"{",
"List",
"<",
"String",
">",
"parsedParameters",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"char",
"nextDelimeter",
"=",
"'",
"'",
";",
"String",
"currentTerm",
"=",
"\"\"",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"methodParameters",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"methodParameters",
".",
"charAt",
"(",
"i",
")",
"==",
"nextDelimeter",
")",
"{",
"if",
"(",
"nextDelimeter",
"==",
"'",
"'",
")",
"{",
"parsedParameters",
".",
"add",
"(",
"currentTerm",
".",
"trim",
"(",
")",
")",
";",
"currentTerm",
"=",
"\"\"",
";",
"}",
"else",
"{",
"currentTerm",
"+=",
"nextDelimeter",
";",
"nextDelimeter",
"=",
"'",
"'",
";",
"}",
"}",
"else",
"{",
"currentTerm",
"+=",
"methodParameters",
".",
"charAt",
"(",
"i",
")",
";",
"if",
"(",
"methodParameters",
".",
"charAt",
"(",
"i",
")",
"==",
"'",
"'",
"||",
"methodParameters",
".",
"charAt",
"(",
"i",
")",
"==",
"'",
"'",
")",
"{",
"nextDelimeter",
"=",
"methodParameters",
".",
"charAt",
"(",
"i",
")",
";",
"}",
"}",
"}",
"if",
"(",
"nextDelimeter",
"!=",
"'",
"'",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"methodSignature",
",",
"PolymerPassErrors",
".",
"POLYMER_UNPARSABLE_STRING",
")",
")",
";",
"return",
"parsedParameters",
";",
"}",
"if",
"(",
"currentTerm",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"parsedParameters",
".",
"add",
"(",
"currentTerm",
".",
"trim",
"(",
")",
")",
";",
"}",
"return",
"parsedParameters",
";",
"}"
] | Parses the parameters string from a complex observer or computed property into distinct
parameters. Since a parameter can be a quoted string literal, we can't just split on commas. | [
"Parses",
"the",
"parameters",
"string",
"from",
"a",
"complex",
"observer",
"or",
"computed",
"property",
"into",
"distinct",
"parameters",
".",
"Since",
"a",
"parameter",
"can",
"be",
"a",
"quoted",
"string",
"literal",
"we",
"can",
"t",
"just",
"split",
"on",
"commas",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L944-L973 |
24,561 | google/closure-compiler | src/com/google/javascript/jscomp/PolymerClassRewriter.java | PolymerClassRewriter.isParamLiteral | private static boolean isParamLiteral(String param) {
try {
Double.parseDouble(param);
return true;
} catch (NumberFormatException e) {
// Check to see if the parameter is a literal - either a quoted string or
// numeric literal
if (param.length() > 1
&& (param.charAt(0) == '"' || param.charAt(0) == '\'')
&& param.charAt(0) == param.charAt(param.length() - 1)) {
return true;
}
}
return false;
} | java | private static boolean isParamLiteral(String param) {
try {
Double.parseDouble(param);
return true;
} catch (NumberFormatException e) {
// Check to see if the parameter is a literal - either a quoted string or
// numeric literal
if (param.length() > 1
&& (param.charAt(0) == '"' || param.charAt(0) == '\'')
&& param.charAt(0) == param.charAt(param.length() - 1)) {
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"isParamLiteral",
"(",
"String",
"param",
")",
"{",
"try",
"{",
"Double",
".",
"parseDouble",
"(",
"param",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"// Check to see if the parameter is a literal - either a quoted string or",
"// numeric literal",
"if",
"(",
"param",
".",
"length",
"(",
")",
">",
"1",
"&&",
"(",
"param",
".",
"charAt",
"(",
"0",
")",
"==",
"'",
"'",
"||",
"param",
".",
"charAt",
"(",
"0",
")",
"==",
"'",
"'",
")",
"&&",
"param",
".",
"charAt",
"(",
"0",
")",
"==",
"param",
".",
"charAt",
"(",
"param",
".",
"length",
"(",
")",
"-",
"1",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Determine if the method parameter a quoted string or numeric literal recognized by Polymer. | [
"Determine",
"if",
"the",
"method",
"parameter",
"a",
"quoted",
"string",
"or",
"numeric",
"literal",
"recognized",
"by",
"Polymer",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerClassRewriter.java#L976-L990 |
24,562 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.inferParameters | @SuppressWarnings("ReferenceEquality") // unknownType is a singleton
private FlowScope inferParameters(FlowScope entryFlowScope) {
Node functionNode = containerScope.getRootNode();
if (!functionNode.isFunction()) {
return entryFlowScope; // we're in the global scope
} else if (NodeUtil.isBundledGoogModuleCall(functionNode.getParent())) {
// Pretend the function literal in `goog.loadModule(function(exports) {` does not exist.
return entryFlowScope;
}
Node astParameters = functionNode.getSecondChild();
Node iifeArgumentNode = null;
if (NodeUtil.isInvocationTarget(functionNode)) {
iifeArgumentNode = functionNode.getNext();
}
FunctionType functionType = JSType.toMaybeFunctionType(functionNode.getJSType());
Node parameterTypeNode = functionType.getParametersNode().getFirstChild();
// This really iterates over three different things at once:
// - the actual AST parameter nodes (which may be REST, DEFAULT_VALUE, etc.)
// - the argument nodes in an IIFE
// - the parameter type nodes from the FunctionType on the FUNCTION node
// Always visit every AST parameter once, regardless of how many IIFE arguments or
// FunctionType param nodes there are.
for (Node astParameter : astParameters.children()) {
if (iifeArgumentNode != null && iifeArgumentNode.isSpread()) {
// block inference on all parameters that might possibly be set by a spread, e.g. `z` in
// (function f(x, y, z = 1))(...[1, 2], 'foo')
iifeArgumentNode = null;
}
// Running variable for the type of the param within the body of the function. We use the
// existing type on the param node as the default, and then transform it according to the
// declaration syntax.
JSType inferredType = getJSType(astParameter);
if (iifeArgumentNode != null) {
if (iifeArgumentNode.getJSType() != null) {
inferredType = iifeArgumentNode.getJSType();
}
} else if (parameterTypeNode != null) {
if (parameterTypeNode.getJSType() != null) {
inferredType = parameterTypeNode.getJSType();
}
}
Node defaultValue = null;
if (astParameter.isDefaultValue()) {
defaultValue = astParameter.getSecondChild();
// must call `traverse` to correctly type the default value
entryFlowScope = traverse(defaultValue, entryFlowScope);
astParameter = astParameter.getFirstChild();
} else if (astParameter.isRest()) {
// e.g. `function f(p1, ...restParamName) {}`
// set astParameter = restParamName
astParameter = astParameter.getOnlyChild();
// convert 'number' into 'Array<number>' for rest parameters
inferredType =
registry.createTemplatizedType(registry.getNativeObjectType(ARRAY_TYPE), inferredType);
}
if (defaultValue != null) {
// The param could possibly be the default type, and `undefined` args won't propagate in.
inferredType =
registry.createUnionType(
inferredType.restrictByNotUndefined(), getJSType(defaultValue));
}
if (astParameter.isDestructuringPattern()) {
// even if the inferredType is null, we still need to type all the nodes inside the
// destructuring pattern. (e.g. in computed properties or default value expressions)
entryFlowScope = updateDestructuringParameter(astParameter, inferredType, entryFlowScope);
} else {
// for simple named parameters, we only need to update the scope/AST if we have a new
// inferred type.
entryFlowScope =
updateNamedParameter(astParameter, defaultValue != null, inferredType, entryFlowScope);
}
parameterTypeNode = parameterTypeNode != null ? parameterTypeNode.getNext() : null;
iifeArgumentNode = iifeArgumentNode != null ? iifeArgumentNode.getNext() : null;
}
return entryFlowScope;
} | java | @SuppressWarnings("ReferenceEquality") // unknownType is a singleton
private FlowScope inferParameters(FlowScope entryFlowScope) {
Node functionNode = containerScope.getRootNode();
if (!functionNode.isFunction()) {
return entryFlowScope; // we're in the global scope
} else if (NodeUtil.isBundledGoogModuleCall(functionNode.getParent())) {
// Pretend the function literal in `goog.loadModule(function(exports) {` does not exist.
return entryFlowScope;
}
Node astParameters = functionNode.getSecondChild();
Node iifeArgumentNode = null;
if (NodeUtil.isInvocationTarget(functionNode)) {
iifeArgumentNode = functionNode.getNext();
}
FunctionType functionType = JSType.toMaybeFunctionType(functionNode.getJSType());
Node parameterTypeNode = functionType.getParametersNode().getFirstChild();
// This really iterates over three different things at once:
// - the actual AST parameter nodes (which may be REST, DEFAULT_VALUE, etc.)
// - the argument nodes in an IIFE
// - the parameter type nodes from the FunctionType on the FUNCTION node
// Always visit every AST parameter once, regardless of how many IIFE arguments or
// FunctionType param nodes there are.
for (Node astParameter : astParameters.children()) {
if (iifeArgumentNode != null && iifeArgumentNode.isSpread()) {
// block inference on all parameters that might possibly be set by a spread, e.g. `z` in
// (function f(x, y, z = 1))(...[1, 2], 'foo')
iifeArgumentNode = null;
}
// Running variable for the type of the param within the body of the function. We use the
// existing type on the param node as the default, and then transform it according to the
// declaration syntax.
JSType inferredType = getJSType(astParameter);
if (iifeArgumentNode != null) {
if (iifeArgumentNode.getJSType() != null) {
inferredType = iifeArgumentNode.getJSType();
}
} else if (parameterTypeNode != null) {
if (parameterTypeNode.getJSType() != null) {
inferredType = parameterTypeNode.getJSType();
}
}
Node defaultValue = null;
if (astParameter.isDefaultValue()) {
defaultValue = astParameter.getSecondChild();
// must call `traverse` to correctly type the default value
entryFlowScope = traverse(defaultValue, entryFlowScope);
astParameter = astParameter.getFirstChild();
} else if (astParameter.isRest()) {
// e.g. `function f(p1, ...restParamName) {}`
// set astParameter = restParamName
astParameter = astParameter.getOnlyChild();
// convert 'number' into 'Array<number>' for rest parameters
inferredType =
registry.createTemplatizedType(registry.getNativeObjectType(ARRAY_TYPE), inferredType);
}
if (defaultValue != null) {
// The param could possibly be the default type, and `undefined` args won't propagate in.
inferredType =
registry.createUnionType(
inferredType.restrictByNotUndefined(), getJSType(defaultValue));
}
if (astParameter.isDestructuringPattern()) {
// even if the inferredType is null, we still need to type all the nodes inside the
// destructuring pattern. (e.g. in computed properties or default value expressions)
entryFlowScope = updateDestructuringParameter(astParameter, inferredType, entryFlowScope);
} else {
// for simple named parameters, we only need to update the scope/AST if we have a new
// inferred type.
entryFlowScope =
updateNamedParameter(astParameter, defaultValue != null, inferredType, entryFlowScope);
}
parameterTypeNode = parameterTypeNode != null ? parameterTypeNode.getNext() : null;
iifeArgumentNode = iifeArgumentNode != null ? iifeArgumentNode.getNext() : null;
}
return entryFlowScope;
} | [
"@",
"SuppressWarnings",
"(",
"\"ReferenceEquality\"",
")",
"// unknownType is a singleton",
"private",
"FlowScope",
"inferParameters",
"(",
"FlowScope",
"entryFlowScope",
")",
"{",
"Node",
"functionNode",
"=",
"containerScope",
".",
"getRootNode",
"(",
")",
";",
"if",
"(",
"!",
"functionNode",
".",
"isFunction",
"(",
")",
")",
"{",
"return",
"entryFlowScope",
";",
"// we're in the global scope",
"}",
"else",
"if",
"(",
"NodeUtil",
".",
"isBundledGoogModuleCall",
"(",
"functionNode",
".",
"getParent",
"(",
")",
")",
")",
"{",
"// Pretend the function literal in `goog.loadModule(function(exports) {` does not exist.",
"return",
"entryFlowScope",
";",
"}",
"Node",
"astParameters",
"=",
"functionNode",
".",
"getSecondChild",
"(",
")",
";",
"Node",
"iifeArgumentNode",
"=",
"null",
";",
"if",
"(",
"NodeUtil",
".",
"isInvocationTarget",
"(",
"functionNode",
")",
")",
"{",
"iifeArgumentNode",
"=",
"functionNode",
".",
"getNext",
"(",
")",
";",
"}",
"FunctionType",
"functionType",
"=",
"JSType",
".",
"toMaybeFunctionType",
"(",
"functionNode",
".",
"getJSType",
"(",
")",
")",
";",
"Node",
"parameterTypeNode",
"=",
"functionType",
".",
"getParametersNode",
"(",
")",
".",
"getFirstChild",
"(",
")",
";",
"// This really iterates over three different things at once:",
"// - the actual AST parameter nodes (which may be REST, DEFAULT_VALUE, etc.)",
"// - the argument nodes in an IIFE",
"// - the parameter type nodes from the FunctionType on the FUNCTION node",
"// Always visit every AST parameter once, regardless of how many IIFE arguments or",
"// FunctionType param nodes there are.",
"for",
"(",
"Node",
"astParameter",
":",
"astParameters",
".",
"children",
"(",
")",
")",
"{",
"if",
"(",
"iifeArgumentNode",
"!=",
"null",
"&&",
"iifeArgumentNode",
".",
"isSpread",
"(",
")",
")",
"{",
"// block inference on all parameters that might possibly be set by a spread, e.g. `z` in",
"// (function f(x, y, z = 1))(...[1, 2], 'foo')",
"iifeArgumentNode",
"=",
"null",
";",
"}",
"// Running variable for the type of the param within the body of the function. We use the",
"// existing type on the param node as the default, and then transform it according to the",
"// declaration syntax.",
"JSType",
"inferredType",
"=",
"getJSType",
"(",
"astParameter",
")",
";",
"if",
"(",
"iifeArgumentNode",
"!=",
"null",
")",
"{",
"if",
"(",
"iifeArgumentNode",
".",
"getJSType",
"(",
")",
"!=",
"null",
")",
"{",
"inferredType",
"=",
"iifeArgumentNode",
".",
"getJSType",
"(",
")",
";",
"}",
"}",
"else",
"if",
"(",
"parameterTypeNode",
"!=",
"null",
")",
"{",
"if",
"(",
"parameterTypeNode",
".",
"getJSType",
"(",
")",
"!=",
"null",
")",
"{",
"inferredType",
"=",
"parameterTypeNode",
".",
"getJSType",
"(",
")",
";",
"}",
"}",
"Node",
"defaultValue",
"=",
"null",
";",
"if",
"(",
"astParameter",
".",
"isDefaultValue",
"(",
")",
")",
"{",
"defaultValue",
"=",
"astParameter",
".",
"getSecondChild",
"(",
")",
";",
"// must call `traverse` to correctly type the default value",
"entryFlowScope",
"=",
"traverse",
"(",
"defaultValue",
",",
"entryFlowScope",
")",
";",
"astParameter",
"=",
"astParameter",
".",
"getFirstChild",
"(",
")",
";",
"}",
"else",
"if",
"(",
"astParameter",
".",
"isRest",
"(",
")",
")",
"{",
"// e.g. `function f(p1, ...restParamName) {}`",
"// set astParameter = restParamName",
"astParameter",
"=",
"astParameter",
".",
"getOnlyChild",
"(",
")",
";",
"// convert 'number' into 'Array<number>' for rest parameters",
"inferredType",
"=",
"registry",
".",
"createTemplatizedType",
"(",
"registry",
".",
"getNativeObjectType",
"(",
"ARRAY_TYPE",
")",
",",
"inferredType",
")",
";",
"}",
"if",
"(",
"defaultValue",
"!=",
"null",
")",
"{",
"// The param could possibly be the default type, and `undefined` args won't propagate in.",
"inferredType",
"=",
"registry",
".",
"createUnionType",
"(",
"inferredType",
".",
"restrictByNotUndefined",
"(",
")",
",",
"getJSType",
"(",
"defaultValue",
")",
")",
";",
"}",
"if",
"(",
"astParameter",
".",
"isDestructuringPattern",
"(",
")",
")",
"{",
"// even if the inferredType is null, we still need to type all the nodes inside the",
"// destructuring pattern. (e.g. in computed properties or default value expressions)",
"entryFlowScope",
"=",
"updateDestructuringParameter",
"(",
"astParameter",
",",
"inferredType",
",",
"entryFlowScope",
")",
";",
"}",
"else",
"{",
"// for simple named parameters, we only need to update the scope/AST if we have a new",
"// inferred type.",
"entryFlowScope",
"=",
"updateNamedParameter",
"(",
"astParameter",
",",
"defaultValue",
"!=",
"null",
",",
"inferredType",
",",
"entryFlowScope",
")",
";",
"}",
"parameterTypeNode",
"=",
"parameterTypeNode",
"!=",
"null",
"?",
"parameterTypeNode",
".",
"getNext",
"(",
")",
":",
"null",
";",
"iifeArgumentNode",
"=",
"iifeArgumentNode",
"!=",
"null",
"?",
"iifeArgumentNode",
".",
"getNext",
"(",
")",
":",
"null",
";",
"}",
"return",
"entryFlowScope",
";",
"}"
] | Infers all of a function's parameters if their types aren't declared. | [
"Infers",
"all",
"of",
"a",
"function",
"s",
"parameters",
"if",
"their",
"types",
"aren",
"t",
"declared",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L151-L236 |
24,563 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.traverseReturn | @CheckReturnValue
private FlowScope traverseReturn(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node retValue = n.getFirstChild();
if (retValue != null) {
JSType type = functionScope.getRootNode().getJSType();
if (type != null) {
FunctionType fnType = type.toMaybeFunctionType();
if (fnType != null) {
inferPropertyTypesToMatchConstraint(
retValue.getJSType(), fnType.getReturnType());
}
}
}
return scope;
} | java | @CheckReturnValue
private FlowScope traverseReturn(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node retValue = n.getFirstChild();
if (retValue != null) {
JSType type = functionScope.getRootNode().getJSType();
if (type != null) {
FunctionType fnType = type.toMaybeFunctionType();
if (fnType != null) {
inferPropertyTypesToMatchConstraint(
retValue.getJSType(), fnType.getReturnType());
}
}
}
return scope;
} | [
"@",
"CheckReturnValue",
"private",
"FlowScope",
"traverseReturn",
"(",
"Node",
"n",
",",
"FlowScope",
"scope",
")",
"{",
"scope",
"=",
"traverseChildren",
"(",
"n",
",",
"scope",
")",
";",
"Node",
"retValue",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"if",
"(",
"retValue",
"!=",
"null",
")",
"{",
"JSType",
"type",
"=",
"functionScope",
".",
"getRootNode",
"(",
")",
".",
"getJSType",
"(",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"FunctionType",
"fnType",
"=",
"type",
".",
"toMaybeFunctionType",
"(",
")",
";",
"if",
"(",
"fnType",
"!=",
"null",
")",
"{",
"inferPropertyTypesToMatchConstraint",
"(",
"retValue",
".",
"getJSType",
"(",
")",
",",
"fnType",
".",
"getReturnType",
"(",
")",
")",
";",
"}",
"}",
"}",
"return",
"scope",
";",
"}"
] | Traverse a return value. | [
"Traverse",
"a",
"return",
"value",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L830-L846 |
24,564 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.traverseCatch | @CheckReturnValue
private FlowScope traverseCatch(Node catchNode, FlowScope scope) {
Node catchTarget = catchNode.getFirstChild();
if (catchTarget.isName()) {
// TODO(lharker): is this case even necessary? seems like TypedScopeCreator handles it
Node name = catchNode.getFirstChild();
JSType type;
// If the catch expression name was declared in the catch use that type,
// otherwise use "unknown".
JSDocInfo info = name.getJSDocInfo();
if (info != null && info.hasType()) {
type = info.getType().evaluate(scope.getDeclarationScope(), registry);
} else {
type = getNativeType(JSTypeNative.UNKNOWN_TYPE);
}
name.setJSType(type);
return redeclareSimpleVar(scope, name, type);
} else if (catchTarget.isDestructuringPattern()) {
Node pattern = catchNode.getFirstChild();
return traverseDestructuringPattern(pattern, scope, unknownType, AssignmentType.DECLARATION);
} else {
checkState(catchTarget.isEmpty(), catchTarget);
// ES2019 allows `try {} catch {}` with no catch expression
return scope;
}
} | java | @CheckReturnValue
private FlowScope traverseCatch(Node catchNode, FlowScope scope) {
Node catchTarget = catchNode.getFirstChild();
if (catchTarget.isName()) {
// TODO(lharker): is this case even necessary? seems like TypedScopeCreator handles it
Node name = catchNode.getFirstChild();
JSType type;
// If the catch expression name was declared in the catch use that type,
// otherwise use "unknown".
JSDocInfo info = name.getJSDocInfo();
if (info != null && info.hasType()) {
type = info.getType().evaluate(scope.getDeclarationScope(), registry);
} else {
type = getNativeType(JSTypeNative.UNKNOWN_TYPE);
}
name.setJSType(type);
return redeclareSimpleVar(scope, name, type);
} else if (catchTarget.isDestructuringPattern()) {
Node pattern = catchNode.getFirstChild();
return traverseDestructuringPattern(pattern, scope, unknownType, AssignmentType.DECLARATION);
} else {
checkState(catchTarget.isEmpty(), catchTarget);
// ES2019 allows `try {} catch {}` with no catch expression
return scope;
}
} | [
"@",
"CheckReturnValue",
"private",
"FlowScope",
"traverseCatch",
"(",
"Node",
"catchNode",
",",
"FlowScope",
"scope",
")",
"{",
"Node",
"catchTarget",
"=",
"catchNode",
".",
"getFirstChild",
"(",
")",
";",
"if",
"(",
"catchTarget",
".",
"isName",
"(",
")",
")",
"{",
"// TODO(lharker): is this case even necessary? seems like TypedScopeCreator handles it",
"Node",
"name",
"=",
"catchNode",
".",
"getFirstChild",
"(",
")",
";",
"JSType",
"type",
";",
"// If the catch expression name was declared in the catch use that type,",
"// otherwise use \"unknown\".",
"JSDocInfo",
"info",
"=",
"name",
".",
"getJSDocInfo",
"(",
")",
";",
"if",
"(",
"info",
"!=",
"null",
"&&",
"info",
".",
"hasType",
"(",
")",
")",
"{",
"type",
"=",
"info",
".",
"getType",
"(",
")",
".",
"evaluate",
"(",
"scope",
".",
"getDeclarationScope",
"(",
")",
",",
"registry",
")",
";",
"}",
"else",
"{",
"type",
"=",
"getNativeType",
"(",
"JSTypeNative",
".",
"UNKNOWN_TYPE",
")",
";",
"}",
"name",
".",
"setJSType",
"(",
"type",
")",
";",
"return",
"redeclareSimpleVar",
"(",
"scope",
",",
"name",
",",
"type",
")",
";",
"}",
"else",
"if",
"(",
"catchTarget",
".",
"isDestructuringPattern",
"(",
")",
")",
"{",
"Node",
"pattern",
"=",
"catchNode",
".",
"getFirstChild",
"(",
")",
";",
"return",
"traverseDestructuringPattern",
"(",
"pattern",
",",
"scope",
",",
"unknownType",
",",
"AssignmentType",
".",
"DECLARATION",
")",
";",
"}",
"else",
"{",
"checkState",
"(",
"catchTarget",
".",
"isEmpty",
"(",
")",
",",
"catchTarget",
")",
";",
"// ES2019 allows `try {} catch {}` with no catch expression",
"return",
"scope",
";",
"}",
"}"
] | Any value can be thrown, so it's really impossible to determine the type of a CATCH param.
Treat it as the UNKNOWN type. | [
"Any",
"value",
"can",
"be",
"thrown",
"so",
"it",
"s",
"really",
"impossible",
"to",
"determine",
"the",
"type",
"of",
"a",
"CATCH",
"param",
".",
"Treat",
"it",
"as",
"the",
"UNKNOWN",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L852-L877 |
24,565 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.updateScopeForAssignment | @CheckReturnValue
private FlowScope updateScopeForAssignment(
FlowScope scope, Node target, JSType resultType, Node updateNode, AssignmentType type) {
checkNotNull(resultType);
checkState(updateNode == null || updateNode == target);
JSType targetType = target.getJSType(); // may be null
Node right = NodeUtil.getRValueOfLValue(target);
if (isPossibleMixinApplication(target, right)) {
addMissingInterfaceProperties(targetType);
}
switch (target.getToken()) {
case NAME:
String varName = target.getString();
TypedVar var = getDeclaredVar(scope, varName);
JSType varType = var == null ? null : var.getType();
boolean isVarDeclaration =
type == AssignmentType.DECLARATION
&& varType != null
&& !var.isTypeInferred()
&& var.getNameNode() != null;
// Whether this variable is declared not because it has JSDoc with a declaration, but
// because it is const and the right-hand-side is easily inferrable.
// e.g. these are 'typeless const declarations':
// const x = 0;
// /** @const */
// a.b.c = SomeOtherConstructor;
// but these are not:
// let x = 0;
// /** @const @constructor */
// a.b.c = someMixin();
// This is messy, since the definition of 'typeless const' is duplicated in
// TypedScopeCreator and this code.
boolean isTypelessConstDecl =
isVarDeclaration
&& NodeUtil.isConstantDeclaration(
compiler.getCodingConvention(), var.getJSDocInfo(), var.getNameNode())
&& !(var.getJSDocInfo() != null
&& var.getJSDocInfo().containsDeclarationExcludingTypelessConst());
// When looking at VAR initializers for declared VARs, we tend
// to use the declared type over the type it's being
// initialized to in the global scope.
//
// For example,
// /** @param {number} */ var f = goog.abstractMethod;
// it's obvious that the programmer wants you to use
// the declared function signature, not the inferred signature.
//
// Or,
// /** @type {Object.<string>} */ var x = {};
// the one-time anonymous object on the right side
// is as narrow as it can possibly be, but we need to make
// sure we back-infer the <string> element constraint on
// the left hand side, so we use the left hand side.
boolean isVarTypeBetter = isVarDeclaration
// Makes it easier to check for NPEs.
&& !resultType.isNullType() && !resultType.isVoidType()
// Do not use the var type if the declaration looked like
// /** @const */ var x = 3;
// because this type was computed from the RHS
&& !isTypelessConstDecl;
// TODO(nicksantos): This might be a better check once we have
// back-inference of object/array constraints. It will probably
// introduce more type warnings. It uses the result type iff it's
// strictly narrower than the declared var type.
//
//boolean isVarTypeBetter = isVarDeclaration &&
// (varType.restrictByNotNullOrUndefined().isSubtype(resultType)
// || !resultType.isSubtype(varType));
if (isVarTypeBetter) {
scope = redeclareSimpleVar(scope, target, varType);
} else {
scope = redeclareSimpleVar(scope, target, resultType);
}
if (updateNode != null) {
updateNode.setJSType(resultType);
}
if (var != null
&& var.isTypeInferred()
// Don't change the typed scope to include "undefined" upon seeing "let foo;", because
// this is incompatible with how we currently handle VARs and breaks existing code.
// TODO(sdh): remove this condition after cleaning up code depending on it.
&& !(target.getParent().isLet() && !target.hasChildren())) {
JSType oldType = var.getType();
var.setType(oldType == null ? resultType : oldType.getLeastSupertype(resultType));
} else if (isTypelessConstDecl) {
// /** @const */ var x = y;
// should be redeclared, so that the type of y
// gets propagated to inner scopes.
var.setType(resultType);
}
break;
case GETPROP:
if (target.isQualifiedName()) {
String qualifiedName = target.getQualifiedName();
boolean declaredSlotType = false;
JSType rawObjType = target.getFirstChild().getJSType();
if (rawObjType != null) {
ObjectType objType = ObjectType.cast(
rawObjType.restrictByNotNullOrUndefined());
if (objType != null) {
String propName = target.getLastChild().getString();
declaredSlotType = objType.isPropertyTypeDeclared(propName);
}
}
JSType safeLeftType = targetType == null ? unknownType : targetType;
scope =
scope.inferQualifiedSlot(
target, qualifiedName, safeLeftType, resultType, declaredSlotType);
}
if (updateNode != null) {
updateNode.setJSType(resultType);
}
ensurePropertyDefined(target, resultType, scope);
break;
default:
break;
}
return scope;
} | java | @CheckReturnValue
private FlowScope updateScopeForAssignment(
FlowScope scope, Node target, JSType resultType, Node updateNode, AssignmentType type) {
checkNotNull(resultType);
checkState(updateNode == null || updateNode == target);
JSType targetType = target.getJSType(); // may be null
Node right = NodeUtil.getRValueOfLValue(target);
if (isPossibleMixinApplication(target, right)) {
addMissingInterfaceProperties(targetType);
}
switch (target.getToken()) {
case NAME:
String varName = target.getString();
TypedVar var = getDeclaredVar(scope, varName);
JSType varType = var == null ? null : var.getType();
boolean isVarDeclaration =
type == AssignmentType.DECLARATION
&& varType != null
&& !var.isTypeInferred()
&& var.getNameNode() != null;
// Whether this variable is declared not because it has JSDoc with a declaration, but
// because it is const and the right-hand-side is easily inferrable.
// e.g. these are 'typeless const declarations':
// const x = 0;
// /** @const */
// a.b.c = SomeOtherConstructor;
// but these are not:
// let x = 0;
// /** @const @constructor */
// a.b.c = someMixin();
// This is messy, since the definition of 'typeless const' is duplicated in
// TypedScopeCreator and this code.
boolean isTypelessConstDecl =
isVarDeclaration
&& NodeUtil.isConstantDeclaration(
compiler.getCodingConvention(), var.getJSDocInfo(), var.getNameNode())
&& !(var.getJSDocInfo() != null
&& var.getJSDocInfo().containsDeclarationExcludingTypelessConst());
// When looking at VAR initializers for declared VARs, we tend
// to use the declared type over the type it's being
// initialized to in the global scope.
//
// For example,
// /** @param {number} */ var f = goog.abstractMethod;
// it's obvious that the programmer wants you to use
// the declared function signature, not the inferred signature.
//
// Or,
// /** @type {Object.<string>} */ var x = {};
// the one-time anonymous object on the right side
// is as narrow as it can possibly be, but we need to make
// sure we back-infer the <string> element constraint on
// the left hand side, so we use the left hand side.
boolean isVarTypeBetter = isVarDeclaration
// Makes it easier to check for NPEs.
&& !resultType.isNullType() && !resultType.isVoidType()
// Do not use the var type if the declaration looked like
// /** @const */ var x = 3;
// because this type was computed from the RHS
&& !isTypelessConstDecl;
// TODO(nicksantos): This might be a better check once we have
// back-inference of object/array constraints. It will probably
// introduce more type warnings. It uses the result type iff it's
// strictly narrower than the declared var type.
//
//boolean isVarTypeBetter = isVarDeclaration &&
// (varType.restrictByNotNullOrUndefined().isSubtype(resultType)
// || !resultType.isSubtype(varType));
if (isVarTypeBetter) {
scope = redeclareSimpleVar(scope, target, varType);
} else {
scope = redeclareSimpleVar(scope, target, resultType);
}
if (updateNode != null) {
updateNode.setJSType(resultType);
}
if (var != null
&& var.isTypeInferred()
// Don't change the typed scope to include "undefined" upon seeing "let foo;", because
// this is incompatible with how we currently handle VARs and breaks existing code.
// TODO(sdh): remove this condition after cleaning up code depending on it.
&& !(target.getParent().isLet() && !target.hasChildren())) {
JSType oldType = var.getType();
var.setType(oldType == null ? resultType : oldType.getLeastSupertype(resultType));
} else if (isTypelessConstDecl) {
// /** @const */ var x = y;
// should be redeclared, so that the type of y
// gets propagated to inner scopes.
var.setType(resultType);
}
break;
case GETPROP:
if (target.isQualifiedName()) {
String qualifiedName = target.getQualifiedName();
boolean declaredSlotType = false;
JSType rawObjType = target.getFirstChild().getJSType();
if (rawObjType != null) {
ObjectType objType = ObjectType.cast(
rawObjType.restrictByNotNullOrUndefined());
if (objType != null) {
String propName = target.getLastChild().getString();
declaredSlotType = objType.isPropertyTypeDeclared(propName);
}
}
JSType safeLeftType = targetType == null ? unknownType : targetType;
scope =
scope.inferQualifiedSlot(
target, qualifiedName, safeLeftType, resultType, declaredSlotType);
}
if (updateNode != null) {
updateNode.setJSType(resultType);
}
ensurePropertyDefined(target, resultType, scope);
break;
default:
break;
}
return scope;
} | [
"@",
"CheckReturnValue",
"private",
"FlowScope",
"updateScopeForAssignment",
"(",
"FlowScope",
"scope",
",",
"Node",
"target",
",",
"JSType",
"resultType",
",",
"Node",
"updateNode",
",",
"AssignmentType",
"type",
")",
"{",
"checkNotNull",
"(",
"resultType",
")",
";",
"checkState",
"(",
"updateNode",
"==",
"null",
"||",
"updateNode",
"==",
"target",
")",
";",
"JSType",
"targetType",
"=",
"target",
".",
"getJSType",
"(",
")",
";",
"// may be null",
"Node",
"right",
"=",
"NodeUtil",
".",
"getRValueOfLValue",
"(",
"target",
")",
";",
"if",
"(",
"isPossibleMixinApplication",
"(",
"target",
",",
"right",
")",
")",
"{",
"addMissingInterfaceProperties",
"(",
"targetType",
")",
";",
"}",
"switch",
"(",
"target",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"NAME",
":",
"String",
"varName",
"=",
"target",
".",
"getString",
"(",
")",
";",
"TypedVar",
"var",
"=",
"getDeclaredVar",
"(",
"scope",
",",
"varName",
")",
";",
"JSType",
"varType",
"=",
"var",
"==",
"null",
"?",
"null",
":",
"var",
".",
"getType",
"(",
")",
";",
"boolean",
"isVarDeclaration",
"=",
"type",
"==",
"AssignmentType",
".",
"DECLARATION",
"&&",
"varType",
"!=",
"null",
"&&",
"!",
"var",
".",
"isTypeInferred",
"(",
")",
"&&",
"var",
".",
"getNameNode",
"(",
")",
"!=",
"null",
";",
"// Whether this variable is declared not because it has JSDoc with a declaration, but",
"// because it is const and the right-hand-side is easily inferrable.",
"// e.g. these are 'typeless const declarations':",
"// const x = 0;",
"// /** @const */",
"// a.b.c = SomeOtherConstructor;",
"// but these are not:",
"// let x = 0;",
"// /** @const @constructor */",
"// a.b.c = someMixin();",
"// This is messy, since the definition of 'typeless const' is duplicated in",
"// TypedScopeCreator and this code.",
"boolean",
"isTypelessConstDecl",
"=",
"isVarDeclaration",
"&&",
"NodeUtil",
".",
"isConstantDeclaration",
"(",
"compiler",
".",
"getCodingConvention",
"(",
")",
",",
"var",
".",
"getJSDocInfo",
"(",
")",
",",
"var",
".",
"getNameNode",
"(",
")",
")",
"&&",
"!",
"(",
"var",
".",
"getJSDocInfo",
"(",
")",
"!=",
"null",
"&&",
"var",
".",
"getJSDocInfo",
"(",
")",
".",
"containsDeclarationExcludingTypelessConst",
"(",
")",
")",
";",
"// When looking at VAR initializers for declared VARs, we tend",
"// to use the declared type over the type it's being",
"// initialized to in the global scope.",
"//",
"// For example,",
"// /** @param {number} */ var f = goog.abstractMethod;",
"// it's obvious that the programmer wants you to use",
"// the declared function signature, not the inferred signature.",
"//",
"// Or,",
"// /** @type {Object.<string>} */ var x = {};",
"// the one-time anonymous object on the right side",
"// is as narrow as it can possibly be, but we need to make",
"// sure we back-infer the <string> element constraint on",
"// the left hand side, so we use the left hand side.",
"boolean",
"isVarTypeBetter",
"=",
"isVarDeclaration",
"// Makes it easier to check for NPEs.",
"&&",
"!",
"resultType",
".",
"isNullType",
"(",
")",
"&&",
"!",
"resultType",
".",
"isVoidType",
"(",
")",
"// Do not use the var type if the declaration looked like",
"// /** @const */ var x = 3;",
"// because this type was computed from the RHS",
"&&",
"!",
"isTypelessConstDecl",
";",
"// TODO(nicksantos): This might be a better check once we have",
"// back-inference of object/array constraints. It will probably",
"// introduce more type warnings. It uses the result type iff it's",
"// strictly narrower than the declared var type.",
"//",
"//boolean isVarTypeBetter = isVarDeclaration &&",
"// (varType.restrictByNotNullOrUndefined().isSubtype(resultType)",
"// || !resultType.isSubtype(varType));",
"if",
"(",
"isVarTypeBetter",
")",
"{",
"scope",
"=",
"redeclareSimpleVar",
"(",
"scope",
",",
"target",
",",
"varType",
")",
";",
"}",
"else",
"{",
"scope",
"=",
"redeclareSimpleVar",
"(",
"scope",
",",
"target",
",",
"resultType",
")",
";",
"}",
"if",
"(",
"updateNode",
"!=",
"null",
")",
"{",
"updateNode",
".",
"setJSType",
"(",
"resultType",
")",
";",
"}",
"if",
"(",
"var",
"!=",
"null",
"&&",
"var",
".",
"isTypeInferred",
"(",
")",
"// Don't change the typed scope to include \"undefined\" upon seeing \"let foo;\", because",
"// this is incompatible with how we currently handle VARs and breaks existing code.",
"// TODO(sdh): remove this condition after cleaning up code depending on it.",
"&&",
"!",
"(",
"target",
".",
"getParent",
"(",
")",
".",
"isLet",
"(",
")",
"&&",
"!",
"target",
".",
"hasChildren",
"(",
")",
")",
")",
"{",
"JSType",
"oldType",
"=",
"var",
".",
"getType",
"(",
")",
";",
"var",
".",
"setType",
"(",
"oldType",
"==",
"null",
"?",
"resultType",
":",
"oldType",
".",
"getLeastSupertype",
"(",
"resultType",
")",
")",
";",
"}",
"else",
"if",
"(",
"isTypelessConstDecl",
")",
"{",
"// /** @const */ var x = y;",
"// should be redeclared, so that the type of y",
"// gets propagated to inner scopes.",
"var",
".",
"setType",
"(",
"resultType",
")",
";",
"}",
"break",
";",
"case",
"GETPROP",
":",
"if",
"(",
"target",
".",
"isQualifiedName",
"(",
")",
")",
"{",
"String",
"qualifiedName",
"=",
"target",
".",
"getQualifiedName",
"(",
")",
";",
"boolean",
"declaredSlotType",
"=",
"false",
";",
"JSType",
"rawObjType",
"=",
"target",
".",
"getFirstChild",
"(",
")",
".",
"getJSType",
"(",
")",
";",
"if",
"(",
"rawObjType",
"!=",
"null",
")",
"{",
"ObjectType",
"objType",
"=",
"ObjectType",
".",
"cast",
"(",
"rawObjType",
".",
"restrictByNotNullOrUndefined",
"(",
")",
")",
";",
"if",
"(",
"objType",
"!=",
"null",
")",
"{",
"String",
"propName",
"=",
"target",
".",
"getLastChild",
"(",
")",
".",
"getString",
"(",
")",
";",
"declaredSlotType",
"=",
"objType",
".",
"isPropertyTypeDeclared",
"(",
"propName",
")",
";",
"}",
"}",
"JSType",
"safeLeftType",
"=",
"targetType",
"==",
"null",
"?",
"unknownType",
":",
"targetType",
";",
"scope",
"=",
"scope",
".",
"inferQualifiedSlot",
"(",
"target",
",",
"qualifiedName",
",",
"safeLeftType",
",",
"resultType",
",",
"declaredSlotType",
")",
";",
"}",
"if",
"(",
"updateNode",
"!=",
"null",
")",
"{",
"updateNode",
".",
"setJSType",
"(",
"resultType",
")",
";",
"}",
"ensurePropertyDefined",
"(",
"target",
",",
"resultType",
",",
"scope",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"return",
"scope",
";",
"}"
] | Updates the scope according to the result of an assignment. | [
"Updates",
"the",
"scope",
"according",
"to",
"the",
"result",
"of",
"an",
"assignment",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L959-L1088 |
24,566 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.ensurePropertyDefined | private void ensurePropertyDefined(Node getprop, JSType rightType, FlowScope scope) {
String propName = getprop.getLastChild().getString();
Node obj = getprop.getFirstChild();
JSType nodeType = getJSType(obj);
ObjectType objectType = ObjectType.cast(
nodeType.restrictByNotNullOrUndefined());
boolean propCreationInConstructor =
obj.isThis() && getJSType(containerScope.getRootNode()).isConstructor();
if (objectType == null) {
registry.registerPropertyOnType(propName, nodeType);
} else {
if (nodeType.isStruct() && !objectType.hasProperty(propName)) {
// In general, we don't want to define a property on a struct object,
// b/c TypeCheck will later check for improper property creation on
// structs. There are two exceptions.
// 1) If it's a property created inside the constructor, on the newly
// created instance, allow it.
// 2) If it's a prototype property, allow it. For example:
// Foo.prototype.bar = baz;
// where Foo.prototype is a struct and the assignment happens at the
// top level and the constructor Foo is defined in the same file.
boolean staticPropCreation = false;
Node maybeAssignStm = getprop.getGrandparent();
if (containerScope.isGlobal() && NodeUtil.isPrototypePropertyDeclaration(maybeAssignStm)) {
String propCreationFilename = maybeAssignStm.getSourceFileName();
Node ctor = objectType.getOwnerFunction().getSource();
if (ctor != null && ctor.getSourceFileName().equals(propCreationFilename)) {
staticPropCreation = true;
}
}
if (!propCreationInConstructor && !staticPropCreation) {
return; // Early return to avoid creating the property below.
}
}
if (ensurePropertyDeclaredHelper(getprop, objectType, scope)) {
return;
}
if (!objectType.isPropertyTypeDeclared(propName)) {
// We do not want a "stray" assign to define an inferred property
// for every object of this type in the program. So we use a heuristic
// approach to determine whether to infer the property.
//
// 1) If the property is already defined, join it with the previously
// inferred type.
// 2) If this isn't an instance object, define it.
// 3) If the property of an object is being assigned in the constructor,
// define it.
// 4) If this is a stub, define it.
// 5) Otherwise, do not define the type, but declare it in the registry
// so that we can use it for missing property checks.
if (objectType.hasProperty(propName) || !objectType.isInstanceType()) {
if ("prototype".equals(propName)) {
objectType.defineDeclaredProperty(propName, rightType, getprop);
} else {
objectType.defineInferredProperty(propName, rightType, getprop);
}
} else if (propCreationInConstructor) {
objectType.defineInferredProperty(propName, rightType, getprop);
} else {
registry.registerPropertyOnType(propName, objectType);
}
}
}
} | java | private void ensurePropertyDefined(Node getprop, JSType rightType, FlowScope scope) {
String propName = getprop.getLastChild().getString();
Node obj = getprop.getFirstChild();
JSType nodeType = getJSType(obj);
ObjectType objectType = ObjectType.cast(
nodeType.restrictByNotNullOrUndefined());
boolean propCreationInConstructor =
obj.isThis() && getJSType(containerScope.getRootNode()).isConstructor();
if (objectType == null) {
registry.registerPropertyOnType(propName, nodeType);
} else {
if (nodeType.isStruct() && !objectType.hasProperty(propName)) {
// In general, we don't want to define a property on a struct object,
// b/c TypeCheck will later check for improper property creation on
// structs. There are two exceptions.
// 1) If it's a property created inside the constructor, on the newly
// created instance, allow it.
// 2) If it's a prototype property, allow it. For example:
// Foo.prototype.bar = baz;
// where Foo.prototype is a struct and the assignment happens at the
// top level and the constructor Foo is defined in the same file.
boolean staticPropCreation = false;
Node maybeAssignStm = getprop.getGrandparent();
if (containerScope.isGlobal() && NodeUtil.isPrototypePropertyDeclaration(maybeAssignStm)) {
String propCreationFilename = maybeAssignStm.getSourceFileName();
Node ctor = objectType.getOwnerFunction().getSource();
if (ctor != null && ctor.getSourceFileName().equals(propCreationFilename)) {
staticPropCreation = true;
}
}
if (!propCreationInConstructor && !staticPropCreation) {
return; // Early return to avoid creating the property below.
}
}
if (ensurePropertyDeclaredHelper(getprop, objectType, scope)) {
return;
}
if (!objectType.isPropertyTypeDeclared(propName)) {
// We do not want a "stray" assign to define an inferred property
// for every object of this type in the program. So we use a heuristic
// approach to determine whether to infer the property.
//
// 1) If the property is already defined, join it with the previously
// inferred type.
// 2) If this isn't an instance object, define it.
// 3) If the property of an object is being assigned in the constructor,
// define it.
// 4) If this is a stub, define it.
// 5) Otherwise, do not define the type, but declare it in the registry
// so that we can use it for missing property checks.
if (objectType.hasProperty(propName) || !objectType.isInstanceType()) {
if ("prototype".equals(propName)) {
objectType.defineDeclaredProperty(propName, rightType, getprop);
} else {
objectType.defineInferredProperty(propName, rightType, getprop);
}
} else if (propCreationInConstructor) {
objectType.defineInferredProperty(propName, rightType, getprop);
} else {
registry.registerPropertyOnType(propName, objectType);
}
}
}
} | [
"private",
"void",
"ensurePropertyDefined",
"(",
"Node",
"getprop",
",",
"JSType",
"rightType",
",",
"FlowScope",
"scope",
")",
"{",
"String",
"propName",
"=",
"getprop",
".",
"getLastChild",
"(",
")",
".",
"getString",
"(",
")",
";",
"Node",
"obj",
"=",
"getprop",
".",
"getFirstChild",
"(",
")",
";",
"JSType",
"nodeType",
"=",
"getJSType",
"(",
"obj",
")",
";",
"ObjectType",
"objectType",
"=",
"ObjectType",
".",
"cast",
"(",
"nodeType",
".",
"restrictByNotNullOrUndefined",
"(",
")",
")",
";",
"boolean",
"propCreationInConstructor",
"=",
"obj",
".",
"isThis",
"(",
")",
"&&",
"getJSType",
"(",
"containerScope",
".",
"getRootNode",
"(",
")",
")",
".",
"isConstructor",
"(",
")",
";",
"if",
"(",
"objectType",
"==",
"null",
")",
"{",
"registry",
".",
"registerPropertyOnType",
"(",
"propName",
",",
"nodeType",
")",
";",
"}",
"else",
"{",
"if",
"(",
"nodeType",
".",
"isStruct",
"(",
")",
"&&",
"!",
"objectType",
".",
"hasProperty",
"(",
"propName",
")",
")",
"{",
"// In general, we don't want to define a property on a struct object,",
"// b/c TypeCheck will later check for improper property creation on",
"// structs. There are two exceptions.",
"// 1) If it's a property created inside the constructor, on the newly",
"// created instance, allow it.",
"// 2) If it's a prototype property, allow it. For example:",
"// Foo.prototype.bar = baz;",
"// where Foo.prototype is a struct and the assignment happens at the",
"// top level and the constructor Foo is defined in the same file.",
"boolean",
"staticPropCreation",
"=",
"false",
";",
"Node",
"maybeAssignStm",
"=",
"getprop",
".",
"getGrandparent",
"(",
")",
";",
"if",
"(",
"containerScope",
".",
"isGlobal",
"(",
")",
"&&",
"NodeUtil",
".",
"isPrototypePropertyDeclaration",
"(",
"maybeAssignStm",
")",
")",
"{",
"String",
"propCreationFilename",
"=",
"maybeAssignStm",
".",
"getSourceFileName",
"(",
")",
";",
"Node",
"ctor",
"=",
"objectType",
".",
"getOwnerFunction",
"(",
")",
".",
"getSource",
"(",
")",
";",
"if",
"(",
"ctor",
"!=",
"null",
"&&",
"ctor",
".",
"getSourceFileName",
"(",
")",
".",
"equals",
"(",
"propCreationFilename",
")",
")",
"{",
"staticPropCreation",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"propCreationInConstructor",
"&&",
"!",
"staticPropCreation",
")",
"{",
"return",
";",
"// Early return to avoid creating the property below.",
"}",
"}",
"if",
"(",
"ensurePropertyDeclaredHelper",
"(",
"getprop",
",",
"objectType",
",",
"scope",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"objectType",
".",
"isPropertyTypeDeclared",
"(",
"propName",
")",
")",
"{",
"// We do not want a \"stray\" assign to define an inferred property",
"// for every object of this type in the program. So we use a heuristic",
"// approach to determine whether to infer the property.",
"//",
"// 1) If the property is already defined, join it with the previously",
"// inferred type.",
"// 2) If this isn't an instance object, define it.",
"// 3) If the property of an object is being assigned in the constructor,",
"// define it.",
"// 4) If this is a stub, define it.",
"// 5) Otherwise, do not define the type, but declare it in the registry",
"// so that we can use it for missing property checks.",
"if",
"(",
"objectType",
".",
"hasProperty",
"(",
"propName",
")",
"||",
"!",
"objectType",
".",
"isInstanceType",
"(",
")",
")",
"{",
"if",
"(",
"\"prototype\"",
".",
"equals",
"(",
"propName",
")",
")",
"{",
"objectType",
".",
"defineDeclaredProperty",
"(",
"propName",
",",
"rightType",
",",
"getprop",
")",
";",
"}",
"else",
"{",
"objectType",
".",
"defineInferredProperty",
"(",
"propName",
",",
"rightType",
",",
"getprop",
")",
";",
"}",
"}",
"else",
"if",
"(",
"propCreationInConstructor",
")",
"{",
"objectType",
".",
"defineInferredProperty",
"(",
"propName",
",",
"rightType",
",",
"getprop",
")",
";",
"}",
"else",
"{",
"registry",
".",
"registerPropertyOnType",
"(",
"propName",
",",
"objectType",
")",
";",
"}",
"}",
"}",
"}"
] | Defines a property if the property has not been defined yet. | [
"Defines",
"a",
"property",
"if",
"the",
"property",
"has",
"not",
"been",
"defined",
"yet",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L1091-L1157 |
24,567 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.ensurePropertyDeclaredHelper | private boolean ensurePropertyDeclaredHelper(
Node getprop, ObjectType objectType, FlowScope scope) {
if (getprop.isQualifiedName()) {
String propName = getprop.getLastChild().getString();
String qName = getprop.getQualifiedName();
TypedVar var = getDeclaredVar(scope, qName);
if (var != null && !var.isTypeInferred()) {
// Handle normal declarations that could not be addressed earlier.
if (propName.equals("prototype")
||
// Handle prototype declarations that could not be addressed earlier.
(!objectType.hasOwnProperty(propName)
&& (!objectType.isInstanceType()
|| (var.isExtern() && !objectType.isNativeObjectType())))) {
return objectType.defineDeclaredProperty(
propName, var.getType(), getprop);
}
}
}
return false;
} | java | private boolean ensurePropertyDeclaredHelper(
Node getprop, ObjectType objectType, FlowScope scope) {
if (getprop.isQualifiedName()) {
String propName = getprop.getLastChild().getString();
String qName = getprop.getQualifiedName();
TypedVar var = getDeclaredVar(scope, qName);
if (var != null && !var.isTypeInferred()) {
// Handle normal declarations that could not be addressed earlier.
if (propName.equals("prototype")
||
// Handle prototype declarations that could not be addressed earlier.
(!objectType.hasOwnProperty(propName)
&& (!objectType.isInstanceType()
|| (var.isExtern() && !objectType.isNativeObjectType())))) {
return objectType.defineDeclaredProperty(
propName, var.getType(), getprop);
}
}
}
return false;
} | [
"private",
"boolean",
"ensurePropertyDeclaredHelper",
"(",
"Node",
"getprop",
",",
"ObjectType",
"objectType",
",",
"FlowScope",
"scope",
")",
"{",
"if",
"(",
"getprop",
".",
"isQualifiedName",
"(",
")",
")",
"{",
"String",
"propName",
"=",
"getprop",
".",
"getLastChild",
"(",
")",
".",
"getString",
"(",
")",
";",
"String",
"qName",
"=",
"getprop",
".",
"getQualifiedName",
"(",
")",
";",
"TypedVar",
"var",
"=",
"getDeclaredVar",
"(",
"scope",
",",
"qName",
")",
";",
"if",
"(",
"var",
"!=",
"null",
"&&",
"!",
"var",
".",
"isTypeInferred",
"(",
")",
")",
"{",
"// Handle normal declarations that could not be addressed earlier.",
"if",
"(",
"propName",
".",
"equals",
"(",
"\"prototype\"",
")",
"||",
"// Handle prototype declarations that could not be addressed earlier.",
"(",
"!",
"objectType",
".",
"hasOwnProperty",
"(",
"propName",
")",
"&&",
"(",
"!",
"objectType",
".",
"isInstanceType",
"(",
")",
"||",
"(",
"var",
".",
"isExtern",
"(",
")",
"&&",
"!",
"objectType",
".",
"isNativeObjectType",
"(",
")",
")",
")",
")",
")",
"{",
"return",
"objectType",
".",
"defineDeclaredProperty",
"(",
"propName",
",",
"var",
".",
"getType",
"(",
")",
",",
"getprop",
")",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] | Declares a property on its owner, if necessary.
@return True if a property was declared. | [
"Declares",
"a",
"property",
"on",
"its",
"owner",
"if",
"necessary",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L1164-L1184 |
24,568 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.traverseDestructuringPattern | private FlowScope traverseDestructuringPattern(
Node pattern, FlowScope scope, JSType patternType, AssignmentType assignmentType) {
return traverseDestructuringPatternHelper(
pattern,
scope,
patternType,
(FlowScope flowScope, Node targetNode, JSType targetType) -> {
targetType = targetType != null ? targetType : getNativeType(UNKNOWN_TYPE);
return updateScopeForAssignment(flowScope, targetNode, targetType, assignmentType);
});
} | java | private FlowScope traverseDestructuringPattern(
Node pattern, FlowScope scope, JSType patternType, AssignmentType assignmentType) {
return traverseDestructuringPatternHelper(
pattern,
scope,
patternType,
(FlowScope flowScope, Node targetNode, JSType targetType) -> {
targetType = targetType != null ? targetType : getNativeType(UNKNOWN_TYPE);
return updateScopeForAssignment(flowScope, targetNode, targetType, assignmentType);
});
} | [
"private",
"FlowScope",
"traverseDestructuringPattern",
"(",
"Node",
"pattern",
",",
"FlowScope",
"scope",
",",
"JSType",
"patternType",
",",
"AssignmentType",
"assignmentType",
")",
"{",
"return",
"traverseDestructuringPatternHelper",
"(",
"pattern",
",",
"scope",
",",
"patternType",
",",
"(",
"FlowScope",
"flowScope",
",",
"Node",
"targetNode",
",",
"JSType",
"targetType",
")",
"->",
"{",
"targetType",
"=",
"targetType",
"!=",
"null",
"?",
"targetType",
":",
"getNativeType",
"(",
"UNKNOWN_TYPE",
")",
";",
"return",
"updateScopeForAssignment",
"(",
"flowScope",
",",
"targetNode",
",",
"targetType",
",",
"assignmentType",
")",
";",
"}",
")",
";",
"}"
] | Traverses a destructuring pattern in an assignment or declaration | [
"Traverses",
"a",
"destructuring",
"pattern",
"in",
"an",
"assignment",
"or",
"declaration"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L1206-L1216 |
24,569 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.traverseArrayLiteral | private FlowScope traverseArrayLiteral(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(ARRAY_TYPE));
return scope;
} | java | private FlowScope traverseArrayLiteral(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(ARRAY_TYPE));
return scope;
} | [
"private",
"FlowScope",
"traverseArrayLiteral",
"(",
"Node",
"n",
",",
"FlowScope",
"scope",
")",
"{",
"scope",
"=",
"traverseChildren",
"(",
"n",
",",
"scope",
")",
";",
"n",
".",
"setJSType",
"(",
"getNativeType",
"(",
"ARRAY_TYPE",
")",
")",
";",
"return",
"scope",
";",
"}"
] | Traverse each element of the array. | [
"Traverse",
"each",
"element",
"of",
"the",
"array",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L1343-L1347 |
24,570 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.backwardsInferenceFromCallSite | private void backwardsInferenceFromCallSite(Node n, FunctionType fnType, FlowScope scope) {
boolean updatedFnType = inferTemplatedTypesForCall(n, fnType, scope);
if (updatedFnType) {
fnType = n.getFirstChild().getJSType().toMaybeFunctionType();
}
updateTypeOfArguments(n, fnType);
updateBind(n);
} | java | private void backwardsInferenceFromCallSite(Node n, FunctionType fnType, FlowScope scope) {
boolean updatedFnType = inferTemplatedTypesForCall(n, fnType, scope);
if (updatedFnType) {
fnType = n.getFirstChild().getJSType().toMaybeFunctionType();
}
updateTypeOfArguments(n, fnType);
updateBind(n);
} | [
"private",
"void",
"backwardsInferenceFromCallSite",
"(",
"Node",
"n",
",",
"FunctionType",
"fnType",
",",
"FlowScope",
"scope",
")",
"{",
"boolean",
"updatedFnType",
"=",
"inferTemplatedTypesForCall",
"(",
"n",
",",
"fnType",
",",
"scope",
")",
";",
"if",
"(",
"updatedFnType",
")",
"{",
"fnType",
"=",
"n",
".",
"getFirstChild",
"(",
")",
".",
"getJSType",
"(",
")",
".",
"toMaybeFunctionType",
"(",
")",
";",
"}",
"updateTypeOfArguments",
"(",
"n",
",",
"fnType",
")",
";",
"updateBind",
"(",
"n",
")",
";",
"}"
] | We only do forward type inference. We do not do full backwards type inference.
In other words, if we have,
<code>
var x = f();
g(x);
</code>
a forward type-inference engine would try to figure out the type
of "x" from the return type of "f". A backwards type-inference engine
would try to figure out the type of "x" from the parameter type of "g".
<p>However, there are a few special syntactic forms where we do some some half-assed backwards
type-inference, because programmers expect it in this day and age. To take an example from
Java,
<code>
List<String> x = Lists.newArrayList();
</code>
The Java compiler will be able to infer the generic type of the List returned by
newArrayList().
<p>In much the same way, we do some special-case backwards inference for JS. Those cases are
enumerated here. | [
"We",
"only",
"do",
"forward",
"type",
"inference",
".",
"We",
"do",
"not",
"do",
"full",
"backwards",
"type",
"inference",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L1617-L1624 |
24,571 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.updateBind | private void updateBind(Node n) {
CodingConvention.Bind bind =
compiler.getCodingConvention().describeFunctionBind(n, false, true);
if (bind == null) {
return;
}
Node target = bind.target;
FunctionType callTargetFn = getJSType(target)
.restrictByNotNullOrUndefined().toMaybeFunctionType();
if (callTargetFn == null) {
return;
}
if (bind.thisValue != null && target.isFunction()) {
JSType thisType = getJSType(bind.thisValue);
if (thisType.toObjectType() != null && !thisType.isUnknownType()
&& callTargetFn.getTypeOfThis().isUnknownType()) {
callTargetFn =
FunctionType.builder(registry)
.copyFromOtherFunction(callTargetFn)
.withTypeOfThis(thisType.toObjectType())
.build();
target.setJSType(callTargetFn);
}
}
n.setJSType(
callTargetFn.getBindReturnType(
// getBindReturnType expects the 'this' argument to be included.
bind.getBoundParameterCount() + 1));
} | java | private void updateBind(Node n) {
CodingConvention.Bind bind =
compiler.getCodingConvention().describeFunctionBind(n, false, true);
if (bind == null) {
return;
}
Node target = bind.target;
FunctionType callTargetFn = getJSType(target)
.restrictByNotNullOrUndefined().toMaybeFunctionType();
if (callTargetFn == null) {
return;
}
if (bind.thisValue != null && target.isFunction()) {
JSType thisType = getJSType(bind.thisValue);
if (thisType.toObjectType() != null && !thisType.isUnknownType()
&& callTargetFn.getTypeOfThis().isUnknownType()) {
callTargetFn =
FunctionType.builder(registry)
.copyFromOtherFunction(callTargetFn)
.withTypeOfThis(thisType.toObjectType())
.build();
target.setJSType(callTargetFn);
}
}
n.setJSType(
callTargetFn.getBindReturnType(
// getBindReturnType expects the 'this' argument to be included.
bind.getBoundParameterCount() + 1));
} | [
"private",
"void",
"updateBind",
"(",
"Node",
"n",
")",
"{",
"CodingConvention",
".",
"Bind",
"bind",
"=",
"compiler",
".",
"getCodingConvention",
"(",
")",
".",
"describeFunctionBind",
"(",
"n",
",",
"false",
",",
"true",
")",
";",
"if",
"(",
"bind",
"==",
"null",
")",
"{",
"return",
";",
"}",
"Node",
"target",
"=",
"bind",
".",
"target",
";",
"FunctionType",
"callTargetFn",
"=",
"getJSType",
"(",
"target",
")",
".",
"restrictByNotNullOrUndefined",
"(",
")",
".",
"toMaybeFunctionType",
"(",
")",
";",
"if",
"(",
"callTargetFn",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"bind",
".",
"thisValue",
"!=",
"null",
"&&",
"target",
".",
"isFunction",
"(",
")",
")",
"{",
"JSType",
"thisType",
"=",
"getJSType",
"(",
"bind",
".",
"thisValue",
")",
";",
"if",
"(",
"thisType",
".",
"toObjectType",
"(",
")",
"!=",
"null",
"&&",
"!",
"thisType",
".",
"isUnknownType",
"(",
")",
"&&",
"callTargetFn",
".",
"getTypeOfThis",
"(",
")",
".",
"isUnknownType",
"(",
")",
")",
"{",
"callTargetFn",
"=",
"FunctionType",
".",
"builder",
"(",
"registry",
")",
".",
"copyFromOtherFunction",
"(",
"callTargetFn",
")",
".",
"withTypeOfThis",
"(",
"thisType",
".",
"toObjectType",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"target",
".",
"setJSType",
"(",
"callTargetFn",
")",
";",
"}",
"}",
"n",
".",
"setJSType",
"(",
"callTargetFn",
".",
"getBindReturnType",
"(",
"// getBindReturnType expects the 'this' argument to be included.",
"bind",
".",
"getBoundParameterCount",
"(",
")",
"+",
"1",
")",
")",
";",
"}"
] | When "bind" is called on a function, we infer the type of the returned
"bound" function by looking at the number of parameters in the call site.
We also infer the "this" type of the target, if it's a function expression. | [
"When",
"bind",
"is",
"called",
"on",
"a",
"function",
"we",
"infer",
"the",
"type",
"of",
"the",
"returned",
"bound",
"function",
"by",
"looking",
"at",
"the",
"number",
"of",
"parameters",
"in",
"the",
"call",
"site",
".",
"We",
"also",
"infer",
"the",
"this",
"type",
"of",
"the",
"target",
"if",
"it",
"s",
"a",
"function",
"expression",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L1631-L1662 |
24,572 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.updateTypeOfArguments | private void updateTypeOfArguments(Node n, FunctionType fnType) {
checkState(NodeUtil.isInvocation(n), n);
Iterator<Node> parameters = fnType.getParameters().iterator();
if (n.isTaggedTemplateLit()) {
// Skip the first parameter because it corresponds to a constructed array of the template lit
// subs, not an actual AST node, so there's nothing to update.
if (!parameters.hasNext()) {
// TypeCheck will warn if there is no first parameter. Just bail out here.
return;
}
parameters.next();
}
Iterator<Node> arguments = NodeUtil.getInvocationArgsAsIterable(n).iterator();
Node iParameter;
Node iArgument;
// Note: if there are too many or too few arguments, TypeCheck will warn.
while (parameters.hasNext() && arguments.hasNext()) {
iArgument = arguments.next();
JSType iArgumentType = getJSType(iArgument);
iParameter = parameters.next();
JSType iParameterType = getJSType(iParameter);
inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType);
// If the parameter to the call is a function expression, propagate the
// function signature from the call site to the function node.
// Filter out non-function types (such as null and undefined) as
// we only care about FUNCTION subtypes here.
FunctionType restrictedParameter = null;
if (iParameterType.isUnionType()) {
UnionType union = iParameterType.toMaybeUnionType();
for (JSType alternative : union.getAlternates()) {
if (alternative.isFunctionType()) {
// There is only one function type per union.
restrictedParameter = alternative.toMaybeFunctionType();
break;
}
}
} else {
restrictedParameter = iParameterType.toMaybeFunctionType();
}
if (restrictedParameter != null
&& iArgument.isFunction()
&& iArgumentType.isFunctionType()) {
FunctionType argFnType = iArgumentType.toMaybeFunctionType();
JSDocInfo argJsdoc = iArgument.getJSDocInfo();
// Treat the parameter & return types of the function as 'declared' if the function has
// JSDoc with type annotations, or a parameter has inline JSDoc.
// Note that this does not distinguish between cases where all parameters have JSDoc vs
// only one parameter has JSDoc.
boolean declared =
(argJsdoc != null && argJsdoc.containsDeclaration())
|| NodeUtil.functionHasInlineJsdocs(iArgument);
iArgument.setJSType(matchFunction(restrictedParameter, argFnType, declared));
}
}
} | java | private void updateTypeOfArguments(Node n, FunctionType fnType) {
checkState(NodeUtil.isInvocation(n), n);
Iterator<Node> parameters = fnType.getParameters().iterator();
if (n.isTaggedTemplateLit()) {
// Skip the first parameter because it corresponds to a constructed array of the template lit
// subs, not an actual AST node, so there's nothing to update.
if (!parameters.hasNext()) {
// TypeCheck will warn if there is no first parameter. Just bail out here.
return;
}
parameters.next();
}
Iterator<Node> arguments = NodeUtil.getInvocationArgsAsIterable(n).iterator();
Node iParameter;
Node iArgument;
// Note: if there are too many or too few arguments, TypeCheck will warn.
while (parameters.hasNext() && arguments.hasNext()) {
iArgument = arguments.next();
JSType iArgumentType = getJSType(iArgument);
iParameter = parameters.next();
JSType iParameterType = getJSType(iParameter);
inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType);
// If the parameter to the call is a function expression, propagate the
// function signature from the call site to the function node.
// Filter out non-function types (such as null and undefined) as
// we only care about FUNCTION subtypes here.
FunctionType restrictedParameter = null;
if (iParameterType.isUnionType()) {
UnionType union = iParameterType.toMaybeUnionType();
for (JSType alternative : union.getAlternates()) {
if (alternative.isFunctionType()) {
// There is only one function type per union.
restrictedParameter = alternative.toMaybeFunctionType();
break;
}
}
} else {
restrictedParameter = iParameterType.toMaybeFunctionType();
}
if (restrictedParameter != null
&& iArgument.isFunction()
&& iArgumentType.isFunctionType()) {
FunctionType argFnType = iArgumentType.toMaybeFunctionType();
JSDocInfo argJsdoc = iArgument.getJSDocInfo();
// Treat the parameter & return types of the function as 'declared' if the function has
// JSDoc with type annotations, or a parameter has inline JSDoc.
// Note that this does not distinguish between cases where all parameters have JSDoc vs
// only one parameter has JSDoc.
boolean declared =
(argJsdoc != null && argJsdoc.containsDeclaration())
|| NodeUtil.functionHasInlineJsdocs(iArgument);
iArgument.setJSType(matchFunction(restrictedParameter, argFnType, declared));
}
}
} | [
"private",
"void",
"updateTypeOfArguments",
"(",
"Node",
"n",
",",
"FunctionType",
"fnType",
")",
"{",
"checkState",
"(",
"NodeUtil",
".",
"isInvocation",
"(",
"n",
")",
",",
"n",
")",
";",
"Iterator",
"<",
"Node",
">",
"parameters",
"=",
"fnType",
".",
"getParameters",
"(",
")",
".",
"iterator",
"(",
")",
";",
"if",
"(",
"n",
".",
"isTaggedTemplateLit",
"(",
")",
")",
"{",
"// Skip the first parameter because it corresponds to a constructed array of the template lit",
"// subs, not an actual AST node, so there's nothing to update.",
"if",
"(",
"!",
"parameters",
".",
"hasNext",
"(",
")",
")",
"{",
"// TypeCheck will warn if there is no first parameter. Just bail out here.",
"return",
";",
"}",
"parameters",
".",
"next",
"(",
")",
";",
"}",
"Iterator",
"<",
"Node",
">",
"arguments",
"=",
"NodeUtil",
".",
"getInvocationArgsAsIterable",
"(",
"n",
")",
".",
"iterator",
"(",
")",
";",
"Node",
"iParameter",
";",
"Node",
"iArgument",
";",
"// Note: if there are too many or too few arguments, TypeCheck will warn.",
"while",
"(",
"parameters",
".",
"hasNext",
"(",
")",
"&&",
"arguments",
".",
"hasNext",
"(",
")",
")",
"{",
"iArgument",
"=",
"arguments",
".",
"next",
"(",
")",
";",
"JSType",
"iArgumentType",
"=",
"getJSType",
"(",
"iArgument",
")",
";",
"iParameter",
"=",
"parameters",
".",
"next",
"(",
")",
";",
"JSType",
"iParameterType",
"=",
"getJSType",
"(",
"iParameter",
")",
";",
"inferPropertyTypesToMatchConstraint",
"(",
"iArgumentType",
",",
"iParameterType",
")",
";",
"// If the parameter to the call is a function expression, propagate the",
"// function signature from the call site to the function node.",
"// Filter out non-function types (such as null and undefined) as",
"// we only care about FUNCTION subtypes here.",
"FunctionType",
"restrictedParameter",
"=",
"null",
";",
"if",
"(",
"iParameterType",
".",
"isUnionType",
"(",
")",
")",
"{",
"UnionType",
"union",
"=",
"iParameterType",
".",
"toMaybeUnionType",
"(",
")",
";",
"for",
"(",
"JSType",
"alternative",
":",
"union",
".",
"getAlternates",
"(",
")",
")",
"{",
"if",
"(",
"alternative",
".",
"isFunctionType",
"(",
")",
")",
"{",
"// There is only one function type per union.",
"restrictedParameter",
"=",
"alternative",
".",
"toMaybeFunctionType",
"(",
")",
";",
"break",
";",
"}",
"}",
"}",
"else",
"{",
"restrictedParameter",
"=",
"iParameterType",
".",
"toMaybeFunctionType",
"(",
")",
";",
"}",
"if",
"(",
"restrictedParameter",
"!=",
"null",
"&&",
"iArgument",
".",
"isFunction",
"(",
")",
"&&",
"iArgumentType",
".",
"isFunctionType",
"(",
")",
")",
"{",
"FunctionType",
"argFnType",
"=",
"iArgumentType",
".",
"toMaybeFunctionType",
"(",
")",
";",
"JSDocInfo",
"argJsdoc",
"=",
"iArgument",
".",
"getJSDocInfo",
"(",
")",
";",
"// Treat the parameter & return types of the function as 'declared' if the function has",
"// JSDoc with type annotations, or a parameter has inline JSDoc.",
"// Note that this does not distinguish between cases where all parameters have JSDoc vs",
"// only one parameter has JSDoc.",
"boolean",
"declared",
"=",
"(",
"argJsdoc",
"!=",
"null",
"&&",
"argJsdoc",
".",
"containsDeclaration",
"(",
")",
")",
"||",
"NodeUtil",
".",
"functionHasInlineJsdocs",
"(",
"iArgument",
")",
";",
"iArgument",
".",
"setJSType",
"(",
"matchFunction",
"(",
"restrictedParameter",
",",
"argFnType",
",",
"declared",
")",
")",
";",
"}",
"}",
"}"
] | Performs a limited back-inference on function arguments based on the expected parameter types.
<p>Currently this only does back-inference in two cases: it infers the type of function literal
arguments and adds inferred properties to inferred object-typed arguments.
<p>For example: if someone calls `Promise<string>.prototype.then` with `(result) => ...` then
we infer that the type of the arrow function is `function(string): ?`, and inside the arrow
function body we know that `result` is a string. | [
"Performs",
"a",
"limited",
"back",
"-",
"inference",
"on",
"function",
"arguments",
"based",
"on",
"the",
"expected",
"parameter",
"types",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L1674-L1735 |
24,573 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.matchFunction | private FunctionType matchFunction(
FunctionType expectedType, FunctionType currentType, boolean declared) {
if (declared) {
// If the function was declared but it doesn't have a known "this"
// but the expected type does, back fill it.
if (currentType.getTypeOfThis().isUnknownType()
&& !expectedType.getTypeOfThis().isUnknownType()) {
FunctionType replacement =
FunctionType.builder(registry)
.copyFromOtherFunction(currentType)
.withTypeOfThis(expectedType.getTypeOfThis())
.build();
return replacement;
}
} else {
// For now, we just make sure the current type has enough
// arguments to match the expected type, and return the
// expected type if it does.
if (currentType.getMaxArity() <= expectedType.getMaxArity()) {
return expectedType;
}
}
return currentType;
} | java | private FunctionType matchFunction(
FunctionType expectedType, FunctionType currentType, boolean declared) {
if (declared) {
// If the function was declared but it doesn't have a known "this"
// but the expected type does, back fill it.
if (currentType.getTypeOfThis().isUnknownType()
&& !expectedType.getTypeOfThis().isUnknownType()) {
FunctionType replacement =
FunctionType.builder(registry)
.copyFromOtherFunction(currentType)
.withTypeOfThis(expectedType.getTypeOfThis())
.build();
return replacement;
}
} else {
// For now, we just make sure the current type has enough
// arguments to match the expected type, and return the
// expected type if it does.
if (currentType.getMaxArity() <= expectedType.getMaxArity()) {
return expectedType;
}
}
return currentType;
} | [
"private",
"FunctionType",
"matchFunction",
"(",
"FunctionType",
"expectedType",
",",
"FunctionType",
"currentType",
",",
"boolean",
"declared",
")",
"{",
"if",
"(",
"declared",
")",
"{",
"// If the function was declared but it doesn't have a known \"this\"",
"// but the expected type does, back fill it.",
"if",
"(",
"currentType",
".",
"getTypeOfThis",
"(",
")",
".",
"isUnknownType",
"(",
")",
"&&",
"!",
"expectedType",
".",
"getTypeOfThis",
"(",
")",
".",
"isUnknownType",
"(",
")",
")",
"{",
"FunctionType",
"replacement",
"=",
"FunctionType",
".",
"builder",
"(",
"registry",
")",
".",
"copyFromOtherFunction",
"(",
"currentType",
")",
".",
"withTypeOfThis",
"(",
"expectedType",
".",
"getTypeOfThis",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"return",
"replacement",
";",
"}",
"}",
"else",
"{",
"// For now, we just make sure the current type has enough",
"// arguments to match the expected type, and return the",
"// expected type if it does.",
"if",
"(",
"currentType",
".",
"getMaxArity",
"(",
")",
"<=",
"expectedType",
".",
"getMaxArity",
"(",
")",
")",
"{",
"return",
"expectedType",
";",
"}",
"}",
"return",
"currentType",
";",
"}"
] | Take the current function type, and try to match the expected function type. This is a form of
backwards-inference, like record-type constraint matching.
@param declared Whether the given function type is user-provided as opposed to inferred | [
"Take",
"the",
"current",
"function",
"type",
"and",
"try",
"to",
"match",
"the",
"expected",
"function",
"type",
".",
"This",
"is",
"a",
"form",
"of",
"backwards",
"-",
"inference",
"like",
"record",
"-",
"type",
"constraint",
"matching",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L1743-L1766 |
24,574 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.buildTypeVariables | private Map<String, JSType> buildTypeVariables(
Map<TemplateType, JSType> inferredTypes) {
Map<String, JSType> typeVars = new LinkedHashMap<>();
for (Entry<TemplateType, JSType> e : inferredTypes.entrySet()) {
// Only add the template type that do not have a type transformation
if (!e.getKey().isTypeTransformation()) {
typeVars.put(e.getKey().getReferenceName(), e.getValue());
}
}
return typeVars;
} | java | private Map<String, JSType> buildTypeVariables(
Map<TemplateType, JSType> inferredTypes) {
Map<String, JSType> typeVars = new LinkedHashMap<>();
for (Entry<TemplateType, JSType> e : inferredTypes.entrySet()) {
// Only add the template type that do not have a type transformation
if (!e.getKey().isTypeTransformation()) {
typeVars.put(e.getKey().getReferenceName(), e.getValue());
}
}
return typeVars;
} | [
"private",
"Map",
"<",
"String",
",",
"JSType",
">",
"buildTypeVariables",
"(",
"Map",
"<",
"TemplateType",
",",
"JSType",
">",
"inferredTypes",
")",
"{",
"Map",
"<",
"String",
",",
"JSType",
">",
"typeVars",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"for",
"(",
"Entry",
"<",
"TemplateType",
",",
"JSType",
">",
"e",
":",
"inferredTypes",
".",
"entrySet",
"(",
")",
")",
"{",
"// Only add the template type that do not have a type transformation",
"if",
"(",
"!",
"e",
".",
"getKey",
"(",
")",
".",
"isTypeTransformation",
"(",
")",
")",
"{",
"typeVars",
".",
"put",
"(",
"e",
".",
"getKey",
"(",
")",
".",
"getReferenceName",
"(",
")",
",",
"e",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"return",
"typeVars",
";",
"}"
] | Build the type environment where type transformations will be evaluated.
It only considers the template type variables that do not have a type
transformation. | [
"Build",
"the",
"type",
"environment",
"where",
"type",
"transformations",
"will",
"be",
"evaluated",
".",
"It",
"only",
"considers",
"the",
"template",
"type",
"variables",
"that",
"do",
"not",
"have",
"a",
"type",
"transformation",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L1992-L2002 |
24,575 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.evaluateTypeTransformations | private Map<TemplateType, JSType> evaluateTypeTransformations(
ImmutableList<TemplateType> templateTypes,
Map<TemplateType, JSType> inferredTypes,
FlowScope scope) {
Map<String, JSType> typeVars = null;
Map<TemplateType, JSType> result = null;
TypeTransformation ttlObj = null;
for (TemplateType type : templateTypes) {
if (type.isTypeTransformation()) {
// Lazy initialization when the first type transformation is found
if (ttlObj == null) {
ttlObj = new TypeTransformation(compiler, scope.getDeclarationScope());
typeVars = buildTypeVariables(inferredTypes);
result = new LinkedHashMap<>();
}
// Evaluate the type transformation expression using the current
// known types for the template type variables
JSType transformedType = ttlObj.eval(
type.getTypeTransformation(),
ImmutableMap.copyOf(typeVars));
result.put(type, transformedType);
// Add the transformed type to the type variables
typeVars.put(type.getReferenceName(), transformedType);
}
}
return result;
} | java | private Map<TemplateType, JSType> evaluateTypeTransformations(
ImmutableList<TemplateType> templateTypes,
Map<TemplateType, JSType> inferredTypes,
FlowScope scope) {
Map<String, JSType> typeVars = null;
Map<TemplateType, JSType> result = null;
TypeTransformation ttlObj = null;
for (TemplateType type : templateTypes) {
if (type.isTypeTransformation()) {
// Lazy initialization when the first type transformation is found
if (ttlObj == null) {
ttlObj = new TypeTransformation(compiler, scope.getDeclarationScope());
typeVars = buildTypeVariables(inferredTypes);
result = new LinkedHashMap<>();
}
// Evaluate the type transformation expression using the current
// known types for the template type variables
JSType transformedType = ttlObj.eval(
type.getTypeTransformation(),
ImmutableMap.copyOf(typeVars));
result.put(type, transformedType);
// Add the transformed type to the type variables
typeVars.put(type.getReferenceName(), transformedType);
}
}
return result;
} | [
"private",
"Map",
"<",
"TemplateType",
",",
"JSType",
">",
"evaluateTypeTransformations",
"(",
"ImmutableList",
"<",
"TemplateType",
">",
"templateTypes",
",",
"Map",
"<",
"TemplateType",
",",
"JSType",
">",
"inferredTypes",
",",
"FlowScope",
"scope",
")",
"{",
"Map",
"<",
"String",
",",
"JSType",
">",
"typeVars",
"=",
"null",
";",
"Map",
"<",
"TemplateType",
",",
"JSType",
">",
"result",
"=",
"null",
";",
"TypeTransformation",
"ttlObj",
"=",
"null",
";",
"for",
"(",
"TemplateType",
"type",
":",
"templateTypes",
")",
"{",
"if",
"(",
"type",
".",
"isTypeTransformation",
"(",
")",
")",
"{",
"// Lazy initialization when the first type transformation is found",
"if",
"(",
"ttlObj",
"==",
"null",
")",
"{",
"ttlObj",
"=",
"new",
"TypeTransformation",
"(",
"compiler",
",",
"scope",
".",
"getDeclarationScope",
"(",
")",
")",
";",
"typeVars",
"=",
"buildTypeVariables",
"(",
"inferredTypes",
")",
";",
"result",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"}",
"// Evaluate the type transformation expression using the current",
"// known types for the template type variables",
"JSType",
"transformedType",
"=",
"ttlObj",
".",
"eval",
"(",
"type",
".",
"getTypeTransformation",
"(",
")",
",",
"ImmutableMap",
".",
"copyOf",
"(",
"typeVars",
")",
")",
";",
"result",
".",
"put",
"(",
"type",
",",
"transformedType",
")",
";",
"// Add the transformed type to the type variables",
"typeVars",
".",
"put",
"(",
"type",
".",
"getReferenceName",
"(",
")",
",",
"transformedType",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | This function will evaluate the type transformations associated to the template types | [
"This",
"function",
"will",
"evaluate",
"the",
"type",
"transformations",
"associated",
"to",
"the",
"template",
"types"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L2005-L2033 |
24,576 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.inferTemplatedTypesForCall | private boolean inferTemplatedTypesForCall(Node n, FunctionType fnType, FlowScope scope) {
ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap().getTemplateKeys();
if (keys.isEmpty()) {
return false;
}
// Try to infer the template types
Map<TemplateType, JSType> rawInferrence = inferTemplateTypesFromParameters(fnType, n, scope);
Map<TemplateType, JSType> inferred = Maps.newIdentityHashMap();
for (TemplateType key : keys) {
JSType type = rawInferrence.get(key);
if (type == null) {
type = unknownType;
}
inferred.put(key, type);
}
// Try to infer the template types using the type transformations
Map<TemplateType, JSType> typeTransformations =
evaluateTypeTransformations(keys, inferred, scope);
if (typeTransformations != null) {
inferred.putAll(typeTransformations);
}
// Replace all template types. If we couldn't find a replacement, we
// replace it with UNKNOWN.
TemplateTypeReplacer replacer = new TemplateTypeReplacer(registry, inferred);
Node callTarget = n.getFirstChild();
FunctionType replacementFnType = fnType.visit(replacer).toMaybeFunctionType();
checkNotNull(replacementFnType);
callTarget.setJSType(replacementFnType);
n.setJSType(replacementFnType.getReturnType());
return replacer.madeChanges;
} | java | private boolean inferTemplatedTypesForCall(Node n, FunctionType fnType, FlowScope scope) {
ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap().getTemplateKeys();
if (keys.isEmpty()) {
return false;
}
// Try to infer the template types
Map<TemplateType, JSType> rawInferrence = inferTemplateTypesFromParameters(fnType, n, scope);
Map<TemplateType, JSType> inferred = Maps.newIdentityHashMap();
for (TemplateType key : keys) {
JSType type = rawInferrence.get(key);
if (type == null) {
type = unknownType;
}
inferred.put(key, type);
}
// Try to infer the template types using the type transformations
Map<TemplateType, JSType> typeTransformations =
evaluateTypeTransformations(keys, inferred, scope);
if (typeTransformations != null) {
inferred.putAll(typeTransformations);
}
// Replace all template types. If we couldn't find a replacement, we
// replace it with UNKNOWN.
TemplateTypeReplacer replacer = new TemplateTypeReplacer(registry, inferred);
Node callTarget = n.getFirstChild();
FunctionType replacementFnType = fnType.visit(replacer).toMaybeFunctionType();
checkNotNull(replacementFnType);
callTarget.setJSType(replacementFnType);
n.setJSType(replacementFnType.getReturnType());
return replacer.madeChanges;
} | [
"private",
"boolean",
"inferTemplatedTypesForCall",
"(",
"Node",
"n",
",",
"FunctionType",
"fnType",
",",
"FlowScope",
"scope",
")",
"{",
"ImmutableList",
"<",
"TemplateType",
">",
"keys",
"=",
"fnType",
".",
"getTemplateTypeMap",
"(",
")",
".",
"getTemplateKeys",
"(",
")",
";",
"if",
"(",
"keys",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Try to infer the template types",
"Map",
"<",
"TemplateType",
",",
"JSType",
">",
"rawInferrence",
"=",
"inferTemplateTypesFromParameters",
"(",
"fnType",
",",
"n",
",",
"scope",
")",
";",
"Map",
"<",
"TemplateType",
",",
"JSType",
">",
"inferred",
"=",
"Maps",
".",
"newIdentityHashMap",
"(",
")",
";",
"for",
"(",
"TemplateType",
"key",
":",
"keys",
")",
"{",
"JSType",
"type",
"=",
"rawInferrence",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"type",
"==",
"null",
")",
"{",
"type",
"=",
"unknownType",
";",
"}",
"inferred",
".",
"put",
"(",
"key",
",",
"type",
")",
";",
"}",
"// Try to infer the template types using the type transformations",
"Map",
"<",
"TemplateType",
",",
"JSType",
">",
"typeTransformations",
"=",
"evaluateTypeTransformations",
"(",
"keys",
",",
"inferred",
",",
"scope",
")",
";",
"if",
"(",
"typeTransformations",
"!=",
"null",
")",
"{",
"inferred",
".",
"putAll",
"(",
"typeTransformations",
")",
";",
"}",
"// Replace all template types. If we couldn't find a replacement, we",
"// replace it with UNKNOWN.",
"TemplateTypeReplacer",
"replacer",
"=",
"new",
"TemplateTypeReplacer",
"(",
"registry",
",",
"inferred",
")",
";",
"Node",
"callTarget",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"FunctionType",
"replacementFnType",
"=",
"fnType",
".",
"visit",
"(",
"replacer",
")",
".",
"toMaybeFunctionType",
"(",
")",
";",
"checkNotNull",
"(",
"replacementFnType",
")",
";",
"callTarget",
".",
"setJSType",
"(",
"replacementFnType",
")",
";",
"n",
".",
"setJSType",
"(",
"replacementFnType",
".",
"getReturnType",
"(",
")",
")",
";",
"return",
"replacer",
".",
"madeChanges",
";",
"}"
] | For functions that use template types, specialize the function type for the call target based
on the call-site specific arguments. Specifically, this enables inference to set the type of
any function literal parameters based on these inferred types. | [
"For",
"functions",
"that",
"use",
"template",
"types",
"specialize",
"the",
"function",
"type",
"for",
"the",
"call",
"target",
"based",
"on",
"the",
"call",
"-",
"site",
"specific",
"arguments",
".",
"Specifically",
"this",
"enables",
"inference",
"to",
"set",
"the",
"type",
"of",
"any",
"function",
"literal",
"parameters",
"based",
"on",
"these",
"inferred",
"types",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L2040-L2075 |
24,577 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.inferPropertyTypesToMatchConstraint | private static void inferPropertyTypesToMatchConstraint(
JSType type, JSType constraint) {
if (type == null || constraint == null) {
return;
}
type.matchConstraint(constraint);
} | java | private static void inferPropertyTypesToMatchConstraint(
JSType type, JSType constraint) {
if (type == null || constraint == null) {
return;
}
type.matchConstraint(constraint);
} | [
"private",
"static",
"void",
"inferPropertyTypesToMatchConstraint",
"(",
"JSType",
"type",
",",
"JSType",
"constraint",
")",
"{",
"if",
"(",
"type",
"==",
"null",
"||",
"constraint",
"==",
"null",
")",
"{",
"return",
";",
"}",
"type",
".",
"matchConstraint",
"(",
"constraint",
")",
";",
"}"
] | Suppose X is an object with inferred properties.
Suppose also that X is used in a way where it would only type-check
correctly if some of those properties are widened.
Then we should be polite and automatically widen X's properties.
For a concrete example, consider:
param x {{prop: (number|undefined)}}
function f(x) {}
f({});
If we give the anonymous object an inferred property of (number|undefined),
then this code will type-check appropriately. | [
"Suppose",
"X",
"is",
"an",
"object",
"with",
"inferred",
"properties",
".",
"Suppose",
"also",
"that",
"X",
"is",
"used",
"in",
"a",
"way",
"where",
"it",
"would",
"only",
"type",
"-",
"check",
"correctly",
"if",
"some",
"of",
"those",
"properties",
"are",
"widened",
".",
"Then",
"we",
"should",
"be",
"polite",
"and",
"automatically",
"widen",
"X",
"s",
"properties",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L2173-L2180 |
24,578 | google/closure-compiler | src/com/google/javascript/jscomp/TypeInference.java | TypeInference.tightenTypeAfterDereference | private FlowScope tightenTypeAfterDereference(Node n, FlowScope scope) {
if (n.isQualifiedName()) {
JSType type = getJSType(n);
JSType narrowed = type.restrictByNotNullOrUndefined();
if (!type.equals(narrowed)) {
scope = narrowScope(scope, n, narrowed);
}
}
return scope;
} | java | private FlowScope tightenTypeAfterDereference(Node n, FlowScope scope) {
if (n.isQualifiedName()) {
JSType type = getJSType(n);
JSType narrowed = type.restrictByNotNullOrUndefined();
if (!type.equals(narrowed)) {
scope = narrowScope(scope, n, narrowed);
}
}
return scope;
} | [
"private",
"FlowScope",
"tightenTypeAfterDereference",
"(",
"Node",
"n",
",",
"FlowScope",
"scope",
")",
"{",
"if",
"(",
"n",
".",
"isQualifiedName",
"(",
")",
")",
"{",
"JSType",
"type",
"=",
"getJSType",
"(",
"n",
")",
";",
"JSType",
"narrowed",
"=",
"type",
".",
"restrictByNotNullOrUndefined",
"(",
")",
";",
"if",
"(",
"!",
"type",
".",
"equals",
"(",
"narrowed",
")",
")",
"{",
"scope",
"=",
"narrowScope",
"(",
"scope",
",",
"n",
",",
"narrowed",
")",
";",
"}",
"}",
"return",
"scope",
";",
"}"
] | If we access a property of a symbol, then that symbol is not
null or undefined. | [
"If",
"we",
"access",
"a",
"property",
"of",
"a",
"symbol",
"then",
"that",
"symbol",
"is",
"not",
"null",
"or",
"undefined",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeInference.java#L2186-L2195 |
24,579 | google/closure-compiler | src/com/google/javascript/jscomp/Es6RewriteModulesToCommonJsModules.java | Es6RewriteModulesToCommonJsModules.normalizePath | private static String normalizePath(String path) {
int indexOfProtocol = path.indexOf("://");
if (indexOfProtocol > -1) {
path = path.substring(indexOfProtocol + 3);
int indexOfSlash = path.indexOf('/');
if (indexOfSlash > -1) {
path = path.substring(indexOfSlash + 1);
}
} else if (path.startsWith("/")) {
path = path.substring(1);
}
return path;
} | java | private static String normalizePath(String path) {
int indexOfProtocol = path.indexOf("://");
if (indexOfProtocol > -1) {
path = path.substring(indexOfProtocol + 3);
int indexOfSlash = path.indexOf('/');
if (indexOfSlash > -1) {
path = path.substring(indexOfSlash + 1);
}
} else if (path.startsWith("/")) {
path = path.substring(1);
}
return path;
} | [
"private",
"static",
"String",
"normalizePath",
"(",
"String",
"path",
")",
"{",
"int",
"indexOfProtocol",
"=",
"path",
".",
"indexOf",
"(",
"\"://\"",
")",
";",
"if",
"(",
"indexOfProtocol",
">",
"-",
"1",
")",
"{",
"path",
"=",
"path",
".",
"substring",
"(",
"indexOfProtocol",
"+",
"3",
")",
";",
"int",
"indexOfSlash",
"=",
"path",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"indexOfSlash",
">",
"-",
"1",
")",
"{",
"path",
"=",
"path",
".",
"substring",
"(",
"indexOfSlash",
"+",
"1",
")",
";",
"}",
"}",
"else",
"if",
"(",
"path",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"path",
"=",
"path",
".",
"substring",
"(",
"1",
")",
";",
"}",
"return",
"path",
";",
"}"
] | Normalizes a registered or import path.
<p>Absolute import paths need to match the registered path exactly. Some {@link
ModuleLoader.ModulePath}s will have a leading slash and some won't. So in order to have
everything line up AND preserve schemes (if they exist) then just strip leading /.
<p>Additionally if any path contains a protocol it will be stripped only the path part will
remain. This is done heuristically as we cannot use {@link java.net.URL} or {@link
java.nio.file.Path} due to GWT. As a result of stripping this cross-domain imports are not
compatible with this pass. | [
"Normalizes",
"a",
"registered",
"or",
"import",
"path",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteModulesToCommonJsModules.java#L102-L114 |
24,580 | google/closure-compiler | src/com/google/javascript/refactoring/ApplySuggestedFixes.java | ApplySuggestedFixes.applySuggestedFixesToFiles | public static void applySuggestedFixesToFiles(Iterable<SuggestedFix> fixes)
throws IOException {
Set<String> filenames = new HashSet<>();
for (SuggestedFix fix : fixes) {
filenames.addAll(fix.getReplacements().keySet());
}
Map<String, String> filenameToCodeMap = new HashMap<>();
for (String filename : filenames) {
filenameToCodeMap.put(filename, Files.asCharSource(new File(filename), UTF_8).read());
}
Map<String, String> newCode = applySuggestedFixesToCode(fixes, filenameToCodeMap);
for (Map.Entry<String, String> entry : newCode.entrySet()) {
Files.asCharSink(new File(entry.getKey()), UTF_8).write(entry.getValue());
}
} | java | public static void applySuggestedFixesToFiles(Iterable<SuggestedFix> fixes)
throws IOException {
Set<String> filenames = new HashSet<>();
for (SuggestedFix fix : fixes) {
filenames.addAll(fix.getReplacements().keySet());
}
Map<String, String> filenameToCodeMap = new HashMap<>();
for (String filename : filenames) {
filenameToCodeMap.put(filename, Files.asCharSource(new File(filename), UTF_8).read());
}
Map<String, String> newCode = applySuggestedFixesToCode(fixes, filenameToCodeMap);
for (Map.Entry<String, String> entry : newCode.entrySet()) {
Files.asCharSink(new File(entry.getKey()), UTF_8).write(entry.getValue());
}
} | [
"public",
"static",
"void",
"applySuggestedFixesToFiles",
"(",
"Iterable",
"<",
"SuggestedFix",
">",
"fixes",
")",
"throws",
"IOException",
"{",
"Set",
"<",
"String",
">",
"filenames",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"for",
"(",
"SuggestedFix",
"fix",
":",
"fixes",
")",
"{",
"filenames",
".",
"addAll",
"(",
"fix",
".",
"getReplacements",
"(",
")",
".",
"keySet",
"(",
")",
")",
";",
"}",
"Map",
"<",
"String",
",",
"String",
">",
"filenameToCodeMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"for",
"(",
"String",
"filename",
":",
"filenames",
")",
"{",
"filenameToCodeMap",
".",
"put",
"(",
"filename",
",",
"Files",
".",
"asCharSource",
"(",
"new",
"File",
"(",
"filename",
")",
",",
"UTF_8",
")",
".",
"read",
"(",
")",
")",
";",
"}",
"Map",
"<",
"String",
",",
"String",
">",
"newCode",
"=",
"applySuggestedFixesToCode",
"(",
"fixes",
",",
"filenameToCodeMap",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"newCode",
".",
"entrySet",
"(",
")",
")",
"{",
"Files",
".",
"asCharSink",
"(",
"new",
"File",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
",",
"UTF_8",
")",
".",
"write",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}"
] | Applies the provided set of suggested fixes to the files listed in the suggested fixes.
The fixes can be provided in any order, but they may not have any overlapping modifications
for the same file. | [
"Applies",
"the",
"provided",
"set",
"of",
"suggested",
"fixes",
"to",
"the",
"files",
"listed",
"in",
"the",
"suggested",
"fixes",
".",
"The",
"fixes",
"can",
"be",
"provided",
"in",
"any",
"order",
"but",
"they",
"may",
"not",
"have",
"any",
"overlapping",
"modifications",
"for",
"the",
"same",
"file",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/refactoring/ApplySuggestedFixes.java#L61-L77 |
24,581 | google/closure-compiler | src/com/google/javascript/refactoring/ApplySuggestedFixes.java | ApplySuggestedFixes.applyCodeReplacements | public static String applyCodeReplacements(Iterable<CodeReplacement> replacements, String code) {
List<CodeReplacement> sortedReplacements = ORDER_CODE_REPLACEMENTS.sortedCopy(replacements);
validateNoOverlaps(sortedReplacements);
StringBuilder sb = new StringBuilder();
int lastIndex = 0;
for (CodeReplacement replacement : sortedReplacements) {
sb.append(code, lastIndex, replacement.getStartPosition());
sb.append(replacement.getNewContent());
lastIndex = replacement.getEndPosition();
}
if (lastIndex <= code.length()) {
sb.append(code, lastIndex, code.length());
}
return sb.toString();
} | java | public static String applyCodeReplacements(Iterable<CodeReplacement> replacements, String code) {
List<CodeReplacement> sortedReplacements = ORDER_CODE_REPLACEMENTS.sortedCopy(replacements);
validateNoOverlaps(sortedReplacements);
StringBuilder sb = new StringBuilder();
int lastIndex = 0;
for (CodeReplacement replacement : sortedReplacements) {
sb.append(code, lastIndex, replacement.getStartPosition());
sb.append(replacement.getNewContent());
lastIndex = replacement.getEndPosition();
}
if (lastIndex <= code.length()) {
sb.append(code, lastIndex, code.length());
}
return sb.toString();
} | [
"public",
"static",
"String",
"applyCodeReplacements",
"(",
"Iterable",
"<",
"CodeReplacement",
">",
"replacements",
",",
"String",
"code",
")",
"{",
"List",
"<",
"CodeReplacement",
">",
"sortedReplacements",
"=",
"ORDER_CODE_REPLACEMENTS",
".",
"sortedCopy",
"(",
"replacements",
")",
";",
"validateNoOverlaps",
"(",
"sortedReplacements",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"int",
"lastIndex",
"=",
"0",
";",
"for",
"(",
"CodeReplacement",
"replacement",
":",
"sortedReplacements",
")",
"{",
"sb",
".",
"append",
"(",
"code",
",",
"lastIndex",
",",
"replacement",
".",
"getStartPosition",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"replacement",
".",
"getNewContent",
"(",
")",
")",
";",
"lastIndex",
"=",
"replacement",
".",
"getEndPosition",
"(",
")",
";",
"}",
"if",
"(",
"lastIndex",
"<=",
"code",
".",
"length",
"(",
")",
")",
"{",
"sb",
".",
"append",
"(",
"code",
",",
"lastIndex",
",",
"code",
".",
"length",
"(",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Applies the provided set of code replacements to the code and returns the transformed code.
The code replacements may not have any overlap. | [
"Applies",
"the",
"provided",
"set",
"of",
"code",
"replacements",
"to",
"the",
"code",
"and",
"returns",
"the",
"transformed",
"code",
".",
"The",
"code",
"replacements",
"may",
"not",
"have",
"any",
"overlap",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/refactoring/ApplySuggestedFixes.java#L146-L161 |
24,582 | google/closure-compiler | src/com/google/javascript/refactoring/ApplySuggestedFixes.java | ApplySuggestedFixes.validateNoOverlaps | private static void validateNoOverlaps(List<CodeReplacement> replacements) {
checkState(ORDER_CODE_REPLACEMENTS.isOrdered(replacements));
if (containsOverlaps(replacements)) {
throw new IllegalArgumentException(
"Found overlap between code replacements!\n" + Joiner.on("\n\n").join(replacements));
}
} | java | private static void validateNoOverlaps(List<CodeReplacement> replacements) {
checkState(ORDER_CODE_REPLACEMENTS.isOrdered(replacements));
if (containsOverlaps(replacements)) {
throw new IllegalArgumentException(
"Found overlap between code replacements!\n" + Joiner.on("\n\n").join(replacements));
}
} | [
"private",
"static",
"void",
"validateNoOverlaps",
"(",
"List",
"<",
"CodeReplacement",
">",
"replacements",
")",
"{",
"checkState",
"(",
"ORDER_CODE_REPLACEMENTS",
".",
"isOrdered",
"(",
"replacements",
")",
")",
";",
"if",
"(",
"containsOverlaps",
"(",
"replacements",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Found overlap between code replacements!\\n\"",
"+",
"Joiner",
".",
"on",
"(",
"\"\\n\\n\"",
")",
".",
"join",
"(",
"replacements",
")",
")",
";",
"}",
"}"
] | Validates that none of the CodeReplacements have any overlap, since applying
changes that have overlap will produce malformed results.
The replacements must be provided in order sorted by start position, as sorted
by ORDER_CODE_REPLACEMENTS. | [
"Validates",
"that",
"none",
"of",
"the",
"CodeReplacements",
"have",
"any",
"overlap",
"since",
"applying",
"changes",
"that",
"have",
"overlap",
"will",
"produce",
"malformed",
"results",
".",
"The",
"replacements",
"must",
"be",
"provided",
"in",
"order",
"sorted",
"by",
"start",
"position",
"as",
"sorted",
"by",
"ORDER_CODE_REPLACEMENTS",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/refactoring/ApplySuggestedFixes.java#L169-L175 |
24,583 | google/closure-compiler | src/com/google/javascript/refactoring/ApplySuggestedFixes.java | ApplySuggestedFixes.containsOverlaps | private static boolean containsOverlaps(List<CodeReplacement> replacements) {
checkState(ORDER_CODE_REPLACEMENTS.isOrdered(replacements));
int start = -1;
for (CodeReplacement replacement : replacements) {
if (replacement.getStartPosition() < start) {
return true;
}
start = Math.max(start, replacement.getEndPosition());
}
return false;
} | java | private static boolean containsOverlaps(List<CodeReplacement> replacements) {
checkState(ORDER_CODE_REPLACEMENTS.isOrdered(replacements));
int start = -1;
for (CodeReplacement replacement : replacements) {
if (replacement.getStartPosition() < start) {
return true;
}
start = Math.max(start, replacement.getEndPosition());
}
return false;
} | [
"private",
"static",
"boolean",
"containsOverlaps",
"(",
"List",
"<",
"CodeReplacement",
">",
"replacements",
")",
"{",
"checkState",
"(",
"ORDER_CODE_REPLACEMENTS",
".",
"isOrdered",
"(",
"replacements",
")",
")",
";",
"int",
"start",
"=",
"-",
"1",
";",
"for",
"(",
"CodeReplacement",
"replacement",
":",
"replacements",
")",
"{",
"if",
"(",
"replacement",
".",
"getStartPosition",
"(",
")",
"<",
"start",
")",
"{",
"return",
"true",
";",
"}",
"start",
"=",
"Math",
".",
"max",
"(",
"start",
",",
"replacement",
".",
"getEndPosition",
"(",
")",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Checks whether the CodeReplacements have any overlap. The replacements must be provided in
order sorted by start position, as sorted by ORDER_CODE_REPLACEMENTS. | [
"Checks",
"whether",
"the",
"CodeReplacements",
"have",
"any",
"overlap",
".",
"The",
"replacements",
"must",
"be",
"provided",
"in",
"order",
"sorted",
"by",
"start",
"position",
"as",
"sorted",
"by",
"ORDER_CODE_REPLACEMENTS",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/refactoring/ApplySuggestedFixes.java#L181-L191 |
24,584 | google/closure-compiler | src/com/google/javascript/jscomp/ClosureRewriteModule.java | ClosureRewriteModule.rewriteJsdoc | private void rewriteJsdoc(JSDocInfo info) {
for (Node typeNode : info.getTypeNodes()) {
NodeUtil.visitPreOrder(typeNode, replaceJsDocRefs);
}
} | java | private void rewriteJsdoc(JSDocInfo info) {
for (Node typeNode : info.getTypeNodes()) {
NodeUtil.visitPreOrder(typeNode, replaceJsDocRefs);
}
} | [
"private",
"void",
"rewriteJsdoc",
"(",
"JSDocInfo",
"info",
")",
"{",
"for",
"(",
"Node",
"typeNode",
":",
"info",
".",
"getTypeNodes",
"(",
")",
")",
"{",
"NodeUtil",
".",
"visitPreOrder",
"(",
"typeNode",
",",
"replaceJsDocRefs",
")",
";",
"}",
"}"
] | Rewrites JsDoc type references to match AST changes resulting from imported alias inlining,
module content renaming of top level constructor functions and classes, and module renaming
from fully qualified legacy namespace to its binary name. | [
"Rewrites",
"JsDoc",
"type",
"references",
"to",
"match",
"AST",
"changes",
"resulting",
"from",
"imported",
"alias",
"inlining",
"module",
"content",
"renaming",
"of",
"top",
"level",
"constructor",
"functions",
"and",
"classes",
"and",
"module",
"renaming",
"from",
"fully",
"qualified",
"legacy",
"namespace",
"to",
"its",
"binary",
"name",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ClosureRewriteModule.java#L514-L518 |
24,585 | google/closure-compiler | src/com/google/javascript/jscomp/ClosureRewriteModule.java | ClosureRewriteModule.pushScript | private void pushScript(ScriptDescription newCurrentScript) {
currentScript = newCurrentScript;
if (!scriptStack.isEmpty()) {
ScriptDescription parentScript = scriptStack.peek();
parentScript.addChildScript(currentScript);
}
scriptStack.addFirst(currentScript);
} | java | private void pushScript(ScriptDescription newCurrentScript) {
currentScript = newCurrentScript;
if (!scriptStack.isEmpty()) {
ScriptDescription parentScript = scriptStack.peek();
parentScript.addChildScript(currentScript);
}
scriptStack.addFirst(currentScript);
} | [
"private",
"void",
"pushScript",
"(",
"ScriptDescription",
"newCurrentScript",
")",
"{",
"currentScript",
"=",
"newCurrentScript",
";",
"if",
"(",
"!",
"scriptStack",
".",
"isEmpty",
"(",
")",
")",
"{",
"ScriptDescription",
"parentScript",
"=",
"scriptStack",
".",
"peek",
"(",
")",
";",
"parentScript",
".",
"addChildScript",
"(",
"currentScript",
")",
";",
"}",
"scriptStack",
".",
"addFirst",
"(",
"currentScript",
")",
";",
"}"
] | Record the provided script as the current script at top of the script stack and add it as a
child of the previous current script if there was one.
<p>Keeping track of the current script facilitates aggregation of accurate script state so that
rewriting can run properly. Handles scripts and nested goog.modules. | [
"Record",
"the",
"provided",
"script",
"as",
"the",
"current",
"script",
"at",
"top",
"of",
"the",
"script",
"stack",
"and",
"add",
"it",
"as",
"a",
"child",
"of",
"the",
"previous",
"current",
"script",
"if",
"there",
"was",
"one",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ClosureRewriteModule.java#L1480-L1487 |
24,586 | google/closure-compiler | src/com/google/javascript/jscomp/ClosureRewriteModule.java | ClosureRewriteModule.reportUnrecognizedRequires | private void reportUnrecognizedRequires() {
for (UnrecognizedRequire unrecognizedRequire : unrecognizedRequires) {
String legacyNamespace = unrecognizedRequire.legacyNamespace;
Node requireNode = unrecognizedRequire.requireNode;
boolean targetGoogModuleExists = rewriteState.containsModule(legacyNamespace);
boolean targetLegacyScriptExists =
rewriteState.legacyScriptNamespaces.contains(legacyNamespace);
if (!targetGoogModuleExists && !targetLegacyScriptExists) {
// The required thing was free to be either a goog.module() or a legacy script but neither
// flavor of file provided the required namespace, so report a vague error.
compiler.report(
JSError.make(
requireNode,
MISSING_MODULE_OR_PROVIDE,
legacyNamespace));
// Remove the require node so this problem isn't reported again in ProcessClosurePrimitives.
if (!preserveSugar) {
Node changeScope = NodeUtil.getEnclosingChangeScopeRoot(requireNode);
if (changeScope == null) {
// It's already been removed; nothing to do.
} else {
compiler.reportChangeToChangeScope(changeScope);
NodeUtil.getEnclosingStatement(requireNode).detach();
}
}
continue;
}
// The required thing actually was available somewhere in the program but just wasn't
// available as early as the require statement would have liked.
if (unrecognizedRequire.mustBeOrdered) {
compiler.report(JSError.make(requireNode, LATE_PROVIDE_ERROR, legacyNamespace));
}
}
// Clear the queue so that repeated reportUnrecognizedRequires() invocations in hotswap compiles
// only report new problems.
unrecognizedRequires.clear();
} | java | private void reportUnrecognizedRequires() {
for (UnrecognizedRequire unrecognizedRequire : unrecognizedRequires) {
String legacyNamespace = unrecognizedRequire.legacyNamespace;
Node requireNode = unrecognizedRequire.requireNode;
boolean targetGoogModuleExists = rewriteState.containsModule(legacyNamespace);
boolean targetLegacyScriptExists =
rewriteState.legacyScriptNamespaces.contains(legacyNamespace);
if (!targetGoogModuleExists && !targetLegacyScriptExists) {
// The required thing was free to be either a goog.module() or a legacy script but neither
// flavor of file provided the required namespace, so report a vague error.
compiler.report(
JSError.make(
requireNode,
MISSING_MODULE_OR_PROVIDE,
legacyNamespace));
// Remove the require node so this problem isn't reported again in ProcessClosurePrimitives.
if (!preserveSugar) {
Node changeScope = NodeUtil.getEnclosingChangeScopeRoot(requireNode);
if (changeScope == null) {
// It's already been removed; nothing to do.
} else {
compiler.reportChangeToChangeScope(changeScope);
NodeUtil.getEnclosingStatement(requireNode).detach();
}
}
continue;
}
// The required thing actually was available somewhere in the program but just wasn't
// available as early as the require statement would have liked.
if (unrecognizedRequire.mustBeOrdered) {
compiler.report(JSError.make(requireNode, LATE_PROVIDE_ERROR, legacyNamespace));
}
}
// Clear the queue so that repeated reportUnrecognizedRequires() invocations in hotswap compiles
// only report new problems.
unrecognizedRequires.clear();
} | [
"private",
"void",
"reportUnrecognizedRequires",
"(",
")",
"{",
"for",
"(",
"UnrecognizedRequire",
"unrecognizedRequire",
":",
"unrecognizedRequires",
")",
"{",
"String",
"legacyNamespace",
"=",
"unrecognizedRequire",
".",
"legacyNamespace",
";",
"Node",
"requireNode",
"=",
"unrecognizedRequire",
".",
"requireNode",
";",
"boolean",
"targetGoogModuleExists",
"=",
"rewriteState",
".",
"containsModule",
"(",
"legacyNamespace",
")",
";",
"boolean",
"targetLegacyScriptExists",
"=",
"rewriteState",
".",
"legacyScriptNamespaces",
".",
"contains",
"(",
"legacyNamespace",
")",
";",
"if",
"(",
"!",
"targetGoogModuleExists",
"&&",
"!",
"targetLegacyScriptExists",
")",
"{",
"// The required thing was free to be either a goog.module() or a legacy script but neither",
"// flavor of file provided the required namespace, so report a vague error.",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"requireNode",
",",
"MISSING_MODULE_OR_PROVIDE",
",",
"legacyNamespace",
")",
")",
";",
"// Remove the require node so this problem isn't reported again in ProcessClosurePrimitives.",
"if",
"(",
"!",
"preserveSugar",
")",
"{",
"Node",
"changeScope",
"=",
"NodeUtil",
".",
"getEnclosingChangeScopeRoot",
"(",
"requireNode",
")",
";",
"if",
"(",
"changeScope",
"==",
"null",
")",
"{",
"// It's already been removed; nothing to do.",
"}",
"else",
"{",
"compiler",
".",
"reportChangeToChangeScope",
"(",
"changeScope",
")",
";",
"NodeUtil",
".",
"getEnclosingStatement",
"(",
"requireNode",
")",
".",
"detach",
"(",
")",
";",
"}",
"}",
"continue",
";",
"}",
"// The required thing actually was available somewhere in the program but just wasn't",
"// available as early as the require statement would have liked.",
"if",
"(",
"unrecognizedRequire",
".",
"mustBeOrdered",
")",
"{",
"compiler",
".",
"report",
"(",
"JSError",
".",
"make",
"(",
"requireNode",
",",
"LATE_PROVIDE_ERROR",
",",
"legacyNamespace",
")",
")",
";",
"}",
"}",
"// Clear the queue so that repeated reportUnrecognizedRequires() invocations in hotswap compiles",
"// only report new problems.",
"unrecognizedRequires",
".",
"clear",
"(",
")",
";",
"}"
] | Examines queue'ed unrecognizedRequires to categorize and report them as either missing module,
missing namespace or late provide. | [
"Examines",
"queue",
"ed",
"unrecognizedRequires",
"to",
"categorize",
"and",
"report",
"them",
"as",
"either",
"missing",
"module",
"missing",
"namespace",
"or",
"late",
"provide",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ClosureRewriteModule.java#L1586-L1626 |
24,587 | google/closure-compiler | src/com/google/javascript/jscomp/ClosureRewriteModule.java | ClosureRewriteModule.replaceStringNodeLocationForExportedTopLevelVariable | private void replaceStringNodeLocationForExportedTopLevelVariable(
Node n, int sourcePosition, int length) {
if (n.hasOneChild()) {
Node assign = n.getFirstChild();
if (assign != null && assign.isAssign()) {
// ASSIGN always has two children.
Node getProp = assign.getFirstChild();
if (getProp != null && getProp.isGetProp()) {
// GETPROP always has two children: a name node and a string node. They should both take
// on the source range of the original variable.
for (Node child : getProp.children()) {
child.setSourceEncodedPosition(sourcePosition);
child.setLength(length);
}
}
}
}
} | java | private void replaceStringNodeLocationForExportedTopLevelVariable(
Node n, int sourcePosition, int length) {
if (n.hasOneChild()) {
Node assign = n.getFirstChild();
if (assign != null && assign.isAssign()) {
// ASSIGN always has two children.
Node getProp = assign.getFirstChild();
if (getProp != null && getProp.isGetProp()) {
// GETPROP always has two children: a name node and a string node. They should both take
// on the source range of the original variable.
for (Node child : getProp.children()) {
child.setSourceEncodedPosition(sourcePosition);
child.setLength(length);
}
}
}
}
} | [
"private",
"void",
"replaceStringNodeLocationForExportedTopLevelVariable",
"(",
"Node",
"n",
",",
"int",
"sourcePosition",
",",
"int",
"length",
")",
"{",
"if",
"(",
"n",
".",
"hasOneChild",
"(",
")",
")",
"{",
"Node",
"assign",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"if",
"(",
"assign",
"!=",
"null",
"&&",
"assign",
".",
"isAssign",
"(",
")",
")",
"{",
"// ASSIGN always has two children.",
"Node",
"getProp",
"=",
"assign",
".",
"getFirstChild",
"(",
")",
";",
"if",
"(",
"getProp",
"!=",
"null",
"&&",
"getProp",
".",
"isGetProp",
"(",
")",
")",
"{",
"// GETPROP always has two children: a name node and a string node. They should both take",
"// on the source range of the original variable.",
"for",
"(",
"Node",
"child",
":",
"getProp",
".",
"children",
"(",
")",
")",
"{",
"child",
".",
"setSourceEncodedPosition",
"(",
"sourcePosition",
")",
";",
"child",
".",
"setLength",
"(",
"length",
")",
";",
"}",
"}",
"}",
"}",
"}"
] | If we had something like const FOO = "text" and we export FOO, change the source location
information for the rewritten FOO. The replacement should be something like MOD.FOO = "text",
so we look for MOD.FOO and replace the source location for FOO to the original location of FOO.
@param n node tree to modify
@param sourcePosition position to set for the start of the STRING node.
@param length length to set for STRING node. | [
"If",
"we",
"had",
"something",
"like",
"const",
"FOO",
"=",
"text",
"and",
"we",
"export",
"FOO",
"change",
"the",
"source",
"location",
"information",
"for",
"the",
"rewritten",
"FOO",
".",
"The",
"replacement",
"should",
"be",
"something",
"like",
"MOD",
".",
"FOO",
"=",
"text",
"so",
"we",
"look",
"for",
"MOD",
".",
"FOO",
"and",
"replace",
"the",
"source",
"location",
"for",
"FOO",
"to",
"the",
"original",
"location",
"of",
"FOO",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ClosureRewriteModule.java#L1732-L1749 |
24,588 | google/closure-compiler | src/com/google/javascript/rhino/NominalTypeBuilder.java | NominalTypeBuilder.declarePrototypeProperty | public void declarePrototypeProperty(String name, JSType type, Node defSite) {
prototype.defineDeclaredProperty(name, type, defSite);
} | java | public void declarePrototypeProperty(String name, JSType type, Node defSite) {
prototype.defineDeclaredProperty(name, type, defSite);
} | [
"public",
"void",
"declarePrototypeProperty",
"(",
"String",
"name",
",",
"JSType",
"type",
",",
"Node",
"defSite",
")",
"{",
"prototype",
".",
"defineDeclaredProperty",
"(",
"name",
",",
"type",
",",
"defSite",
")",
";",
"}"
] | Declares a property on the nominal type's prototype. | [
"Declares",
"a",
"property",
"on",
"the",
"nominal",
"type",
"s",
"prototype",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/NominalTypeBuilder.java#L70-L72 |
24,589 | google/closure-compiler | src/com/google/javascript/rhino/NominalTypeBuilder.java | NominalTypeBuilder.declareInstanceProperty | public void declareInstanceProperty(String name, JSType type, Node defSite) {
instance.defineDeclaredProperty(name, type, defSite);
} | java | public void declareInstanceProperty(String name, JSType type, Node defSite) {
instance.defineDeclaredProperty(name, type, defSite);
} | [
"public",
"void",
"declareInstanceProperty",
"(",
"String",
"name",
",",
"JSType",
"type",
",",
"Node",
"defSite",
")",
"{",
"instance",
".",
"defineDeclaredProperty",
"(",
"name",
",",
"type",
",",
"defSite",
")",
";",
"}"
] | Declares an instance property on the nominal type. | [
"Declares",
"an",
"instance",
"property",
"on",
"the",
"nominal",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/NominalTypeBuilder.java#L75-L77 |
24,590 | google/closure-compiler | src/com/google/javascript/rhino/NominalTypeBuilder.java | NominalTypeBuilder.declareConstructorProperty | public void declareConstructorProperty(String name, JSType type, Node defSite) {
constructor.defineDeclaredProperty(name, type, defSite);
} | java | public void declareConstructorProperty(String name, JSType type, Node defSite) {
constructor.defineDeclaredProperty(name, type, defSite);
} | [
"public",
"void",
"declareConstructorProperty",
"(",
"String",
"name",
",",
"JSType",
"type",
",",
"Node",
"defSite",
")",
"{",
"constructor",
".",
"defineDeclaredProperty",
"(",
"name",
",",
"type",
",",
"defSite",
")",
";",
"}"
] | Declares a static property on the nominal type's constructor. | [
"Declares",
"a",
"static",
"property",
"on",
"the",
"nominal",
"type",
"s",
"constructor",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/NominalTypeBuilder.java#L80-L82 |
24,591 | google/closure-compiler | src/com/google/javascript/rhino/NominalTypeBuilder.java | NominalTypeBuilder.superClass | public NominalTypeBuilder superClass() {
FunctionType ctor = instance.getSuperClassConstructor();
if (ctor == null) {
return null;
}
return new NominalTypeBuilder(ctor, ctor.getInstanceType());
} | java | public NominalTypeBuilder superClass() {
FunctionType ctor = instance.getSuperClassConstructor();
if (ctor == null) {
return null;
}
return new NominalTypeBuilder(ctor, ctor.getInstanceType());
} | [
"public",
"NominalTypeBuilder",
"superClass",
"(",
")",
"{",
"FunctionType",
"ctor",
"=",
"instance",
".",
"getSuperClassConstructor",
"(",
")",
";",
"if",
"(",
"ctor",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",
"NominalTypeBuilder",
"(",
"ctor",
",",
"ctor",
".",
"getInstanceType",
"(",
")",
")",
";",
"}"
] | Returns a NominalTypeBuilder for this type's superclass. | [
"Returns",
"a",
"NominalTypeBuilder",
"for",
"this",
"type",
"s",
"superclass",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/NominalTypeBuilder.java#L85-L91 |
24,592 | google/closure-compiler | src/com/google/javascript/rhino/jstype/TemplateTypeMap.java | TemplateTypeMap.hasTemplateKey | @SuppressWarnings("ReferenceEquality")
public boolean hasTemplateKey(TemplateType templateKey) {
// Note: match by identity, not equality
for (TemplateType entry : templateKeys) {
if (entry == templateKey) {
return true;
}
}
return false;
} | java | @SuppressWarnings("ReferenceEquality")
public boolean hasTemplateKey(TemplateType templateKey) {
// Note: match by identity, not equality
for (TemplateType entry : templateKeys) {
if (entry == templateKey) {
return true;
}
}
return false;
} | [
"@",
"SuppressWarnings",
"(",
"\"ReferenceEquality\"",
")",
"public",
"boolean",
"hasTemplateKey",
"(",
"TemplateType",
"templateKey",
")",
"{",
"// Note: match by identity, not equality",
"for",
"(",
"TemplateType",
"entry",
":",
"templateKeys",
")",
"{",
"if",
"(",
"entry",
"==",
"templateKey",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Returns true if this map contains the specified template key, false
otherwise. | [
"Returns",
"true",
"if",
"this",
"map",
"contains",
"the",
"specified",
"template",
"key",
"false",
"otherwise",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMap.java#L124-L133 |
24,593 | google/closure-compiler | src/com/google/javascript/rhino/jstype/TemplateTypeMap.java | TemplateTypeMap.getTemplateTypeIndex | private int getTemplateTypeIndex(TemplateType key) {
int maxIndex = Math.min(templateKeys.size(), templateValues.size());
for (int i = maxIndex - 1; i >= 0; i--) {
if (isSameKey(templateKeys.get(i), key)) {
return i;
}
}
return -1;
} | java | private int getTemplateTypeIndex(TemplateType key) {
int maxIndex = Math.min(templateKeys.size(), templateValues.size());
for (int i = maxIndex - 1; i >= 0; i--) {
if (isSameKey(templateKeys.get(i), key)) {
return i;
}
}
return -1;
} | [
"private",
"int",
"getTemplateTypeIndex",
"(",
"TemplateType",
"key",
")",
"{",
"int",
"maxIndex",
"=",
"Math",
".",
"min",
"(",
"templateKeys",
".",
"size",
"(",
")",
",",
"templateValues",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"maxIndex",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"isSameKey",
"(",
"templateKeys",
".",
"get",
"(",
"i",
")",
",",
"key",
")",
")",
"{",
"return",
"i",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | Returns the index of the JSType value associated with the specified
template key. If no JSType value is associated, returns -1. | [
"Returns",
"the",
"index",
"of",
"the",
"JSType",
"value",
"associated",
"with",
"the",
"specified",
"template",
"key",
".",
"If",
"no",
"JSType",
"value",
"is",
"associated",
"returns",
"-",
"1",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMap.java#L187-L195 |
24,594 | google/closure-compiler | src/com/google/javascript/rhino/jstype/TemplateTypeMap.java | TemplateTypeMap.getResolvedTemplateType | public JSType getResolvedTemplateType(TemplateType key) {
int index = getTemplateTypeIndex(key);
return (index == -1)
? registry.getNativeType(JSTypeNative.UNKNOWN_TYPE)
: resolvedTemplateValues[index];
} | java | public JSType getResolvedTemplateType(TemplateType key) {
int index = getTemplateTypeIndex(key);
return (index == -1)
? registry.getNativeType(JSTypeNative.UNKNOWN_TYPE)
: resolvedTemplateValues[index];
} | [
"public",
"JSType",
"getResolvedTemplateType",
"(",
"TemplateType",
"key",
")",
"{",
"int",
"index",
"=",
"getTemplateTypeIndex",
"(",
"key",
")",
";",
"return",
"(",
"index",
"==",
"-",
"1",
")",
"?",
"registry",
".",
"getNativeType",
"(",
"JSTypeNative",
".",
"UNKNOWN_TYPE",
")",
":",
"resolvedTemplateValues",
"[",
"index",
"]",
";",
"}"
] | Returns the JSType value associated with the specified template key. If no
JSType value is associated, returns UNKNOWN_TYPE. | [
"Returns",
"the",
"JSType",
"value",
"associated",
"with",
"the",
"specified",
"template",
"key",
".",
"If",
"no",
"JSType",
"value",
"is",
"associated",
"returns",
"UNKNOWN_TYPE",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMap.java#L201-L206 |
24,595 | google/closure-compiler | src/com/google/javascript/rhino/jstype/TemplateTypeMap.java | TemplateTypeMap.checkEquivalenceHelper | public boolean checkEquivalenceHelper(
TemplateTypeMap that, EquivalenceMethod eqMethod, SubtypingMode subtypingMode) {
return checkEquivalenceHelper(that, eqMethod, EqCache.create(), subtypingMode);
} | java | public boolean checkEquivalenceHelper(
TemplateTypeMap that, EquivalenceMethod eqMethod, SubtypingMode subtypingMode) {
return checkEquivalenceHelper(that, eqMethod, EqCache.create(), subtypingMode);
} | [
"public",
"boolean",
"checkEquivalenceHelper",
"(",
"TemplateTypeMap",
"that",
",",
"EquivalenceMethod",
"eqMethod",
",",
"SubtypingMode",
"subtypingMode",
")",
"{",
"return",
"checkEquivalenceHelper",
"(",
"that",
",",
"eqMethod",
",",
"EqCache",
".",
"create",
"(",
")",
",",
"subtypingMode",
")",
";",
"}"
] | Determines if this map and the specified map have equivalent template
types. | [
"Determines",
"if",
"this",
"map",
"and",
"the",
"specified",
"map",
"have",
"equivalent",
"template",
"types",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMap.java#L220-L223 |
24,596 | google/closure-compiler | src/com/google/javascript/rhino/jstype/TemplateTypeMap.java | TemplateTypeMap.failedEquivalenceCheck | private static boolean failedEquivalenceCheck(
EquivalenceMatch eqMatch, EquivalenceMethod eqMethod) {
return eqMatch == EquivalenceMatch.VALUE_MISMATCH
|| (eqMatch == EquivalenceMatch.NO_KEY_MATCH && eqMethod != EquivalenceMethod.INVARIANT);
} | java | private static boolean failedEquivalenceCheck(
EquivalenceMatch eqMatch, EquivalenceMethod eqMethod) {
return eqMatch == EquivalenceMatch.VALUE_MISMATCH
|| (eqMatch == EquivalenceMatch.NO_KEY_MATCH && eqMethod != EquivalenceMethod.INVARIANT);
} | [
"private",
"static",
"boolean",
"failedEquivalenceCheck",
"(",
"EquivalenceMatch",
"eqMatch",
",",
"EquivalenceMethod",
"eqMethod",
")",
"{",
"return",
"eqMatch",
"==",
"EquivalenceMatch",
".",
"VALUE_MISMATCH",
"||",
"(",
"eqMatch",
"==",
"EquivalenceMatch",
".",
"NO_KEY_MATCH",
"&&",
"eqMethod",
"!=",
"EquivalenceMethod",
".",
"INVARIANT",
")",
";",
"}"
] | Determines if the specified EquivalenceMatch is considered a failing
condition for an equivalence check, given the EquivalenceMethod used for
the check. | [
"Determines",
"if",
"the",
"specified",
"EquivalenceMatch",
"is",
"considered",
"a",
"failing",
"condition",
"for",
"an",
"equivalence",
"check",
"given",
"the",
"EquivalenceMethod",
"used",
"for",
"the",
"check",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMap.java#L289-L293 |
24,597 | google/closure-compiler | src/com/google/javascript/rhino/jstype/TemplateTypeMap.java | TemplateTypeMap.extend | TemplateTypeMap extend(TemplateTypeMap other) {
ImmutableList<JSType> resizedOtherValues = other.resizedToMatchKeys(other.templateValues);
return registry.createTemplateTypeMap(
concatImmutableLists(other.templateKeys, templateKeys),
concatImmutableLists(resizedOtherValues, templateValues));
} | java | TemplateTypeMap extend(TemplateTypeMap other) {
ImmutableList<JSType> resizedOtherValues = other.resizedToMatchKeys(other.templateValues);
return registry.createTemplateTypeMap(
concatImmutableLists(other.templateKeys, templateKeys),
concatImmutableLists(resizedOtherValues, templateValues));
} | [
"TemplateTypeMap",
"extend",
"(",
"TemplateTypeMap",
"other",
")",
"{",
"ImmutableList",
"<",
"JSType",
">",
"resizedOtherValues",
"=",
"other",
".",
"resizedToMatchKeys",
"(",
"other",
".",
"templateValues",
")",
";",
"return",
"registry",
".",
"createTemplateTypeMap",
"(",
"concatImmutableLists",
"(",
"other",
".",
"templateKeys",
",",
"templateKeys",
")",
",",
"concatImmutableLists",
"(",
"resizedOtherValues",
",",
"templateValues",
")",
")",
";",
"}"
] | Extends this TemplateTypeMap with the contents of the specified map. UNKNOWN_TYPE will be used
as the value for any missing values in the specified map. | [
"Extends",
"this",
"TemplateTypeMap",
"with",
"the",
"contents",
"of",
"the",
"specified",
"map",
".",
"UNKNOWN_TYPE",
"will",
"be",
"used",
"as",
"the",
"value",
"for",
"any",
"missing",
"values",
"in",
"the",
"specified",
"map",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMap.java#L299-L304 |
24,598 | google/closure-compiler | src/com/google/javascript/rhino/jstype/TemplateTypeMap.java | TemplateTypeMap.copyFilledWithValues | TemplateTypeMap copyFilledWithValues(ImmutableList<JSType> additionalValues) {
ImmutableList<JSType> finalValues =
resizedToMatchKeys(concatImmutableLists(templateValues, additionalValues));
return registry.createTemplateTypeMap(templateKeys, finalValues);
} | java | TemplateTypeMap copyFilledWithValues(ImmutableList<JSType> additionalValues) {
ImmutableList<JSType> finalValues =
resizedToMatchKeys(concatImmutableLists(templateValues, additionalValues));
return registry.createTemplateTypeMap(templateKeys, finalValues);
} | [
"TemplateTypeMap",
"copyFilledWithValues",
"(",
"ImmutableList",
"<",
"JSType",
">",
"additionalValues",
")",
"{",
"ImmutableList",
"<",
"JSType",
">",
"finalValues",
"=",
"resizedToMatchKeys",
"(",
"concatImmutableLists",
"(",
"templateValues",
",",
"additionalValues",
")",
")",
";",
"return",
"registry",
".",
"createTemplateTypeMap",
"(",
"templateKeys",
",",
"finalValues",
")",
";",
"}"
] | Returns a new TemplateTypeMap whose values have been extended with the specified list. | [
"Returns",
"a",
"new",
"TemplateTypeMap",
"whose",
"values",
"have",
"been",
"extended",
"with",
"the",
"specified",
"list",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMap.java#L307-L311 |
24,599 | google/closure-compiler | src/com/google/javascript/rhino/jstype/TemplateTypeMap.java | TemplateTypeMap.remove | TemplateTypeMap remove(Set<TemplateType> toRemove) {
ImmutableList.Builder<TemplateType> keys = ImmutableList.builder();
keys.addAll(templateKeys.subList(0, templateValues.size()));
for (int i = templateValues.size(); i < templateKeys.size(); i++) {
TemplateType key = templateKeys.get(i);
if (!toRemove.contains(key)) {
keys.add(key);
}
}
return registry.createTemplateTypeMap(keys.build(), templateValues);
} | java | TemplateTypeMap remove(Set<TemplateType> toRemove) {
ImmutableList.Builder<TemplateType> keys = ImmutableList.builder();
keys.addAll(templateKeys.subList(0, templateValues.size()));
for (int i = templateValues.size(); i < templateKeys.size(); i++) {
TemplateType key = templateKeys.get(i);
if (!toRemove.contains(key)) {
keys.add(key);
}
}
return registry.createTemplateTypeMap(keys.build(), templateValues);
} | [
"TemplateTypeMap",
"remove",
"(",
"Set",
"<",
"TemplateType",
">",
"toRemove",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"TemplateType",
">",
"keys",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"keys",
".",
"addAll",
"(",
"templateKeys",
".",
"subList",
"(",
"0",
",",
"templateValues",
".",
"size",
"(",
")",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"templateValues",
".",
"size",
"(",
")",
";",
"i",
"<",
"templateKeys",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"TemplateType",
"key",
"=",
"templateKeys",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"!",
"toRemove",
".",
"contains",
"(",
"key",
")",
")",
"{",
"keys",
".",
"add",
"(",
"key",
")",
";",
"}",
"}",
"return",
"registry",
".",
"createTemplateTypeMap",
"(",
"keys",
".",
"build",
"(",
")",
",",
"templateValues",
")",
";",
"}"
] | Returns a new TemplateTypeMap with the given template types removed. Keys will only be removed
if they are unmapped. | [
"Returns",
"a",
"new",
"TemplateTypeMap",
"with",
"the",
"given",
"template",
"types",
"removed",
".",
"Keys",
"will",
"only",
"be",
"removed",
"if",
"they",
"are",
"unmapped",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/TemplateTypeMap.java#L317-L327 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.