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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,800 | square/wire | wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/ProtoParser.java | ProtoParser.stripDefault | private @Nullable String stripDefault(List<OptionElement> options) {
String result = null;
for (Iterator<OptionElement> i = options.iterator(); i.hasNext();) {
OptionElement option = i.next();
if (option.getName().equals("default")) {
i.remove();
result = String.valueOf(option.getValue()); // Defaults aren't options!
}
}
return result;
} | java | private @Nullable String stripDefault(List<OptionElement> options) {
String result = null;
for (Iterator<OptionElement> i = options.iterator(); i.hasNext();) {
OptionElement option = i.next();
if (option.getName().equals("default")) {
i.remove();
result = String.valueOf(option.getValue()); // Defaults aren't options!
}
}
return result;
} | [
"private",
"@",
"Nullable",
"String",
"stripDefault",
"(",
"List",
"<",
"OptionElement",
">",
"options",
")",
"{",
"String",
"result",
"=",
"null",
";",
"for",
"(",
"Iterator",
"<",
"OptionElement",
">",
"i",
"=",
"options",
".",
"iterator",
"(",
")",
";",
"i",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"OptionElement",
"option",
"=",
"i",
".",
"next",
"(",
")",
";",
"if",
"(",
"option",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"\"default\"",
")",
")",
"{",
"i",
".",
"remove",
"(",
")",
";",
"result",
"=",
"String",
".",
"valueOf",
"(",
"option",
".",
"getValue",
"(",
")",
")",
";",
"// Defaults aren't options!",
"}",
"}",
"return",
"result",
";",
"}"
] | Defaults aren't options. This finds an option named "default", removes, and returns it. Returns
null if no default option is present. | [
"Defaults",
"aren",
"t",
"options",
".",
"This",
"finds",
"an",
"option",
"named",
"default",
"removes",
"and",
"returns",
"it",
".",
"Returns",
"null",
"if",
"no",
"default",
"option",
"is",
"present",
"."
] | 4a9a00dfadfc14d6a0780b85810418f9cbc78a49 | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/ProtoParser.java#L366-L376 |
23,801 | square/wire | wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/ProtoParser.java | ProtoParser.readReserved | private ReservedElement readReserved(Location location, String documentation) {
ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
while (true) {
char c = reader.peekChar();
if (c == '"' || c == '\'') {
valuesBuilder.add(reader.readQuotedString());
} else {
int tagStart = reader.readInt();
c = reader.peekChar();
if (c != ',' && c != ';') {
if (!reader.readWord().equals("to")) {
throw reader.unexpected("expected ',', ';', or 'to'");
}
int tagEnd = reader.readInt();
valuesBuilder.add(Range.closed(tagStart, tagEnd));
} else {
valuesBuilder.add(tagStart);
}
}
c = reader.readChar();
if (c == ';') break;
if (c != ',') throw reader.unexpected("expected ',' or ';'");
}
ImmutableList<Object> values = valuesBuilder.build();
if (values.isEmpty()) {
throw reader.unexpected("'reserved' must have at least one field name or tag");
}
return new ReservedElement(location, documentation, values);
} | java | private ReservedElement readReserved(Location location, String documentation) {
ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
while (true) {
char c = reader.peekChar();
if (c == '"' || c == '\'') {
valuesBuilder.add(reader.readQuotedString());
} else {
int tagStart = reader.readInt();
c = reader.peekChar();
if (c != ',' && c != ';') {
if (!reader.readWord().equals("to")) {
throw reader.unexpected("expected ',', ';', or 'to'");
}
int tagEnd = reader.readInt();
valuesBuilder.add(Range.closed(tagStart, tagEnd));
} else {
valuesBuilder.add(tagStart);
}
}
c = reader.readChar();
if (c == ';') break;
if (c != ',') throw reader.unexpected("expected ',' or ';'");
}
ImmutableList<Object> values = valuesBuilder.build();
if (values.isEmpty()) {
throw reader.unexpected("'reserved' must have at least one field name or tag");
}
return new ReservedElement(location, documentation, values);
} | [
"private",
"ReservedElement",
"readReserved",
"(",
"Location",
"location",
",",
"String",
"documentation",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"Object",
">",
"valuesBuilder",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"char",
"c",
"=",
"reader",
".",
"peekChar",
"(",
")",
";",
"if",
"(",
"c",
"==",
"'",
"'",
"||",
"c",
"==",
"'",
"'",
")",
"{",
"valuesBuilder",
".",
"add",
"(",
"reader",
".",
"readQuotedString",
"(",
")",
")",
";",
"}",
"else",
"{",
"int",
"tagStart",
"=",
"reader",
".",
"readInt",
"(",
")",
";",
"c",
"=",
"reader",
".",
"peekChar",
"(",
")",
";",
"if",
"(",
"c",
"!=",
"'",
"'",
"&&",
"c",
"!=",
"'",
"'",
")",
"{",
"if",
"(",
"!",
"reader",
".",
"readWord",
"(",
")",
".",
"equals",
"(",
"\"to\"",
")",
")",
"{",
"throw",
"reader",
".",
"unexpected",
"(",
"\"expected ',', ';', or 'to'\"",
")",
";",
"}",
"int",
"tagEnd",
"=",
"reader",
".",
"readInt",
"(",
")",
";",
"valuesBuilder",
".",
"add",
"(",
"Range",
".",
"closed",
"(",
"tagStart",
",",
"tagEnd",
")",
")",
";",
"}",
"else",
"{",
"valuesBuilder",
".",
"add",
"(",
"tagStart",
")",
";",
"}",
"}",
"c",
"=",
"reader",
".",
"readChar",
"(",
")",
";",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"break",
";",
"if",
"(",
"c",
"!=",
"'",
"'",
")",
"throw",
"reader",
".",
"unexpected",
"(",
"\"expected ',' or ';'\"",
")",
";",
"}",
"ImmutableList",
"<",
"Object",
">",
"values",
"=",
"valuesBuilder",
".",
"build",
"(",
")",
";",
"if",
"(",
"values",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"reader",
".",
"unexpected",
"(",
"\"'reserved' must have at least one field name or tag\"",
")",
";",
"}",
"return",
"new",
"ReservedElement",
"(",
"location",
",",
"documentation",
",",
"values",
")",
";",
"}"
] | Reads a reserved tags and names list like "reserved 10, 12 to 14, 'foo';". | [
"Reads",
"a",
"reserved",
"tags",
"and",
"names",
"list",
"like",
"reserved",
"10",
"12",
"to",
"14",
"foo",
";",
"."
] | 4a9a00dfadfc14d6a0780b85810418f9cbc78a49 | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/ProtoParser.java#L437-L468 |
23,802 | square/wire | wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/ProtoParser.java | ProtoParser.readEnumConstant | private EnumConstantElement readEnumConstant(
String documentation, Location location, String label) {
reader.require('=');
int tag = reader.readInt();
List<OptionElement> options = new OptionReader(reader).readOptions();
reader.require(';');
documentation = reader.tryAppendTrailingDocumentation(documentation);
return new EnumConstantElement(
location,
label,
tag,
documentation,
options);
} | java | private EnumConstantElement readEnumConstant(
String documentation, Location location, String label) {
reader.require('=');
int tag = reader.readInt();
List<OptionElement> options = new OptionReader(reader).readOptions();
reader.require(';');
documentation = reader.tryAppendTrailingDocumentation(documentation);
return new EnumConstantElement(
location,
label,
tag,
documentation,
options);
} | [
"private",
"EnumConstantElement",
"readEnumConstant",
"(",
"String",
"documentation",
",",
"Location",
"location",
",",
"String",
"label",
")",
"{",
"reader",
".",
"require",
"(",
"'",
"'",
")",
";",
"int",
"tag",
"=",
"reader",
".",
"readInt",
"(",
")",
";",
"List",
"<",
"OptionElement",
">",
"options",
"=",
"new",
"OptionReader",
"(",
"reader",
")",
".",
"readOptions",
"(",
")",
";",
"reader",
".",
"require",
"(",
"'",
"'",
")",
";",
"documentation",
"=",
"reader",
".",
"tryAppendTrailingDocumentation",
"(",
"documentation",
")",
";",
"return",
"new",
"EnumConstantElement",
"(",
"location",
",",
"label",
",",
"tag",
",",
"documentation",
",",
"options",
")",
";",
"}"
] | Reads an enum constant like "ROCK = 0;". The label is the constant name. | [
"Reads",
"an",
"enum",
"constant",
"like",
"ROCK",
"=",
"0",
";",
".",
"The",
"label",
"is",
"the",
"constant",
"name",
"."
] | 4a9a00dfadfc14d6a0780b85810418f9cbc78a49 | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/ProtoParser.java#L488-L504 |
23,803 | square/wire | wire-java-generator/src/main/java/com/squareup/wire/java/ProfileLoader.java | ProfileLoader.pathsToAttempt | Multimap<Path, String> pathsToAttempt(Set<Location> protoLocations) {
Multimap<Path, String> result = MultimapBuilder.linkedHashKeys().linkedHashSetValues().build();
for (Location location : protoLocations) {
pathsToAttempt(result, location);
}
return result;
} | java | Multimap<Path, String> pathsToAttempt(Set<Location> protoLocations) {
Multimap<Path, String> result = MultimapBuilder.linkedHashKeys().linkedHashSetValues().build();
for (Location location : protoLocations) {
pathsToAttempt(result, location);
}
return result;
} | [
"Multimap",
"<",
"Path",
",",
"String",
">",
"pathsToAttempt",
"(",
"Set",
"<",
"Location",
">",
"protoLocations",
")",
"{",
"Multimap",
"<",
"Path",
",",
"String",
">",
"result",
"=",
"MultimapBuilder",
".",
"linkedHashKeys",
"(",
")",
".",
"linkedHashSetValues",
"(",
")",
".",
"build",
"(",
")",
";",
"for",
"(",
"Location",
"location",
":",
"protoLocations",
")",
"{",
"pathsToAttempt",
"(",
"result",
",",
"location",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Returns a multimap whose keys are base directories and whose values are potential locations of
wire profile files. | [
"Returns",
"a",
"multimap",
"whose",
"keys",
"are",
"base",
"directories",
"and",
"whose",
"values",
"are",
"potential",
"locations",
"of",
"wire",
"profile",
"files",
"."
] | 4a9a00dfadfc14d6a0780b85810418f9cbc78a49 | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-java-generator/src/main/java/com/squareup/wire/java/ProfileLoader.java#L110-L116 |
23,804 | square/wire | wire-schema/src/main/java/com/squareup/wire/schema/MarkSet.java | MarkSet.mark | boolean mark(ProtoType type) {
if (type == null) throw new NullPointerException("type == null");
if (identifierSet.excludes(type)) return false;
return types.add(type);
} | java | boolean mark(ProtoType type) {
if (type == null) throw new NullPointerException("type == null");
if (identifierSet.excludes(type)) return false;
return types.add(type);
} | [
"boolean",
"mark",
"(",
"ProtoType",
"type",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"type == null\"",
")",
";",
"if",
"(",
"identifierSet",
".",
"excludes",
"(",
"type",
")",
")",
"return",
"false",
";",
"return",
"types",
".",
"add",
"(",
"type",
")",
";",
"}"
] | Marks a type as transitively reachable by the includes set. Returns true if the mark is new,
the type will be retained, and its own dependencies should be traversed. | [
"Marks",
"a",
"type",
"as",
"transitively",
"reachable",
"by",
"the",
"includes",
"set",
".",
"Returns",
"true",
"if",
"the",
"mark",
"is",
"new",
"the",
"type",
"will",
"be",
"retained",
"and",
"its",
"own",
"dependencies",
"should",
"be",
"traversed",
"."
] | 4a9a00dfadfc14d6a0780b85810418f9cbc78a49 | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/MarkSet.java#L73-L77 |
23,805 | square/wire | wire-schema/src/main/java/com/squareup/wire/schema/MarkSet.java | MarkSet.mark | boolean mark(ProtoMember protoMember) {
if (protoMember == null) throw new NullPointerException("type == null");
if (identifierSet.excludes(protoMember)) return false;
return members.containsKey(protoMember.type())
? members.put(protoMember.type(), protoMember)
: types.add(protoMember.type());
} | java | boolean mark(ProtoMember protoMember) {
if (protoMember == null) throw new NullPointerException("type == null");
if (identifierSet.excludes(protoMember)) return false;
return members.containsKey(protoMember.type())
? members.put(protoMember.type(), protoMember)
: types.add(protoMember.type());
} | [
"boolean",
"mark",
"(",
"ProtoMember",
"protoMember",
")",
"{",
"if",
"(",
"protoMember",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"type == null\"",
")",
";",
"if",
"(",
"identifierSet",
".",
"excludes",
"(",
"protoMember",
")",
")",
"return",
"false",
";",
"return",
"members",
".",
"containsKey",
"(",
"protoMember",
".",
"type",
"(",
")",
")",
"?",
"members",
".",
"put",
"(",
"protoMember",
".",
"type",
"(",
")",
",",
"protoMember",
")",
":",
"types",
".",
"add",
"(",
"protoMember",
".",
"type",
"(",
")",
")",
";",
"}"
] | Marks a member as transitively reachable by the includes set. Returns true if the mark is new,
the member will be retained, and its own dependencies should be traversed. | [
"Marks",
"a",
"member",
"as",
"transitively",
"reachable",
"by",
"the",
"includes",
"set",
".",
"Returns",
"true",
"if",
"the",
"mark",
"is",
"new",
"the",
"member",
"will",
"be",
"retained",
"and",
"its",
"own",
"dependencies",
"should",
"be",
"traversed",
"."
] | 4a9a00dfadfc14d6a0780b85810418f9cbc78a49 | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/MarkSet.java#L83-L89 |
23,806 | square/wire | wire-schema/src/main/java/com/squareup/wire/schema/ProtoType.java | ProtoType.enclosingTypeOrPackage | public String enclosingTypeOrPackage() {
int dot = string.lastIndexOf('.');
return dot == -1 ? null : string.substring(0, dot);
} | java | public String enclosingTypeOrPackage() {
int dot = string.lastIndexOf('.');
return dot == -1 ? null : string.substring(0, dot);
} | [
"public",
"String",
"enclosingTypeOrPackage",
"(",
")",
"{",
"int",
"dot",
"=",
"string",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"return",
"dot",
"==",
"-",
"1",
"?",
"null",
":",
"string",
".",
"substring",
"(",
"0",
",",
"dot",
")",
";",
"}"
] | Returns the enclosing type, or null if this type is not nested in another type. | [
"Returns",
"the",
"enclosing",
"type",
"or",
"null",
"if",
"this",
"type",
"is",
"not",
"nested",
"in",
"another",
"type",
"."
] | 4a9a00dfadfc14d6a0780b85810418f9cbc78a49 | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/ProtoType.java#L104-L107 |
23,807 | square/wire | wire-schema/src/main/java/com/squareup/wire/schema/Linker.java | Linker.packageName | String packageName() {
for (Object context : contextStack) {
if (context instanceof ProtoFile) return ((ProtoFile) context).packageName();
}
return null;
} | java | String packageName() {
for (Object context : contextStack) {
if (context instanceof ProtoFile) return ((ProtoFile) context).packageName();
}
return null;
} | [
"String",
"packageName",
"(",
")",
"{",
"for",
"(",
"Object",
"context",
":",
"contextStack",
")",
"{",
"if",
"(",
"context",
"instanceof",
"ProtoFile",
")",
"return",
"(",
"(",
"ProtoFile",
")",
"context",
")",
".",
"packageName",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Returns the current package name from the context stack. | [
"Returns",
"the",
"current",
"package",
"name",
"from",
"the",
"context",
"stack",
"."
] | 4a9a00dfadfc14d6a0780b85810418f9cbc78a49 | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/Linker.java#L226-L231 |
23,808 | Sayi/poi-tl | src/main/java/com/deepoove/poi/XWPFTemplate.java | XWPFTemplate.compile | public static XWPFTemplate compile(InputStream inputStream, Configure config) {
try {
XWPFTemplate instance = new XWPFTemplate();
instance.config = config;
instance.doc = new NiceXWPFDocument(inputStream);
instance.visitor = new TemplateVisitor(instance.config);
instance.eleTemplates = instance.visitor.visitDocument(instance.doc);
return instance;
} catch (IOException e) {
logger.error("Compile template failed", e);
throw new ResolverException("Compile template failed");
}
} | java | public static XWPFTemplate compile(InputStream inputStream, Configure config) {
try {
XWPFTemplate instance = new XWPFTemplate();
instance.config = config;
instance.doc = new NiceXWPFDocument(inputStream);
instance.visitor = new TemplateVisitor(instance.config);
instance.eleTemplates = instance.visitor.visitDocument(instance.doc);
return instance;
} catch (IOException e) {
logger.error("Compile template failed", e);
throw new ResolverException("Compile template failed");
}
} | [
"public",
"static",
"XWPFTemplate",
"compile",
"(",
"InputStream",
"inputStream",
",",
"Configure",
"config",
")",
"{",
"try",
"{",
"XWPFTemplate",
"instance",
"=",
"new",
"XWPFTemplate",
"(",
")",
";",
"instance",
".",
"config",
"=",
"config",
";",
"instance",
".",
"doc",
"=",
"new",
"NiceXWPFDocument",
"(",
"inputStream",
")",
";",
"instance",
".",
"visitor",
"=",
"new",
"TemplateVisitor",
"(",
"instance",
".",
"config",
")",
";",
"instance",
".",
"eleTemplates",
"=",
"instance",
".",
"visitor",
".",
"visitDocument",
"(",
"instance",
".",
"doc",
")",
";",
"return",
"instance",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"Compile template failed\"",
",",
"e",
")",
";",
"throw",
"new",
"ResolverException",
"(",
"\"Compile template failed\"",
")",
";",
"}",
"}"
] | template file as InputStream
@param inputStream
@param config
@return
@version 1.2.0 | [
"template",
"file",
"as",
"InputStream"
] | cf502a6aed473c534df4b0cac5e038fcb95d3f06 | https://github.com/Sayi/poi-tl/blob/cf502a6aed473c534df4b0cac5e038fcb95d3f06/src/main/java/com/deepoove/poi/XWPFTemplate.java#L108-L120 |
23,809 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/GenericResourceRepository.java | GenericResourceRepository.isInvalidEncodedPath | private boolean isInvalidEncodedPath(String path) {
if (path.contains("%")) {
try {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8
// chars
String decodedPath = URLDecoder.decode(path, "UTF-8");
if (isInvalidPath(decodedPath)) {
return true;
}
decodedPath = processPath(decodedPath);
if (isInvalidPath(decodedPath)) {
return true;
}
}
catch (IllegalArgumentException | UnsupportedEncodingException ex) {
// Should never happen...
}
}
return false;
} | java | private boolean isInvalidEncodedPath(String path) {
if (path.contains("%")) {
try {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8
// chars
String decodedPath = URLDecoder.decode(path, "UTF-8");
if (isInvalidPath(decodedPath)) {
return true;
}
decodedPath = processPath(decodedPath);
if (isInvalidPath(decodedPath)) {
return true;
}
}
catch (IllegalArgumentException | UnsupportedEncodingException ex) {
// Should never happen...
}
}
return false;
} | [
"private",
"boolean",
"isInvalidEncodedPath",
"(",
"String",
"path",
")",
"{",
"if",
"(",
"path",
".",
"contains",
"(",
"\"%\"",
")",
")",
"{",
"try",
"{",
"// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8",
"// chars",
"String",
"decodedPath",
"=",
"URLDecoder",
".",
"decode",
"(",
"path",
",",
"\"UTF-8\"",
")",
";",
"if",
"(",
"isInvalidPath",
"(",
"decodedPath",
")",
")",
"{",
"return",
"true",
";",
"}",
"decodedPath",
"=",
"processPath",
"(",
"decodedPath",
")",
";",
"if",
"(",
"isInvalidPath",
"(",
"decodedPath",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"catch",
"(",
"IllegalArgumentException",
"|",
"UnsupportedEncodingException",
"ex",
")",
"{",
"// Should never happen...",
"}",
"}",
"return",
"false",
";",
"}"
] | Check whether the given path contains invalid escape sequences.
@param path the path to validate
@return {@code true} if the path is invalid, {@code false} otherwise | [
"Check",
"whether",
"the",
"given",
"path",
"contains",
"invalid",
"escape",
"sequences",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/GenericResourceRepository.java#L116-L135 |
23,810 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitCredentialsProviderFactory.java | GitCredentialsProviderFactory.createFor | @Deprecated
public CredentialsProvider createFor(String uri, String username, String password,
String passphrase) {
return createFor(uri, username, password, passphrase, false);
} | java | @Deprecated
public CredentialsProvider createFor(String uri, String username, String password,
String passphrase) {
return createFor(uri, username, password, passphrase, false);
} | [
"@",
"Deprecated",
"public",
"CredentialsProvider",
"createFor",
"(",
"String",
"uri",
",",
"String",
"username",
",",
"String",
"password",
",",
"String",
"passphrase",
")",
"{",
"return",
"createFor",
"(",
"uri",
",",
"username",
",",
"password",
",",
"passphrase",
",",
"false",
")",
";",
"}"
] | Search for a credential provider that will handle the specified URI. If not found,
and the username or passphrase has text, then create a default using the provided
username and password or passphrase. Otherwise null.
@param uri the URI of the repository (cannot be null)
@param username the username provided for the repository (may be null)
@param password the password provided for the repository (may be null)
@param passphrase the passphrase to unlock the ssh private key (may be null)
@return the first matched credentials provider or the default or null.
@deprecated in favour of
{@link #createFor(String, String, String, String, boolean)} | [
"Search",
"for",
"a",
"credential",
"provider",
"that",
"will",
"handle",
"the",
"specified",
"URI",
".",
"If",
"not",
"found",
"and",
"the",
"username",
"or",
"passphrase",
"has",
"text",
"then",
"create",
"a",
"default",
"using",
"the",
"provided",
"username",
"and",
"password",
"or",
"passphrase",
".",
"Otherwise",
"null",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitCredentialsProviderFactory.java#L59-L63 |
23,811 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitCredentialsProviderFactory.java | GitCredentialsProviderFactory.createFor | public CredentialsProvider createFor(String uri, String username, String password,
String passphrase, boolean skipSslValidation) {
CredentialsProvider provider = null;
if (awsAvailable() && AwsCodeCommitCredentialProvider.canHandle(uri)) {
this.logger
.debug("Constructing AwsCodeCommitCredentialProvider for URI " + uri);
AwsCodeCommitCredentialProvider aws = new AwsCodeCommitCredentialProvider();
aws.setUsername(username);
aws.setPassword(password);
provider = aws;
}
else if (hasText(username)) {
this.logger.debug(
"Constructing UsernamePasswordCredentialsProvider for URI " + uri);
provider = new UsernamePasswordCredentialsProvider(username,
password.toCharArray());
}
else if (hasText(passphrase)) {
this.logger
.debug("Constructing PassphraseCredentialsProvider for URI " + uri);
provider = new PassphraseCredentialsProvider(passphrase);
}
if (skipSslValidation && GitSkipSslValidationCredentialsProvider.canHandle(uri)) {
this.logger
.debug("Constructing GitSkipSslValidationCredentialsProvider for URI "
+ uri);
provider = new GitSkipSslValidationCredentialsProvider(provider);
}
if (provider == null) {
this.logger.debug("No credentials provider required for URI " + uri);
}
return provider;
} | java | public CredentialsProvider createFor(String uri, String username, String password,
String passphrase, boolean skipSslValidation) {
CredentialsProvider provider = null;
if (awsAvailable() && AwsCodeCommitCredentialProvider.canHandle(uri)) {
this.logger
.debug("Constructing AwsCodeCommitCredentialProvider for URI " + uri);
AwsCodeCommitCredentialProvider aws = new AwsCodeCommitCredentialProvider();
aws.setUsername(username);
aws.setPassword(password);
provider = aws;
}
else if (hasText(username)) {
this.logger.debug(
"Constructing UsernamePasswordCredentialsProvider for URI " + uri);
provider = new UsernamePasswordCredentialsProvider(username,
password.toCharArray());
}
else if (hasText(passphrase)) {
this.logger
.debug("Constructing PassphraseCredentialsProvider for URI " + uri);
provider = new PassphraseCredentialsProvider(passphrase);
}
if (skipSslValidation && GitSkipSslValidationCredentialsProvider.canHandle(uri)) {
this.logger
.debug("Constructing GitSkipSslValidationCredentialsProvider for URI "
+ uri);
provider = new GitSkipSslValidationCredentialsProvider(provider);
}
if (provider == null) {
this.logger.debug("No credentials provider required for URI " + uri);
}
return provider;
} | [
"public",
"CredentialsProvider",
"createFor",
"(",
"String",
"uri",
",",
"String",
"username",
",",
"String",
"password",
",",
"String",
"passphrase",
",",
"boolean",
"skipSslValidation",
")",
"{",
"CredentialsProvider",
"provider",
"=",
"null",
";",
"if",
"(",
"awsAvailable",
"(",
")",
"&&",
"AwsCodeCommitCredentialProvider",
".",
"canHandle",
"(",
"uri",
")",
")",
"{",
"this",
".",
"logger",
".",
"debug",
"(",
"\"Constructing AwsCodeCommitCredentialProvider for URI \"",
"+",
"uri",
")",
";",
"AwsCodeCommitCredentialProvider",
"aws",
"=",
"new",
"AwsCodeCommitCredentialProvider",
"(",
")",
";",
"aws",
".",
"setUsername",
"(",
"username",
")",
";",
"aws",
".",
"setPassword",
"(",
"password",
")",
";",
"provider",
"=",
"aws",
";",
"}",
"else",
"if",
"(",
"hasText",
"(",
"username",
")",
")",
"{",
"this",
".",
"logger",
".",
"debug",
"(",
"\"Constructing UsernamePasswordCredentialsProvider for URI \"",
"+",
"uri",
")",
";",
"provider",
"=",
"new",
"UsernamePasswordCredentialsProvider",
"(",
"username",
",",
"password",
".",
"toCharArray",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"hasText",
"(",
"passphrase",
")",
")",
"{",
"this",
".",
"logger",
".",
"debug",
"(",
"\"Constructing PassphraseCredentialsProvider for URI \"",
"+",
"uri",
")",
";",
"provider",
"=",
"new",
"PassphraseCredentialsProvider",
"(",
"passphrase",
")",
";",
"}",
"if",
"(",
"skipSslValidation",
"&&",
"GitSkipSslValidationCredentialsProvider",
".",
"canHandle",
"(",
"uri",
")",
")",
"{",
"this",
".",
"logger",
".",
"debug",
"(",
"\"Constructing GitSkipSslValidationCredentialsProvider for URI \"",
"+",
"uri",
")",
";",
"provider",
"=",
"new",
"GitSkipSslValidationCredentialsProvider",
"(",
"provider",
")",
";",
"}",
"if",
"(",
"provider",
"==",
"null",
")",
"{",
"this",
".",
"logger",
".",
"debug",
"(",
"\"No credentials provider required for URI \"",
"+",
"uri",
")",
";",
"}",
"return",
"provider",
";",
"}"
] | Search for a credential provider that will handle the specified URI. If not found,
and the username or passphrase has text, then create a default using the provided
username and password or passphrase.
If skipSslValidation is true and the URI has an https scheme, the default
credential provider's behaviour is modified to suppress any SSL validation errors
that occur when communicating via the URI.
Otherwise null.
@param uri the URI of the repository (cannot be null)
@param username the username provided for the repository (may be null)
@param password the password provided for the repository (may be null)
@param passphrase the passphrase to unlock the ssh private key (may be null)
@param skipSslValidation whether to skip SSL validation when connecting via HTTPS
@return the first matched credentials provider or the default or null. | [
"Search",
"for",
"a",
"credential",
"provider",
"that",
"will",
"handle",
"the",
"specified",
"URI",
".",
"If",
"not",
"found",
"and",
"the",
"username",
"or",
"passphrase",
"has",
"text",
"then",
"create",
"a",
"default",
"using",
"the",
"provided",
"username",
"and",
"password",
"or",
"passphrase",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitCredentialsProviderFactory.java#L82-L117 |
23,812 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java | JGitEnvironmentRepository.refresh | public String refresh(String label) {
Git git = null;
try {
git = createGitClient();
if (shouldPull(git)) {
FetchResult fetchStatus = fetch(git, label);
if (this.deleteUntrackedBranches && fetchStatus != null) {
deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(),
git);
}
// checkout after fetch so we can get any new branches, tags, ect.
checkout(git, label);
tryMerge(git, label);
}
else {
// nothing to update so just checkout and merge.
// Merge because remote branch could have been updated before
checkout(git, label);
tryMerge(git, label);
}
// always return what is currently HEAD as the version
return git.getRepository().findRef("HEAD").getObjectId().getName();
}
catch (RefNotFoundException e) {
throw new NoSuchLabelException("No such label: " + label, e);
}
catch (NoRemoteRepositoryException e) {
throw new NoSuchRepositoryException("No such repository: " + getUri(), e);
}
catch (GitAPIException e) {
throw new NoSuchRepositoryException(
"Cannot clone or checkout repository: " + getUri(), e);
}
catch (Exception e) {
throw new IllegalStateException("Cannot load environment", e);
}
finally {
try {
if (git != null) {
git.close();
}
}
catch (Exception e) {
this.logger.warn("Could not close git repository", e);
}
}
} | java | public String refresh(String label) {
Git git = null;
try {
git = createGitClient();
if (shouldPull(git)) {
FetchResult fetchStatus = fetch(git, label);
if (this.deleteUntrackedBranches && fetchStatus != null) {
deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(),
git);
}
// checkout after fetch so we can get any new branches, tags, ect.
checkout(git, label);
tryMerge(git, label);
}
else {
// nothing to update so just checkout and merge.
// Merge because remote branch could have been updated before
checkout(git, label);
tryMerge(git, label);
}
// always return what is currently HEAD as the version
return git.getRepository().findRef("HEAD").getObjectId().getName();
}
catch (RefNotFoundException e) {
throw new NoSuchLabelException("No such label: " + label, e);
}
catch (NoRemoteRepositoryException e) {
throw new NoSuchRepositoryException("No such repository: " + getUri(), e);
}
catch (GitAPIException e) {
throw new NoSuchRepositoryException(
"Cannot clone or checkout repository: " + getUri(), e);
}
catch (Exception e) {
throw new IllegalStateException("Cannot load environment", e);
}
finally {
try {
if (git != null) {
git.close();
}
}
catch (Exception e) {
this.logger.warn("Could not close git repository", e);
}
}
} | [
"public",
"String",
"refresh",
"(",
"String",
"label",
")",
"{",
"Git",
"git",
"=",
"null",
";",
"try",
"{",
"git",
"=",
"createGitClient",
"(",
")",
";",
"if",
"(",
"shouldPull",
"(",
"git",
")",
")",
"{",
"FetchResult",
"fetchStatus",
"=",
"fetch",
"(",
"git",
",",
"label",
")",
";",
"if",
"(",
"this",
".",
"deleteUntrackedBranches",
"&&",
"fetchStatus",
"!=",
"null",
")",
"{",
"deleteUntrackedLocalBranches",
"(",
"fetchStatus",
".",
"getTrackingRefUpdates",
"(",
")",
",",
"git",
")",
";",
"}",
"// checkout after fetch so we can get any new branches, tags, ect.",
"checkout",
"(",
"git",
",",
"label",
")",
";",
"tryMerge",
"(",
"git",
",",
"label",
")",
";",
"}",
"else",
"{",
"// nothing to update so just checkout and merge.",
"// Merge because remote branch could have been updated before",
"checkout",
"(",
"git",
",",
"label",
")",
";",
"tryMerge",
"(",
"git",
",",
"label",
")",
";",
"}",
"// always return what is currently HEAD as the version",
"return",
"git",
".",
"getRepository",
"(",
")",
".",
"findRef",
"(",
"\"HEAD\"",
")",
".",
"getObjectId",
"(",
")",
".",
"getName",
"(",
")",
";",
"}",
"catch",
"(",
"RefNotFoundException",
"e",
")",
"{",
"throw",
"new",
"NoSuchLabelException",
"(",
"\"No such label: \"",
"+",
"label",
",",
"e",
")",
";",
"}",
"catch",
"(",
"NoRemoteRepositoryException",
"e",
")",
"{",
"throw",
"new",
"NoSuchRepositoryException",
"(",
"\"No such repository: \"",
"+",
"getUri",
"(",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"GitAPIException",
"e",
")",
"{",
"throw",
"new",
"NoSuchRepositoryException",
"(",
"\"Cannot clone or checkout repository: \"",
"+",
"getUri",
"(",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot load environment\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"try",
"{",
"if",
"(",
"git",
"!=",
"null",
")",
"{",
"git",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"this",
".",
"logger",
".",
"warn",
"(",
"\"Could not close git repository\"",
",",
"e",
")",
";",
"}",
"}",
"}"
] | Get the working directory ready.
@param label label to refresh
@return head id | [
"Get",
"the",
"working",
"directory",
"ready",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java#L265-L311 |
23,813 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java | JGitEnvironmentRepository.initClonedRepository | private void initClonedRepository() throws GitAPIException, IOException {
if (!getUri().startsWith(FILE_URI_PREFIX)) {
deleteBaseDirIfExists();
Git git = cloneToBasedir();
if (git != null) {
git.close();
}
git = openGitRepository();
if (git != null) {
git.close();
}
}
} | java | private void initClonedRepository() throws GitAPIException, IOException {
if (!getUri().startsWith(FILE_URI_PREFIX)) {
deleteBaseDirIfExists();
Git git = cloneToBasedir();
if (git != null) {
git.close();
}
git = openGitRepository();
if (git != null) {
git.close();
}
}
} | [
"private",
"void",
"initClonedRepository",
"(",
")",
"throws",
"GitAPIException",
",",
"IOException",
"{",
"if",
"(",
"!",
"getUri",
"(",
")",
".",
"startsWith",
"(",
"FILE_URI_PREFIX",
")",
")",
"{",
"deleteBaseDirIfExists",
"(",
")",
";",
"Git",
"git",
"=",
"cloneToBasedir",
"(",
")",
";",
"if",
"(",
"git",
"!=",
"null",
")",
"{",
"git",
".",
"close",
"(",
")",
";",
"}",
"git",
"=",
"openGitRepository",
"(",
")",
";",
"if",
"(",
"git",
"!=",
"null",
")",
"{",
"git",
".",
"close",
"(",
")",
";",
"}",
"}",
"}"
] | Clones the remote repository and then opens a connection to it.
@throws GitAPIException when cloning fails
@throws IOException when repo opening fails | [
"Clones",
"the",
"remote",
"repository",
"and",
"then",
"opens",
"a",
"connection",
"to",
"it",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java#L337-L350 |
23,814 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java | JGitEnvironmentRepository.deleteUntrackedLocalBranches | private Collection<String> deleteUntrackedLocalBranches(
Collection<TrackingRefUpdate> trackingRefUpdates, Git git) {
if (CollectionUtils.isEmpty(trackingRefUpdates)) {
return Collections.emptyList();
}
Collection<String> branchesToDelete = new ArrayList<>();
for (TrackingRefUpdate trackingRefUpdate : trackingRefUpdates) {
ReceiveCommand receiveCommand = trackingRefUpdate.asReceiveCommand();
if (receiveCommand.getType() == DELETE) {
String localRefName = trackingRefUpdate.getLocalName();
if (StringUtils.startsWithIgnoreCase(localRefName,
LOCAL_BRANCH_REF_PREFIX)) {
String localBranchName = localRefName.substring(
LOCAL_BRANCH_REF_PREFIX.length(), localRefName.length());
branchesToDelete.add(localBranchName);
}
}
}
if (CollectionUtils.isEmpty(branchesToDelete)) {
return Collections.emptyList();
}
try {
// make sure that deleted branch not a current one
checkout(git, this.defaultLabel);
return deleteBranches(git, branchesToDelete);
}
catch (Exception ex) {
String message = format("Failed to delete %s branches.", branchesToDelete);
warn(message, ex);
return Collections.emptyList();
}
} | java | private Collection<String> deleteUntrackedLocalBranches(
Collection<TrackingRefUpdate> trackingRefUpdates, Git git) {
if (CollectionUtils.isEmpty(trackingRefUpdates)) {
return Collections.emptyList();
}
Collection<String> branchesToDelete = new ArrayList<>();
for (TrackingRefUpdate trackingRefUpdate : trackingRefUpdates) {
ReceiveCommand receiveCommand = trackingRefUpdate.asReceiveCommand();
if (receiveCommand.getType() == DELETE) {
String localRefName = trackingRefUpdate.getLocalName();
if (StringUtils.startsWithIgnoreCase(localRefName,
LOCAL_BRANCH_REF_PREFIX)) {
String localBranchName = localRefName.substring(
LOCAL_BRANCH_REF_PREFIX.length(), localRefName.length());
branchesToDelete.add(localBranchName);
}
}
}
if (CollectionUtils.isEmpty(branchesToDelete)) {
return Collections.emptyList();
}
try {
// make sure that deleted branch not a current one
checkout(git, this.defaultLabel);
return deleteBranches(git, branchesToDelete);
}
catch (Exception ex) {
String message = format("Failed to delete %s branches.", branchesToDelete);
warn(message, ex);
return Collections.emptyList();
}
} | [
"private",
"Collection",
"<",
"String",
">",
"deleteUntrackedLocalBranches",
"(",
"Collection",
"<",
"TrackingRefUpdate",
">",
"trackingRefUpdates",
",",
"Git",
"git",
")",
"{",
"if",
"(",
"CollectionUtils",
".",
"isEmpty",
"(",
"trackingRefUpdates",
")",
")",
"{",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"}",
"Collection",
"<",
"String",
">",
"branchesToDelete",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"TrackingRefUpdate",
"trackingRefUpdate",
":",
"trackingRefUpdates",
")",
"{",
"ReceiveCommand",
"receiveCommand",
"=",
"trackingRefUpdate",
".",
"asReceiveCommand",
"(",
")",
";",
"if",
"(",
"receiveCommand",
".",
"getType",
"(",
")",
"==",
"DELETE",
")",
"{",
"String",
"localRefName",
"=",
"trackingRefUpdate",
".",
"getLocalName",
"(",
")",
";",
"if",
"(",
"StringUtils",
".",
"startsWithIgnoreCase",
"(",
"localRefName",
",",
"LOCAL_BRANCH_REF_PREFIX",
")",
")",
"{",
"String",
"localBranchName",
"=",
"localRefName",
".",
"substring",
"(",
"LOCAL_BRANCH_REF_PREFIX",
".",
"length",
"(",
")",
",",
"localRefName",
".",
"length",
"(",
")",
")",
";",
"branchesToDelete",
".",
"add",
"(",
"localBranchName",
")",
";",
"}",
"}",
"}",
"if",
"(",
"CollectionUtils",
".",
"isEmpty",
"(",
"branchesToDelete",
")",
")",
"{",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"}",
"try",
"{",
"// make sure that deleted branch not a current one",
"checkout",
"(",
"git",
",",
"this",
".",
"defaultLabel",
")",
";",
"return",
"deleteBranches",
"(",
"git",
",",
"branchesToDelete",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"String",
"message",
"=",
"format",
"(",
"\"Failed to delete %s branches.\"",
",",
"branchesToDelete",
")",
";",
"warn",
"(",
"message",
",",
"ex",
")",
";",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"}",
"}"
] | Deletes local branches if corresponding remote branch was removed.
@param trackingRefUpdates list of tracking ref updates
@param git git instance
@return list of deleted branches | [
"Deletes",
"local",
"branches",
"if",
"corresponding",
"remote",
"branch",
"was",
"removed",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java#L358-L392 |
23,815 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java | JGitEnvironmentRepository.copyRepository | private synchronized Git copyRepository() throws IOException, GitAPIException {
deleteBaseDirIfExists();
getBasedir().mkdirs();
Assert.state(getBasedir().exists(), "Could not create basedir: " + getBasedir());
if (getUri().startsWith(FILE_URI_PREFIX)) {
return copyFromLocalRepository();
}
else {
return cloneToBasedir();
}
} | java | private synchronized Git copyRepository() throws IOException, GitAPIException {
deleteBaseDirIfExists();
getBasedir().mkdirs();
Assert.state(getBasedir().exists(), "Could not create basedir: " + getBasedir());
if (getUri().startsWith(FILE_URI_PREFIX)) {
return copyFromLocalRepository();
}
else {
return cloneToBasedir();
}
} | [
"private",
"synchronized",
"Git",
"copyRepository",
"(",
")",
"throws",
"IOException",
",",
"GitAPIException",
"{",
"deleteBaseDirIfExists",
"(",
")",
";",
"getBasedir",
"(",
")",
".",
"mkdirs",
"(",
")",
";",
"Assert",
".",
"state",
"(",
"getBasedir",
"(",
")",
".",
"exists",
"(",
")",
",",
"\"Could not create basedir: \"",
"+",
"getBasedir",
"(",
")",
")",
";",
"if",
"(",
"getUri",
"(",
")",
".",
"startsWith",
"(",
"FILE_URI_PREFIX",
")",
")",
"{",
"return",
"copyFromLocalRepository",
"(",
")",
";",
"}",
"else",
"{",
"return",
"cloneToBasedir",
"(",
")",
";",
"}",
"}"
] | request). | [
"request",
")",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java#L556-L566 |
23,816 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java | AwsCodeCommitCredentialProvider.canonicalRequestDigest | private static byte[] canonicalRequestDigest(URIish uri)
throws NoSuchAlgorithmException {
StringBuilder canonicalRequest = new StringBuilder();
canonicalRequest.append("GIT\n") // codecommit uses GIT as the request method
.append(uri.getPath()).append("\n") // URI request path
.append("\n") // Query string, always empty for codecommit
// Next is canonical headers, codecommit only requires the host header
.append("host:").append(uri.getHost()).append("\n").append("\n") // canonical
// headers
// are
// always
// terminated
// by
// newline
.append("host\n"); // The list of canonical headers, only one for
// codecommit
MessageDigest digest = MessageDigest.getInstance(SHA_256);
return digest.digest(canonicalRequest.toString().getBytes());
} | java | private static byte[] canonicalRequestDigest(URIish uri)
throws NoSuchAlgorithmException {
StringBuilder canonicalRequest = new StringBuilder();
canonicalRequest.append("GIT\n") // codecommit uses GIT as the request method
.append(uri.getPath()).append("\n") // URI request path
.append("\n") // Query string, always empty for codecommit
// Next is canonical headers, codecommit only requires the host header
.append("host:").append(uri.getHost()).append("\n").append("\n") // canonical
// headers
// are
// always
// terminated
// by
// newline
.append("host\n"); // The list of canonical headers, only one for
// codecommit
MessageDigest digest = MessageDigest.getInstance(SHA_256);
return digest.digest(canonicalRequest.toString().getBytes());
} | [
"private",
"static",
"byte",
"[",
"]",
"canonicalRequestDigest",
"(",
"URIish",
"uri",
")",
"throws",
"NoSuchAlgorithmException",
"{",
"StringBuilder",
"canonicalRequest",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"canonicalRequest",
".",
"append",
"(",
"\"GIT\\n\"",
")",
"// codecommit uses GIT as the request method",
".",
"append",
"(",
"uri",
".",
"getPath",
"(",
")",
")",
".",
"append",
"(",
"\"\\n\"",
")",
"// URI request path",
".",
"append",
"(",
"\"\\n\"",
")",
"// Query string, always empty for codecommit",
"// Next is canonical headers, codecommit only requires the host header",
".",
"append",
"(",
"\"host:\"",
")",
".",
"append",
"(",
"uri",
".",
"getHost",
"(",
")",
")",
".",
"append",
"(",
"\"\\n\"",
")",
".",
"append",
"(",
"\"\\n\"",
")",
"// canonical",
"// headers",
"// are",
"// always",
"// terminated",
"// by",
"// newline",
".",
"append",
"(",
"\"host\\n\"",
")",
";",
"// The list of canonical headers, only one for",
"// codecommit",
"MessageDigest",
"digest",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"SHA_256",
")",
";",
"return",
"digest",
".",
"digest",
"(",
"canonicalRequest",
".",
"toString",
"(",
")",
".",
"getBytes",
"(",
")",
")",
";",
"}"
] | Creates a message digest.
@param uri uri to process
@return a message digest
@throws NoSuchAlgorithmException when the SHA 256 algorithm is not found | [
"Creates",
"a",
"message",
"digest",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java#L160-L180 |
23,817 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java | AwsCodeCommitCredentialProvider.get | @Override
public boolean get(URIish uri, CredentialItem... items)
throws UnsupportedCredentialItem {
String codeCommitPassword;
String awsAccessKey;
String awsSecretKey;
try {
AWSCredentials awsCredentials = retrieveAwsCredentials();
StringBuilder awsKey = new StringBuilder();
awsKey.append(awsCredentials.getAWSAccessKeyId());
awsSecretKey = awsCredentials.getAWSSecretKey();
if (awsCredentials instanceof AWSSessionCredentials) {
AWSSessionCredentials sessionCreds = (AWSSessionCredentials) awsCredentials;
if (sessionCreds.getSessionToken() != null) {
awsKey.append('%').append(sessionCreds.getSessionToken());
}
}
awsAccessKey = awsKey.toString();
}
catch (Throwable t) {
this.logger.warn("Unable to retrieve AWS Credentials", t);
return false;
}
try {
codeCommitPassword = calculateCodeCommitPassword(uri, awsSecretKey);
}
catch (Throwable t) {
this.logger.warn("Error calculating the AWS CodeCommit password", t);
return false;
}
for (CredentialItem i : items) {
if (i instanceof CredentialItem.Username) {
((CredentialItem.Username) i).setValue(awsAccessKey);
this.logger.trace("Returning username " + awsAccessKey);
continue;
}
if (i instanceof CredentialItem.Password) {
((CredentialItem.Password) i).setValue(codeCommitPassword.toCharArray());
this.logger.trace("Returning password " + codeCommitPassword);
continue;
}
if (i instanceof CredentialItem.StringType
&& i.getPromptText().equals("Password: ")) { //$NON-NLS-1$
((CredentialItem.StringType) i).setValue(codeCommitPassword);
this.logger.trace("Returning password string " + codeCommitPassword);
continue;
}
throw new UnsupportedCredentialItem(uri,
i.getClass().getName() + ":" + i.getPromptText()); //$NON-NLS-1$
}
return true;
} | java | @Override
public boolean get(URIish uri, CredentialItem... items)
throws UnsupportedCredentialItem {
String codeCommitPassword;
String awsAccessKey;
String awsSecretKey;
try {
AWSCredentials awsCredentials = retrieveAwsCredentials();
StringBuilder awsKey = new StringBuilder();
awsKey.append(awsCredentials.getAWSAccessKeyId());
awsSecretKey = awsCredentials.getAWSSecretKey();
if (awsCredentials instanceof AWSSessionCredentials) {
AWSSessionCredentials sessionCreds = (AWSSessionCredentials) awsCredentials;
if (sessionCreds.getSessionToken() != null) {
awsKey.append('%').append(sessionCreds.getSessionToken());
}
}
awsAccessKey = awsKey.toString();
}
catch (Throwable t) {
this.logger.warn("Unable to retrieve AWS Credentials", t);
return false;
}
try {
codeCommitPassword = calculateCodeCommitPassword(uri, awsSecretKey);
}
catch (Throwable t) {
this.logger.warn("Error calculating the AWS CodeCommit password", t);
return false;
}
for (CredentialItem i : items) {
if (i instanceof CredentialItem.Username) {
((CredentialItem.Username) i).setValue(awsAccessKey);
this.logger.trace("Returning username " + awsAccessKey);
continue;
}
if (i instanceof CredentialItem.Password) {
((CredentialItem.Password) i).setValue(codeCommitPassword.toCharArray());
this.logger.trace("Returning password " + codeCommitPassword);
continue;
}
if (i instanceof CredentialItem.StringType
&& i.getPromptText().equals("Password: ")) { //$NON-NLS-1$
((CredentialItem.StringType) i).setValue(codeCommitPassword);
this.logger.trace("Returning password string " + codeCommitPassword);
continue;
}
throw new UnsupportedCredentialItem(uri,
i.getClass().getName() + ":" + i.getPromptText()); //$NON-NLS-1$
}
return true;
} | [
"@",
"Override",
"public",
"boolean",
"get",
"(",
"URIish",
"uri",
",",
"CredentialItem",
"...",
"items",
")",
"throws",
"UnsupportedCredentialItem",
"{",
"String",
"codeCommitPassword",
";",
"String",
"awsAccessKey",
";",
"String",
"awsSecretKey",
";",
"try",
"{",
"AWSCredentials",
"awsCredentials",
"=",
"retrieveAwsCredentials",
"(",
")",
";",
"StringBuilder",
"awsKey",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"awsKey",
".",
"append",
"(",
"awsCredentials",
".",
"getAWSAccessKeyId",
"(",
")",
")",
";",
"awsSecretKey",
"=",
"awsCredentials",
".",
"getAWSSecretKey",
"(",
")",
";",
"if",
"(",
"awsCredentials",
"instanceof",
"AWSSessionCredentials",
")",
"{",
"AWSSessionCredentials",
"sessionCreds",
"=",
"(",
"AWSSessionCredentials",
")",
"awsCredentials",
";",
"if",
"(",
"sessionCreds",
".",
"getSessionToken",
"(",
")",
"!=",
"null",
")",
"{",
"awsKey",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"sessionCreds",
".",
"getSessionToken",
"(",
")",
")",
";",
"}",
"}",
"awsAccessKey",
"=",
"awsKey",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"this",
".",
"logger",
".",
"warn",
"(",
"\"Unable to retrieve AWS Credentials\"",
",",
"t",
")",
";",
"return",
"false",
";",
"}",
"try",
"{",
"codeCommitPassword",
"=",
"calculateCodeCommitPassword",
"(",
"uri",
",",
"awsSecretKey",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"this",
".",
"logger",
".",
"warn",
"(",
"\"Error calculating the AWS CodeCommit password\"",
",",
"t",
")",
";",
"return",
"false",
";",
"}",
"for",
"(",
"CredentialItem",
"i",
":",
"items",
")",
"{",
"if",
"(",
"i",
"instanceof",
"CredentialItem",
".",
"Username",
")",
"{",
"(",
"(",
"CredentialItem",
".",
"Username",
")",
"i",
")",
".",
"setValue",
"(",
"awsAccessKey",
")",
";",
"this",
".",
"logger",
".",
"trace",
"(",
"\"Returning username \"",
"+",
"awsAccessKey",
")",
";",
"continue",
";",
"}",
"if",
"(",
"i",
"instanceof",
"CredentialItem",
".",
"Password",
")",
"{",
"(",
"(",
"CredentialItem",
".",
"Password",
")",
"i",
")",
".",
"setValue",
"(",
"codeCommitPassword",
".",
"toCharArray",
"(",
")",
")",
";",
"this",
".",
"logger",
".",
"trace",
"(",
"\"Returning password \"",
"+",
"codeCommitPassword",
")",
";",
"continue",
";",
"}",
"if",
"(",
"i",
"instanceof",
"CredentialItem",
".",
"StringType",
"&&",
"i",
".",
"getPromptText",
"(",
")",
".",
"equals",
"(",
"\"Password: \"",
")",
")",
"{",
"//$NON-NLS-1$",
"(",
"(",
"CredentialItem",
".",
"StringType",
")",
"i",
")",
".",
"setValue",
"(",
"codeCommitPassword",
")",
";",
"this",
".",
"logger",
".",
"trace",
"(",
"\"Returning password string \"",
"+",
"codeCommitPassword",
")",
";",
"continue",
";",
"}",
"throw",
"new",
"UnsupportedCredentialItem",
"(",
"uri",
",",
"i",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\":\"",
"+",
"i",
".",
"getPromptText",
"(",
")",
")",
";",
"//$NON-NLS-1$",
"}",
"return",
"true",
";",
"}"
] | Get the username and password to use for the given uri.
@see org.eclipse.jgit.transport.CredentialsProvider#get(org.eclipse.jgit.transport.URIish,
org.eclipse.jgit.transport.CredentialItem[]) | [
"Get",
"the",
"username",
"and",
"password",
"to",
"use",
"for",
"the",
"given",
"uri",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java#L284-L337 |
23,818 | spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/PassphraseCredentialsProvider.java | PassphraseCredentialsProvider.get | @Override
public boolean get(URIish uri, CredentialItem... items)
throws UnsupportedCredentialItem {
for (final CredentialItem item : items) {
if (item instanceof CredentialItem.StringType
&& item.getPromptText().startsWith(PROMPT)) {
((CredentialItem.StringType) item).setValue(this.passphrase);
continue;
}
throw new UnsupportedCredentialItem(uri,
item.getClass().getName() + ":" + item.getPromptText());
}
return true;
} | java | @Override
public boolean get(URIish uri, CredentialItem... items)
throws UnsupportedCredentialItem {
for (final CredentialItem item : items) {
if (item instanceof CredentialItem.StringType
&& item.getPromptText().startsWith(PROMPT)) {
((CredentialItem.StringType) item).setValue(this.passphrase);
continue;
}
throw new UnsupportedCredentialItem(uri,
item.getClass().getName() + ":" + item.getPromptText());
}
return true;
} | [
"@",
"Override",
"public",
"boolean",
"get",
"(",
"URIish",
"uri",
",",
"CredentialItem",
"...",
"items",
")",
"throws",
"UnsupportedCredentialItem",
"{",
"for",
"(",
"final",
"CredentialItem",
"item",
":",
"items",
")",
"{",
"if",
"(",
"item",
"instanceof",
"CredentialItem",
".",
"StringType",
"&&",
"item",
".",
"getPromptText",
"(",
")",
".",
"startsWith",
"(",
"PROMPT",
")",
")",
"{",
"(",
"(",
"CredentialItem",
".",
"StringType",
")",
"item",
")",
".",
"setValue",
"(",
"this",
".",
"passphrase",
")",
";",
"continue",
";",
"}",
"throw",
"new",
"UnsupportedCredentialItem",
"(",
"uri",
",",
"item",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\":\"",
"+",
"item",
".",
"getPromptText",
"(",
")",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Ask for the credential items to be populated with the passphrase.
@param uri the URI of the remote resource that needs authentication.
@param items the items the application requires to complete authentication.
@return {@code true} if the request was successful and values were supplied;
{@code false} if the user canceled the request and did not supply all requested
values.
@throws UnsupportedCredentialItem if one of the items supplied is not supported. | [
"Ask",
"for",
"the",
"credential",
"items",
"to",
"be",
"populated",
"with",
"the",
"passphrase",
"."
] | 6b99631f78bac4e1b521d2cc126c8b2da45d1f1f | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/PassphraseCredentialsProvider.java#L83-L96 |
23,819 | google/closure-compiler | src/com/google/javascript/jscomp/GuardedCallback.java | GuardedCallback.isGuarded | boolean isGuarded(T resource) {
// Check if this polyfill is already guarded. If so, return true right away.
if (guarded.contains(resource)) {
return true;
}
// If not, see if this is itself a feature check guard. This is
// defined as a usage of the polyfill in such a way that throws
// away the actual value and only cares about its truthiness or
// typeof. We walk up the ancestor tree through a small set of
// node types and if this is detected to be a guard, then the
// conditional node is marked as a guard for this polyfill.
Context context = contextStack.peek();
if (!context.safe) {
return false;
}
// Loop over all the linked conditionals and register this as a guard.
while (context != null && context.conditional != null) {
registeredGuards.put(context.conditional, resource);
context = context.linked;
}
return true;
} | java | boolean isGuarded(T resource) {
// Check if this polyfill is already guarded. If so, return true right away.
if (guarded.contains(resource)) {
return true;
}
// If not, see if this is itself a feature check guard. This is
// defined as a usage of the polyfill in such a way that throws
// away the actual value and only cares about its truthiness or
// typeof. We walk up the ancestor tree through a small set of
// node types and if this is detected to be a guard, then the
// conditional node is marked as a guard for this polyfill.
Context context = contextStack.peek();
if (!context.safe) {
return false;
}
// Loop over all the linked conditionals and register this as a guard.
while (context != null && context.conditional != null) {
registeredGuards.put(context.conditional, resource);
context = context.linked;
}
return true;
} | [
"boolean",
"isGuarded",
"(",
"T",
"resource",
")",
"{",
"// Check if this polyfill is already guarded. If so, return true right away.",
"if",
"(",
"guarded",
".",
"contains",
"(",
"resource",
")",
")",
"{",
"return",
"true",
";",
"}",
"// If not, see if this is itself a feature check guard. This is",
"// defined as a usage of the polyfill in such a way that throws",
"// away the actual value and only cares about its truthiness or",
"// typeof. We walk up the ancestor tree through a small set of",
"// node types and if this is detected to be a guard, then the",
"// conditional node is marked as a guard for this polyfill.",
"Context",
"context",
"=",
"contextStack",
".",
"peek",
"(",
")",
";",
"if",
"(",
"!",
"context",
".",
"safe",
")",
"{",
"return",
"false",
";",
"}",
"// Loop over all the linked conditionals and register this as a guard.",
"while",
"(",
"context",
"!=",
"null",
"&&",
"context",
".",
"conditional",
"!=",
"null",
")",
"{",
"registeredGuards",
".",
"put",
"(",
"context",
".",
"conditional",
",",
"resource",
")",
";",
"context",
"=",
"context",
".",
"linked",
";",
"}",
"return",
"true",
";",
"}"
] | Determines if the given resource is guarded, either intrinsically or
conditionally. If the former, any ancestor conditional nodes are
registered as feature-testing the resource. | [
"Determines",
"if",
"the",
"given",
"resource",
"is",
"guarded",
"either",
"intrinsically",
"or",
"conditionally",
".",
"If",
"the",
"former",
"any",
"ancestor",
"conditional",
"nodes",
"are",
"registered",
"as",
"feature",
"-",
"testing",
"the",
"resource",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/GuardedCallback.java#L244-L267 |
23,820 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.prioritizeFromEntryNode | private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
PriorityQueue<DiGraphNode<Node, Branch>> worklist =
new PriorityQueue<>(10, priorityComparator);
worklist.add(entry);
while (!worklist.isEmpty()) {
DiGraphNode<Node, Branch> current = worklist.remove();
if (nodePriorities.containsKey(current)) {
continue;
}
nodePriorities.put(current, ++priorityCounter);
List<DiGraphNode<Node, Branch>> successors = cfg.getDirectedSuccNodes(current);
worklist.addAll(successors);
}
} | java | private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
PriorityQueue<DiGraphNode<Node, Branch>> worklist =
new PriorityQueue<>(10, priorityComparator);
worklist.add(entry);
while (!worklist.isEmpty()) {
DiGraphNode<Node, Branch> current = worklist.remove();
if (nodePriorities.containsKey(current)) {
continue;
}
nodePriorities.put(current, ++priorityCounter);
List<DiGraphNode<Node, Branch>> successors = cfg.getDirectedSuccNodes(current);
worklist.addAll(successors);
}
} | [
"private",
"void",
"prioritizeFromEntryNode",
"(",
"DiGraphNode",
"<",
"Node",
",",
"Branch",
">",
"entry",
")",
"{",
"PriorityQueue",
"<",
"DiGraphNode",
"<",
"Node",
",",
"Branch",
">",
">",
"worklist",
"=",
"new",
"PriorityQueue",
"<>",
"(",
"10",
",",
"priorityComparator",
")",
";",
"worklist",
".",
"add",
"(",
"entry",
")",
";",
"while",
"(",
"!",
"worklist",
".",
"isEmpty",
"(",
")",
")",
"{",
"DiGraphNode",
"<",
"Node",
",",
"Branch",
">",
"current",
"=",
"worklist",
".",
"remove",
"(",
")",
";",
"if",
"(",
"nodePriorities",
".",
"containsKey",
"(",
"current",
")",
")",
"{",
"continue",
";",
"}",
"nodePriorities",
".",
"put",
"(",
"current",
",",
"++",
"priorityCounter",
")",
";",
"List",
"<",
"DiGraphNode",
"<",
"Node",
",",
"Branch",
">",
">",
"successors",
"=",
"cfg",
".",
"getDirectedSuccNodes",
"(",
"current",
")",
";",
"worklist",
".",
"addAll",
"(",
"successors",
")",
";",
"}",
"}"
] | Given an entry node, find all the nodes reachable from that node
and prioritize them. | [
"Given",
"an",
"entry",
"node",
"find",
"all",
"the",
"nodes",
"reachable",
"from",
"that",
"node",
"and",
"prioritize",
"them",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L196-L212 |
23,821 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.computeFallThrough | static Node computeFallThrough(Node n) {
switch (n.getToken()) {
case DO:
case FOR:
return computeFallThrough(n.getFirstChild());
case FOR_IN:
case FOR_OF:
case FOR_AWAIT_OF:
return n.getSecondChild();
case LABEL:
return computeFallThrough(n.getLastChild());
default:
return n;
}
} | java | static Node computeFallThrough(Node n) {
switch (n.getToken()) {
case DO:
case FOR:
return computeFallThrough(n.getFirstChild());
case FOR_IN:
case FOR_OF:
case FOR_AWAIT_OF:
return n.getSecondChild();
case LABEL:
return computeFallThrough(n.getLastChild());
default:
return n;
}
} | [
"static",
"Node",
"computeFallThrough",
"(",
"Node",
"n",
")",
"{",
"switch",
"(",
"n",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"DO",
":",
"case",
"FOR",
":",
"return",
"computeFallThrough",
"(",
"n",
".",
"getFirstChild",
"(",
")",
")",
";",
"case",
"FOR_IN",
":",
"case",
"FOR_OF",
":",
"case",
"FOR_AWAIT_OF",
":",
"return",
"n",
".",
"getSecondChild",
"(",
")",
";",
"case",
"LABEL",
":",
"return",
"computeFallThrough",
"(",
"n",
".",
"getLastChild",
"(",
")",
")",
";",
"default",
":",
"return",
"n",
";",
"}",
"}"
] | Computes the destination node of n when we want to fallthrough into the
subtree of n. We don't always create a CFG edge into n itself because of
DOs and FORs. | [
"Computes",
"the",
"destination",
"node",
"of",
"n",
"when",
"we",
"want",
"to",
"fallthrough",
"into",
"the",
"subtree",
"of",
"n",
".",
"We",
"don",
"t",
"always",
"create",
"a",
"CFG",
"edge",
"into",
"n",
"itself",
"because",
"of",
"DOs",
"and",
"FORs",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L836-L850 |
23,822 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.createEdge | private void createEdge(Node fromNode, ControlFlowGraph.Branch branch,
Node toNode) {
cfg.createNode(fromNode);
cfg.createNode(toNode);
cfg.connectIfNotFound(fromNode, branch, toNode);
} | java | private void createEdge(Node fromNode, ControlFlowGraph.Branch branch,
Node toNode) {
cfg.createNode(fromNode);
cfg.createNode(toNode);
cfg.connectIfNotFound(fromNode, branch, toNode);
} | [
"private",
"void",
"createEdge",
"(",
"Node",
"fromNode",
",",
"ControlFlowGraph",
".",
"Branch",
"branch",
",",
"Node",
"toNode",
")",
"{",
"cfg",
".",
"createNode",
"(",
"fromNode",
")",
";",
"cfg",
".",
"createNode",
"(",
"toNode",
")",
";",
"cfg",
".",
"connectIfNotFound",
"(",
"fromNode",
",",
"branch",
",",
"toNode",
")",
";",
"}"
] | Connects the two nodes in the control flow graph.
@param fromNode Source.
@param toNode Destination. | [
"Connects",
"the",
"two",
"nodes",
"in",
"the",
"control",
"flow",
"graph",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L858-L863 |
23,823 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.connectToPossibleExceptionHandler | private void connectToPossibleExceptionHandler(Node cfgNode, Node target) {
if (mayThrowException(target) && !exceptionHandler.isEmpty()) {
Node lastJump = cfgNode;
for (Node handler : exceptionHandler) {
if (handler.isFunction()) {
return;
}
checkState(handler.isTry());
Node catchBlock = NodeUtil.getCatchBlock(handler);
boolean lastJumpInCatchBlock = false;
for (Node ancestor : lastJump.getAncestors()) {
if (ancestor == handler) {
break;
} else if (ancestor == catchBlock) {
lastJumpInCatchBlock = true;
break;
}
}
// No catch but a FINALLY, or lastJump is inside the catch block.
if (!NodeUtil.hasCatchHandler(catchBlock) || lastJumpInCatchBlock) {
if (lastJump == cfgNode) {
createEdge(cfgNode, Branch.ON_EX, handler.getLastChild());
} else {
finallyMap.put(lastJump, handler.getLastChild());
}
} else { // Has a catch.
if (lastJump == cfgNode) {
createEdge(cfgNode, Branch.ON_EX, catchBlock);
return;
} else {
finallyMap.put(lastJump, catchBlock);
}
}
lastJump = handler;
}
}
} | java | private void connectToPossibleExceptionHandler(Node cfgNode, Node target) {
if (mayThrowException(target) && !exceptionHandler.isEmpty()) {
Node lastJump = cfgNode;
for (Node handler : exceptionHandler) {
if (handler.isFunction()) {
return;
}
checkState(handler.isTry());
Node catchBlock = NodeUtil.getCatchBlock(handler);
boolean lastJumpInCatchBlock = false;
for (Node ancestor : lastJump.getAncestors()) {
if (ancestor == handler) {
break;
} else if (ancestor == catchBlock) {
lastJumpInCatchBlock = true;
break;
}
}
// No catch but a FINALLY, or lastJump is inside the catch block.
if (!NodeUtil.hasCatchHandler(catchBlock) || lastJumpInCatchBlock) {
if (lastJump == cfgNode) {
createEdge(cfgNode, Branch.ON_EX, handler.getLastChild());
} else {
finallyMap.put(lastJump, handler.getLastChild());
}
} else { // Has a catch.
if (lastJump == cfgNode) {
createEdge(cfgNode, Branch.ON_EX, catchBlock);
return;
} else {
finallyMap.put(lastJump, catchBlock);
}
}
lastJump = handler;
}
}
} | [
"private",
"void",
"connectToPossibleExceptionHandler",
"(",
"Node",
"cfgNode",
",",
"Node",
"target",
")",
"{",
"if",
"(",
"mayThrowException",
"(",
"target",
")",
"&&",
"!",
"exceptionHandler",
".",
"isEmpty",
"(",
")",
")",
"{",
"Node",
"lastJump",
"=",
"cfgNode",
";",
"for",
"(",
"Node",
"handler",
":",
"exceptionHandler",
")",
"{",
"if",
"(",
"handler",
".",
"isFunction",
"(",
")",
")",
"{",
"return",
";",
"}",
"checkState",
"(",
"handler",
".",
"isTry",
"(",
")",
")",
";",
"Node",
"catchBlock",
"=",
"NodeUtil",
".",
"getCatchBlock",
"(",
"handler",
")",
";",
"boolean",
"lastJumpInCatchBlock",
"=",
"false",
";",
"for",
"(",
"Node",
"ancestor",
":",
"lastJump",
".",
"getAncestors",
"(",
")",
")",
"{",
"if",
"(",
"ancestor",
"==",
"handler",
")",
"{",
"break",
";",
"}",
"else",
"if",
"(",
"ancestor",
"==",
"catchBlock",
")",
"{",
"lastJumpInCatchBlock",
"=",
"true",
";",
"break",
";",
"}",
"}",
"// No catch but a FINALLY, or lastJump is inside the catch block.",
"if",
"(",
"!",
"NodeUtil",
".",
"hasCatchHandler",
"(",
"catchBlock",
")",
"||",
"lastJumpInCatchBlock",
")",
"{",
"if",
"(",
"lastJump",
"==",
"cfgNode",
")",
"{",
"createEdge",
"(",
"cfgNode",
",",
"Branch",
".",
"ON_EX",
",",
"handler",
".",
"getLastChild",
"(",
")",
")",
";",
"}",
"else",
"{",
"finallyMap",
".",
"put",
"(",
"lastJump",
",",
"handler",
".",
"getLastChild",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"// Has a catch.",
"if",
"(",
"lastJump",
"==",
"cfgNode",
")",
"{",
"createEdge",
"(",
"cfgNode",
",",
"Branch",
".",
"ON_EX",
",",
"catchBlock",
")",
";",
"return",
";",
"}",
"else",
"{",
"finallyMap",
".",
"put",
"(",
"lastJump",
",",
"catchBlock",
")",
";",
"}",
"}",
"lastJump",
"=",
"handler",
";",
"}",
"}",
"}"
] | Connects cfgNode to the proper CATCH block if target subtree might throw
an exception. If there are FINALLY blocks reached before a CATCH, it will
make the corresponding entry in finallyMap. | [
"Connects",
"cfgNode",
"to",
"the",
"proper",
"CATCH",
"block",
"if",
"target",
"subtree",
"might",
"throw",
"an",
"exception",
".",
"If",
"there",
"are",
"FINALLY",
"blocks",
"reached",
"before",
"a",
"CATCH",
"it",
"will",
"make",
"the",
"corresponding",
"entry",
"in",
"finallyMap",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L870-L908 |
23,824 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.isBreakTarget | public static boolean isBreakTarget(Node target, String label) {
return isBreakStructure(target, label != null) &&
matchLabel(target.getParent(), label);
} | java | public static boolean isBreakTarget(Node target, String label) {
return isBreakStructure(target, label != null) &&
matchLabel(target.getParent(), label);
} | [
"public",
"static",
"boolean",
"isBreakTarget",
"(",
"Node",
"target",
",",
"String",
"label",
")",
"{",
"return",
"isBreakStructure",
"(",
"target",
",",
"label",
"!=",
"null",
")",
"&&",
"matchLabel",
"(",
"target",
".",
"getParent",
"(",
")",
",",
"label",
")",
";",
"}"
] | Checks if target is actually the break target of labeled continue. The
label can be null if it is an unlabeled break. | [
"Checks",
"if",
"target",
"is",
"actually",
"the",
"break",
"target",
"of",
"labeled",
"continue",
".",
"The",
"label",
"can",
"be",
"null",
"if",
"it",
"is",
"an",
"unlabeled",
"break",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L928-L931 |
23,825 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.isContinueTarget | static boolean isContinueTarget(
Node target, String label) {
return NodeUtil.isLoopStructure(target) && matchLabel(target.getParent(), label);
} | java | static boolean isContinueTarget(
Node target, String label) {
return NodeUtil.isLoopStructure(target) && matchLabel(target.getParent(), label);
} | [
"static",
"boolean",
"isContinueTarget",
"(",
"Node",
"target",
",",
"String",
"label",
")",
"{",
"return",
"NodeUtil",
".",
"isLoopStructure",
"(",
"target",
")",
"&&",
"matchLabel",
"(",
"target",
".",
"getParent",
"(",
")",
",",
"label",
")",
";",
"}"
] | Checks if target is actually the continue target of labeled continue. The
label can be null if it is an unlabeled continue. | [
"Checks",
"if",
"target",
"is",
"actually",
"the",
"continue",
"target",
"of",
"labeled",
"continue",
".",
"The",
"label",
"can",
"be",
"null",
"if",
"it",
"is",
"an",
"unlabeled",
"continue",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L937-L940 |
23,826 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.matchLabel | private static boolean matchLabel(Node target, String label) {
if (label == null) {
return true;
}
while (target.isLabel()) {
if (target.getFirstChild().getString().equals(label)) {
return true;
}
target = target.getParent();
}
return false;
} | java | private static boolean matchLabel(Node target, String label) {
if (label == null) {
return true;
}
while (target.isLabel()) {
if (target.getFirstChild().getString().equals(label)) {
return true;
}
target = target.getParent();
}
return false;
} | [
"private",
"static",
"boolean",
"matchLabel",
"(",
"Node",
"target",
",",
"String",
"label",
")",
"{",
"if",
"(",
"label",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"while",
"(",
"target",
".",
"isLabel",
"(",
")",
")",
"{",
"if",
"(",
"target",
".",
"getFirstChild",
"(",
")",
".",
"getString",
"(",
")",
".",
"equals",
"(",
"label",
")",
")",
"{",
"return",
"true",
";",
"}",
"target",
"=",
"target",
".",
"getParent",
"(",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Check if label is actually referencing the target control structure. If
label is null, it always returns true. | [
"Check",
"if",
"label",
"is",
"actually",
"referencing",
"the",
"target",
"control",
"structure",
".",
"If",
"label",
"is",
"null",
"it",
"always",
"returns",
"true",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L946-L957 |
23,827 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.mayThrowException | public static boolean mayThrowException(Node n) {
switch (n.getToken()) {
case CALL:
case TAGGED_TEMPLATELIT:
case GETPROP:
case GETELEM:
case THROW:
case NEW:
case ASSIGN:
case INC:
case DEC:
case INSTANCEOF:
case IN:
case YIELD:
case AWAIT:
return true;
case FUNCTION:
return false;
default:
break;
}
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (!ControlFlowGraph.isEnteringNewCfgNode(c) && mayThrowException(c)) {
return true;
}
}
return false;
} | java | public static boolean mayThrowException(Node n) {
switch (n.getToken()) {
case CALL:
case TAGGED_TEMPLATELIT:
case GETPROP:
case GETELEM:
case THROW:
case NEW:
case ASSIGN:
case INC:
case DEC:
case INSTANCEOF:
case IN:
case YIELD:
case AWAIT:
return true;
case FUNCTION:
return false;
default:
break;
}
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (!ControlFlowGraph.isEnteringNewCfgNode(c) && mayThrowException(c)) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"mayThrowException",
"(",
"Node",
"n",
")",
"{",
"switch",
"(",
"n",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"CALL",
":",
"case",
"TAGGED_TEMPLATELIT",
":",
"case",
"GETPROP",
":",
"case",
"GETELEM",
":",
"case",
"THROW",
":",
"case",
"NEW",
":",
"case",
"ASSIGN",
":",
"case",
"INC",
":",
"case",
"DEC",
":",
"case",
"INSTANCEOF",
":",
"case",
"IN",
":",
"case",
"YIELD",
":",
"case",
"AWAIT",
":",
"return",
"true",
";",
"case",
"FUNCTION",
":",
"return",
"false",
";",
"default",
":",
"break",
";",
"}",
"for",
"(",
"Node",
"c",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"c",
"!=",
"null",
";",
"c",
"=",
"c",
".",
"getNext",
"(",
")",
")",
"{",
"if",
"(",
"!",
"ControlFlowGraph",
".",
"isEnteringNewCfgNode",
"(",
"c",
")",
"&&",
"mayThrowException",
"(",
"c",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Determines if the subtree might throw an exception. | [
"Determines",
"if",
"the",
"subtree",
"might",
"throw",
"an",
"exception",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L962-L989 |
23,828 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.isBreakStructure | static boolean isBreakStructure(Node n, boolean labeled) {
switch (n.getToken()) {
case FOR:
case FOR_IN:
case FOR_OF:
case FOR_AWAIT_OF:
case DO:
case WHILE:
case SWITCH:
return true;
case BLOCK:
case ROOT:
case IF:
case TRY:
return labeled;
default:
return false;
}
} | java | static boolean isBreakStructure(Node n, boolean labeled) {
switch (n.getToken()) {
case FOR:
case FOR_IN:
case FOR_OF:
case FOR_AWAIT_OF:
case DO:
case WHILE:
case SWITCH:
return true;
case BLOCK:
case ROOT:
case IF:
case TRY:
return labeled;
default:
return false;
}
} | [
"static",
"boolean",
"isBreakStructure",
"(",
"Node",
"n",
",",
"boolean",
"labeled",
")",
"{",
"switch",
"(",
"n",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"FOR",
":",
"case",
"FOR_IN",
":",
"case",
"FOR_OF",
":",
"case",
"FOR_AWAIT_OF",
":",
"case",
"DO",
":",
"case",
"WHILE",
":",
"case",
"SWITCH",
":",
"return",
"true",
";",
"case",
"BLOCK",
":",
"case",
"ROOT",
":",
"case",
"IF",
":",
"case",
"TRY",
":",
"return",
"labeled",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
] | Determines whether the given node can be terminated with a BREAK node. | [
"Determines",
"whether",
"the",
"given",
"node",
"can",
"be",
"terminated",
"with",
"a",
"BREAK",
"node",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L994-L1012 |
23,829 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.getExceptionHandler | static Node getExceptionHandler(Node n) {
for (Node cur = n;
!cur.isScript() && !cur.isFunction();
cur = cur.getParent()) {
Node catchNode = getCatchHandlerForBlock(cur);
if (catchNode != null) {
return catchNode;
}
}
return null;
} | java | static Node getExceptionHandler(Node n) {
for (Node cur = n;
!cur.isScript() && !cur.isFunction();
cur = cur.getParent()) {
Node catchNode = getCatchHandlerForBlock(cur);
if (catchNode != null) {
return catchNode;
}
}
return null;
} | [
"static",
"Node",
"getExceptionHandler",
"(",
"Node",
"n",
")",
"{",
"for",
"(",
"Node",
"cur",
"=",
"n",
";",
"!",
"cur",
".",
"isScript",
"(",
")",
"&&",
"!",
"cur",
".",
"isFunction",
"(",
")",
";",
"cur",
"=",
"cur",
".",
"getParent",
"(",
")",
")",
"{",
"Node",
"catchNode",
"=",
"getCatchHandlerForBlock",
"(",
"cur",
")",
";",
"if",
"(",
"catchNode",
"!=",
"null",
")",
"{",
"return",
"catchNode",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Get the TRY block with a CATCH that would be run if n throws an exception.
@return The CATCH node or null if it there isn't a CATCH before the
the function terminates. | [
"Get",
"the",
"TRY",
"block",
"with",
"a",
"CATCH",
"that",
"would",
"be",
"run",
"if",
"n",
"throws",
"an",
"exception",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L1019-L1029 |
23,830 | google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.getCatchHandlerForBlock | static Node getCatchHandlerForBlock(Node block) {
if (block.isBlock()
&& block.getParent().isTry()
&& block.getParent().getFirstChild() == block) {
for (Node s = block.getNext(); s != null; s = s.getNext()) {
if (NodeUtil.hasCatchHandler(s)) {
return s.getFirstChild();
}
}
}
return null;
} | java | static Node getCatchHandlerForBlock(Node block) {
if (block.isBlock()
&& block.getParent().isTry()
&& block.getParent().getFirstChild() == block) {
for (Node s = block.getNext(); s != null; s = s.getNext()) {
if (NodeUtil.hasCatchHandler(s)) {
return s.getFirstChild();
}
}
}
return null;
} | [
"static",
"Node",
"getCatchHandlerForBlock",
"(",
"Node",
"block",
")",
"{",
"if",
"(",
"block",
".",
"isBlock",
"(",
")",
"&&",
"block",
".",
"getParent",
"(",
")",
".",
"isTry",
"(",
")",
"&&",
"block",
".",
"getParent",
"(",
")",
".",
"getFirstChild",
"(",
")",
"==",
"block",
")",
"{",
"for",
"(",
"Node",
"s",
"=",
"block",
".",
"getNext",
"(",
")",
";",
"s",
"!=",
"null",
";",
"s",
"=",
"s",
".",
"getNext",
"(",
")",
")",
"{",
"if",
"(",
"NodeUtil",
".",
"hasCatchHandler",
"(",
"s",
")",
")",
"{",
"return",
"s",
".",
"getFirstChild",
"(",
")",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | Locate the catch BLOCK given the first block in a TRY.
@return The CATCH node or null there is no catch handler. | [
"Locate",
"the",
"catch",
"BLOCK",
"given",
"the",
"first",
"block",
"in",
"a",
"TRY",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L1035-L1046 |
23,831 | google/closure-compiler | src/com/google/javascript/jscomp/CoverageInstrumentationCallback.java | CoverageInstrumentationCallback.visit | @Override
public void visit(NodeTraversal traversal, Node node, Node parent) {
// SCRIPT node is special - it is the root of the AST for code from a file.
// Append code to declare and initialize structures used in instrumentation.
if (node.isScript()) {
String fileName = getFileName(traversal);
if (instrumentationData.get(fileName) != null) {
if (node.hasChildren() && node.getFirstChild().isModuleBody()) {
node = node.getFirstChild();
}
node.addChildrenToFront(newHeaderNode(traversal, node).removeChildren());
}
traversal.reportCodeChange();
return;
}
// Don't instrument global statements
if (reach == CoverageReach.CONDITIONAL
&& parent != null && parent.isScript()) {
return;
}
// For arrow functions whose body is an expression instead of a block,
// convert it to a block so that it can be instrumented.
if (node.isFunction() && !NodeUtil.getFunctionBody(node).isBlock()) {
Node returnValue = NodeUtil.getFunctionBody(node);
Node body = IR.block(IR.returnNode(returnValue.detach()));
body.useSourceInfoIfMissingFromForTree(returnValue);
node.addChildToBack(body);
}
// Add instrumentation code just before a function block.
// Similarly before other constructs: 'with', 'case', 'default', 'catch'
if (node.isFunction()
|| node.isWith()
|| node.isCase()
|| node.isDefaultCase()
|| node.isCatch()) {
Node codeBlock = node.getLastChild();
codeBlock.addChildToFront(
newInstrumentationNode(traversal, node));
traversal.reportCodeChange();
return;
}
// Add instrumentation code as the first child of a 'try' block.
if (node.isTry()) {
Node firstChild = node.getFirstChild();
firstChild.addChildToFront(
newInstrumentationNode(traversal, node));
traversal.reportCodeChange();
return;
}
// For any other statement, add instrumentation code just before it.
if (parent != null && NodeUtil.isStatementBlock(parent) && !node.isModuleBody()) {
parent.addChildBefore(
newInstrumentationNode(traversal, node),
node);
traversal.reportCodeChange();
return;
}
} | java | @Override
public void visit(NodeTraversal traversal, Node node, Node parent) {
// SCRIPT node is special - it is the root of the AST for code from a file.
// Append code to declare and initialize structures used in instrumentation.
if (node.isScript()) {
String fileName = getFileName(traversal);
if (instrumentationData.get(fileName) != null) {
if (node.hasChildren() && node.getFirstChild().isModuleBody()) {
node = node.getFirstChild();
}
node.addChildrenToFront(newHeaderNode(traversal, node).removeChildren());
}
traversal.reportCodeChange();
return;
}
// Don't instrument global statements
if (reach == CoverageReach.CONDITIONAL
&& parent != null && parent.isScript()) {
return;
}
// For arrow functions whose body is an expression instead of a block,
// convert it to a block so that it can be instrumented.
if (node.isFunction() && !NodeUtil.getFunctionBody(node).isBlock()) {
Node returnValue = NodeUtil.getFunctionBody(node);
Node body = IR.block(IR.returnNode(returnValue.detach()));
body.useSourceInfoIfMissingFromForTree(returnValue);
node.addChildToBack(body);
}
// Add instrumentation code just before a function block.
// Similarly before other constructs: 'with', 'case', 'default', 'catch'
if (node.isFunction()
|| node.isWith()
|| node.isCase()
|| node.isDefaultCase()
|| node.isCatch()) {
Node codeBlock = node.getLastChild();
codeBlock.addChildToFront(
newInstrumentationNode(traversal, node));
traversal.reportCodeChange();
return;
}
// Add instrumentation code as the first child of a 'try' block.
if (node.isTry()) {
Node firstChild = node.getFirstChild();
firstChild.addChildToFront(
newInstrumentationNode(traversal, node));
traversal.reportCodeChange();
return;
}
// For any other statement, add instrumentation code just before it.
if (parent != null && NodeUtil.isStatementBlock(parent) && !node.isModuleBody()) {
parent.addChildBefore(
newInstrumentationNode(traversal, node),
node);
traversal.reportCodeChange();
return;
}
} | [
"@",
"Override",
"public",
"void",
"visit",
"(",
"NodeTraversal",
"traversal",
",",
"Node",
"node",
",",
"Node",
"parent",
")",
"{",
"// SCRIPT node is special - it is the root of the AST for code from a file.",
"// Append code to declare and initialize structures used in instrumentation.",
"if",
"(",
"node",
".",
"isScript",
"(",
")",
")",
"{",
"String",
"fileName",
"=",
"getFileName",
"(",
"traversal",
")",
";",
"if",
"(",
"instrumentationData",
".",
"get",
"(",
"fileName",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"node",
".",
"hasChildren",
"(",
")",
"&&",
"node",
".",
"getFirstChild",
"(",
")",
".",
"isModuleBody",
"(",
")",
")",
"{",
"node",
"=",
"node",
".",
"getFirstChild",
"(",
")",
";",
"}",
"node",
".",
"addChildrenToFront",
"(",
"newHeaderNode",
"(",
"traversal",
",",
"node",
")",
".",
"removeChildren",
"(",
")",
")",
";",
"}",
"traversal",
".",
"reportCodeChange",
"(",
")",
";",
"return",
";",
"}",
"// Don't instrument global statements",
"if",
"(",
"reach",
"==",
"CoverageReach",
".",
"CONDITIONAL",
"&&",
"parent",
"!=",
"null",
"&&",
"parent",
".",
"isScript",
"(",
")",
")",
"{",
"return",
";",
"}",
"// For arrow functions whose body is an expression instead of a block,",
"// convert it to a block so that it can be instrumented.",
"if",
"(",
"node",
".",
"isFunction",
"(",
")",
"&&",
"!",
"NodeUtil",
".",
"getFunctionBody",
"(",
"node",
")",
".",
"isBlock",
"(",
")",
")",
"{",
"Node",
"returnValue",
"=",
"NodeUtil",
".",
"getFunctionBody",
"(",
"node",
")",
";",
"Node",
"body",
"=",
"IR",
".",
"block",
"(",
"IR",
".",
"returnNode",
"(",
"returnValue",
".",
"detach",
"(",
")",
")",
")",
";",
"body",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"returnValue",
")",
";",
"node",
".",
"addChildToBack",
"(",
"body",
")",
";",
"}",
"// Add instrumentation code just before a function block.",
"// Similarly before other constructs: 'with', 'case', 'default', 'catch'",
"if",
"(",
"node",
".",
"isFunction",
"(",
")",
"||",
"node",
".",
"isWith",
"(",
")",
"||",
"node",
".",
"isCase",
"(",
")",
"||",
"node",
".",
"isDefaultCase",
"(",
")",
"||",
"node",
".",
"isCatch",
"(",
")",
")",
"{",
"Node",
"codeBlock",
"=",
"node",
".",
"getLastChild",
"(",
")",
";",
"codeBlock",
".",
"addChildToFront",
"(",
"newInstrumentationNode",
"(",
"traversal",
",",
"node",
")",
")",
";",
"traversal",
".",
"reportCodeChange",
"(",
")",
";",
"return",
";",
"}",
"// Add instrumentation code as the first child of a 'try' block.",
"if",
"(",
"node",
".",
"isTry",
"(",
")",
")",
"{",
"Node",
"firstChild",
"=",
"node",
".",
"getFirstChild",
"(",
")",
";",
"firstChild",
".",
"addChildToFront",
"(",
"newInstrumentationNode",
"(",
"traversal",
",",
"node",
")",
")",
";",
"traversal",
".",
"reportCodeChange",
"(",
")",
";",
"return",
";",
"}",
"// For any other statement, add instrumentation code just before it.",
"if",
"(",
"parent",
"!=",
"null",
"&&",
"NodeUtil",
".",
"isStatementBlock",
"(",
"parent",
")",
"&&",
"!",
"node",
".",
"isModuleBody",
"(",
")",
")",
"{",
"parent",
".",
"addChildBefore",
"(",
"newInstrumentationNode",
"(",
"traversal",
",",
"node",
")",
",",
"node",
")",
";",
"traversal",
".",
"reportCodeChange",
"(",
")",
";",
"return",
";",
"}",
"}"
] | Instruments the JS code by inserting appropriate nodes into the AST. The
instrumentation logic is tuned to collect "line coverage" data only. | [
"Instruments",
"the",
"JS",
"code",
"by",
"inserting",
"appropriate",
"nodes",
"into",
"the",
"AST",
".",
"The",
"instrumentation",
"logic",
"is",
"tuned",
"to",
"collect",
"line",
"coverage",
"data",
"only",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CoverageInstrumentationCallback.java#L146-L208 |
23,832 | google/closure-compiler | src/com/google/javascript/jscomp/PrepareAst.java | PrepareAst.normalizeNodeTypes | private void normalizeNodeTypes(Node n) {
normalizeBlocks(n);
for (Node child = n.getFirstChild();
child != null; child = child.getNext()) {
// This pass is run during the CompilerTestCase validation, so this
// parent pointer check serves as a more general check.
checkState(child.getParent() == n);
normalizeNodeTypes(child);
}
} | java | private void normalizeNodeTypes(Node n) {
normalizeBlocks(n);
for (Node child = n.getFirstChild();
child != null; child = child.getNext()) {
// This pass is run during the CompilerTestCase validation, so this
// parent pointer check serves as a more general check.
checkState(child.getParent() == n);
normalizeNodeTypes(child);
}
} | [
"private",
"void",
"normalizeNodeTypes",
"(",
"Node",
"n",
")",
"{",
"normalizeBlocks",
"(",
"n",
")",
";",
"for",
"(",
"Node",
"child",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"child",
"!=",
"null",
";",
"child",
"=",
"child",
".",
"getNext",
"(",
")",
")",
"{",
"// This pass is run during the CompilerTestCase validation, so this",
"// parent pointer check serves as a more general check.",
"checkState",
"(",
"child",
".",
"getParent",
"(",
")",
"==",
"n",
")",
";",
"normalizeNodeTypes",
"(",
"child",
")",
";",
"}",
"}"
] | Covert EXPR_VOID to EXPR_RESULT to simplify the rest of the code. | [
"Covert",
"EXPR_VOID",
"to",
"EXPR_RESULT",
"to",
"simplify",
"the",
"rest",
"of",
"the",
"code",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PrepareAst.java#L76-L87 |
23,833 | google/closure-compiler | src/com/google/javascript/jscomp/PrepareAst.java | PrepareAst.normalizeBlocks | private void normalizeBlocks(Node n) {
if (NodeUtil.isControlStructure(n)
&& !n.isLabel()
&& !n.isSwitch()) {
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (NodeUtil.isControlStructureCodeBlock(n, c) && !c.isBlock()) {
Node newBlock = IR.block().srcref(n);
n.replaceChild(c, newBlock);
newBlock.setIsAddedBlock(true);
if (!c.isEmpty()) {
newBlock.addChildrenToFront(c);
}
c = newBlock;
reportChange();
}
}
}
} | java | private void normalizeBlocks(Node n) {
if (NodeUtil.isControlStructure(n)
&& !n.isLabel()
&& !n.isSwitch()) {
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (NodeUtil.isControlStructureCodeBlock(n, c) && !c.isBlock()) {
Node newBlock = IR.block().srcref(n);
n.replaceChild(c, newBlock);
newBlock.setIsAddedBlock(true);
if (!c.isEmpty()) {
newBlock.addChildrenToFront(c);
}
c = newBlock;
reportChange();
}
}
}
} | [
"private",
"void",
"normalizeBlocks",
"(",
"Node",
"n",
")",
"{",
"if",
"(",
"NodeUtil",
".",
"isControlStructure",
"(",
"n",
")",
"&&",
"!",
"n",
".",
"isLabel",
"(",
")",
"&&",
"!",
"n",
".",
"isSwitch",
"(",
")",
")",
"{",
"for",
"(",
"Node",
"c",
"=",
"n",
".",
"getFirstChild",
"(",
")",
";",
"c",
"!=",
"null",
";",
"c",
"=",
"c",
".",
"getNext",
"(",
")",
")",
"{",
"if",
"(",
"NodeUtil",
".",
"isControlStructureCodeBlock",
"(",
"n",
",",
"c",
")",
"&&",
"!",
"c",
".",
"isBlock",
"(",
")",
")",
"{",
"Node",
"newBlock",
"=",
"IR",
".",
"block",
"(",
")",
".",
"srcref",
"(",
"n",
")",
";",
"n",
".",
"replaceChild",
"(",
"c",
",",
"newBlock",
")",
";",
"newBlock",
".",
"setIsAddedBlock",
"(",
"true",
")",
";",
"if",
"(",
"!",
"c",
".",
"isEmpty",
"(",
")",
")",
"{",
"newBlock",
".",
"addChildrenToFront",
"(",
"c",
")",
";",
"}",
"c",
"=",
"newBlock",
";",
"reportChange",
"(",
")",
";",
"}",
"}",
"}",
"}"
] | Add blocks to IF, WHILE, DO, etc. | [
"Add",
"blocks",
"to",
"IF",
"WHILE",
"DO",
"etc",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PrepareAst.java#L92-L109 |
23,834 | google/closure-compiler | src/com/google/javascript/jscomp/lint/CheckInterfaces.java | CheckInterfaces.isInterface | private boolean isInterface(Node n) {
if (!n.isFunction()) {
return false;
}
JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(n);
return jsDoc != null && jsDoc.isInterface();
} | java | private boolean isInterface(Node n) {
if (!n.isFunction()) {
return false;
}
JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(n);
return jsDoc != null && jsDoc.isInterface();
} | [
"private",
"boolean",
"isInterface",
"(",
"Node",
"n",
")",
"{",
"if",
"(",
"!",
"n",
".",
"isFunction",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"JSDocInfo",
"jsDoc",
"=",
"NodeUtil",
".",
"getBestJSDocInfo",
"(",
"n",
")",
";",
"return",
"jsDoc",
"!=",
"null",
"&&",
"jsDoc",
".",
"isInterface",
"(",
")",
";",
"}"
] | Whether a function is an interface constructor, or a method on an interface. | [
"Whether",
"a",
"function",
"is",
"an",
"interface",
"constructor",
"or",
"a",
"method",
"on",
"an",
"interface",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/lint/CheckInterfaces.java#L65-L72 |
23,835 | google/closure-compiler | src/com/google/javascript/jscomp/Es6RewriteDestructuring.java | Es6RewriteDestructuring.pullDestructuringOutOfParams | private void pullDestructuringOutOfParams(Node paramList, Node function) {
Node insertSpot = null;
Node body = function.getLastChild();
int i = 0;
Node next = null;
for (Node param = paramList.getFirstChild(); param != null; param = next, i++) {
next = param.getNext();
if (param.isDefaultValue()) {
Node nameOrPattern = param.removeFirstChild();
// We'll be cloning nameOrPattern below, and we don't want to clone the JSDoc info with it
JSDocInfo jsDoc = nameOrPattern.getJSDocInfo();
nameOrPattern.setJSDocInfo(null);
Node defaultValue = param.removeFirstChild();
Node newParam;
// Treat name=undefined (and equivalent) as if it was just name. There
// is no need to generate a (name===void 0?void 0:name) statement for
// such arguments.
boolean isNoop = false;
if (!nameOrPattern.isName()) {
// Do not try to optimize unless nameOrPattern is a simple name.
} else if (defaultValue.isName()) {
isNoop = "undefined".equals(defaultValue.getString());
} else if (defaultValue.isVoid()) {
// Any kind of 'void literal' is fine, but 'void fun()' or anything
// else with side effects isn't. We're not trying to be particularly
// smart here and treat 'void {}' for example as if it could cause side effects.
isNoop = NodeUtil.isImmutableValue(defaultValue.getFirstChild());
}
if (isNoop) {
newParam = nameOrPattern.cloneTree();
} else {
newParam =
nameOrPattern.isName()
? nameOrPattern
: astFactory.createName(getTempVariableName(), nameOrPattern.getJSType());
Node lhs = nameOrPattern.cloneTree();
Node rhs = defaultValueHook(newParam.cloneTree(), defaultValue);
Node newStatement =
nameOrPattern.isName()
? IR.exprResult(astFactory.createAssign(lhs, rhs))
: IR.var(lhs, rhs);
newStatement.useSourceInfoIfMissingFromForTree(param);
body.addChildAfter(newStatement, insertSpot);
insertSpot = newStatement;
}
paramList.replaceChild(param, newParam);
newParam.setOptionalArg(true);
newParam.setJSDocInfo(jsDoc);
compiler.reportChangeToChangeScope(function);
} else if (param.isDestructuringPattern()) {
insertSpot =
replacePatternParamWithTempVar(function, insertSpot, param, getTempVariableName());
compiler.reportChangeToChangeScope(function);
} else if (param.isRest() && param.getFirstChild().isDestructuringPattern()) {
insertSpot =
replacePatternParamWithTempVar(
function, insertSpot, param.getFirstChild(), getTempVariableName());
compiler.reportChangeToChangeScope(function);
}
}
} | java | private void pullDestructuringOutOfParams(Node paramList, Node function) {
Node insertSpot = null;
Node body = function.getLastChild();
int i = 0;
Node next = null;
for (Node param = paramList.getFirstChild(); param != null; param = next, i++) {
next = param.getNext();
if (param.isDefaultValue()) {
Node nameOrPattern = param.removeFirstChild();
// We'll be cloning nameOrPattern below, and we don't want to clone the JSDoc info with it
JSDocInfo jsDoc = nameOrPattern.getJSDocInfo();
nameOrPattern.setJSDocInfo(null);
Node defaultValue = param.removeFirstChild();
Node newParam;
// Treat name=undefined (and equivalent) as if it was just name. There
// is no need to generate a (name===void 0?void 0:name) statement for
// such arguments.
boolean isNoop = false;
if (!nameOrPattern.isName()) {
// Do not try to optimize unless nameOrPattern is a simple name.
} else if (defaultValue.isName()) {
isNoop = "undefined".equals(defaultValue.getString());
} else if (defaultValue.isVoid()) {
// Any kind of 'void literal' is fine, but 'void fun()' or anything
// else with side effects isn't. We're not trying to be particularly
// smart here and treat 'void {}' for example as if it could cause side effects.
isNoop = NodeUtil.isImmutableValue(defaultValue.getFirstChild());
}
if (isNoop) {
newParam = nameOrPattern.cloneTree();
} else {
newParam =
nameOrPattern.isName()
? nameOrPattern
: astFactory.createName(getTempVariableName(), nameOrPattern.getJSType());
Node lhs = nameOrPattern.cloneTree();
Node rhs = defaultValueHook(newParam.cloneTree(), defaultValue);
Node newStatement =
nameOrPattern.isName()
? IR.exprResult(astFactory.createAssign(lhs, rhs))
: IR.var(lhs, rhs);
newStatement.useSourceInfoIfMissingFromForTree(param);
body.addChildAfter(newStatement, insertSpot);
insertSpot = newStatement;
}
paramList.replaceChild(param, newParam);
newParam.setOptionalArg(true);
newParam.setJSDocInfo(jsDoc);
compiler.reportChangeToChangeScope(function);
} else if (param.isDestructuringPattern()) {
insertSpot =
replacePatternParamWithTempVar(function, insertSpot, param, getTempVariableName());
compiler.reportChangeToChangeScope(function);
} else if (param.isRest() && param.getFirstChild().isDestructuringPattern()) {
insertSpot =
replacePatternParamWithTempVar(
function, insertSpot, param.getFirstChild(), getTempVariableName());
compiler.reportChangeToChangeScope(function);
}
}
} | [
"private",
"void",
"pullDestructuringOutOfParams",
"(",
"Node",
"paramList",
",",
"Node",
"function",
")",
"{",
"Node",
"insertSpot",
"=",
"null",
";",
"Node",
"body",
"=",
"function",
".",
"getLastChild",
"(",
")",
";",
"int",
"i",
"=",
"0",
";",
"Node",
"next",
"=",
"null",
";",
"for",
"(",
"Node",
"param",
"=",
"paramList",
".",
"getFirstChild",
"(",
")",
";",
"param",
"!=",
"null",
";",
"param",
"=",
"next",
",",
"i",
"++",
")",
"{",
"next",
"=",
"param",
".",
"getNext",
"(",
")",
";",
"if",
"(",
"param",
".",
"isDefaultValue",
"(",
")",
")",
"{",
"Node",
"nameOrPattern",
"=",
"param",
".",
"removeFirstChild",
"(",
")",
";",
"// We'll be cloning nameOrPattern below, and we don't want to clone the JSDoc info with it",
"JSDocInfo",
"jsDoc",
"=",
"nameOrPattern",
".",
"getJSDocInfo",
"(",
")",
";",
"nameOrPattern",
".",
"setJSDocInfo",
"(",
"null",
")",
";",
"Node",
"defaultValue",
"=",
"param",
".",
"removeFirstChild",
"(",
")",
";",
"Node",
"newParam",
";",
"// Treat name=undefined (and equivalent) as if it was just name. There",
"// is no need to generate a (name===void 0?void 0:name) statement for",
"// such arguments.",
"boolean",
"isNoop",
"=",
"false",
";",
"if",
"(",
"!",
"nameOrPattern",
".",
"isName",
"(",
")",
")",
"{",
"// Do not try to optimize unless nameOrPattern is a simple name.",
"}",
"else",
"if",
"(",
"defaultValue",
".",
"isName",
"(",
")",
")",
"{",
"isNoop",
"=",
"\"undefined\"",
".",
"equals",
"(",
"defaultValue",
".",
"getString",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"defaultValue",
".",
"isVoid",
"(",
")",
")",
"{",
"// Any kind of 'void literal' is fine, but 'void fun()' or anything",
"// else with side effects isn't. We're not trying to be particularly",
"// smart here and treat 'void {}' for example as if it could cause side effects.",
"isNoop",
"=",
"NodeUtil",
".",
"isImmutableValue",
"(",
"defaultValue",
".",
"getFirstChild",
"(",
")",
")",
";",
"}",
"if",
"(",
"isNoop",
")",
"{",
"newParam",
"=",
"nameOrPattern",
".",
"cloneTree",
"(",
")",
";",
"}",
"else",
"{",
"newParam",
"=",
"nameOrPattern",
".",
"isName",
"(",
")",
"?",
"nameOrPattern",
":",
"astFactory",
".",
"createName",
"(",
"getTempVariableName",
"(",
")",
",",
"nameOrPattern",
".",
"getJSType",
"(",
")",
")",
";",
"Node",
"lhs",
"=",
"nameOrPattern",
".",
"cloneTree",
"(",
")",
";",
"Node",
"rhs",
"=",
"defaultValueHook",
"(",
"newParam",
".",
"cloneTree",
"(",
")",
",",
"defaultValue",
")",
";",
"Node",
"newStatement",
"=",
"nameOrPattern",
".",
"isName",
"(",
")",
"?",
"IR",
".",
"exprResult",
"(",
"astFactory",
".",
"createAssign",
"(",
"lhs",
",",
"rhs",
")",
")",
":",
"IR",
".",
"var",
"(",
"lhs",
",",
"rhs",
")",
";",
"newStatement",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"param",
")",
";",
"body",
".",
"addChildAfter",
"(",
"newStatement",
",",
"insertSpot",
")",
";",
"insertSpot",
"=",
"newStatement",
";",
"}",
"paramList",
".",
"replaceChild",
"(",
"param",
",",
"newParam",
")",
";",
"newParam",
".",
"setOptionalArg",
"(",
"true",
")",
";",
"newParam",
".",
"setJSDocInfo",
"(",
"jsDoc",
")",
";",
"compiler",
".",
"reportChangeToChangeScope",
"(",
"function",
")",
";",
"}",
"else",
"if",
"(",
"param",
".",
"isDestructuringPattern",
"(",
")",
")",
"{",
"insertSpot",
"=",
"replacePatternParamWithTempVar",
"(",
"function",
",",
"insertSpot",
",",
"param",
",",
"getTempVariableName",
"(",
")",
")",
";",
"compiler",
".",
"reportChangeToChangeScope",
"(",
"function",
")",
";",
"}",
"else",
"if",
"(",
"param",
".",
"isRest",
"(",
")",
"&&",
"param",
".",
"getFirstChild",
"(",
")",
".",
"isDestructuringPattern",
"(",
")",
")",
"{",
"insertSpot",
"=",
"replacePatternParamWithTempVar",
"(",
"function",
",",
"insertSpot",
",",
"param",
".",
"getFirstChild",
"(",
")",
",",
"getTempVariableName",
"(",
")",
")",
";",
"compiler",
".",
"reportChangeToChangeScope",
"(",
"function",
")",
";",
"}",
"}",
"}"
] | the parameter list contains a usage of OBJECT_REST. | [
"the",
"parameter",
"list",
"contains",
"a",
"usage",
"of",
"OBJECT_REST",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteDestructuring.java#L225-L289 |
23,836 | google/closure-compiler | src/com/google/javascript/jscomp/Es6RewriteDestructuring.java | Es6RewriteDestructuring.replacePatternParamWithTempVar | private Node replacePatternParamWithTempVar(
Node function, Node insertSpot, Node patternParam, String tempVarName) {
// Convert `function f([a, b]) {}` to `function f(tempVar) { var [a, b] = tempVar; }`
JSType paramType = patternParam.getJSType();
Node newParam = astFactory.createName(tempVarName, paramType);
newParam.setJSDocInfo(patternParam.getJSDocInfo());
patternParam.replaceWith(newParam);
Node newDecl = IR.var(patternParam, astFactory.createName(tempVarName, paramType));
function.getLastChild().addChildAfter(newDecl, insertSpot);
return newDecl;
} | java | private Node replacePatternParamWithTempVar(
Node function, Node insertSpot, Node patternParam, String tempVarName) {
// Convert `function f([a, b]) {}` to `function f(tempVar) { var [a, b] = tempVar; }`
JSType paramType = patternParam.getJSType();
Node newParam = astFactory.createName(tempVarName, paramType);
newParam.setJSDocInfo(patternParam.getJSDocInfo());
patternParam.replaceWith(newParam);
Node newDecl = IR.var(patternParam, astFactory.createName(tempVarName, paramType));
function.getLastChild().addChildAfter(newDecl, insertSpot);
return newDecl;
} | [
"private",
"Node",
"replacePatternParamWithTempVar",
"(",
"Node",
"function",
",",
"Node",
"insertSpot",
",",
"Node",
"patternParam",
",",
"String",
"tempVarName",
")",
"{",
"// Convert `function f([a, b]) {}` to `function f(tempVar) { var [a, b] = tempVar; }`",
"JSType",
"paramType",
"=",
"patternParam",
".",
"getJSType",
"(",
")",
";",
"Node",
"newParam",
"=",
"astFactory",
".",
"createName",
"(",
"tempVarName",
",",
"paramType",
")",
";",
"newParam",
".",
"setJSDocInfo",
"(",
"patternParam",
".",
"getJSDocInfo",
"(",
")",
")",
";",
"patternParam",
".",
"replaceWith",
"(",
"newParam",
")",
";",
"Node",
"newDecl",
"=",
"IR",
".",
"var",
"(",
"patternParam",
",",
"astFactory",
".",
"createName",
"(",
"tempVarName",
",",
"paramType",
")",
")",
";",
"function",
".",
"getLastChild",
"(",
")",
".",
"addChildAfter",
"(",
"newDecl",
",",
"insertSpot",
")",
";",
"return",
"newDecl",
";",
"}"
] | Replace a destructuring pattern parameter with a a temporary parameter name and add a new
local variable declaration to the function assigning the temporary parameter to the pattern.
<p> Note: Rewrites of variable declaration destructuring will happen later to rewrite
this declaration as non-destructured code.
@param function
@param insertSpot The local variable declaration will be inserted after this statement.
@param patternParam
@param tempVarName the name to use for the temporary variable
@return the declaration statement that was generated for the local variable | [
"Replace",
"a",
"destructuring",
"pattern",
"parameter",
"with",
"a",
"a",
"temporary",
"parameter",
"name",
"and",
"add",
"a",
"new",
"local",
"variable",
"declaration",
"to",
"the",
"function",
"assigning",
"the",
"temporary",
"parameter",
"to",
"the",
"pattern",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteDestructuring.java#L303-L313 |
23,837 | google/closure-compiler | src/com/google/javascript/jscomp/Es6RewriteDestructuring.java | Es6RewriteDestructuring.replacePattern | private void replacePattern(
NodeTraversal t, Node pattern, Node rhs, Node parent, Node nodeToDetach) {
checkArgument(NodeUtil.isStatement(nodeToDetach), nodeToDetach);
switch (pattern.getToken()) {
case ARRAY_PATTERN:
replaceArrayPattern(t, pattern, rhs, parent, nodeToDetach);
break;
case OBJECT_PATTERN:
replaceObjectPattern(t, pattern, rhs, parent, nodeToDetach);
break;
default:
throw new IllegalStateException("unexpected");
}
} | java | private void replacePattern(
NodeTraversal t, Node pattern, Node rhs, Node parent, Node nodeToDetach) {
checkArgument(NodeUtil.isStatement(nodeToDetach), nodeToDetach);
switch (pattern.getToken()) {
case ARRAY_PATTERN:
replaceArrayPattern(t, pattern, rhs, parent, nodeToDetach);
break;
case OBJECT_PATTERN:
replaceObjectPattern(t, pattern, rhs, parent, nodeToDetach);
break;
default:
throw new IllegalStateException("unexpected");
}
} | [
"private",
"void",
"replacePattern",
"(",
"NodeTraversal",
"t",
",",
"Node",
"pattern",
",",
"Node",
"rhs",
",",
"Node",
"parent",
",",
"Node",
"nodeToDetach",
")",
"{",
"checkArgument",
"(",
"NodeUtil",
".",
"isStatement",
"(",
"nodeToDetach",
")",
",",
"nodeToDetach",
")",
";",
"switch",
"(",
"pattern",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"ARRAY_PATTERN",
":",
"replaceArrayPattern",
"(",
"t",
",",
"pattern",
",",
"rhs",
",",
"parent",
",",
"nodeToDetach",
")",
";",
"break",
";",
"case",
"OBJECT_PATTERN",
":",
"replaceObjectPattern",
"(",
"t",
",",
"pattern",
",",
"rhs",
",",
"parent",
",",
"nodeToDetach",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"IllegalStateException",
"(",
"\"unexpected\"",
")",
";",
"}",
"}"
] | Transpiles a destructuring pattern in a declaration or assignment to ES5
@param nodeToDetach a statement node containing the pattern. This method will replace the node
with one or more other statements. | [
"Transpiles",
"a",
"destructuring",
"pattern",
"in",
"a",
"declaration",
"or",
"assignment",
"to",
"ES5"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteDestructuring.java#L350-L363 |
23,838 | google/closure-compiler | src/com/google/javascript/jscomp/Es6RewriteDestructuring.java | Es6RewriteDestructuring.objectPatternRestRHS | private Node objectPatternRestRHS(
Node objectPattern, Node rest, String restTempVarName, ArrayList<Node> statedProperties) {
checkArgument(objectPattern.getLastChild() == rest);
Node restTempVarModel = astFactory.createName(restTempVarName, objectPattern.getJSType());
Node result = restTempVarModel.cloneNode();
if (!statedProperties.isEmpty()) {
Iterator<Node> propItr = statedProperties.iterator();
Node comma = deletionNodeForRestProperty(restTempVarModel.cloneNode(), propItr.next());
while (propItr.hasNext()) {
comma =
astFactory.createComma(
comma, deletionNodeForRestProperty(restTempVarModel.cloneNode(), propItr.next()));
}
result = astFactory.createComma(comma, result);
}
result.useSourceInfoIfMissingFromForTree(rest);
return result;
} | java | private Node objectPatternRestRHS(
Node objectPattern, Node rest, String restTempVarName, ArrayList<Node> statedProperties) {
checkArgument(objectPattern.getLastChild() == rest);
Node restTempVarModel = astFactory.createName(restTempVarName, objectPattern.getJSType());
Node result = restTempVarModel.cloneNode();
if (!statedProperties.isEmpty()) {
Iterator<Node> propItr = statedProperties.iterator();
Node comma = deletionNodeForRestProperty(restTempVarModel.cloneNode(), propItr.next());
while (propItr.hasNext()) {
comma =
astFactory.createComma(
comma, deletionNodeForRestProperty(restTempVarModel.cloneNode(), propItr.next()));
}
result = astFactory.createComma(comma, result);
}
result.useSourceInfoIfMissingFromForTree(rest);
return result;
} | [
"private",
"Node",
"objectPatternRestRHS",
"(",
"Node",
"objectPattern",
",",
"Node",
"rest",
",",
"String",
"restTempVarName",
",",
"ArrayList",
"<",
"Node",
">",
"statedProperties",
")",
"{",
"checkArgument",
"(",
"objectPattern",
".",
"getLastChild",
"(",
")",
"==",
"rest",
")",
";",
"Node",
"restTempVarModel",
"=",
"astFactory",
".",
"createName",
"(",
"restTempVarName",
",",
"objectPattern",
".",
"getJSType",
"(",
")",
")",
";",
"Node",
"result",
"=",
"restTempVarModel",
".",
"cloneNode",
"(",
")",
";",
"if",
"(",
"!",
"statedProperties",
".",
"isEmpty",
"(",
")",
")",
"{",
"Iterator",
"<",
"Node",
">",
"propItr",
"=",
"statedProperties",
".",
"iterator",
"(",
")",
";",
"Node",
"comma",
"=",
"deletionNodeForRestProperty",
"(",
"restTempVarModel",
".",
"cloneNode",
"(",
")",
",",
"propItr",
".",
"next",
"(",
")",
")",
";",
"while",
"(",
"propItr",
".",
"hasNext",
"(",
")",
")",
"{",
"comma",
"=",
"astFactory",
".",
"createComma",
"(",
"comma",
",",
"deletionNodeForRestProperty",
"(",
"restTempVarModel",
".",
"cloneNode",
"(",
")",
",",
"propItr",
".",
"next",
"(",
")",
")",
")",
";",
"}",
"result",
"=",
"astFactory",
".",
"createComma",
"(",
"comma",
",",
"result",
")",
";",
"}",
"result",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"rest",
")",
";",
"return",
"result",
";",
"}"
] | Convert "rest" of object destructuring lhs by making a clone and deleting any properties that
were stated in the original object pattern.
<p>Nodes in statedProperties that are a stringKey will be used in a getprop when deleting. All
other types will be used in a getelem such as what is done for computed properties.
<pre>
{a, [foo()]:b, ...x} = rhs;
becomes
var temp = rhs;
var temp1 = Object.assign({}, temp);
var temp2 = foo()
a = temp.a
b = temp[foo()]
x = (delete temp1.a, delete temp1[temp2], temp1);
</pre>
@param rest node representing the "...rest" of objectPattern
@param restTempVarName name of var containing clone of result of rhs evaluation
@param statedProperties list of properties to delete from the clone | [
"Convert",
"rest",
"of",
"object",
"destructuring",
"lhs",
"by",
"making",
"a",
"clone",
"and",
"deleting",
"any",
"properties",
"that",
"were",
"stated",
"in",
"the",
"original",
"object",
"pattern",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteDestructuring.java#L545-L562 |
23,839 | google/closure-compiler | src/com/google/javascript/jscomp/Es6RewriteDestructuring.java | Es6RewriteDestructuring.defaultValueHook | private Node defaultValueHook(Node getprop, Node defaultValue) {
Node undefined = astFactory.createName("undefined", JSTypeNative.VOID_TYPE);
undefined.makeNonIndexable();
Node getpropClone = getprop.cloneTree().setJSType(getprop.getJSType());
return astFactory.createHook(
astFactory.createSheq(getprop, undefined), defaultValue, getpropClone);
} | java | private Node defaultValueHook(Node getprop, Node defaultValue) {
Node undefined = astFactory.createName("undefined", JSTypeNative.VOID_TYPE);
undefined.makeNonIndexable();
Node getpropClone = getprop.cloneTree().setJSType(getprop.getJSType());
return astFactory.createHook(
astFactory.createSheq(getprop, undefined), defaultValue, getpropClone);
} | [
"private",
"Node",
"defaultValueHook",
"(",
"Node",
"getprop",
",",
"Node",
"defaultValue",
")",
"{",
"Node",
"undefined",
"=",
"astFactory",
".",
"createName",
"(",
"\"undefined\"",
",",
"JSTypeNative",
".",
"VOID_TYPE",
")",
";",
"undefined",
".",
"makeNonIndexable",
"(",
")",
";",
"Node",
"getpropClone",
"=",
"getprop",
".",
"cloneTree",
"(",
")",
".",
"setJSType",
"(",
"getprop",
".",
"getJSType",
"(",
")",
")",
";",
"return",
"astFactory",
".",
"createHook",
"(",
"astFactory",
".",
"createSheq",
"(",
"getprop",
",",
"undefined",
")",
",",
"defaultValue",
",",
"getpropClone",
")",
";",
"}"
] | Helper for transpiling DEFAULT_VALUE trees. | [
"Helper",
"for",
"transpiling",
"DEFAULT_VALUE",
"trees",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteDestructuring.java#L770-L776 |
23,840 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.cloneClassDoc | public JSDocInfo cloneClassDoc() {
JSDocInfo other = new JSDocInfo();
other.info = this.info == null ? null : this.info.cloneClassDoc();
other.documentation = this.documentation;
other.visibility = this.visibility;
other.bitset = this.bitset;
other.type = cloneType(this.type, false);
other.thisType = cloneType(this.thisType, false);
other.includeDocumentation = this.includeDocumentation;
other.originalCommentPosition = this.originalCommentPosition;
other.setConstructor(false);
other.setStruct(false);
if (!isInterface() && other.info != null) {
other.info.baseType = null;
}
return other;
} | java | public JSDocInfo cloneClassDoc() {
JSDocInfo other = new JSDocInfo();
other.info = this.info == null ? null : this.info.cloneClassDoc();
other.documentation = this.documentation;
other.visibility = this.visibility;
other.bitset = this.bitset;
other.type = cloneType(this.type, false);
other.thisType = cloneType(this.thisType, false);
other.includeDocumentation = this.includeDocumentation;
other.originalCommentPosition = this.originalCommentPosition;
other.setConstructor(false);
other.setStruct(false);
if (!isInterface() && other.info != null) {
other.info.baseType = null;
}
return other;
} | [
"public",
"JSDocInfo",
"cloneClassDoc",
"(",
")",
"{",
"JSDocInfo",
"other",
"=",
"new",
"JSDocInfo",
"(",
")",
";",
"other",
".",
"info",
"=",
"this",
".",
"info",
"==",
"null",
"?",
"null",
":",
"this",
".",
"info",
".",
"cloneClassDoc",
"(",
")",
";",
"other",
".",
"documentation",
"=",
"this",
".",
"documentation",
";",
"other",
".",
"visibility",
"=",
"this",
".",
"visibility",
";",
"other",
".",
"bitset",
"=",
"this",
".",
"bitset",
";",
"other",
".",
"type",
"=",
"cloneType",
"(",
"this",
".",
"type",
",",
"false",
")",
";",
"other",
".",
"thisType",
"=",
"cloneType",
"(",
"this",
".",
"thisType",
",",
"false",
")",
";",
"other",
".",
"includeDocumentation",
"=",
"this",
".",
"includeDocumentation",
";",
"other",
".",
"originalCommentPosition",
"=",
"this",
".",
"originalCommentPosition",
";",
"other",
".",
"setConstructor",
"(",
"false",
")",
";",
"other",
".",
"setStruct",
"(",
"false",
")",
";",
"if",
"(",
"!",
"isInterface",
"(",
")",
"&&",
"other",
".",
"info",
"!=",
"null",
")",
"{",
"other",
".",
"info",
".",
"baseType",
"=",
"null",
";",
"}",
"return",
"other",
";",
"}"
] | This is used to get all nodes + the description, excluding the param nodes. Used to help in an
ES5 to ES6 class converter only. | [
"This",
"is",
"used",
"to",
"get",
"all",
"nodes",
"+",
"the",
"description",
"excluding",
"the",
"param",
"nodes",
".",
"Used",
"to",
"help",
"in",
"an",
"ES5",
"to",
"ES6",
"class",
"converter",
"only",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L607-L623 |
23,841 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.cloneConstructorDoc | public JSDocInfo cloneConstructorDoc() {
JSDocInfo other = new JSDocInfo();
other.info = this.info == null ? null : this.info.cloneConstructorDoc();
other.documentation =
this.documentation == null ? null : this.documentation.cloneConstructorDoc();
return other;
} | java | public JSDocInfo cloneConstructorDoc() {
JSDocInfo other = new JSDocInfo();
other.info = this.info == null ? null : this.info.cloneConstructorDoc();
other.documentation =
this.documentation == null ? null : this.documentation.cloneConstructorDoc();
return other;
} | [
"public",
"JSDocInfo",
"cloneConstructorDoc",
"(",
")",
"{",
"JSDocInfo",
"other",
"=",
"new",
"JSDocInfo",
"(",
")",
";",
"other",
".",
"info",
"=",
"this",
".",
"info",
"==",
"null",
"?",
"null",
":",
"this",
".",
"info",
".",
"cloneConstructorDoc",
"(",
")",
";",
"other",
".",
"documentation",
"=",
"this",
".",
"documentation",
"==",
"null",
"?",
"null",
":",
"this",
".",
"documentation",
".",
"cloneConstructorDoc",
"(",
")",
";",
"return",
"other",
";",
"}"
] | This is used to get only the parameter nodes. Used to help in an ES5 to ES6 converter class
only. | [
"This",
"is",
"used",
"to",
"get",
"only",
"the",
"parameter",
"nodes",
".",
"Used",
"to",
"help",
"in",
"an",
"ES5",
"to",
"ES6",
"converter",
"class",
"only",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L629-L635 |
23,842 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.setDeprecationReason | boolean setDeprecationReason(String reason) {
lazyInitInfo();
if (info.deprecated != null) {
return false;
}
info.deprecated = reason;
return true;
} | java | boolean setDeprecationReason(String reason) {
lazyInitInfo();
if (info.deprecated != null) {
return false;
}
info.deprecated = reason;
return true;
} | [
"boolean",
"setDeprecationReason",
"(",
"String",
"reason",
")",
"{",
"lazyInitInfo",
"(",
")",
";",
"if",
"(",
"info",
".",
"deprecated",
"!=",
"null",
")",
"{",
"return",
"false",
";",
"}",
"info",
".",
"deprecated",
"=",
"reason",
";",
"return",
"true",
";",
"}"
] | Sets the deprecation reason.
@param reason The deprecation reason | [
"Sets",
"the",
"deprecation",
"reason",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1171-L1180 |
23,843 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.addSuppression | void addSuppression(String suppression) {
lazyInitInfo();
if (info.suppressions == null) {
info.suppressions = ImmutableSet.of(suppression);
} else {
info.suppressions = new ImmutableSet.Builder<String>()
.addAll(info.suppressions)
.add(suppression)
.build();
}
} | java | void addSuppression(String suppression) {
lazyInitInfo();
if (info.suppressions == null) {
info.suppressions = ImmutableSet.of(suppression);
} else {
info.suppressions = new ImmutableSet.Builder<String>()
.addAll(info.suppressions)
.add(suppression)
.build();
}
} | [
"void",
"addSuppression",
"(",
"String",
"suppression",
")",
"{",
"lazyInitInfo",
"(",
")",
";",
"if",
"(",
"info",
".",
"suppressions",
"==",
"null",
")",
"{",
"info",
".",
"suppressions",
"=",
"ImmutableSet",
".",
"of",
"(",
"suppression",
")",
";",
"}",
"else",
"{",
"info",
".",
"suppressions",
"=",
"new",
"ImmutableSet",
".",
"Builder",
"<",
"String",
">",
"(",
")",
".",
"addAll",
"(",
"info",
".",
"suppressions",
")",
".",
"add",
"(",
"suppression",
")",
".",
"build",
"(",
")",
";",
"}",
"}"
] | Add a suppressed warning. | [
"Add",
"a",
"suppressed",
"warning",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1185-L1196 |
23,844 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.setModifies | boolean setModifies(Set<String> modifies) {
lazyInitInfo();
if (info.modifies != null) {
return false;
}
info.modifies = ImmutableSet.copyOf(modifies);
return true;
} | java | boolean setModifies(Set<String> modifies) {
lazyInitInfo();
if (info.modifies != null) {
return false;
}
info.modifies = ImmutableSet.copyOf(modifies);
return true;
} | [
"boolean",
"setModifies",
"(",
"Set",
"<",
"String",
">",
"modifies",
")",
"{",
"lazyInitInfo",
"(",
")",
";",
"if",
"(",
"info",
".",
"modifies",
"!=",
"null",
")",
"{",
"return",
"false",
";",
"}",
"info",
".",
"modifies",
"=",
"ImmutableSet",
".",
"copyOf",
"(",
"modifies",
")",
";",
"return",
"true",
";",
"}"
] | Sets modifies values.
@param modifies A list of modifies types. | [
"Sets",
"modifies",
"values",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1215-L1224 |
23,845 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.documentVersion | boolean documentVersion(String version) {
if (!lazyInitDocumentation()) {
return true;
}
if (documentation.version != null) {
return false;
}
documentation.version = version;
return true;
} | java | boolean documentVersion(String version) {
if (!lazyInitDocumentation()) {
return true;
}
if (documentation.version != null) {
return false;
}
documentation.version = version;
return true;
} | [
"boolean",
"documentVersion",
"(",
"String",
"version",
")",
"{",
"if",
"(",
"!",
"lazyInitDocumentation",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"documentation",
".",
"version",
"!=",
"null",
")",
"{",
"return",
"false",
";",
"}",
"documentation",
".",
"version",
"=",
"version",
";",
"return",
"true",
";",
"}"
] | Documents the version. | [
"Documents",
"the",
"version",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1229-L1240 |
23,846 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.declareThrows | boolean declareThrows(JSTypeExpression jsType) {
lazyInitInfo();
if (info.thrownTypes == null) {
info.thrownTypes = new ArrayList<>();
}
info.thrownTypes.add(jsType);
return true;
} | java | boolean declareThrows(JSTypeExpression jsType) {
lazyInitInfo();
if (info.thrownTypes == null) {
info.thrownTypes = new ArrayList<>();
}
info.thrownTypes.add(jsType);
return true;
} | [
"boolean",
"declareThrows",
"(",
"JSTypeExpression",
"jsType",
")",
"{",
"lazyInitInfo",
"(",
")",
";",
"if",
"(",
"info",
".",
"thrownTypes",
"==",
"null",
")",
"{",
"info",
".",
"thrownTypes",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"info",
".",
"thrownTypes",
".",
"add",
"(",
"jsType",
")",
";",
"return",
"true",
";",
"}"
] | Declares that the method throws a given type.
@param jsType The type that can be thrown by the method. | [
"Declares",
"that",
"the",
"method",
"throws",
"a",
"given",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1462-L1471 |
23,847 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getParameterType | public JSTypeExpression getParameterType(String parameter) {
if (info == null || info.parameters == null) {
return null;
}
return info.parameters.get(parameter);
} | java | public JSTypeExpression getParameterType(String parameter) {
if (info == null || info.parameters == null) {
return null;
}
return info.parameters.get(parameter);
} | [
"public",
"JSTypeExpression",
"getParameterType",
"(",
"String",
"parameter",
")",
"{",
"if",
"(",
"info",
"==",
"null",
"||",
"info",
".",
"parameters",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"info",
".",
"parameters",
".",
"get",
"(",
"parameter",
")",
";",
"}"
] | Gets the type of a given named parameter.
@param parameter the parameter's name
@return the parameter's type or {@code null} if this parameter is not
defined or has a {@code null} type | [
"Gets",
"the",
"type",
"of",
"a",
"given",
"named",
"parameter",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1488-L1493 |
23,848 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.hasParameter | public boolean hasParameter(String parameter) {
if (info == null || info.parameters == null) {
return false;
}
return info.parameters.containsKey(parameter);
} | java | public boolean hasParameter(String parameter) {
if (info == null || info.parameters == null) {
return false;
}
return info.parameters.containsKey(parameter);
} | [
"public",
"boolean",
"hasParameter",
"(",
"String",
"parameter",
")",
"{",
"if",
"(",
"info",
"==",
"null",
"||",
"info",
".",
"parameters",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"info",
".",
"parameters",
".",
"containsKey",
"(",
"parameter",
")",
";",
"}"
] | Returns whether the parameter is defined. | [
"Returns",
"whether",
"the",
"parameter",
"is",
"defined",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1498-L1503 |
23,849 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getParameterNames | public Set<String> getParameterNames() {
if (info == null || info.parameters == null) {
return ImmutableSet.of();
}
return ImmutableSet.copyOf(info.parameters.keySet());
} | java | public Set<String> getParameterNames() {
if (info == null || info.parameters == null) {
return ImmutableSet.of();
}
return ImmutableSet.copyOf(info.parameters.keySet());
} | [
"public",
"Set",
"<",
"String",
">",
"getParameterNames",
"(",
")",
"{",
"if",
"(",
"info",
"==",
"null",
"||",
"info",
".",
"parameters",
"==",
"null",
")",
"{",
"return",
"ImmutableSet",
".",
"of",
"(",
")",
";",
"}",
"return",
"ImmutableSet",
".",
"copyOf",
"(",
"info",
".",
"parameters",
".",
"keySet",
"(",
")",
")",
";",
"}"
] | Returns the set of names of the defined parameters. The iteration order
of the returned set is the order in which parameters are defined in the
JSDoc, rather than the order in which the function declares them.
@return the set of names of the defined parameters. The returned set is
immutable. | [
"Returns",
"the",
"set",
"of",
"names",
"of",
"the",
"defined",
"parameters",
".",
"The",
"iteration",
"order",
"of",
"the",
"returned",
"set",
"is",
"the",
"order",
"in",
"which",
"parameters",
"are",
"defined",
"in",
"the",
"JSDoc",
"rather",
"than",
"the",
"order",
"in",
"which",
"the",
"function",
"declares",
"them",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1523-L1528 |
23,850 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getParameterNameAt | public String getParameterNameAt(int index) {
if (info == null || info.parameters == null) {
return null;
}
if (index >= info.parameters.size()) {
return null;
}
return Iterables.get(info.parameters.keySet(), index);
} | java | public String getParameterNameAt(int index) {
if (info == null || info.parameters == null) {
return null;
}
if (index >= info.parameters.size()) {
return null;
}
return Iterables.get(info.parameters.keySet(), index);
} | [
"public",
"String",
"getParameterNameAt",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"info",
"==",
"null",
"||",
"info",
".",
"parameters",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"index",
">=",
"info",
".",
"parameters",
".",
"size",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"Iterables",
".",
"get",
"(",
"info",
".",
"parameters",
".",
"keySet",
"(",
")",
",",
"index",
")",
";",
"}"
] | Returns the nth name in the defined parameters. The iteration order
is the order in which parameters are defined in the JSDoc, rather
than the order in which the function declares them. | [
"Returns",
"the",
"nth",
"name",
"in",
"the",
"defined",
"parameters",
".",
"The",
"iteration",
"order",
"is",
"the",
"order",
"in",
"which",
"parameters",
"are",
"defined",
"in",
"the",
"JSDoc",
"rather",
"than",
"the",
"order",
"in",
"which",
"the",
"function",
"declares",
"them",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1535-L1543 |
23,851 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getThrownTypes | public List<JSTypeExpression> getThrownTypes() {
if (info == null || info.thrownTypes == null) {
return ImmutableList.of();
}
return Collections.unmodifiableList(info.thrownTypes);
} | java | public List<JSTypeExpression> getThrownTypes() {
if (info == null || info.thrownTypes == null) {
return ImmutableList.of();
}
return Collections.unmodifiableList(info.thrownTypes);
} | [
"public",
"List",
"<",
"JSTypeExpression",
">",
"getThrownTypes",
"(",
")",
"{",
"if",
"(",
"info",
"==",
"null",
"||",
"info",
".",
"thrownTypes",
"==",
"null",
")",
"{",
"return",
"ImmutableList",
".",
"of",
"(",
")",
";",
"}",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"info",
".",
"thrownTypes",
")",
";",
"}"
] | Returns the list of thrown types. | [
"Returns",
"the",
"list",
"of",
"thrown",
"types",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1592-L1597 |
23,852 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getThrowsDescriptionForType | public String getThrowsDescriptionForType(JSTypeExpression type) {
if (documentation == null || documentation.throwsDescriptions == null) {
return null;
}
return documentation.throwsDescriptions.get(type);
} | java | public String getThrowsDescriptionForType(JSTypeExpression type) {
if (documentation == null || documentation.throwsDescriptions == null) {
return null;
}
return documentation.throwsDescriptions.get(type);
} | [
"public",
"String",
"getThrowsDescriptionForType",
"(",
"JSTypeExpression",
"type",
")",
"{",
"if",
"(",
"documentation",
"==",
"null",
"||",
"documentation",
".",
"throwsDescriptions",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"documentation",
".",
"throwsDescriptions",
".",
"get",
"(",
"type",
")",
";",
"}"
] | Get the message for a given thrown type. | [
"Get",
"the",
"message",
"for",
"a",
"given",
"thrown",
"type",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1602-L1608 |
23,853 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.addImplementedInterface | boolean addImplementedInterface(JSTypeExpression interfaceName) {
lazyInitInfo();
if (info.implementedInterfaces == null) {
info.implementedInterfaces = new ArrayList<>(2);
}
if (info.implementedInterfaces.contains(interfaceName)) {
return false;
}
info.implementedInterfaces.add(interfaceName);
return true;
} | java | boolean addImplementedInterface(JSTypeExpression interfaceName) {
lazyInitInfo();
if (info.implementedInterfaces == null) {
info.implementedInterfaces = new ArrayList<>(2);
}
if (info.implementedInterfaces.contains(interfaceName)) {
return false;
}
info.implementedInterfaces.add(interfaceName);
return true;
} | [
"boolean",
"addImplementedInterface",
"(",
"JSTypeExpression",
"interfaceName",
")",
"{",
"lazyInitInfo",
"(",
")",
";",
"if",
"(",
"info",
".",
"implementedInterfaces",
"==",
"null",
")",
"{",
"info",
".",
"implementedInterfaces",
"=",
"new",
"ArrayList",
"<>",
"(",
"2",
")",
";",
"}",
"if",
"(",
"info",
".",
"implementedInterfaces",
".",
"contains",
"(",
"interfaceName",
")",
")",
"{",
"return",
"false",
";",
"}",
"info",
".",
"implementedInterfaces",
".",
"add",
"(",
"interfaceName",
")",
";",
"return",
"true",
";",
"}"
] | Adds an implemented interface. Returns whether the interface was added. If
the interface was already present in the list, it won't get added again. | [
"Adds",
"an",
"implemented",
"interface",
".",
"Returns",
"whether",
"the",
"interface",
"was",
"added",
".",
"If",
"the",
"interface",
"was",
"already",
"present",
"in",
"the",
"list",
"it",
"won",
"t",
"get",
"added",
"again",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L1943-L1953 |
23,854 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getExtendedInterfaces | public List<JSTypeExpression> getExtendedInterfaces() {
if (info == null || info.extendedInterfaces == null) {
return ImmutableList.of();
}
return Collections.unmodifiableList(info.extendedInterfaces);
} | java | public List<JSTypeExpression> getExtendedInterfaces() {
if (info == null || info.extendedInterfaces == null) {
return ImmutableList.of();
}
return Collections.unmodifiableList(info.extendedInterfaces);
} | [
"public",
"List",
"<",
"JSTypeExpression",
">",
"getExtendedInterfaces",
"(",
")",
"{",
"if",
"(",
"info",
"==",
"null",
"||",
"info",
".",
"extendedInterfaces",
"==",
"null",
")",
"{",
"return",
"ImmutableList",
".",
"of",
"(",
")",
";",
"}",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"info",
".",
"extendedInterfaces",
")",
";",
"}"
] | Returns the interfaces extended by an interface
@return An immutable list of JSTypeExpression objects that can
be resolved to types. | [
"Returns",
"the",
"interfaces",
"extended",
"by",
"an",
"interface"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L2002-L2007 |
23,855 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getSuppressions | public Set<String> getSuppressions() {
Set<String> suppressions = info == null ? null : info.suppressions;
return suppressions == null ? Collections.<String>emptySet() : suppressions;
} | java | public Set<String> getSuppressions() {
Set<String> suppressions = info == null ? null : info.suppressions;
return suppressions == null ? Collections.<String>emptySet() : suppressions;
} | [
"public",
"Set",
"<",
"String",
">",
"getSuppressions",
"(",
")",
"{",
"Set",
"<",
"String",
">",
"suppressions",
"=",
"info",
"==",
"null",
"?",
"null",
":",
"info",
".",
"suppressions",
";",
"return",
"suppressions",
"==",
"null",
"?",
"Collections",
".",
"<",
"String",
">",
"emptySet",
"(",
")",
":",
"suppressions",
";",
"}"
] | Returns the set of suppressed warnings. | [
"Returns",
"the",
"set",
"of",
"suppressed",
"warnings",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L2029-L2032 |
23,856 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getModifies | public Set<String> getModifies() {
Set<String> modifies = info == null ? null : info.modifies;
return modifies == null ? Collections.<String>emptySet() : modifies;
} | java | public Set<String> getModifies() {
Set<String> modifies = info == null ? null : info.modifies;
return modifies == null ? Collections.<String>emptySet() : modifies;
} | [
"public",
"Set",
"<",
"String",
">",
"getModifies",
"(",
")",
"{",
"Set",
"<",
"String",
">",
"modifies",
"=",
"info",
"==",
"null",
"?",
"null",
":",
"info",
".",
"modifies",
";",
"return",
"modifies",
"==",
"null",
"?",
"Collections",
".",
"<",
"String",
">",
"emptySet",
"(",
")",
":",
"modifies",
";",
"}"
] | Returns the set of sideeffect notations. | [
"Returns",
"the",
"set",
"of",
"sideeffect",
"notations",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L2037-L2040 |
23,857 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.hasDescriptionForParameter | public boolean hasDescriptionForParameter(String name) {
if (documentation == null || documentation.parameters == null) {
return false;
}
return documentation.parameters.containsKey(name);
} | java | public boolean hasDescriptionForParameter(String name) {
if (documentation == null || documentation.parameters == null) {
return false;
}
return documentation.parameters.containsKey(name);
} | [
"public",
"boolean",
"hasDescriptionForParameter",
"(",
"String",
"name",
")",
"{",
"if",
"(",
"documentation",
"==",
"null",
"||",
"documentation",
".",
"parameters",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"documentation",
".",
"parameters",
".",
"containsKey",
"(",
"name",
")",
";",
"}"
] | Returns whether a description exists for the parameter with the specified
name. | [
"Returns",
"whether",
"a",
"description",
"exists",
"for",
"the",
"parameter",
"with",
"the",
"specified",
"name",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L2057-L2063 |
23,858 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getDescriptionForParameter | public String getDescriptionForParameter(String name) {
if (documentation == null || documentation.parameters == null) {
return null;
}
return documentation.parameters.get(name);
} | java | public String getDescriptionForParameter(String name) {
if (documentation == null || documentation.parameters == null) {
return null;
}
return documentation.parameters.get(name);
} | [
"public",
"String",
"getDescriptionForParameter",
"(",
"String",
"name",
")",
"{",
"if",
"(",
"documentation",
"==",
"null",
"||",
"documentation",
".",
"parameters",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"documentation",
".",
"parameters",
".",
"get",
"(",
"name",
")",
";",
"}"
] | Returns the description for the parameter with the given name, if its
exists. | [
"Returns",
"the",
"description",
"for",
"the",
"parameter",
"with",
"the",
"given",
"name",
"if",
"its",
"exists",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L2069-L2075 |
23,859 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getMarkers | public Collection<Marker> getMarkers() {
return (documentation == null || documentation.markers == null)
? ImmutableList.<Marker>of() : documentation.markers;
} | java | public Collection<Marker> getMarkers() {
return (documentation == null || documentation.markers == null)
? ImmutableList.<Marker>of() : documentation.markers;
} | [
"public",
"Collection",
"<",
"Marker",
">",
"getMarkers",
"(",
")",
"{",
"return",
"(",
"documentation",
"==",
"null",
"||",
"documentation",
".",
"markers",
"==",
"null",
")",
"?",
"ImmutableList",
".",
"<",
"Marker",
">",
"of",
"(",
")",
":",
"documentation",
".",
"markers",
";",
"}"
] | Gets the list of all markers for the documentation in this JSDoc. | [
"Gets",
"the",
"list",
"of",
"all",
"markers",
"for",
"the",
"documentation",
"in",
"this",
"JSDoc",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L2127-L2130 |
23,860 | google/closure-compiler | src/com/google/javascript/rhino/JSDocInfo.java | JSDocInfo.getTypeTransformations | public ImmutableMap<String, Node> getTypeTransformations() {
if (info == null || info.typeTransformations == null) {
return ImmutableMap.<String, Node>of();
}
return ImmutableMap.copyOf(info.typeTransformations);
} | java | public ImmutableMap<String, Node> getTypeTransformations() {
if (info == null || info.typeTransformations == null) {
return ImmutableMap.<String, Node>of();
}
return ImmutableMap.copyOf(info.typeTransformations);
} | [
"public",
"ImmutableMap",
"<",
"String",
",",
"Node",
">",
"getTypeTransformations",
"(",
")",
"{",
"if",
"(",
"info",
"==",
"null",
"||",
"info",
".",
"typeTransformations",
"==",
"null",
")",
"{",
"return",
"ImmutableMap",
".",
"<",
"String",
",",
"Node",
">",
"of",
"(",
")",
";",
"}",
"return",
"ImmutableMap",
".",
"copyOf",
"(",
"info",
".",
"typeTransformations",
")",
";",
"}"
] | Gets the type transformations. | [
"Gets",
"the",
"type",
"transformations",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/JSDocInfo.java#L2145-L2150 |
23,861 | google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.removeScopesForScript | void removeScopesForScript(String scriptName) {
memoized.keySet().removeIf(n -> scriptName.equals(NodeUtil.getSourceName(n)));
} | java | void removeScopesForScript(String scriptName) {
memoized.keySet().removeIf(n -> scriptName.equals(NodeUtil.getSourceName(n)));
} | [
"void",
"removeScopesForScript",
"(",
"String",
"scriptName",
")",
"{",
"memoized",
".",
"keySet",
"(",
")",
".",
"removeIf",
"(",
"n",
"->",
"scriptName",
".",
"equals",
"(",
"NodeUtil",
".",
"getSourceName",
"(",
"n",
")",
")",
")",
";",
"}"
] | Removes all scopes with root nodes from a given script file.
@param scriptName the name of the script file to remove nodes for. | [
"Removes",
"all",
"scopes",
"with",
"root",
"nodes",
"from",
"a",
"given",
"script",
"file",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L350-L352 |
23,862 | google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.createScope | TypedScope createScope(Node n) {
TypedScope s = memoized.get(n);
return s != null
? s
: createScope(n, createScope(NodeUtil.getEnclosingScopeRoot(n.getParent())));
} | java | TypedScope createScope(Node n) {
TypedScope s = memoized.get(n);
return s != null
? s
: createScope(n, createScope(NodeUtil.getEnclosingScopeRoot(n.getParent())));
} | [
"TypedScope",
"createScope",
"(",
"Node",
"n",
")",
"{",
"TypedScope",
"s",
"=",
"memoized",
".",
"get",
"(",
"n",
")",
";",
"return",
"s",
"!=",
"null",
"?",
"s",
":",
"createScope",
"(",
"n",
",",
"createScope",
"(",
"NodeUtil",
".",
"getEnclosingScopeRoot",
"(",
"n",
".",
"getParent",
"(",
")",
")",
")",
")",
";",
"}"
] | Create a scope if it doesn't already exist, looking up in the map for the parent scope. | [
"Create",
"a",
"scope",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"looking",
"up",
"in",
"the",
"map",
"for",
"the",
"parent",
"scope",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L355-L360 |
23,863 | google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.createScope | @Override
public TypedScope createScope(Node root, AbstractScope<?, ?> parent) {
checkArgument(parent == null || parent instanceof TypedScope);
TypedScope typedParent = (TypedScope) parent;
TypedScope scope = memoized.get(root);
if (scope != null) {
checkState(typedParent == scope.getParent());
} else {
scope = createScopeInternal(root, typedParent);
memoized.put(root, scope);
}
return scope;
} | java | @Override
public TypedScope createScope(Node root, AbstractScope<?, ?> parent) {
checkArgument(parent == null || parent instanceof TypedScope);
TypedScope typedParent = (TypedScope) parent;
TypedScope scope = memoized.get(root);
if (scope != null) {
checkState(typedParent == scope.getParent());
} else {
scope = createScopeInternal(root, typedParent);
memoized.put(root, scope);
}
return scope;
} | [
"@",
"Override",
"public",
"TypedScope",
"createScope",
"(",
"Node",
"root",
",",
"AbstractScope",
"<",
"?",
",",
"?",
">",
"parent",
")",
"{",
"checkArgument",
"(",
"parent",
"==",
"null",
"||",
"parent",
"instanceof",
"TypedScope",
")",
";",
"TypedScope",
"typedParent",
"=",
"(",
"TypedScope",
")",
"parent",
";",
"TypedScope",
"scope",
"=",
"memoized",
".",
"get",
"(",
"root",
")",
";",
"if",
"(",
"scope",
"!=",
"null",
")",
"{",
"checkState",
"(",
"typedParent",
"==",
"scope",
".",
"getParent",
"(",
")",
")",
";",
"}",
"else",
"{",
"scope",
"=",
"createScopeInternal",
"(",
"root",
",",
"typedParent",
")",
";",
"memoized",
".",
"put",
"(",
"root",
",",
"scope",
")",
";",
"}",
"return",
"scope",
";",
"}"
] | Creates a scope with all types declared. Declares newly discovered types
and type properties in the type registry. | [
"Creates",
"a",
"scope",
"with",
"all",
"types",
"declared",
".",
"Declares",
"newly",
"discovered",
"types",
"and",
"type",
"properties",
"in",
"the",
"type",
"registry",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L366-L379 |
23,864 | google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.initializeModuleScope | private void initializeModuleScope(Node moduleBody, Module module, TypedScope moduleScope) {
if (module.metadata().isGoogModule()) {
declareExportsInModuleScope(module, moduleBody, moduleScope);
markGoogModuleExportsAsConst(module);
}
} | java | private void initializeModuleScope(Node moduleBody, Module module, TypedScope moduleScope) {
if (module.metadata().isGoogModule()) {
declareExportsInModuleScope(module, moduleBody, moduleScope);
markGoogModuleExportsAsConst(module);
}
} | [
"private",
"void",
"initializeModuleScope",
"(",
"Node",
"moduleBody",
",",
"Module",
"module",
",",
"TypedScope",
"moduleScope",
")",
"{",
"if",
"(",
"module",
".",
"metadata",
"(",
")",
".",
"isGoogModule",
"(",
")",
")",
"{",
"declareExportsInModuleScope",
"(",
"module",
",",
"moduleBody",
",",
"moduleScope",
")",
";",
"markGoogModuleExportsAsConst",
"(",
"module",
")",
";",
"}",
"}"
] | Builds the beginning of a module-scope. This can be an ES module or a goog.module. | [
"Builds",
"the",
"beginning",
"of",
"a",
"module",
"-",
"scope",
".",
"This",
"can",
"be",
"an",
"ES",
"module",
"or",
"a",
"goog",
".",
"module",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L465-L470 |
23,865 | google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.declareExportsInModuleScope | private void declareExportsInModuleScope(
Module googModule, Node moduleBody, TypedScope moduleScope) {
if (!googModule.namespace().containsKey(Export.NAMESPACE)) {
// The goog.module never assigns `exports = ...`, so declare `exports` as an object literal.
moduleScope.declare(
"exports",
googModule.metadata().rootNode(),
typeRegistry.createAnonymousObjectType(null),
compiler.getInput(moduleBody.getInputId()),
/* inferred= */ false);
}
} | java | private void declareExportsInModuleScope(
Module googModule, Node moduleBody, TypedScope moduleScope) {
if (!googModule.namespace().containsKey(Export.NAMESPACE)) {
// The goog.module never assigns `exports = ...`, so declare `exports` as an object literal.
moduleScope.declare(
"exports",
googModule.metadata().rootNode(),
typeRegistry.createAnonymousObjectType(null),
compiler.getInput(moduleBody.getInputId()),
/* inferred= */ false);
}
} | [
"private",
"void",
"declareExportsInModuleScope",
"(",
"Module",
"googModule",
",",
"Node",
"moduleBody",
",",
"TypedScope",
"moduleScope",
")",
"{",
"if",
"(",
"!",
"googModule",
".",
"namespace",
"(",
")",
".",
"containsKey",
"(",
"Export",
".",
"NAMESPACE",
")",
")",
"{",
"// The goog.module never assigns `exports = ...`, so declare `exports` as an object literal.",
"moduleScope",
".",
"declare",
"(",
"\"exports\"",
",",
"googModule",
".",
"metadata",
"(",
")",
".",
"rootNode",
"(",
")",
",",
"typeRegistry",
".",
"createAnonymousObjectType",
"(",
"null",
")",
",",
"compiler",
".",
"getInput",
"(",
"moduleBody",
".",
"getInputId",
"(",
")",
")",
",",
"/* inferred= */",
"false",
")",
";",
"}",
"}"
] | Ensures that the name `exports` is declared in goog.module scope.
<p>If a goog.module explicitly assigns to exports, we want to treat that assignment inside the
scope as if it were a declaration: `const exports = ...`. This method only handles cases where
we want to treat exports as implicitly declared. | [
"Ensures",
"that",
"the",
"name",
"exports",
"is",
"declared",
"in",
"goog",
".",
"module",
"scope",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L479-L490 |
23,866 | google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.gatherAllProvides | private void gatherAllProvides(Node root) {
if (!processClosurePrimitives) {
return;
}
Node externs = root.getFirstChild();
Node js = root.getSecondChild();
Map<String, ProvidedName> providedNames =
new ProcessClosureProvidesAndRequires(
compiler,
/* preprocessorSymbolTable= */ null,
CheckLevel.OFF,
/* preserveGoogProvidesAndRequires= */ true)
.collectProvidedNames(externs, js);
for (ProvidedName name : providedNames.values()) {
if (name.getCandidateDefinition() != null) {
// This name will be defined eventually. Don't worry about it.
Node firstDefinitionNode = name.getCandidateDefinition();
if (NodeUtil.isExprAssign(firstDefinitionNode)
&& firstDefinitionNode.getFirstFirstChild().isName()) {
// Treat assignments of provided names as declarations.
undeclaredNamesForClosure.add(firstDefinitionNode.getFirstFirstChild());
}
} else if (name.getFirstProvideCall() != null
&& NodeUtil.isExprCall(name.getFirstProvideCall())) {
// This name is implicitly created by a goog.provide call; declare it in the scope once
// reaching the provide call.
providedNamesFromCall.put(name.getFirstProvideCall(), name);
}
}
} | java | private void gatherAllProvides(Node root) {
if (!processClosurePrimitives) {
return;
}
Node externs = root.getFirstChild();
Node js = root.getSecondChild();
Map<String, ProvidedName> providedNames =
new ProcessClosureProvidesAndRequires(
compiler,
/* preprocessorSymbolTable= */ null,
CheckLevel.OFF,
/* preserveGoogProvidesAndRequires= */ true)
.collectProvidedNames(externs, js);
for (ProvidedName name : providedNames.values()) {
if (name.getCandidateDefinition() != null) {
// This name will be defined eventually. Don't worry about it.
Node firstDefinitionNode = name.getCandidateDefinition();
if (NodeUtil.isExprAssign(firstDefinitionNode)
&& firstDefinitionNode.getFirstFirstChild().isName()) {
// Treat assignments of provided names as declarations.
undeclaredNamesForClosure.add(firstDefinitionNode.getFirstFirstChild());
}
} else if (name.getFirstProvideCall() != null
&& NodeUtil.isExprCall(name.getFirstProvideCall())) {
// This name is implicitly created by a goog.provide call; declare it in the scope once
// reaching the provide call.
providedNamesFromCall.put(name.getFirstProvideCall(), name);
}
}
} | [
"private",
"void",
"gatherAllProvides",
"(",
"Node",
"root",
")",
"{",
"if",
"(",
"!",
"processClosurePrimitives",
")",
"{",
"return",
";",
"}",
"Node",
"externs",
"=",
"root",
".",
"getFirstChild",
"(",
")",
";",
"Node",
"js",
"=",
"root",
".",
"getSecondChild",
"(",
")",
";",
"Map",
"<",
"String",
",",
"ProvidedName",
">",
"providedNames",
"=",
"new",
"ProcessClosureProvidesAndRequires",
"(",
"compiler",
",",
"/* preprocessorSymbolTable= */",
"null",
",",
"CheckLevel",
".",
"OFF",
",",
"/* preserveGoogProvidesAndRequires= */",
"true",
")",
".",
"collectProvidedNames",
"(",
"externs",
",",
"js",
")",
";",
"for",
"(",
"ProvidedName",
"name",
":",
"providedNames",
".",
"values",
"(",
")",
")",
"{",
"if",
"(",
"name",
".",
"getCandidateDefinition",
"(",
")",
"!=",
"null",
")",
"{",
"// This name will be defined eventually. Don't worry about it.",
"Node",
"firstDefinitionNode",
"=",
"name",
".",
"getCandidateDefinition",
"(",
")",
";",
"if",
"(",
"NodeUtil",
".",
"isExprAssign",
"(",
"firstDefinitionNode",
")",
"&&",
"firstDefinitionNode",
".",
"getFirstFirstChild",
"(",
")",
".",
"isName",
"(",
")",
")",
"{",
"// Treat assignments of provided names as declarations.",
"undeclaredNamesForClosure",
".",
"add",
"(",
"firstDefinitionNode",
".",
"getFirstFirstChild",
"(",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"name",
".",
"getFirstProvideCall",
"(",
")",
"!=",
"null",
"&&",
"NodeUtil",
".",
"isExprCall",
"(",
"name",
".",
"getFirstProvideCall",
"(",
")",
")",
")",
"{",
"// This name is implicitly created by a goog.provide call; declare it in the scope once",
"// reaching the provide call.",
"providedNamesFromCall",
".",
"put",
"(",
"name",
".",
"getFirstProvideCall",
"(",
")",
",",
"name",
")",
";",
"}",
"}",
"}"
] | Gathers all namespaces created by goog.provide and any definitions in code.
<p>This method does not actually declare anything in the scope. In order to accurately report
redefinition warnings, wait to declare implicit names until the actual goog.provide call.
@param root The global ROOT or a SCRIPT | [
"Gathers",
"all",
"namespaces",
"created",
"by",
"goog",
".",
"provide",
"and",
"any",
"definitions",
"in",
"code",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L518-L549 |
23,867 | google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.patchGlobalScope | void patchGlobalScope(TypedScope globalScope, Node scriptRoot) {
// Preconditions: This is supposed to be called only on (named) SCRIPT nodes
// and a global typed scope should have been generated already.
checkState(scriptRoot.isScript());
checkNotNull(globalScope);
checkState(globalScope.isGlobal());
String scriptName = NodeUtil.getSourceName(scriptRoot);
checkNotNull(scriptName);
Predicate<Node> inScript = n -> scriptName.equals(NodeUtil.getSourceName(n));
escapedVarNames.removeIf(var -> inScript.test(var.getScopeRoot()));
assignedVarNames.removeIf(var -> inScript.test(var.getScopeRoot()));
functionsWithNonEmptyReturns.removeIf(inScript);
new FirstOrderFunctionAnalyzer().process(null, scriptRoot);
// TODO(bashir): Variable declaration is not the only side effect of last
// global scope generation but here we only wipe that part off.
// Remove all variables that were previously declared in this scripts.
// First find all vars to remove then remove them because of iterator.
List<TypedVar> varsToRemove = new ArrayList<>();
for (TypedVar oldVar : globalScope.getVarIterable()) {
if (scriptName.equals(oldVar.getInputName())) {
varsToRemove.add(oldVar);
}
}
for (TypedVar var : varsToRemove) {
// By removing the type here, we're potentially invalidating any files that contain
// references to this type. Those files will need to be recompiled. Ideally, this
// was handled by the compiler (see b/29121507), but in the meantime users of incremental
// compilation will need to manage it themselves (e.g., by recompiling dependent files
// based on the dep graph).
String typeName = var.getName();
globalScope.undeclare(var);
globalScope.getTypeOfThis().toObjectType().removeProperty(typeName);
if (typeRegistry.getType(globalScope, typeName) != null) {
typeRegistry.removeType(globalScope, typeName);
}
}
// Now re-traverse the given script.
NormalScopeBuilder scopeBuilder = new NormalScopeBuilder(globalScope, null);
NodeTraversal.traverse(compiler, scriptRoot, scopeBuilder);
} | java | void patchGlobalScope(TypedScope globalScope, Node scriptRoot) {
// Preconditions: This is supposed to be called only on (named) SCRIPT nodes
// and a global typed scope should have been generated already.
checkState(scriptRoot.isScript());
checkNotNull(globalScope);
checkState(globalScope.isGlobal());
String scriptName = NodeUtil.getSourceName(scriptRoot);
checkNotNull(scriptName);
Predicate<Node> inScript = n -> scriptName.equals(NodeUtil.getSourceName(n));
escapedVarNames.removeIf(var -> inScript.test(var.getScopeRoot()));
assignedVarNames.removeIf(var -> inScript.test(var.getScopeRoot()));
functionsWithNonEmptyReturns.removeIf(inScript);
new FirstOrderFunctionAnalyzer().process(null, scriptRoot);
// TODO(bashir): Variable declaration is not the only side effect of last
// global scope generation but here we only wipe that part off.
// Remove all variables that were previously declared in this scripts.
// First find all vars to remove then remove them because of iterator.
List<TypedVar> varsToRemove = new ArrayList<>();
for (TypedVar oldVar : globalScope.getVarIterable()) {
if (scriptName.equals(oldVar.getInputName())) {
varsToRemove.add(oldVar);
}
}
for (TypedVar var : varsToRemove) {
// By removing the type here, we're potentially invalidating any files that contain
// references to this type. Those files will need to be recompiled. Ideally, this
// was handled by the compiler (see b/29121507), but in the meantime users of incremental
// compilation will need to manage it themselves (e.g., by recompiling dependent files
// based on the dep graph).
String typeName = var.getName();
globalScope.undeclare(var);
globalScope.getTypeOfThis().toObjectType().removeProperty(typeName);
if (typeRegistry.getType(globalScope, typeName) != null) {
typeRegistry.removeType(globalScope, typeName);
}
}
// Now re-traverse the given script.
NormalScopeBuilder scopeBuilder = new NormalScopeBuilder(globalScope, null);
NodeTraversal.traverse(compiler, scriptRoot, scopeBuilder);
} | [
"void",
"patchGlobalScope",
"(",
"TypedScope",
"globalScope",
",",
"Node",
"scriptRoot",
")",
"{",
"// Preconditions: This is supposed to be called only on (named) SCRIPT nodes",
"// and a global typed scope should have been generated already.",
"checkState",
"(",
"scriptRoot",
".",
"isScript",
"(",
")",
")",
";",
"checkNotNull",
"(",
"globalScope",
")",
";",
"checkState",
"(",
"globalScope",
".",
"isGlobal",
"(",
")",
")",
";",
"String",
"scriptName",
"=",
"NodeUtil",
".",
"getSourceName",
"(",
"scriptRoot",
")",
";",
"checkNotNull",
"(",
"scriptName",
")",
";",
"Predicate",
"<",
"Node",
">",
"inScript",
"=",
"n",
"->",
"scriptName",
".",
"equals",
"(",
"NodeUtil",
".",
"getSourceName",
"(",
"n",
")",
")",
";",
"escapedVarNames",
".",
"removeIf",
"(",
"var",
"->",
"inScript",
".",
"test",
"(",
"var",
".",
"getScopeRoot",
"(",
")",
")",
")",
";",
"assignedVarNames",
".",
"removeIf",
"(",
"var",
"->",
"inScript",
".",
"test",
"(",
"var",
".",
"getScopeRoot",
"(",
")",
")",
")",
";",
"functionsWithNonEmptyReturns",
".",
"removeIf",
"(",
"inScript",
")",
";",
"new",
"FirstOrderFunctionAnalyzer",
"(",
")",
".",
"process",
"(",
"null",
",",
"scriptRoot",
")",
";",
"// TODO(bashir): Variable declaration is not the only side effect of last",
"// global scope generation but here we only wipe that part off.",
"// Remove all variables that were previously declared in this scripts.",
"// First find all vars to remove then remove them because of iterator.",
"List",
"<",
"TypedVar",
">",
"varsToRemove",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"TypedVar",
"oldVar",
":",
"globalScope",
".",
"getVarIterable",
"(",
")",
")",
"{",
"if",
"(",
"scriptName",
".",
"equals",
"(",
"oldVar",
".",
"getInputName",
"(",
")",
")",
")",
"{",
"varsToRemove",
".",
"add",
"(",
"oldVar",
")",
";",
"}",
"}",
"for",
"(",
"TypedVar",
"var",
":",
"varsToRemove",
")",
"{",
"// By removing the type here, we're potentially invalidating any files that contain",
"// references to this type. Those files will need to be recompiled. Ideally, this",
"// was handled by the compiler (see b/29121507), but in the meantime users of incremental",
"// compilation will need to manage it themselves (e.g., by recompiling dependent files",
"// based on the dep graph).",
"String",
"typeName",
"=",
"var",
".",
"getName",
"(",
")",
";",
"globalScope",
".",
"undeclare",
"(",
"var",
")",
";",
"globalScope",
".",
"getTypeOfThis",
"(",
")",
".",
"toObjectType",
"(",
")",
".",
"removeProperty",
"(",
"typeName",
")",
";",
"if",
"(",
"typeRegistry",
".",
"getType",
"(",
"globalScope",
",",
"typeName",
")",
"!=",
"null",
")",
"{",
"typeRegistry",
".",
"removeType",
"(",
"globalScope",
",",
"typeName",
")",
";",
"}",
"}",
"// Now re-traverse the given script.",
"NormalScopeBuilder",
"scopeBuilder",
"=",
"new",
"NormalScopeBuilder",
"(",
"globalScope",
",",
"null",
")",
";",
"NodeTraversal",
".",
"traverse",
"(",
"compiler",
",",
"scriptRoot",
",",
"scopeBuilder",
")",
";",
"}"
] | Patches a given global scope by removing variables previously declared in a script and
re-traversing a new version of that script.
@param globalScope The global scope generated by {@code createScope}.
@param scriptRoot The script that is modified. | [
"Patches",
"a",
"given",
"global",
"scope",
"by",
"removing",
"variables",
"previously",
"declared",
"in",
"a",
"script",
"and",
"re",
"-",
"traversing",
"a",
"new",
"version",
"of",
"that",
"script",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L558-L603 |
23,868 | google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.setDeferredType | void setDeferredType(Node node, JSType type) {
// Other parts of this pass may read the not-yet-resolved type off the node.
// (like when we set the LHS of an assign with a typed RHS function.)
node.setJSType(type);
deferredSetTypes.add(new DeferredSetType(node, type));
} | java | void setDeferredType(Node node, JSType type) {
// Other parts of this pass may read the not-yet-resolved type off the node.
// (like when we set the LHS of an assign with a typed RHS function.)
node.setJSType(type);
deferredSetTypes.add(new DeferredSetType(node, type));
} | [
"void",
"setDeferredType",
"(",
"Node",
"node",
",",
"JSType",
"type",
")",
"{",
"// Other parts of this pass may read the not-yet-resolved type off the node.",
"// (like when we set the LHS of an assign with a typed RHS function.)",
"node",
".",
"setJSType",
"(",
"type",
")",
";",
"deferredSetTypes",
".",
"add",
"(",
"new",
"DeferredSetType",
"(",
"node",
",",
"type",
")",
")",
";",
"}"
] | Set the type for a node now, and enqueue it to be updated with a resolved type later. | [
"Set",
"the",
"type",
"for",
"a",
"node",
"now",
"and",
"enqueue",
"it",
"to",
"be",
"updated",
"with",
"a",
"resolved",
"type",
"later",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L656-L661 |
23,869 | google/closure-compiler | src/com/google/javascript/jscomp/DefaultNameGenerator.java | DefaultNameGenerator.reserveCharacters | CharPriority[] reserveCharacters(char[] chars, char[] reservedCharacters) {
if (reservedCharacters == null || reservedCharacters.length == 0) {
CharPriority[] result = new CharPriority[chars.length];
for (int i = 0; i < chars.length; i++) {
result[i] = priorityLookupMap.get(chars[i]);
}
return result;
}
Set<Character> charSet = new LinkedHashSet<>(Chars.asList(chars));
for (char reservedCharacter : reservedCharacters) {
charSet.remove(reservedCharacter);
}
CharPriority[] result = new CharPriority[charSet.size()];
int index = 0;
for (char c : charSet) {
result[index++] = priorityLookupMap.get(c);
}
return result;
} | java | CharPriority[] reserveCharacters(char[] chars, char[] reservedCharacters) {
if (reservedCharacters == null || reservedCharacters.length == 0) {
CharPriority[] result = new CharPriority[chars.length];
for (int i = 0; i < chars.length; i++) {
result[i] = priorityLookupMap.get(chars[i]);
}
return result;
}
Set<Character> charSet = new LinkedHashSet<>(Chars.asList(chars));
for (char reservedCharacter : reservedCharacters) {
charSet.remove(reservedCharacter);
}
CharPriority[] result = new CharPriority[charSet.size()];
int index = 0;
for (char c : charSet) {
result[index++] = priorityLookupMap.get(c);
}
return result;
} | [
"CharPriority",
"[",
"]",
"reserveCharacters",
"(",
"char",
"[",
"]",
"chars",
",",
"char",
"[",
"]",
"reservedCharacters",
")",
"{",
"if",
"(",
"reservedCharacters",
"==",
"null",
"||",
"reservedCharacters",
".",
"length",
"==",
"0",
")",
"{",
"CharPriority",
"[",
"]",
"result",
"=",
"new",
"CharPriority",
"[",
"chars",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"chars",
".",
"length",
";",
"i",
"++",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"priorityLookupMap",
".",
"get",
"(",
"chars",
"[",
"i",
"]",
")",
";",
"}",
"return",
"result",
";",
"}",
"Set",
"<",
"Character",
">",
"charSet",
"=",
"new",
"LinkedHashSet",
"<>",
"(",
"Chars",
".",
"asList",
"(",
"chars",
")",
")",
";",
"for",
"(",
"char",
"reservedCharacter",
":",
"reservedCharacters",
")",
"{",
"charSet",
".",
"remove",
"(",
"reservedCharacter",
")",
";",
"}",
"CharPriority",
"[",
"]",
"result",
"=",
"new",
"CharPriority",
"[",
"charSet",
".",
"size",
"(",
")",
"]",
";",
"int",
"index",
"=",
"0",
";",
"for",
"(",
"char",
"c",
":",
"charSet",
")",
"{",
"result",
"[",
"index",
"++",
"]",
"=",
"priorityLookupMap",
".",
"get",
"(",
"c",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Provides the array of available characters based on the specified arrays.
@param chars The list of characters that are legal
@param reservedCharacters The characters that should not be used
@return An array of characters to use. Will return the chars array if
reservedCharacters is null or empty, otherwise creates a new array. | [
"Provides",
"the",
"array",
"of",
"available",
"characters",
"based",
"on",
"the",
"specified",
"arrays",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DefaultNameGenerator.java#L222-L241 |
23,870 | google/closure-compiler | src/com/google/javascript/jscomp/DefaultNameGenerator.java | DefaultNameGenerator.checkPrefix | private void checkPrefix(String prefix) {
if (prefix.length() > 0) {
// Make sure that prefix starts with a legal character.
if (!contains(firstChars, prefix.charAt(0))) {
char[] chars = new char[firstChars.length];
for (int i = 0; i < chars.length; i++) {
chars[i] = firstChars[i].name;
}
throw new IllegalArgumentException(
"prefix must start with one of: " + Arrays.toString(chars));
}
for (int pos = 1; pos < prefix.length(); ++pos) {
char[] chars = new char[nonFirstChars.length];
for (int i = 0; i < chars.length; i++) {
chars[i] = nonFirstChars[i].name;
}
if (!contains(nonFirstChars, prefix.charAt(pos))) {
throw new IllegalArgumentException(
"prefix has invalid characters, must be one of: "
+ Arrays.toString(chars));
}
}
}
} | java | private void checkPrefix(String prefix) {
if (prefix.length() > 0) {
// Make sure that prefix starts with a legal character.
if (!contains(firstChars, prefix.charAt(0))) {
char[] chars = new char[firstChars.length];
for (int i = 0; i < chars.length; i++) {
chars[i] = firstChars[i].name;
}
throw new IllegalArgumentException(
"prefix must start with one of: " + Arrays.toString(chars));
}
for (int pos = 1; pos < prefix.length(); ++pos) {
char[] chars = new char[nonFirstChars.length];
for (int i = 0; i < chars.length; i++) {
chars[i] = nonFirstChars[i].name;
}
if (!contains(nonFirstChars, prefix.charAt(pos))) {
throw new IllegalArgumentException(
"prefix has invalid characters, must be one of: "
+ Arrays.toString(chars));
}
}
}
} | [
"private",
"void",
"checkPrefix",
"(",
"String",
"prefix",
")",
"{",
"if",
"(",
"prefix",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"// Make sure that prefix starts with a legal character.",
"if",
"(",
"!",
"contains",
"(",
"firstChars",
",",
"prefix",
".",
"charAt",
"(",
"0",
")",
")",
")",
"{",
"char",
"[",
"]",
"chars",
"=",
"new",
"char",
"[",
"firstChars",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"chars",
".",
"length",
";",
"i",
"++",
")",
"{",
"chars",
"[",
"i",
"]",
"=",
"firstChars",
"[",
"i",
"]",
".",
"name",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"prefix must start with one of: \"",
"+",
"Arrays",
".",
"toString",
"(",
"chars",
")",
")",
";",
"}",
"for",
"(",
"int",
"pos",
"=",
"1",
";",
"pos",
"<",
"prefix",
".",
"length",
"(",
")",
";",
"++",
"pos",
")",
"{",
"char",
"[",
"]",
"chars",
"=",
"new",
"char",
"[",
"nonFirstChars",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"chars",
".",
"length",
";",
"i",
"++",
")",
"{",
"chars",
"[",
"i",
"]",
"=",
"nonFirstChars",
"[",
"i",
"]",
".",
"name",
";",
"}",
"if",
"(",
"!",
"contains",
"(",
"nonFirstChars",
",",
"prefix",
".",
"charAt",
"(",
"pos",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"prefix has invalid characters, must be one of: \"",
"+",
"Arrays",
".",
"toString",
"(",
"chars",
")",
")",
";",
"}",
"}",
"}",
"}"
] | Validates a name prefix. | [
"Validates",
"a",
"name",
"prefix",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DefaultNameGenerator.java#L244-L267 |
23,871 | google/closure-compiler | src/com/google/javascript/jscomp/DefaultNameGenerator.java | DefaultNameGenerator.generateNextName | @Override
public String generateNextName() {
String name;
do {
name = prefix;
int i = nameCount;
if (name.isEmpty()) {
int pos = i % firstChars.length;
name = String.valueOf(firstChars[pos].name);
i /= firstChars.length;
}
while (i > 0) {
i--;
int pos = i % nonFirstChars.length;
name += nonFirstChars[pos].name;
i /= nonFirstChars.length;
}
nameCount++;
// Make sure it's not a JS keyword or reserved name.
} while (TokenStream.isKeyword(name) || reservedNames.contains(name));
return name;
} | java | @Override
public String generateNextName() {
String name;
do {
name = prefix;
int i = nameCount;
if (name.isEmpty()) {
int pos = i % firstChars.length;
name = String.valueOf(firstChars[pos].name);
i /= firstChars.length;
}
while (i > 0) {
i--;
int pos = i % nonFirstChars.length;
name += nonFirstChars[pos].name;
i /= nonFirstChars.length;
}
nameCount++;
// Make sure it's not a JS keyword or reserved name.
} while (TokenStream.isKeyword(name) || reservedNames.contains(name));
return name;
} | [
"@",
"Override",
"public",
"String",
"generateNextName",
"(",
")",
"{",
"String",
"name",
";",
"do",
"{",
"name",
"=",
"prefix",
";",
"int",
"i",
"=",
"nameCount",
";",
"if",
"(",
"name",
".",
"isEmpty",
"(",
")",
")",
"{",
"int",
"pos",
"=",
"i",
"%",
"firstChars",
".",
"length",
";",
"name",
"=",
"String",
".",
"valueOf",
"(",
"firstChars",
"[",
"pos",
"]",
".",
"name",
")",
";",
"i",
"/=",
"firstChars",
".",
"length",
";",
"}",
"while",
"(",
"i",
">",
"0",
")",
"{",
"i",
"--",
";",
"int",
"pos",
"=",
"i",
"%",
"nonFirstChars",
".",
"length",
";",
"name",
"+=",
"nonFirstChars",
"[",
"pos",
"]",
".",
"name",
";",
"i",
"/=",
"nonFirstChars",
".",
"length",
";",
"}",
"nameCount",
"++",
";",
"// Make sure it's not a JS keyword or reserved name.",
"}",
"while",
"(",
"TokenStream",
".",
"isKeyword",
"(",
"name",
")",
"||",
"reservedNames",
".",
"contains",
"(",
"name",
")",
")",
";",
"return",
"name",
";",
"}"
] | Generates the next short name. | [
"Generates",
"the",
"next",
"short",
"name",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DefaultNameGenerator.java#L281-L307 |
23,872 | google/closure-compiler | src/com/google/javascript/jscomp/CheckMissingReturn.java | CheckMissingReturn.fastAllPathsReturnCheck | private boolean fastAllPathsReturnCheck(ControlFlowGraph<Node> cfg) {
for (DiGraphEdge<Node, Branch> s : cfg.getImplicitReturn().getInEdges()) {
Node n = s.getSource().getValue();
// NOTE(dimvar): it is possible to change ControlFlowAnalysis.java, so
// that the calls that always throw are treated in the same way as THROW
// in the CFG. Then, we would not need to use the coding convention here.
if (!n.isReturn() && !convention.isFunctionCallThatAlwaysThrows(n)) {
return false;
}
}
return true;
} | java | private boolean fastAllPathsReturnCheck(ControlFlowGraph<Node> cfg) {
for (DiGraphEdge<Node, Branch> s : cfg.getImplicitReturn().getInEdges()) {
Node n = s.getSource().getValue();
// NOTE(dimvar): it is possible to change ControlFlowAnalysis.java, so
// that the calls that always throw are treated in the same way as THROW
// in the CFG. Then, we would not need to use the coding convention here.
if (!n.isReturn() && !convention.isFunctionCallThatAlwaysThrows(n)) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"fastAllPathsReturnCheck",
"(",
"ControlFlowGraph",
"<",
"Node",
">",
"cfg",
")",
"{",
"for",
"(",
"DiGraphEdge",
"<",
"Node",
",",
"Branch",
">",
"s",
":",
"cfg",
".",
"getImplicitReturn",
"(",
")",
".",
"getInEdges",
"(",
")",
")",
"{",
"Node",
"n",
"=",
"s",
".",
"getSource",
"(",
")",
".",
"getValue",
"(",
")",
";",
"// NOTE(dimvar): it is possible to change ControlFlowAnalysis.java, so",
"// that the calls that always throw are treated in the same way as THROW",
"// in the CFG. Then, we would not need to use the coding convention here.",
"if",
"(",
"!",
"n",
".",
"isReturn",
"(",
")",
"&&",
"!",
"convention",
".",
"isFunctionCallThatAlwaysThrows",
"(",
"n",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Fast check to see if all execution paths contain a return statement.
May spuriously report that a return statement is missing.
@return true if all paths return, converse not necessarily true | [
"Fast",
"check",
"to",
"see",
"if",
"all",
"execution",
"paths",
"contain",
"a",
"return",
"statement",
".",
"May",
"spuriously",
"report",
"that",
"a",
"return",
"statement",
"is",
"missing",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckMissingReturn.java#L140-L151 |
23,873 | google/closure-compiler | src/com/google/javascript/jscomp/CheckMissingReturn.java | CheckMissingReturn.getExplicitReturnTypeIfExpected | @Nullable
private JSType getExplicitReturnTypeIfExpected(Node scopeRoot) {
if (!scopeRoot.isFunction()) {
// Nothing to do in a global/module/block scope.
return null;
}
FunctionType scopeType = JSType.toMaybeFunctionType(scopeRoot.getJSType());
if (scopeType == null) {
return null;
}
if (isEmptyFunction(scopeRoot)) {
return null;
}
if (scopeType.isConstructor()) {
return null;
}
JSType returnType = scopeType.getReturnType();
if (returnType == null) {
return null;
}
if (scopeRoot.isAsyncFunction()) {
// Unwrap the declared return type (e.g. "!Promise<number>" becomes "number")
returnType = Promises.getTemplateTypeOfThenable(compiler.getTypeRegistry(), returnType);
}
if (!isVoidOrUnknown(returnType)) {
return returnType;
}
return null;
} | java | @Nullable
private JSType getExplicitReturnTypeIfExpected(Node scopeRoot) {
if (!scopeRoot.isFunction()) {
// Nothing to do in a global/module/block scope.
return null;
}
FunctionType scopeType = JSType.toMaybeFunctionType(scopeRoot.getJSType());
if (scopeType == null) {
return null;
}
if (isEmptyFunction(scopeRoot)) {
return null;
}
if (scopeType.isConstructor()) {
return null;
}
JSType returnType = scopeType.getReturnType();
if (returnType == null) {
return null;
}
if (scopeRoot.isAsyncFunction()) {
// Unwrap the declared return type (e.g. "!Promise<number>" becomes "number")
returnType = Promises.getTemplateTypeOfThenable(compiler.getTypeRegistry(), returnType);
}
if (!isVoidOrUnknown(returnType)) {
return returnType;
}
return null;
} | [
"@",
"Nullable",
"private",
"JSType",
"getExplicitReturnTypeIfExpected",
"(",
"Node",
"scopeRoot",
")",
"{",
"if",
"(",
"!",
"scopeRoot",
".",
"isFunction",
"(",
")",
")",
"{",
"// Nothing to do in a global/module/block scope.",
"return",
"null",
";",
"}",
"FunctionType",
"scopeType",
"=",
"JSType",
".",
"toMaybeFunctionType",
"(",
"scopeRoot",
".",
"getJSType",
"(",
")",
")",
";",
"if",
"(",
"scopeType",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"isEmptyFunction",
"(",
"scopeRoot",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"scopeType",
".",
"isConstructor",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"JSType",
"returnType",
"=",
"scopeType",
".",
"getReturnType",
"(",
")",
";",
"if",
"(",
"returnType",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"scopeRoot",
".",
"isAsyncFunction",
"(",
")",
")",
"{",
"// Unwrap the declared return type (e.g. \"!Promise<number>\" becomes \"number\")",
"returnType",
"=",
"Promises",
".",
"getTemplateTypeOfThenable",
"(",
"compiler",
".",
"getTypeRegistry",
"(",
")",
",",
"returnType",
")",
";",
"}",
"if",
"(",
"!",
"isVoidOrUnknown",
"(",
"returnType",
")",
")",
"{",
"return",
"returnType",
";",
"}",
"return",
"null",
";",
"}"
] | Determines if the given scope should explicitly return. All functions
with non-void or non-unknown return types must have explicit returns.
Exception: Constructors which specifically specify a return type are
used to allow invocation without requiring the "new" keyword. They
have an implicit return type. See unit tests.
@return If a return type is expected, returns it. Otherwise, returns null. | [
"Determines",
"if",
"the",
"given",
"scope",
"should",
"explicitly",
"return",
".",
"All",
"functions",
"with",
"non",
"-",
"void",
"or",
"non",
"-",
"unknown",
"return",
"types",
"must",
"have",
"explicit",
"returns",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckMissingReturn.java#L177-L213 |
23,874 | google/closure-compiler | src/com/google/javascript/jscomp/RewriteAsyncIteration.java | RewriteAsyncIteration.convertAsyncGenerator | private void convertAsyncGenerator(NodeTraversal t, Node originalFunction) {
checkNotNull(originalFunction);
checkState(originalFunction.isAsyncGeneratorFunction());
Node asyncGeneratorWrapperRef =
astFactory.createAsyncGeneratorWrapperReference(originalFunction.getJSType(), t.getScope());
Node innerFunction =
astFactory.createEmptyAsyncGeneratorWrapperArgument(asyncGeneratorWrapperRef.getJSType());
Node innerBlock = originalFunction.getLastChild();
originalFunction.removeChild(innerBlock);
innerFunction.replaceChild(innerFunction.getLastChild(), innerBlock);
// Body should be:
// return new $jscomp.AsyncGeneratorWrapper((new function with original block here)());
Node outerBlock =
astFactory.createBlock(
astFactory.createReturn(
astFactory.createNewNode(
asyncGeneratorWrapperRef, astFactory.createCall(innerFunction))));
originalFunction.addChildToBack(outerBlock);
originalFunction.setIsAsyncFunction(false);
originalFunction.setIsGeneratorFunction(false);
originalFunction.useSourceInfoIfMissingFromForTree(originalFunction);
// Both the inner and original functions should be marked as changed.
compiler.reportChangeToChangeScope(originalFunction);
compiler.reportChangeToChangeScope(innerFunction);
} | java | private void convertAsyncGenerator(NodeTraversal t, Node originalFunction) {
checkNotNull(originalFunction);
checkState(originalFunction.isAsyncGeneratorFunction());
Node asyncGeneratorWrapperRef =
astFactory.createAsyncGeneratorWrapperReference(originalFunction.getJSType(), t.getScope());
Node innerFunction =
astFactory.createEmptyAsyncGeneratorWrapperArgument(asyncGeneratorWrapperRef.getJSType());
Node innerBlock = originalFunction.getLastChild();
originalFunction.removeChild(innerBlock);
innerFunction.replaceChild(innerFunction.getLastChild(), innerBlock);
// Body should be:
// return new $jscomp.AsyncGeneratorWrapper((new function with original block here)());
Node outerBlock =
astFactory.createBlock(
astFactory.createReturn(
astFactory.createNewNode(
asyncGeneratorWrapperRef, astFactory.createCall(innerFunction))));
originalFunction.addChildToBack(outerBlock);
originalFunction.setIsAsyncFunction(false);
originalFunction.setIsGeneratorFunction(false);
originalFunction.useSourceInfoIfMissingFromForTree(originalFunction);
// Both the inner and original functions should be marked as changed.
compiler.reportChangeToChangeScope(originalFunction);
compiler.reportChangeToChangeScope(innerFunction);
} | [
"private",
"void",
"convertAsyncGenerator",
"(",
"NodeTraversal",
"t",
",",
"Node",
"originalFunction",
")",
"{",
"checkNotNull",
"(",
"originalFunction",
")",
";",
"checkState",
"(",
"originalFunction",
".",
"isAsyncGeneratorFunction",
"(",
")",
")",
";",
"Node",
"asyncGeneratorWrapperRef",
"=",
"astFactory",
".",
"createAsyncGeneratorWrapperReference",
"(",
"originalFunction",
".",
"getJSType",
"(",
")",
",",
"t",
".",
"getScope",
"(",
")",
")",
";",
"Node",
"innerFunction",
"=",
"astFactory",
".",
"createEmptyAsyncGeneratorWrapperArgument",
"(",
"asyncGeneratorWrapperRef",
".",
"getJSType",
"(",
")",
")",
";",
"Node",
"innerBlock",
"=",
"originalFunction",
".",
"getLastChild",
"(",
")",
";",
"originalFunction",
".",
"removeChild",
"(",
"innerBlock",
")",
";",
"innerFunction",
".",
"replaceChild",
"(",
"innerFunction",
".",
"getLastChild",
"(",
")",
",",
"innerBlock",
")",
";",
"// Body should be:",
"// return new $jscomp.AsyncGeneratorWrapper((new function with original block here)());",
"Node",
"outerBlock",
"=",
"astFactory",
".",
"createBlock",
"(",
"astFactory",
".",
"createReturn",
"(",
"astFactory",
".",
"createNewNode",
"(",
"asyncGeneratorWrapperRef",
",",
"astFactory",
".",
"createCall",
"(",
"innerFunction",
")",
")",
")",
")",
";",
"originalFunction",
".",
"addChildToBack",
"(",
"outerBlock",
")",
";",
"originalFunction",
".",
"setIsAsyncFunction",
"(",
"false",
")",
";",
"originalFunction",
".",
"setIsGeneratorFunction",
"(",
"false",
")",
";",
"originalFunction",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"originalFunction",
")",
";",
"// Both the inner and original functions should be marked as changed.",
"compiler",
".",
"reportChangeToChangeScope",
"(",
"originalFunction",
")",
";",
"compiler",
".",
"reportChangeToChangeScope",
"(",
"innerFunction",
")",
";",
"}"
] | Moves the body of an async generator function into a nested generator function and removes the
async and generator props from the original function.
<pre>{@code
async function* foo() {
bar();
}
}</pre>
<p>becomes
<pre>{@code
function foo() {
return new $jscomp.AsyncGeneratorWrapper((function*(){
bar();
})())
}
}</pre>
@param originalFunction the original AsyncGeneratorFunction Node to be converted. | [
"Moves",
"the",
"body",
"of",
"an",
"async",
"generator",
"function",
"into",
"a",
"nested",
"generator",
"function",
"and",
"removes",
"the",
"async",
"and",
"generator",
"props",
"from",
"the",
"original",
"function",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RewriteAsyncIteration.java#L370-L398 |
23,875 | google/closure-compiler | src/com/google/javascript/jscomp/RewriteAsyncIteration.java | RewriteAsyncIteration.convertAwaitOfAsyncGenerator | private void convertAwaitOfAsyncGenerator(NodeTraversal t, LexicalContext ctx, Node awaitNode) {
checkNotNull(awaitNode);
checkState(awaitNode.isAwait());
checkState(ctx != null && ctx.function != null);
checkState(ctx.function.isAsyncGeneratorFunction());
Node expression = awaitNode.removeFirstChild();
checkNotNull(expression, "await needs an expression");
Node newActionRecord =
astFactory.createNewNode(
astFactory.createQName(t.getScope(), ACTION_RECORD_NAME),
astFactory.createQName(t.getScope(), ACTION_ENUM_AWAIT),
expression);
newActionRecord.useSourceInfoIfMissingFromForTree(awaitNode);
awaitNode.addChildToFront(newActionRecord);
awaitNode.setToken(Token.YIELD);
} | java | private void convertAwaitOfAsyncGenerator(NodeTraversal t, LexicalContext ctx, Node awaitNode) {
checkNotNull(awaitNode);
checkState(awaitNode.isAwait());
checkState(ctx != null && ctx.function != null);
checkState(ctx.function.isAsyncGeneratorFunction());
Node expression = awaitNode.removeFirstChild();
checkNotNull(expression, "await needs an expression");
Node newActionRecord =
astFactory.createNewNode(
astFactory.createQName(t.getScope(), ACTION_RECORD_NAME),
astFactory.createQName(t.getScope(), ACTION_ENUM_AWAIT),
expression);
newActionRecord.useSourceInfoIfMissingFromForTree(awaitNode);
awaitNode.addChildToFront(newActionRecord);
awaitNode.setToken(Token.YIELD);
} | [
"private",
"void",
"convertAwaitOfAsyncGenerator",
"(",
"NodeTraversal",
"t",
",",
"LexicalContext",
"ctx",
",",
"Node",
"awaitNode",
")",
"{",
"checkNotNull",
"(",
"awaitNode",
")",
";",
"checkState",
"(",
"awaitNode",
".",
"isAwait",
"(",
")",
")",
";",
"checkState",
"(",
"ctx",
"!=",
"null",
"&&",
"ctx",
".",
"function",
"!=",
"null",
")",
";",
"checkState",
"(",
"ctx",
".",
"function",
".",
"isAsyncGeneratorFunction",
"(",
")",
")",
";",
"Node",
"expression",
"=",
"awaitNode",
".",
"removeFirstChild",
"(",
")",
";",
"checkNotNull",
"(",
"expression",
",",
"\"await needs an expression\"",
")",
";",
"Node",
"newActionRecord",
"=",
"astFactory",
".",
"createNewNode",
"(",
"astFactory",
".",
"createQName",
"(",
"t",
".",
"getScope",
"(",
")",
",",
"ACTION_RECORD_NAME",
")",
",",
"astFactory",
".",
"createQName",
"(",
"t",
".",
"getScope",
"(",
")",
",",
"ACTION_ENUM_AWAIT",
")",
",",
"expression",
")",
";",
"newActionRecord",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"awaitNode",
")",
";",
"awaitNode",
".",
"addChildToFront",
"(",
"newActionRecord",
")",
";",
"awaitNode",
".",
"setToken",
"(",
"Token",
".",
"YIELD",
")",
";",
"}"
] | Converts an await into a yield of an ActionRecord to perform "AWAIT".
<pre>{@code await myPromise}</pre>
<p>becomes
<pre>{@code yield new ActionRecord(ActionEnum.AWAIT_VALUE, myPromise)}</pre>
@param awaitNode the original await Node to be converted | [
"Converts",
"an",
"await",
"into",
"a",
"yield",
"of",
"an",
"ActionRecord",
"to",
"perform",
"AWAIT",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RewriteAsyncIteration.java#L411-L427 |
23,876 | google/closure-compiler | src/com/google/javascript/jscomp/RewriteAsyncIteration.java | RewriteAsyncIteration.convertYieldOfAsyncGenerator | private void convertYieldOfAsyncGenerator(NodeTraversal t, LexicalContext ctx, Node yieldNode) {
checkNotNull(yieldNode);
checkState(yieldNode.isYield());
checkState(ctx != null && ctx.function != null);
checkState(ctx.function.isAsyncGeneratorFunction());
Node expression = yieldNode.removeFirstChild();
Node newActionRecord =
astFactory.createNewNode(astFactory.createQName(t.getScope(), ACTION_RECORD_NAME));
if (yieldNode.isYieldAll()) {
checkNotNull(expression);
// yield* expression becomes new ActionRecord(YIELD_STAR, expression)
newActionRecord.addChildToBack(astFactory.createQName(t.getScope(), ACTION_ENUM_YIELD_STAR));
newActionRecord.addChildToBack(expression);
} else {
if (expression == null) {
expression = NodeUtil.newUndefinedNode(null);
}
// yield expression becomes new ActionRecord(YIELD, expression)
newActionRecord.addChildToBack(astFactory.createQName(t.getScope(), ACTION_ENUM_YIELD));
newActionRecord.addChildToBack(expression);
}
newActionRecord.useSourceInfoIfMissingFromForTree(yieldNode);
yieldNode.addChildToFront(newActionRecord);
yieldNode.removeProp(Node.YIELD_ALL);
} | java | private void convertYieldOfAsyncGenerator(NodeTraversal t, LexicalContext ctx, Node yieldNode) {
checkNotNull(yieldNode);
checkState(yieldNode.isYield());
checkState(ctx != null && ctx.function != null);
checkState(ctx.function.isAsyncGeneratorFunction());
Node expression = yieldNode.removeFirstChild();
Node newActionRecord =
astFactory.createNewNode(astFactory.createQName(t.getScope(), ACTION_RECORD_NAME));
if (yieldNode.isYieldAll()) {
checkNotNull(expression);
// yield* expression becomes new ActionRecord(YIELD_STAR, expression)
newActionRecord.addChildToBack(astFactory.createQName(t.getScope(), ACTION_ENUM_YIELD_STAR));
newActionRecord.addChildToBack(expression);
} else {
if (expression == null) {
expression = NodeUtil.newUndefinedNode(null);
}
// yield expression becomes new ActionRecord(YIELD, expression)
newActionRecord.addChildToBack(astFactory.createQName(t.getScope(), ACTION_ENUM_YIELD));
newActionRecord.addChildToBack(expression);
}
newActionRecord.useSourceInfoIfMissingFromForTree(yieldNode);
yieldNode.addChildToFront(newActionRecord);
yieldNode.removeProp(Node.YIELD_ALL);
} | [
"private",
"void",
"convertYieldOfAsyncGenerator",
"(",
"NodeTraversal",
"t",
",",
"LexicalContext",
"ctx",
",",
"Node",
"yieldNode",
")",
"{",
"checkNotNull",
"(",
"yieldNode",
")",
";",
"checkState",
"(",
"yieldNode",
".",
"isYield",
"(",
")",
")",
";",
"checkState",
"(",
"ctx",
"!=",
"null",
"&&",
"ctx",
".",
"function",
"!=",
"null",
")",
";",
"checkState",
"(",
"ctx",
".",
"function",
".",
"isAsyncGeneratorFunction",
"(",
")",
")",
";",
"Node",
"expression",
"=",
"yieldNode",
".",
"removeFirstChild",
"(",
")",
";",
"Node",
"newActionRecord",
"=",
"astFactory",
".",
"createNewNode",
"(",
"astFactory",
".",
"createQName",
"(",
"t",
".",
"getScope",
"(",
")",
",",
"ACTION_RECORD_NAME",
")",
")",
";",
"if",
"(",
"yieldNode",
".",
"isYieldAll",
"(",
")",
")",
"{",
"checkNotNull",
"(",
"expression",
")",
";",
"// yield* expression becomes new ActionRecord(YIELD_STAR, expression)",
"newActionRecord",
".",
"addChildToBack",
"(",
"astFactory",
".",
"createQName",
"(",
"t",
".",
"getScope",
"(",
")",
",",
"ACTION_ENUM_YIELD_STAR",
")",
")",
";",
"newActionRecord",
".",
"addChildToBack",
"(",
"expression",
")",
";",
"}",
"else",
"{",
"if",
"(",
"expression",
"==",
"null",
")",
"{",
"expression",
"=",
"NodeUtil",
".",
"newUndefinedNode",
"(",
"null",
")",
";",
"}",
"// yield expression becomes new ActionRecord(YIELD, expression)",
"newActionRecord",
".",
"addChildToBack",
"(",
"astFactory",
".",
"createQName",
"(",
"t",
".",
"getScope",
"(",
")",
",",
"ACTION_ENUM_YIELD",
")",
")",
";",
"newActionRecord",
".",
"addChildToBack",
"(",
"expression",
")",
";",
"}",
"newActionRecord",
".",
"useSourceInfoIfMissingFromForTree",
"(",
"yieldNode",
")",
";",
"yieldNode",
".",
"addChildToFront",
"(",
"newActionRecord",
")",
";",
"yieldNode",
".",
"removeProp",
"(",
"Node",
".",
"YIELD_ALL",
")",
";",
"}"
] | Converts a yield into a yield of an ActionRecord to perform "YIELD" or "YIELD_STAR".
<pre>{@code
yield;
yield first;
yield* second;
}</pre>
<p>becomes
<pre>{@code
yield new ActionRecord(ActionEnum.YIELD_VALUE, undefined);
yield new ActionRecord(ActionEnum.YIELD_VALUE, first);
yield new ActionRecord(ActionEnum.YIELD_STAR, second);
}</pre>
@param yieldNode the Node to be converted | [
"Converts",
"a",
"yield",
"into",
"a",
"yield",
"of",
"an",
"ActionRecord",
"to",
"perform",
"YIELD",
"or",
"YIELD_STAR",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RewriteAsyncIteration.java#L448-L475 |
23,877 | google/closure-compiler | src/com/google/javascript/jscomp/AmbiguateProperties.java | AmbiguateProperties.getIntForType | private int getIntForType(JSType type) {
// Templatized types don't exist at runtime, so collapse to raw type
if (type != null && type.isGenericObjectType()) {
type = type.toMaybeObjectType().getRawType();
}
if (intForType.containsKey(type)) {
return intForType.get(type).intValue();
}
int newInt = intForType.size() + 1;
intForType.put(type, newInt);
return newInt;
} | java | private int getIntForType(JSType type) {
// Templatized types don't exist at runtime, so collapse to raw type
if (type != null && type.isGenericObjectType()) {
type = type.toMaybeObjectType().getRawType();
}
if (intForType.containsKey(type)) {
return intForType.get(type).intValue();
}
int newInt = intForType.size() + 1;
intForType.put(type, newInt);
return newInt;
} | [
"private",
"int",
"getIntForType",
"(",
"JSType",
"type",
")",
"{",
"// Templatized types don't exist at runtime, so collapse to raw type",
"if",
"(",
"type",
"!=",
"null",
"&&",
"type",
".",
"isGenericObjectType",
"(",
")",
")",
"{",
"type",
"=",
"type",
".",
"toMaybeObjectType",
"(",
")",
".",
"getRawType",
"(",
")",
";",
"}",
"if",
"(",
"intForType",
".",
"containsKey",
"(",
"type",
")",
")",
"{",
"return",
"intForType",
".",
"get",
"(",
"type",
")",
".",
"intValue",
"(",
")",
";",
"}",
"int",
"newInt",
"=",
"intForType",
".",
"size",
"(",
")",
"+",
"1",
";",
"intForType",
".",
"put",
"(",
"type",
",",
"newInt",
")",
";",
"return",
"newInt",
";",
"}"
] | Returns an integer that uniquely identifies a JSType. | [
"Returns",
"an",
"integer",
"that",
"uniquely",
"identifies",
"a",
"JSType",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AmbiguateProperties.java#L165-L176 |
23,878 | google/closure-compiler | src/com/google/javascript/jscomp/AmbiguateProperties.java | AmbiguateProperties.computeRelatedTypesForNonUnionType | @SuppressWarnings("ReferenceEquality")
private void computeRelatedTypesForNonUnionType(JSType type) {
// This method could be expanded to handle union types if necessary, but currently no union
// types are ever passed as input so the method doesn't have logic for union types
checkState(!type.isUnionType(), type);
if (relatedBitsets.containsKey(type)) {
// We only need to generate the bit set once.
return;
}
JSTypeBitSet related = new JSTypeBitSet(intForType.size());
relatedBitsets.put(type, related);
related.set(getIntForType(type));
// A prototype is related to its instance.
if (type.isFunctionPrototypeType()) {
FunctionType maybeCtor = type.toMaybeObjectType().getOwnerFunction();
if (maybeCtor.isConstructor() || maybeCtor.isInterface()) {
addRelatedInstance(maybeCtor, related);
}
return;
}
// A class/interface is related to its subclasses/implementors.
FunctionType constructor = type.toMaybeObjectType().getConstructor();
if (constructor != null) {
for (FunctionType subType : constructor.getDirectSubTypes()) {
addRelatedInstance(subType, related);
}
}
// We only specifically handle implicit prototypes of functions in the case of ES6 classes
// For regular functions, the implicit prototype being Function.prototype does not matter
// because the type `Function` is invalidating.
// This may cause unexpected behavior for code that manually sets a prototype, e.g.
// Object.setPrototypeOf(myFunction, prototypeObj);
// but code like that should not be used with --ambiguate_properties or type-based optimizations
FunctionType fnType = type.toMaybeFunctionType();
if (fnType != null) {
for (FunctionType subType : fnType.getDirectSubTypes()) {
// We record all subtypes of constructors, but don't care about old 'ES5-style' subtyping,
// just ES6-style. This is equivalent to saying that the subtype constructor's implicit
// prototype is the given type
if (fnType == subType.getImplicitPrototype()) {
addRelatedType(subType, related);
}
}
}
} | java | @SuppressWarnings("ReferenceEquality")
private void computeRelatedTypesForNonUnionType(JSType type) {
// This method could be expanded to handle union types if necessary, but currently no union
// types are ever passed as input so the method doesn't have logic for union types
checkState(!type.isUnionType(), type);
if (relatedBitsets.containsKey(type)) {
// We only need to generate the bit set once.
return;
}
JSTypeBitSet related = new JSTypeBitSet(intForType.size());
relatedBitsets.put(type, related);
related.set(getIntForType(type));
// A prototype is related to its instance.
if (type.isFunctionPrototypeType()) {
FunctionType maybeCtor = type.toMaybeObjectType().getOwnerFunction();
if (maybeCtor.isConstructor() || maybeCtor.isInterface()) {
addRelatedInstance(maybeCtor, related);
}
return;
}
// A class/interface is related to its subclasses/implementors.
FunctionType constructor = type.toMaybeObjectType().getConstructor();
if (constructor != null) {
for (FunctionType subType : constructor.getDirectSubTypes()) {
addRelatedInstance(subType, related);
}
}
// We only specifically handle implicit prototypes of functions in the case of ES6 classes
// For regular functions, the implicit prototype being Function.prototype does not matter
// because the type `Function` is invalidating.
// This may cause unexpected behavior for code that manually sets a prototype, e.g.
// Object.setPrototypeOf(myFunction, prototypeObj);
// but code like that should not be used with --ambiguate_properties or type-based optimizations
FunctionType fnType = type.toMaybeFunctionType();
if (fnType != null) {
for (FunctionType subType : fnType.getDirectSubTypes()) {
// We record all subtypes of constructors, but don't care about old 'ES5-style' subtyping,
// just ES6-style. This is equivalent to saying that the subtype constructor's implicit
// prototype is the given type
if (fnType == subType.getImplicitPrototype()) {
addRelatedType(subType, related);
}
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"ReferenceEquality\"",
")",
"private",
"void",
"computeRelatedTypesForNonUnionType",
"(",
"JSType",
"type",
")",
"{",
"// This method could be expanded to handle union types if necessary, but currently no union",
"// types are ever passed as input so the method doesn't have logic for union types",
"checkState",
"(",
"!",
"type",
".",
"isUnionType",
"(",
")",
",",
"type",
")",
";",
"if",
"(",
"relatedBitsets",
".",
"containsKey",
"(",
"type",
")",
")",
"{",
"// We only need to generate the bit set once.",
"return",
";",
"}",
"JSTypeBitSet",
"related",
"=",
"new",
"JSTypeBitSet",
"(",
"intForType",
".",
"size",
"(",
")",
")",
";",
"relatedBitsets",
".",
"put",
"(",
"type",
",",
"related",
")",
";",
"related",
".",
"set",
"(",
"getIntForType",
"(",
"type",
")",
")",
";",
"// A prototype is related to its instance.",
"if",
"(",
"type",
".",
"isFunctionPrototypeType",
"(",
")",
")",
"{",
"FunctionType",
"maybeCtor",
"=",
"type",
".",
"toMaybeObjectType",
"(",
")",
".",
"getOwnerFunction",
"(",
")",
";",
"if",
"(",
"maybeCtor",
".",
"isConstructor",
"(",
")",
"||",
"maybeCtor",
".",
"isInterface",
"(",
")",
")",
"{",
"addRelatedInstance",
"(",
"maybeCtor",
",",
"related",
")",
";",
"}",
"return",
";",
"}",
"// A class/interface is related to its subclasses/implementors.",
"FunctionType",
"constructor",
"=",
"type",
".",
"toMaybeObjectType",
"(",
")",
".",
"getConstructor",
"(",
")",
";",
"if",
"(",
"constructor",
"!=",
"null",
")",
"{",
"for",
"(",
"FunctionType",
"subType",
":",
"constructor",
".",
"getDirectSubTypes",
"(",
")",
")",
"{",
"addRelatedInstance",
"(",
"subType",
",",
"related",
")",
";",
"}",
"}",
"// We only specifically handle implicit prototypes of functions in the case of ES6 classes",
"// For regular functions, the implicit prototype being Function.prototype does not matter",
"// because the type `Function` is invalidating.",
"// This may cause unexpected behavior for code that manually sets a prototype, e.g.",
"// Object.setPrototypeOf(myFunction, prototypeObj);",
"// but code like that should not be used with --ambiguate_properties or type-based optimizations",
"FunctionType",
"fnType",
"=",
"type",
".",
"toMaybeFunctionType",
"(",
")",
";",
"if",
"(",
"fnType",
"!=",
"null",
")",
"{",
"for",
"(",
"FunctionType",
"subType",
":",
"fnType",
".",
"getDirectSubTypes",
"(",
")",
")",
"{",
"// We record all subtypes of constructors, but don't care about old 'ES5-style' subtyping,",
"// just ES6-style. This is equivalent to saying that the subtype constructor's implicit",
"// prototype is the given type",
"if",
"(",
"fnType",
"==",
"subType",
".",
"getImplicitPrototype",
"(",
")",
")",
"{",
"addRelatedType",
"(",
"subType",
",",
"related",
")",
";",
"}",
"}",
"}",
"}"
] | Adds subtypes - and implementors, in the case of interfaces - of the type to its JSTypeBitSet
of related types.
<p>The 'is related to' relationship is best understood graphically. Draw an arrow from each
instance type to the prototype of each of its subclass. Draw an arrow from each prototype to
its instance type. Draw an arrow from each interface to its implementors. A type is related to
another if there is a directed path in the graph from the type to other. Thus, the 'is related
to' relationship is reflexive and transitive.
<p>Example with Foo extends Bar which extends Baz and Bar implements I:
<pre>{@code
Foo -> Bar.prototype -> Bar -> Baz.prototype -> Baz
^
|
I
}</pre>
<p>We also need to handle relationships between functions because of ES6 class-side inheritance
although the top Function type itself is invalidating. | [
"Adds",
"subtypes",
"-",
"and",
"implementors",
"in",
"the",
"case",
"of",
"interfaces",
"-",
"of",
"the",
"type",
"to",
"its",
"JSTypeBitSet",
"of",
"related",
"types",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AmbiguateProperties.java#L279-L328 |
23,879 | google/closure-compiler | src/com/google/javascript/jscomp/AmbiguateProperties.java | AmbiguateProperties.addRelatedInstance | private void addRelatedInstance(FunctionType constructor, JSTypeBitSet related) {
checkArgument(constructor.hasInstanceType(),
"Constructor %s without instance type.", constructor);
ObjectType instanceType = constructor.getInstanceType();
addRelatedType(instanceType, related);
} | java | private void addRelatedInstance(FunctionType constructor, JSTypeBitSet related) {
checkArgument(constructor.hasInstanceType(),
"Constructor %s without instance type.", constructor);
ObjectType instanceType = constructor.getInstanceType();
addRelatedType(instanceType, related);
} | [
"private",
"void",
"addRelatedInstance",
"(",
"FunctionType",
"constructor",
",",
"JSTypeBitSet",
"related",
")",
"{",
"checkArgument",
"(",
"constructor",
".",
"hasInstanceType",
"(",
")",
",",
"\"Constructor %s without instance type.\"",
",",
"constructor",
")",
";",
"ObjectType",
"instanceType",
"=",
"constructor",
".",
"getInstanceType",
"(",
")",
";",
"addRelatedType",
"(",
"instanceType",
",",
"related",
")",
";",
"}"
] | Adds the instance of the given constructor, its implicit prototype and all
its related types to the given bit set. | [
"Adds",
"the",
"instance",
"of",
"the",
"given",
"constructor",
"its",
"implicit",
"prototype",
"and",
"all",
"its",
"related",
"types",
"to",
"the",
"given",
"bit",
"set",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AmbiguateProperties.java#L334-L339 |
23,880 | google/closure-compiler | src/com/google/javascript/jscomp/AmbiguateProperties.java | AmbiguateProperties.addRelatedType | private void addRelatedType(JSType type, JSTypeBitSet related) {
computeRelatedTypesForNonUnionType(type);
related.or(relatedBitsets.get(type));
} | java | private void addRelatedType(JSType type, JSTypeBitSet related) {
computeRelatedTypesForNonUnionType(type);
related.or(relatedBitsets.get(type));
} | [
"private",
"void",
"addRelatedType",
"(",
"JSType",
"type",
",",
"JSTypeBitSet",
"related",
")",
"{",
"computeRelatedTypesForNonUnionType",
"(",
"type",
")",
";",
"related",
".",
"or",
"(",
"relatedBitsets",
".",
"get",
"(",
"type",
")",
")",
";",
"}"
] | Adds the given type and all its related types to the given bit set. | [
"Adds",
"the",
"given",
"type",
"and",
"all",
"its",
"related",
"types",
"to",
"the",
"given",
"bit",
"set",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AmbiguateProperties.java#L342-L345 |
23,881 | google/closure-compiler | src/com/google/javascript/jscomp/CheckGlobalNames.java | CheckGlobalNames.checkDescendantNames | private void checkDescendantNames(Name name, boolean nameIsDefined) {
if (name.props != null) {
for (Name prop : name.props) {
// if the ancestor of a property is not defined, then we should emit
// warnings for all references to the property.
boolean propIsDefined = false;
if (nameIsDefined) {
// if the ancestor of a property is defined, then let's check that
// the property is also explicitly defined if it needs to be.
propIsDefined =
(!propertyMustBeInitializedByFullName(prop)
|| prop.getGlobalSets() + prop.getLocalSets() > 0);
}
validateName(prop, propIsDefined);
checkDescendantNames(prop, propIsDefined);
}
}
} | java | private void checkDescendantNames(Name name, boolean nameIsDefined) {
if (name.props != null) {
for (Name prop : name.props) {
// if the ancestor of a property is not defined, then we should emit
// warnings for all references to the property.
boolean propIsDefined = false;
if (nameIsDefined) {
// if the ancestor of a property is defined, then let's check that
// the property is also explicitly defined if it needs to be.
propIsDefined =
(!propertyMustBeInitializedByFullName(prop)
|| prop.getGlobalSets() + prop.getLocalSets() > 0);
}
validateName(prop, propIsDefined);
checkDescendantNames(prop, propIsDefined);
}
}
} | [
"private",
"void",
"checkDescendantNames",
"(",
"Name",
"name",
",",
"boolean",
"nameIsDefined",
")",
"{",
"if",
"(",
"name",
".",
"props",
"!=",
"null",
")",
"{",
"for",
"(",
"Name",
"prop",
":",
"name",
".",
"props",
")",
"{",
"// if the ancestor of a property is not defined, then we should emit",
"// warnings for all references to the property.",
"boolean",
"propIsDefined",
"=",
"false",
";",
"if",
"(",
"nameIsDefined",
")",
"{",
"// if the ancestor of a property is defined, then let's check that",
"// the property is also explicitly defined if it needs to be.",
"propIsDefined",
"=",
"(",
"!",
"propertyMustBeInitializedByFullName",
"(",
"prop",
")",
"||",
"prop",
".",
"getGlobalSets",
"(",
")",
"+",
"prop",
".",
"getLocalSets",
"(",
")",
">",
"0",
")",
";",
"}",
"validateName",
"(",
"prop",
",",
"propIsDefined",
")",
";",
"checkDescendantNames",
"(",
"prop",
",",
"propIsDefined",
")",
";",
"}",
"}",
"}"
] | Checks to make sure all the descendants of a name are defined if they
are referenced.
@param name A global name.
@param nameIsDefined If true, {@code name} is defined. Otherwise, it's
undefined, and any references to descendant names should emit warnings. | [
"Checks",
"to",
"make",
"sure",
"all",
"the",
"descendants",
"of",
"a",
"name",
"are",
"defined",
"if",
"they",
"are",
"referenced",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckGlobalNames.java#L132-L150 |
23,882 | google/closure-compiler | src/com/google/javascript/jscomp/CheckGlobalNames.java | CheckGlobalNames.checkForBadModuleReference | private boolean checkForBadModuleReference(Name name, Ref ref) {
JSModuleGraph moduleGraph = compiler.getModuleGraph();
if (name.getGlobalSets() == 0 || ref.type == Ref.Type.SET_FROM_GLOBAL) {
// Back off if either 1) this name was never set, or 2) this reference /is/ a set.
return false;
}
if (name.getGlobalSets() == 1) {
// there is only one global set - it should be set as name.declaration
// just look at that declaration instead of iterating through every single reference.
Ref declaration = checkNotNull(name.getDeclaration());
return !isSetFromPrecedingModule(ref, declaration, moduleGraph);
}
// there are multiple sets, so check if any of them happens in this module or a module earlier
// in the dependency chain.
for (Ref set : name.getRefs()) {
if (isSetFromPrecedingModule(ref, set, moduleGraph)) {
return false;
}
}
return true;
} | java | private boolean checkForBadModuleReference(Name name, Ref ref) {
JSModuleGraph moduleGraph = compiler.getModuleGraph();
if (name.getGlobalSets() == 0 || ref.type == Ref.Type.SET_FROM_GLOBAL) {
// Back off if either 1) this name was never set, or 2) this reference /is/ a set.
return false;
}
if (name.getGlobalSets() == 1) {
// there is only one global set - it should be set as name.declaration
// just look at that declaration instead of iterating through every single reference.
Ref declaration = checkNotNull(name.getDeclaration());
return !isSetFromPrecedingModule(ref, declaration, moduleGraph);
}
// there are multiple sets, so check if any of them happens in this module or a module earlier
// in the dependency chain.
for (Ref set : name.getRefs()) {
if (isSetFromPrecedingModule(ref, set, moduleGraph)) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"checkForBadModuleReference",
"(",
"Name",
"name",
",",
"Ref",
"ref",
")",
"{",
"JSModuleGraph",
"moduleGraph",
"=",
"compiler",
".",
"getModuleGraph",
"(",
")",
";",
"if",
"(",
"name",
".",
"getGlobalSets",
"(",
")",
"==",
"0",
"||",
"ref",
".",
"type",
"==",
"Ref",
".",
"Type",
".",
"SET_FROM_GLOBAL",
")",
"{",
"// Back off if either 1) this name was never set, or 2) this reference /is/ a set.",
"return",
"false",
";",
"}",
"if",
"(",
"name",
".",
"getGlobalSets",
"(",
")",
"==",
"1",
")",
"{",
"// there is only one global set - it should be set as name.declaration",
"// just look at that declaration instead of iterating through every single reference.",
"Ref",
"declaration",
"=",
"checkNotNull",
"(",
"name",
".",
"getDeclaration",
"(",
")",
")",
";",
"return",
"!",
"isSetFromPrecedingModule",
"(",
"ref",
",",
"declaration",
",",
"moduleGraph",
")",
";",
"}",
"// there are multiple sets, so check if any of them happens in this module or a module earlier",
"// in the dependency chain.",
"for",
"(",
"Ref",
"set",
":",
"name",
".",
"getRefs",
"(",
")",
")",
"{",
"if",
"(",
"isSetFromPrecedingModule",
"(",
"ref",
",",
"set",
",",
"moduleGraph",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Returns true if this name is potentially referenced before being defined in a different module
<p>For example:
<ul>
<li>Module B depends on Module A. name is set in Module A and referenced in Module B. this is
fine, and this method returns false.
<li>Module A and Module B are unrelated. name is set in Module A and referenced in Module B.
this is an error, and this method returns true.
<li>name is referenced in Module A, and never set globally. This warning is not specific to
modules, so is emitted elsewhere.
</ul> | [
"Returns",
"true",
"if",
"this",
"name",
"is",
"potentially",
"referenced",
"before",
"being",
"defined",
"in",
"a",
"different",
"module"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckGlobalNames.java#L229-L249 |
23,883 | google/closure-compiler | src/com/google/javascript/jscomp/CheckGlobalNames.java | CheckGlobalNames.isSetFromPrecedingModule | private static boolean isSetFromPrecedingModule(
Ref originalRef, Ref set, JSModuleGraph moduleGraph) {
return set.type == Ref.Type.SET_FROM_GLOBAL
&& (originalRef.getModule() == set.getModule()
|| moduleGraph.dependsOn(originalRef.getModule(), set.getModule()));
} | java | private static boolean isSetFromPrecedingModule(
Ref originalRef, Ref set, JSModuleGraph moduleGraph) {
return set.type == Ref.Type.SET_FROM_GLOBAL
&& (originalRef.getModule() == set.getModule()
|| moduleGraph.dependsOn(originalRef.getModule(), set.getModule()));
} | [
"private",
"static",
"boolean",
"isSetFromPrecedingModule",
"(",
"Ref",
"originalRef",
",",
"Ref",
"set",
",",
"JSModuleGraph",
"moduleGraph",
")",
"{",
"return",
"set",
".",
"type",
"==",
"Ref",
".",
"Type",
".",
"SET_FROM_GLOBAL",
"&&",
"(",
"originalRef",
".",
"getModule",
"(",
")",
"==",
"set",
".",
"getModule",
"(",
")",
"||",
"moduleGraph",
".",
"dependsOn",
"(",
"originalRef",
".",
"getModule",
"(",
")",
",",
"set",
".",
"getModule",
"(",
")",
")",
")",
";",
"}"
] | Whether the set is in the global scope and occurs in a module the original ref depends on | [
"Whether",
"the",
"set",
"is",
"in",
"the",
"global",
"scope",
"and",
"occurs",
"in",
"a",
"module",
"the",
"original",
"ref",
"depends",
"on"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckGlobalNames.java#L252-L257 |
23,884 | google/closure-compiler | src/com/google/javascript/jscomp/CheckGlobalNames.java | CheckGlobalNames.propertyMustBeInitializedByFullName | private boolean propertyMustBeInitializedByFullName(Name name) {
// If an object or function literal in the global namespace is never
// aliased, then its properties can only come from one of 2 places:
// 1) From its prototype chain, or
// 2) From an assignment to its fully qualified name.
// If we assume #1 is not the case, then #2 implies that its
// properties must all be modeled in the GlobalNamespace as well.
//
// We assume that for global object literals and types (constructors and
// interfaces), we can find all the properties inherited from the prototype
// chain of functions and objects.
if (name.getParent() == null) {
return false;
}
if (isNameUnsafelyAliased(name.getParent())) {
// e.g. if we have `const ns = {}; escape(ns); alert(ns.a.b);`
// we don't expect ns.a.b to be defined somewhere because `ns` has escaped
return false;
}
if (objectPrototypeProps.contains(name.getBaseName())) {
// checks for things on Object.prototype, e.g. a call to
// something.hasOwnProperty('a');
return false;
}
if (name.getParent().isObjectLiteral()) {
// if this is a property on an object literal, always expect an initialization somewhere
return true;
}
if (name.getParent().isClass()) {
// only warn on class properties if there is no superclass, because we don't handle
// class side inheritance here very well yet.
return !hasSuperclass(name.getParent());
}
// warn on remaining names if they are on a constructor and are not a Function.prototype
// property (e.g. f.call(1);)
return name.getParent().isFunction()
&& name.getParent().isDeclaredType()
&& !functionPrototypeProps.contains(name.getBaseName());
} | java | private boolean propertyMustBeInitializedByFullName(Name name) {
// If an object or function literal in the global namespace is never
// aliased, then its properties can only come from one of 2 places:
// 1) From its prototype chain, or
// 2) From an assignment to its fully qualified name.
// If we assume #1 is not the case, then #2 implies that its
// properties must all be modeled in the GlobalNamespace as well.
//
// We assume that for global object literals and types (constructors and
// interfaces), we can find all the properties inherited from the prototype
// chain of functions and objects.
if (name.getParent() == null) {
return false;
}
if (isNameUnsafelyAliased(name.getParent())) {
// e.g. if we have `const ns = {}; escape(ns); alert(ns.a.b);`
// we don't expect ns.a.b to be defined somewhere because `ns` has escaped
return false;
}
if (objectPrototypeProps.contains(name.getBaseName())) {
// checks for things on Object.prototype, e.g. a call to
// something.hasOwnProperty('a');
return false;
}
if (name.getParent().isObjectLiteral()) {
// if this is a property on an object literal, always expect an initialization somewhere
return true;
}
if (name.getParent().isClass()) {
// only warn on class properties if there is no superclass, because we don't handle
// class side inheritance here very well yet.
return !hasSuperclass(name.getParent());
}
// warn on remaining names if they are on a constructor and are not a Function.prototype
// property (e.g. f.call(1);)
return name.getParent().isFunction()
&& name.getParent().isDeclaredType()
&& !functionPrototypeProps.contains(name.getBaseName());
} | [
"private",
"boolean",
"propertyMustBeInitializedByFullName",
"(",
"Name",
"name",
")",
"{",
"// If an object or function literal in the global namespace is never",
"// aliased, then its properties can only come from one of 2 places:",
"// 1) From its prototype chain, or",
"// 2) From an assignment to its fully qualified name.",
"// If we assume #1 is not the case, then #2 implies that its",
"// properties must all be modeled in the GlobalNamespace as well.",
"//",
"// We assume that for global object literals and types (constructors and",
"// interfaces), we can find all the properties inherited from the prototype",
"// chain of functions and objects.",
"if",
"(",
"name",
".",
"getParent",
"(",
")",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"isNameUnsafelyAliased",
"(",
"name",
".",
"getParent",
"(",
")",
")",
")",
"{",
"// e.g. if we have `const ns = {}; escape(ns); alert(ns.a.b);`",
"// we don't expect ns.a.b to be defined somewhere because `ns` has escaped",
"return",
"false",
";",
"}",
"if",
"(",
"objectPrototypeProps",
".",
"contains",
"(",
"name",
".",
"getBaseName",
"(",
")",
")",
")",
"{",
"// checks for things on Object.prototype, e.g. a call to",
"// something.hasOwnProperty('a');",
"return",
"false",
";",
"}",
"if",
"(",
"name",
".",
"getParent",
"(",
")",
".",
"isObjectLiteral",
"(",
")",
")",
"{",
"// if this is a property on an object literal, always expect an initialization somewhere",
"return",
"true",
";",
"}",
"if",
"(",
"name",
".",
"getParent",
"(",
")",
".",
"isClass",
"(",
")",
")",
"{",
"// only warn on class properties if there is no superclass, because we don't handle",
"// class side inheritance here very well yet.",
"return",
"!",
"hasSuperclass",
"(",
"name",
".",
"getParent",
"(",
")",
")",
";",
"}",
"// warn on remaining names if they are on a constructor and are not a Function.prototype",
"// property (e.g. f.call(1);)",
"return",
"name",
".",
"getParent",
"(",
")",
".",
"isFunction",
"(",
")",
"&&",
"name",
".",
"getParent",
"(",
")",
".",
"isDeclaredType",
"(",
")",
"&&",
"!",
"functionPrototypeProps",
".",
"contains",
"(",
"name",
".",
"getBaseName",
"(",
")",
")",
";",
"}"
] | The input name is a property. Check whether this property
must be initialized with its full qualified name. | [
"The",
"input",
"name",
"is",
"a",
"property",
".",
"Check",
"whether",
"this",
"property",
"must",
"be",
"initialized",
"with",
"its",
"full",
"qualified",
"name",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckGlobalNames.java#L283-L326 |
23,885 | google/closure-compiler | src/com/google/javascript/jscomp/CheckGlobalNames.java | CheckGlobalNames.hasSuperclass | private boolean hasSuperclass(Name es6Class) {
Node decl = es6Class.getDeclaration().getNode();
Node classNode = NodeUtil.getRValueOfLValue(decl);
checkState(classNode.isClass(), classNode);
Node superclass = classNode.getSecondChild();
return !superclass.isEmpty();
} | java | private boolean hasSuperclass(Name es6Class) {
Node decl = es6Class.getDeclaration().getNode();
Node classNode = NodeUtil.getRValueOfLValue(decl);
checkState(classNode.isClass(), classNode);
Node superclass = classNode.getSecondChild();
return !superclass.isEmpty();
} | [
"private",
"boolean",
"hasSuperclass",
"(",
"Name",
"es6Class",
")",
"{",
"Node",
"decl",
"=",
"es6Class",
".",
"getDeclaration",
"(",
")",
".",
"getNode",
"(",
")",
";",
"Node",
"classNode",
"=",
"NodeUtil",
".",
"getRValueOfLValue",
"(",
"decl",
")",
";",
"checkState",
"(",
"classNode",
".",
"isClass",
"(",
")",
",",
"classNode",
")",
";",
"Node",
"superclass",
"=",
"classNode",
".",
"getSecondChild",
"(",
")",
";",
"return",
"!",
"superclass",
".",
"isEmpty",
"(",
")",
";",
"}"
] | Returns whether the given ES6 class extends something. | [
"Returns",
"whether",
"the",
"given",
"ES6",
"class",
"extends",
"something",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckGlobalNames.java#L329-L336 |
23,886 | google/closure-compiler | src/com/google/javascript/jscomp/ModuleImportResolver.java | ModuleImportResolver.getClosureNamespaceTypeFromCall | ScopedName getClosureNamespaceTypeFromCall(Node googRequire) {
if (moduleMap == null) {
// TODO(b/124919359): make sure all tests have generated a ModuleMap
return null;
}
String moduleId = googRequire.getSecondChild().getString();
Module module = moduleMap.getClosureModule(moduleId);
if (module == null) {
return null;
}
switch (module.metadata().moduleType()) {
case GOOG_PROVIDE:
// Expect this to be a global variable
Node provide = module.metadata().rootNode();
if (provide != null && provide.isScript()) {
return ScopedName.of(moduleId, provide.getGrandparent());
} else {
// Unknown module requires default to 'goog provides', but we don't want to type them.
return null;
}
case GOOG_MODULE:
case LEGACY_GOOG_MODULE:
// TODO(b/124919359): Fix getGoogModuleScopeRoot to never return null.
Node scopeRoot = getGoogModuleScopeRoot(module);
return scopeRoot != null ? ScopedName.of("exports", scopeRoot) : null;
case ES6_MODULE:
throw new IllegalStateException("Type checking ES modules not yet supported");
case COMMON_JS:
throw new IllegalStateException("Type checking CommonJs modules not yet supported");
case SCRIPT:
throw new IllegalStateException("Cannot import a name from a SCRIPT");
}
throw new AssertionError();
} | java | ScopedName getClosureNamespaceTypeFromCall(Node googRequire) {
if (moduleMap == null) {
// TODO(b/124919359): make sure all tests have generated a ModuleMap
return null;
}
String moduleId = googRequire.getSecondChild().getString();
Module module = moduleMap.getClosureModule(moduleId);
if (module == null) {
return null;
}
switch (module.metadata().moduleType()) {
case GOOG_PROVIDE:
// Expect this to be a global variable
Node provide = module.metadata().rootNode();
if (provide != null && provide.isScript()) {
return ScopedName.of(moduleId, provide.getGrandparent());
} else {
// Unknown module requires default to 'goog provides', but we don't want to type them.
return null;
}
case GOOG_MODULE:
case LEGACY_GOOG_MODULE:
// TODO(b/124919359): Fix getGoogModuleScopeRoot to never return null.
Node scopeRoot = getGoogModuleScopeRoot(module);
return scopeRoot != null ? ScopedName.of("exports", scopeRoot) : null;
case ES6_MODULE:
throw new IllegalStateException("Type checking ES modules not yet supported");
case COMMON_JS:
throw new IllegalStateException("Type checking CommonJs modules not yet supported");
case SCRIPT:
throw new IllegalStateException("Cannot import a name from a SCRIPT");
}
throw new AssertionError();
} | [
"ScopedName",
"getClosureNamespaceTypeFromCall",
"(",
"Node",
"googRequire",
")",
"{",
"if",
"(",
"moduleMap",
"==",
"null",
")",
"{",
"// TODO(b/124919359): make sure all tests have generated a ModuleMap",
"return",
"null",
";",
"}",
"String",
"moduleId",
"=",
"googRequire",
".",
"getSecondChild",
"(",
")",
".",
"getString",
"(",
")",
";",
"Module",
"module",
"=",
"moduleMap",
".",
"getClosureModule",
"(",
"moduleId",
")",
";",
"if",
"(",
"module",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"switch",
"(",
"module",
".",
"metadata",
"(",
")",
".",
"moduleType",
"(",
")",
")",
"{",
"case",
"GOOG_PROVIDE",
":",
"// Expect this to be a global variable",
"Node",
"provide",
"=",
"module",
".",
"metadata",
"(",
")",
".",
"rootNode",
"(",
")",
";",
"if",
"(",
"provide",
"!=",
"null",
"&&",
"provide",
".",
"isScript",
"(",
")",
")",
"{",
"return",
"ScopedName",
".",
"of",
"(",
"moduleId",
",",
"provide",
".",
"getGrandparent",
"(",
")",
")",
";",
"}",
"else",
"{",
"// Unknown module requires default to 'goog provides', but we don't want to type them.",
"return",
"null",
";",
"}",
"case",
"GOOG_MODULE",
":",
"case",
"LEGACY_GOOG_MODULE",
":",
"// TODO(b/124919359): Fix getGoogModuleScopeRoot to never return null.",
"Node",
"scopeRoot",
"=",
"getGoogModuleScopeRoot",
"(",
"module",
")",
";",
"return",
"scopeRoot",
"!=",
"null",
"?",
"ScopedName",
".",
"of",
"(",
"\"exports\"",
",",
"scopeRoot",
")",
":",
"null",
";",
"case",
"ES6_MODULE",
":",
"throw",
"new",
"IllegalStateException",
"(",
"\"Type checking ES modules not yet supported\"",
")",
";",
"case",
"COMMON_JS",
":",
"throw",
"new",
"IllegalStateException",
"(",
"\"Type checking CommonJs modules not yet supported\"",
")",
";",
"case",
"SCRIPT",
":",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot import a name from a SCRIPT\"",
")",
";",
"}",
"throw",
"new",
"AssertionError",
"(",
")",
";",
"}"
] | Attempts to look up the type of a Closure namespace from a require call
<p>This returns null if the given {@link ModuleMap} is null, if the required module does not
exist, or if support is missing for the type of required {@link Module}. Currently only
requires of other goog.modules are supported.
@param googRequire a CALL node representing some kind of Closure require. | [
"Attempts",
"to",
"look",
"up",
"the",
"type",
"of",
"a",
"Closure",
"namespace",
"from",
"a",
"require",
"call"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ModuleImportResolver.java#L68-L102 |
23,887 | google/closure-compiler | src/com/google/javascript/jscomp/TemplateAstMatcher.java | TemplateAstMatcher.initTemplate | private Node initTemplate(Node templateFunctionNode) {
Node prepped = templateFunctionNode.cloneTree();
prepTemplatePlaceholders(prepped);
Node body = prepped.getLastChild();
Node startNode;
if (body.hasOneChild() && body.getFirstChild().isExprResult()) {
// When matching an expression, don't require it to be a complete
// statement.
startNode = body.getFirstFirstChild();
} else {
startNode = body.getFirstChild();
}
for (int i = 0; i < templateLocals.size(); i++) {
// reserve space in the locals array.
this.localVarMatches.add(null);
}
for (int i = 0; i < templateParams.size(); i++) {
// reserve space in the params array.
this.paramNodeMatches.add(null);
}
return startNode;
} | java | private Node initTemplate(Node templateFunctionNode) {
Node prepped = templateFunctionNode.cloneTree();
prepTemplatePlaceholders(prepped);
Node body = prepped.getLastChild();
Node startNode;
if (body.hasOneChild() && body.getFirstChild().isExprResult()) {
// When matching an expression, don't require it to be a complete
// statement.
startNode = body.getFirstFirstChild();
} else {
startNode = body.getFirstChild();
}
for (int i = 0; i < templateLocals.size(); i++) {
// reserve space in the locals array.
this.localVarMatches.add(null);
}
for (int i = 0; i < templateParams.size(); i++) {
// reserve space in the params array.
this.paramNodeMatches.add(null);
}
return startNode;
} | [
"private",
"Node",
"initTemplate",
"(",
"Node",
"templateFunctionNode",
")",
"{",
"Node",
"prepped",
"=",
"templateFunctionNode",
".",
"cloneTree",
"(",
")",
";",
"prepTemplatePlaceholders",
"(",
"prepped",
")",
";",
"Node",
"body",
"=",
"prepped",
".",
"getLastChild",
"(",
")",
";",
"Node",
"startNode",
";",
"if",
"(",
"body",
".",
"hasOneChild",
"(",
")",
"&&",
"body",
".",
"getFirstChild",
"(",
")",
".",
"isExprResult",
"(",
")",
")",
"{",
"// When matching an expression, don't require it to be a complete",
"// statement.",
"startNode",
"=",
"body",
".",
"getFirstFirstChild",
"(",
")",
";",
"}",
"else",
"{",
"startNode",
"=",
"body",
".",
"getFirstChild",
"(",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"templateLocals",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"// reserve space in the locals array.",
"this",
".",
"localVarMatches",
".",
"add",
"(",
"null",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"templateParams",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"// reserve space in the params array.",
"this",
".",
"paramNodeMatches",
".",
"add",
"(",
"null",
")",
";",
"}",
"return",
"startNode",
";",
"}"
] | Prepare an template AST to use when performing matches.
@param templateFunctionNode The template declaration function to extract
the template AST from.
@return The first node of the template AST sequence to use when matching. | [
"Prepare",
"an",
"template",
"AST",
"to",
"use",
"when",
"performing",
"matches",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TemplateAstMatcher.java#L167-L191 |
23,888 | google/closure-compiler | src/com/google/javascript/jscomp/TemplateAstMatcher.java | TemplateAstMatcher.prepTemplatePlaceholders | private void prepTemplatePlaceholders(Node fn) {
final List<String> locals = templateLocals;
final List<String> params = templateParams;
final Map<String, JSType> paramTypes = new HashMap<>();
// drop the function name so it isn't include in the name maps
String fnName = fn.getFirstChild().getString();
fn.getFirstChild().setString("");
// Build a list of parameter names and types.
Node templateParametersNode = fn.getSecondChild();
JSDocInfo info = NodeUtil.getBestJSDocInfo(fn);
if (templateParametersNode.hasChildren()) {
Preconditions.checkNotNull(info,
"Missing JSDoc declaration for template function %s", fnName);
}
for (Node paramNode : templateParametersNode.children()) {
String name = paramNode.getString();
JSTypeExpression expression = info.getParameterType(name);
Preconditions.checkNotNull(expression,
"Missing JSDoc for parameter %s of template function %s",
name, fnName);
JSType type = typeRegistry.evaluateTypeExpressionInGlobalScope(expression);
checkNotNull(type);
params.add(name);
paramTypes.put(name, type);
}
// Find references to string literals, local variables and parameters and replace them.
traverse(
fn,
new Visitor() {
@Override
public void visit(Node n) {
if (n.isName()) {
Node parent = n.getParent();
String name = n.getString();
if (!name.isEmpty() && parent.isVar() && !locals.contains(name)) {
locals.add(n.getString());
}
if (params.contains(name)) {
JSType type = paramTypes.get(name);
boolean isStringLiteral =
type.isStringValueType() && name.startsWith("string_literal");
replaceNodeInPlace(
n, createTemplateParameterNode(params.indexOf(name), type, isStringLiteral));
} else if (locals.contains(name)) {
replaceNodeInPlace(n, createTemplateLocalNameNode(locals.indexOf(name)));
}
}
}
});
} | java | private void prepTemplatePlaceholders(Node fn) {
final List<String> locals = templateLocals;
final List<String> params = templateParams;
final Map<String, JSType> paramTypes = new HashMap<>();
// drop the function name so it isn't include in the name maps
String fnName = fn.getFirstChild().getString();
fn.getFirstChild().setString("");
// Build a list of parameter names and types.
Node templateParametersNode = fn.getSecondChild();
JSDocInfo info = NodeUtil.getBestJSDocInfo(fn);
if (templateParametersNode.hasChildren()) {
Preconditions.checkNotNull(info,
"Missing JSDoc declaration for template function %s", fnName);
}
for (Node paramNode : templateParametersNode.children()) {
String name = paramNode.getString();
JSTypeExpression expression = info.getParameterType(name);
Preconditions.checkNotNull(expression,
"Missing JSDoc for parameter %s of template function %s",
name, fnName);
JSType type = typeRegistry.evaluateTypeExpressionInGlobalScope(expression);
checkNotNull(type);
params.add(name);
paramTypes.put(name, type);
}
// Find references to string literals, local variables and parameters and replace them.
traverse(
fn,
new Visitor() {
@Override
public void visit(Node n) {
if (n.isName()) {
Node parent = n.getParent();
String name = n.getString();
if (!name.isEmpty() && parent.isVar() && !locals.contains(name)) {
locals.add(n.getString());
}
if (params.contains(name)) {
JSType type = paramTypes.get(name);
boolean isStringLiteral =
type.isStringValueType() && name.startsWith("string_literal");
replaceNodeInPlace(
n, createTemplateParameterNode(params.indexOf(name), type, isStringLiteral));
} else if (locals.contains(name)) {
replaceNodeInPlace(n, createTemplateLocalNameNode(locals.indexOf(name)));
}
}
}
});
} | [
"private",
"void",
"prepTemplatePlaceholders",
"(",
"Node",
"fn",
")",
"{",
"final",
"List",
"<",
"String",
">",
"locals",
"=",
"templateLocals",
";",
"final",
"List",
"<",
"String",
">",
"params",
"=",
"templateParams",
";",
"final",
"Map",
"<",
"String",
",",
"JSType",
">",
"paramTypes",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"// drop the function name so it isn't include in the name maps",
"String",
"fnName",
"=",
"fn",
".",
"getFirstChild",
"(",
")",
".",
"getString",
"(",
")",
";",
"fn",
".",
"getFirstChild",
"(",
")",
".",
"setString",
"(",
"\"\"",
")",
";",
"// Build a list of parameter names and types.",
"Node",
"templateParametersNode",
"=",
"fn",
".",
"getSecondChild",
"(",
")",
";",
"JSDocInfo",
"info",
"=",
"NodeUtil",
".",
"getBestJSDocInfo",
"(",
"fn",
")",
";",
"if",
"(",
"templateParametersNode",
".",
"hasChildren",
"(",
")",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"info",
",",
"\"Missing JSDoc declaration for template function %s\"",
",",
"fnName",
")",
";",
"}",
"for",
"(",
"Node",
"paramNode",
":",
"templateParametersNode",
".",
"children",
"(",
")",
")",
"{",
"String",
"name",
"=",
"paramNode",
".",
"getString",
"(",
")",
";",
"JSTypeExpression",
"expression",
"=",
"info",
".",
"getParameterType",
"(",
"name",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"expression",
",",
"\"Missing JSDoc for parameter %s of template function %s\"",
",",
"name",
",",
"fnName",
")",
";",
"JSType",
"type",
"=",
"typeRegistry",
".",
"evaluateTypeExpressionInGlobalScope",
"(",
"expression",
")",
";",
"checkNotNull",
"(",
"type",
")",
";",
"params",
".",
"add",
"(",
"name",
")",
";",
"paramTypes",
".",
"put",
"(",
"name",
",",
"type",
")",
";",
"}",
"// Find references to string literals, local variables and parameters and replace them.",
"traverse",
"(",
"fn",
",",
"new",
"Visitor",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"visit",
"(",
"Node",
"n",
")",
"{",
"if",
"(",
"n",
".",
"isName",
"(",
")",
")",
"{",
"Node",
"parent",
"=",
"n",
".",
"getParent",
"(",
")",
";",
"String",
"name",
"=",
"n",
".",
"getString",
"(",
")",
";",
"if",
"(",
"!",
"name",
".",
"isEmpty",
"(",
")",
"&&",
"parent",
".",
"isVar",
"(",
")",
"&&",
"!",
"locals",
".",
"contains",
"(",
"name",
")",
")",
"{",
"locals",
".",
"add",
"(",
"n",
".",
"getString",
"(",
")",
")",
";",
"}",
"if",
"(",
"params",
".",
"contains",
"(",
"name",
")",
")",
"{",
"JSType",
"type",
"=",
"paramTypes",
".",
"get",
"(",
"name",
")",
";",
"boolean",
"isStringLiteral",
"=",
"type",
".",
"isStringValueType",
"(",
")",
"&&",
"name",
".",
"startsWith",
"(",
"\"string_literal\"",
")",
";",
"replaceNodeInPlace",
"(",
"n",
",",
"createTemplateParameterNode",
"(",
"params",
".",
"indexOf",
"(",
"name",
")",
",",
"type",
",",
"isStringLiteral",
")",
")",
";",
"}",
"else",
"if",
"(",
"locals",
".",
"contains",
"(",
"name",
")",
")",
"{",
"replaceNodeInPlace",
"(",
"n",
",",
"createTemplateLocalNameNode",
"(",
"locals",
".",
"indexOf",
"(",
"name",
")",
")",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"}"
] | Build parameter and local information for the template and replace
the references in the template 'fn' with placeholder nodes use to
facility matching. | [
"Build",
"parameter",
"and",
"local",
"information",
"for",
"the",
"template",
"and",
"replace",
"the",
"references",
"in",
"the",
"template",
"fn",
"with",
"placeholder",
"nodes",
"use",
"to",
"facility",
"matching",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TemplateAstMatcher.java#L198-L251 |
23,889 | google/closure-compiler | src/com/google/javascript/jscomp/TemplateAstMatcher.java | TemplateAstMatcher.createTemplateParameterNode | private Node createTemplateParameterNode(int index, JSType type, boolean isStringLiteral) {
checkState(index >= 0);
checkNotNull(type);
Node n = Node.newNumber(index);
if (isStringLiteral) {
n.setToken(TEMPLATE_STRING_LITERAL);
} else {
n.setToken(TEMPLATE_TYPE_PARAM);
}
n.setJSType(type);
return n;
} | java | private Node createTemplateParameterNode(int index, JSType type, boolean isStringLiteral) {
checkState(index >= 0);
checkNotNull(type);
Node n = Node.newNumber(index);
if (isStringLiteral) {
n.setToken(TEMPLATE_STRING_LITERAL);
} else {
n.setToken(TEMPLATE_TYPE_PARAM);
}
n.setJSType(type);
return n;
} | [
"private",
"Node",
"createTemplateParameterNode",
"(",
"int",
"index",
",",
"JSType",
"type",
",",
"boolean",
"isStringLiteral",
")",
"{",
"checkState",
"(",
"index",
">=",
"0",
")",
";",
"checkNotNull",
"(",
"type",
")",
";",
"Node",
"n",
"=",
"Node",
".",
"newNumber",
"(",
"index",
")",
";",
"if",
"(",
"isStringLiteral",
")",
"{",
"n",
".",
"setToken",
"(",
"TEMPLATE_STRING_LITERAL",
")",
";",
"}",
"else",
"{",
"n",
".",
"setToken",
"(",
"TEMPLATE_TYPE_PARAM",
")",
";",
"}",
"n",
".",
"setJSType",
"(",
"type",
")",
";",
"return",
"n",
";",
"}"
] | Creates a template parameter or string literal template node. | [
"Creates",
"a",
"template",
"parameter",
"or",
"string",
"literal",
"template",
"node",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TemplateAstMatcher.java#L293-L304 |
23,890 | google/closure-compiler | src/com/google/javascript/jscomp/TemplateAstMatcher.java | TemplateAstMatcher.matchesTemplateShape | private boolean matchesTemplateShape(Node template, Node ast) {
while (template != null) {
if (ast == null || !matchesNodeShape(template, ast)) {
return false;
}
template = template.getNext();
ast = ast.getNext();
}
return true;
} | java | private boolean matchesTemplateShape(Node template, Node ast) {
while (template != null) {
if (ast == null || !matchesNodeShape(template, ast)) {
return false;
}
template = template.getNext();
ast = ast.getNext();
}
return true;
} | [
"private",
"boolean",
"matchesTemplateShape",
"(",
"Node",
"template",
",",
"Node",
"ast",
")",
"{",
"while",
"(",
"template",
"!=",
"null",
")",
"{",
"if",
"(",
"ast",
"==",
"null",
"||",
"!",
"matchesNodeShape",
"(",
"template",
",",
"ast",
")",
")",
"{",
"return",
"false",
";",
"}",
"template",
"=",
"template",
".",
"getNext",
"(",
")",
";",
"ast",
"=",
"ast",
".",
"getNext",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Returns whether the template matches an AST structure node starting with
node, taking into account the template parameters that were provided to
this matcher.
Here only the template shape is checked, template local declarations and
parameters are checked later. | [
"Returns",
"whether",
"the",
"template",
"matches",
"an",
"AST",
"structure",
"node",
"starting",
"with",
"node",
"taking",
"into",
"account",
"the",
"template",
"parameters",
"that",
"were",
"provided",
"to",
"this",
"matcher",
".",
"Here",
"only",
"the",
"template",
"shape",
"is",
"checked",
"template",
"local",
"declarations",
"and",
"parameters",
"are",
"checked",
"later",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TemplateAstMatcher.java#L324-L333 |
23,891 | google/closure-compiler | src/com/google/javascript/jscomp/TemplateAstMatcher.java | TemplateAstMatcher.matchesNode | private boolean matchesNode(Node template, Node ast) {
if (isTemplateParameterNode(template)) {
int paramIndex = (int) (template.getDouble());
Node previousMatch = paramNodeMatches.get(paramIndex);
if (previousMatch != null) {
// If this named node has already been matched against, make sure all
// subsequent usages of the same named node are equivalent.
return ast.isEquivalentTo(previousMatch);
}
// Only the types need to match for the template parameters, which allows
// the template function to express arbitrary expressions.
JSType templateType = template.getJSType();
checkNotNull(templateType, "null template parameter type.");
// TODO(johnlenz): We shouldn't spend time checking template whose
// types whose definitions aren't included (NoResolvedType). Alternately
// we should treat them as "unknown" and perform loose matches.
if (isUnresolvedType(templateType)) {
return false;
}
MatchResult matchResult = typeMatchingStrategy.match(templateType, ast.getJSType());
isLooseMatch = matchResult.isLooseMatch();
boolean isMatch = matchResult.isMatch();
if (isMatch && previousMatch == null) {
paramNodeMatches.set(paramIndex, ast);
}
return isMatch;
} else if (isTemplateLocalNameNode(template)) {
// If this template name node was already matched against, then make sure
// all subsequent usages of the same template name node are equivalent in
// the matched code.
// For example, this code will handle the case:
// function template() {
// var a = 'str';
// fn(a);
// }
//
// will only match test code:
// var b = 'str';
// fn(b);
//
// but it will not match:
// var b = 'str';
// fn('str');
int paramIndex = (int) (template.getDouble());
boolean previouslyMatched = this.localVarMatches.get(paramIndex) != null;
if (previouslyMatched) {
// If this named node has already been matched against, make sure all
// subsequent usages of the same named node are equivalent.
return ast.getString().equals(this.localVarMatches.get(paramIndex));
} else {
String originalName = ast.getOriginalName();
String name = (originalName != null) ? originalName : ast.getString();
this.localVarMatches.set(paramIndex, name);
}
} else if (isTemplateParameterStringLiteralNode(template)) {
int paramIndex = (int) (template.getDouble());
Node previousMatch = paramNodeMatches.get(paramIndex);
if (previousMatch != null) {
return ast.isEquivalentTo(previousMatch);
}
if (NodeUtil.isSomeCompileTimeConstStringValue(ast)) {
paramNodeMatches.set(paramIndex, ast);
return true;
}
return false;
}
// Template and AST shape has already been checked, but continue look for
// other template variables (parameters and locals) that must be checked.
Node templateChild = template.getFirstChild();
Node astChild = ast.getFirstChild();
while (templateChild != null) {
if (!matchesNode(templateChild, astChild)) {
return false;
}
templateChild = templateChild.getNext();
astChild = astChild.getNext();
}
return true;
} | java | private boolean matchesNode(Node template, Node ast) {
if (isTemplateParameterNode(template)) {
int paramIndex = (int) (template.getDouble());
Node previousMatch = paramNodeMatches.get(paramIndex);
if (previousMatch != null) {
// If this named node has already been matched against, make sure all
// subsequent usages of the same named node are equivalent.
return ast.isEquivalentTo(previousMatch);
}
// Only the types need to match for the template parameters, which allows
// the template function to express arbitrary expressions.
JSType templateType = template.getJSType();
checkNotNull(templateType, "null template parameter type.");
// TODO(johnlenz): We shouldn't spend time checking template whose
// types whose definitions aren't included (NoResolvedType). Alternately
// we should treat them as "unknown" and perform loose matches.
if (isUnresolvedType(templateType)) {
return false;
}
MatchResult matchResult = typeMatchingStrategy.match(templateType, ast.getJSType());
isLooseMatch = matchResult.isLooseMatch();
boolean isMatch = matchResult.isMatch();
if (isMatch && previousMatch == null) {
paramNodeMatches.set(paramIndex, ast);
}
return isMatch;
} else if (isTemplateLocalNameNode(template)) {
// If this template name node was already matched against, then make sure
// all subsequent usages of the same template name node are equivalent in
// the matched code.
// For example, this code will handle the case:
// function template() {
// var a = 'str';
// fn(a);
// }
//
// will only match test code:
// var b = 'str';
// fn(b);
//
// but it will not match:
// var b = 'str';
// fn('str');
int paramIndex = (int) (template.getDouble());
boolean previouslyMatched = this.localVarMatches.get(paramIndex) != null;
if (previouslyMatched) {
// If this named node has already been matched against, make sure all
// subsequent usages of the same named node are equivalent.
return ast.getString().equals(this.localVarMatches.get(paramIndex));
} else {
String originalName = ast.getOriginalName();
String name = (originalName != null) ? originalName : ast.getString();
this.localVarMatches.set(paramIndex, name);
}
} else if (isTemplateParameterStringLiteralNode(template)) {
int paramIndex = (int) (template.getDouble());
Node previousMatch = paramNodeMatches.get(paramIndex);
if (previousMatch != null) {
return ast.isEquivalentTo(previousMatch);
}
if (NodeUtil.isSomeCompileTimeConstStringValue(ast)) {
paramNodeMatches.set(paramIndex, ast);
return true;
}
return false;
}
// Template and AST shape has already been checked, but continue look for
// other template variables (parameters and locals) that must be checked.
Node templateChild = template.getFirstChild();
Node astChild = ast.getFirstChild();
while (templateChild != null) {
if (!matchesNode(templateChild, astChild)) {
return false;
}
templateChild = templateChild.getNext();
astChild = astChild.getNext();
}
return true;
} | [
"private",
"boolean",
"matchesNode",
"(",
"Node",
"template",
",",
"Node",
"ast",
")",
"{",
"if",
"(",
"isTemplateParameterNode",
"(",
"template",
")",
")",
"{",
"int",
"paramIndex",
"=",
"(",
"int",
")",
"(",
"template",
".",
"getDouble",
"(",
")",
")",
";",
"Node",
"previousMatch",
"=",
"paramNodeMatches",
".",
"get",
"(",
"paramIndex",
")",
";",
"if",
"(",
"previousMatch",
"!=",
"null",
")",
"{",
"// If this named node has already been matched against, make sure all",
"// subsequent usages of the same named node are equivalent.",
"return",
"ast",
".",
"isEquivalentTo",
"(",
"previousMatch",
")",
";",
"}",
"// Only the types need to match for the template parameters, which allows",
"// the template function to express arbitrary expressions.",
"JSType",
"templateType",
"=",
"template",
".",
"getJSType",
"(",
")",
";",
"checkNotNull",
"(",
"templateType",
",",
"\"null template parameter type.\"",
")",
";",
"// TODO(johnlenz): We shouldn't spend time checking template whose",
"// types whose definitions aren't included (NoResolvedType). Alternately",
"// we should treat them as \"unknown\" and perform loose matches.",
"if",
"(",
"isUnresolvedType",
"(",
"templateType",
")",
")",
"{",
"return",
"false",
";",
"}",
"MatchResult",
"matchResult",
"=",
"typeMatchingStrategy",
".",
"match",
"(",
"templateType",
",",
"ast",
".",
"getJSType",
"(",
")",
")",
";",
"isLooseMatch",
"=",
"matchResult",
".",
"isLooseMatch",
"(",
")",
";",
"boolean",
"isMatch",
"=",
"matchResult",
".",
"isMatch",
"(",
")",
";",
"if",
"(",
"isMatch",
"&&",
"previousMatch",
"==",
"null",
")",
"{",
"paramNodeMatches",
".",
"set",
"(",
"paramIndex",
",",
"ast",
")",
";",
"}",
"return",
"isMatch",
";",
"}",
"else",
"if",
"(",
"isTemplateLocalNameNode",
"(",
"template",
")",
")",
"{",
"// If this template name node was already matched against, then make sure",
"// all subsequent usages of the same template name node are equivalent in",
"// the matched code.",
"// For example, this code will handle the case:",
"// function template() {",
"// var a = 'str';",
"// fn(a);",
"// }",
"//",
"// will only match test code:",
"// var b = 'str';",
"// fn(b);",
"//",
"// but it will not match:",
"// var b = 'str';",
"// fn('str');",
"int",
"paramIndex",
"=",
"(",
"int",
")",
"(",
"template",
".",
"getDouble",
"(",
")",
")",
";",
"boolean",
"previouslyMatched",
"=",
"this",
".",
"localVarMatches",
".",
"get",
"(",
"paramIndex",
")",
"!=",
"null",
";",
"if",
"(",
"previouslyMatched",
")",
"{",
"// If this named node has already been matched against, make sure all",
"// subsequent usages of the same named node are equivalent.",
"return",
"ast",
".",
"getString",
"(",
")",
".",
"equals",
"(",
"this",
".",
"localVarMatches",
".",
"get",
"(",
"paramIndex",
")",
")",
";",
"}",
"else",
"{",
"String",
"originalName",
"=",
"ast",
".",
"getOriginalName",
"(",
")",
";",
"String",
"name",
"=",
"(",
"originalName",
"!=",
"null",
")",
"?",
"originalName",
":",
"ast",
".",
"getString",
"(",
")",
";",
"this",
".",
"localVarMatches",
".",
"set",
"(",
"paramIndex",
",",
"name",
")",
";",
"}",
"}",
"else",
"if",
"(",
"isTemplateParameterStringLiteralNode",
"(",
"template",
")",
")",
"{",
"int",
"paramIndex",
"=",
"(",
"int",
")",
"(",
"template",
".",
"getDouble",
"(",
")",
")",
";",
"Node",
"previousMatch",
"=",
"paramNodeMatches",
".",
"get",
"(",
"paramIndex",
")",
";",
"if",
"(",
"previousMatch",
"!=",
"null",
")",
"{",
"return",
"ast",
".",
"isEquivalentTo",
"(",
"previousMatch",
")",
";",
"}",
"if",
"(",
"NodeUtil",
".",
"isSomeCompileTimeConstStringValue",
"(",
"ast",
")",
")",
"{",
"paramNodeMatches",
".",
"set",
"(",
"paramIndex",
",",
"ast",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
"// Template and AST shape has already been checked, but continue look for",
"// other template variables (parameters and locals) that must be checked.",
"Node",
"templateChild",
"=",
"template",
".",
"getFirstChild",
"(",
")",
";",
"Node",
"astChild",
"=",
"ast",
".",
"getFirstChild",
"(",
")",
";",
"while",
"(",
"templateChild",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"matchesNode",
"(",
"templateChild",
",",
"astChild",
")",
")",
"{",
"return",
"false",
";",
"}",
"templateChild",
"=",
"templateChild",
".",
"getNext",
"(",
")",
";",
"astChild",
"=",
"astChild",
".",
"getNext",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Returns whether two nodes are equivalent, taking into account the template parameters that were
provided to this matcher. If the template comparison node is a parameter node, then only the
types of the node must match. If the template node is a string literal, only match string
literals. Otherwise, the node must be equal and the child nodes must be equivalent according to
the same function. This differs from the built in Node equivalence function with the special
comparison. | [
"Returns",
"whether",
"two",
"nodes",
"are",
"equivalent",
"taking",
"into",
"account",
"the",
"template",
"parameters",
"that",
"were",
"provided",
"to",
"this",
"matcher",
".",
"If",
"the",
"template",
"comparison",
"node",
"is",
"a",
"parameter",
"node",
"then",
"only",
"the",
"types",
"of",
"the",
"node",
"must",
"match",
".",
"If",
"the",
"template",
"node",
"is",
"a",
"string",
"literal",
"only",
"match",
"string",
"literals",
".",
"Otherwise",
"the",
"node",
"must",
"be",
"equal",
"and",
"the",
"child",
"nodes",
"must",
"be",
"equivalent",
"according",
"to",
"the",
"same",
"function",
".",
"This",
"differs",
"from",
"the",
"built",
"in",
"Node",
"equivalence",
"function",
"with",
"the",
"special",
"comparison",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TemplateAstMatcher.java#L391-L476 |
23,892 | google/closure-compiler | src/com/google/javascript/rhino/jstype/PrototypeObjectType.java | PrototypeObjectType.hasOverriddenNativeProperty | private boolean hasOverriddenNativeProperty(String propertyName) {
if (isNativeObjectType()) {
return false;
}
JSType propertyType = getPropertyType(propertyName);
ObjectType nativeType =
isFunctionType()
? registry.getNativeObjectType(JSTypeNative.FUNCTION_PROTOTYPE)
: registry.getNativeObjectType(JSTypeNative.OBJECT_PROTOTYPE);
JSType nativePropertyType = nativeType.getPropertyType(propertyName);
return propertyType != nativePropertyType;
} | java | private boolean hasOverriddenNativeProperty(String propertyName) {
if (isNativeObjectType()) {
return false;
}
JSType propertyType = getPropertyType(propertyName);
ObjectType nativeType =
isFunctionType()
? registry.getNativeObjectType(JSTypeNative.FUNCTION_PROTOTYPE)
: registry.getNativeObjectType(JSTypeNative.OBJECT_PROTOTYPE);
JSType nativePropertyType = nativeType.getPropertyType(propertyName);
return propertyType != nativePropertyType;
} | [
"private",
"boolean",
"hasOverriddenNativeProperty",
"(",
"String",
"propertyName",
")",
"{",
"if",
"(",
"isNativeObjectType",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"JSType",
"propertyType",
"=",
"getPropertyType",
"(",
"propertyName",
")",
";",
"ObjectType",
"nativeType",
"=",
"isFunctionType",
"(",
")",
"?",
"registry",
".",
"getNativeObjectType",
"(",
"JSTypeNative",
".",
"FUNCTION_PROTOTYPE",
")",
":",
"registry",
".",
"getNativeObjectType",
"(",
"JSTypeNative",
".",
"OBJECT_PROTOTYPE",
")",
";",
"JSType",
"nativePropertyType",
"=",
"nativeType",
".",
"getPropertyType",
"(",
"propertyName",
")",
";",
"return",
"propertyType",
"!=",
"nativePropertyType",
";",
"}"
] | Given the name of a native object property, checks whether the property is
present on the object and different from the native one. | [
"Given",
"the",
"name",
"of",
"a",
"native",
"object",
"property",
"checks",
"whether",
"the",
"property",
"is",
"present",
"on",
"the",
"object",
"and",
"different",
"from",
"the",
"native",
"one",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/PrototypeObjectType.java#L247-L259 |
23,893 | google/closure-compiler | src/com/google/javascript/rhino/jstype/PrototypeObjectType.java | PrototypeObjectType.isSubtype | private static boolean isSubtype(
ObjectType typeA,
RecordType typeB,
ImplCache implicitImplCache,
SubtypingMode subtypingMode) {
MatchStatus cached = implicitImplCache.checkCache(typeA, typeB);
if (cached != null) {
return cached.subtypeValue();
}
boolean result =
isStructuralSubtypeHelper(
typeA, typeB, implicitImplCache, subtypingMode, ALL_PROPS_ARE_REQUIRED);
return implicitImplCache.updateCache(typeA, typeB, MatchStatus.valueOf(result));
} | java | private static boolean isSubtype(
ObjectType typeA,
RecordType typeB,
ImplCache implicitImplCache,
SubtypingMode subtypingMode) {
MatchStatus cached = implicitImplCache.checkCache(typeA, typeB);
if (cached != null) {
return cached.subtypeValue();
}
boolean result =
isStructuralSubtypeHelper(
typeA, typeB, implicitImplCache, subtypingMode, ALL_PROPS_ARE_REQUIRED);
return implicitImplCache.updateCache(typeA, typeB, MatchStatus.valueOf(result));
} | [
"private",
"static",
"boolean",
"isSubtype",
"(",
"ObjectType",
"typeA",
",",
"RecordType",
"typeB",
",",
"ImplCache",
"implicitImplCache",
",",
"SubtypingMode",
"subtypingMode",
")",
"{",
"MatchStatus",
"cached",
"=",
"implicitImplCache",
".",
"checkCache",
"(",
"typeA",
",",
"typeB",
")",
";",
"if",
"(",
"cached",
"!=",
"null",
")",
"{",
"return",
"cached",
".",
"subtypeValue",
"(",
")",
";",
"}",
"boolean",
"result",
"=",
"isStructuralSubtypeHelper",
"(",
"typeA",
",",
"typeB",
",",
"implicitImplCache",
",",
"subtypingMode",
",",
"ALL_PROPS_ARE_REQUIRED",
")",
";",
"return",
"implicitImplCache",
".",
"updateCache",
"(",
"typeA",
",",
"typeB",
",",
"MatchStatus",
".",
"valueOf",
"(",
"result",
")",
")",
";",
"}"
] | Determines if typeA is a subtype of typeB | [
"Determines",
"if",
"typeA",
"is",
"a",
"subtype",
"of",
"typeB"
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/PrototypeObjectType.java#L433-L448 |
23,894 | google/closure-compiler | src/com/google/javascript/jscomp/SourceMapInput.java | SourceMapInput.getSourceMap | public synchronized @Nullable SourceMapConsumerV3 getSourceMap(ErrorManager errorManager) {
if (!cached) {
// Avoid re-reading or reparsing files.
cached = true;
String sourceMapPath = sourceFile.getOriginalPath();
try {
String sourceMapContents = sourceFile.getCode();
SourceMapConsumerV3 consumer = new SourceMapConsumerV3();
consumer.parse(sourceMapContents);
parsedSourceMap = consumer;
} catch (IOException e) {
JSError error =
JSError.make(SourceMapInput.SOURCEMAP_RESOLVE_FAILED, sourceMapPath, e.getMessage());
errorManager.report(error.getDefaultLevel(), error);
} catch (SourceMapParseException e) {
JSError error =
JSError.make(SourceMapInput.SOURCEMAP_PARSE_FAILED, sourceMapPath, e.getMessage());
errorManager.report(error.getDefaultLevel(), error);
}
}
return parsedSourceMap;
} | java | public synchronized @Nullable SourceMapConsumerV3 getSourceMap(ErrorManager errorManager) {
if (!cached) {
// Avoid re-reading or reparsing files.
cached = true;
String sourceMapPath = sourceFile.getOriginalPath();
try {
String sourceMapContents = sourceFile.getCode();
SourceMapConsumerV3 consumer = new SourceMapConsumerV3();
consumer.parse(sourceMapContents);
parsedSourceMap = consumer;
} catch (IOException e) {
JSError error =
JSError.make(SourceMapInput.SOURCEMAP_RESOLVE_FAILED, sourceMapPath, e.getMessage());
errorManager.report(error.getDefaultLevel(), error);
} catch (SourceMapParseException e) {
JSError error =
JSError.make(SourceMapInput.SOURCEMAP_PARSE_FAILED, sourceMapPath, e.getMessage());
errorManager.report(error.getDefaultLevel(), error);
}
}
return parsedSourceMap;
} | [
"public",
"synchronized",
"@",
"Nullable",
"SourceMapConsumerV3",
"getSourceMap",
"(",
"ErrorManager",
"errorManager",
")",
"{",
"if",
"(",
"!",
"cached",
")",
"{",
"// Avoid re-reading or reparsing files.",
"cached",
"=",
"true",
";",
"String",
"sourceMapPath",
"=",
"sourceFile",
".",
"getOriginalPath",
"(",
")",
";",
"try",
"{",
"String",
"sourceMapContents",
"=",
"sourceFile",
".",
"getCode",
"(",
")",
";",
"SourceMapConsumerV3",
"consumer",
"=",
"new",
"SourceMapConsumerV3",
"(",
")",
";",
"consumer",
".",
"parse",
"(",
"sourceMapContents",
")",
";",
"parsedSourceMap",
"=",
"consumer",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"JSError",
"error",
"=",
"JSError",
".",
"make",
"(",
"SourceMapInput",
".",
"SOURCEMAP_RESOLVE_FAILED",
",",
"sourceMapPath",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"errorManager",
".",
"report",
"(",
"error",
".",
"getDefaultLevel",
"(",
")",
",",
"error",
")",
";",
"}",
"catch",
"(",
"SourceMapParseException",
"e",
")",
"{",
"JSError",
"error",
"=",
"JSError",
".",
"make",
"(",
"SourceMapInput",
".",
"SOURCEMAP_PARSE_FAILED",
",",
"sourceMapPath",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"errorManager",
".",
"report",
"(",
"error",
".",
"getDefaultLevel",
"(",
")",
",",
"error",
")",
";",
"}",
"}",
"return",
"parsedSourceMap",
";",
"}"
] | Gets the source map, reading from disk and parsing if necessary. Returns null if the sourcemap
cannot be resolved or is malformed. | [
"Gets",
"the",
"source",
"map",
"reading",
"from",
"disk",
"and",
"parsing",
"if",
"necessary",
".",
"Returns",
"null",
"if",
"the",
"sourcemap",
"cannot",
"be",
"resolved",
"or",
"is",
"malformed",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SourceMapInput.java#L50-L71 |
23,895 | google/closure-compiler | src/com/google/javascript/jscomp/RemoveUnusedPolyfills.java | RemoveUnusedPolyfills.getLastPartOfQualifiedName | private static String getLastPartOfQualifiedName(Node n) {
if (n.isName()) {
return n.getString();
} else if (n.isGetProp()) {
return n.getLastChild().getString();
}
return null;
} | java | private static String getLastPartOfQualifiedName(Node n) {
if (n.isName()) {
return n.getString();
} else if (n.isGetProp()) {
return n.getLastChild().getString();
}
return null;
} | [
"private",
"static",
"String",
"getLastPartOfQualifiedName",
"(",
"Node",
"n",
")",
"{",
"if",
"(",
"n",
".",
"isName",
"(",
")",
")",
"{",
"return",
"n",
".",
"getString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"n",
".",
"isGetProp",
"(",
")",
")",
"{",
"return",
"n",
".",
"getLastChild",
"(",
")",
".",
"getString",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] | or null for 'this' and 'super'. | [
"or",
"null",
"for",
"this",
"and",
"super",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedPolyfills.java#L222-L229 |
23,896 | google/closure-compiler | src/com/google/javascript/jscomp/CrossChunkCodeMotion.java | CrossChunkCodeMotion.moveGlobalSymbols | private void moveGlobalSymbols(Collection<GlobalSymbol> globalSymbols) {
for (GlobalSymbolCycle globalSymbolCycle :
new OrderAndCombineGlobalSymbols(globalSymbols).orderAndCombine()) {
// Symbols whose declarations refer to each other must be grouped together and their
// declaration statements moved together.
globalSymbolCycle.moveDeclarationStatements();
}
} | java | private void moveGlobalSymbols(Collection<GlobalSymbol> globalSymbols) {
for (GlobalSymbolCycle globalSymbolCycle :
new OrderAndCombineGlobalSymbols(globalSymbols).orderAndCombine()) {
// Symbols whose declarations refer to each other must be grouped together and their
// declaration statements moved together.
globalSymbolCycle.moveDeclarationStatements();
}
} | [
"private",
"void",
"moveGlobalSymbols",
"(",
"Collection",
"<",
"GlobalSymbol",
">",
"globalSymbols",
")",
"{",
"for",
"(",
"GlobalSymbolCycle",
"globalSymbolCycle",
":",
"new",
"OrderAndCombineGlobalSymbols",
"(",
"globalSymbols",
")",
".",
"orderAndCombine",
"(",
")",
")",
"{",
"// Symbols whose declarations refer to each other must be grouped together and their",
"// declaration statements moved together.",
"globalSymbolCycle",
".",
"moveDeclarationStatements",
"(",
")",
";",
"}",
"}"
] | Moves all of the declaration statements that can move to their best possible chunk location. | [
"Moves",
"all",
"of",
"the",
"declaration",
"statements",
"that",
"can",
"move",
"to",
"their",
"best",
"possible",
"chunk",
"location",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CrossChunkCodeMotion.java#L214-L221 |
23,897 | google/closure-compiler | src/com/google/javascript/refactoring/RefasterJsScanner.java | RefasterJsScanner.loadRefasterJsTemplate | public void loadRefasterJsTemplate(String refasterjsTemplate) throws IOException {
checkState(
templateJs == null, "Can't load RefasterJs template since a template is already loaded.");
this.templateJs =
Thread.currentThread().getContextClassLoader().getResource(refasterjsTemplate) != null
? Resources.toString(Resources.getResource(refasterjsTemplate), UTF_8)
: Files.asCharSource(new File(refasterjsTemplate), UTF_8).read();
} | java | public void loadRefasterJsTemplate(String refasterjsTemplate) throws IOException {
checkState(
templateJs == null, "Can't load RefasterJs template since a template is already loaded.");
this.templateJs =
Thread.currentThread().getContextClassLoader().getResource(refasterjsTemplate) != null
? Resources.toString(Resources.getResource(refasterjsTemplate), UTF_8)
: Files.asCharSource(new File(refasterjsTemplate), UTF_8).read();
} | [
"public",
"void",
"loadRefasterJsTemplate",
"(",
"String",
"refasterjsTemplate",
")",
"throws",
"IOException",
"{",
"checkState",
"(",
"templateJs",
"==",
"null",
",",
"\"Can't load RefasterJs template since a template is already loaded.\"",
")",
";",
"this",
".",
"templateJs",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
".",
"getResource",
"(",
"refasterjsTemplate",
")",
"!=",
"null",
"?",
"Resources",
".",
"toString",
"(",
"Resources",
".",
"getResource",
"(",
"refasterjsTemplate",
")",
",",
"UTF_8",
")",
":",
"Files",
".",
"asCharSource",
"(",
"new",
"File",
"(",
"refasterjsTemplate",
")",
",",
"UTF_8",
")",
".",
"read",
"(",
")",
";",
"}"
] | Loads the RefasterJs template. This must be called before the scanner is used. | [
"Loads",
"the",
"RefasterJs",
"template",
".",
"This",
"must",
"be",
"called",
"before",
"the",
"scanner",
"is",
"used",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/refactoring/RefasterJsScanner.java#L85-L92 |
23,898 | google/closure-compiler | src/com/google/javascript/refactoring/RefasterJsScanner.java | RefasterJsScanner.transformNode | private Node transformNode(
Node templateNode,
Map<String, Node> templateNodeToMatchMap,
Map<String, String> shortNames) {
Node clone = templateNode.cloneNode();
if (templateNode.isName()) {
String name = templateNode.getString();
if (templateNodeToMatchMap.containsKey(name)) {
Node templateMatch = templateNodeToMatchMap.get(name);
Preconditions.checkNotNull(templateMatch, "Match for %s is null", name);
if (templateNode.getParent().isVar()) {
// Var declarations should only copy the variable name from the saved match, but the rest
// of the subtree should come from the template node.
clone.setString(templateMatch.getString());
} else {
return templateMatch.cloneTree();
}
}
} else if (templateNode.isCall()
&& templateNode.getBooleanProp(Node.FREE_CALL)
&& templateNode.getFirstChild().isName()) {
String name = templateNode.getFirstChild().getString();
if (templateNodeToMatchMap.containsKey(name)) {
// If this function call matches a template parameter, don't treat it as a free call.
// This mirrors the behavior in the TemplateAstMatcher as well as ensures the code
// generator doesn't generate code like "(0,fn)()".
clone.putBooleanProp(Node.FREE_CALL, false);
}
}
if (templateNode.isQualifiedName()) {
String name = templateNode.getQualifiedName();
if (shortNames.containsKey(name)) {
String shortName = shortNames.get(name);
if (!shortName.equals(name)) {
return IR.name(shortNames.get(name));
}
}
}
for (Node child : templateNode.children()) {
clone.addChildToBack(transformNode(child, templateNodeToMatchMap, shortNames));
}
return clone;
} | java | private Node transformNode(
Node templateNode,
Map<String, Node> templateNodeToMatchMap,
Map<String, String> shortNames) {
Node clone = templateNode.cloneNode();
if (templateNode.isName()) {
String name = templateNode.getString();
if (templateNodeToMatchMap.containsKey(name)) {
Node templateMatch = templateNodeToMatchMap.get(name);
Preconditions.checkNotNull(templateMatch, "Match for %s is null", name);
if (templateNode.getParent().isVar()) {
// Var declarations should only copy the variable name from the saved match, but the rest
// of the subtree should come from the template node.
clone.setString(templateMatch.getString());
} else {
return templateMatch.cloneTree();
}
}
} else if (templateNode.isCall()
&& templateNode.getBooleanProp(Node.FREE_CALL)
&& templateNode.getFirstChild().isName()) {
String name = templateNode.getFirstChild().getString();
if (templateNodeToMatchMap.containsKey(name)) {
// If this function call matches a template parameter, don't treat it as a free call.
// This mirrors the behavior in the TemplateAstMatcher as well as ensures the code
// generator doesn't generate code like "(0,fn)()".
clone.putBooleanProp(Node.FREE_CALL, false);
}
}
if (templateNode.isQualifiedName()) {
String name = templateNode.getQualifiedName();
if (shortNames.containsKey(name)) {
String shortName = shortNames.get(name);
if (!shortName.equals(name)) {
return IR.name(shortNames.get(name));
}
}
}
for (Node child : templateNode.children()) {
clone.addChildToBack(transformNode(child, templateNodeToMatchMap, shortNames));
}
return clone;
} | [
"private",
"Node",
"transformNode",
"(",
"Node",
"templateNode",
",",
"Map",
"<",
"String",
",",
"Node",
">",
"templateNodeToMatchMap",
",",
"Map",
"<",
"String",
",",
"String",
">",
"shortNames",
")",
"{",
"Node",
"clone",
"=",
"templateNode",
".",
"cloneNode",
"(",
")",
";",
"if",
"(",
"templateNode",
".",
"isName",
"(",
")",
")",
"{",
"String",
"name",
"=",
"templateNode",
".",
"getString",
"(",
")",
";",
"if",
"(",
"templateNodeToMatchMap",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"Node",
"templateMatch",
"=",
"templateNodeToMatchMap",
".",
"get",
"(",
"name",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"templateMatch",
",",
"\"Match for %s is null\"",
",",
"name",
")",
";",
"if",
"(",
"templateNode",
".",
"getParent",
"(",
")",
".",
"isVar",
"(",
")",
")",
"{",
"// Var declarations should only copy the variable name from the saved match, but the rest",
"// of the subtree should come from the template node.",
"clone",
".",
"setString",
"(",
"templateMatch",
".",
"getString",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"templateMatch",
".",
"cloneTree",
"(",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"templateNode",
".",
"isCall",
"(",
")",
"&&",
"templateNode",
".",
"getBooleanProp",
"(",
"Node",
".",
"FREE_CALL",
")",
"&&",
"templateNode",
".",
"getFirstChild",
"(",
")",
".",
"isName",
"(",
")",
")",
"{",
"String",
"name",
"=",
"templateNode",
".",
"getFirstChild",
"(",
")",
".",
"getString",
"(",
")",
";",
"if",
"(",
"templateNodeToMatchMap",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"// If this function call matches a template parameter, don't treat it as a free call.",
"// This mirrors the behavior in the TemplateAstMatcher as well as ensures the code",
"// generator doesn't generate code like \"(0,fn)()\".",
"clone",
".",
"putBooleanProp",
"(",
"Node",
".",
"FREE_CALL",
",",
"false",
")",
";",
"}",
"}",
"if",
"(",
"templateNode",
".",
"isQualifiedName",
"(",
")",
")",
"{",
"String",
"name",
"=",
"templateNode",
".",
"getQualifiedName",
"(",
")",
";",
"if",
"(",
"shortNames",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"String",
"shortName",
"=",
"shortNames",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"!",
"shortName",
".",
"equals",
"(",
"name",
")",
")",
"{",
"return",
"IR",
".",
"name",
"(",
"shortNames",
".",
"get",
"(",
"name",
")",
")",
";",
"}",
"}",
"}",
"for",
"(",
"Node",
"child",
":",
"templateNode",
".",
"children",
"(",
")",
")",
"{",
"clone",
".",
"addChildToBack",
"(",
"transformNode",
"(",
"child",
",",
"templateNodeToMatchMap",
",",
"shortNames",
")",
")",
";",
"}",
"return",
"clone",
";",
"}"
] | Transforms the template node to a replacement node by mapping the template names to the ones
that were matched against in the JsSourceMatcher. | [
"Transforms",
"the",
"template",
"node",
"to",
"a",
"replacement",
"node",
"by",
"mapping",
"the",
"template",
"names",
"to",
"the",
"ones",
"that",
"were",
"matched",
"against",
"in",
"the",
"JsSourceMatcher",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/refactoring/RefasterJsScanner.java#L209-L251 |
23,899 | google/closure-compiler | src/com/google/javascript/rhino/jstype/RecordTypeBuilder.java | RecordTypeBuilder.build | public JSType build() {
// If we have an empty record, simply return the object type.
if (isEmpty) {
return registry.getNativeObjectType(JSTypeNative.OBJECT_TYPE);
}
ImmutableSortedMap.Builder<String, RecordProperty> m = ImmutableSortedMap.naturalOrder();
m.putAll(this.properties);
return new RecordType(registry, m.build(), isDeclared);
} | java | public JSType build() {
// If we have an empty record, simply return the object type.
if (isEmpty) {
return registry.getNativeObjectType(JSTypeNative.OBJECT_TYPE);
}
ImmutableSortedMap.Builder<String, RecordProperty> m = ImmutableSortedMap.naturalOrder();
m.putAll(this.properties);
return new RecordType(registry, m.build(), isDeclared);
} | [
"public",
"JSType",
"build",
"(",
")",
"{",
"// If we have an empty record, simply return the object type.",
"if",
"(",
"isEmpty",
")",
"{",
"return",
"registry",
".",
"getNativeObjectType",
"(",
"JSTypeNative",
".",
"OBJECT_TYPE",
")",
";",
"}",
"ImmutableSortedMap",
".",
"Builder",
"<",
"String",
",",
"RecordProperty",
">",
"m",
"=",
"ImmutableSortedMap",
".",
"naturalOrder",
"(",
")",
";",
"m",
".",
"putAll",
"(",
"this",
".",
"properties",
")",
";",
"return",
"new",
"RecordType",
"(",
"registry",
",",
"m",
".",
"build",
"(",
")",
",",
"isDeclared",
")",
";",
"}"
] | Creates a record. Fails if any duplicate property names were added.
@return The record type. | [
"Creates",
"a",
"record",
".",
"Fails",
"if",
"any",
"duplicate",
"property",
"names",
"were",
"added",
"."
] | d81e36740f6a9e8ac31a825ee8758182e1dc5aae | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/RecordTypeBuilder.java#L85-L93 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.