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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
google/closure-templates | java/src/com/google/template/soy/data/ordainers/GsonOrdainer.java | GsonOrdainer.serializeElement | public static SanitizedContent serializeElement(JsonElement element) {
// NOTE: Because JsonElement doesn't have any particular mechanism preventing random classes
// from impersonating it, this low-tech check prevents at least obvious misuse.
Preconditions.checkArgument(
element instanceof JsonArray
|| element instanceof JsonObject
|| element instanceof JsonNull
|| element instanceof JsonPrimitive);
// JsonPrimitive(String).toString() is broken, so use Gson which uses a consistent set of
// flags to produce embeddable JSON.
return ordainJson(new Gson().toJson(element));
} | java | public static SanitizedContent serializeElement(JsonElement element) {
// NOTE: Because JsonElement doesn't have any particular mechanism preventing random classes
// from impersonating it, this low-tech check prevents at least obvious misuse.
Preconditions.checkArgument(
element instanceof JsonArray
|| element instanceof JsonObject
|| element instanceof JsonNull
|| element instanceof JsonPrimitive);
// JsonPrimitive(String).toString() is broken, so use Gson which uses a consistent set of
// flags to produce embeddable JSON.
return ordainJson(new Gson().toJson(element));
} | [
"public",
"static",
"SanitizedContent",
"serializeElement",
"(",
"JsonElement",
"element",
")",
"{",
"// NOTE: Because JsonElement doesn't have any particular mechanism preventing random classes",
"// from impersonating it, this low-tech check prevents at least obvious misuse.",
"Preconditions... | Serializes a JsonElement to string.
@param element A Gson element.
@return SanitizedContent containing the object rendered as a json string. | [
"Serializes",
"a",
"JsonElement",
"to",
"string",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/ordainers/GsonOrdainer.java#L80-L91 | train |
google/closure-templates | java/src/com/google/template/soy/base/SourceLocation.java | SourceLocation.isJustBefore | public boolean isJustBefore(SourceLocation that) {
if (!this.filePath.equals(that.filePath)) {
return false;
}
return this.getEndLine() == that.getBeginLine()
&& this.getEndColumn() + 1 == that.getBeginColumn();
} | java | public boolean isJustBefore(SourceLocation that) {
if (!this.filePath.equals(that.filePath)) {
return false;
}
return this.getEndLine() == that.getBeginLine()
&& this.getEndColumn() + 1 == that.getBeginColumn();
} | [
"public",
"boolean",
"isJustBefore",
"(",
"SourceLocation",
"that",
")",
"{",
"if",
"(",
"!",
"this",
".",
"filePath",
".",
"equals",
"(",
"that",
".",
"filePath",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"this",
".",
"getEndLine",
"(",
")... | Returns true if this location ends one character before the other location starts. | [
"Returns",
"true",
"if",
"this",
"location",
"ends",
"one",
"character",
"before",
"the",
"other",
"location",
"starts",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/SourceLocation.java#L126-L133 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/CodeChunk.java | CodeChunk.getStatementsForInsertingIntoForeignCodeAtIndent | public final String getStatementsForInsertingIntoForeignCodeAtIndent(int startingIndent) {
String code = getCode(startingIndent);
return code.endsWith("\n") ? code : code + "\n";
} | java | public final String getStatementsForInsertingIntoForeignCodeAtIndent(int startingIndent) {
String code = getCode(startingIndent);
return code.endsWith("\n") ? code : code + "\n";
} | [
"public",
"final",
"String",
"getStatementsForInsertingIntoForeignCodeAtIndent",
"(",
"int",
"startingIndent",
")",
"{",
"String",
"code",
"=",
"getCode",
"(",
"startingIndent",
")",
";",
"return",
"code",
".",
"endsWith",
"(",
"\"\\n\"",
")",
"?",
"code",
":",
... | Returns a sequence of JavaScript statements suitable for inserting into JS code that is not
managed by the CodeChunk DSL. The string is guaranteed to end in a newline.
<p>Callers should use {@link #getCode()} when the CodeChunk DSL is managing the entire code
generation. getCode may drop variable declarations if there is no other code referencing those
variables.
<p>By contrast, this method is provided for incremental migration to the CodeChunk DSL.
Variable declarations will not be dropped, since there may be gencode not managed by the
CodeChunk DSL that references them.
<p>TODO(b/33382980): remove.
@param startingIndent The indent level of the foreign code into which this code will be
inserted. This doesn't affect the correctness of the composed code, only its readability. | [
"Returns",
"a",
"sequence",
"of",
"JavaScript",
"statements",
"suitable",
"for",
"inserting",
"into",
"JS",
"code",
"that",
"is",
"not",
"managed",
"by",
"the",
"CodeChunk",
"DSL",
".",
"The",
"string",
"is",
"guaranteed",
"to",
"end",
"in",
"a",
"newline",
... | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/CodeChunk.java#L141-L144 | train |
google/closure-templates | java/src/com/google/template/soy/passes/htmlmatcher/HtmlMatcherGraph.java | HtmlMatcherGraph.addNode | public void addNode(HtmlMatcherGraphNode node) {
checkNotNull(node);
if (graphCursor.isPresent()) {
graphCursor.get().linkActiveEdgeToNode(node);
}
setGraphCursorNode(node);
} | java | public void addNode(HtmlMatcherGraphNode node) {
checkNotNull(node);
if (graphCursor.isPresent()) {
graphCursor.get().linkActiveEdgeToNode(node);
}
setGraphCursorNode(node);
} | [
"public",
"void",
"addNode",
"(",
"HtmlMatcherGraphNode",
"node",
")",
"{",
"checkNotNull",
"(",
"node",
")",
";",
"if",
"(",
"graphCursor",
".",
"isPresent",
"(",
")",
")",
"{",
"graphCursor",
".",
"get",
"(",
")",
".",
"linkActiveEdgeToNode",
"(",
"node"... | Attaches a new HTML tag node to the graph at the current cursor position.
@param node the node to add | [
"Attaches",
"a",
"new",
"HTML",
"tag",
"node",
"to",
"the",
"graph",
"at",
"the",
"current",
"cursor",
"position",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/htmlmatcher/HtmlMatcherGraph.java#L74-L80 | train |
google/closure-templates | java/src/com/google/template/soy/examples/SimpleUsage.java | SimpleUsage.main | public static void main(String[] args) {
// Compile the template.
SoyFileSet sfs = SoyFileSet.builder().add(Resources.getResource("simple.soy")).build();
SoyTofu tofu = sfs.compileToTofu();
// Example 1.
writeExampleHeader();
System.out.println(tofu.newRenderer("soy.examples.simple.helloWorld").render());
// Create a namespaced tofu object to make calls more concise.
SoyTofu simpleTofu = tofu.forNamespace("soy.examples.simple");
// Example 2.
writeExampleHeader();
System.out.println(
simpleTofu.newRenderer(".helloName").setData(ImmutableMap.of("name", "Ana")).render());
// Example 3.
writeExampleHeader();
System.out.println(
simpleTofu
.newRenderer(".helloNames")
.setData(ImmutableMap.of("names", ImmutableList.of("Bob", "Cid", "Dee")))
.render());
} | java | public static void main(String[] args) {
// Compile the template.
SoyFileSet sfs = SoyFileSet.builder().add(Resources.getResource("simple.soy")).build();
SoyTofu tofu = sfs.compileToTofu();
// Example 1.
writeExampleHeader();
System.out.println(tofu.newRenderer("soy.examples.simple.helloWorld").render());
// Create a namespaced tofu object to make calls more concise.
SoyTofu simpleTofu = tofu.forNamespace("soy.examples.simple");
// Example 2.
writeExampleHeader();
System.out.println(
simpleTofu.newRenderer(".helloName").setData(ImmutableMap.of("name", "Ana")).render());
// Example 3.
writeExampleHeader();
System.out.println(
simpleTofu
.newRenderer(".helloNames")
.setData(ImmutableMap.of("names", ImmutableList.of("Bob", "Cid", "Dee")))
.render());
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"// Compile the template.",
"SoyFileSet",
"sfs",
"=",
"SoyFileSet",
".",
"builder",
"(",
")",
".",
"add",
"(",
"Resources",
".",
"getResource",
"(",
"\"simple.soy\"",
")",
")",
... | Prints the generated HTML to stdout.
@param args Not used. | [
"Prints",
"the",
"generated",
"HTML",
"to",
"stdout",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/examples/SimpleUsage.java#L41-L66 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/TemplateDelegateNode.java | TemplateDelegateNode.resolveVariantExpression | private DelTemplateKey resolveVariantExpression() {
if (delTemplateVariantExpr == null) {
delTemplateKey = DelTemplateKey.create(delTemplateName, "");
return delTemplateKey;
}
ExprNode exprNode = delTemplateVariantExpr.getRoot();
if (exprNode instanceof GlobalNode) {
GlobalNode globalNode = (GlobalNode) exprNode;
if (globalNode.isResolved()) {
exprNode = globalNode.getValue();
} else {
// This global was not substituted. This happens when TemplateRegistries are built for
// message extraction and parseinfo generation. To make this 'work' we just use the Global
// name for the variant value. This is fine and will help catch some errors.
// Because these nodes won't be used for code generation this should be safe.
// For this reason we also don't store the key, instead we just return it.
return DelTemplateKey.create(delTemplateName, globalNode.getName());
}
}
if (exprNode instanceof IntegerNode) {
// Globals were already substituted: We may now create the definitive variant and key fields
// on this node.
long variantValue = ((IntegerNode) exprNode).getValue();
delTemplateKey = DelTemplateKey.create(delTemplateName, String.valueOf(variantValue));
} else if (exprNode instanceof StringNode) {
// Globals were already substituted: We may now create the definitive variant and key fields
// on this node.
delTemplateKey = DelTemplateKey.create(delTemplateName, ((StringNode) exprNode).getValue());
} else {
// We must have already reported an error, just create an arbitrary variant expr.
delTemplateKey = DelTemplateKey.create(delTemplateName, exprNode.toSourceString());
}
return delTemplateKey;
} | java | private DelTemplateKey resolveVariantExpression() {
if (delTemplateVariantExpr == null) {
delTemplateKey = DelTemplateKey.create(delTemplateName, "");
return delTemplateKey;
}
ExprNode exprNode = delTemplateVariantExpr.getRoot();
if (exprNode instanceof GlobalNode) {
GlobalNode globalNode = (GlobalNode) exprNode;
if (globalNode.isResolved()) {
exprNode = globalNode.getValue();
} else {
// This global was not substituted. This happens when TemplateRegistries are built for
// message extraction and parseinfo generation. To make this 'work' we just use the Global
// name for the variant value. This is fine and will help catch some errors.
// Because these nodes won't be used for code generation this should be safe.
// For this reason we also don't store the key, instead we just return it.
return DelTemplateKey.create(delTemplateName, globalNode.getName());
}
}
if (exprNode instanceof IntegerNode) {
// Globals were already substituted: We may now create the definitive variant and key fields
// on this node.
long variantValue = ((IntegerNode) exprNode).getValue();
delTemplateKey = DelTemplateKey.create(delTemplateName, String.valueOf(variantValue));
} else if (exprNode instanceof StringNode) {
// Globals were already substituted: We may now create the definitive variant and key fields
// on this node.
delTemplateKey = DelTemplateKey.create(delTemplateName, ((StringNode) exprNode).getValue());
} else {
// We must have already reported an error, just create an arbitrary variant expr.
delTemplateKey = DelTemplateKey.create(delTemplateName, exprNode.toSourceString());
}
return delTemplateKey;
} | [
"private",
"DelTemplateKey",
"resolveVariantExpression",
"(",
")",
"{",
"if",
"(",
"delTemplateVariantExpr",
"==",
"null",
")",
"{",
"delTemplateKey",
"=",
"DelTemplateKey",
".",
"create",
"(",
"delTemplateName",
",",
"\"\"",
")",
";",
"return",
"delTemplateKey",
... | Calculate a DeltemplateKey for the variant.
<p>This is done lazily so that global references can be resolved. This is not ideal since
nothing guarantees that resolution happens before access.
<p>Note we don't do validation of the variant values since that is handled by the
TemplateDelegateNodeBuilder during construction | [
"Calculate",
"a",
"DeltemplateKey",
"for",
"the",
"variant",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/TemplateDelegateNode.java#L175-L208 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/NamespaceDeclaration.java | NamespaceDeclaration.toSourceString | public String toSourceString() {
return "{namespace "
+ namespace.identifier()
+ (attrs.isEmpty() ? "" : " " + Joiner.on(' ').join(attrs))
+ "}\n";
} | java | public String toSourceString() {
return "{namespace "
+ namespace.identifier()
+ (attrs.isEmpty() ? "" : " " + Joiner.on(' ').join(attrs))
+ "}\n";
} | [
"public",
"String",
"toSourceString",
"(",
")",
"{",
"return",
"\"{namespace \"",
"+",
"namespace",
".",
"identifier",
"(",
")",
"+",
"(",
"attrs",
".",
"isEmpty",
"(",
")",
"?",
"\"\"",
":",
"\" \"",
"+",
"Joiner",
".",
"on",
"(",
"'",
"'",
")",
"."... | Returns an approximation of what the original source for this namespace looked like. | [
"Returns",
"an",
"approximation",
"of",
"what",
"the",
"original",
"source",
"for",
"this",
"namespace",
"looked",
"like",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/NamespaceDeclaration.java#L81-L86 | train |
google/closure-templates | java/src/com/google/template/soy/data/internalutils/NodeContentKinds.java | NodeContentKinds.toJsUnpackFunction | public static String toJsUnpackFunction(Descriptor protoDescriptor) {
return Preconditions.checkNotNull(PROTO_TO_JS_UNPACK_FN.get(protoDescriptor.getFullName()));
} | java | public static String toJsUnpackFunction(Descriptor protoDescriptor) {
return Preconditions.checkNotNull(PROTO_TO_JS_UNPACK_FN.get(protoDescriptor.getFullName()));
} | [
"public",
"static",
"String",
"toJsUnpackFunction",
"(",
"Descriptor",
"protoDescriptor",
")",
"{",
"return",
"Preconditions",
".",
"checkNotNull",
"(",
"PROTO_TO_JS_UNPACK_FN",
".",
"get",
"(",
"protoDescriptor",
".",
"getFullName",
"(",
")",
")",
")",
";",
"}"
] | Returns the unpack function for converting safe protos to JS SanitizedContent. | [
"Returns",
"the",
"unpack",
"function",
"for",
"converting",
"safe",
"protos",
"to",
"JS",
"SanitizedContent",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/internalutils/NodeContentKinds.java#L223-L225 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/MsgHtmlTagNode.java | MsgHtmlTagNode.getFullTagText | @Nullable
private static String getFullTagText(HtmlTagNode openTagNode) {
class Visitor implements NodeVisitor<Node, VisitDirective> {
boolean isConstantContent = true;
@Override
public VisitDirective exec(Node node) {
if (node instanceof RawTextNode
|| node instanceof HtmlAttributeNode
|| node instanceof HtmlAttributeValueNode
|| node instanceof HtmlOpenTagNode
|| node instanceof HtmlCloseTagNode) {
return VisitDirective.CONTINUE;
}
isConstantContent = false;
return VisitDirective.ABORT;
}
}
Visitor visitor = new Visitor();
SoyTreeUtils.visitAllNodes(openTagNode, visitor);
if (visitor.isConstantContent) {
// toSourceString is lame, but how this worked before
return openTagNode.toSourceString();
}
return null;
} | java | @Nullable
private static String getFullTagText(HtmlTagNode openTagNode) {
class Visitor implements NodeVisitor<Node, VisitDirective> {
boolean isConstantContent = true;
@Override
public VisitDirective exec(Node node) {
if (node instanceof RawTextNode
|| node instanceof HtmlAttributeNode
|| node instanceof HtmlAttributeValueNode
|| node instanceof HtmlOpenTagNode
|| node instanceof HtmlCloseTagNode) {
return VisitDirective.CONTINUE;
}
isConstantContent = false;
return VisitDirective.ABORT;
}
}
Visitor visitor = new Visitor();
SoyTreeUtils.visitAllNodes(openTagNode, visitor);
if (visitor.isConstantContent) {
// toSourceString is lame, but how this worked before
return openTagNode.toSourceString();
}
return null;
} | [
"@",
"Nullable",
"private",
"static",
"String",
"getFullTagText",
"(",
"HtmlTagNode",
"openTagNode",
")",
"{",
"class",
"Visitor",
"implements",
"NodeVisitor",
"<",
"Node",
",",
"VisitDirective",
">",
"{",
"boolean",
"isConstantContent",
"=",
"true",
";",
"@",
"... | This method calculates a string that can be used to tell if two tags that were turned into
placeholders are equivalent and thus could be turned into identical placeholders.
<p>In theory we should use something like {@link ExprEquivalence} to see if two nodes would
render the same thing. However, for backwards compatibility we need to use a different
heuristic. The old code would simply detect if the node had a single child and use the {@link
SoyNode#toSourceString()} of it for the tag text. Due to how the children were constructed,
this would only happen if the tag was a single {@link RawTextNode}, e.g. {@code <foo
class=bar>}. Now that we are actually parsing the html tags the rules are more complex. We
should instead only use the {@link SoyNode#toSourceString()} if the only (transitive) children
are {@link RawTextNode}, {@link HtmlAttributeNode} or {@link HtmlAttributeValueNode}. | [
"This",
"method",
"calculates",
"a",
"string",
"that",
"can",
"be",
"used",
"to",
"tell",
"if",
"two",
"tags",
"that",
"were",
"turned",
"into",
"placeholders",
"are",
"equivalent",
"and",
"thus",
"could",
"be",
"turned",
"into",
"identical",
"placeholders",
... | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/MsgHtmlTagNode.java#L113-L138 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/SoyJsPluginUtils.java | SoyJsPluginUtils.genJsExprUsingSoySyntax | public static JsExpr genJsExprUsingSoySyntax(Operator op, List<JsExpr> operandJsExprs) {
List<Expression> operands =
Lists.transform(operandJsExprs, input -> fromExpr(input, ImmutableList.<GoogRequire>of()));
return Expression.operation(op, operands).assertExpr();
} | java | public static JsExpr genJsExprUsingSoySyntax(Operator op, List<JsExpr> operandJsExprs) {
List<Expression> operands =
Lists.transform(operandJsExprs, input -> fromExpr(input, ImmutableList.<GoogRequire>of()));
return Expression.operation(op, operands).assertExpr();
} | [
"public",
"static",
"JsExpr",
"genJsExprUsingSoySyntax",
"(",
"Operator",
"op",
",",
"List",
"<",
"JsExpr",
">",
"operandJsExprs",
")",
"{",
"List",
"<",
"Expression",
">",
"operands",
"=",
"Lists",
".",
"transform",
"(",
"operandJsExprs",
",",
"input",
"->",
... | Generates a JS expression for the given operator and operands. | [
"Generates",
"a",
"JS",
"expression",
"for",
"the",
"given",
"operator",
"and",
"operands",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/SoyJsPluginUtils.java#L57-L61 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/SoyRuntimeType.java | SoyRuntimeType.protoType | public static Type protoType(Descriptor descriptor) {
return Type.getType('L' + JavaQualifiedNames.getClassName(descriptor).replace('.', '/') + ';');
} | java | public static Type protoType(Descriptor descriptor) {
return Type.getType('L' + JavaQualifiedNames.getClassName(descriptor).replace('.', '/') + ';');
} | [
"public",
"static",
"Type",
"protoType",
"(",
"Descriptor",
"descriptor",
")",
"{",
"return",
"Type",
".",
"getType",
"(",
"'",
"'",
"+",
"JavaQualifiedNames",
".",
"getClassName",
"(",
"descriptor",
")",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")"... | Returns the runtime type for the message correspdoning to the given descriptor.. | [
"Returns",
"the",
"runtime",
"type",
"for",
"the",
"message",
"correspdoning",
"to",
"the",
"given",
"descriptor",
".."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/SoyRuntimeType.java#L255-L257 | train |
google/closure-templates | java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java | BasicFunctionsRuntime.concatLists | public static List<SoyValueProvider> concatLists(List<SoyList> args) {
ImmutableList.Builder<SoyValueProvider> flattened = ImmutableList.builder();
for (SoyList soyList : args) {
flattened.addAll(soyList.asJavaList());
}
return flattened.build();
} | java | public static List<SoyValueProvider> concatLists(List<SoyList> args) {
ImmutableList.Builder<SoyValueProvider> flattened = ImmutableList.builder();
for (SoyList soyList : args) {
flattened.addAll(soyList.asJavaList());
}
return flattened.build();
} | [
"public",
"static",
"List",
"<",
"SoyValueProvider",
">",
"concatLists",
"(",
"List",
"<",
"SoyList",
">",
"args",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"SoyValueProvider",
">",
"flattened",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"for... | Concatenates its arguments. | [
"Concatenates",
"its",
"arguments",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java#L71-L77 | train |
google/closure-templates | java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java | BasicFunctionsRuntime.join | public static String join(SoyList list, String separator) {
List<String> stringList = new ArrayList<>();
for (SoyValue value : list.asResolvedJavaList()) {
stringList.add(value.coerceToString());
}
return Joiner.on(separator).join(stringList);
} | java | public static String join(SoyList list, String separator) {
List<String> stringList = new ArrayList<>();
for (SoyValue value : list.asResolvedJavaList()) {
stringList.add(value.coerceToString());
}
return Joiner.on(separator).join(stringList);
} | [
"public",
"static",
"String",
"join",
"(",
"SoyList",
"list",
",",
"String",
"separator",
")",
"{",
"List",
"<",
"String",
">",
"stringList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"SoyValue",
"value",
":",
"list",
".",
"asResolvedJava... | Joins the list elements by a separator. | [
"Joins",
"the",
"list",
"elements",
"by",
"a",
"separator",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java#L85-L91 | train |
google/closure-templates | java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java | BasicFunctionsRuntime.keys | public static List<SoyValue> keys(SoyValue sv) {
SoyLegacyObjectMap map = (SoyLegacyObjectMap) sv;
List<SoyValue> list = new ArrayList<>(map.getItemCnt());
Iterables.addAll(list, map.getItemKeys());
return list;
} | java | public static List<SoyValue> keys(SoyValue sv) {
SoyLegacyObjectMap map = (SoyLegacyObjectMap) sv;
List<SoyValue> list = new ArrayList<>(map.getItemCnt());
Iterables.addAll(list, map.getItemKeys());
return list;
} | [
"public",
"static",
"List",
"<",
"SoyValue",
">",
"keys",
"(",
"SoyValue",
"sv",
")",
"{",
"SoyLegacyObjectMap",
"map",
"=",
"(",
"SoyLegacyObjectMap",
")",
"sv",
";",
"List",
"<",
"SoyValue",
">",
"list",
"=",
"new",
"ArrayList",
"<>",
"(",
"map",
".",
... | Returns a list of all the keys in the given map. For the JavaSource variant, while the function
signature is ? instead of legacy_object_map. | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"keys",
"in",
"the",
"given",
"map",
".",
"For",
"the",
"JavaSource",
"variant",
"while",
"the",
"function",
"signature",
"is",
"?",
"instead",
"of",
"legacy_object_map",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java#L109-L114 | train |
google/closure-templates | java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java | BasicFunctionsRuntime.max | public static NumberData max(SoyValue arg0, SoyValue arg1) {
if (arg0 instanceof IntegerData && arg1 instanceof IntegerData) {
return IntegerData.forValue(Math.max(arg0.longValue(), arg1.longValue()));
} else {
return FloatData.forValue(Math.max(arg0.numberValue(), arg1.numberValue()));
}
} | java | public static NumberData max(SoyValue arg0, SoyValue arg1) {
if (arg0 instanceof IntegerData && arg1 instanceof IntegerData) {
return IntegerData.forValue(Math.max(arg0.longValue(), arg1.longValue()));
} else {
return FloatData.forValue(Math.max(arg0.numberValue(), arg1.numberValue()));
}
} | [
"public",
"static",
"NumberData",
"max",
"(",
"SoyValue",
"arg0",
",",
"SoyValue",
"arg1",
")",
"{",
"if",
"(",
"arg0",
"instanceof",
"IntegerData",
"&&",
"arg1",
"instanceof",
"IntegerData",
")",
"{",
"return",
"IntegerData",
".",
"forValue",
"(",
"Math",
"... | Returns the numeric maximum of the two arguments. | [
"Returns",
"the",
"numeric",
"maximum",
"of",
"the",
"two",
"arguments",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java#L132-L138 | train |
google/closure-templates | java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java | BasicFunctionsRuntime.round | public static long round(SoyValue value) {
if (value instanceof IntegerData) {
return value.longValue();
} else {
return Math.round(value.numberValue());
}
} | java | public static long round(SoyValue value) {
if (value instanceof IntegerData) {
return value.longValue();
} else {
return Math.round(value.numberValue());
}
} | [
"public",
"static",
"long",
"round",
"(",
"SoyValue",
"value",
")",
"{",
"if",
"(",
"value",
"instanceof",
"IntegerData",
")",
"{",
"return",
"value",
".",
"longValue",
"(",
")",
";",
"}",
"else",
"{",
"return",
"Math",
".",
"round",
"(",
"value",
".",... | Rounds the given value to the closest integer. | [
"Rounds",
"the",
"given",
"value",
"to",
"the",
"closest",
"integer",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basicfunctions/BasicFunctionsRuntime.java#L184-L190 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/CallDelegateNode.java | CallDelegateNode.setParamsToRuntimeCheck | public void setParamsToRuntimeCheck(
ImmutableMap<String, Predicate<String>> paramsToRuntimeCheck) {
checkState(this.paramsToRuntimeCheckByDelegate == null);
this.paramsToRuntimeCheckByDelegate = checkNotNull(paramsToRuntimeCheck);
} | java | public void setParamsToRuntimeCheck(
ImmutableMap<String, Predicate<String>> paramsToRuntimeCheck) {
checkState(this.paramsToRuntimeCheckByDelegate == null);
this.paramsToRuntimeCheckByDelegate = checkNotNull(paramsToRuntimeCheck);
} | [
"public",
"void",
"setParamsToRuntimeCheck",
"(",
"ImmutableMap",
"<",
"String",
",",
"Predicate",
"<",
"String",
">",
">",
"paramsToRuntimeCheck",
")",
"{",
"checkState",
"(",
"this",
".",
"paramsToRuntimeCheckByDelegate",
"==",
"null",
")",
";",
"this",
".",
"... | Sets the params that require runtime type checking for each possible delegate target.
<p>This mechanism is used by the TOFU runtime only to save some work when calling templates. | [
"Sets",
"the",
"params",
"that",
"require",
"runtime",
"type",
"checking",
"for",
"each",
"possible",
"delegate",
"target",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/CallDelegateNode.java#L176-L180 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/ExpressionCompiler.java | ExpressionCompiler.createBasicCompiler | static BasicExpressionCompiler createBasicCompiler(
TemplateParameterLookup parameters,
TemplateVariableManager varManager,
ErrorReporter reporter,
SoyTypeRegistry registry) {
return new BasicExpressionCompiler(parameters, varManager, reporter, registry);
} | java | static BasicExpressionCompiler createBasicCompiler(
TemplateParameterLookup parameters,
TemplateVariableManager varManager,
ErrorReporter reporter,
SoyTypeRegistry registry) {
return new BasicExpressionCompiler(parameters, varManager, reporter, registry);
} | [
"static",
"BasicExpressionCompiler",
"createBasicCompiler",
"(",
"TemplateParameterLookup",
"parameters",
",",
"TemplateVariableManager",
"varManager",
",",
"ErrorReporter",
"reporter",
",",
"SoyTypeRegistry",
"registry",
")",
"{",
"return",
"new",
"BasicExpressionCompiler",
... | Create a basic compiler with trivial detaching logic.
<p>All generated detach points are implemented as {@code return} statements and the returned
value is boxed, so it is only valid for use by the {@link LazyClosureCompiler}. | [
"Create",
"a",
"basic",
"compiler",
"with",
"trivial",
"detaching",
"logic",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/ExpressionCompiler.java#L190-L196 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/ExpressionCompiler.java | ExpressionCompiler.compile | SoyExpression compile(ExprNode node, Label reattachPoint) {
return asBasicCompiler(reattachPoint).compile(node);
} | java | SoyExpression compile(ExprNode node, Label reattachPoint) {
return asBasicCompiler(reattachPoint).compile(node);
} | [
"SoyExpression",
"compile",
"(",
"ExprNode",
"node",
",",
"Label",
"reattachPoint",
")",
"{",
"return",
"asBasicCompiler",
"(",
"reattachPoint",
")",
".",
"compile",
"(",
"node",
")",
";",
"}"
] | Compiles the given expression tree to a sequence of bytecode.
<p>The reattachPoint should be {@link CodeBuilder#mark(Label) marked} by the caller at a
location where the stack depth is 0 and will be used to 'reattach' execution if the compiled
expression needs to perform a detach operation. | [
"Compiles",
"the",
"given",
"expression",
"tree",
"to",
"a",
"sequence",
"of",
"bytecode",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/ExpressionCompiler.java#L224-L226 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/ExpressionCompiler.java | ExpressionCompiler.compileWithNoDetaches | Optional<SoyExpression> compileWithNoDetaches(ExprNode node) {
checkNotNull(node);
if (RequiresDetachVisitor.INSTANCE.exec(node)) {
return Optional.absent();
}
Supplier<ExpressionDetacher> throwingSupplier =
() -> {
throw new AssertionError();
};
return Optional.of(
new CompilerVisitor(parameters, varManager, throwingSupplier, reporter, registry)
.exec(node));
} | java | Optional<SoyExpression> compileWithNoDetaches(ExprNode node) {
checkNotNull(node);
if (RequiresDetachVisitor.INSTANCE.exec(node)) {
return Optional.absent();
}
Supplier<ExpressionDetacher> throwingSupplier =
() -> {
throw new AssertionError();
};
return Optional.of(
new CompilerVisitor(parameters, varManager, throwingSupplier, reporter, registry)
.exec(node));
} | [
"Optional",
"<",
"SoyExpression",
">",
"compileWithNoDetaches",
"(",
"ExprNode",
"node",
")",
"{",
"checkNotNull",
"(",
"node",
")",
";",
"if",
"(",
"RequiresDetachVisitor",
".",
"INSTANCE",
".",
"exec",
"(",
"node",
")",
")",
"{",
"return",
"Optional",
".",... | Compiles the given expression tree to a sequence of bytecode if it can be done without
generating any detach operations. | [
"Compiles",
"the",
"given",
"expression",
"tree",
"to",
"a",
"sequence",
"of",
"bytecode",
"if",
"it",
"can",
"be",
"done",
"without",
"generating",
"any",
"detach",
"operations",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/ExpressionCompiler.java#L245-L257 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/GenPyExprsVisitor.java | GenPyExprsVisitor.visitPrintNode | @Override
protected void visitPrintNode(PrintNode node) {
TranslateToPyExprVisitor translator =
new TranslateToPyExprVisitor(localVarExprs, pluginValueFactory, errorReporter);
PyExpr pyExpr = translator.exec(node.getExpr());
// Process directives.
for (PrintDirectiveNode directiveNode : node.getChildren()) {
// Get directive.
SoyPrintDirective directive = directiveNode.getPrintDirective();
if (!(directive instanceof SoyPySrcPrintDirective)) {
errorReporter.report(
directiveNode.getSourceLocation(),
UNKNOWN_SOY_PY_SRC_PRINT_DIRECTIVE,
directiveNode.getName());
continue;
}
// Get directive args.
List<ExprRootNode> args = directiveNode.getArgs();
// Translate directive args.
List<PyExpr> argsPyExprs = new ArrayList<>(args.size());
for (ExprRootNode arg : args) {
argsPyExprs.add(translator.exec(arg));
}
// Apply directive.
pyExpr = ((SoyPySrcPrintDirective) directive).applyForPySrc(pyExpr, argsPyExprs);
}
pyExprs.add(pyExpr);
} | java | @Override
protected void visitPrintNode(PrintNode node) {
TranslateToPyExprVisitor translator =
new TranslateToPyExprVisitor(localVarExprs, pluginValueFactory, errorReporter);
PyExpr pyExpr = translator.exec(node.getExpr());
// Process directives.
for (PrintDirectiveNode directiveNode : node.getChildren()) {
// Get directive.
SoyPrintDirective directive = directiveNode.getPrintDirective();
if (!(directive instanceof SoyPySrcPrintDirective)) {
errorReporter.report(
directiveNode.getSourceLocation(),
UNKNOWN_SOY_PY_SRC_PRINT_DIRECTIVE,
directiveNode.getName());
continue;
}
// Get directive args.
List<ExprRootNode> args = directiveNode.getArgs();
// Translate directive args.
List<PyExpr> argsPyExprs = new ArrayList<>(args.size());
for (ExprRootNode arg : args) {
argsPyExprs.add(translator.exec(arg));
}
// Apply directive.
pyExpr = ((SoyPySrcPrintDirective) directive).applyForPySrc(pyExpr, argsPyExprs);
}
pyExprs.add(pyExpr);
} | [
"@",
"Override",
"protected",
"void",
"visitPrintNode",
"(",
"PrintNode",
"node",
")",
"{",
"TranslateToPyExprVisitor",
"translator",
"=",
"new",
"TranslateToPyExprVisitor",
"(",
"localVarExprs",
",",
"pluginValueFactory",
",",
"errorReporter",
")",
";",
"PyExpr",
"py... | Visiting a print node accomplishes 3 basic tasks. It loads data, it performs any operations
needed, and it executes the appropriate print directives.
<p>TODO(dcphillips): Add support for local variables once LetNode are supported.
<p>Example:
<pre>
{$boo |changeNewlineToBr}
{$goo + 5}
</pre>
might generate
<pre>
sanitize.change_newline_to_br(data.get('boo'))
data.get('goo') + 5
</pre> | [
"Visiting",
"a",
"print",
"node",
"accomplishes",
"3",
"basic",
"tasks",
".",
"It",
"loads",
"data",
"it",
"performs",
"any",
"operations",
"needed",
"and",
"it",
"executes",
"the",
"appropriate",
"print",
"directives",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/GenPyExprsVisitor.java#L180-L213 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/GenPyExprsVisitor.java | GenPyExprsVisitor.visitIfNode | @Override
protected void visitIfNode(IfNode node) {
// Create another instance of this visitor for generating Python expressions from children.
GenPyExprsVisitor genPyExprsVisitor =
genPyExprsVisitorFactory.create(localVarExprs, errorReporter);
TranslateToPyExprVisitor translator =
new TranslateToPyExprVisitor(localVarExprs, pluginValueFactory, errorReporter);
StringBuilder pyExprTextSb = new StringBuilder();
boolean hasElse = false;
// We need to be careful about parenthesizing the sub-expressions in a python ternary operator,
// as nested ternary operators will right-associate. Due to the structure of the parse tree,
// we accumulate open parens in the loop below, and pendingParens tracks how many closing parens
// we need to add at the end.
int pendingParens = 0;
for (SoyNode child : node.getChildren()) {
if (child instanceof IfCondNode) {
IfCondNode icn = (IfCondNode) child;
// Python ternary conditional expressions modify the order of the conditional from
// <conditional> ? <true> : <false> to
// <true> if <conditional> else <false>
PyExpr condBlock = PyExprUtils.concatPyExprs(genPyExprsVisitor.exec(icn)).toPyString();
condBlock =
PyExprUtils.maybeProtect(
condBlock, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL));
pyExprTextSb.append("(").append(condBlock.getText());
// Append the conditional and if/else syntax.
PyExpr condPyExpr = translator.exec(icn.getExpr());
pyExprTextSb.append(") if (").append(condPyExpr.getText()).append(") else (");
pendingParens++;
} else if (child instanceof IfElseNode) {
hasElse = true;
IfElseNode ien = (IfElseNode) child;
PyExpr elseBlock = PyExprUtils.concatPyExprs(genPyExprsVisitor.exec(ien)).toPyString();
pyExprTextSb.append(elseBlock.getText()).append(")");
pendingParens--;
} else {
throw new AssertionError("Unexpected if child node type. Child: " + child);
}
}
if (!hasElse) {
pyExprTextSb.append("''");
}
for (int i = 0; i < pendingParens; i++) {
pyExprTextSb.append(")");
}
// By their nature, inline'd conditionals can only contain output strings, so they can be
// treated as a string type with a conditional precedence.
pyExprs.add(
new PyStringExpr(
pyExprTextSb.toString(), PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL)));
} | java | @Override
protected void visitIfNode(IfNode node) {
// Create another instance of this visitor for generating Python expressions from children.
GenPyExprsVisitor genPyExprsVisitor =
genPyExprsVisitorFactory.create(localVarExprs, errorReporter);
TranslateToPyExprVisitor translator =
new TranslateToPyExprVisitor(localVarExprs, pluginValueFactory, errorReporter);
StringBuilder pyExprTextSb = new StringBuilder();
boolean hasElse = false;
// We need to be careful about parenthesizing the sub-expressions in a python ternary operator,
// as nested ternary operators will right-associate. Due to the structure of the parse tree,
// we accumulate open parens in the loop below, and pendingParens tracks how many closing parens
// we need to add at the end.
int pendingParens = 0;
for (SoyNode child : node.getChildren()) {
if (child instanceof IfCondNode) {
IfCondNode icn = (IfCondNode) child;
// Python ternary conditional expressions modify the order of the conditional from
// <conditional> ? <true> : <false> to
// <true> if <conditional> else <false>
PyExpr condBlock = PyExprUtils.concatPyExprs(genPyExprsVisitor.exec(icn)).toPyString();
condBlock =
PyExprUtils.maybeProtect(
condBlock, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL));
pyExprTextSb.append("(").append(condBlock.getText());
// Append the conditional and if/else syntax.
PyExpr condPyExpr = translator.exec(icn.getExpr());
pyExprTextSb.append(") if (").append(condPyExpr.getText()).append(") else (");
pendingParens++;
} else if (child instanceof IfElseNode) {
hasElse = true;
IfElseNode ien = (IfElseNode) child;
PyExpr elseBlock = PyExprUtils.concatPyExprs(genPyExprsVisitor.exec(ien)).toPyString();
pyExprTextSb.append(elseBlock.getText()).append(")");
pendingParens--;
} else {
throw new AssertionError("Unexpected if child node type. Child: " + child);
}
}
if (!hasElse) {
pyExprTextSb.append("''");
}
for (int i = 0; i < pendingParens; i++) {
pyExprTextSb.append(")");
}
// By their nature, inline'd conditionals can only contain output strings, so they can be
// treated as a string type with a conditional precedence.
pyExprs.add(
new PyStringExpr(
pyExprTextSb.toString(), PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL)));
} | [
"@",
"Override",
"protected",
"void",
"visitIfNode",
"(",
"IfNode",
"node",
")",
"{",
"// Create another instance of this visitor for generating Python expressions from children.",
"GenPyExprsVisitor",
"genPyExprsVisitor",
"=",
"genPyExprsVisitorFactory",
".",
"create",
"(",
"loc... | If all the children are computable as expressions, the IfNode can be written as a ternary
conditional expression. | [
"If",
"all",
"the",
"children",
"are",
"computable",
"as",
"expressions",
"the",
"IfNode",
"can",
"be",
"written",
"as",
"a",
"ternary",
"conditional",
"expression",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/GenPyExprsVisitor.java#L269-L328 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/HtmlTagNode.java | HtmlTagNode.getDirectAttributeNamed | @Nullable
public HtmlAttributeNode getDirectAttributeNamed(String attrName) {
// the child at index 0 is the tag name
for (int i = 1; i < numChildren(); i++) {
StandaloneNode child = getChild(i);
if (child instanceof HtmlAttributeNode) {
HtmlAttributeNode attr = (HtmlAttributeNode) child;
if (attr.definitelyMatchesAttributeName(attrName)) {
return attr;
}
}
}
return null;
} | java | @Nullable
public HtmlAttributeNode getDirectAttributeNamed(String attrName) {
// the child at index 0 is the tag name
for (int i = 1; i < numChildren(); i++) {
StandaloneNode child = getChild(i);
if (child instanceof HtmlAttributeNode) {
HtmlAttributeNode attr = (HtmlAttributeNode) child;
if (attr.definitelyMatchesAttributeName(attrName)) {
return attr;
}
}
}
return null;
} | [
"@",
"Nullable",
"public",
"HtmlAttributeNode",
"getDirectAttributeNamed",
"(",
"String",
"attrName",
")",
"{",
"// the child at index 0 is the tag name",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"numChildren",
"(",
")",
";",
"i",
"++",
")",
"{",
"Stan... | Returns an attribute with the given static name if it is a direct child. | [
"Returns",
"an",
"attribute",
"with",
"the",
"given",
"static",
"name",
"if",
"it",
"is",
"a",
"direct",
"child",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/HtmlTagNode.java#L128-L141 | train |
google/closure-templates | java/src/com/google/template/soy/data/SoyValueConverter.java | SoyValueConverter.newListFromIterable | private SoyList newListFromIterable(Iterable<?> items) {
// Create a list backed by a Java list which has eagerly converted each value into a lazy
// value provider. Specifically, the list iteration is done eagerly so that the lazy value
// provider can cache its value.
ImmutableList.Builder<SoyValueProvider> builder = ImmutableList.builder();
for (Object item : items) {
builder.add(convertLazy(item));
}
return ListImpl.forProviderList(builder.build());
} | java | private SoyList newListFromIterable(Iterable<?> items) {
// Create a list backed by a Java list which has eagerly converted each value into a lazy
// value provider. Specifically, the list iteration is done eagerly so that the lazy value
// provider can cache its value.
ImmutableList.Builder<SoyValueProvider> builder = ImmutableList.builder();
for (Object item : items) {
builder.add(convertLazy(item));
}
return ListImpl.forProviderList(builder.build());
} | [
"private",
"SoyList",
"newListFromIterable",
"(",
"Iterable",
"<",
"?",
">",
"items",
")",
"{",
"// Create a list backed by a Java list which has eagerly converted each value into a lazy",
"// value provider. Specifically, the list iteration is done eagerly so that the lazy value",
"// pro... | Creates a SoyList from a Java Iterable.
<p>Values are converted into Soy types lazily and only once.
@param items The collection of Java values
@return A new SoyList initialized from the given Java Collection. | [
"Creates",
"a",
"SoyList",
"from",
"a",
"Java",
"Iterable",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SoyValueConverter.java#L420-L429 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/internal/MsgUtils.java | MsgUtils.buildMsgPartsAndComputeMsgIdForDualFormat | public static MsgPartsAndIds buildMsgPartsAndComputeMsgIdForDualFormat(MsgNode msgNode) {
if (msgNode.isPlrselMsg()) {
MsgPartsAndIds mpai = buildMsgPartsAndComputeMsgIds(msgNode, true);
return new MsgPartsAndIds(mpai.parts, mpai.idUsingBracedPhs, -1L);
} else {
return buildMsgPartsAndComputeMsgIds(msgNode, false);
}
} | java | public static MsgPartsAndIds buildMsgPartsAndComputeMsgIdForDualFormat(MsgNode msgNode) {
if (msgNode.isPlrselMsg()) {
MsgPartsAndIds mpai = buildMsgPartsAndComputeMsgIds(msgNode, true);
return new MsgPartsAndIds(mpai.parts, mpai.idUsingBracedPhs, -1L);
} else {
return buildMsgPartsAndComputeMsgIds(msgNode, false);
}
} | [
"public",
"static",
"MsgPartsAndIds",
"buildMsgPartsAndComputeMsgIdForDualFormat",
"(",
"MsgNode",
"msgNode",
")",
"{",
"if",
"(",
"msgNode",
".",
"isPlrselMsg",
"(",
")",
")",
"{",
"MsgPartsAndIds",
"mpai",
"=",
"buildMsgPartsAndComputeMsgIds",
"(",
"msgNode",
",",
... | Builds the list of SoyMsgParts and computes the unique message id for the given MsgNode,
assuming a specific dual format.
<p>Note: The field {@code idUsingBracedPhs} in the return value is simply set to -1L.
@param msgNode The message parsed from the Soy source.
@return A {@code MsgPartsAndIds} object, assuming a specific dual format, with field {@code
idUsingBracedPhs} set to -1L. | [
"Builds",
"the",
"list",
"of",
"SoyMsgParts",
"and",
"computes",
"the",
"unique",
"message",
"id",
"for",
"the",
"given",
"MsgNode",
"assuming",
"a",
"specific",
"dual",
"format",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/internal/MsgUtils.java#L77-L85 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/internal/MsgUtils.java | MsgUtils.computeMsgId | private static long computeMsgId(MsgNode msgNode) {
return SoyMsgIdComputer.computeMsgId(
buildMsgParts(msgNode), msgNode.getMeaning(), msgNode.getContentType());
} | java | private static long computeMsgId(MsgNode msgNode) {
return SoyMsgIdComputer.computeMsgId(
buildMsgParts(msgNode), msgNode.getMeaning(), msgNode.getContentType());
} | [
"private",
"static",
"long",
"computeMsgId",
"(",
"MsgNode",
"msgNode",
")",
"{",
"return",
"SoyMsgIdComputer",
".",
"computeMsgId",
"(",
"buildMsgParts",
"(",
"msgNode",
")",
",",
"msgNode",
".",
"getMeaning",
"(",
")",
",",
"msgNode",
".",
"getContentType",
... | Computes the unique message id for the given MsgNode.
@param msgNode The message parsed from the Soy source.
@return The message id. | [
"Computes",
"the",
"unique",
"message",
"id",
"for",
"the",
"given",
"MsgNode",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/internal/MsgUtils.java#L146-L149 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/internal/MsgUtils.java | MsgUtils.computeMsgIdUsingBracedPhs | private static long computeMsgIdUsingBracedPhs(MsgNode msgNode) {
return SoyMsgIdComputer.computeMsgIdUsingBracedPhs(
buildMsgParts(msgNode), msgNode.getMeaning(), msgNode.getContentType());
} | java | private static long computeMsgIdUsingBracedPhs(MsgNode msgNode) {
return SoyMsgIdComputer.computeMsgIdUsingBracedPhs(
buildMsgParts(msgNode), msgNode.getMeaning(), msgNode.getContentType());
} | [
"private",
"static",
"long",
"computeMsgIdUsingBracedPhs",
"(",
"MsgNode",
"msgNode",
")",
"{",
"return",
"SoyMsgIdComputer",
".",
"computeMsgIdUsingBracedPhs",
"(",
"buildMsgParts",
"(",
"msgNode",
")",
",",
"msgNode",
".",
"getMeaning",
"(",
")",
",",
"msgNode",
... | Computes the alternate unique id for this message. Only use this if you use braced
placeholders.
@param msgNode The message parsed from the Soy source.
@return The alternate message id using braced placeholders. | [
"Computes",
"the",
"alternate",
"unique",
"id",
"for",
"this",
"message",
".",
"Only",
"use",
"this",
"if",
"you",
"use",
"braced",
"placeholders",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/internal/MsgUtils.java#L158-L161 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/internal/MsgUtils.java | MsgUtils.buildMsgPartsForChildren | private static ImmutableList<SoyMsgPart> buildMsgPartsForChildren(
MsgBlockNode parent, MsgNode msgNode) {
ImmutableList.Builder<SoyMsgPart> msgParts = ImmutableList.builder();
doBuildMsgPartsForChildren(parent, msgNode, msgParts);
return msgParts.build();
} | java | private static ImmutableList<SoyMsgPart> buildMsgPartsForChildren(
MsgBlockNode parent, MsgNode msgNode) {
ImmutableList.Builder<SoyMsgPart> msgParts = ImmutableList.builder();
doBuildMsgPartsForChildren(parent, msgNode, msgParts);
return msgParts.build();
} | [
"private",
"static",
"ImmutableList",
"<",
"SoyMsgPart",
">",
"buildMsgPartsForChildren",
"(",
"MsgBlockNode",
"parent",
",",
"MsgNode",
"msgNode",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"SoyMsgPart",
">",
"msgParts",
"=",
"ImmutableList",
".",
"builder",
... | Builds the list of SoyMsgParts for all the children of a given parent node.
@param parent Can be MsgNode, MsgPluralCaseNode, MsgPluralDefaultNode, MsgSelectCaseNode, or
MsgSelectDefaultNode.
@param msgNode The MsgNode containing 'parent'. | [
"Builds",
"the",
"list",
"of",
"SoyMsgParts",
"for",
"all",
"the",
"children",
"of",
"a",
"given",
"parent",
"node",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/internal/MsgUtils.java#L173-L179 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/internal/MsgUtils.java | MsgUtils.buildMsgPartForPlural | private static SoyMsgPluralPart buildMsgPartForPlural(
MsgPluralNode msgPluralNode, MsgNode msgNode) {
// This is the list of the cases.
ImmutableList.Builder<SoyMsgPart.Case<SoyMsgPluralCaseSpec>> pluralCases =
ImmutableList.builder();
for (CaseOrDefaultNode child : msgPluralNode.getChildren()) {
ImmutableList<SoyMsgPart> caseMsgParts =
buildMsgPartsForChildren((MsgBlockNode) child, msgNode);
SoyMsgPluralCaseSpec caseSpec;
if (child instanceof MsgPluralCaseNode) {
caseSpec = new SoyMsgPluralCaseSpec(((MsgPluralCaseNode) child).getCaseNumber());
} else if (child instanceof MsgPluralDefaultNode) {
caseSpec = new SoyMsgPluralCaseSpec(Type.OTHER);
} else {
throw new AssertionError("Unidentified node under a plural node.");
}
pluralCases.add(SoyMsgPart.Case.create(caseSpec, caseMsgParts));
}
return new SoyMsgPluralPart(
msgNode.getPluralVarName(msgPluralNode), msgPluralNode.getOffset(), pluralCases.build());
} | java | private static SoyMsgPluralPart buildMsgPartForPlural(
MsgPluralNode msgPluralNode, MsgNode msgNode) {
// This is the list of the cases.
ImmutableList.Builder<SoyMsgPart.Case<SoyMsgPluralCaseSpec>> pluralCases =
ImmutableList.builder();
for (CaseOrDefaultNode child : msgPluralNode.getChildren()) {
ImmutableList<SoyMsgPart> caseMsgParts =
buildMsgPartsForChildren((MsgBlockNode) child, msgNode);
SoyMsgPluralCaseSpec caseSpec;
if (child instanceof MsgPluralCaseNode) {
caseSpec = new SoyMsgPluralCaseSpec(((MsgPluralCaseNode) child).getCaseNumber());
} else if (child instanceof MsgPluralDefaultNode) {
caseSpec = new SoyMsgPluralCaseSpec(Type.OTHER);
} else {
throw new AssertionError("Unidentified node under a plural node.");
}
pluralCases.add(SoyMsgPart.Case.create(caseSpec, caseMsgParts));
}
return new SoyMsgPluralPart(
msgNode.getPluralVarName(msgPluralNode), msgPluralNode.getOffset(), pluralCases.build());
} | [
"private",
"static",
"SoyMsgPluralPart",
"buildMsgPartForPlural",
"(",
"MsgPluralNode",
"msgPluralNode",
",",
"MsgNode",
"msgNode",
")",
"{",
"// This is the list of the cases.",
"ImmutableList",
".",
"Builder",
"<",
"SoyMsgPart",
".",
"Case",
"<",
"SoyMsgPluralCaseSpec",
... | Builds the list of SoyMsgParts for the given MsgPluralNode.
@param msgPluralNode The plural node parsed from the Soy source.
@param msgNode The MsgNode containing 'msgPluralNode'.
@return A SoyMsgPluralPart. | [
"Builds",
"the",
"list",
"of",
"SoyMsgParts",
"for",
"the",
"given",
"MsgPluralNode",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/internal/MsgUtils.java#L209-L237 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/internal/MsgUtils.java | MsgUtils.buildMsgPartForSelect | private static SoyMsgSelectPart buildMsgPartForSelect(
MsgSelectNode msgSelectNode, MsgNode msgNode) {
// This is the list of the cases.
ImmutableList.Builder<SoyMsgPart.Case<String>> selectCases = ImmutableList.builder();
for (CaseOrDefaultNode child : msgSelectNode.getChildren()) {
ImmutableList<SoyMsgPart> caseMsgParts =
buildMsgPartsForChildren((MsgBlockNode) child, msgNode);
String caseValue;
if (child instanceof MsgSelectCaseNode) {
caseValue = ((MsgSelectCaseNode) child).getCaseValue();
} else if (child instanceof MsgSelectDefaultNode) {
caseValue = null;
} else {
throw new AssertionError("Unidentified node under a select node.");
}
selectCases.add(SoyMsgPart.Case.create(caseValue, caseMsgParts));
}
return new SoyMsgSelectPart(msgNode.getSelectVarName(msgSelectNode), selectCases.build());
} | java | private static SoyMsgSelectPart buildMsgPartForSelect(
MsgSelectNode msgSelectNode, MsgNode msgNode) {
// This is the list of the cases.
ImmutableList.Builder<SoyMsgPart.Case<String>> selectCases = ImmutableList.builder();
for (CaseOrDefaultNode child : msgSelectNode.getChildren()) {
ImmutableList<SoyMsgPart> caseMsgParts =
buildMsgPartsForChildren((MsgBlockNode) child, msgNode);
String caseValue;
if (child instanceof MsgSelectCaseNode) {
caseValue = ((MsgSelectCaseNode) child).getCaseValue();
} else if (child instanceof MsgSelectDefaultNode) {
caseValue = null;
} else {
throw new AssertionError("Unidentified node under a select node.");
}
selectCases.add(SoyMsgPart.Case.create(caseValue, caseMsgParts));
}
return new SoyMsgSelectPart(msgNode.getSelectVarName(msgSelectNode), selectCases.build());
} | [
"private",
"static",
"SoyMsgSelectPart",
"buildMsgPartForSelect",
"(",
"MsgSelectNode",
"msgSelectNode",
",",
"MsgNode",
"msgNode",
")",
"{",
"// This is the list of the cases.",
"ImmutableList",
".",
"Builder",
"<",
"SoyMsgPart",
".",
"Case",
"<",
"String",
">>",
"sele... | Builds the list of SoyMsgParts for the given MsgSelectNode.
@param msgSelectNode The select node parsed from the Soy source.
@param msgNode The MsgNode containing 'msgSelectNode'.
@return A SoyMsgSelectPart. | [
"Builds",
"the",
"list",
"of",
"SoyMsgParts",
"for",
"the",
"given",
"MsgSelectNode",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/internal/MsgUtils.java#L246-L267 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenCallCodeUtils.java | GenCallCodeUtils.gen | public Expression gen(
CallNode callNode,
TemplateAliases templateAliases,
TranslationContext translationContext,
ErrorReporter errorReporter,
TranslateExprNodeVisitor exprTranslator) {
// Build the JS CodeChunk for the callee's name.
Expression callee = genCallee(callNode, templateAliases, exprTranslator);
// Generate the data object to pass to callee
Expression objToPass =
genObjToPass(callNode, templateAliases, translationContext, errorReporter, exprTranslator);
Expression call = genMainCall(callee, objToPass, callNode);
if (callNode.getEscapingDirectives().isEmpty()) {
return call;
}
return applyEscapingDirectives(call, callNode);
} | java | public Expression gen(
CallNode callNode,
TemplateAliases templateAliases,
TranslationContext translationContext,
ErrorReporter errorReporter,
TranslateExprNodeVisitor exprTranslator) {
// Build the JS CodeChunk for the callee's name.
Expression callee = genCallee(callNode, templateAliases, exprTranslator);
// Generate the data object to pass to callee
Expression objToPass =
genObjToPass(callNode, templateAliases, translationContext, errorReporter, exprTranslator);
Expression call = genMainCall(callee, objToPass, callNode);
if (callNode.getEscapingDirectives().isEmpty()) {
return call;
}
return applyEscapingDirectives(call, callNode);
} | [
"public",
"Expression",
"gen",
"(",
"CallNode",
"callNode",
",",
"TemplateAliases",
"templateAliases",
",",
"TranslationContext",
"translationContext",
",",
"ErrorReporter",
"errorReporter",
",",
"TranslateExprNodeVisitor",
"exprTranslator",
")",
"{",
"// Build the JS CodeChu... | Generates the JS expression for a given call.
<p>Important: If there are CallParamContentNode children whose contents are not computable as
JS expressions, then this function assumes that, elsewhere, code has been generated to define
their respective 'param<n>' temporary variables.
<p>Here are five example calls:
<pre>
{call some.func data="all" /}
{call some.func data="$boo.foo" /}
{call some.func}
{param goo = $moo /}
{/call}
{call some.func data="$boo"}
{param goo}Blah{/param}
{/call}
{call some.func}
{param goo}
{for $i in range(3)}{$i}{/for}
{/param}
{/call}
</pre>
Their respective generated calls might be the following:
<pre>
some.func(opt_data)
some.func(opt_data.boo.foo)
some.func({goo: opt_data.moo})
some.func(soy.$$assignDefaults({goo: 'Blah'}, opt_data.boo))
some.func({goo: param65})
</pre>
Note that in the last case, the param content is not computable as JS expressions, so we assume
that code has been generated to define the temporary variable 'param<n>'.
@param callNode The call to generate code for.
@param templateAliases A mapping of fully qualified calls to a variable in scope.
@return The JS expression for the call. | [
"Generates",
"the",
"JS",
"expression",
"for",
"a",
"given",
"call",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenCallCodeUtils.java#L122-L141 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenCallCodeUtils.java | GenCallCodeUtils.genObjToPass | public Expression genObjToPass(
CallNode callNode,
TemplateAliases templateAliases,
TranslationContext translationContext,
ErrorReporter errorReporter,
TranslateExprNodeVisitor exprTranslator) {
// ------ Generate the expression for the original data to pass ------
Expression dataToPass;
if (callNode.isPassingAllData()) {
dataToPass = JsRuntime.OPT_DATA;
} else if (callNode.isPassingData()) {
dataToPass = exprTranslator.exec(callNode.getDataExpr());
} else if (callNode.numChildren() == 0) {
// If we're passing neither children nor indirect data, we can immediately return null.
return LITERAL_NULL;
} else {
dataToPass = LITERAL_NULL;
}
Map<String, Expression> paramDefaults = getDefaultParams(callNode, translationContext);
// ------ Case 1: No additional params ------
if (callNode.numChildren() == 0) {
if (!paramDefaults.isEmpty()) {
dataToPass = SOY_ASSIGN_DEFAULTS.call(dataToPass, Expression.objectLiteral(paramDefaults));
}
// Ignore inconsistencies between Closure Compiler & Soy type systems (eg, proto nullability).
return dataToPass.castAs("?");
}
// ------ Build an object literal containing the additional params ------
Map<String, Expression> params = paramDefaults;
for (CallParamNode child : callNode.getChildren()) {
Expression value;
if (child instanceof CallParamValueNode) {
CallParamValueNode cpvn = (CallParamValueNode) child;
value = exprTranslator.exec(cpvn.getExpr());
} else {
CallParamContentNode cpcn = (CallParamContentNode) child;
if (isComputableAsJsExprsVisitor.exec(cpcn)) {
List<Expression> chunks =
genJsExprsVisitorFactory
.create(translationContext, templateAliases, errorReporter)
.exec(cpcn);
value = CodeChunkUtils.concatChunksForceString(chunks);
} else {
// This is a param with content that cannot be represented as JS expressions, so we assume
// that code has been generated to define the temporary variable 'param<n>'.
value = id("param" + cpcn.getId());
}
value = maybeWrapContent(translationContext.codeGenerator(), cpcn, value);
}
params.put(child.getKey().identifier(), value);
}
Expression paramsExp = Expression.objectLiteral(params);
// ------ Cases 2 and 3: Additional params with and without original data to pass ------
if (callNode.isPassingData()) {
Expression allData = SOY_ASSIGN_DEFAULTS.call(paramsExp, dataToPass);
// No need to cast; assignDefaults already returns {?}.
return allData;
} else {
// Ignore inconsistencies between Closure Compiler & Soy type systems (eg, proto nullability).
return paramsExp.castAs("?");
}
} | java | public Expression genObjToPass(
CallNode callNode,
TemplateAliases templateAliases,
TranslationContext translationContext,
ErrorReporter errorReporter,
TranslateExprNodeVisitor exprTranslator) {
// ------ Generate the expression for the original data to pass ------
Expression dataToPass;
if (callNode.isPassingAllData()) {
dataToPass = JsRuntime.OPT_DATA;
} else if (callNode.isPassingData()) {
dataToPass = exprTranslator.exec(callNode.getDataExpr());
} else if (callNode.numChildren() == 0) {
// If we're passing neither children nor indirect data, we can immediately return null.
return LITERAL_NULL;
} else {
dataToPass = LITERAL_NULL;
}
Map<String, Expression> paramDefaults = getDefaultParams(callNode, translationContext);
// ------ Case 1: No additional params ------
if (callNode.numChildren() == 0) {
if (!paramDefaults.isEmpty()) {
dataToPass = SOY_ASSIGN_DEFAULTS.call(dataToPass, Expression.objectLiteral(paramDefaults));
}
// Ignore inconsistencies between Closure Compiler & Soy type systems (eg, proto nullability).
return dataToPass.castAs("?");
}
// ------ Build an object literal containing the additional params ------
Map<String, Expression> params = paramDefaults;
for (CallParamNode child : callNode.getChildren()) {
Expression value;
if (child instanceof CallParamValueNode) {
CallParamValueNode cpvn = (CallParamValueNode) child;
value = exprTranslator.exec(cpvn.getExpr());
} else {
CallParamContentNode cpcn = (CallParamContentNode) child;
if (isComputableAsJsExprsVisitor.exec(cpcn)) {
List<Expression> chunks =
genJsExprsVisitorFactory
.create(translationContext, templateAliases, errorReporter)
.exec(cpcn);
value = CodeChunkUtils.concatChunksForceString(chunks);
} else {
// This is a param with content that cannot be represented as JS expressions, so we assume
// that code has been generated to define the temporary variable 'param<n>'.
value = id("param" + cpcn.getId());
}
value = maybeWrapContent(translationContext.codeGenerator(), cpcn, value);
}
params.put(child.getKey().identifier(), value);
}
Expression paramsExp = Expression.objectLiteral(params);
// ------ Cases 2 and 3: Additional params with and without original data to pass ------
if (callNode.isPassingData()) {
Expression allData = SOY_ASSIGN_DEFAULTS.call(paramsExp, dataToPass);
// No need to cast; assignDefaults already returns {?}.
return allData;
} else {
// Ignore inconsistencies between Closure Compiler & Soy type systems (eg, proto nullability).
return paramsExp.castAs("?");
}
} | [
"public",
"Expression",
"genObjToPass",
"(",
"CallNode",
"callNode",
",",
"TemplateAliases",
"templateAliases",
",",
"TranslationContext",
"translationContext",
",",
"ErrorReporter",
"errorReporter",
",",
"TranslateExprNodeVisitor",
"exprTranslator",
")",
"{",
"// ------ Gene... | Generates the JS expression for the object to pass in a given call.
<p>Important: If there are CallParamContentNode children whose contents are not computable as
JS expressions, then this function assumes that, elsewhere, code has been generated to define
their respective 'param<n>' temporary variables.
<p>Here are five example calls:
<pre>
{call some.func data="all" /}
{call some.func data="$boo.foo" /}
{call some.func}
{param goo = $moo /}
{/call}
{call some.func data="$boo"}
{param goo}Blah{/param}
{/call}
{call some.func}
{param goo}
{for $i in range(3)}{$i}{/for}
{/param}
{/call}
</pre>
Their respective objects to pass might be the following:
<pre>
opt_data
opt_data.boo.foo
{goo: opt_data.moo}
soy.$$assignDefaults({goo: 'Blah'}, opt_data.boo)
{goo: param65}
</pre>
Note that in the last case, the param content is not computable as JS expressions, so we assume
that code has been generated to define the temporary variable 'param<n>'.
@param callNode The call to generate code for.
@param templateAliases A mapping of fully qualified calls to a variable in scope.
@return The JS expression for the object to pass in the call. | [
"Generates",
"the",
"JS",
"expression",
"for",
"the",
"object",
"to",
"pass",
"in",
"a",
"given",
"call",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenCallCodeUtils.java#L261-L331 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenCallCodeUtils.java | GenCallCodeUtils.maybeWrapContent | protected Expression maybeWrapContent(
CodeChunk.Generator generator, CallParamContentNode node, Expression content) {
if (node.getContentKind() == null) {
return content;
}
// Use the internal blocks wrapper, to maintain falsiness of empty string
return sanitizedContentOrdainerFunctionForInternalBlocks(node.getContentKind()).call(content);
} | java | protected Expression maybeWrapContent(
CodeChunk.Generator generator, CallParamContentNode node, Expression content) {
if (node.getContentKind() == null) {
return content;
}
// Use the internal blocks wrapper, to maintain falsiness of empty string
return sanitizedContentOrdainerFunctionForInternalBlocks(node.getContentKind()).call(content);
} | [
"protected",
"Expression",
"maybeWrapContent",
"(",
"CodeChunk",
".",
"Generator",
"generator",
",",
"CallParamContentNode",
"node",
",",
"Expression",
"content",
")",
"{",
"if",
"(",
"node",
".",
"getContentKind",
"(",
")",
"==",
"null",
")",
"{",
"return",
"... | If the param node had a content kind specified, it was autoescaped in the corresponding
context. Hence the result of evaluating the param block is wrapped in a SanitizedContent
instance of the appropriate kind.
<p>The expression for the constructor of SanitizedContent of the appropriate kind (e.g., "new
SanitizedHtml"), or null if the node has no 'kind' attribute. This uses the variant used in
internal blocks. | [
"If",
"the",
"param",
"node",
"had",
"a",
"content",
"kind",
"specified",
"it",
"was",
"autoescaped",
"in",
"the",
"corresponding",
"context",
".",
"Hence",
"the",
"result",
"of",
"evaluating",
"the",
"param",
"block",
"is",
"wrapped",
"in",
"a",
"SanitizedC... | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenCallCodeUtils.java#L360-L368 | train |
google/closure-templates | java/src/com/google/template/soy/types/SoyTypeRegistry.java | SoyTypeRegistry.getType | @Nullable
public SoyType getType(String typeName) {
SoyType result = BUILTIN_TYPES.get(typeName);
if (result != null) {
return result;
}
synchronized (lock) {
result = protoTypeCache.get(typeName);
if (result == null) {
GenericDescriptor descriptor = descriptors.get(typeName);
if (descriptor == null) {
return null;
}
if (descriptor instanceof EnumDescriptor) {
result = new SoyProtoEnumType((EnumDescriptor) descriptor);
} else {
result = new SoyProtoType(this, (Descriptor) descriptor, extensions.get(typeName));
}
protoTypeCache.put(typeName, result);
}
}
return result;
} | java | @Nullable
public SoyType getType(String typeName) {
SoyType result = BUILTIN_TYPES.get(typeName);
if (result != null) {
return result;
}
synchronized (lock) {
result = protoTypeCache.get(typeName);
if (result == null) {
GenericDescriptor descriptor = descriptors.get(typeName);
if (descriptor == null) {
return null;
}
if (descriptor instanceof EnumDescriptor) {
result = new SoyProtoEnumType((EnumDescriptor) descriptor);
} else {
result = new SoyProtoType(this, (Descriptor) descriptor, extensions.get(typeName));
}
protoTypeCache.put(typeName, result);
}
}
return result;
} | [
"@",
"Nullable",
"public",
"SoyType",
"getType",
"(",
"String",
"typeName",
")",
"{",
"SoyType",
"result",
"=",
"BUILTIN_TYPES",
".",
"get",
"(",
"typeName",
")",
";",
"if",
"(",
"result",
"!=",
"null",
")",
"{",
"return",
"result",
";",
"}",
"synchroniz... | Look up a type by name. Returns null if there is no such type.
@param typeName The fully-qualified name of the type.
@return The type object, or {@code null}. | [
"Look",
"up",
"a",
"type",
"by",
"name",
".",
"Returns",
"null",
"if",
"there",
"is",
"no",
"such",
"type",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypeRegistry.java#L176-L198 | train |
google/closure-templates | java/src/com/google/template/soy/types/SoyTypeRegistry.java | SoyTypeRegistry.findTypeWithMatchingNamespace | public String findTypeWithMatchingNamespace(String prefix) {
prefix = prefix + ".";
// This must be sorted so that errors are deterministic, or we'll break integration tests.
for (String name : getAllSortedTypeNames()) {
if (name.startsWith(prefix)) {
return name;
}
}
return null;
} | java | public String findTypeWithMatchingNamespace(String prefix) {
prefix = prefix + ".";
// This must be sorted so that errors are deterministic, or we'll break integration tests.
for (String name : getAllSortedTypeNames()) {
if (name.startsWith(prefix)) {
return name;
}
}
return null;
} | [
"public",
"String",
"findTypeWithMatchingNamespace",
"(",
"String",
"prefix",
")",
"{",
"prefix",
"=",
"prefix",
"+",
"\".\"",
";",
"// This must be sorted so that errors are deterministic, or we'll break integration tests.",
"for",
"(",
"String",
"name",
":",
"getAllSortedTy... | Finds a type whose top-level namespace is a specified prefix, or null if there are none. | [
"Finds",
"a",
"type",
"whose",
"top",
"-",
"level",
"namespace",
"is",
"a",
"specified",
"prefix",
"or",
"null",
"if",
"there",
"are",
"none",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypeRegistry.java#L201-L210 | train |
google/closure-templates | java/src/com/google/template/soy/types/SoyTypeRegistry.java | SoyTypeRegistry.getAllSortedTypeNames | public Iterable<String> getAllSortedTypeNames() {
synchronized (lock) {
if (lazyAllSortedTypeNames == null) {
lazyAllSortedTypeNames =
Stream.concat(BUILTIN_TYPES.keySet().stream(), descriptors.keySet().stream())
.sorted()
.collect(toImmutableList());
}
return lazyAllSortedTypeNames;
}
} | java | public Iterable<String> getAllSortedTypeNames() {
synchronized (lock) {
if (lazyAllSortedTypeNames == null) {
lazyAllSortedTypeNames =
Stream.concat(BUILTIN_TYPES.keySet().stream(), descriptors.keySet().stream())
.sorted()
.collect(toImmutableList());
}
return lazyAllSortedTypeNames;
}
} | [
"public",
"Iterable",
"<",
"String",
">",
"getAllSortedTypeNames",
"(",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"if",
"(",
"lazyAllSortedTypeNames",
"==",
"null",
")",
"{",
"lazyAllSortedTypeNames",
"=",
"Stream",
".",
"concat",
"(",
"BUILTIN_TYPES",
... | Gets all known types, sorted alphabetically. | [
"Gets",
"all",
"known",
"types",
"sorted",
"alphabetically",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypeRegistry.java#L213-L223 | train |
google/closure-templates | java/src/com/google/template/soy/types/SoyTypeRegistry.java | SoyTypeRegistry.getOrCreateUnionType | public SoyType getOrCreateUnionType(Collection<SoyType> members) {
SoyType type = UnionType.of(members);
if (type.getKind() == SoyType.Kind.UNION) {
type = unionTypes.intern((UnionType) type);
}
return type;
} | java | public SoyType getOrCreateUnionType(Collection<SoyType> members) {
SoyType type = UnionType.of(members);
if (type.getKind() == SoyType.Kind.UNION) {
type = unionTypes.intern((UnionType) type);
}
return type;
} | [
"public",
"SoyType",
"getOrCreateUnionType",
"(",
"Collection",
"<",
"SoyType",
">",
"members",
")",
"{",
"SoyType",
"type",
"=",
"UnionType",
".",
"of",
"(",
"members",
")",
";",
"if",
"(",
"type",
".",
"getKind",
"(",
")",
"==",
"SoyType",
".",
"Kind",... | Factory function which creates a union type, given the member types. This folds identical union
types together.
@param members The members of the union.
@return The union type. | [
"Factory",
"function",
"which",
"creates",
"a",
"union",
"type",
"given",
"the",
"member",
"types",
".",
"This",
"folds",
"identical",
"union",
"types",
"together",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypeRegistry.java#L270-L276 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/restricted/SoyMsgRawTextPart.java | SoyMsgRawTextPart.of | public static SoyMsgRawTextPart of(String rawText) {
int utf8Length = Utf8.encodedLength(rawText);
// Determine whether UTF8 or UTF16 uses less memory, and choose between one of the two internal
// implementations. char[] is preferred if the sizes are equal because it is faster to turn
// back into a String. In a realistic application with 1 million messages in memory, using
// UTF-8 saves about 35M, and dynamicaly switching encodings saves another 10M.
// IMPORTANT! This choice is deterministic, so that for any particular input string the choice
// of implementation class is the same. This ensures operations like equals() and hashCode()
// do not have to decode the contents.
if (utf8Length < rawText.length() * BYTES_PER_CHAR) {
return new Utf8SoyMsgRawTextPart(rawText);
} else {
return new CharArraySoyMsgRawTextPart(rawText);
}
} | java | public static SoyMsgRawTextPart of(String rawText) {
int utf8Length = Utf8.encodedLength(rawText);
// Determine whether UTF8 or UTF16 uses less memory, and choose between one of the two internal
// implementations. char[] is preferred if the sizes are equal because it is faster to turn
// back into a String. In a realistic application with 1 million messages in memory, using
// UTF-8 saves about 35M, and dynamicaly switching encodings saves another 10M.
// IMPORTANT! This choice is deterministic, so that for any particular input string the choice
// of implementation class is the same. This ensures operations like equals() and hashCode()
// do not have to decode the contents.
if (utf8Length < rawText.length() * BYTES_PER_CHAR) {
return new Utf8SoyMsgRawTextPart(rawText);
} else {
return new CharArraySoyMsgRawTextPart(rawText);
}
} | [
"public",
"static",
"SoyMsgRawTextPart",
"of",
"(",
"String",
"rawText",
")",
"{",
"int",
"utf8Length",
"=",
"Utf8",
".",
"encodedLength",
"(",
"rawText",
")",
";",
"// Determine whether UTF8 or UTF16 uses less memory, and choose between one of the two internal",
"// implemen... | Returns a SoyMsgRawTextPart representing the specified raw text string. | [
"Returns",
"a",
"SoyMsgRawTextPart",
"representing",
"the",
"specified",
"raw",
"text",
"string",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/restricted/SoyMsgRawTextPart.java#L37-L54 | train |
google/closure-templates | java/src/com/google/template/soy/exprtree/FunctionNode.java | FunctionNode.isPure | public boolean isPure() {
if (soyFunction instanceof BuiltinFunction) {
return ((BuiltinFunction) soyFunction).isPure();
}
return soyFunction.getClass().isAnnotationPresent(SoyPureFunction.class);
} | java | public boolean isPure() {
if (soyFunction instanceof BuiltinFunction) {
return ((BuiltinFunction) soyFunction).isPure();
}
return soyFunction.getClass().isAnnotationPresent(SoyPureFunction.class);
} | [
"public",
"boolean",
"isPure",
"(",
")",
"{",
"if",
"(",
"soyFunction",
"instanceof",
"BuiltinFunction",
")",
"{",
"return",
"(",
"(",
"BuiltinFunction",
")",
"soyFunction",
")",
".",
"isPure",
"(",
")",
";",
"}",
"return",
"soyFunction",
".",
"getClass",
... | Whether or not this function is pure.
<p>See {@link SoyPureFunction} for the definition of a pure function. | [
"Whether",
"or",
"not",
"this",
"function",
"is",
"pure",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/exprtree/FunctionNode.java#L156-L161 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/PyCodeBuilder.java | PyCodeBuilder.addToOutputVar | void addToOutputVar(PyExpr pyExpr) {
boolean isList = pyExpr instanceof PyListExpr;
if (isList && !getOutputVarIsInited()) {
appendLine(getOutputVarName(), " = ", pyExpr.getText());
} else {
initOutputVarIfNecessary();
String function = isList ? ".extend(" : ".append(";
appendLine(getOutputVarName(), function, pyExpr.getText(), ")");
}
setOutputVarInited();
} | java | void addToOutputVar(PyExpr pyExpr) {
boolean isList = pyExpr instanceof PyListExpr;
if (isList && !getOutputVarIsInited()) {
appendLine(getOutputVarName(), " = ", pyExpr.getText());
} else {
initOutputVarIfNecessary();
String function = isList ? ".extend(" : ".append(";
appendLine(getOutputVarName(), function, pyExpr.getText(), ")");
}
setOutputVarInited();
} | [
"void",
"addToOutputVar",
"(",
"PyExpr",
"pyExpr",
")",
"{",
"boolean",
"isList",
"=",
"pyExpr",
"instanceof",
"PyListExpr",
";",
"if",
"(",
"isList",
"&&",
"!",
"getOutputVarIsInited",
"(",
")",
")",
"{",
"appendLine",
"(",
"getOutputVarName",
"(",
")",
","... | Add a single PyExpr object to the output variable. | [
"Add",
"a",
"single",
"PyExpr",
"object",
"to",
"the",
"output",
"variable",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/PyCodeBuilder.java#L118-L128 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/PyCodeBuilder.java | PyCodeBuilder.getOutputAsString | PyStringExpr getOutputAsString() {
Preconditions.checkState(getOutputVarName() != null);
initOutputVarIfNecessary();
return new PyListExpr(getOutputVarName(), Integer.MAX_VALUE).toPyString();
} | java | PyStringExpr getOutputAsString() {
Preconditions.checkState(getOutputVarName() != null);
initOutputVarIfNecessary();
return new PyListExpr(getOutputVarName(), Integer.MAX_VALUE).toPyString();
} | [
"PyStringExpr",
"getOutputAsString",
"(",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"getOutputVarName",
"(",
")",
"!=",
"null",
")",
";",
"initOutputVarIfNecessary",
"(",
")",
";",
"return",
"new",
"PyListExpr",
"(",
"getOutputVarName",
"(",
")",
",",
... | Provide the output object as a string. Since we store all data in the output variables as a
list for concatenation performance, this step does the joining to convert the output into a
String.
@return A PyExpr object of the output joined into a String. | [
"Provide",
"the",
"output",
"object",
"as",
"a",
"string",
".",
"Since",
"we",
"store",
"all",
"data",
"in",
"the",
"output",
"variables",
"as",
"a",
"list",
"for",
"concatenation",
"performance",
"this",
"step",
"does",
"the",
"joining",
"to",
"convert",
... | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/PyCodeBuilder.java#L137-L142 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/MsgNode.java | MsgNode.getAndRemoveGenderExprs | @Nullable
public List<ExprRootNode> getAndRemoveGenderExprs() {
List<ExprRootNode> genderExprs = this.genderExprs;
this.genderExprs = null;
return genderExprs;
} | java | @Nullable
public List<ExprRootNode> getAndRemoveGenderExprs() {
List<ExprRootNode> genderExprs = this.genderExprs;
this.genderExprs = null;
return genderExprs;
} | [
"@",
"Nullable",
"public",
"List",
"<",
"ExprRootNode",
">",
"getAndRemoveGenderExprs",
"(",
")",
"{",
"List",
"<",
"ExprRootNode",
">",
"genderExprs",
"=",
"this",
".",
"genderExprs",
";",
"this",
".",
"genderExprs",
"=",
"null",
";",
"return",
"genderExprs",... | Returns the list of expressions for gender values and sets that field to null.
<p>Note that this node's command text will still contain the substring genders="...". We think
this is okay since the command text is only used for reporting errors (in fact, it might be
good as a reminder of how the msg was originally written). | [
"Returns",
"the",
"list",
"of",
"expressions",
"for",
"gender",
"values",
"and",
"sets",
"that",
"field",
"to",
"null",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/MsgNode.java#L265-L270 | train |
google/closure-templates | java/src/com/google/template/soy/error/ErrorReporter.java | ErrorReporter.create | public static ErrorReporter create(Map<String, SoyFileSupplier> filePathsToSuppliers) {
return new ErrorReporterImpl(ImmutableMap.copyOf(filePathsToSuppliers));
} | java | public static ErrorReporter create(Map<String, SoyFileSupplier> filePathsToSuppliers) {
return new ErrorReporterImpl(ImmutableMap.copyOf(filePathsToSuppliers));
} | [
"public",
"static",
"ErrorReporter",
"create",
"(",
"Map",
"<",
"String",
",",
"SoyFileSupplier",
">",
"filePathsToSuppliers",
")",
"{",
"return",
"new",
"ErrorReporterImpl",
"(",
"ImmutableMap",
".",
"copyOf",
"(",
"filePathsToSuppliers",
")",
")",
";",
"}"
] | Creates a new ErrorReporter which can create source snippets from the given files. | [
"Creates",
"a",
"new",
"ErrorReporter",
"which",
"can",
"create",
"source",
"snippets",
"from",
"the",
"given",
"files",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/error/ErrorReporter.java#L34-L36 | train |
google/closure-templates | java/src/com/google/template/soy/shared/internal/SharedRuntime.java | SharedRuntime.equal | public static boolean equal(SoyValue operand0, SoyValue operand1) {
// Treat the case where either is a string specially.
// TODO(gboyer): This should probably handle SanitizedContent == SanitizedContent, even though
// Javascript doesn't handle that case properly. http://b/21461181
if (operand0 instanceof StringData || operand0 instanceof UnsanitizedString) {
return compareString(operand0.stringValue(), operand1);
}
if (operand1 instanceof StringData || operand1 instanceof UnsanitizedString) {
return compareString(operand1.stringValue(), operand0);
}
return Objects.equals(operand0, operand1);
} | java | public static boolean equal(SoyValue operand0, SoyValue operand1) {
// Treat the case where either is a string specially.
// TODO(gboyer): This should probably handle SanitizedContent == SanitizedContent, even though
// Javascript doesn't handle that case properly. http://b/21461181
if (operand0 instanceof StringData || operand0 instanceof UnsanitizedString) {
return compareString(operand0.stringValue(), operand1);
}
if (operand1 instanceof StringData || operand1 instanceof UnsanitizedString) {
return compareString(operand1.stringValue(), operand0);
}
return Objects.equals(operand0, operand1);
} | [
"public",
"static",
"boolean",
"equal",
"(",
"SoyValue",
"operand0",
",",
"SoyValue",
"operand1",
")",
"{",
"// Treat the case where either is a string specially.",
"// TODO(gboyer): This should probably handle SanitizedContent == SanitizedContent, even though",
"// Javascript doesn't ha... | Custom equality operator that smooths out differences between different Soy runtimes.
<p>This approximates Javascript's behavior, but is much easier to understand. | [
"Custom",
"equality",
"operator",
"that",
"smooths",
"out",
"differences",
"between",
"different",
"Soy",
"runtimes",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/SharedRuntime.java#L39-L50 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/GoogRequire.java | GoogRequire.reference | public Expression reference() {
if (chunk() instanceof VariableDeclaration) {
return id(((VariableDeclaration) chunk()).varName(), ImmutableSet.of(this));
} else {
return dottedIdWithRequires(symbol(), ImmutableSet.of(this));
}
} | java | public Expression reference() {
if (chunk() instanceof VariableDeclaration) {
return id(((VariableDeclaration) chunk()).varName(), ImmutableSet.of(this));
} else {
return dottedIdWithRequires(symbol(), ImmutableSet.of(this));
}
} | [
"public",
"Expression",
"reference",
"(",
")",
"{",
"if",
"(",
"chunk",
"(",
")",
"instanceof",
"VariableDeclaration",
")",
"{",
"return",
"id",
"(",
"(",
"(",
"VariableDeclaration",
")",
"chunk",
"(",
")",
")",
".",
"varName",
"(",
")",
",",
"ImmutableS... | Returns a code chunk that can act as a reference to the required symbol. | [
"Returns",
"a",
"code",
"chunk",
"that",
"can",
"act",
"as",
"a",
"reference",
"to",
"the",
"required",
"symbol",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/GoogRequire.java#L89-L95 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/GoogRequire.java | GoogRequire.merge | public GoogRequire merge(GoogRequire other) {
checkArgument(other.symbol().equals(symbol()));
if (other.equals(this)) {
return this;
}
// if symbols are equal and the references are, then they must differ only by requireType or not
// prefer the non requireType symbol
if ((other.chunk() instanceof VariableDeclaration
&& chunk() instanceof VariableDeclaration
&& ((VariableDeclaration) chunk())
.varName()
.equals(((VariableDeclaration) other.chunk()).varName()))
|| (!(chunk() instanceof VariableReference)
&& !(other.chunk() instanceof VariableDeclaration))) {
if (other.isTypeRequire()) {
return this;
}
return other;
}
throw new IllegalArgumentException(
"Found the same namespace added as a require in multiple incompatible ways: "
+ other
+ " vs. "
+ this);
} | java | public GoogRequire merge(GoogRequire other) {
checkArgument(other.symbol().equals(symbol()));
if (other.equals(this)) {
return this;
}
// if symbols are equal and the references are, then they must differ only by requireType or not
// prefer the non requireType symbol
if ((other.chunk() instanceof VariableDeclaration
&& chunk() instanceof VariableDeclaration
&& ((VariableDeclaration) chunk())
.varName()
.equals(((VariableDeclaration) other.chunk()).varName()))
|| (!(chunk() instanceof VariableReference)
&& !(other.chunk() instanceof VariableDeclaration))) {
if (other.isTypeRequire()) {
return this;
}
return other;
}
throw new IllegalArgumentException(
"Found the same namespace added as a require in multiple incompatible ways: "
+ other
+ " vs. "
+ this);
} | [
"public",
"GoogRequire",
"merge",
"(",
"GoogRequire",
"other",
")",
"{",
"checkArgument",
"(",
"other",
".",
"symbol",
"(",
")",
".",
"equals",
"(",
"symbol",
"(",
")",
")",
")",
";",
"if",
"(",
"other",
".",
"equals",
"(",
"this",
")",
")",
"{",
"... | For 2 goog requires with the same symbol. Return the perfered one. | [
"For",
"2",
"goog",
"requires",
"with",
"the",
"same",
"symbol",
".",
"Return",
"the",
"perfered",
"one",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/GoogRequire.java#L116-L140 | train |
google/closure-templates | java/src/com/google/template/soy/incrementaldomsrc/GenIncrementalDomCodeVisitor.java | GenIncrementalDomCodeVisitor.incrementKeyForTemplate | private Expression incrementKeyForTemplate(TemplateNode template) {
Holder<Integer> keyCounter = keyCounterStack.peek();
return JsRuntime.XID.call(
Expression.stringLiteral(template.getTemplateName() + "-" + keyCounter.value++));
} | java | private Expression incrementKeyForTemplate(TemplateNode template) {
Holder<Integer> keyCounter = keyCounterStack.peek();
return JsRuntime.XID.call(
Expression.stringLiteral(template.getTemplateName() + "-" + keyCounter.value++));
} | [
"private",
"Expression",
"incrementKeyForTemplate",
"(",
"TemplateNode",
"template",
")",
"{",
"Holder",
"<",
"Integer",
">",
"keyCounter",
"=",
"keyCounterStack",
".",
"peek",
"(",
")",
";",
"return",
"JsRuntime",
".",
"XID",
".",
"call",
"(",
"Expression",
"... | Returns a unique key for the template. This has the side-effect of incrementing the current
keyCounter at the top of the stack. | [
"Returns",
"a",
"unique",
"key",
"for",
"the",
"template",
".",
"This",
"has",
"the",
"side",
"-",
"effect",
"of",
"incrementing",
"the",
"current",
"keyCounter",
"at",
"the",
"top",
"of",
"the",
"stack",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/incrementaldomsrc/GenIncrementalDomCodeVisitor.java#L1026-L1030 | train |
google/closure-templates | java/src/com/google/template/soy/passes/PassManager.java | PassManager.runWholeFilesetPasses | public void runWholeFilesetPasses(SoyFileSetNode soyTree, TemplateRegistry templateRegistry) {
ImmutableList<SoyFileNode> sourceFiles = ImmutableList.copyOf(soyTree.getChildren());
IdGenerator idGenerator = soyTree.getNodeIdGenerator();
for (CompilerFileSetPass pass : crossTemplateCheckingPasses) {
CompilerFileSetPass.Result result = pass.run(sourceFiles, idGenerator, templateRegistry);
if (result == CompilerFileSetPass.Result.STOP) {
break;
}
}
} | java | public void runWholeFilesetPasses(SoyFileSetNode soyTree, TemplateRegistry templateRegistry) {
ImmutableList<SoyFileNode> sourceFiles = ImmutableList.copyOf(soyTree.getChildren());
IdGenerator idGenerator = soyTree.getNodeIdGenerator();
for (CompilerFileSetPass pass : crossTemplateCheckingPasses) {
CompilerFileSetPass.Result result = pass.run(sourceFiles, idGenerator, templateRegistry);
if (result == CompilerFileSetPass.Result.STOP) {
break;
}
}
} | [
"public",
"void",
"runWholeFilesetPasses",
"(",
"SoyFileSetNode",
"soyTree",
",",
"TemplateRegistry",
"templateRegistry",
")",
"{",
"ImmutableList",
"<",
"SoyFileNode",
">",
"sourceFiles",
"=",
"ImmutableList",
".",
"copyOf",
"(",
"soyTree",
".",
"getChildren",
"(",
... | Runs all the fileset passes including the autoescaper and optimization passes if configured. | [
"Runs",
"all",
"the",
"fileset",
"passes",
"including",
"the",
"autoescaper",
"and",
"optimization",
"passes",
"if",
"configured",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/PassManager.java#L98-L107 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/TemplateNode.java | TemplateNode.appendHeaderVarDecl | protected void appendHeaderVarDecl(
ImmutableList<? extends TemplateHeaderVarDefn> headerVars, StringBuilder sb) {
for (TemplateHeaderVarDefn headerVar : headerVars) {
sb.append(" {").append(getDeclName(headerVar));
if (!headerVar.isRequired()) {
sb.append("?");
}
sb.append(" ")
.append(headerVar.name())
.append(": ")
.append(headerVar.hasType() ? headerVar.type() : headerVar.getTypeNode())
.append("}");
if (headerVar.desc() != null) {
sb.append(" /** ").append(headerVar.desc()).append(" */");
}
sb.append("\n");
}
} | java | protected void appendHeaderVarDecl(
ImmutableList<? extends TemplateHeaderVarDefn> headerVars, StringBuilder sb) {
for (TemplateHeaderVarDefn headerVar : headerVars) {
sb.append(" {").append(getDeclName(headerVar));
if (!headerVar.isRequired()) {
sb.append("?");
}
sb.append(" ")
.append(headerVar.name())
.append(": ")
.append(headerVar.hasType() ? headerVar.type() : headerVar.getTypeNode())
.append("}");
if (headerVar.desc() != null) {
sb.append(" /** ").append(headerVar.desc()).append(" */");
}
sb.append("\n");
}
} | [
"protected",
"void",
"appendHeaderVarDecl",
"(",
"ImmutableList",
"<",
"?",
"extends",
"TemplateHeaderVarDefn",
">",
"headerVars",
",",
"StringBuilder",
"sb",
")",
"{",
"for",
"(",
"TemplateHeaderVarDefn",
"headerVar",
":",
"headerVars",
")",
"{",
"sb",
".",
"appe... | Add the Soy template syntax that declares `headerVar` to the string builder. | [
"Add",
"the",
"Soy",
"template",
"syntax",
"that",
"declares",
"headerVar",
"to",
"the",
"string",
"builder",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/TemplateNode.java#L566-L584 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/TemplateNode.java | TemplateNode.createStackTraceElement | public StackTraceElement createStackTraceElement(SourceLocation srcLocation) {
return new StackTraceElement(
/* declaringClass= */ soyFileHeaderInfo.namespace,
// The partial template name begins with a '.' that causes the stack trace element to
// print "namespace..templateName" otherwise.
/* methodName= */ partialTemplateName.substring(1),
srcLocation.getFileName(),
srcLocation.getBeginLine());
} | java | public StackTraceElement createStackTraceElement(SourceLocation srcLocation) {
return new StackTraceElement(
/* declaringClass= */ soyFileHeaderInfo.namespace,
// The partial template name begins with a '.' that causes the stack trace element to
// print "namespace..templateName" otherwise.
/* methodName= */ partialTemplateName.substring(1),
srcLocation.getFileName(),
srcLocation.getBeginLine());
} | [
"public",
"StackTraceElement",
"createStackTraceElement",
"(",
"SourceLocation",
"srcLocation",
")",
"{",
"return",
"new",
"StackTraceElement",
"(",
"/* declaringClass= */",
"soyFileHeaderInfo",
".",
"namespace",
",",
"// The partial template name begins with a '.' that causes the ... | Construct a StackTraceElement that will point to the given source location of the current
template. | [
"Construct",
"a",
"StackTraceElement",
"that",
"will",
"point",
"to",
"the",
"given",
"source",
"location",
"of",
"the",
"current",
"template",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/TemplateNode.java#L590-L598 | train |
google/closure-templates | java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java | AbstractGenerateSoyEscapingDirectiveCode.configure | protected void configure(String[] args) throws IOException {
for (String arg : args) {
if (arg.startsWith("--input=")) {
FileRef ref = createInput();
ref.setPath(arg.substring(arg.indexOf('=') + 1));
} else if (arg.startsWith("--output=")) {
FileRef ref = createOutput();
ref.setPath(arg.substring(arg.indexOf('=') + 1));
} else if (arg.startsWith("--libdefined=")) {
FunctionNamePredicate libdefined = new FunctionNamePredicate();
libdefined.setPattern(arg.substring(arg.indexOf('=') + 1));
addConfiguredLibdefined(libdefined);
} else {
throw new IllegalArgumentException(arg);
}
}
} | java | protected void configure(String[] args) throws IOException {
for (String arg : args) {
if (arg.startsWith("--input=")) {
FileRef ref = createInput();
ref.setPath(arg.substring(arg.indexOf('=') + 1));
} else if (arg.startsWith("--output=")) {
FileRef ref = createOutput();
ref.setPath(arg.substring(arg.indexOf('=') + 1));
} else if (arg.startsWith("--libdefined=")) {
FunctionNamePredicate libdefined = new FunctionNamePredicate();
libdefined.setPattern(arg.substring(arg.indexOf('=') + 1));
addConfiguredLibdefined(libdefined);
} else {
throw new IllegalArgumentException(arg);
}
}
} | [
"protected",
"void",
"configure",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"IOException",
"{",
"for",
"(",
"String",
"arg",
":",
"args",
")",
"{",
"if",
"(",
"arg",
".",
"startsWith",
"(",
"\"--input=\"",
")",
")",
"{",
"FileRef",
"ref",
"=",
... | Setup method to read arguments and setup initial configuration.
@param args Main method input arguments. | [
"Setup",
"method",
"to",
"read",
"arguments",
"and",
"setup",
"initial",
"configuration",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java#L151-L167 | train |
google/closure-templates | java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java | AbstractGenerateSoyEscapingDirectiveCode.execute | @Override
public void execute() {
super.execute();
if (output == null) {
System.err.println(
"Please add an <output> for the <" + getTaskName() + "> at " + this.getLocation());
return;
}
// Gather output in a buffer rather than generating a bad file with a valid timestamp.
StringBuilder sb = new StringBuilder();
// Output the source files that use the helper functions first, so we get the appropriate file
// overviews and copyright headers.
for (FileRef input : inputs) {
try {
boolean inGeneratedCode = false;
for (String line : Files.readLines(input.file, Charsets.UTF_8)) {
// Skip code between generated code markers so that this transformation is idempotent.
// We can run an old output through this class, and get the latest version out.
if (inGeneratedCode) {
if (GENERATED_CODE_END_MARKER.equals(line.trim())) {
inGeneratedCode = false;
}
} else if (GENERATED_CODE_START_MARKER.equals(line.trim())) {
inGeneratedCode = true;
} else {
sb.append(line).append('\n');
}
}
} catch (IOException ex) {
System.err.println("Failed to read " + input.file);
ex.printStackTrace();
return;
}
}
// Generate helper functions for escape directives.
generateCode(availableIdentifiers, sb);
// Output a file now that we know generation hasn't failed.
try {
Files.asCharSink(output.file, Charsets.UTF_8).write(sb);
} catch (IOException ex) {
// Make sure an abortive write does not leave a file w
output.file.delete();
}
} | java | @Override
public void execute() {
super.execute();
if (output == null) {
System.err.println(
"Please add an <output> for the <" + getTaskName() + "> at " + this.getLocation());
return;
}
// Gather output in a buffer rather than generating a bad file with a valid timestamp.
StringBuilder sb = new StringBuilder();
// Output the source files that use the helper functions first, so we get the appropriate file
// overviews and copyright headers.
for (FileRef input : inputs) {
try {
boolean inGeneratedCode = false;
for (String line : Files.readLines(input.file, Charsets.UTF_8)) {
// Skip code between generated code markers so that this transformation is idempotent.
// We can run an old output through this class, and get the latest version out.
if (inGeneratedCode) {
if (GENERATED_CODE_END_MARKER.equals(line.trim())) {
inGeneratedCode = false;
}
} else if (GENERATED_CODE_START_MARKER.equals(line.trim())) {
inGeneratedCode = true;
} else {
sb.append(line).append('\n');
}
}
} catch (IOException ex) {
System.err.println("Failed to read " + input.file);
ex.printStackTrace();
return;
}
}
// Generate helper functions for escape directives.
generateCode(availableIdentifiers, sb);
// Output a file now that we know generation hasn't failed.
try {
Files.asCharSink(output.file, Charsets.UTF_8).write(sb);
} catch (IOException ex) {
// Make sure an abortive write does not leave a file w
output.file.delete();
}
} | [
"@",
"Override",
"public",
"void",
"execute",
"(",
")",
"{",
"super",
".",
"execute",
"(",
")",
";",
"if",
"(",
"output",
"==",
"null",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"Please add an <output> for the <\"",
"+",
"getTaskName",
"(",
... | Called to actually build the output by Ant. | [
"Called",
"to",
"actually",
"build",
"the",
"output",
"by",
"Ant",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java#L170-L217 | train |
google/closure-templates | java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java | AbstractGenerateSoyEscapingDirectiveCode.writeStringLiteral | protected void writeStringLiteral(String value, StringBuilder out) {
out.append('\'').append(escapeOutputString(value)).append('\'');
} | java | protected void writeStringLiteral(String value, StringBuilder out) {
out.append('\'').append(escapeOutputString(value)).append('\'');
} | [
"protected",
"void",
"writeStringLiteral",
"(",
"String",
"value",
",",
"StringBuilder",
"out",
")",
"{",
"out",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"escapeOutputString",
"(",
"value",
")",
")",
".",
"append",
"(",
"'",
"'",
")",
";"... | Appends a string literal with the given value onto the given buffer. | [
"Appends",
"a",
"string",
"literal",
"with",
"the",
"given",
"value",
"onto",
"the",
"given",
"buffer",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java#L455-L457 | train |
google/closure-templates | java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java | AbstractGenerateSoyEscapingDirectiveCode.writeUnsafeStringLiteral | private void writeUnsafeStringLiteral(char value, StringBuilder out) {
if (!isPrintable(value)) {
// Don't emit non-Latin characters or control characters since they don't roundtrip well.
out.append(String.format(value >= 0x100 ? "'\\u%04x'" : "'\\x%02x'", (int) value));
} else {
out.append('\'').append(escapeOutputString(String.valueOf(value))).append('\'');
}
} | java | private void writeUnsafeStringLiteral(char value, StringBuilder out) {
if (!isPrintable(value)) {
// Don't emit non-Latin characters or control characters since they don't roundtrip well.
out.append(String.format(value >= 0x100 ? "'\\u%04x'" : "'\\x%02x'", (int) value));
} else {
out.append('\'').append(escapeOutputString(String.valueOf(value))).append('\'');
}
} | [
"private",
"void",
"writeUnsafeStringLiteral",
"(",
"char",
"value",
",",
"StringBuilder",
"out",
")",
"{",
"if",
"(",
"!",
"isPrintable",
"(",
"value",
")",
")",
"{",
"// Don't emit non-Latin characters or control characters since they don't roundtrip well.",
"out",
".",... | Appends a string literal which may not be printable with the given value onto the given buffer. | [
"Appends",
"a",
"string",
"literal",
"which",
"may",
"not",
"be",
"printable",
"with",
"the",
"given",
"value",
"onto",
"the",
"given",
"buffer",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/AbstractGenerateSoyEscapingDirectiveCode.java#L462-L469 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/JsRuntime.java | JsRuntime.extensionField | public static Expression extensionField(FieldDescriptor desc) {
String jsExtensionImport = ProtoUtils.getJsExtensionImport(desc);
String jsExtensionName = ProtoUtils.getJsExtensionName(desc);
return symbolWithNamespace(jsExtensionImport, jsExtensionName);
} | java | public static Expression extensionField(FieldDescriptor desc) {
String jsExtensionImport = ProtoUtils.getJsExtensionImport(desc);
String jsExtensionName = ProtoUtils.getJsExtensionName(desc);
return symbolWithNamespace(jsExtensionImport, jsExtensionName);
} | [
"public",
"static",
"Expression",
"extensionField",
"(",
"FieldDescriptor",
"desc",
")",
"{",
"String",
"jsExtensionImport",
"=",
"ProtoUtils",
".",
"getJsExtensionImport",
"(",
"desc",
")",
";",
"String",
"jsExtensionName",
"=",
"ProtoUtils",
".",
"getJsExtensionName... | Returns the field containing the extension object for the given field descriptor. | [
"Returns",
"the",
"field",
"containing",
"the",
"extension",
"object",
"for",
"the",
"given",
"field",
"descriptor",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsRuntime.java#L179-L183 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/JsRuntime.java | JsRuntime.protoToSanitizedContentConverterFunction | public static Expression protoToSanitizedContentConverterFunction(Descriptor messageType) {
return GoogRequire.create(NodeContentKinds.toJsUnpackFunction(messageType)).reference();
} | java | public static Expression protoToSanitizedContentConverterFunction(Descriptor messageType) {
return GoogRequire.create(NodeContentKinds.toJsUnpackFunction(messageType)).reference();
} | [
"public",
"static",
"Expression",
"protoToSanitizedContentConverterFunction",
"(",
"Descriptor",
"messageType",
")",
"{",
"return",
"GoogRequire",
".",
"create",
"(",
"NodeContentKinds",
".",
"toJsUnpackFunction",
"(",
"messageType",
")",
")",
".",
"reference",
"(",
"... | Returns a function that can 'unpack' safe proto types into sanitized content types.. | [
"Returns",
"a",
"function",
"that",
"can",
"unpack",
"safe",
"proto",
"types",
"into",
"sanitized",
"content",
"types",
".."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsRuntime.java#L186-L188 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/JsRuntime.java | JsRuntime.protoConstructor | public static Expression protoConstructor(SoyProtoType type) {
return GoogRequire.create(type.getNameForBackend(SoyBackendKind.JS_SRC)).reference();
} | java | public static Expression protoConstructor(SoyProtoType type) {
return GoogRequire.create(type.getNameForBackend(SoyBackendKind.JS_SRC)).reference();
} | [
"public",
"static",
"Expression",
"protoConstructor",
"(",
"SoyProtoType",
"type",
")",
"{",
"return",
"GoogRequire",
".",
"create",
"(",
"type",
".",
"getNameForBackend",
"(",
"SoyBackendKind",
".",
"JS_SRC",
")",
")",
".",
"reference",
"(",
")",
";",
"}"
] | Returns the constructor for the proto. | [
"Returns",
"the",
"constructor",
"for",
"the",
"proto",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsRuntime.java#L212-L214 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/JsRuntime.java | JsRuntime.sanitizedContentType | public static Expression sanitizedContentType(SanitizedContentKind kind) {
return GoogRequire.create(NodeContentKinds.toJsSanitizedContentCtorName(kind)).reference();
} | java | public static Expression sanitizedContentType(SanitizedContentKind kind) {
return GoogRequire.create(NodeContentKinds.toJsSanitizedContentCtorName(kind)).reference();
} | [
"public",
"static",
"Expression",
"sanitizedContentType",
"(",
"SanitizedContentKind",
"kind",
")",
"{",
"return",
"GoogRequire",
".",
"create",
"(",
"NodeContentKinds",
".",
"toJsSanitizedContentCtorName",
"(",
"kind",
")",
")",
".",
"reference",
"(",
")",
";",
"... | Returns the js type for the sanitized content object corresponding to the given ContentKind. | [
"Returns",
"the",
"js",
"type",
"for",
"the",
"sanitized",
"content",
"object",
"corresponding",
"to",
"the",
"given",
"ContentKind",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsRuntime.java#L219-L221 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/JsRuntime.java | JsRuntime.symbolWithNamespace | private static Expression symbolWithNamespace(String requireSymbol, String fullyQualifiedSymbol) {
GoogRequire require = GoogRequire.create(requireSymbol);
if (fullyQualifiedSymbol.equals(require.symbol())) {
return require.reference();
}
String ident = fullyQualifiedSymbol.substring(require.symbol().length() + 1);
return require.dotAccess(ident);
} | java | private static Expression symbolWithNamespace(String requireSymbol, String fullyQualifiedSymbol) {
GoogRequire require = GoogRequire.create(requireSymbol);
if (fullyQualifiedSymbol.equals(require.symbol())) {
return require.reference();
}
String ident = fullyQualifiedSymbol.substring(require.symbol().length() + 1);
return require.dotAccess(ident);
} | [
"private",
"static",
"Expression",
"symbolWithNamespace",
"(",
"String",
"requireSymbol",
",",
"String",
"fullyQualifiedSymbol",
")",
"{",
"GoogRequire",
"require",
"=",
"GoogRequire",
".",
"create",
"(",
"requireSymbol",
")",
";",
"if",
"(",
"fullyQualifiedSymbol",
... | Returns a code chunk that accesses the given symbol.
@param requireSymbol The symbol to {@code goog.require}
@param fullyQualifiedSymbol The symbol we want to access. | [
"Returns",
"a",
"code",
"chunk",
"that",
"accesses",
"the",
"given",
"symbol",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsRuntime.java#L229-L236 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/IsComputableAsJsExprsVisitor.java | IsComputableAsJsExprsVisitor.areChildrenComputableAsJsExprs | private boolean areChildrenComputableAsJsExprs(ParentSoyNode<?> node) {
for (SoyNode child : node.getChildren()) {
if (canSkipChild(child)) {
continue;
}
if (!visit(child)) {
return false;
}
}
return true;
} | java | private boolean areChildrenComputableAsJsExprs(ParentSoyNode<?> node) {
for (SoyNode child : node.getChildren()) {
if (canSkipChild(child)) {
continue;
}
if (!visit(child)) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"areChildrenComputableAsJsExprs",
"(",
"ParentSoyNode",
"<",
"?",
">",
"node",
")",
"{",
"for",
"(",
"SoyNode",
"child",
":",
"node",
".",
"getChildren",
"(",
")",
")",
"{",
"if",
"(",
"canSkipChild",
"(",
"child",
")",
")",
"{",
"c... | Private helper to check whether all children of a given parent node satisfy
IsComputableAsJsExprsVisitor.
@param node The parent node whose children to check.
@return True if all children satisfy IsComputableAsJsExprsVisitor. | [
"Private",
"helper",
"to",
"check",
"whether",
"all",
"children",
"of",
"a",
"given",
"parent",
"node",
"satisfy",
"IsComputableAsJsExprsVisitor",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/IsComputableAsJsExprsVisitor.java#L231-L243 | train |
google/closure-templates | java/src/com/google/template/soy/SoyFileSetParser.java | SoyFileSetParser.parseWithVersions | private ParseResult parseWithVersions() throws IOException {
List<TemplateMetadata> templateMetadatas = new ArrayList<>();
for (CompilationUnitAndKind unit : compilationUnits()) {
templateMetadatas.addAll(
TemplateMetadataSerializer.templatesFromCompilationUnit(
unit.compilationUnit(),
unit.fileKind(),
typeRegistry(),
unit.filePath(),
errorReporter()));
}
IdGenerator nodeIdGen =
(cache() != null) ? cache().getNodeIdGenerator() : new IncrementingIdGenerator();
SoyFileSetNode soyTree = new SoyFileSetNode(nodeIdGen.genId(), nodeIdGen);
boolean filesWereSkipped = false;
// TODO(lukes): there are other places in the compiler (autoescaper) which may use the id
// generator but fail to lock on it. Eliminate the id system to avoid this whole issue.
synchronized (nodeIdGen) { // Avoid using the same ID generator in multiple threads.
for (SoyFileSupplier fileSupplier : soyFileSuppliers().values()) {
SoyFileSupplier.Version version = fileSupplier.getVersion();
VersionedFile cachedFile =
cache() != null ? cache().get(fileSupplier.getFilePath(), version) : null;
SoyFileNode node;
if (cachedFile == null) {
node = parseSoyFileHelper(fileSupplier, nodeIdGen);
// TODO(b/19269289): implement error recovery and keep on trucking in order to display
// as many errors as possible. Currently, the later passes just spew NPEs if run on
// a malformed parse tree.
if (node == null) {
filesWereSkipped = true;
continue;
}
// Run passes that are considered part of initial parsing.
passManager().runSingleFilePasses(node, nodeIdGen);
// Run passes that check the tree.
if (cache() != null) {
cache().put(fileSupplier.getFilePath(), VersionedFile.of(node, version));
}
} else {
node = cachedFile.file();
}
for (TemplateNode template : node.getChildren()) {
templateMetadatas.add(TemplateMetadata.fromTemplate(template));
}
soyTree.addChild(node);
}
TemplateRegistry registry = new TemplateRegistry(templateMetadatas, errorReporter());
// Run passes that check the tree iff we successfully parsed every file.
if (!filesWereSkipped) {
passManager().runWholeFilesetPasses(soyTree, registry);
}
return ParseResult.create(soyTree, registry);
}
} | java | private ParseResult parseWithVersions() throws IOException {
List<TemplateMetadata> templateMetadatas = new ArrayList<>();
for (CompilationUnitAndKind unit : compilationUnits()) {
templateMetadatas.addAll(
TemplateMetadataSerializer.templatesFromCompilationUnit(
unit.compilationUnit(),
unit.fileKind(),
typeRegistry(),
unit.filePath(),
errorReporter()));
}
IdGenerator nodeIdGen =
(cache() != null) ? cache().getNodeIdGenerator() : new IncrementingIdGenerator();
SoyFileSetNode soyTree = new SoyFileSetNode(nodeIdGen.genId(), nodeIdGen);
boolean filesWereSkipped = false;
// TODO(lukes): there are other places in the compiler (autoescaper) which may use the id
// generator but fail to lock on it. Eliminate the id system to avoid this whole issue.
synchronized (nodeIdGen) { // Avoid using the same ID generator in multiple threads.
for (SoyFileSupplier fileSupplier : soyFileSuppliers().values()) {
SoyFileSupplier.Version version = fileSupplier.getVersion();
VersionedFile cachedFile =
cache() != null ? cache().get(fileSupplier.getFilePath(), version) : null;
SoyFileNode node;
if (cachedFile == null) {
node = parseSoyFileHelper(fileSupplier, nodeIdGen);
// TODO(b/19269289): implement error recovery and keep on trucking in order to display
// as many errors as possible. Currently, the later passes just spew NPEs if run on
// a malformed parse tree.
if (node == null) {
filesWereSkipped = true;
continue;
}
// Run passes that are considered part of initial parsing.
passManager().runSingleFilePasses(node, nodeIdGen);
// Run passes that check the tree.
if (cache() != null) {
cache().put(fileSupplier.getFilePath(), VersionedFile.of(node, version));
}
} else {
node = cachedFile.file();
}
for (TemplateNode template : node.getChildren()) {
templateMetadatas.add(TemplateMetadata.fromTemplate(template));
}
soyTree.addChild(node);
}
TemplateRegistry registry = new TemplateRegistry(templateMetadatas, errorReporter());
// Run passes that check the tree iff we successfully parsed every file.
if (!filesWereSkipped) {
passManager().runWholeFilesetPasses(soyTree, registry);
}
return ParseResult.create(soyTree, registry);
}
} | [
"private",
"ParseResult",
"parseWithVersions",
"(",
")",
"throws",
"IOException",
"{",
"List",
"<",
"TemplateMetadata",
">",
"templateMetadatas",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"CompilationUnitAndKind",
"unit",
":",
"compilationUnits",
"... | Parses a set of Soy files, returning a structure containing the parse tree and template
registry. | [
"Parses",
"a",
"set",
"of",
"Soy",
"files",
"returning",
"a",
"structure",
"containing",
"the",
"parse",
"tree",
"and",
"template",
"registry",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSetParser.java#L166-L220 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/IsComputableAsPyExprVisitor.java | IsComputableAsPyExprVisitor.areChildrenComputableAsPyExprs | private boolean areChildrenComputableAsPyExprs(ParentSoyNode<?> node) {
for (SoyNode child : node.getChildren()) {
// Note: Save time by not visiting RawTextNode and PrintNode children.
if (!(child instanceof RawTextNode) && !(child instanceof PrintNode)) {
if (!visit(child)) {
return false;
}
}
}
return true;
} | java | private boolean areChildrenComputableAsPyExprs(ParentSoyNode<?> node) {
for (SoyNode child : node.getChildren()) {
// Note: Save time by not visiting RawTextNode and PrintNode children.
if (!(child instanceof RawTextNode) && !(child instanceof PrintNode)) {
if (!visit(child)) {
return false;
}
}
}
return true;
} | [
"private",
"boolean",
"areChildrenComputableAsPyExprs",
"(",
"ParentSoyNode",
"<",
"?",
">",
"node",
")",
"{",
"for",
"(",
"SoyNode",
"child",
":",
"node",
".",
"getChildren",
"(",
")",
")",
"{",
"// Note: Save time by not visiting RawTextNode and PrintNode children.",
... | Private helper to check whether all SoyNode children of a given parent node satisfy
IsComputableAsPyExprVisitor. ExprNode children are assumed to be computable as PyExprs.
@param node The parent node whose children to check.
@return True if all children satisfy IsComputableAsPyExprVisitor. | [
"Private",
"helper",
"to",
"check",
"whether",
"all",
"SoyNode",
"children",
"of",
"a",
"given",
"parent",
"node",
"satisfy",
"IsComputableAsPyExprVisitor",
".",
"ExprNode",
"children",
"are",
"assumed",
"to",
"be",
"computable",
"as",
"PyExprs",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/IsComputableAsPyExprVisitor.java#L178-L190 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java | InnerClasses.registerInnerClass | public TypeInfo registerInnerClass(String simpleName, int accessModifiers) {
classNames.claimName(simpleName);
TypeInfo innerClass = outer.innerClass(simpleName);
innerClassesAccessModifiers.put(innerClass, accessModifiers);
return innerClass;
} | java | public TypeInfo registerInnerClass(String simpleName, int accessModifiers) {
classNames.claimName(simpleName);
TypeInfo innerClass = outer.innerClass(simpleName);
innerClassesAccessModifiers.put(innerClass, accessModifiers);
return innerClass;
} | [
"public",
"TypeInfo",
"registerInnerClass",
"(",
"String",
"simpleName",
",",
"int",
"accessModifiers",
")",
"{",
"classNames",
".",
"claimName",
"(",
"simpleName",
")",
";",
"TypeInfo",
"innerClass",
"=",
"outer",
".",
"innerClass",
"(",
"simpleName",
")",
";",... | Register the given name as an inner class with the given access modifiers.
@return A {@link TypeInfo} with the full class name | [
"Register",
"the",
"given",
"name",
"as",
"an",
"inner",
"class",
"with",
"the",
"given",
"access",
"modifiers",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java#L51-L56 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java | InnerClasses.add | public void add(ClassData classData) {
checkRegistered(classData.type());
innerClasses.put(classData.type(), classData);
} | java | public void add(ClassData classData) {
checkRegistered(classData.type());
innerClasses.put(classData.type(), classData);
} | [
"public",
"void",
"add",
"(",
"ClassData",
"classData",
")",
"{",
"checkRegistered",
"(",
"classData",
".",
"type",
"(",
")",
")",
";",
"innerClasses",
".",
"put",
"(",
"classData",
".",
"type",
"(",
")",
",",
"classData",
")",
";",
"}"
] | Adds the data for an inner class.
@throws java.lang.IllegalArgumentException if the class wasn't previous registered via {@link
#registerInnerClass(String, int)} or {@link #registerInnerClassWithGeneratedName(String,
int)}. | [
"Adds",
"the",
"data",
"for",
"an",
"inner",
"class",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java#L78-L81 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java | InnerClasses.registerAsInnerClass | public void registerAsInnerClass(ClassVisitor visitor, TypeInfo innerClass) {
checkRegistered(innerClass);
doRegister(visitor, innerClass);
} | java | public void registerAsInnerClass(ClassVisitor visitor, TypeInfo innerClass) {
checkRegistered(innerClass);
doRegister(visitor, innerClass);
} | [
"public",
"void",
"registerAsInnerClass",
"(",
"ClassVisitor",
"visitor",
",",
"TypeInfo",
"innerClass",
")",
"{",
"checkRegistered",
"(",
"innerClass",
")",
";",
"doRegister",
"(",
"visitor",
",",
"innerClass",
")",
";",
"}"
] | Registers this factory as an inner class on the given class writer.
<p>Registering an inner class is confusing. The inner class needs to call this and so does the
outer class. Confirmed by running ASMIfier. Also, failure to call visitInnerClass on both
classes either breaks reflective apis (like class.getSimpleName()/getEnclosingClass), or causes
verifier errors (like IncompatibleClassChangeError). | [
"Registers",
"this",
"factory",
"as",
"an",
"inner",
"class",
"on",
"the",
"given",
"class",
"writer",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java#L97-L100 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java | InnerClasses.registerAllInnerClasses | public void registerAllInnerClasses(ClassVisitor visitor) {
for (Map.Entry<TypeInfo, Integer> entry : innerClassesAccessModifiers.entrySet()) {
TypeInfo innerClass = entry.getKey();
doRegister(visitor, innerClass);
}
} | java | public void registerAllInnerClasses(ClassVisitor visitor) {
for (Map.Entry<TypeInfo, Integer> entry : innerClassesAccessModifiers.entrySet()) {
TypeInfo innerClass = entry.getKey();
doRegister(visitor, innerClass);
}
} | [
"public",
"void",
"registerAllInnerClasses",
"(",
"ClassVisitor",
"visitor",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"TypeInfo",
",",
"Integer",
">",
"entry",
":",
"innerClassesAccessModifiers",
".",
"entrySet",
"(",
")",
")",
"{",
"TypeInfo",
"innerCl... | Registers all inner classes to the given outer class. | [
"Registers",
"all",
"inner",
"classes",
"to",
"the",
"given",
"outer",
"class",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java#L103-L108 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/restricted/SoyMsgBundleCompactor.java | SoyMsgBundleCompactor.compact | public SoyMsgBundle compact(SoyMsgBundle input) {
ImmutableList.Builder<SoyMsg> builder = ImmutableList.builder();
for (SoyMsg msg : input) {
ImmutableList<SoyMsgPart> parts = compactParts(msg.getParts());
builder.add(
SoyMsg.builder()
.setId(msg.getId())
.setLocaleString(msg.getLocaleString())
.setIsPlrselMsg(MsgPartUtils.hasPlrselPart(parts))
.setParts(parts)
.build());
}
return new RenderOnlySoyMsgBundleImpl(input.getLocaleString(), builder.build());
} | java | public SoyMsgBundle compact(SoyMsgBundle input) {
ImmutableList.Builder<SoyMsg> builder = ImmutableList.builder();
for (SoyMsg msg : input) {
ImmutableList<SoyMsgPart> parts = compactParts(msg.getParts());
builder.add(
SoyMsg.builder()
.setId(msg.getId())
.setLocaleString(msg.getLocaleString())
.setIsPlrselMsg(MsgPartUtils.hasPlrselPart(parts))
.setParts(parts)
.build());
}
return new RenderOnlySoyMsgBundleImpl(input.getLocaleString(), builder.build());
} | [
"public",
"SoyMsgBundle",
"compact",
"(",
"SoyMsgBundle",
"input",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"SoyMsg",
">",
"builder",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"for",
"(",
"SoyMsg",
"msg",
":",
"input",
")",
"{",
"Immutabl... | Returns a more memory-efficient version of the internal message bundle.
<p>Only enough information is retained for rendering; not enough for message extraction. As a
side effect, this SoyMsgBundleCompactor instance will also retain references to parts of the
messages in order to reuse identical objects. | [
"Returns",
"a",
"more",
"memory",
"-",
"efficient",
"version",
"of",
"the",
"internal",
"message",
"bundle",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/restricted/SoyMsgBundleCompactor.java#L57-L70 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/restricted/SoyMsgBundleCompactor.java | SoyMsgBundleCompactor.compactParts | private ImmutableList<SoyMsgPart> compactParts(ImmutableList<SoyMsgPart> parts) {
ImmutableList.Builder<SoyMsgPart> builder = ImmutableList.builder();
for (SoyMsgPart part : parts) {
builder.add(compactPart(part));
}
return builder.build();
} | java | private ImmutableList<SoyMsgPart> compactParts(ImmutableList<SoyMsgPart> parts) {
ImmutableList.Builder<SoyMsgPart> builder = ImmutableList.builder();
for (SoyMsgPart part : parts) {
builder.add(compactPart(part));
}
return builder.build();
} | [
"private",
"ImmutableList",
"<",
"SoyMsgPart",
">",
"compactParts",
"(",
"ImmutableList",
"<",
"SoyMsgPart",
">",
"parts",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"SoyMsgPart",
">",
"builder",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"for",... | Compacts a set of message parts. | [
"Compacts",
"a",
"set",
"of",
"message",
"parts",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/restricted/SoyMsgBundleCompactor.java#L73-L79 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/restricted/SoyMsgBundleCompactor.java | SoyMsgBundleCompactor.compactPart | private SoyMsgPart compactPart(SoyMsgPart part) {
if (part instanceof SoyMsgPluralPart) {
part = compactPlural((SoyMsgPluralPart) part);
} else if (part instanceof SoyMsgSelectPart) {
part = compactSelect((SoyMsgSelectPart) part);
} else if (part instanceof SoyMsgPlaceholderPart) {
part = compactPlaceholder((SoyMsgPlaceholderPart) part);
}
// Now intern the message part.
return intern(part);
} | java | private SoyMsgPart compactPart(SoyMsgPart part) {
if (part instanceof SoyMsgPluralPart) {
part = compactPlural((SoyMsgPluralPart) part);
} else if (part instanceof SoyMsgSelectPart) {
part = compactSelect((SoyMsgSelectPart) part);
} else if (part instanceof SoyMsgPlaceholderPart) {
part = compactPlaceholder((SoyMsgPlaceholderPart) part);
}
// Now intern the message part.
return intern(part);
} | [
"private",
"SoyMsgPart",
"compactPart",
"(",
"SoyMsgPart",
"part",
")",
"{",
"if",
"(",
"part",
"instanceof",
"SoyMsgPluralPart",
")",
"{",
"part",
"=",
"compactPlural",
"(",
"(",
"SoyMsgPluralPart",
")",
"part",
")",
";",
"}",
"else",
"if",
"(",
"part",
"... | Compacts a single message part.
<p>If the part is a plural/select part, it might be expanded into multiple parts. | [
"Compacts",
"a",
"single",
"message",
"part",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/restricted/SoyMsgBundleCompactor.java#L86-L96 | train |
google/closure-templates | java/src/com/google/template/soy/base/internal/UniqueNameGenerator.java | UniqueNameGenerator.claimName | public void claimName(String name) {
checkName(name);
if (names.add(name, 1) != 0) {
names.remove(name);
// give a slightly better error message in this case
if (reserved.contains(name)) {
throw new IllegalArgumentException("Tried to claim a reserved name: " + name);
}
throw new IllegalArgumentException("Name: " + name + " was already claimed!");
}
} | java | public void claimName(String name) {
checkName(name);
if (names.add(name, 1) != 0) {
names.remove(name);
// give a slightly better error message in this case
if (reserved.contains(name)) {
throw new IllegalArgumentException("Tried to claim a reserved name: " + name);
}
throw new IllegalArgumentException("Name: " + name + " was already claimed!");
}
} | [
"public",
"void",
"claimName",
"(",
"String",
"name",
")",
"{",
"checkName",
"(",
"name",
")",
";",
"if",
"(",
"names",
".",
"add",
"(",
"name",
",",
"1",
")",
"!=",
"0",
")",
"{",
"names",
".",
"remove",
"(",
"name",
")",
";",
"// give a slightly ... | Registers the name, throwing an IllegalArgumentException if it has already been registered. | [
"Registers",
"the",
"name",
"throwing",
"an",
"IllegalArgumentException",
"if",
"it",
"has",
"already",
"been",
"registered",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/internal/UniqueNameGenerator.java#L47-L57 | train |
google/closure-templates | java/src/com/google/template/soy/base/internal/UniqueNameGenerator.java | UniqueNameGenerator.reserve | public void reserve(String name) {
checkName(name);
// if this is new
if (reserved.add(name)) {
// add it to names, so that generateName will still work for reserved names (they will just
// get suffixes).
if (!names.add(name)) {
names.remove(name);
throw new IllegalArgumentException("newly reserved name: " + name + " was already used!");
}
}
} | java | public void reserve(String name) {
checkName(name);
// if this is new
if (reserved.add(name)) {
// add it to names, so that generateName will still work for reserved names (they will just
// get suffixes).
if (!names.add(name)) {
names.remove(name);
throw new IllegalArgumentException("newly reserved name: " + name + " was already used!");
}
}
} | [
"public",
"void",
"reserve",
"(",
"String",
"name",
")",
"{",
"checkName",
"(",
"name",
")",
";",
"// if this is new",
"if",
"(",
"reserved",
".",
"add",
"(",
"name",
")",
")",
"{",
"// add it to names, so that generateName will still work for reserved names (they wil... | Reserves the name, useful for keywords. | [
"Reserves",
"the",
"name",
"useful",
"for",
"keywords",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/internal/UniqueNameGenerator.java#L67-L78 | train |
google/closure-templates | java/src/com/google/template/soy/base/internal/UniqueNameGenerator.java | UniqueNameGenerator.generateName | public String generateName(String name) {
checkName(name);
names.add(name);
int count = names.count(name);
if (count == 1) {
return name;
}
return name + collisionSeparator + (count - 1);
} | java | public String generateName(String name) {
checkName(name);
names.add(name);
int count = names.count(name);
if (count == 1) {
return name;
}
return name + collisionSeparator + (count - 1);
} | [
"public",
"String",
"generateName",
"(",
"String",
"name",
")",
"{",
"checkName",
"(",
"name",
")",
";",
"names",
".",
"add",
"(",
"name",
")",
";",
"int",
"count",
"=",
"names",
".",
"count",
"(",
"name",
")",
";",
"if",
"(",
"count",
"==",
"1",
... | Returns a name based on the supplied one that is guaranteed to be unique among the names that
have been returned by this method. | [
"Returns",
"a",
"name",
"based",
"on",
"the",
"supplied",
"one",
"that",
"is",
"guaranteed",
"to",
"be",
"unique",
"among",
"the",
"names",
"that",
"have",
"been",
"returned",
"by",
"this",
"method",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/internal/UniqueNameGenerator.java#L84-L92 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java | GenJsCodeVisitor.addCodeToRequireCss | private static void addCodeToRequireCss(JsDoc.Builder header, SoyFileNode soyFile) {
SortedSet<String> requiredCssNamespaces = new TreeSet<>();
requiredCssNamespaces.addAll(soyFile.getRequiredCssNamespaces());
for (TemplateNode template : soyFile.getChildren()) {
requiredCssNamespaces.addAll(template.getRequiredCssNamespaces());
}
// NOTE: CSS requires in JS can only be done on a file by file basis at this time. Perhaps in
// the future, this might be supported per function.
for (String requiredCssNamespace : requiredCssNamespaces) {
header.addParameterizedAnnotation("requirecss", requiredCssNamespace);
}
} | java | private static void addCodeToRequireCss(JsDoc.Builder header, SoyFileNode soyFile) {
SortedSet<String> requiredCssNamespaces = new TreeSet<>();
requiredCssNamespaces.addAll(soyFile.getRequiredCssNamespaces());
for (TemplateNode template : soyFile.getChildren()) {
requiredCssNamespaces.addAll(template.getRequiredCssNamespaces());
}
// NOTE: CSS requires in JS can only be done on a file by file basis at this time. Perhaps in
// the future, this might be supported per function.
for (String requiredCssNamespace : requiredCssNamespaces) {
header.addParameterizedAnnotation("requirecss", requiredCssNamespace);
}
} | [
"private",
"static",
"void",
"addCodeToRequireCss",
"(",
"JsDoc",
".",
"Builder",
"header",
",",
"SoyFileNode",
"soyFile",
")",
"{",
"SortedSet",
"<",
"String",
">",
"requiredCssNamespaces",
"=",
"new",
"TreeSet",
"<>",
"(",
")",
";",
"requiredCssNamespaces",
".... | Appends requirecss jsdoc tags in the file header section.
@param soyFile The file with the templates.. | [
"Appends",
"requirecss",
"jsdoc",
"tags",
"in",
"the",
"file",
"header",
"section",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java#L487-L500 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java | GenJsCodeVisitor.generateFunctionBody | @CheckReturnValue
protected Statement generateFunctionBody(TemplateNode node, String alias) {
ImmutableList.Builder<Statement> bodyStatements = ImmutableList.builder();
bodyStatements.add(
Statement.assign(
JsRuntime.OPT_IJ_DATA,
id("opt_ijData_deprecated")
.or(JsRuntime.OPT_IJ_DATA, templateTranslationContext.codeGenerator())
.castAs("!soy.IjData")));
if (node instanceof TemplateElementNode) {
TemplateElementNode elementNode = (TemplateElementNode) node;
for (TemplateStateVar stateVar : elementNode.getStateVars()) {
Expression expr = getExprTranslator().exec(stateVar.defaultValue());
// A state variable can be something like ns.foo.FooProto|null. Without
// this cast, access to this variable can trigger JS conformance errors
// due to unknown type.
if (!stateVar.type().equals(stateVar.defaultValue().getType())) {
expr = expr.castAs(JsType.forJsSrc(stateVar.type()).typeExpr());
}
bodyStatements.add(VariableDeclaration.builder(stateVar.name()).setRhs(expr).build());
}
}
// Generate statement to ensure data is defined, if necessary.
if (new ShouldEnsureDataIsDefinedVisitor().exec(node)) {
bodyStatements.add(
assign(
OPT_DATA,
OPT_DATA.or(EMPTY_OBJECT_LITERAL, templateTranslationContext.codeGenerator())));
}
// Type check parameters.
bodyStatements.add(genParamTypeChecks(node, alias));
SanitizedContentKind kind = node.getContentKind();
if (isComputableAsJsExprsVisitor.exec(node)) {
// Case 1: The code style is 'concat' and the whole template body can be represented as JS
// expressions. We specially handle this case because we don't want to generate the variable
// 'output' at all. We simply concatenate the JS expressions and return the result.
List<Expression> templateBodyChunks = genJsExprsVisitor.exec(node);
if (kind == null) {
// The template is not strict. Thus, it may not apply an escaping directive to *every* print
// command, which means that some of its print commands could produce a number. Thus, there
// is a danger that a plus operator between two expressions in the list will do numeric
// addition instead of string concatenation. Furthermore, a non-strict template always needs
// to return a string, but if there is just one expression in the list, and we return it as
// is, we may not always produce a string (since an escaping directive may not be getting
// applied in that expression at all, or a directive might be getting applied that produces
// SanitizedContent). We thus call a method that makes sure to return an expression that
// produces a string and is in no danger of using numeric addition when concatenating the
// expressions in the list.
bodyStatements.add(returnValue(CodeChunkUtils.concatChunksForceString(templateBodyChunks)));
} else {
// The template is strict. Thus, it applies an escaping directive to *every* print command,
// which means that no print command produces a number, which means that there is no danger
// of a plus operator between two print commands doing numeric addition instead of string
// concatenation. And since a strict template needs to return SanitizedContent, it is ok to
// get an expression that produces SanitizedContent, which is indeed possible with an
// escaping directive that produces SanitizedContent. Thus, we do not have to be extra
// careful when concatenating the expressions in the list.
bodyStatements.add(
returnValue(sanitize(CodeChunkUtils.concatChunks(templateBodyChunks), kind)));
}
} else {
// Case 2: Normal case.
jsCodeBuilder.pushOutputVar("output");
Statement codeChunk = visitChildrenReturningCodeChunk(node);
jsCodeBuilder.popOutputVar();
bodyStatements.add(Statement.of(codeChunk, returnValue(sanitize(id("output"), kind))));
}
return Statement.of(bodyStatements.build());
} | java | @CheckReturnValue
protected Statement generateFunctionBody(TemplateNode node, String alias) {
ImmutableList.Builder<Statement> bodyStatements = ImmutableList.builder();
bodyStatements.add(
Statement.assign(
JsRuntime.OPT_IJ_DATA,
id("opt_ijData_deprecated")
.or(JsRuntime.OPT_IJ_DATA, templateTranslationContext.codeGenerator())
.castAs("!soy.IjData")));
if (node instanceof TemplateElementNode) {
TemplateElementNode elementNode = (TemplateElementNode) node;
for (TemplateStateVar stateVar : elementNode.getStateVars()) {
Expression expr = getExprTranslator().exec(stateVar.defaultValue());
// A state variable can be something like ns.foo.FooProto|null. Without
// this cast, access to this variable can trigger JS conformance errors
// due to unknown type.
if (!stateVar.type().equals(stateVar.defaultValue().getType())) {
expr = expr.castAs(JsType.forJsSrc(stateVar.type()).typeExpr());
}
bodyStatements.add(VariableDeclaration.builder(stateVar.name()).setRhs(expr).build());
}
}
// Generate statement to ensure data is defined, if necessary.
if (new ShouldEnsureDataIsDefinedVisitor().exec(node)) {
bodyStatements.add(
assign(
OPT_DATA,
OPT_DATA.or(EMPTY_OBJECT_LITERAL, templateTranslationContext.codeGenerator())));
}
// Type check parameters.
bodyStatements.add(genParamTypeChecks(node, alias));
SanitizedContentKind kind = node.getContentKind();
if (isComputableAsJsExprsVisitor.exec(node)) {
// Case 1: The code style is 'concat' and the whole template body can be represented as JS
// expressions. We specially handle this case because we don't want to generate the variable
// 'output' at all. We simply concatenate the JS expressions and return the result.
List<Expression> templateBodyChunks = genJsExprsVisitor.exec(node);
if (kind == null) {
// The template is not strict. Thus, it may not apply an escaping directive to *every* print
// command, which means that some of its print commands could produce a number. Thus, there
// is a danger that a plus operator between two expressions in the list will do numeric
// addition instead of string concatenation. Furthermore, a non-strict template always needs
// to return a string, but if there is just one expression in the list, and we return it as
// is, we may not always produce a string (since an escaping directive may not be getting
// applied in that expression at all, or a directive might be getting applied that produces
// SanitizedContent). We thus call a method that makes sure to return an expression that
// produces a string and is in no danger of using numeric addition when concatenating the
// expressions in the list.
bodyStatements.add(returnValue(CodeChunkUtils.concatChunksForceString(templateBodyChunks)));
} else {
// The template is strict. Thus, it applies an escaping directive to *every* print command,
// which means that no print command produces a number, which means that there is no danger
// of a plus operator between two print commands doing numeric addition instead of string
// concatenation. And since a strict template needs to return SanitizedContent, it is ok to
// get an expression that produces SanitizedContent, which is indeed possible with an
// escaping directive that produces SanitizedContent. Thus, we do not have to be extra
// careful when concatenating the expressions in the list.
bodyStatements.add(
returnValue(sanitize(CodeChunkUtils.concatChunks(templateBodyChunks), kind)));
}
} else {
// Case 2: Normal case.
jsCodeBuilder.pushOutputVar("output");
Statement codeChunk = visitChildrenReturningCodeChunk(node);
jsCodeBuilder.popOutputVar();
bodyStatements.add(Statement.of(codeChunk, returnValue(sanitize(id("output"), kind))));
}
return Statement.of(bodyStatements.build());
} | [
"@",
"CheckReturnValue",
"protected",
"Statement",
"generateFunctionBody",
"(",
"TemplateNode",
"node",
",",
"String",
"alias",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"Statement",
">",
"bodyStatements",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",... | Generates the function body. | [
"Generates",
"the",
"function",
"body",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java#L769-L841 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java | GenJsCodeVisitor.coerceTypeForSwitchComparison | private Expression coerceTypeForSwitchComparison(ExprRootNode expr) {
Expression switchOn = translateExpr(expr);
SoyType type = expr.getType();
// If the type is possibly a sanitized content type then we need to toString it.
if (SoyTypes.makeNullable(StringType.getInstance()).isAssignableFrom(type)
|| type.equals(AnyType.getInstance())
|| type.equals(UnknownType.getInstance())) {
CodeChunk.Generator codeGenerator = templateTranslationContext.codeGenerator();
Expression tmp = codeGenerator.declarationBuilder().setRhs(switchOn).build().ref();
return Expression.ifExpression(GOOG_IS_OBJECT.call(tmp), tmp.dotAccess("toString").call())
.setElse(tmp)
.build(codeGenerator);
}
// For everything else just pass through. switching on objects/collections is unlikely to
// have reasonably defined behavior.
return switchOn;
} | java | private Expression coerceTypeForSwitchComparison(ExprRootNode expr) {
Expression switchOn = translateExpr(expr);
SoyType type = expr.getType();
// If the type is possibly a sanitized content type then we need to toString it.
if (SoyTypes.makeNullable(StringType.getInstance()).isAssignableFrom(type)
|| type.equals(AnyType.getInstance())
|| type.equals(UnknownType.getInstance())) {
CodeChunk.Generator codeGenerator = templateTranslationContext.codeGenerator();
Expression tmp = codeGenerator.declarationBuilder().setRhs(switchOn).build().ref();
return Expression.ifExpression(GOOG_IS_OBJECT.call(tmp), tmp.dotAccess("toString").call())
.setElse(tmp)
.build(codeGenerator);
}
// For everything else just pass through. switching on objects/collections is unlikely to
// have reasonably defined behavior.
return switchOn;
} | [
"private",
"Expression",
"coerceTypeForSwitchComparison",
"(",
"ExprRootNode",
"expr",
")",
"{",
"Expression",
"switchOn",
"=",
"translateExpr",
"(",
"expr",
")",
";",
"SoyType",
"type",
"=",
"expr",
".",
"getType",
"(",
")",
";",
"// If the type is possibly a sanit... | to strings. | [
"to",
"strings",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java#L1092-L1108 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java | GenJsCodeVisitor.genParamsRecordType | private String genParamsRecordType(TemplateNode node) {
Set<String> paramNames = new HashSet<>();
// Generate members for explicit params.
Map<String, String> record = new LinkedHashMap<>();
for (TemplateParam param : node.getParams()) {
JsType jsType = getJsTypeForParamForDeclaration(param.type());
record.put(
param.name(), jsType.typeExprForRecordMember(/* isOptional= */ !param.isRequired()));
for (GoogRequire require : jsType.getGoogRequires()) {
// TODO(lukes): switch these to requireTypes
jsCodeBuilder.addGoogRequire(require);
}
paramNames.add(param.name());
}
// Do the same for indirect params, if we can find them.
// If there's a conflict between the explicitly-declared type, and the type
// inferred from the indirect params, then the explicit type wins.
// Also note that indirect param types may not be inferrable if the target
// is not in the current compilation file set.
IndirectParamsInfo ipi =
new IndirectParamsCalculator(templateRegistry)
.calculateIndirectParams(templateRegistry.getMetadata(node));
// If there are any calls outside of the file set, then we can't know
// the complete types of any indirect params. In such a case, we can simply
// omit the indirect params from the function type signature, since record
// types in JS allow additional undeclared fields to be present.
if (!ipi.mayHaveIndirectParamsInExternalCalls && !ipi.mayHaveIndirectParamsInExternalDelCalls) {
for (String indirectParamName : ipi.indirectParamTypes.keySet()) {
if (paramNames.contains(indirectParamName)) {
continue;
}
Collection<SoyType> paramTypes = ipi.indirectParamTypes.get(indirectParamName);
SoyType combinedType = SoyTypes.computeLowestCommonType(typeRegistry, paramTypes);
// Note that Union folds duplicate types and flattens unions, so if
// the combinedType is already a union this will do the right thing.
// TODO: detect cases where nullable is not needed (requires flow
// analysis to determine if the template is always called.)
SoyType indirectParamType =
typeRegistry.getOrCreateUnionType(combinedType, NullType.getInstance());
JsType jsType = getJsTypeForParamForDeclaration(indirectParamType);
// NOTE: we do not add goog.requires for indirect types. This is because it might introduce
// strict deps errors. This should be fine though since the transitive soy template that
// actually has the param will add them.
record.put(indirectParamName, jsType.typeExprForRecordMember(/* isOptional= */ true));
}
}
StringBuilder sb = new StringBuilder();
sb.append("{\n * ");
Joiner.on(",\n * ").withKeyValueSeparator(": ").appendTo(sb, record);
// trailing comma in record is important in case the last record member is the
// unknown type
sb.append(",\n * }");
return sb.toString();
} | java | private String genParamsRecordType(TemplateNode node) {
Set<String> paramNames = new HashSet<>();
// Generate members for explicit params.
Map<String, String> record = new LinkedHashMap<>();
for (TemplateParam param : node.getParams()) {
JsType jsType = getJsTypeForParamForDeclaration(param.type());
record.put(
param.name(), jsType.typeExprForRecordMember(/* isOptional= */ !param.isRequired()));
for (GoogRequire require : jsType.getGoogRequires()) {
// TODO(lukes): switch these to requireTypes
jsCodeBuilder.addGoogRequire(require);
}
paramNames.add(param.name());
}
// Do the same for indirect params, if we can find them.
// If there's a conflict between the explicitly-declared type, and the type
// inferred from the indirect params, then the explicit type wins.
// Also note that indirect param types may not be inferrable if the target
// is not in the current compilation file set.
IndirectParamsInfo ipi =
new IndirectParamsCalculator(templateRegistry)
.calculateIndirectParams(templateRegistry.getMetadata(node));
// If there are any calls outside of the file set, then we can't know
// the complete types of any indirect params. In such a case, we can simply
// omit the indirect params from the function type signature, since record
// types in JS allow additional undeclared fields to be present.
if (!ipi.mayHaveIndirectParamsInExternalCalls && !ipi.mayHaveIndirectParamsInExternalDelCalls) {
for (String indirectParamName : ipi.indirectParamTypes.keySet()) {
if (paramNames.contains(indirectParamName)) {
continue;
}
Collection<SoyType> paramTypes = ipi.indirectParamTypes.get(indirectParamName);
SoyType combinedType = SoyTypes.computeLowestCommonType(typeRegistry, paramTypes);
// Note that Union folds duplicate types and flattens unions, so if
// the combinedType is already a union this will do the right thing.
// TODO: detect cases where nullable is not needed (requires flow
// analysis to determine if the template is always called.)
SoyType indirectParamType =
typeRegistry.getOrCreateUnionType(combinedType, NullType.getInstance());
JsType jsType = getJsTypeForParamForDeclaration(indirectParamType);
// NOTE: we do not add goog.requires for indirect types. This is because it might introduce
// strict deps errors. This should be fine though since the transitive soy template that
// actually has the param will add them.
record.put(indirectParamName, jsType.typeExprForRecordMember(/* isOptional= */ true));
}
}
StringBuilder sb = new StringBuilder();
sb.append("{\n * ");
Joiner.on(",\n * ").withKeyValueSeparator(": ").appendTo(sb, record);
// trailing comma in record is important in case the last record member is the
// unknown type
sb.append(",\n * }");
return sb.toString();
} | [
"private",
"String",
"genParamsRecordType",
"(",
"TemplateNode",
"node",
")",
"{",
"Set",
"<",
"String",
">",
"paramNames",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"// Generate members for explicit params.",
"Map",
"<",
"String",
",",
"String",
">",
"record"... | Generate the JSDoc for the opt_data parameter. | [
"Generate",
"the",
"JSDoc",
"for",
"the",
"opt_data",
"parameter",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java#L1442-L1497 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java | GenJsCodeVisitor.genParamTypeChecks | @CheckReturnValue
protected Statement genParamTypeChecks(TemplateNode node, String alias) {
ImmutableList.Builder<Statement> declarations = ImmutableList.builder();
for (TemplateParam param : node.getAllParams()) {
String paramName = param.name();
SoyType paramType = param.type();
CodeChunk.Generator generator = templateTranslationContext.codeGenerator();
Expression paramChunk = genCodeForParamAccess(paramName, param);
JsType jsType = getJsTypeForParamTypeCheck(paramType);
// The opt_param.name value that will be type-tested.
String paramAlias = genParamAlias(paramName);
Expression coerced = jsType.getValueCoercion(paramChunk, generator);
if (coerced != null) {
// since we have coercion logic, dump into a temporary
paramChunk = generator.declarationBuilder().setRhs(coerced).build().ref();
}
if (param.hasDefault()) {
if (coerced == null) {
paramChunk = generator.declarationBuilder().setRhs(paramChunk).build().ref();
}
declarations.add(
genParamDefault(param, paramChunk, alias, jsType, /* declareStatic= */ true));
}
// The param value to assign
Expression value;
Optional<Expression> soyTypeAssertion =
jsType.getSoyTypeAssertion(paramChunk, paramName, generator);
// The type-cast expression.
if (soyTypeAssertion.isPresent()) {
value = soyTypeAssertion.get();
} else {
value = paramChunk;
}
VariableDeclaration.Builder declarationBuilder =
VariableDeclaration.builder(paramAlias)
.setRhs(value)
.setGoogRequires(jsType.getGoogRequires());
declarationBuilder.setJsDoc(
JsDoc.builder()
.addParameterizedAnnotation(
"type", getJsTypeForParamForDeclaration(paramType).typeExpr())
.build());
VariableDeclaration declaration = declarationBuilder.build();
declarations.add(declaration);
templateTranslationContext
.soyToJsVariableMappings()
// TODO(lukes): this should really be declartion.ref() but we cannot do that until
// everything is on the code chunk api.
.put(paramName, id(paramAlias));
}
return Statement.of(declarations.build());
} | java | @CheckReturnValue
protected Statement genParamTypeChecks(TemplateNode node, String alias) {
ImmutableList.Builder<Statement> declarations = ImmutableList.builder();
for (TemplateParam param : node.getAllParams()) {
String paramName = param.name();
SoyType paramType = param.type();
CodeChunk.Generator generator = templateTranslationContext.codeGenerator();
Expression paramChunk = genCodeForParamAccess(paramName, param);
JsType jsType = getJsTypeForParamTypeCheck(paramType);
// The opt_param.name value that will be type-tested.
String paramAlias = genParamAlias(paramName);
Expression coerced = jsType.getValueCoercion(paramChunk, generator);
if (coerced != null) {
// since we have coercion logic, dump into a temporary
paramChunk = generator.declarationBuilder().setRhs(coerced).build().ref();
}
if (param.hasDefault()) {
if (coerced == null) {
paramChunk = generator.declarationBuilder().setRhs(paramChunk).build().ref();
}
declarations.add(
genParamDefault(param, paramChunk, alias, jsType, /* declareStatic= */ true));
}
// The param value to assign
Expression value;
Optional<Expression> soyTypeAssertion =
jsType.getSoyTypeAssertion(paramChunk, paramName, generator);
// The type-cast expression.
if (soyTypeAssertion.isPresent()) {
value = soyTypeAssertion.get();
} else {
value = paramChunk;
}
VariableDeclaration.Builder declarationBuilder =
VariableDeclaration.builder(paramAlias)
.setRhs(value)
.setGoogRequires(jsType.getGoogRequires());
declarationBuilder.setJsDoc(
JsDoc.builder()
.addParameterizedAnnotation(
"type", getJsTypeForParamForDeclaration(paramType).typeExpr())
.build());
VariableDeclaration declaration = declarationBuilder.build();
declarations.add(declaration);
templateTranslationContext
.soyToJsVariableMappings()
// TODO(lukes): this should really be declartion.ref() but we cannot do that until
// everything is on the code chunk api.
.put(paramName, id(paramAlias));
}
return Statement.of(declarations.build());
} | [
"@",
"CheckReturnValue",
"protected",
"Statement",
"genParamTypeChecks",
"(",
"TemplateNode",
"node",
",",
"String",
"alias",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"Statement",
">",
"declarations",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"... | Generate code to verify the runtime types of the input params. Also typecasts the input
parameters and assigns them to local variables for use in the template.
@param node the template node. | [
"Generate",
"code",
"to",
"verify",
"the",
"runtime",
"types",
"of",
"the",
"input",
"params",
".",
"Also",
"typecasts",
"the",
"input",
"parameters",
"and",
"assigns",
"them",
"to",
"local",
"variables",
"for",
"use",
"in",
"the",
"template",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java#L1557-L1610 | train |
google/closure-templates | java/src/com/google/template/soy/passes/PluginResolver.java | PluginResolver.nullResolver | public static PluginResolver nullResolver(Mode mode, ErrorReporter reporter) {
return new PluginResolver(
mode, ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(), reporter);
} | java | public static PluginResolver nullResolver(Mode mode, ErrorReporter reporter) {
return new PluginResolver(
mode, ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(), reporter);
} | [
"public",
"static",
"PluginResolver",
"nullResolver",
"(",
"Mode",
"mode",
",",
"ErrorReporter",
"reporter",
")",
"{",
"return",
"new",
"PluginResolver",
"(",
"mode",
",",
"ImmutableMap",
".",
"of",
"(",
")",
",",
"ImmutableMap",
".",
"of",
"(",
")",
",",
... | Returns an empty resolver. Useful for tests, or situations where it is known that no plugins
will be needed. | [
"Returns",
"an",
"empty",
"resolver",
".",
"Useful",
"for",
"tests",
"or",
"situations",
"where",
"it",
"is",
"known",
"that",
"no",
"plugins",
"will",
"be",
"needed",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/PluginResolver.java#L48-L51 | train |
google/closure-templates | java/src/com/google/template/soy/passes/PluginResolver.java | PluginResolver.lookupPrintDirective | public SoyPrintDirective lookupPrintDirective(String name, int numArgs, SourceLocation location) {
SoyPrintDirective soyPrintDirective = printDirectives.get(name);
if (soyPrintDirective == null) {
reportMissing(location, "print directive", name, printDirectives.keySet());
soyPrintDirective = createPlaceholderPrintDirective(name, numArgs);
}
checkNumArgs("print directive", soyPrintDirective.getValidArgsSizes(), numArgs, location);
warnIfDeprecated(name, soyPrintDirective, location);
return soyPrintDirective;
} | java | public SoyPrintDirective lookupPrintDirective(String name, int numArgs, SourceLocation location) {
SoyPrintDirective soyPrintDirective = printDirectives.get(name);
if (soyPrintDirective == null) {
reportMissing(location, "print directive", name, printDirectives.keySet());
soyPrintDirective = createPlaceholderPrintDirective(name, numArgs);
}
checkNumArgs("print directive", soyPrintDirective.getValidArgsSizes(), numArgs, location);
warnIfDeprecated(name, soyPrintDirective, location);
return soyPrintDirective;
} | [
"public",
"SoyPrintDirective",
"lookupPrintDirective",
"(",
"String",
"name",
",",
"int",
"numArgs",
",",
"SourceLocation",
"location",
")",
"{",
"SoyPrintDirective",
"soyPrintDirective",
"=",
"printDirectives",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"soyPr... | Returns a print directive with the given name and arity.
<p>An error will be reported according to the current {@link Mode} and a placeholder function
will be returned if it cannot be found. | [
"Returns",
"a",
"print",
"directive",
"with",
"the",
"given",
"name",
"and",
"arity",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/PluginResolver.java#L177-L186 | train |
google/closure-templates | java/src/com/google/template/soy/passes/PluginResolver.java | PluginResolver.lookupSoyFunction | public Object lookupSoyFunction(String name, int numArgs, SourceLocation location) {
Object soyFunction = functions.get(name);
if (soyFunction == null) {
reportMissing(location, "function", name, functions.keySet());
return ERROR_PLACEHOLDER_FUNCTION;
}
Set<Integer> validArgsSize;
if (soyFunction instanceof SoyFunction) {
validArgsSize = ((SoyFunction) soyFunction).getValidArgsSizes();
} else {
validArgsSize =
getValidArgsSizes(
soyFunction.getClass().getAnnotation(SoyFunctionSignature.class).value());
}
checkNumArgs("function", validArgsSize, numArgs, location);
warnIfDeprecated(name, soyFunction, location);
return soyFunction;
} | java | public Object lookupSoyFunction(String name, int numArgs, SourceLocation location) {
Object soyFunction = functions.get(name);
if (soyFunction == null) {
reportMissing(location, "function", name, functions.keySet());
return ERROR_PLACEHOLDER_FUNCTION;
}
Set<Integer> validArgsSize;
if (soyFunction instanceof SoyFunction) {
validArgsSize = ((SoyFunction) soyFunction).getValidArgsSizes();
} else {
validArgsSize =
getValidArgsSizes(
soyFunction.getClass().getAnnotation(SoyFunctionSignature.class).value());
}
checkNumArgs("function", validArgsSize, numArgs, location);
warnIfDeprecated(name, soyFunction, location);
return soyFunction;
} | [
"public",
"Object",
"lookupSoyFunction",
"(",
"String",
"name",
",",
"int",
"numArgs",
",",
"SourceLocation",
"location",
")",
"{",
"Object",
"soyFunction",
"=",
"functions",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"soyFunction",
"==",
"null",
")",
"... | Returns a function with the given name and arity.
<p>An error will be reported according to the current {@link Mode} and a placeholder function
will be returned if it cannot be found. | [
"Returns",
"a",
"function",
"with",
"the",
"given",
"name",
"and",
"arity",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/PluginResolver.java#L194-L211 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/PrintDirectiveNode.java | PrintDirectiveNode.setPrintDirective | public void setPrintDirective(SoyPrintDirective printDirective) {
checkState(this.printDirective == null, "setPrintDirective has already been called");
checkArgument(name.identifier().equals(printDirective.getName()));
this.printDirective = checkNotNull(printDirective);
} | java | public void setPrintDirective(SoyPrintDirective printDirective) {
checkState(this.printDirective == null, "setPrintDirective has already been called");
checkArgument(name.identifier().equals(printDirective.getName()));
this.printDirective = checkNotNull(printDirective);
} | [
"public",
"void",
"setPrintDirective",
"(",
"SoyPrintDirective",
"printDirective",
")",
"{",
"checkState",
"(",
"this",
".",
"printDirective",
"==",
"null",
",",
"\"setPrintDirective has already been called\"",
")",
";",
"checkArgument",
"(",
"name",
".",
"identifier",
... | Sets the print directive. | [
"Sets",
"the",
"print",
"directive",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/PrintDirectiveNode.java#L142-L146 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/LocalVariableStack.java | LocalVariableStack.addVariable | LocalVariableStack addVariable(String name, PyExpr varExpression) {
Preconditions.checkState(!localVarExprs.isEmpty());
localVarExprs.peek().put(name, varExpression);
return this;
} | java | LocalVariableStack addVariable(String name, PyExpr varExpression) {
Preconditions.checkState(!localVarExprs.isEmpty());
localVarExprs.peek().put(name, varExpression);
return this;
} | [
"LocalVariableStack",
"addVariable",
"(",
"String",
"name",
",",
"PyExpr",
"varExpression",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"!",
"localVarExprs",
".",
"isEmpty",
"(",
")",
")",
";",
"localVarExprs",
".",
"peek",
"(",
")",
".",
"put",
"(",
... | Adds a variable to the current reference frame.
@param name The name of the variable as used by calling expressions.
@param varExpression The underlying expression used to access the variable.
@return A reference to this object. | [
"Adds",
"a",
"variable",
"to",
"the",
"current",
"reference",
"frame",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/LocalVariableStack.java#L56-L60 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.derive | public Context derive(HtmlContext state) {
return state == this.state ? this : toBuilder().withState(state).build();
} | java | public Context derive(HtmlContext state) {
return state == this.state ? this : toBuilder().withState(state).build();
} | [
"public",
"Context",
"derive",
"(",
"HtmlContext",
"state",
")",
"{",
"return",
"state",
"==",
"this",
".",
"state",
"?",
"this",
":",
"toBuilder",
"(",
")",
".",
"withState",
"(",
"state",
")",
".",
"build",
"(",
")",
";",
"}"
] | Returns a context that differs only in the state. | [
"Returns",
"a",
"context",
"that",
"differs",
"only",
"in",
"the",
"state",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L210-L212 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.derive | public Context derive(JsFollowingSlash slashType) {
return slashType == this.slashType ? this : toBuilder().withSlashType(slashType).build();
} | java | public Context derive(JsFollowingSlash slashType) {
return slashType == this.slashType ? this : toBuilder().withSlashType(slashType).build();
} | [
"public",
"Context",
"derive",
"(",
"JsFollowingSlash",
"slashType",
")",
"{",
"return",
"slashType",
"==",
"this",
".",
"slashType",
"?",
"this",
":",
"toBuilder",
"(",
")",
".",
"withSlashType",
"(",
"slashType",
")",
".",
"build",
"(",
")",
";",
"}"
] | Returns a context that differs only in the following slash. | [
"Returns",
"a",
"context",
"that",
"differs",
"only",
"in",
"the",
"following",
"slash",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L215-L217 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.derive | public Context derive(UriPart uriPart) {
return uriPart == this.uriPart ? this : toBuilder().withUriPart(uriPart).build();
} | java | public Context derive(UriPart uriPart) {
return uriPart == this.uriPart ? this : toBuilder().withUriPart(uriPart).build();
} | [
"public",
"Context",
"derive",
"(",
"UriPart",
"uriPart",
")",
"{",
"return",
"uriPart",
"==",
"this",
".",
"uriPart",
"?",
"this",
":",
"toBuilder",
"(",
")",
".",
"withUriPart",
"(",
"uriPart",
")",
".",
"build",
"(",
")",
";",
"}"
] | Returns a context that differs only in the uri part. | [
"Returns",
"a",
"context",
"that",
"differs",
"only",
"in",
"the",
"uri",
"part",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L220-L222 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.derive | public Context derive(HtmlHtmlAttributePosition htmlHtmlAttributePosition) {
return htmlHtmlAttributePosition == this.htmlHtmlAttributePosition
? this
: toBuilder().withHtmlHtmlAttributePosition(htmlHtmlAttributePosition).build();
} | java | public Context derive(HtmlHtmlAttributePosition htmlHtmlAttributePosition) {
return htmlHtmlAttributePosition == this.htmlHtmlAttributePosition
? this
: toBuilder().withHtmlHtmlAttributePosition(htmlHtmlAttributePosition).build();
} | [
"public",
"Context",
"derive",
"(",
"HtmlHtmlAttributePosition",
"htmlHtmlAttributePosition",
")",
"{",
"return",
"htmlHtmlAttributePosition",
"==",
"this",
".",
"htmlHtmlAttributePosition",
"?",
"this",
":",
"toBuilder",
"(",
")",
".",
"withHtmlHtmlAttributePosition",
"(... | Returns a context that differs only in the HTML attribute containing HTML position. | [
"Returns",
"a",
"context",
"that",
"differs",
"only",
"in",
"the",
"HTML",
"attribute",
"containing",
"HTML",
"position",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L225-L229 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.getContextAfterDynamicValue | public Context getContextAfterDynamicValue() {
// TODO: If the context is JS, perhaps this should return JsFollowingSlash.UNKNOWN. Right now
// we assume that the dynamic value is also an expression, but JsFollowingSlash.UNKNOWN would
// account for things that end in semicolons (since the next slash could be either a regex OR a
// division op).
if (state == HtmlContext.JS) {
switch (slashType) {
case DIV_OP:
case UNKNOWN:
return this;
case REGEX:
return derive(JsFollowingSlash.DIV_OP);
case NONE:
throw new IllegalStateException(slashType.name());
}
} else if (state == HtmlContext.HTML_BEFORE_OPEN_TAG_NAME
|| state == HtmlContext.HTML_BEFORE_CLOSE_TAG_NAME) {
// We assume ElementType.NORMAL, because filterHtmlElementName filters dangerous tag names.
return toBuilder()
.withState(HtmlContext.HTML_TAG_NAME)
.withElType(ElementType.NORMAL)
.build();
} else if (state == HtmlContext.HTML_TAG) {
// To handle a substitution that starts an attribute name <tag {$attrName}=...>
return toBuilder()
.withState(HtmlContext.HTML_ATTRIBUTE_NAME)
.withAttrType(AttributeType.PLAIN_TEXT)
.build();
} else if (uriPart == UriPart.START) {
if (uriType == UriType.TRUSTED_RESOURCE) {
return derive(UriPart.AUTHORITY_OR_PATH);
}
return derive(UriPart.MAYBE_VARIABLE_SCHEME);
}
return this;
} | java | public Context getContextAfterDynamicValue() {
// TODO: If the context is JS, perhaps this should return JsFollowingSlash.UNKNOWN. Right now
// we assume that the dynamic value is also an expression, but JsFollowingSlash.UNKNOWN would
// account for things that end in semicolons (since the next slash could be either a regex OR a
// division op).
if (state == HtmlContext.JS) {
switch (slashType) {
case DIV_OP:
case UNKNOWN:
return this;
case REGEX:
return derive(JsFollowingSlash.DIV_OP);
case NONE:
throw new IllegalStateException(slashType.name());
}
} else if (state == HtmlContext.HTML_BEFORE_OPEN_TAG_NAME
|| state == HtmlContext.HTML_BEFORE_CLOSE_TAG_NAME) {
// We assume ElementType.NORMAL, because filterHtmlElementName filters dangerous tag names.
return toBuilder()
.withState(HtmlContext.HTML_TAG_NAME)
.withElType(ElementType.NORMAL)
.build();
} else if (state == HtmlContext.HTML_TAG) {
// To handle a substitution that starts an attribute name <tag {$attrName}=...>
return toBuilder()
.withState(HtmlContext.HTML_ATTRIBUTE_NAME)
.withAttrType(AttributeType.PLAIN_TEXT)
.build();
} else if (uriPart == UriPart.START) {
if (uriType == UriType.TRUSTED_RESOURCE) {
return derive(UriPart.AUTHORITY_OR_PATH);
}
return derive(UriPart.MAYBE_VARIABLE_SCHEME);
}
return this;
} | [
"public",
"Context",
"getContextAfterDynamicValue",
"(",
")",
"{",
"// TODO: If the context is JS, perhaps this should return JsFollowingSlash.UNKNOWN. Right now",
"// we assume that the dynamic value is also an expression, but JsFollowingSlash.UNKNOWN would",
"// account for things that end in semi... | The context after printing a correctly-escaped dynamic value in this context.
<p>This makes the optimistic assumption that the escaped string is not empty. This can lead to
correctness behaviors, but the default is to fail closed; for example, printing an empty string
at UriPart.START switches to MAYBE_VARIABLE_SCHEME, which is designed not to trust the printed
value anyway. Same in JS -- we might switch to DIV_OP when we should have stayed in REGEX, but
in the worse case, we'll just produce JavaScript that doesn't compile (which is safe). | [
"The",
"context",
"after",
"printing",
"a",
"correctly",
"-",
"escaped",
"dynamic",
"value",
"in",
"this",
"context",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L245-L280 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.computeContextAfterAttributeDelimiter | static Context computeContextAfterAttributeDelimiter(
ElementType elType,
AttributeType attrType,
AttributeEndDelimiter delim,
UriType uriType,
int templateNestDepth) {
HtmlContext state;
JsFollowingSlash slash = JsFollowingSlash.NONE;
UriPart uriPart = UriPart.NONE;
switch (attrType) {
case PLAIN_TEXT:
state = HtmlContext.HTML_NORMAL_ATTR_VALUE;
break;
case SCRIPT:
state = HtmlContext.JS;
// Start a JS block in a regex state since
// /foo/.test(str) && doSideEffect();
// which starts with a regular expression literal is a valid and possibly useful program,
// but there is no valid program which starts with a division operator.
slash = JsFollowingSlash.REGEX;
break;
case STYLE:
state = HtmlContext.CSS;
break;
case HTML:
state = HtmlContext.HTML_HTML_ATTR_VALUE;
break;
case META_REFRESH_CONTENT:
state = HtmlContext.HTML_META_REFRESH_CONTENT;
break;
case URI:
state = HtmlContext.URI;
uriPart = UriPart.START;
break;
// NONE is not a valid AttributeType inside an attribute value.
default:
throw new AssertionError("Unexpected attribute type " + attrType);
}
Preconditions.checkArgument(
(uriType != UriType.NONE) == (attrType == AttributeType.URI),
"uriType=%s but attrType=%s",
uriType,
attrType);
return new Context(
state,
elType,
attrType,
delim,
slash,
uriPart,
uriType,
HtmlHtmlAttributePosition.NONE,
templateNestDepth,
0);
} | java | static Context computeContextAfterAttributeDelimiter(
ElementType elType,
AttributeType attrType,
AttributeEndDelimiter delim,
UriType uriType,
int templateNestDepth) {
HtmlContext state;
JsFollowingSlash slash = JsFollowingSlash.NONE;
UriPart uriPart = UriPart.NONE;
switch (attrType) {
case PLAIN_TEXT:
state = HtmlContext.HTML_NORMAL_ATTR_VALUE;
break;
case SCRIPT:
state = HtmlContext.JS;
// Start a JS block in a regex state since
// /foo/.test(str) && doSideEffect();
// which starts with a regular expression literal is a valid and possibly useful program,
// but there is no valid program which starts with a division operator.
slash = JsFollowingSlash.REGEX;
break;
case STYLE:
state = HtmlContext.CSS;
break;
case HTML:
state = HtmlContext.HTML_HTML_ATTR_VALUE;
break;
case META_REFRESH_CONTENT:
state = HtmlContext.HTML_META_REFRESH_CONTENT;
break;
case URI:
state = HtmlContext.URI;
uriPart = UriPart.START;
break;
// NONE is not a valid AttributeType inside an attribute value.
default:
throw new AssertionError("Unexpected attribute type " + attrType);
}
Preconditions.checkArgument(
(uriType != UriType.NONE) == (attrType == AttributeType.URI),
"uriType=%s but attrType=%s",
uriType,
attrType);
return new Context(
state,
elType,
attrType,
delim,
slash,
uriPart,
uriType,
HtmlHtmlAttributePosition.NONE,
templateNestDepth,
0);
} | [
"static",
"Context",
"computeContextAfterAttributeDelimiter",
"(",
"ElementType",
"elType",
",",
"AttributeType",
"attrType",
",",
"AttributeEndDelimiter",
"delim",
",",
"UriType",
"uriType",
",",
"int",
"templateNestDepth",
")",
"{",
"HtmlContext",
"state",
";",
"JsFol... | Computes the context after an attribute delimiter is seen.
@param elType The type of element whose tag the attribute appears in.
@param attrType The type of attribute whose value the delimiter starts.
@param delim The type of delimiter that will mark the end of the attribute value.
@param templateNestDepth The number of (@code <template>} elements on the open element stack.
@return A context suitable for the start of the attribute value. | [
"Computes",
"the",
"context",
"after",
"an",
"attribute",
"delimiter",
"is",
"seen",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L291-L345 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.getMsgEscapingStrategy | Optional<MsgEscapingStrategy> getMsgEscapingStrategy(SoyNode node) {
switch (state) {
case HTML_PCDATA:
// In normal HTML PCDATA context, it makes sense to escape all of the print nodes, but not
// escape the entire message. This allows Soy to support putting anchors and other small
// bits of HTML in messages.
return Optional.of(new MsgEscapingStrategy(this, ImmutableList.of()));
case CSS_DQ_STRING:
case CSS_SQ_STRING:
case JS_DQ_STRING:
case JS_SQ_STRING:
case TEXT:
case URI:
if (state == HtmlContext.URI && uriPart != UriPart.QUERY) {
// NOTE: Only support the query portion of URIs.
return Optional.absent();
}
// In other contexts like JS and CSS strings, it makes sense to treat the message's
// placeholders as plain text, but escape the entire result of message evaluation.
return Optional.of(
new MsgEscapingStrategy(
new Context(HtmlContext.TEXT), getEscapingModes(node, ImmutableList.of())));
case HTML_RCDATA:
case HTML_NORMAL_ATTR_VALUE:
case HTML_COMMENT:
// The weirdest case is HTML attributes. Ideally, we'd like to treat these as a text string
// and escape when done. However, many messages have HTML entities such as » in them.
// A good way around this is to escape the print nodes in the message, but normalize
// (escape except for ampersands) the final message.
// Also, content inside <title>, <textarea>, and HTML comments have a similar requirement,
// where any entities in the messages are probably intended to be preserved.
return Optional.of(
new MsgEscapingStrategy(this, ImmutableList.of(EscapingMode.NORMALIZE_HTML)));
default:
// Other contexts, primarily source code contexts, don't have a meaningful way to support
// natural language text.
return Optional.absent();
}
} | java | Optional<MsgEscapingStrategy> getMsgEscapingStrategy(SoyNode node) {
switch (state) {
case HTML_PCDATA:
// In normal HTML PCDATA context, it makes sense to escape all of the print nodes, but not
// escape the entire message. This allows Soy to support putting anchors and other small
// bits of HTML in messages.
return Optional.of(new MsgEscapingStrategy(this, ImmutableList.of()));
case CSS_DQ_STRING:
case CSS_SQ_STRING:
case JS_DQ_STRING:
case JS_SQ_STRING:
case TEXT:
case URI:
if (state == HtmlContext.URI && uriPart != UriPart.QUERY) {
// NOTE: Only support the query portion of URIs.
return Optional.absent();
}
// In other contexts like JS and CSS strings, it makes sense to treat the message's
// placeholders as plain text, but escape the entire result of message evaluation.
return Optional.of(
new MsgEscapingStrategy(
new Context(HtmlContext.TEXT), getEscapingModes(node, ImmutableList.of())));
case HTML_RCDATA:
case HTML_NORMAL_ATTR_VALUE:
case HTML_COMMENT:
// The weirdest case is HTML attributes. Ideally, we'd like to treat these as a text string
// and escape when done. However, many messages have HTML entities such as » in them.
// A good way around this is to escape the print nodes in the message, but normalize
// (escape except for ampersands) the final message.
// Also, content inside <title>, <textarea>, and HTML comments have a similar requirement,
// where any entities in the messages are probably intended to be preserved.
return Optional.of(
new MsgEscapingStrategy(this, ImmutableList.of(EscapingMode.NORMALIZE_HTML)));
default:
// Other contexts, primarily source code contexts, don't have a meaningful way to support
// natural language text.
return Optional.absent();
}
} | [
"Optional",
"<",
"MsgEscapingStrategy",
">",
"getMsgEscapingStrategy",
"(",
"SoyNode",
"node",
")",
"{",
"switch",
"(",
"state",
")",
"{",
"case",
"HTML_PCDATA",
":",
"// In normal HTML PCDATA context, it makes sense to escape all of the print nodes, but not",
"// escape the en... | Determines the strategy to escape Soy msg tags.
<p>Importantly, this determines the context that the message should be considered in, how the
print nodes will be escaped, and how the entire message will be escaped. We need different
strategies in different contexts because messages in general aren't trusted, but we also need
to be able to include markup interspersed in an HTML message; for example, an anchor that Soy
factored out of the message.
<p>Note that it'd be very nice to be able to simply escape the strings that came out of the
translation database, and distribute the escaping entirely over the print nodes. However, the
translation machinery, especially in Javascript, doesn't offer a way to escape just the bits
that come from the translation database without also re-escaping the substitutions.
@param node The node, for error messages
@return relevant strategy, or absent in case there's no valid strategy and it is an error to
have a message in this context | [
"Determines",
"the",
"strategy",
"to",
"escape",
"Soy",
"msg",
"tags",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L557-L598 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.isCompatibleWith | public boolean isCompatibleWith(EscapingMode mode) {
// TODO: Come up with a compatibility matrix.
if (mode == EscapingMode.ESCAPE_JS_VALUE) {
// Don't introduce quotes inside a string.
switch (state) {
case JS_SQ_STRING:
case JS_DQ_STRING:
case CSS_SQ_STRING:
case CSS_DQ_STRING:
return false;
default:
return true;
}
} else if (mode == EscapingMode.TEXT) {
// The TEXT directive may only be used in TEXT mode; in any other context, it would act as
// autoescape-cancelling.
return state == HtmlContext.TEXT;
} else if (delimType == AttributeEndDelimiter.SPACE_OR_TAG_END) {
// Need ESCAPE_HTML_ATTRIBUTE_NOSPACE instead.
if (mode == EscapingMode.ESCAPE_HTML
|| mode == EscapingMode.ESCAPE_HTML_ATTRIBUTE
|| mode == EscapingMode.ESCAPE_HTML_RCDATA) {
return false;
}
}
return true;
} | java | public boolean isCompatibleWith(EscapingMode mode) {
// TODO: Come up with a compatibility matrix.
if (mode == EscapingMode.ESCAPE_JS_VALUE) {
// Don't introduce quotes inside a string.
switch (state) {
case JS_SQ_STRING:
case JS_DQ_STRING:
case CSS_SQ_STRING:
case CSS_DQ_STRING:
return false;
default:
return true;
}
} else if (mode == EscapingMode.TEXT) {
// The TEXT directive may only be used in TEXT mode; in any other context, it would act as
// autoescape-cancelling.
return state == HtmlContext.TEXT;
} else if (delimType == AttributeEndDelimiter.SPACE_OR_TAG_END) {
// Need ESCAPE_HTML_ATTRIBUTE_NOSPACE instead.
if (mode == EscapingMode.ESCAPE_HTML
|| mode == EscapingMode.ESCAPE_HTML_ATTRIBUTE
|| mode == EscapingMode.ESCAPE_HTML_RCDATA) {
return false;
}
}
return true;
} | [
"public",
"boolean",
"isCompatibleWith",
"(",
"EscapingMode",
"mode",
")",
"{",
"// TODO: Come up with a compatibility matrix.",
"if",
"(",
"mode",
"==",
"EscapingMode",
".",
"ESCAPE_JS_VALUE",
")",
"{",
"// Don't introduce quotes inside a string.",
"switch",
"(",
"state",
... | True if the given escaping mode could make sense in this context. | [
"True",
"if",
"the",
"given",
"escaping",
"mode",
"could",
"make",
"sense",
"in",
"this",
"context",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L601-L627 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.packedBits | public int packedBits() {
int bits = templateNestDepth;
bits = (bits << N_URI_TYPE_BITS) | uriType.ordinal();
bits = (bits << N_URI_PART_BITS) | uriPart.ordinal();
bits = (bits << N_JS_SLASH_BITS) | slashType.ordinal();
bits = (bits << N_DELIM_BITS) | delimType.ordinal();
bits = (bits << N_ATTR_BITS) | attrType.ordinal();
bits = (bits << N_ELEMENT_BITS) | elType.ordinal();
bits = (bits << N_STATE_BITS) | state.ordinal();
return bits;
} | java | public int packedBits() {
int bits = templateNestDepth;
bits = (bits << N_URI_TYPE_BITS) | uriType.ordinal();
bits = (bits << N_URI_PART_BITS) | uriPart.ordinal();
bits = (bits << N_JS_SLASH_BITS) | slashType.ordinal();
bits = (bits << N_DELIM_BITS) | delimType.ordinal();
bits = (bits << N_ATTR_BITS) | attrType.ordinal();
bits = (bits << N_ELEMENT_BITS) | elType.ordinal();
bits = (bits << N_STATE_BITS) | state.ordinal();
return bits;
} | [
"public",
"int",
"packedBits",
"(",
")",
"{",
"int",
"bits",
"=",
"templateNestDepth",
";",
"bits",
"=",
"(",
"bits",
"<<",
"N_URI_TYPE_BITS",
")",
"|",
"uriType",
".",
"ordinal",
"(",
")",
";",
"bits",
"=",
"(",
"bits",
"<<",
"N_URI_PART_BITS",
")",
"... | An integer form that uniquely identifies this context. This form is not guaranteed to be stable
across versions, so do not use as a long-lived serialized form. | [
"An",
"integer",
"form",
"that",
"uniquely",
"identifies",
"this",
"context",
".",
"This",
"form",
"is",
"not",
"guaranteed",
"to",
"be",
"stable",
"across",
"versions",
"so",
"do",
"not",
"use",
"as",
"a",
"long",
"-",
"lived",
"serialized",
"form",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L660-L670 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.unionUriParts | private static UriPart unionUriParts(UriPart a, UriPart b) {
Preconditions.checkArgument(a != b);
if (a == UriPart.DANGEROUS_SCHEME || b == UriPart.DANGEROUS_SCHEME) {
// Dangerous schemes (like javascript:) are poison -- if either side is dangerous, the whole
// thing is.
return UriPart.DANGEROUS_SCHEME;
} else if (a == UriPart.FRAGMENT
|| b == UriPart.FRAGMENT
|| a == UriPart.UNKNOWN
|| b == UriPart.UNKNOWN) {
// UNKNOWN means one part is in the #fragment and one is not. This is the case if one is
// FRAGMENT and the other is not, or if one of the branches was UNKNOWN to begin with.
return UriPart.UNKNOWN;
} else if ((a == UriPart.MAYBE_VARIABLE_SCHEME || b == UriPart.MAYBE_VARIABLE_SCHEME)
&& a != UriPart.UNKNOWN_PRE_FRAGMENT
&& b != UriPart.UNKNOWN_PRE_FRAGMENT) {
// This is the case you might see on a URL that starts with a print statement, and one
// branch has a slash or ampersand but the other doesn't. Re-entering
// MAYBE_VARIABLE_SCHEME allows us to pretend that the last branch was just part of the
// leading print statement, which leaves us in a relatively-unknown state, but no more
// unknown had it just been completely opaque.
//
// Good Example 1: {$urlWithQuery}{if $a}&a={$a}{/if}{if $b}&b={$b}{/if}
// In this example, the first "if" statement has two branches:
// - "true": {$urlWithQuery}&a={$a} looks like a QUERY due to hueristics
// - "false": {$urlWithQuery} only, which Soy doesn't know at compile-time to actually
// have a query, and it remains in MAYBE_VARIABLE_SCHEME.
// Instead of yielding UNKNOWN, this yields MAYBE_VARIABLE_SCHEME, which the second
// {if $b} can safely deal with.
//
// Good Example 2: {$base}{if $a}/a{/if}{if $b}/b{/if}
// In this, one branch transitions definitely into an authority or path, but the other
// might not. However, we can remain in MAYBE_VARIABLE_SCHEME safely.
return UriPart.MAYBE_VARIABLE_SCHEME;
} else {
// The part is unknown, but we think it's before the fragment. In this case, it's clearly
// ambiguous at compile-time that it's not clear what to do. Examples:
//
// /foo/{if $cond}?a={/if}
// {$base}{if $cond}?a={$a}{else}/b{/if}
// {if $cond}{$base}{else}/a{if $cond2}?b=1{/if}{/if}
//
// Unlike MAYBE_VARIABLE_SCHEME, we don't need to try to gracefully recover here, because
// the template author can easily disambiguate this.
return UriPart.UNKNOWN_PRE_FRAGMENT;
}
} | java | private static UriPart unionUriParts(UriPart a, UriPart b) {
Preconditions.checkArgument(a != b);
if (a == UriPart.DANGEROUS_SCHEME || b == UriPart.DANGEROUS_SCHEME) {
// Dangerous schemes (like javascript:) are poison -- if either side is dangerous, the whole
// thing is.
return UriPart.DANGEROUS_SCHEME;
} else if (a == UriPart.FRAGMENT
|| b == UriPart.FRAGMENT
|| a == UriPart.UNKNOWN
|| b == UriPart.UNKNOWN) {
// UNKNOWN means one part is in the #fragment and one is not. This is the case if one is
// FRAGMENT and the other is not, or if one of the branches was UNKNOWN to begin with.
return UriPart.UNKNOWN;
} else if ((a == UriPart.MAYBE_VARIABLE_SCHEME || b == UriPart.MAYBE_VARIABLE_SCHEME)
&& a != UriPart.UNKNOWN_PRE_FRAGMENT
&& b != UriPart.UNKNOWN_PRE_FRAGMENT) {
// This is the case you might see on a URL that starts with a print statement, and one
// branch has a slash or ampersand but the other doesn't. Re-entering
// MAYBE_VARIABLE_SCHEME allows us to pretend that the last branch was just part of the
// leading print statement, which leaves us in a relatively-unknown state, but no more
// unknown had it just been completely opaque.
//
// Good Example 1: {$urlWithQuery}{if $a}&a={$a}{/if}{if $b}&b={$b}{/if}
// In this example, the first "if" statement has two branches:
// - "true": {$urlWithQuery}&a={$a} looks like a QUERY due to hueristics
// - "false": {$urlWithQuery} only, which Soy doesn't know at compile-time to actually
// have a query, and it remains in MAYBE_VARIABLE_SCHEME.
// Instead of yielding UNKNOWN, this yields MAYBE_VARIABLE_SCHEME, which the second
// {if $b} can safely deal with.
//
// Good Example 2: {$base}{if $a}/a{/if}{if $b}/b{/if}
// In this, one branch transitions definitely into an authority or path, but the other
// might not. However, we can remain in MAYBE_VARIABLE_SCHEME safely.
return UriPart.MAYBE_VARIABLE_SCHEME;
} else {
// The part is unknown, but we think it's before the fragment. In this case, it's clearly
// ambiguous at compile-time that it's not clear what to do. Examples:
//
// /foo/{if $cond}?a={/if}
// {$base}{if $cond}?a={$a}{else}/b{/if}
// {if $cond}{$base}{else}/a{if $cond2}?b=1{/if}{/if}
//
// Unlike MAYBE_VARIABLE_SCHEME, we don't need to try to gracefully recover here, because
// the template author can easily disambiguate this.
return UriPart.UNKNOWN_PRE_FRAGMENT;
}
} | [
"private",
"static",
"UriPart",
"unionUriParts",
"(",
"UriPart",
"a",
",",
"UriPart",
"b",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"a",
"!=",
"b",
")",
";",
"if",
"(",
"a",
"==",
"UriPart",
".",
"DANGEROUS_SCHEME",
"||",
"b",
"==",
"UriPart... | Determines the correct URI part if two branches are joined. | [
"Determines",
"the",
"correct",
"URI",
"part",
"if",
"two",
"branches",
"are",
"joined",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L725-L771 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.parse | @VisibleForTesting
static Context parse(String text) {
Queue<String> parts = Lists.newLinkedList(Arrays.asList(text.split(" ")));
Context.Builder builder = HTML_PCDATA.toBuilder();
builder.withState(HtmlContext.valueOf(parts.remove()));
if (!parts.isEmpty()) {
try {
builder.withElType(ElementType.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withAttrType(AttributeType.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withDelimType(AttributeEndDelimiter.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withSlashType(JsFollowingSlash.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withUriPart(UriPart.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withUriType(UriType.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
String part = parts.element();
String prefix = "templateNestDepth=";
if (part.startsWith(prefix)) {
try {
builder.withTemplateNestDepth(Integer.parseInt(part.substring(prefix.length())));
parts.remove();
} catch (NumberFormatException ex) {
// OK
}
}
}
if (!parts.isEmpty()) {
String part = parts.element();
String prefix = "jsTemplateLiteralNestDepth=";
if (part.startsWith(prefix)) {
try {
builder.withJsTemplateLiteralNestDepth(Integer.parseInt(part.substring(prefix.length())));
parts.remove();
} catch (NumberFormatException ex) {
// OK
}
}
}
if (!parts.isEmpty()) {
throw new IllegalArgumentException(
"Unable to parse context \"" + text + "\". Unparsed portion: " + parts);
}
Context result = builder.build();
return result;
} | java | @VisibleForTesting
static Context parse(String text) {
Queue<String> parts = Lists.newLinkedList(Arrays.asList(text.split(" ")));
Context.Builder builder = HTML_PCDATA.toBuilder();
builder.withState(HtmlContext.valueOf(parts.remove()));
if (!parts.isEmpty()) {
try {
builder.withElType(ElementType.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withAttrType(AttributeType.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withDelimType(AttributeEndDelimiter.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withSlashType(JsFollowingSlash.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withUriPart(UriPart.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withUriType(UriType.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
String part = parts.element();
String prefix = "templateNestDepth=";
if (part.startsWith(prefix)) {
try {
builder.withTemplateNestDepth(Integer.parseInt(part.substring(prefix.length())));
parts.remove();
} catch (NumberFormatException ex) {
// OK
}
}
}
if (!parts.isEmpty()) {
String part = parts.element();
String prefix = "jsTemplateLiteralNestDepth=";
if (part.startsWith(prefix)) {
try {
builder.withJsTemplateLiteralNestDepth(Integer.parseInt(part.substring(prefix.length())));
parts.remove();
} catch (NumberFormatException ex) {
// OK
}
}
}
if (!parts.isEmpty()) {
throw new IllegalArgumentException(
"Unable to parse context \"" + text + "\". Unparsed portion: " + parts);
}
Context result = builder.build();
return result;
} | [
"@",
"VisibleForTesting",
"static",
"Context",
"parse",
"(",
"String",
"text",
")",
"{",
"Queue",
"<",
"String",
">",
"parts",
"=",
"Lists",
".",
"newLinkedList",
"(",
"Arrays",
".",
"asList",
"(",
"text",
".",
"split",
"(",
"\" \"",
")",
")",
")",
";"... | Parses a condensed string version of a context, for use in tests. | [
"Parses",
"a",
"condensed",
"string",
"version",
"of",
"a",
"context",
"for",
"use",
"in",
"tests",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L902-L985 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.isValidStartContextForContentKind | public boolean isValidStartContextForContentKind(SanitizedContentKind contentKind) {
if (templateNestDepth != 0) {
return false;
}
switch (contentKind) {
case ATTRIBUTES:
// Allow HTML attribute names, regardless of the kind of attribute (e.g. plain text)
// or immediately after an open tag.
return state == HtmlContext.HTML_ATTRIBUTE_NAME || state == HtmlContext.HTML_TAG;
default:
// NOTE: For URI's, we need to be picky that the context has no attribute type, since we
// don't want to forget to escape ampersands.
return this.equals(getStartContextForContentKind(contentKind));
}
} | java | public boolean isValidStartContextForContentKind(SanitizedContentKind contentKind) {
if (templateNestDepth != 0) {
return false;
}
switch (contentKind) {
case ATTRIBUTES:
// Allow HTML attribute names, regardless of the kind of attribute (e.g. plain text)
// or immediately after an open tag.
return state == HtmlContext.HTML_ATTRIBUTE_NAME || state == HtmlContext.HTML_TAG;
default:
// NOTE: For URI's, we need to be picky that the context has no attribute type, since we
// don't want to forget to escape ampersands.
return this.equals(getStartContextForContentKind(contentKind));
}
} | [
"public",
"boolean",
"isValidStartContextForContentKind",
"(",
"SanitizedContentKind",
"contentKind",
")",
"{",
"if",
"(",
"templateNestDepth",
"!=",
"0",
")",
"{",
"return",
"false",
";",
"}",
"switch",
"(",
"contentKind",
")",
"{",
"case",
"ATTRIBUTES",
":",
"... | Determines whether a particular context is valid at the start of a block of a particular
content kind. | [
"Determines",
"whether",
"a",
"particular",
"context",
"is",
"valid",
"at",
"the",
"start",
"of",
"a",
"block",
"of",
"a",
"particular",
"content",
"kind",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L1004-L1018 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.isValidStartContextForContentKindLoose | public boolean isValidStartContextForContentKindLoose(SanitizedContentKind contentKind) {
switch (contentKind) {
case URI:
// Allow contextual templates directly call URI templates, even if we technically need to
// do HTML-escaping for correct output. Supported browsers recover gracefully when
// ampersands are underescaped, as long as there are no nearby semicolons. However, this
// special case is limited ONLY to transitional cases, where the caller is contextual and
// the callee is strict.
return state == HtmlContext.URI;
default:
return isValidStartContextForContentKind(contentKind);
}
} | java | public boolean isValidStartContextForContentKindLoose(SanitizedContentKind contentKind) {
switch (contentKind) {
case URI:
// Allow contextual templates directly call URI templates, even if we technically need to
// do HTML-escaping for correct output. Supported browsers recover gracefully when
// ampersands are underescaped, as long as there are no nearby semicolons. However, this
// special case is limited ONLY to transitional cases, where the caller is contextual and
// the callee is strict.
return state == HtmlContext.URI;
default:
return isValidStartContextForContentKind(contentKind);
}
} | [
"public",
"boolean",
"isValidStartContextForContentKindLoose",
"(",
"SanitizedContentKind",
"contentKind",
")",
"{",
"switch",
"(",
"contentKind",
")",
"{",
"case",
"URI",
":",
"// Allow contextual templates directly call URI templates, even if we technically need to",
"// do HTML-... | Determines whether a particular context is allowed for contextual to strict calls.
<p>This is slightly more relaxed, and used to help piecemeal transition of templates from
contextual to strict. | [
"Determines",
"whether",
"a",
"particular",
"context",
"is",
"allowed",
"for",
"contextual",
"to",
"strict",
"calls",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L1026-L1038 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.getMostAppropriateContentKind | public SanitizedContentKind getMostAppropriateContentKind() {
SanitizedContentKind kind = STATE_TO_CONTENT_KIND.get(state);
if (kind != null && isValidStartContextForContentKindLoose(kind)) {
return kind;
}
return SanitizedContentKind.TEXT;
} | java | public SanitizedContentKind getMostAppropriateContentKind() {
SanitizedContentKind kind = STATE_TO_CONTENT_KIND.get(state);
if (kind != null && isValidStartContextForContentKindLoose(kind)) {
return kind;
}
return SanitizedContentKind.TEXT;
} | [
"public",
"SanitizedContentKind",
"getMostAppropriateContentKind",
"(",
")",
"{",
"SanitizedContentKind",
"kind",
"=",
"STATE_TO_CONTENT_KIND",
".",
"get",
"(",
"state",
")",
";",
"if",
"(",
"kind",
"!=",
"null",
"&&",
"isValidStartContextForContentKindLoose",
"(",
"k... | Returns the most sensible content kind for a context.
<p>This is primarily for error messages, indicating to the user what content kind can be used
to mostly null out the escaping. Returns TEXT if no useful match was detected. | [
"Returns",
"the",
"most",
"sensible",
"content",
"kind",
"for",
"a",
"context",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L1059-L1065 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.isValidEndContextForContentKind | public final boolean isValidEndContextForContentKind(SanitizedContentKind contentKind) {
if (templateNestDepth != 0) {
return false;
}
switch (contentKind) {
case CSS:
return state == HtmlContext.CSS && elType == ElementType.NONE;
case HTML:
return state == HtmlContext.HTML_PCDATA && elType == ElementType.NONE;
case ATTRIBUTES:
// Allow any html attribute context or html tag this. HTML_TAG is needed for constructs
// like "checked" that don't require an attribute value. Explicitly disallow
// HTML_NORMAL_ATTR_VALUE (e.g. foo={$x} without quotes) to help catch cases where
// attributes aren't safely composable (e.g. foo={$x}checked would end up with one long
// attribute value, whereas foo="{$x}"checked would be parsed as intended).
return state == HtmlContext.HTML_ATTRIBUTE_NAME || state == HtmlContext.HTML_TAG;
case JS:
// Just ensure the state is JS -- don't worry about whether a regex is coming or not.
return state == HtmlContext.JS && elType == ElementType.NONE;
case URI:
// Ensure that the URI content is non-empty and the URI type remains normal (which is
// the assumed type of the URI content kind).
return state == HtmlContext.URI && uriType == UriType.NORMAL && uriPart != UriPart.START;
case TEXT:
return state == HtmlContext.TEXT;
case TRUSTED_RESOURCE_URI:
// Ensure that the URI content is non-empty and the URI type remains normal (which is
// the assumed type of the URI content kind).
return state == HtmlContext.URI
&& uriType == UriType.TRUSTED_RESOURCE
&& uriPart != UriPart.START;
}
throw new IllegalArgumentException(
"Specified content kind " + contentKind + " has no associated end context.");
} | java | public final boolean isValidEndContextForContentKind(SanitizedContentKind contentKind) {
if (templateNestDepth != 0) {
return false;
}
switch (contentKind) {
case CSS:
return state == HtmlContext.CSS && elType == ElementType.NONE;
case HTML:
return state == HtmlContext.HTML_PCDATA && elType == ElementType.NONE;
case ATTRIBUTES:
// Allow any html attribute context or html tag this. HTML_TAG is needed for constructs
// like "checked" that don't require an attribute value. Explicitly disallow
// HTML_NORMAL_ATTR_VALUE (e.g. foo={$x} without quotes) to help catch cases where
// attributes aren't safely composable (e.g. foo={$x}checked would end up with one long
// attribute value, whereas foo="{$x}"checked would be parsed as intended).
return state == HtmlContext.HTML_ATTRIBUTE_NAME || state == HtmlContext.HTML_TAG;
case JS:
// Just ensure the state is JS -- don't worry about whether a regex is coming or not.
return state == HtmlContext.JS && elType == ElementType.NONE;
case URI:
// Ensure that the URI content is non-empty and the URI type remains normal (which is
// the assumed type of the URI content kind).
return state == HtmlContext.URI && uriType == UriType.NORMAL && uriPart != UriPart.START;
case TEXT:
return state == HtmlContext.TEXT;
case TRUSTED_RESOURCE_URI:
// Ensure that the URI content is non-empty and the URI type remains normal (which is
// the assumed type of the URI content kind).
return state == HtmlContext.URI
&& uriType == UriType.TRUSTED_RESOURCE
&& uriPart != UriPart.START;
}
throw new IllegalArgumentException(
"Specified content kind " + contentKind + " has no associated end context.");
} | [
"public",
"final",
"boolean",
"isValidEndContextForContentKind",
"(",
"SanitizedContentKind",
"contentKind",
")",
"{",
"if",
"(",
"templateNestDepth",
"!=",
"0",
")",
"{",
"return",
"false",
";",
"}",
"switch",
"(",
"contentKind",
")",
"{",
"case",
"CSS",
":",
... | Determines whether a particular context is valid for the end of a block of a particular content
kind. | [
"Determines",
"whether",
"a",
"particular",
"context",
"is",
"valid",
"for",
"the",
"end",
"of",
"a",
"block",
"of",
"a",
"particular",
"content",
"kind",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L1071-L1105 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java | Context.getLikelyEndContextMismatchCause | public final String getLikelyEndContextMismatchCause(SanitizedContentKind contentKind) {
Preconditions.checkArgument(!isValidEndContextForContentKind(contentKind));
if (contentKind == SanitizedContentKind.ATTRIBUTES) {
// Special error message for ATTRIBUTES since it has some specific logic.
return "an unterminated attribute value, or ending with an unquoted attribute";
}
switch (state) {
case HTML_TAG_NAME:
case HTML_TAG:
case HTML_ATTRIBUTE_NAME:
case HTML_NORMAL_ATTR_VALUE:
return "an unterminated HTML tag or attribute";
case CSS:
return "an unclosed style block or attribute";
case JS:
case JS_LINE_COMMENT: // Line comments are terminated by end of input.
return "an unclosed script block or attribute";
case CSS_COMMENT:
case HTML_COMMENT:
case JS_BLOCK_COMMENT:
return "an unterminated comment";
case CSS_DQ_STRING:
case CSS_SQ_STRING:
case JS_DQ_STRING:
case JS_SQ_STRING:
return "an unterminated string literal";
case URI:
case CSS_URI:
case CSS_DQ_URI:
case CSS_SQ_URI:
return "an unterminated or empty URI";
case JS_REGEX:
return "an unterminated regular expression";
default:
if (templateNestDepth != 0) {
return "an unterminated <template> element";
} else {
return "unknown to compiler";
}
}
} | java | public final String getLikelyEndContextMismatchCause(SanitizedContentKind contentKind) {
Preconditions.checkArgument(!isValidEndContextForContentKind(contentKind));
if (contentKind == SanitizedContentKind.ATTRIBUTES) {
// Special error message for ATTRIBUTES since it has some specific logic.
return "an unterminated attribute value, or ending with an unquoted attribute";
}
switch (state) {
case HTML_TAG_NAME:
case HTML_TAG:
case HTML_ATTRIBUTE_NAME:
case HTML_NORMAL_ATTR_VALUE:
return "an unterminated HTML tag or attribute";
case CSS:
return "an unclosed style block or attribute";
case JS:
case JS_LINE_COMMENT: // Line comments are terminated by end of input.
return "an unclosed script block or attribute";
case CSS_COMMENT:
case HTML_COMMENT:
case JS_BLOCK_COMMENT:
return "an unterminated comment";
case CSS_DQ_STRING:
case CSS_SQ_STRING:
case JS_DQ_STRING:
case JS_SQ_STRING:
return "an unterminated string literal";
case URI:
case CSS_URI:
case CSS_DQ_URI:
case CSS_SQ_URI:
return "an unterminated or empty URI";
case JS_REGEX:
return "an unterminated regular expression";
default:
if (templateNestDepth != 0) {
return "an unterminated <template> element";
} else {
return "unknown to compiler";
}
}
} | [
"public",
"final",
"String",
"getLikelyEndContextMismatchCause",
"(",
"SanitizedContentKind",
"contentKind",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"!",
"isValidEndContextForContentKind",
"(",
"contentKind",
")",
")",
";",
"if",
"(",
"contentKind",
"==",
... | Returns a plausible human-readable description of a context mismatch;
<p>This assumes that the provided context is an invalid end context for the particular content
kind. | [
"Returns",
"a",
"plausible",
"human",
"-",
"readable",
"description",
"of",
"a",
"context",
"mismatch",
";"
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Context.java#L1113-L1160 | train |
google/closure-templates | java/src/com/google/template/soy/base/internal/IndentedLinesBuilder.java | IndentedLinesBuilder.increaseIndent | public void increaseIndent(int numStops) {
indentLen += numStops * indentIncrementLen;
Preconditions.checkState(0 <= indentLen && indentLen <= MAX_INDENT_LEN);
indent = SPACES.substring(0, indentLen);
} | java | public void increaseIndent(int numStops) {
indentLen += numStops * indentIncrementLen;
Preconditions.checkState(0 <= indentLen && indentLen <= MAX_INDENT_LEN);
indent = SPACES.substring(0, indentLen);
} | [
"public",
"void",
"increaseIndent",
"(",
"int",
"numStops",
")",
"{",
"indentLen",
"+=",
"numStops",
"*",
"indentIncrementLen",
";",
"Preconditions",
".",
"checkState",
"(",
"0",
"<=",
"indentLen",
"&&",
"indentLen",
"<=",
"MAX_INDENT_LEN",
")",
";",
"indent",
... | Increases the indent by the given number of stops. | [
"Increases",
"the",
"indent",
"by",
"the",
"given",
"number",
"of",
"stops",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/internal/IndentedLinesBuilder.java#L99-L103 | train |
google/closure-templates | java/src/com/google/template/soy/base/internal/IndentedLinesBuilder.java | IndentedLinesBuilder.appendParts | public IndentedLinesBuilder appendParts(Object... parts) {
for (Object part : parts) {
sb.append(part);
}
return this;
} | java | public IndentedLinesBuilder appendParts(Object... parts) {
for (Object part : parts) {
sb.append(part);
}
return this;
} | [
"public",
"IndentedLinesBuilder",
"appendParts",
"(",
"Object",
"...",
"parts",
")",
"{",
"for",
"(",
"Object",
"part",
":",
"parts",
")",
"{",
"sb",
".",
"append",
"(",
"part",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Appends some parts to the current line.
@param parts The parts to append.
@return This object. | [
"Appends",
"some",
"parts",
"to",
"the",
"current",
"line",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/internal/IndentedLinesBuilder.java#L137-L142 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.