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/soytree/TemplateNodeBuilder.java
TemplateNodeBuilder.setId
public T setId(int id) { Preconditions.checkState(this.id == null); this.id = id; return (T) this; }
java
public T setId(int id) { Preconditions.checkState(this.id == null); this.id = id; return (T) this; }
[ "public", "T", "setId", "(", "int", "id", ")", "{", "Preconditions", ".", "checkState", "(", "this", ".", "id", "==", "null", ")", ";", "this", ".", "id", "=", "id", ";", "return", "(", "T", ")", "this", ";", "}" ]
Sets the id for the node to be built. @return This builder.
[ "Sets", "the", "id", "for", "the", "node", "to", "be", "built", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/TemplateNodeBuilder.java#L125-L129
train
google/closure-templates
java/src/com/google/template/soy/soytree/TemplateNodeBuilder.java
TemplateNodeBuilder.setSoyDoc
public T setSoyDoc(String soyDoc, SourceLocation soyDocLocation) { Preconditions.checkState(this.soyDoc == null); Preconditions.checkState(cmdText != null); int paramOffset = soyDoc.indexOf("@param"); if (paramOffset != -1) { errorReporter.report( new RawTextNode(-1, soyDoc, soyDocLocation) .substringLocation(paramOffset, paramOffset + "@param".length()), SOYDOC_PARAM); } this.soyDoc = soyDoc; Preconditions.checkArgument(soyDoc.startsWith("/**") && soyDoc.endsWith("*/")); this.soyDocDesc = cleanSoyDocHelper(soyDoc); return (T) this; }
java
public T setSoyDoc(String soyDoc, SourceLocation soyDocLocation) { Preconditions.checkState(this.soyDoc == null); Preconditions.checkState(cmdText != null); int paramOffset = soyDoc.indexOf("@param"); if (paramOffset != -1) { errorReporter.report( new RawTextNode(-1, soyDoc, soyDocLocation) .substringLocation(paramOffset, paramOffset + "@param".length()), SOYDOC_PARAM); } this.soyDoc = soyDoc; Preconditions.checkArgument(soyDoc.startsWith("/**") && soyDoc.endsWith("*/")); this.soyDocDesc = cleanSoyDocHelper(soyDoc); return (T) this; }
[ "public", "T", "setSoyDoc", "(", "String", "soyDoc", ",", "SourceLocation", "soyDocLocation", ")", "{", "Preconditions", ".", "checkState", "(", "this", ".", "soyDoc", "==", "null", ")", ";", "Preconditions", ".", "checkState", "(", "cmdText", "!=", "null", ...
Sets the SoyDoc for the node to be built. @return This builder.
[ "Sets", "the", "SoyDoc", "for", "the", "node", "to", "be", "built", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/TemplateNodeBuilder.java#L193-L208
train
google/closure-templates
java/src/com/google/template/soy/soytree/TemplateNodeBuilder.java
TemplateNodeBuilder.addParams
public T addParams(Iterable<? extends TemplateParam> newParams) { Set<String> seenParamKeys = new HashSet<>(); if (this.params == null) { this.params = ImmutableList.copyOf(newParams); } else { for (TemplateParam oldParam : this.params) { seenParamKeys.add(oldParam.name()); } this.params = ImmutableList.<TemplateParam>builder().addAll(this.params).addAll(newParams).build(); } // Check new params. for (TemplateParam param : newParams) { if (param.name().equals("ij")) { errorReporter.report(param.nameLocation(), INVALID_PARAM_NAMED_IJ); } if (!seenParamKeys.add(param.name())) { errorReporter.report(param.nameLocation(), PARAM_ALREADY_DECLARED, param.name()); } } return (T) this; }
java
public T addParams(Iterable<? extends TemplateParam> newParams) { Set<String> seenParamKeys = new HashSet<>(); if (this.params == null) { this.params = ImmutableList.copyOf(newParams); } else { for (TemplateParam oldParam : this.params) { seenParamKeys.add(oldParam.name()); } this.params = ImmutableList.<TemplateParam>builder().addAll(this.params).addAll(newParams).build(); } // Check new params. for (TemplateParam param : newParams) { if (param.name().equals("ij")) { errorReporter.report(param.nameLocation(), INVALID_PARAM_NAMED_IJ); } if (!seenParamKeys.add(param.name())) { errorReporter.report(param.nameLocation(), PARAM_ALREADY_DECLARED, param.name()); } } return (T) this; }
[ "public", "T", "addParams", "(", "Iterable", "<", "?", "extends", "TemplateParam", ">", "newParams", ")", "{", "Set", "<", "String", ">", "seenParamKeys", "=", "new", "HashSet", "<>", "(", ")", ";", "if", "(", "this", ".", "params", "==", "null", ")", ...
This method is intended to be called at most once for header params. @param newParams The params to add.
[ "This", "method", "is", "intended", "to", "be", "called", "at", "most", "once", "for", "header", "params", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/TemplateNodeBuilder.java#L215-L238
train
google/closure-templates
java/src/com/google/template/soy/soytree/SoyTreeUtils.java
SoyTreeUtils.getAllNodesOfType
public static <T extends Node> ImmutableList<T> getAllNodesOfType( Node rootSoyNode, final Class<T> classObject) { return getAllMatchingNodesOfType(rootSoyNode, classObject, arg -> true); }
java
public static <T extends Node> ImmutableList<T> getAllNodesOfType( Node rootSoyNode, final Class<T> classObject) { return getAllMatchingNodesOfType(rootSoyNode, classObject, arg -> true); }
[ "public", "static", "<", "T", "extends", "Node", ">", "ImmutableList", "<", "T", ">", "getAllNodesOfType", "(", "Node", "rootSoyNode", ",", "final", "Class", "<", "T", ">", "classObject", ")", "{", "return", "getAllMatchingNodesOfType", "(", "rootSoyNode", ","...
Retrieves all nodes in a tree that are an instance of a particular class. @param <T> The type of node to retrieve. @param rootSoyNode The parse tree to search. @param classObject The class whose instances to search for, including subclasses. @return The nodes in the order they appear.
[ "Retrieves", "all", "nodes", "in", "a", "tree", "that", "are", "an", "instance", "of", "a", "particular", "class", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/SoyTreeUtils.java#L136-L139
train
google/closure-templates
java/src/com/google/template/soy/soytree/SoyTreeUtils.java
SoyTreeUtils.getAllMatchingNodesOfType
private static <T extends Node> ImmutableList<T> getAllMatchingNodesOfType( Node rootSoyNode, final Class<T> classObject, final Predicate<T> filter) { final ImmutableList.Builder<T> matchedNodesBuilder = ImmutableList.builder(); // optimization to avoid navigating into expr trees if we can't possibly match anything final boolean exploreExpressions = ExprNode.class.isAssignableFrom(classObject); visitAllNodes( rootSoyNode, new NodeVisitor<Node, VisitDirective>() { @Override public VisitDirective exec(Node node) { if (classObject.isInstance(node)) { T typedNode = classObject.cast(node); if (filter.test(typedNode)) { matchedNodesBuilder.add(typedNode); } } if (!exploreExpressions && node instanceof ExprNode) { return VisitDirective.SKIP_CHILDREN; } return VisitDirective.CONTINUE; } }); return matchedNodesBuilder.build(); }
java
private static <T extends Node> ImmutableList<T> getAllMatchingNodesOfType( Node rootSoyNode, final Class<T> classObject, final Predicate<T> filter) { final ImmutableList.Builder<T> matchedNodesBuilder = ImmutableList.builder(); // optimization to avoid navigating into expr trees if we can't possibly match anything final boolean exploreExpressions = ExprNode.class.isAssignableFrom(classObject); visitAllNodes( rootSoyNode, new NodeVisitor<Node, VisitDirective>() { @Override public VisitDirective exec(Node node) { if (classObject.isInstance(node)) { T typedNode = classObject.cast(node); if (filter.test(typedNode)) { matchedNodesBuilder.add(typedNode); } } if (!exploreExpressions && node instanceof ExprNode) { return VisitDirective.SKIP_CHILDREN; } return VisitDirective.CONTINUE; } }); return matchedNodesBuilder.build(); }
[ "private", "static", "<", "T", "extends", "Node", ">", "ImmutableList", "<", "T", ">", "getAllMatchingNodesOfType", "(", "Node", "rootSoyNode", ",", "final", "Class", "<", "T", ">", "classObject", ",", "final", "Predicate", "<", "T", ">", "filter", ")", "{...
Retrieves all nodes in a tree that are an instance of a particular class and match the given predicate.
[ "Retrieves", "all", "nodes", "in", "a", "tree", "that", "are", "an", "instance", "of", "a", "particular", "class", "and", "match", "the", "given", "predicate", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/SoyTreeUtils.java#L145-L168
train
google/closure-templates
java/src/com/google/template/soy/soytree/SoyTreeUtils.java
SoyTreeUtils.execOnAllV2Exprs
public static <R> void execOnAllV2Exprs( SoyNode node, final AbstractNodeVisitor<ExprNode, R> exprNodeVisitor) { visitAllNodes( node, new NodeVisitor<Node, VisitDirective>() { @Override public VisitDirective exec(Node node) { if (node instanceof ExprHolderNode) { for (ExprRootNode expr : ((ExprHolderNode) node).getExprList()) { exprNodeVisitor.exec(expr); } } else if (node instanceof ExprNode) { return VisitDirective.SKIP_CHILDREN; } return VisitDirective.CONTINUE; } }); }
java
public static <R> void execOnAllV2Exprs( SoyNode node, final AbstractNodeVisitor<ExprNode, R> exprNodeVisitor) { visitAllNodes( node, new NodeVisitor<Node, VisitDirective>() { @Override public VisitDirective exec(Node node) { if (node instanceof ExprHolderNode) { for (ExprRootNode expr : ((ExprHolderNode) node).getExprList()) { exprNodeVisitor.exec(expr); } } else if (node instanceof ExprNode) { return VisitDirective.SKIP_CHILDREN; } return VisitDirective.CONTINUE; } }); }
[ "public", "static", "<", "R", ">", "void", "execOnAllV2Exprs", "(", "SoyNode", "node", ",", "final", "AbstractNodeVisitor", "<", "ExprNode", ",", "R", ">", "exprNodeVisitor", ")", "{", "visitAllNodes", "(", "node", ",", "new", "NodeVisitor", "<", "Node", ","...
Given a Soy node and a visitor for expression trees, traverses the subtree of the node and executes the visitor on all expressions held by nodes in the subtree. <p>Only processes expressions in V2 syntax. Ignores all expressions in V1 syntax. @param <R> The ExprNode visitor's return type. @param node The root of the subtree to visit all expressions in. @param exprNodeVisitor The visitor to execute on all expressions.
[ "Given", "a", "Soy", "node", "and", "a", "visitor", "for", "expression", "trees", "traverses", "the", "subtree", "of", "the", "node", "and", "executes", "the", "visitor", "on", "all", "expressions", "held", "by", "nodes", "in", "the", "subtree", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/SoyTreeUtils.java#L242-L259
train
google/closure-templates
java/src/com/google/template/soy/soytree/TagName.java
TagName.checkCloseTagClosesOptional
public static boolean checkCloseTagClosesOptional(TagName closeTag, TagName optionalOpenTag) { // TODO(b/120994894): Replace this with checkArgument() when HtmlTagEntry can be replaced. if (!optionalOpenTag.isStatic() || !optionalOpenTag.isDefinitelyOptional()) { return false; } if (!closeTag.isStatic()) { return true; } String openTagName = optionalOpenTag.getStaticTagNameAsLowerCase(); String closeTagName = closeTag.getStaticTagNameAsLowerCase(); checkArgument(!openTagName.equals(closeTagName)); if ("p".equals(openTagName)) { return !PTAG_CLOSE_EXCEPTIONS.contains(closeTagName); } return OPTIONAL_TAG_CLOSE_TAG_RULES.containsEntry(openTagName, closeTagName); }
java
public static boolean checkCloseTagClosesOptional(TagName closeTag, TagName optionalOpenTag) { // TODO(b/120994894): Replace this with checkArgument() when HtmlTagEntry can be replaced. if (!optionalOpenTag.isStatic() || !optionalOpenTag.isDefinitelyOptional()) { return false; } if (!closeTag.isStatic()) { return true; } String openTagName = optionalOpenTag.getStaticTagNameAsLowerCase(); String closeTagName = closeTag.getStaticTagNameAsLowerCase(); checkArgument(!openTagName.equals(closeTagName)); if ("p".equals(openTagName)) { return !PTAG_CLOSE_EXCEPTIONS.contains(closeTagName); } return OPTIONAL_TAG_CLOSE_TAG_RULES.containsEntry(openTagName, closeTagName); }
[ "public", "static", "boolean", "checkCloseTagClosesOptional", "(", "TagName", "closeTag", ",", "TagName", "optionalOpenTag", ")", "{", "// TODO(b/120994894): Replace this with checkArgument() when HtmlTagEntry can be replaced.", "if", "(", "!", "optionalOpenTag", ".", "isStatic",...
Checks if the an open tag can be auto-closed by a following close tag which does not have the same tag name as the open tag. <p>We throws an {@code IllegalArgumentException} if two inputs have the same tag names, since this should never happen (should be handled by previous logic in {@code StrictHtmlValidationPass}). <p>This implements half of the content model described in <a href="https://www.w3.org/TR/html5/syntax.html#optional-tags">https://www.w3.org/TR/html5/syntax.html#optional-tags</a>. Notably we do nothing when we see cases like "li element is immediately followed by another li element". The validation logic relies on auto-closing open tags when we see close tags. Since only {@code </ul>} and {@code </ol>} are allowed to close {@code <li>}, we believe this should still give us a confident error message. We might consider adding support for popping open tags when we visit open tags in the future.
[ "Checks", "if", "the", "an", "open", "tag", "can", "be", "auto", "-", "closed", "by", "a", "following", "close", "tag", "which", "does", "not", "have", "the", "same", "tag", "name", "as", "the", "open", "tag", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/TagName.java#L276-L291
train
google/closure-templates
java/src/com/google/template/soy/soytree/TagName.java
TagName.checkOpenTagClosesOptional
public static boolean checkOpenTagClosesOptional(TagName openTag, TagName optionalOpenTag) { checkArgument(optionalOpenTag.isDefinitelyOptional(), "Open tag is not optional."); if (!(openTag.isStatic() && optionalOpenTag.isStatic())) { return false; } String optionalTagName = optionalOpenTag.getStaticTagNameAsLowerCase(); String openTagName = openTag.getStaticTagNameAsLowerCase(); return OPTIONAL_TAG_OPEN_CLOSE_RULES.containsEntry(optionalTagName, openTagName); }
java
public static boolean checkOpenTagClosesOptional(TagName openTag, TagName optionalOpenTag) { checkArgument(optionalOpenTag.isDefinitelyOptional(), "Open tag is not optional."); if (!(openTag.isStatic() && optionalOpenTag.isStatic())) { return false; } String optionalTagName = optionalOpenTag.getStaticTagNameAsLowerCase(); String openTagName = openTag.getStaticTagNameAsLowerCase(); return OPTIONAL_TAG_OPEN_CLOSE_RULES.containsEntry(optionalTagName, openTagName); }
[ "public", "static", "boolean", "checkOpenTagClosesOptional", "(", "TagName", "openTag", ",", "TagName", "optionalOpenTag", ")", "{", "checkArgument", "(", "optionalOpenTag", ".", "isDefinitelyOptional", "(", ")", ",", "\"Open tag is not optional.\"", ")", ";", "if", "...
Checks if the given open tag can implicitly close the given optional tag. <p>This implements the content model described in https://www.w3.org/TR/html5/syntax.html#optional-tags. <p><b>Note:</b>If {@code this} is a dynamic tag, then this test alsways returns {@code false} because the tag name can't be determined at parse time. <p>Detects two types of implicit closing scenarios: <ol> <li>an open tag can implicitly close another open tag, for example: {@code <li> <li>} <li>a close tag can implicitly close an open tag, for example: {@code <li> </ul>} </ol> @param openTag the open tag name to check. Must be an {@link HtmlOpenTagNode}. @param optionalOpenTag the optional tag that may be closed by this tag. This must be an optional open tag. @return whether {@code htmlTagName} can close {@code optionalTagName}
[ "Checks", "if", "the", "given", "open", "tag", "can", "implicitly", "close", "the", "given", "optional", "tag", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/TagName.java#L314-L322
train
google/closure-templates
java/src/com/google/template/soy/jssrc/dsl/SwitchBuilder.java
SwitchBuilder.addCase
public SwitchBuilder addCase(Expression caseLabel, Statement body) { clauses.add(new Switch.CaseClause(ImmutableList.of(caseLabel), body)); return this; }
java
public SwitchBuilder addCase(Expression caseLabel, Statement body) { clauses.add(new Switch.CaseClause(ImmutableList.of(caseLabel), body)); return this; }
[ "public", "SwitchBuilder", "addCase", "(", "Expression", "caseLabel", ",", "Statement", "body", ")", "{", "clauses", ".", "add", "(", "new", "Switch", ".", "CaseClause", "(", "ImmutableList", ".", "of", "(", "caseLabel", ")", ",", "body", ")", ")", ";", ...
Adds a case clause to this switch statement.
[ "Adds", "a", "case", "clause", "to", "this", "switch", "statement", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/SwitchBuilder.java#L44-L47
train
google/closure-templates
java/src/com/google/template/soy/soytree/CommandTagAttribute.java
CommandTagAttribute.valueAsExpr
public ExprNode valueAsExpr(ErrorReporter reporter) { checkState(value == null); if (valueExprList.size() > 1) { reporter.report( valueExprList.get(1).getSourceLocation(), EXPECTED_A_SINGLE_EXPRESSION, key.identifier()); // Return the first expr to avoid an NPE in CallNode ctor. return valueExprList.get(0); } return Iterables.getOnlyElement(valueExprList); }
java
public ExprNode valueAsExpr(ErrorReporter reporter) { checkState(value == null); if (valueExprList.size() > 1) { reporter.report( valueExprList.get(1).getSourceLocation(), EXPECTED_A_SINGLE_EXPRESSION, key.identifier()); // Return the first expr to avoid an NPE in CallNode ctor. return valueExprList.get(0); } return Iterables.getOnlyElement(valueExprList); }
[ "public", "ExprNode", "valueAsExpr", "(", "ErrorReporter", "reporter", ")", "{", "checkState", "(", "value", "==", "null", ")", ";", "if", "(", "valueExprList", ".", "size", "(", ")", ">", "1", ")", "{", "reporter", ".", "report", "(", "valueExprList", "...
Returns the value as an expression. Only call on an expression attribute.
[ "Returns", "the", "value", "as", "an", "expression", ".", "Only", "call", "on", "an", "expression", "attribute", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/CommandTagAttribute.java#L262-L271
train
google/closure-templates
java/src/com/google/template/soy/soytree/MsgSubstUnitBaseVarNameUtils.java
MsgSubstUnitBaseVarNameUtils.genNoncollidingBaseNamesForExprs
public static List<String> genNoncollidingBaseNamesForExprs( List<ExprNode> exprNodes, String fallbackBaseName, ErrorReporter errorReporter) { int numExprs = exprNodes.size(); // --- Compute candidate base names for each expression. --- List<List<String>> candidateBaseNameLists = Lists.newArrayListWithCapacity(numExprs); for (ExprNode exprRoot : exprNodes) { candidateBaseNameLists.add(genCandidateBaseNamesForExpr(exprRoot)); } // --- Build a multiset of collision strings (if key has > 1 values, then it's a collision). --- // Note: We could combine this loop with the previous loop, but it's more readable this way. Multimap<String, ExprNode> collisionStrToLongestCandidatesMultimap = HashMultimap.create(); for (int i = 0; i < numExprs; i++) { ExprNode exprRoot = exprNodes.get(i); List<String> candidateBaseNameList = candidateBaseNameLists.get(i); if (candidateBaseNameList.isEmpty()) { continue; } String longestCandidate = candidateBaseNameList.get(candidateBaseNameList.size() - 1); // Add longest candidate as a collision string. collisionStrToLongestCandidatesMultimap.put(longestCandidate, exprRoot); // Add all suffixes that begin after an underscore char as collision strings. for (int j = 0, n = longestCandidate.length(); j < n; j++) { if (longestCandidate.charAt(j) == '_') { collisionStrToLongestCandidatesMultimap.put(longestCandidate.substring(j + 1), exprRoot); } } } // --- Find the shortest noncolliding candidate base name for each expression. --- List<String> noncollidingBaseNames = Lists.newArrayListWithCapacity(numExprs); OUTER: for (int i = 0; i < numExprs; i++) { List<String> candidateBaseNameList = candidateBaseNameLists.get(i); if (!candidateBaseNameList.isEmpty()) { // Has candidates: Use the shortest candidate that doesn't collide. for (String candidateBaseName : candidateBaseNameList) { if (collisionStrToLongestCandidatesMultimap.get(candidateBaseName).size() == 1) { // Found candidate with 1 value in multimap, which means no collision. noncollidingBaseNames.add(candidateBaseName); continue OUTER; } } // Did not find any candidate with no collision. ExprNode exprRoot = exprNodes.get(i); String longestCandidate = candidateBaseNameList.get(candidateBaseNameList.size() - 1); ExprNode collidingExprRoot = null; for (ExprNode er : collisionStrToLongestCandidatesMultimap.get(longestCandidate)) { if (er != exprRoot) { collidingExprRoot = er; break; } } errorReporter.report( collidingExprRoot.getSourceLocation(), COLLIDING_EXPRESSIONS, exprRoot.toSourceString(), collidingExprRoot.toSourceString()); return noncollidingBaseNames; } else { // No candidates: Use fallback. noncollidingBaseNames.add(fallbackBaseName); } } return noncollidingBaseNames; }
java
public static List<String> genNoncollidingBaseNamesForExprs( List<ExprNode> exprNodes, String fallbackBaseName, ErrorReporter errorReporter) { int numExprs = exprNodes.size(); // --- Compute candidate base names for each expression. --- List<List<String>> candidateBaseNameLists = Lists.newArrayListWithCapacity(numExprs); for (ExprNode exprRoot : exprNodes) { candidateBaseNameLists.add(genCandidateBaseNamesForExpr(exprRoot)); } // --- Build a multiset of collision strings (if key has > 1 values, then it's a collision). --- // Note: We could combine this loop with the previous loop, but it's more readable this way. Multimap<String, ExprNode> collisionStrToLongestCandidatesMultimap = HashMultimap.create(); for (int i = 0; i < numExprs; i++) { ExprNode exprRoot = exprNodes.get(i); List<String> candidateBaseNameList = candidateBaseNameLists.get(i); if (candidateBaseNameList.isEmpty()) { continue; } String longestCandidate = candidateBaseNameList.get(candidateBaseNameList.size() - 1); // Add longest candidate as a collision string. collisionStrToLongestCandidatesMultimap.put(longestCandidate, exprRoot); // Add all suffixes that begin after an underscore char as collision strings. for (int j = 0, n = longestCandidate.length(); j < n; j++) { if (longestCandidate.charAt(j) == '_') { collisionStrToLongestCandidatesMultimap.put(longestCandidate.substring(j + 1), exprRoot); } } } // --- Find the shortest noncolliding candidate base name for each expression. --- List<String> noncollidingBaseNames = Lists.newArrayListWithCapacity(numExprs); OUTER: for (int i = 0; i < numExprs; i++) { List<String> candidateBaseNameList = candidateBaseNameLists.get(i); if (!candidateBaseNameList.isEmpty()) { // Has candidates: Use the shortest candidate that doesn't collide. for (String candidateBaseName : candidateBaseNameList) { if (collisionStrToLongestCandidatesMultimap.get(candidateBaseName).size() == 1) { // Found candidate with 1 value in multimap, which means no collision. noncollidingBaseNames.add(candidateBaseName); continue OUTER; } } // Did not find any candidate with no collision. ExprNode exprRoot = exprNodes.get(i); String longestCandidate = candidateBaseNameList.get(candidateBaseNameList.size() - 1); ExprNode collidingExprRoot = null; for (ExprNode er : collisionStrToLongestCandidatesMultimap.get(longestCandidate)) { if (er != exprRoot) { collidingExprRoot = er; break; } } errorReporter.report( collidingExprRoot.getSourceLocation(), COLLIDING_EXPRESSIONS, exprRoot.toSourceString(), collidingExprRoot.toSourceString()); return noncollidingBaseNames; } else { // No candidates: Use fallback. noncollidingBaseNames.add(fallbackBaseName); } } return noncollidingBaseNames; }
[ "public", "static", "List", "<", "String", ">", "genNoncollidingBaseNamesForExprs", "(", "List", "<", "ExprNode", ">", "exprNodes", ",", "String", "fallbackBaseName", ",", "ErrorReporter", "errorReporter", ")", "{", "int", "numExprs", "=", "exprNodes", ".", "size"...
Generates base names for all the expressions in a list, where for each expression, we use the shortest candidate base name that does not collide with any of the candidate base names generated from other expressions in the list. Two candidate base names are considered to collide if they are identical or if one is a suffix of the other beginning after an underscore character. <p>For example, given the expressions $userGender and $target.gender, the generated base names would be USER_GENDER and TARGET_GENDER. (Even though the shortest candidate base names are USER_GENDER and GENDER, the latter one is not used since it collides with the former one.) <p>Note: We prefer the shorter candidate base names when possible, because the translator usually doesn't care about all the names. E.g. $data.actionTargets[0].personInfo.gender turns into GENDER as opposed to DATA_ACTION_TARGETS_0_PERSON_INFO_GENDER, which is overkill and probably more confusing. Another reason is that refactorings that change higher-level names should not change messages unnecessarily. E.g. a refactoring that changes $data.actionTargets[0].personInfo.gender -> $userData.actionTargets[0].personInfo.gender should not change the placeholder name. @param exprNodes The expr nodes of the expressions to generate noncolliding base names for. @param fallbackBaseName The fallback base name. @param errorReporter For reporting collision errors. @return The list of generated noncolliding base names.
[ "Generates", "base", "names", "for", "all", "the", "expressions", "in", "a", "list", "where", "for", "each", "expression", "we", "use", "the", "shortest", "candidate", "base", "name", "that", "does", "not", "collide", "with", "any", "of", "the", "candidate",...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/MsgSubstUnitBaseVarNameUtils.java#L148-L220
train
google/closure-templates
java/src/com/google/template/soy/jssrc/dsl/ConditionalExpressionBuilder.java
ConditionalExpressionBuilder.build
@CheckReturnValue public Expression build(CodeChunk.Generator codeGenerator) { ImmutableList<IfThenPair<Expression>> pairs = conditions.build(); Expression ternary = tryCreateTernary(pairs); if (ternary != null) { return ternary; } // Otherwise we need to introduce a temporary and assign to it in each branch VariableDeclaration decl = codeGenerator.declarationBuilder().build(); Expression var = decl.ref(); ConditionalBuilder builder = null; for (IfThenPair<Expression> oldCondition : pairs) { Expression newConsequent = var.assign(oldCondition.consequent); if (builder == null) { builder = ifStatement(oldCondition.predicate, newConsequent.asStatement()); } else { builder.addElseIf(oldCondition.predicate, newConsequent.asStatement()); } } if (trailingElse != null) { builder.setElse(var.assign(trailingElse).asStatement()); } return var.withInitialStatements(ImmutableList.of(decl, builder.build())); }
java
@CheckReturnValue public Expression build(CodeChunk.Generator codeGenerator) { ImmutableList<IfThenPair<Expression>> pairs = conditions.build(); Expression ternary = tryCreateTernary(pairs); if (ternary != null) { return ternary; } // Otherwise we need to introduce a temporary and assign to it in each branch VariableDeclaration decl = codeGenerator.declarationBuilder().build(); Expression var = decl.ref(); ConditionalBuilder builder = null; for (IfThenPair<Expression> oldCondition : pairs) { Expression newConsequent = var.assign(oldCondition.consequent); if (builder == null) { builder = ifStatement(oldCondition.predicate, newConsequent.asStatement()); } else { builder.addElseIf(oldCondition.predicate, newConsequent.asStatement()); } } if (trailingElse != null) { builder.setElse(var.assign(trailingElse).asStatement()); } return var.withInitialStatements(ImmutableList.of(decl, builder.build())); }
[ "@", "CheckReturnValue", "public", "Expression", "build", "(", "CodeChunk", ".", "Generator", "codeGenerator", ")", "{", "ImmutableList", "<", "IfThenPair", "<", "Expression", ">>", "pairs", "=", "conditions", ".", "build", "(", ")", ";", "Expression", "ternary"...
Finishes building this conditional.
[ "Finishes", "building", "this", "conditional", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/ConditionalExpressionBuilder.java#L73-L96
train
google/closure-templates
java/src/com/google/template/soy/soyparse/RawTextBuilder.java
RawTextBuilder.addBasic
void addBasic(Token token) { if (basicStart == -1) { basicStart = buffer.length(); basicStartOfWhitespace = -1; basicHasNewline = false; } switch (token.kind) { case SoyFileParserConstants.TOKEN_WS: if (token.image.indexOf('\r') != -1 || token.image.indexOf('\n') != -1) { basicHasNewline = true; } if (basicStartOfWhitespace == -1 && whitespaceMode == WhitespaceMode.JOIN) { basicStartOfWhitespace = buffer.length(); endLineAtStartOfWhitespace = offsets.endLine(); endColumnAtStartOfWhitespace = offsets.endColumn(); } break; case SoyFileParserConstants.TOKEN_NOT_WS: maybeCollapseWhitespace(token.image); break; default: throw new AssertionError( SoyFileParserConstants.tokenImage[token.kind] + " is not a basic text token"); } append(token, token.image); }
java
void addBasic(Token token) { if (basicStart == -1) { basicStart = buffer.length(); basicStartOfWhitespace = -1; basicHasNewline = false; } switch (token.kind) { case SoyFileParserConstants.TOKEN_WS: if (token.image.indexOf('\r') != -1 || token.image.indexOf('\n') != -1) { basicHasNewline = true; } if (basicStartOfWhitespace == -1 && whitespaceMode == WhitespaceMode.JOIN) { basicStartOfWhitespace = buffer.length(); endLineAtStartOfWhitespace = offsets.endLine(); endColumnAtStartOfWhitespace = offsets.endColumn(); } break; case SoyFileParserConstants.TOKEN_NOT_WS: maybeCollapseWhitespace(token.image); break; default: throw new AssertionError( SoyFileParserConstants.tokenImage[token.kind] + " is not a basic text token"); } append(token, token.image); }
[ "void", "addBasic", "(", "Token", "token", ")", "{", "if", "(", "basicStart", "==", "-", "1", ")", "{", "basicStart", "=", "buffer", ".", "length", "(", ")", ";", "basicStartOfWhitespace", "=", "-", "1", ";", "basicHasNewline", "=", "false", ";", "}", ...
Append a basic token. 'Basic' tokens are text literals.
[ "Append", "a", "basic", "token", ".", "Basic", "tokens", "are", "text", "literals", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soyparse/RawTextBuilder.java#L92-L117
train
google/closure-templates
java/src/com/google/template/soy/soyparse/RawTextBuilder.java
RawTextBuilder.append
private void append(Token token, String content) { if (content.isEmpty()) { throw new IllegalStateException( String.format( "shouldn't append empty content: %s @ %s", SoyFileParserConstants.tokenImage[token.kind], Tokens.createSrcLoc(fileName, token))); } // add a new offset if: // - this is the first token // - the previous token introduced a discontinuity (due to a special token, or whitespace // joining) // - this token doesn't directly abut the previous token (this happens when there is a comment) boolean addOffset = false; if (offsets.isEmpty()) { addOffset = true; } else if (discontinuityReason != Reason.NONE) { addOffset = true; } else { // are the two tokens not adjacent? We don't actually record comments in the AST or token // stream so this is kind of a guess, but all known cases are due to comments. if (offsets.endLine() == token.beginLine) { if (offsets.endColumn() + 1 != token.beginColumn) { addOffset = true; discontinuityReason = Reason.COMMENT; } } else if (offsets.endLine() + 1 == token.beginLine && token.beginColumn != 1) { addOffset = true; discontinuityReason = Reason.COMMENT; } } if (addOffset) { offsets.add(buffer.length(), token.beginLine, token.beginColumn, discontinuityReason); discontinuityReason = Reason.NONE; } offsets.setEndLocation(token.endLine, token.endColumn); buffer.append(content); }
java
private void append(Token token, String content) { if (content.isEmpty()) { throw new IllegalStateException( String.format( "shouldn't append empty content: %s @ %s", SoyFileParserConstants.tokenImage[token.kind], Tokens.createSrcLoc(fileName, token))); } // add a new offset if: // - this is the first token // - the previous token introduced a discontinuity (due to a special token, or whitespace // joining) // - this token doesn't directly abut the previous token (this happens when there is a comment) boolean addOffset = false; if (offsets.isEmpty()) { addOffset = true; } else if (discontinuityReason != Reason.NONE) { addOffset = true; } else { // are the two tokens not adjacent? We don't actually record comments in the AST or token // stream so this is kind of a guess, but all known cases are due to comments. if (offsets.endLine() == token.beginLine) { if (offsets.endColumn() + 1 != token.beginColumn) { addOffset = true; discontinuityReason = Reason.COMMENT; } } else if (offsets.endLine() + 1 == token.beginLine && token.beginColumn != 1) { addOffset = true; discontinuityReason = Reason.COMMENT; } } if (addOffset) { offsets.add(buffer.length(), token.beginLine, token.beginColumn, discontinuityReason); discontinuityReason = Reason.NONE; } offsets.setEndLocation(token.endLine, token.endColumn); buffer.append(content); }
[ "private", "void", "append", "(", "Token", "token", ",", "String", "content", ")", "{", "if", "(", "content", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "String", ".", "format", "(", "\"shouldn't append empty content: %s ...
updates the location with the given tokens location.
[ "updates", "the", "location", "with", "the", "given", "tokens", "location", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soyparse/RawTextBuilder.java#L174-L210
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/shared/Names.java
Names.javaClassNameFromSoyTemplateName
public static String javaClassNameFromSoyTemplateName(String soyTemplate) { checkArgument( BaseUtils.isDottedIdentifier(soyTemplate), "%s is not a valid template name.", soyTemplate); return CLASS_PREFIX + soyTemplate; }
java
public static String javaClassNameFromSoyTemplateName(String soyTemplate) { checkArgument( BaseUtils.isDottedIdentifier(soyTemplate), "%s is not a valid template name.", soyTemplate); return CLASS_PREFIX + soyTemplate; }
[ "public", "static", "String", "javaClassNameFromSoyTemplateName", "(", "String", "soyTemplate", ")", "{", "checkArgument", "(", "BaseUtils", ".", "isDottedIdentifier", "(", "soyTemplate", ")", ",", "\"%s is not a valid template name.\"", ",", "soyTemplate", ")", ";", "r...
Translate a user controlled Soy name to a form that is safe to encode in a java class, method or field name. <p>Soy identifiers are very simple, they are restricted to the following regex: {@code [a-zA-Z_]([a-zA-Z_0-9])*}. So a template name is just one or more identifiers separated by {@code .} characters. To escape it, we simply replace all '.'s with '_'s, and all '_'s with '__' and prefix with a package name.
[ "Translate", "a", "user", "controlled", "Soy", "name", "to", "a", "form", "that", "is", "safe", "to", "encode", "in", "a", "java", "class", "method", "or", "field", "name", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/shared/Names.java#L48-L52
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/shared/Names.java
Names.javaFileName
public static String javaFileName(String soyNamespace, String fileName) { checkArgument( BaseUtils.isDottedIdentifier(soyNamespace), "%s is not a valid soy namspace name.", soyNamespace); return (CLASS_PREFIX + soyNamespace).replace('.', '/') + '/' + fileName; }
java
public static String javaFileName(String soyNamespace, String fileName) { checkArgument( BaseUtils.isDottedIdentifier(soyNamespace), "%s is not a valid soy namspace name.", soyNamespace); return (CLASS_PREFIX + soyNamespace).replace('.', '/') + '/' + fileName; }
[ "public", "static", "String", "javaFileName", "(", "String", "soyNamespace", ",", "String", "fileName", ")", "{", "checkArgument", "(", "BaseUtils", ".", "isDottedIdentifier", "(", "soyNamespace", ")", ",", "\"%s is not a valid soy namspace name.\"", ",", "soyNamespace"...
Given the soy namespace and file name returns the path where the corresponding resource should be stored.
[ "Given", "the", "soy", "namespace", "and", "file", "name", "returns", "the", "path", "where", "the", "corresponding", "resource", "should", "be", "stored", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/shared/Names.java#L58-L64
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/shared/Names.java
Names.rewriteStackTrace
public static void rewriteStackTrace(Throwable throwable) { StackTraceElement[] stack = throwable.getStackTrace(); for (int i = 0; i < stack.length; i++) { StackTraceElement curr = stack[i]; if (curr.getClassName().startsWith(CLASS_PREFIX)) { stack[i] = new StackTraceElement( soyTemplateNameFromJavaClassName(curr.getClassName()), // TODO(lukes): remove the method name? only if it == 'render'? curr.getMethodName(), curr.getFileName(), curr.getLineNumber()); } } throwable.setStackTrace(stack); }
java
public static void rewriteStackTrace(Throwable throwable) { StackTraceElement[] stack = throwable.getStackTrace(); for (int i = 0; i < stack.length; i++) { StackTraceElement curr = stack[i]; if (curr.getClassName().startsWith(CLASS_PREFIX)) { stack[i] = new StackTraceElement( soyTemplateNameFromJavaClassName(curr.getClassName()), // TODO(lukes): remove the method name? only if it == 'render'? curr.getMethodName(), curr.getFileName(), curr.getLineNumber()); } } throwable.setStackTrace(stack); }
[ "public", "static", "void", "rewriteStackTrace", "(", "Throwable", "throwable", ")", "{", "StackTraceElement", "[", "]", "stack", "=", "throwable", ".", "getStackTrace", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "stack", ".", "lengt...
Rewrites the given stack trace by replacing all references to generated jbcsrc types with the original template names.
[ "Rewrites", "the", "given", "stack", "trace", "by", "replacing", "all", "references", "to", "generated", "jbcsrc", "types", "with", "the", "original", "template", "names", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/shared/Names.java#L82-L97
train
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/V1JsExprTranslator.java
V1JsExprTranslator.translateVar
private static String translateVar(SoyToJsVariableMappings variableMappings, Matcher matcher) { Preconditions.checkArgument(matcher.matches()); String firstPart = matcher.group(1); StringBuilder exprTextSb = new StringBuilder(); // ------ Translate the first key, which may be a variable or a data key ------ String translation = getLocalVarTranslation(firstPart, variableMappings); if (translation != null) { // Case 1: In-scope local var. exprTextSb.append(translation); } else { // Case 2: Data reference. exprTextSb.append("opt_data.").append(firstPart); } return exprTextSb.toString(); }
java
private static String translateVar(SoyToJsVariableMappings variableMappings, Matcher matcher) { Preconditions.checkArgument(matcher.matches()); String firstPart = matcher.group(1); StringBuilder exprTextSb = new StringBuilder(); // ------ Translate the first key, which may be a variable or a data key ------ String translation = getLocalVarTranslation(firstPart, variableMappings); if (translation != null) { // Case 1: In-scope local var. exprTextSb.append(translation); } else { // Case 2: Data reference. exprTextSb.append("opt_data.").append(firstPart); } return exprTextSb.toString(); }
[ "private", "static", "String", "translateVar", "(", "SoyToJsVariableMappings", "variableMappings", ",", "Matcher", "matcher", ")", "{", "Preconditions", ".", "checkArgument", "(", "matcher", ".", "matches", "(", ")", ")", ";", "String", "firstPart", "=", "matcher"...
Helper function to translate a variable or data reference. <p>Examples: <pre> $boo --> opt_data.boo (var ref) </pre> @param variableMappings The current replacement JS expressions for the local variables (and foreach-loop special functions) current in scope. @param matcher Matcher formed from {@link V1JsExprTranslator#VAR_OR_REF}. @return Generated translation for the variable or data reference.
[ "Helper", "function", "to", "translate", "a", "variable", "or", "data", "reference", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/V1JsExprTranslator.java#L143-L160
train
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/JsType.java
JsType.typeExprForRecordMember
public String typeExprForRecordMember(boolean isOptional) { if (typeExpressions.size() > 1 || isOptional) { // needs parens return "(" + typeExpr() + (isOptional && !typeExpressions.contains("undefined") ? "|undefined" : "") + ")"; } return typeExpr(); }
java
public String typeExprForRecordMember(boolean isOptional) { if (typeExpressions.size() > 1 || isOptional) { // needs parens return "(" + typeExpr() + (isOptional && !typeExpressions.contains("undefined") ? "|undefined" : "") + ")"; } return typeExpr(); }
[ "public", "String", "typeExprForRecordMember", "(", "boolean", "isOptional", ")", "{", "if", "(", "typeExpressions", ".", "size", "(", ")", ">", "1", "||", "isOptional", ")", "{", "// needs parens", "return", "\"(\"", "+", "typeExpr", "(", ")", "+", "(", "...
Returns a type expression for a record member. In some cases this requires additional parens.
[ "Returns", "a", "type", "expression", "for", "a", "record", "member", ".", "In", "some", "cases", "this", "requires", "additional", "parens", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsType.java#L508-L517
train
google/closure-templates
java/src/com/google/template/soy/data/internal/DictImpl.java
DictImpl.forProviderMap
public static DictImpl forProviderMap( Map<String, ? extends SoyValueProvider> providerMap, RuntimeMapTypeTracker.Type mapType) { return new DictImpl(providerMap, mapType); }
java
public static DictImpl forProviderMap( Map<String, ? extends SoyValueProvider> providerMap, RuntimeMapTypeTracker.Type mapType) { return new DictImpl(providerMap, mapType); }
[ "public", "static", "DictImpl", "forProviderMap", "(", "Map", "<", "String", ",", "?", "extends", "SoyValueProvider", ">", "providerMap", ",", "RuntimeMapTypeTracker", ".", "Type", "mapType", ")", "{", "return", "new", "DictImpl", "(", "providerMap", ",", "mapTy...
Creates a SoyDict implementation for a particular underlying provider map. <p>The map may be mutable, but will not be mutated by the DictImpl.
[ "Creates", "a", "SoyDict", "implementation", "for", "a", "particular", "underlying", "provider", "map", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/internal/DictImpl.java#L85-L88
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/RenderException.java
RenderException.concatWithJavaStackTrace
private StackTraceElement[] concatWithJavaStackTrace(StackTraceElement[] javaStackTrace) { if (soyStackTrace.isEmpty()) { return javaStackTrace; } StackTraceElement[] finalStackTrace = new StackTraceElement[soyStackTrace.size() + javaStackTrace.length]; soyStackTrace.toArray(finalStackTrace); System.arraycopy( javaStackTrace, 0, finalStackTrace, soyStackTrace.size(), javaStackTrace.length); return finalStackTrace; }
java
private StackTraceElement[] concatWithJavaStackTrace(StackTraceElement[] javaStackTrace) { if (soyStackTrace.isEmpty()) { return javaStackTrace; } StackTraceElement[] finalStackTrace = new StackTraceElement[soyStackTrace.size() + javaStackTrace.length]; soyStackTrace.toArray(finalStackTrace); System.arraycopy( javaStackTrace, 0, finalStackTrace, soyStackTrace.size(), javaStackTrace.length); return finalStackTrace; }
[ "private", "StackTraceElement", "[", "]", "concatWithJavaStackTrace", "(", "StackTraceElement", "[", "]", "javaStackTrace", ")", "{", "if", "(", "soyStackTrace", ".", "isEmpty", "(", ")", ")", "{", "return", "javaStackTrace", ";", "}", "StackTraceElement", "[", ...
Prepend the soy stack trace to the given standard java stack trace. @param javaStackTrace The java stack trace to prepend. This should come from Throwable#getStackTrace() @return The combined stack trace to use. Callers should call Throwable#setStackTrace() to override another Throwable's stack trace.
[ "Prepend", "the", "soy", "stack", "trace", "to", "the", "given", "standard", "java", "stack", "trace", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/RenderException.java#L103-L114
train
google/closure-templates
java/src/com/google/template/soy/data/restricted/CollectionData.java
CollectionData.put
public void put(Object... data) { // TODO: Perhaps change to only convert varargs to Map, and do put(Map) elsewhere. if (data.length % 2 != 0) { throw new SoyDataException( "Varargs to put(...) must have an even number of arguments (key-value pairs)."); } for (int i = 0; i < data.length; i += 2) { try { put((String) data[i], SoyData.createFromExistingData(data[i + 1])); } catch (ClassCastException cce) { throw new SoyDataException( "Attempting to add a mapping containing a non-string key (key type " + data[i].getClass().getName() + ")."); } } }
java
public void put(Object... data) { // TODO: Perhaps change to only convert varargs to Map, and do put(Map) elsewhere. if (data.length % 2 != 0) { throw new SoyDataException( "Varargs to put(...) must have an even number of arguments (key-value pairs)."); } for (int i = 0; i < data.length; i += 2) { try { put((String) data[i], SoyData.createFromExistingData(data[i + 1])); } catch (ClassCastException cce) { throw new SoyDataException( "Attempting to add a mapping containing a non-string key (key type " + data[i].getClass().getName() + ")."); } } }
[ "public", "void", "put", "(", "Object", "...", "data", ")", "{", "// TODO: Perhaps change to only convert varargs to Map, and do put(Map) elsewhere.", "if", "(", "data", ".", "length", "%", "2", "!=", "0", ")", "{", "throw", "new", "SoyDataException", "(", "\"Vararg...
Convenience function to put multiple mappings in one call. @param data The mappings to put, as alternating keys/values. Indices 0, 2, 4, ... must be valid key strings. Indices 1, 3, 5, ... must be valid Soy data values. @throws SoyDataException When attempting to add an invalid varargs list or a mapping containing an invalid key.
[ "Convenience", "function", "to", "put", "multiple", "mappings", "in", "one", "call", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/restricted/CollectionData.java#L47-L64
train
google/closure-templates
java/src/com/google/template/soy/data/restricted/CollectionData.java
CollectionData.remove
public void remove(String keyStr) { List<String> keys = split(keyStr, '.'); int numKeys = keys.size(); CollectionData collectionData = this; for (int i = 0; i <= numKeys - 2; ++i) { SoyData soyData = collectionData.getSingle(keys.get(i)); if (!(soyData instanceof CollectionData)) { return; } collectionData = (CollectionData) soyData; } collectionData.removeSingle(keys.get(numKeys - 1)); }
java
public void remove(String keyStr) { List<String> keys = split(keyStr, '.'); int numKeys = keys.size(); CollectionData collectionData = this; for (int i = 0; i <= numKeys - 2; ++i) { SoyData soyData = collectionData.getSingle(keys.get(i)); if (!(soyData instanceof CollectionData)) { return; } collectionData = (CollectionData) soyData; } collectionData.removeSingle(keys.get(numKeys - 1)); }
[ "public", "void", "remove", "(", "String", "keyStr", ")", "{", "List", "<", "String", ">", "keys", "=", "split", "(", "keyStr", ",", "'", "'", ")", ";", "int", "numKeys", "=", "keys", ".", "size", "(", ")", ";", "CollectionData", "collectionData", "=...
Removes the data at the specified key string. @param keyStr One or more map keys and/or list indices (separated by '.' if multiple parts). Indicates the path to the location within this data tree.
[ "Removes", "the", "data", "at", "the", "specified", "key", "string", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/restricted/CollectionData.java#L164-L179
train
google/closure-templates
java/src/com/google/template/soy/data/restricted/CollectionData.java
CollectionData.split
private static List<String> split(String str, char delim) { List<String> result = Lists.newArrayList(); int currPartStart = 0; while (true) { int currPartEnd = str.indexOf(delim, currPartStart); if (currPartEnd == -1) { result.add(str.substring(currPartStart)); break; } else { result.add(str.substring(currPartStart, currPartEnd)); currPartStart = currPartEnd + 1; } } return result; }
java
private static List<String> split(String str, char delim) { List<String> result = Lists.newArrayList(); int currPartStart = 0; while (true) { int currPartEnd = str.indexOf(delim, currPartStart); if (currPartEnd == -1) { result.add(str.substring(currPartStart)); break; } else { result.add(str.substring(currPartStart, currPartEnd)); currPartStart = currPartEnd + 1; } } return result; }
[ "private", "static", "List", "<", "String", ">", "split", "(", "String", "str", ",", "char", "delim", ")", "{", "List", "<", "String", ">", "result", "=", "Lists", ".", "newArrayList", "(", ")", ";", "int", "currPartStart", "=", "0", ";", "while", "(...
Splits a string into tokens at the specified delimiter. @param str The string to split. Must not be null. @param delim The delimiter character. @return A list of tokens. Will not return null.
[ "Splits", "a", "string", "into", "tokens", "at", "the", "specified", "delimiter", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/restricted/CollectionData.java#L369-L386
train
google/closure-templates
java/src/com/google/template/soy/types/SoyTypes.java
SoyTypes.isNumericPrimitive
public static boolean isNumericPrimitive(SoyType type) { SoyType.Kind kind = type.getKind(); if (NUMERIC_PRIMITIVES.contains(kind)) { return true; } return type.isAssignableFrom(NUMBER_TYPE) || NUMBER_TYPE.isAssignableFrom(type); }
java
public static boolean isNumericPrimitive(SoyType type) { SoyType.Kind kind = type.getKind(); if (NUMERIC_PRIMITIVES.contains(kind)) { return true; } return type.isAssignableFrom(NUMBER_TYPE) || NUMBER_TYPE.isAssignableFrom(type); }
[ "public", "static", "boolean", "isNumericPrimitive", "(", "SoyType", "type", ")", "{", "SoyType", ".", "Kind", "kind", "=", "type", ".", "getKind", "(", ")", ";", "if", "(", "NUMERIC_PRIMITIVES", ".", "contains", "(", "kind", ")", ")", "{", "return", "tr...
Returns true if the input type is a numeric primitive type, such as int, float, proto enum, and number.
[ "Returns", "true", "if", "the", "input", "type", "is", "a", "numeric", "primitive", "type", "such", "as", "int", "float", "proto", "enum", "and", "number", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypes.java#L62-L68
train
google/closure-templates
java/src/com/google/template/soy/types/SoyTypes.java
SoyTypes.tryRemoveNull
public static SoyType tryRemoveNull(SoyType soyType) { if (soyType == NullType.getInstance()) { return NullType.getInstance(); } return removeNull(soyType); }
java
public static SoyType tryRemoveNull(SoyType soyType) { if (soyType == NullType.getInstance()) { return NullType.getInstance(); } return removeNull(soyType); }
[ "public", "static", "SoyType", "tryRemoveNull", "(", "SoyType", "soyType", ")", "{", "if", "(", "soyType", "==", "NullType", ".", "getInstance", "(", ")", ")", "{", "return", "NullType", ".", "getInstance", "(", ")", ";", "}", "return", "removeNull", "(", ...
If the type is nullable, makes it non-nullable. <p>If the type is the null type, then it returns the null type.
[ "If", "the", "type", "is", "nullable", "makes", "it", "non", "-", "nullable", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypes.java#L83-L88
train
google/closure-templates
java/src/com/google/template/soy/types/SoyTypes.java
SoyTypes.computeLowestCommonType
public static SoyType computeLowestCommonType( SoyTypeRegistry typeRegistry, SoyType t0, SoyType t1) { if (t0 == ErrorType.getInstance() || t1 == ErrorType.getInstance()) { return ErrorType.getInstance(); } if (t0.isAssignableFrom(t1)) { return t0; } else if (t1.isAssignableFrom(t0)) { return t1; } else { // Create a union. This preserves the most information. return typeRegistry.getOrCreateUnionType(t0, t1); } }
java
public static SoyType computeLowestCommonType( SoyTypeRegistry typeRegistry, SoyType t0, SoyType t1) { if (t0 == ErrorType.getInstance() || t1 == ErrorType.getInstance()) { return ErrorType.getInstance(); } if (t0.isAssignableFrom(t1)) { return t0; } else if (t1.isAssignableFrom(t0)) { return t1; } else { // Create a union. This preserves the most information. return typeRegistry.getOrCreateUnionType(t0, t1); } }
[ "public", "static", "SoyType", "computeLowestCommonType", "(", "SoyTypeRegistry", "typeRegistry", ",", "SoyType", "t0", ",", "SoyType", "t1", ")", "{", "if", "(", "t0", "==", "ErrorType", ".", "getInstance", "(", ")", "||", "t1", "==", "ErrorType", ".", "get...
Compute the most specific type that is assignable from both t0 and t1. @param typeRegistry Type registry. @param t0 A type. @param t1 Another type. @return A type that is assignable from both t0 and t1.
[ "Compute", "the", "most", "specific", "type", "that", "is", "assignable", "from", "both", "t0", "and", "t1", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypes.java#L114-L127
train
google/closure-templates
java/src/com/google/template/soy/types/SoyTypes.java
SoyTypes.computeLowestCommonType
public static SoyType computeLowestCommonType( SoyTypeRegistry typeRegistry, Collection<SoyType> types) { SoyType result = null; for (SoyType type : types) { result = (result == null) ? type : computeLowestCommonType(typeRegistry, result, type); } return result; }
java
public static SoyType computeLowestCommonType( SoyTypeRegistry typeRegistry, Collection<SoyType> types) { SoyType result = null; for (SoyType type : types) { result = (result == null) ? type : computeLowestCommonType(typeRegistry, result, type); } return result; }
[ "public", "static", "SoyType", "computeLowestCommonType", "(", "SoyTypeRegistry", "typeRegistry", ",", "Collection", "<", "SoyType", ">", "types", ")", "{", "SoyType", "result", "=", "null", ";", "for", "(", "SoyType", "type", ":", "types", ")", "{", "result",...
Compute the most specific type that is assignable from all types within a collection. @param typeRegistry Type registry. @param types List of types. @return A type that is assignable from all of the listed types.
[ "Compute", "the", "most", "specific", "type", "that", "is", "assignable", "from", "all", "types", "within", "a", "collection", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypes.java#L136-L143
train
google/closure-templates
java/src/com/google/template/soy/types/SoyTypes.java
SoyTypes.computeLowestCommonTypeArithmetic
public static Optional<SoyType> computeLowestCommonTypeArithmetic(SoyType t0, SoyType t1) { // If either of the types is an error type, return the error type if (t0.getKind() == Kind.ERROR || t1.getKind() == Kind.ERROR) { return Optional.of(ErrorType.getInstance()); } // If either of the types isn't numeric or unknown, then this isn't valid for an arithmetic // operation. if (!isNumericOrUnknown(t0) || !isNumericOrUnknown(t1)) { return Optional.absent(); } // Note: everything is assignable to unknown and itself. So the first two conditions take care // of all cases but a mix of float and int. if (t0.isAssignableFrom(t1)) { return Optional.of(t0); } else if (t1.isAssignableFrom(t0)) { return Optional.of(t1); } else { // If we get here then we know that we have a mix of float and int. In this case arithmetic // ops always 'upgrade' to float. So just return that. return Optional.of(FloatType.getInstance()); } }
java
public static Optional<SoyType> computeLowestCommonTypeArithmetic(SoyType t0, SoyType t1) { // If either of the types is an error type, return the error type if (t0.getKind() == Kind.ERROR || t1.getKind() == Kind.ERROR) { return Optional.of(ErrorType.getInstance()); } // If either of the types isn't numeric or unknown, then this isn't valid for an arithmetic // operation. if (!isNumericOrUnknown(t0) || !isNumericOrUnknown(t1)) { return Optional.absent(); } // Note: everything is assignable to unknown and itself. So the first two conditions take care // of all cases but a mix of float and int. if (t0.isAssignableFrom(t1)) { return Optional.of(t0); } else if (t1.isAssignableFrom(t0)) { return Optional.of(t1); } else { // If we get here then we know that we have a mix of float and int. In this case arithmetic // ops always 'upgrade' to float. So just return that. return Optional.of(FloatType.getInstance()); } }
[ "public", "static", "Optional", "<", "SoyType", ">", "computeLowestCommonTypeArithmetic", "(", "SoyType", "t0", ",", "SoyType", "t1", ")", "{", "// If either of the types is an error type, return the error type", "if", "(", "t0", ".", "getKind", "(", ")", "==", "Kind"...
Compute the most specific type that is assignable from both t0 and t1, taking into account arithmetic promotions - that is, converting int to float if needed. @param t0 A type. @param t1 Another type. @return A type that is assignable from both t0 and t1 or absent if the types are not arithmetic meaning a subtype of 'number' or unknown.
[ "Compute", "the", "most", "specific", "type", "that", "is", "assignable", "from", "both", "t0", "and", "t1", "taking", "into", "account", "arithmetic", "promotions", "-", "that", "is", "converting", "int", "to", "float", "if", "needed", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypes.java#L154-L176
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/DetachState.java
DetachState.detachForCall
Statement detachForCall(final Expression callRender) { checkArgument(callRender.resultType().equals(RENDER_RESULT_TYPE)); final Label reattachRender = new Label(); final SaveRestoreState saveRestoreState = variables.saveRestoreState(); // We pass NULL statement for the restore logic since we handle that ourselves below int state = addState(reattachRender, Statement.NULL_STATEMENT); final Statement saveState = stateField.putInstanceField(thisExpr, BytecodeUtils.constant(state)); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { // Legend: RR = RenderResult, Z = boolean callRender.gen(adapter); // Stack: RR adapter.dup(); // Stack: RR, RR MethodRef.RENDER_RESULT_IS_DONE.invokeUnchecked(adapter); // Stack: RR, Z // if isDone goto Done Label end = new Label(); adapter.ifZCmp(Opcodes.IFNE, end); // Stack: RR saveRestoreState.save().gen(adapter); saveState.gen(adapter); adapter.returnValue(); adapter.mark(reattachRender); callRender.gen(adapter); // Stack: RR adapter.dup(); // Stack: RR, RR MethodRef.RENDER_RESULT_IS_DONE.invokeUnchecked(adapter); // Stack: RR, Z // if isDone goto restore Label restore = new Label(); adapter.ifZCmp(Opcodes.IFNE, restore); // Stack: RR // no need to save or restore anything adapter.returnValue(); adapter.mark(restore); // Stack: RR saveRestoreState.restore().gen(adapter); adapter.mark(end); // Stack: RR adapter.pop(); // Stack: } }; }
java
Statement detachForCall(final Expression callRender) { checkArgument(callRender.resultType().equals(RENDER_RESULT_TYPE)); final Label reattachRender = new Label(); final SaveRestoreState saveRestoreState = variables.saveRestoreState(); // We pass NULL statement for the restore logic since we handle that ourselves below int state = addState(reattachRender, Statement.NULL_STATEMENT); final Statement saveState = stateField.putInstanceField(thisExpr, BytecodeUtils.constant(state)); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { // Legend: RR = RenderResult, Z = boolean callRender.gen(adapter); // Stack: RR adapter.dup(); // Stack: RR, RR MethodRef.RENDER_RESULT_IS_DONE.invokeUnchecked(adapter); // Stack: RR, Z // if isDone goto Done Label end = new Label(); adapter.ifZCmp(Opcodes.IFNE, end); // Stack: RR saveRestoreState.save().gen(adapter); saveState.gen(adapter); adapter.returnValue(); adapter.mark(reattachRender); callRender.gen(adapter); // Stack: RR adapter.dup(); // Stack: RR, RR MethodRef.RENDER_RESULT_IS_DONE.invokeUnchecked(adapter); // Stack: RR, Z // if isDone goto restore Label restore = new Label(); adapter.ifZCmp(Opcodes.IFNE, restore); // Stack: RR // no need to save or restore anything adapter.returnValue(); adapter.mark(restore); // Stack: RR saveRestoreState.restore().gen(adapter); adapter.mark(end); // Stack: RR adapter.pop(); // Stack: } }; }
[ "Statement", "detachForCall", "(", "final", "Expression", "callRender", ")", "{", "checkArgument", "(", "callRender", ".", "resultType", "(", ")", ".", "equals", "(", "RENDER_RESULT_TYPE", ")", ")", ";", "final", "Label", "reattachRender", "=", "new", "Label", ...
Generate detach logic for calls. <p>Calls are a little different due to a desire to minimize the cost of detaches. We assume that if a given call site detaches once, it is more likely to detach multiple times. So we generate code that looks like: <pre>{@code RenderResult initialResult = template.render(appendable, renderContext); if (!initialResult.isDone()) { // save all fields state = REATTACH_RENDER; return initialResult; } else { goto END; } REATTACH_RENDER: // restore nothing! RenderResult secondResult = template.render(appendable, renderContext); if (!secondResult.isDone()) { // saveFields state = REATTACH_RENDER; return secondResult; } else { // restore all fields goto END; } END: }</pre> <p>With this technique we save re-running the save-restore logic for multiple detaches from the same call site. This should be especially useful for top level templates. <p>A consequence of this technique is that the callRender expression cannot depend on any variables that are controlled by the restore logic. @param callRender an Expression that can generate code to call the render method, should be safe to generate more than once. And should not rely on any state that is managed by the save restore logic.
[ "Generate", "detach", "logic", "for", "calls", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/DetachState.java#L256-L294
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/DetachState.java
DetachState.generateReattachTable
Statement generateReattachTable() { final Expression readField = stateField.accessor(thisExpr); final Statement defaultCase = Statement.throwExpression(MethodRef.RUNTIME_UNEXPECTED_STATE_ERROR.invoke(readField)); return new Statement() { @Override protected void doGen(final CodeBuilder adapter) { int[] keys = new int[reattaches.size()]; for (int i = 0; i < keys.length; i++) { keys[i] = i; } readField.gen(adapter); // Generate a switch table. Note, while it might be preferable to just 'goto state', Java // doesn't allow computable gotos (probably because it makes verification impossible). So // instead we emulate that with a jump table. And anyway we still need to execute 'restore' // logic to repopulate the local variable tables, so the 'case' statements are a natural // place for that logic to live. adapter.tableSwitch( keys, new TableSwitchGenerator() { @Override public void generateCase(int key, Label end) { if (key == 0) { // State 0 is special, it means initial state, so we just jump to the very end adapter.goTo(end); return; } ReattachState reattachState = reattaches.get(key); // restore and jump! reattachState.restoreStatement().gen(adapter); adapter.goTo(reattachState.reattachPoint()); } @Override public void generateDefault() { defaultCase.gen(adapter); } }, // Use tableswitch instead of lookupswitch. TableSwitch is appropriate because our case // labels are sequential integers in the range [0, N). This means that switch is O(1) // and // there are no 'holes' meaning that it is compact in the bytecode. true); } }; }
java
Statement generateReattachTable() { final Expression readField = stateField.accessor(thisExpr); final Statement defaultCase = Statement.throwExpression(MethodRef.RUNTIME_UNEXPECTED_STATE_ERROR.invoke(readField)); return new Statement() { @Override protected void doGen(final CodeBuilder adapter) { int[] keys = new int[reattaches.size()]; for (int i = 0; i < keys.length; i++) { keys[i] = i; } readField.gen(adapter); // Generate a switch table. Note, while it might be preferable to just 'goto state', Java // doesn't allow computable gotos (probably because it makes verification impossible). So // instead we emulate that with a jump table. And anyway we still need to execute 'restore' // logic to repopulate the local variable tables, so the 'case' statements are a natural // place for that logic to live. adapter.tableSwitch( keys, new TableSwitchGenerator() { @Override public void generateCase(int key, Label end) { if (key == 0) { // State 0 is special, it means initial state, so we just jump to the very end adapter.goTo(end); return; } ReattachState reattachState = reattaches.get(key); // restore and jump! reattachState.restoreStatement().gen(adapter); adapter.goTo(reattachState.reattachPoint()); } @Override public void generateDefault() { defaultCase.gen(adapter); } }, // Use tableswitch instead of lookupswitch. TableSwitch is appropriate because our case // labels are sequential integers in the range [0, N). This means that switch is O(1) // and // there are no 'holes' meaning that it is compact in the bytecode. true); } }; }
[ "Statement", "generateReattachTable", "(", ")", "{", "final", "Expression", "readField", "=", "stateField", ".", "accessor", "(", "thisExpr", ")", ";", "final", "Statement", "defaultCase", "=", "Statement", ".", "throwExpression", "(", "MethodRef", ".", "RUNTIME_U...
Returns a statement that generates the reattach jump table. <p>Note: This statement should be the <em>first</em> statement in any detachable method.
[ "Returns", "a", "statement", "that", "generates", "the", "reattach", "jump", "table", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/DetachState.java#L301-L346
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/DetachState.java
DetachState.addState
private int addState(Label reattachPoint, Statement restore) { ReattachState create = ReattachState.create(reattachPoint, restore); reattaches.add(create); int state = reattaches.size() - 1; // the index of the ReattachState in the list return state; }
java
private int addState(Label reattachPoint, Statement restore) { ReattachState create = ReattachState.create(reattachPoint, restore); reattaches.add(create); int state = reattaches.size() - 1; // the index of the ReattachState in the list return state; }
[ "private", "int", "addState", "(", "Label", "reattachPoint", ",", "Statement", "restore", ")", "{", "ReattachState", "create", "=", "ReattachState", ".", "create", "(", "reattachPoint", ",", "restore", ")", ";", "reattaches", ".", "add", "(", "create", ")", ...
Add a new state item and return the state.
[ "Add", "a", "new", "state", "item", "and", "return", "the", "state", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/DetachState.java#L349-L354
train
google/closure-templates
java/src/com/google/template/soy/jssrc/dsl/Operation.java
Operation.shouldProtect
private boolean shouldProtect(Expression operand, OperandPosition operandPosition) { if (operand instanceof Operation) { Operation operation = (Operation) operand; return operation.precedence() < this.precedence() || (operation.precedence() == this.precedence() && operandPosition.shouldParenthesize(operation.associativity())); } else if (operand instanceof Leaf) { // JsExprs have precedence info, but not associativity. So at least check the precedence. JsExpr expr = ((Leaf) operand).value(); return expr.getPrecedence() < this.precedence(); } else { return false; } }
java
private boolean shouldProtect(Expression operand, OperandPosition operandPosition) { if (operand instanceof Operation) { Operation operation = (Operation) operand; return operation.precedence() < this.precedence() || (operation.precedence() == this.precedence() && operandPosition.shouldParenthesize(operation.associativity())); } else if (operand instanceof Leaf) { // JsExprs have precedence info, but not associativity. So at least check the precedence. JsExpr expr = ((Leaf) operand).value(); return expr.getPrecedence() < this.precedence(); } else { return false; } }
[ "private", "boolean", "shouldProtect", "(", "Expression", "operand", ",", "OperandPosition", "operandPosition", ")", "{", "if", "(", "operand", "instanceof", "Operation", ")", "{", "Operation", "operation", "=", "(", "Operation", ")", "operand", ";", "return", "...
An operand needs to be protected with parens if <ul> <li>its {@link #precedence} is lower than the operator's precedence, or <li>its precedence is the same as the operator's, it is {@link Associativity#LEFT left associative}, and it appears to the right of the operator, or <li>its precedence is the same as the operator's, it is {@link Associativity#RIGHT right associative}, and it appears to the left of the operator. </ul>
[ "An", "operand", "needs", "to", "be", "protected", "with", "parens", "if" ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Operation.java#L64-L77
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/opti/SimplifyVisitor.java
SimplifyVisitor.create
public static SimplifyVisitor create( IdGenerator idGenerator, ImmutableList<SoyFileNode> sourceFiles) { return new SimplifyVisitor( idGenerator, sourceFiles, new SimplifyExprVisitor(), new PreevalVisitorFactory()); }
java
public static SimplifyVisitor create( IdGenerator idGenerator, ImmutableList<SoyFileNode> sourceFiles) { return new SimplifyVisitor( idGenerator, sourceFiles, new SimplifyExprVisitor(), new PreevalVisitorFactory()); }
[ "public", "static", "SimplifyVisitor", "create", "(", "IdGenerator", "idGenerator", ",", "ImmutableList", "<", "SoyFileNode", ">", "sourceFiles", ")", "{", "return", "new", "SimplifyVisitor", "(", "idGenerator", ",", "sourceFiles", ",", "new", "SimplifyExprVisitor", ...
Creates a new simplify visitor.
[ "Creates", "a", "new", "simplify", "visitor", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/opti/SimplifyVisitor.java#L58-L62
train
google/closure-templates
java/src/com/google/template/soy/msgs/internal/SoyMsgIdComputer.java
SoyMsgIdComputer.buildMsgContentStrForMsgIdComputation
@VisibleForTesting static String buildMsgContentStrForMsgIdComputation( ImmutableList<SoyMsgPart> msgParts, boolean doUseBracedPhs) { msgParts = IcuSyntaxUtils.convertMsgPartsToEmbeddedIcuSyntax(msgParts); StringBuilder msgStrSb = new StringBuilder(); for (SoyMsgPart msgPart : msgParts) { if (msgPart instanceof SoyMsgRawTextPart) { msgStrSb.append(((SoyMsgRawTextPart) msgPart).getRawText()); } else if (msgPart instanceof SoyMsgPlaceholderPart) { if (doUseBracedPhs) { msgStrSb.append('{'); } msgStrSb.append(((SoyMsgPlaceholderPart) msgPart).getPlaceholderName()); if (doUseBracedPhs) { msgStrSb.append('}'); } } else { throw new AssertionError("unexpected child: " + msgPart); } } return msgStrSb.toString(); }
java
@VisibleForTesting static String buildMsgContentStrForMsgIdComputation( ImmutableList<SoyMsgPart> msgParts, boolean doUseBracedPhs) { msgParts = IcuSyntaxUtils.convertMsgPartsToEmbeddedIcuSyntax(msgParts); StringBuilder msgStrSb = new StringBuilder(); for (SoyMsgPart msgPart : msgParts) { if (msgPart instanceof SoyMsgRawTextPart) { msgStrSb.append(((SoyMsgRawTextPart) msgPart).getRawText()); } else if (msgPart instanceof SoyMsgPlaceholderPart) { if (doUseBracedPhs) { msgStrSb.append('{'); } msgStrSb.append(((SoyMsgPlaceholderPart) msgPart).getPlaceholderName()); if (doUseBracedPhs) { msgStrSb.append('}'); } } else { throw new AssertionError("unexpected child: " + msgPart); } } return msgStrSb.toString(); }
[ "@", "VisibleForTesting", "static", "String", "buildMsgContentStrForMsgIdComputation", "(", "ImmutableList", "<", "SoyMsgPart", ">", "msgParts", ",", "boolean", "doUseBracedPhs", ")", "{", "msgParts", "=", "IcuSyntaxUtils", ".", "convertMsgPartsToEmbeddedIcuSyntax", "(", ...
Private helper to build the canonical message content string that should be used for msg id computation. <p>Note: For people who know what "presentation" means in this context, the result string should be exactly the presentation string. @param msgParts The parts of the message. @param doUseBracedPhs Whether to use braced placeholders. @return The canonical message content string that should be used for msg id computation.
[ "Private", "helper", "to", "build", "the", "canonical", "message", "content", "string", "that", "should", "be", "used", "for", "msg", "id", "computation", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/internal/SoyMsgIdComputer.java#L129-L157
train
google/closure-templates
java/src/com/google/template/soy/soyparse/ParseErrors.java
ParseErrors.formatParseExceptionDetails
private static String formatParseExceptionDetails( String errorToken, List<String> expectedTokens) { // quotes/normalize the expected tokens before rendering, just in case after normalization some // can be deduplicated. ImmutableSet.Builder<String> normalizedTokensBuilder = ImmutableSet.builder(); for (String t : expectedTokens) { normalizedTokensBuilder.add(maybeQuoteForParseError(t)); } expectedTokens = normalizedTokensBuilder.build().asList(); StringBuilder details = new StringBuilder(); int numExpectedTokens = expectedTokens.size(); if (numExpectedTokens != 0) { details.append(": expected "); for (int i = 0; i < numExpectedTokens; i++) { details.append(expectedTokens.get(i)); if (i < numExpectedTokens - 2) { details.append(", "); } if (i == numExpectedTokens - 2) { if (numExpectedTokens > 2) { details.append(','); } details.append(" or "); } } } return String.format( "parse error at '%s'%s", escapeWhitespaceForErrorPrinting(errorToken), details.toString()); }
java
private static String formatParseExceptionDetails( String errorToken, List<String> expectedTokens) { // quotes/normalize the expected tokens before rendering, just in case after normalization some // can be deduplicated. ImmutableSet.Builder<String> normalizedTokensBuilder = ImmutableSet.builder(); for (String t : expectedTokens) { normalizedTokensBuilder.add(maybeQuoteForParseError(t)); } expectedTokens = normalizedTokensBuilder.build().asList(); StringBuilder details = new StringBuilder(); int numExpectedTokens = expectedTokens.size(); if (numExpectedTokens != 0) { details.append(": expected "); for (int i = 0; i < numExpectedTokens; i++) { details.append(expectedTokens.get(i)); if (i < numExpectedTokens - 2) { details.append(", "); } if (i == numExpectedTokens - 2) { if (numExpectedTokens > 2) { details.append(','); } details.append(" or "); } } } return String.format( "parse error at '%s'%s", escapeWhitespaceForErrorPrinting(errorToken), details.toString()); }
[ "private", "static", "String", "formatParseExceptionDetails", "(", "String", "errorToken", ",", "List", "<", "String", ">", "expectedTokens", ")", "{", "// quotes/normalize the expected tokens before rendering, just in case after normalization some", "// can be deduplicated.", "Imm...
A helper method for formatting javacc ParseExceptions. @param errorToken The piece of text that we were unable to parse. @param expectedTokens The set of formatted tokens that we were expecting next.
[ "A", "helper", "method", "for", "formatting", "javacc", "ParseExceptions", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soyparse/ParseErrors.java#L287-L317
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/EvalVisitor.java
EvalVisitor.maybeMarkBadProtoAccess
private static void maybeMarkBadProtoAccess(ExprNode expr, SoyValue value) { if (value instanceof SoyProtoValue) { ((SoyProtoValue) value).setAccessLocationKey(expr.getSourceLocation()); } }
java
private static void maybeMarkBadProtoAccess(ExprNode expr, SoyValue value) { if (value instanceof SoyProtoValue) { ((SoyProtoValue) value).setAccessLocationKey(expr.getSourceLocation()); } }
[ "private", "static", "void", "maybeMarkBadProtoAccess", "(", "ExprNode", "expr", ",", "SoyValue", "value", ")", "{", "if", "(", "value", "instanceof", "SoyProtoValue", ")", "{", "(", "(", "SoyProtoValue", ")", "value", ")", ".", "setAccessLocationKey", "(", "e...
If the value is a proto, then set the current access location since we are about to access it incorrectly.
[ "If", "the", "value", "is", "a", "proto", "then", "set", "the", "current", "access", "location", "since", "we", "are", "about", "to", "access", "it", "incorrectly", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/EvalVisitor.java#L481-L485
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/EvalVisitor.java
EvalVisitor.isNullOrUndefinedBase
private static boolean isNullOrUndefinedBase(SoyValue base) { return base == null || base instanceof NullData || base instanceof UndefinedData || base == NullSafetySentinel.INSTANCE; }
java
private static boolean isNullOrUndefinedBase(SoyValue base) { return base == null || base instanceof NullData || base instanceof UndefinedData || base == NullSafetySentinel.INSTANCE; }
[ "private", "static", "boolean", "isNullOrUndefinedBase", "(", "SoyValue", "base", ")", "{", "return", "base", "==", "null", "||", "base", "instanceof", "NullData", "||", "base", "instanceof", "UndefinedData", "||", "base", "==", "NullSafetySentinel", ".", "INSTANC...
Returns true if the base SoyValue of a data access chain is null or undefined.
[ "Returns", "true", "if", "the", "base", "SoyValue", "of", "a", "data", "access", "chain", "is", "null", "or", "undefined", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/EvalVisitor.java#L488-L493
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/opti/SimplifyExprVisitor.java
SimplifyExprVisitor.visitFieldAccessNode
@Override protected void visitFieldAccessNode(FieldAccessNode node) { // simplify children first visitChildren(node); ExprNode baseExpr = node.getChild(0); if (baseExpr instanceof RecordLiteralNode) { RecordLiteralNode recordLiteral = (RecordLiteralNode) baseExpr; for (int i = 0; i < recordLiteral.numChildren(); i++) { if (recordLiteral.getKey(i).identifier().equals(node.getFieldName())) { node.getParent().replaceChild(node, recordLiteral.getChild(i)); return; } } // replace with null? this should have been a compiler error. } else if (baseExpr instanceof ProtoInitNode) { ProtoInitNode protoInit = (ProtoInitNode) baseExpr; int fieldIndex = -1; for (int i = 0; i < protoInit.getParamNames().size(); i++) { if (protoInit.getParamNames().get(i).identifier().equals(node.getFieldName())) { fieldIndex = i; break; } } if (fieldIndex != -1) { node.getParent().replaceChild(node, protoInit.getChild(fieldIndex)); } else { // here we could replace with a default value or null, but for now, do nothing, rather than // implement proto default field semantics. } } }
java
@Override protected void visitFieldAccessNode(FieldAccessNode node) { // simplify children first visitChildren(node); ExprNode baseExpr = node.getChild(0); if (baseExpr instanceof RecordLiteralNode) { RecordLiteralNode recordLiteral = (RecordLiteralNode) baseExpr; for (int i = 0; i < recordLiteral.numChildren(); i++) { if (recordLiteral.getKey(i).identifier().equals(node.getFieldName())) { node.getParent().replaceChild(node, recordLiteral.getChild(i)); return; } } // replace with null? this should have been a compiler error. } else if (baseExpr instanceof ProtoInitNode) { ProtoInitNode protoInit = (ProtoInitNode) baseExpr; int fieldIndex = -1; for (int i = 0; i < protoInit.getParamNames().size(); i++) { if (protoInit.getParamNames().get(i).identifier().equals(node.getFieldName())) { fieldIndex = i; break; } } if (fieldIndex != -1) { node.getParent().replaceChild(node, protoInit.getChild(fieldIndex)); } else { // here we could replace with a default value or null, but for now, do nothing, rather than // implement proto default field semantics. } } }
[ "@", "Override", "protected", "void", "visitFieldAccessNode", "(", "FieldAccessNode", "node", ")", "{", "// simplify children first", "visitChildren", "(", "node", ")", ";", "ExprNode", "baseExpr", "=", "node", ".", "getChild", "(", "0", ")", ";", "if", "(", "...
this code since it desugars into a record literal.
[ "this", "code", "since", "it", "desugars", "into", "a", "record", "literal", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/opti/SimplifyExprVisitor.java#L148-L178
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/opti/SimplifyExprVisitor.java
SimplifyExprVisitor.attemptPreeval
private void attemptPreeval(ExprNode node) { // Note that we need to catch RenderException because preevaluation may fail, e.g. when // (a) the expression uses a bidi function that needs bidiGlobalDir to be in scope, but the // apiCallScope is not currently active, // (b) the expression uses an external function (Soy V1 syntax), // (c) other cases I haven't thought up. SoyValue preevalResult; try { preevalResult = preevalVisitor.exec(node); } catch (RenderException e) { return; // failed to preevaluate } PrimitiveNode newNode = InternalValueUtils.convertPrimitiveDataToExpr( (PrimitiveData) preevalResult, node.getSourceLocation()); if (newNode != null) { node.getParent().replaceChild(node, newNode); } }
java
private void attemptPreeval(ExprNode node) { // Note that we need to catch RenderException because preevaluation may fail, e.g. when // (a) the expression uses a bidi function that needs bidiGlobalDir to be in scope, but the // apiCallScope is not currently active, // (b) the expression uses an external function (Soy V1 syntax), // (c) other cases I haven't thought up. SoyValue preevalResult; try { preevalResult = preevalVisitor.exec(node); } catch (RenderException e) { return; // failed to preevaluate } PrimitiveNode newNode = InternalValueUtils.convertPrimitiveDataToExpr( (PrimitiveData) preevalResult, node.getSourceLocation()); if (newNode != null) { node.getParent().replaceChild(node, newNode); } }
[ "private", "void", "attemptPreeval", "(", "ExprNode", "node", ")", "{", "// Note that we need to catch RenderException because preevaluation may fail, e.g. when", "// (a) the expression uses a bidi function that needs bidiGlobalDir to be in scope, but the", "// apiCallScope is not currently ...
Attempts to preevaluate a node. If successful, the node is replaced with a new constant node in the tree. If unsuccessful, the tree is not changed.
[ "Attempts", "to", "preevaluate", "a", "node", ".", "If", "successful", "the", "node", "is", "replaced", "with", "a", "new", "constant", "node", "in", "the", "tree", ".", "If", "unsuccessful", "the", "tree", "is", "not", "changed", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/opti/SimplifyExprVisitor.java#L262-L282
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/opti/SimplifyExprVisitor.java
SimplifyExprVisitor.getConstantOrNull
static SoyValue getConstantOrNull(ExprNode expr) { switch (expr.getKind()) { case NULL_NODE: return NullData.INSTANCE; case BOOLEAN_NODE: return BooleanData.forValue(((BooleanNode) expr).getValue()); case INTEGER_NODE: return IntegerData.forValue(((IntegerNode) expr).getValue()); case FLOAT_NODE: return FloatData.forValue(((FloatNode) expr).getValue()); case STRING_NODE: return StringData.forValue(((StringNode) expr).getValue()); case GLOBAL_NODE: GlobalNode global = (GlobalNode) expr; if (global.isResolved()) { return getConstantOrNull(global.getValue()); } return null; default: return null; } }
java
static SoyValue getConstantOrNull(ExprNode expr) { switch (expr.getKind()) { case NULL_NODE: return NullData.INSTANCE; case BOOLEAN_NODE: return BooleanData.forValue(((BooleanNode) expr).getValue()); case INTEGER_NODE: return IntegerData.forValue(((IntegerNode) expr).getValue()); case FLOAT_NODE: return FloatData.forValue(((FloatNode) expr).getValue()); case STRING_NODE: return StringData.forValue(((StringNode) expr).getValue()); case GLOBAL_NODE: GlobalNode global = (GlobalNode) expr; if (global.isResolved()) { return getConstantOrNull(global.getValue()); } return null; default: return null; } }
[ "static", "SoyValue", "getConstantOrNull", "(", "ExprNode", "expr", ")", "{", "switch", "(", "expr", ".", "getKind", "(", ")", ")", "{", "case", "NULL_NODE", ":", "return", "NullData", ".", "INSTANCE", ";", "case", "BOOLEAN_NODE", ":", "return", "BooleanData...
Returns the value of the given expression if it's constant, else returns null.
[ "Returns", "the", "value", "of", "the", "given", "expression", "if", "it", "s", "constant", "else", "returns", "null", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/opti/SimplifyExprVisitor.java#L290-L312
train
google/closure-templates
java/src/com/google/template/soy/internal/proto/FieldVisitor.java
FieldVisitor.visitField
public static <T> T visitField(FieldDescriptor fieldDescriptor, FieldVisitor<T> visitor) { // NOTE: map fields are technically repeated, so check isMap first. if (fieldDescriptor.isMapField()) { List<FieldDescriptor> mapFields = fieldDescriptor.getMessageType().getFields(); checkState(mapFields.size() == 2, "proto representation of map fields changed"); FieldDescriptor keyField = mapFields.get(0); FieldDescriptor valueField = mapFields.get(1); return visitor.visitMap( fieldDescriptor, getScalarType(keyField, visitor), getScalarType(valueField, visitor)); } else if (fieldDescriptor.isRepeated()) { return visitor.visitRepeated(getScalarType(fieldDescriptor, visitor)); } else { return getScalarType(fieldDescriptor, visitor); } }
java
public static <T> T visitField(FieldDescriptor fieldDescriptor, FieldVisitor<T> visitor) { // NOTE: map fields are technically repeated, so check isMap first. if (fieldDescriptor.isMapField()) { List<FieldDescriptor> mapFields = fieldDescriptor.getMessageType().getFields(); checkState(mapFields.size() == 2, "proto representation of map fields changed"); FieldDescriptor keyField = mapFields.get(0); FieldDescriptor valueField = mapFields.get(1); return visitor.visitMap( fieldDescriptor, getScalarType(keyField, visitor), getScalarType(valueField, visitor)); } else if (fieldDescriptor.isRepeated()) { return visitor.visitRepeated(getScalarType(fieldDescriptor, visitor)); } else { return getScalarType(fieldDescriptor, visitor); } }
[ "public", "static", "<", "T", ">", "T", "visitField", "(", "FieldDescriptor", "fieldDescriptor", ",", "FieldVisitor", "<", "T", ">", "visitor", ")", "{", "// NOTE: map fields are technically repeated, so check isMap first.", "if", "(", "fieldDescriptor", ".", "isMapFiel...
Applies the visitor to the given field.
[ "Applies", "the", "visitor", "to", "the", "given", "field", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/FieldVisitor.java#L36-L50
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/JbcSrcJavaValue.java
JbcSrcJavaValue.error
static JbcSrcJavaValue error(Expression expr, JbcSrcValueErrorReporter reporter) { return new JbcSrcJavaValue( expr, /* method= */ null, /* allowedType= */ null, /* constantNull= */ false, /* error= */ true, reporter); }
java
static JbcSrcJavaValue error(Expression expr, JbcSrcValueErrorReporter reporter) { return new JbcSrcJavaValue( expr, /* method= */ null, /* allowedType= */ null, /* constantNull= */ false, /* error= */ true, reporter); }
[ "static", "JbcSrcJavaValue", "error", "(", "Expression", "expr", ",", "JbcSrcValueErrorReporter", "reporter", ")", "{", "return", "new", "JbcSrcJavaValue", "(", "expr", ",", "/* method= */", "null", ",", "/* allowedType= */", "null", ",", "/* constantNull= */", "false...
Constructs a JbcSrcJavaValue that represents an error.
[ "Constructs", "a", "JbcSrcJavaValue", "that", "represents", "an", "error", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/JbcSrcJavaValue.java#L39-L47
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/JbcSrcJavaValue.java
JbcSrcJavaValue.of
static JbcSrcJavaValue of(Expression expr, JbcSrcValueErrorReporter reporter) { if (expr instanceof SoyExpression) { return new JbcSrcJavaValue( expr, /* method= */ null, /* allowedType= */ ((SoyExpression) expr).soyType(), /* constantNull= */ false, /* error= */ false, reporter); } return new JbcSrcJavaValue( expr, /* method= */ null, /* allowedType= */ null, /* constantNull= */ false, /* error= */ false, reporter); }
java
static JbcSrcJavaValue of(Expression expr, JbcSrcValueErrorReporter reporter) { if (expr instanceof SoyExpression) { return new JbcSrcJavaValue( expr, /* method= */ null, /* allowedType= */ ((SoyExpression) expr).soyType(), /* constantNull= */ false, /* error= */ false, reporter); } return new JbcSrcJavaValue( expr, /* method= */ null, /* allowedType= */ null, /* constantNull= */ false, /* error= */ false, reporter); }
[ "static", "JbcSrcJavaValue", "of", "(", "Expression", "expr", ",", "JbcSrcValueErrorReporter", "reporter", ")", "{", "if", "(", "expr", "instanceof", "SoyExpression", ")", "{", "return", "new", "JbcSrcJavaValue", "(", "expr", ",", "/* method= */", "null", ",", "...
Constructs a JbcSrcJavaValue based on the Expression.
[ "Constructs", "a", "JbcSrcJavaValue", "based", "on", "the", "Expression", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/JbcSrcJavaValue.java#L50-L67
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/JbcSrcJavaValue.java
JbcSrcJavaValue.of
static JbcSrcJavaValue of(Expression expr, Method method, JbcSrcValueErrorReporter reporter) { checkNotNull(method); if (expr instanceof SoyExpression) { return new JbcSrcJavaValue( expr, method, /* allowedType= */ ((SoyExpression) expr).soyType(), /* constantNull= */ false, /* error= */ false, reporter); } return new JbcSrcJavaValue( expr, method, /* allowedType= */ null, /* constantNull= */ false, /* error= */ false, reporter); }
java
static JbcSrcJavaValue of(Expression expr, Method method, JbcSrcValueErrorReporter reporter) { checkNotNull(method); if (expr instanceof SoyExpression) { return new JbcSrcJavaValue( expr, method, /* allowedType= */ ((SoyExpression) expr).soyType(), /* constantNull= */ false, /* error= */ false, reporter); } return new JbcSrcJavaValue( expr, method, /* allowedType= */ null, /* constantNull= */ false, /* error= */ false, reporter); }
[ "static", "JbcSrcJavaValue", "of", "(", "Expression", "expr", ",", "Method", "method", ",", "JbcSrcValueErrorReporter", "reporter", ")", "{", "checkNotNull", "(", "method", ")", ";", "if", "(", "expr", "instanceof", "SoyExpression", ")", "{", "return", "new", ...
Constructs a JbcSrcJavaValue based on the Expression. The method is used to display helpful error messages to the user if necessary. It is not invoked.
[ "Constructs", "a", "JbcSrcJavaValue", "based", "on", "the", "Expression", ".", "The", "method", "is", "used", "to", "display", "helpful", "error", "messages", "to", "the", "user", "if", "necessary", ".", "It", "is", "not", "invoked", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/JbcSrcJavaValue.java#L73-L91
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/JbcSrcJavaValue.java
JbcSrcJavaValue.of
static JbcSrcJavaValue of( SoyExpression expr, SoyType allowedType, JbcSrcValueErrorReporter reporter) { return new JbcSrcJavaValue( expr, /* method= */ null, checkNotNull(allowedType), /* constantNull= */ false, /* error= */ false, reporter); }
java
static JbcSrcJavaValue of( SoyExpression expr, SoyType allowedType, JbcSrcValueErrorReporter reporter) { return new JbcSrcJavaValue( expr, /* method= */ null, checkNotNull(allowedType), /* constantNull= */ false, /* error= */ false, reporter); }
[ "static", "JbcSrcJavaValue", "of", "(", "SoyExpression", "expr", ",", "SoyType", "allowedType", ",", "JbcSrcValueErrorReporter", "reporter", ")", "{", "return", "new", "JbcSrcJavaValue", "(", "expr", ",", "/* method= */", "null", ",", "checkNotNull", "(", "allowedTy...
Constructs a JbcSrcJavaValue based on the Expression, with the given SoyType as allowed types. The SoyType is expected to be based on the function signature, so can be broader than the soy type of the expression itself. The expression is expected to be assignable to the type.
[ "Constructs", "a", "JbcSrcJavaValue", "based", "on", "the", "Expression", "with", "the", "given", "SoyType", "as", "allowed", "types", ".", "The", "SoyType", "is", "expected", "to", "be", "based", "on", "the", "function", "signature", "so", "can", "be", "bro...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/JbcSrcJavaValue.java#L98-L107
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java
BytecodeUtils.classFromAsmType
public static Class<?> classFromAsmType(Type type) { Optional<Class<?>> maybeClass = objectTypeToClassCache.getUnchecked(type); if (!maybeClass.isPresent()) { throw new IllegalArgumentException("Could not load: " + type); } return maybeClass.get(); }
java
public static Class<?> classFromAsmType(Type type) { Optional<Class<?>> maybeClass = objectTypeToClassCache.getUnchecked(type); if (!maybeClass.isPresent()) { throw new IllegalArgumentException("Could not load: " + type); } return maybeClass.get(); }
[ "public", "static", "Class", "<", "?", ">", "classFromAsmType", "(", "Type", "type", ")", "{", "Optional", "<", "Class", "<", "?", ">", ">", "maybeClass", "=", "objectTypeToClassCache", ".", "getUnchecked", "(", "type", ")", ";", "if", "(", "!", "maybeCl...
Returns the runtime class represented by the given type. @throws IllegalArgumentException if the class cannot be found. It is expected that this method will only be called for types that have a runtime on the compilers classpath.
[ "Returns", "the", "runtime", "class", "represented", "by", "the", "given", "type", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L220-L226
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java
BytecodeUtils.numericConversion
public static Expression numericConversion(final Expression expr, final Type to) { if (to.equals(expr.resultType())) { return expr; } if (!isNumericPrimitive(to) || !isNumericPrimitive(expr.resultType())) { throw new IllegalArgumentException("Cannot convert from " + expr.resultType() + " to " + to); } return new Expression(to, expr.features()) { @Override protected void doGen(CodeBuilder adapter) { expr.gen(adapter); adapter.cast(expr.resultType(), to); } }; }
java
public static Expression numericConversion(final Expression expr, final Type to) { if (to.equals(expr.resultType())) { return expr; } if (!isNumericPrimitive(to) || !isNumericPrimitive(expr.resultType())) { throw new IllegalArgumentException("Cannot convert from " + expr.resultType() + " to " + to); } return new Expression(to, expr.features()) { @Override protected void doGen(CodeBuilder adapter) { expr.gen(adapter); adapter.cast(expr.resultType(), to); } }; }
[ "public", "static", "Expression", "numericConversion", "(", "final", "Expression", "expr", ",", "final", "Type", "to", ")", "{", "if", "(", "to", ".", "equals", "(", "expr", ".", "resultType", "(", ")", ")", ")", "{", "return", "expr", ";", "}", "if", ...
Returns an expression that does a numeric conversion cast from the given expression to the given type. @throws IllegalArgumentException if either the expression or the target type is not a numeric primitive
[ "Returns", "an", "expression", "that", "does", "a", "numeric", "conversion", "cast", "from", "the", "given", "expression", "to", "the", "given", "type", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L409-L423
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java
BytecodeUtils.compare
public static Expression compare( final int comparisonOpcode, final Expression left, final Expression right) { checkArgument( left.resultType().equals(right.resultType()), "left and right must have matching types, found %s and %s", left.resultType(), right.resultType()); checkIntComparisonOpcode(left.resultType(), comparisonOpcode); Features features = Expression.areAllCheap(left, right) ? Features.of(Feature.CHEAP) : Features.of(); return new Expression(Type.BOOLEAN_TYPE, features) { @Override protected void doGen(CodeBuilder mv) { left.gen(mv); right.gen(mv); Label ifTrue = mv.newLabel(); Label end = mv.newLabel(); mv.ifCmp(left.resultType(), comparisonOpcode, ifTrue); mv.pushBoolean(false); mv.goTo(end); mv.mark(ifTrue); mv.pushBoolean(true); mv.mark(end); } }; }
java
public static Expression compare( final int comparisonOpcode, final Expression left, final Expression right) { checkArgument( left.resultType().equals(right.resultType()), "left and right must have matching types, found %s and %s", left.resultType(), right.resultType()); checkIntComparisonOpcode(left.resultType(), comparisonOpcode); Features features = Expression.areAllCheap(left, right) ? Features.of(Feature.CHEAP) : Features.of(); return new Expression(Type.BOOLEAN_TYPE, features) { @Override protected void doGen(CodeBuilder mv) { left.gen(mv); right.gen(mv); Label ifTrue = mv.newLabel(); Label end = mv.newLabel(); mv.ifCmp(left.resultType(), comparisonOpcode, ifTrue); mv.pushBoolean(false); mv.goTo(end); mv.mark(ifTrue); mv.pushBoolean(true); mv.mark(end); } }; }
[ "public", "static", "Expression", "compare", "(", "final", "int", "comparisonOpcode", ",", "final", "Expression", "left", ",", "final", "Expression", "right", ")", "{", "checkArgument", "(", "left", ".", "resultType", "(", ")", ".", "equals", "(", "right", "...
Compares the two primitive valued expressions using the provided comparison operation.
[ "Compares", "the", "two", "primitive", "valued", "expressions", "using", "the", "provided", "comparison", "operation", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L502-L527
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java
BytecodeUtils.logicalNot
public static Expression logicalNot(final Expression baseExpr) { baseExpr.checkAssignableTo(Type.BOOLEAN_TYPE); checkArgument(baseExpr.resultType().equals(Type.BOOLEAN_TYPE), "not a boolean expression"); return new Expression(Type.BOOLEAN_TYPE, baseExpr.features()) { @Override protected void doGen(CodeBuilder mv) { baseExpr.gen(mv); // Surprisingly, java bytecode uses a branch (instead of 'xor 1' or something) to implement // this. This is most likely useful for allowing true to be represented by any non-zero // number. Label ifTrue = mv.newLabel(); Label end = mv.newLabel(); mv.ifZCmp(Opcodes.IFNE, ifTrue); // if not 0 goto ifTrue mv.pushBoolean(true); mv.goTo(end); mv.mark(ifTrue); mv.pushBoolean(false); mv.mark(end); } }; }
java
public static Expression logicalNot(final Expression baseExpr) { baseExpr.checkAssignableTo(Type.BOOLEAN_TYPE); checkArgument(baseExpr.resultType().equals(Type.BOOLEAN_TYPE), "not a boolean expression"); return new Expression(Type.BOOLEAN_TYPE, baseExpr.features()) { @Override protected void doGen(CodeBuilder mv) { baseExpr.gen(mv); // Surprisingly, java bytecode uses a branch (instead of 'xor 1' or something) to implement // this. This is most likely useful for allowing true to be represented by any non-zero // number. Label ifTrue = mv.newLabel(); Label end = mv.newLabel(); mv.ifZCmp(Opcodes.IFNE, ifTrue); // if not 0 goto ifTrue mv.pushBoolean(true); mv.goTo(end); mv.mark(ifTrue); mv.pushBoolean(false); mv.mark(end); } }; }
[ "public", "static", "Expression", "logicalNot", "(", "final", "Expression", "baseExpr", ")", "{", "baseExpr", ".", "checkAssignableTo", "(", "Type", ".", "BOOLEAN_TYPE", ")", ";", "checkArgument", "(", "baseExpr", ".", "resultType", "(", ")", ".", "equals", "(...
Returns an expression that evaluates to the logical negation of the given boolean valued expression.
[ "Returns", "an", "expression", "that", "evaluates", "to", "the", "logical", "negation", "of", "the", "given", "boolean", "valued", "expression", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L553-L573
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java
BytecodeUtils.doEqualsString
private static Expression doEqualsString(SoyExpression stringExpr, SoyExpression other) { // This is compatible with SharedRuntime.compareString, which interestingly makes == break // transitivity. See b/21461181 SoyRuntimeType otherRuntimeType = other.soyRuntimeType(); if (otherRuntimeType.isKnownStringOrSanitizedContent()) { if (stringExpr.isNonNullable()) { return stringExpr.invoke(MethodRef.EQUALS, other.unboxAsString()); } else { return MethodRef.OBJECTS_EQUALS.invoke(stringExpr, other.unboxAsString()); } } if (otherRuntimeType.isKnownNumber() && other.isNonNullable()) { // in this case, we actually try to convert stringExpr to a number return MethodRef.RUNTIME_STRING_EQUALS_AS_NUMBER.invoke(stringExpr, other.coerceToDouble()); } // We don't know what other is, assume the worst and call out to our boxed implementation for // string comparisons. return MethodRef.RUNTIME_COMPARE_NULLABLE_STRING.invoke(stringExpr, other.box()); }
java
private static Expression doEqualsString(SoyExpression stringExpr, SoyExpression other) { // This is compatible with SharedRuntime.compareString, which interestingly makes == break // transitivity. See b/21461181 SoyRuntimeType otherRuntimeType = other.soyRuntimeType(); if (otherRuntimeType.isKnownStringOrSanitizedContent()) { if (stringExpr.isNonNullable()) { return stringExpr.invoke(MethodRef.EQUALS, other.unboxAsString()); } else { return MethodRef.OBJECTS_EQUALS.invoke(stringExpr, other.unboxAsString()); } } if (otherRuntimeType.isKnownNumber() && other.isNonNullable()) { // in this case, we actually try to convert stringExpr to a number return MethodRef.RUNTIME_STRING_EQUALS_AS_NUMBER.invoke(stringExpr, other.coerceToDouble()); } // We don't know what other is, assume the worst and call out to our boxed implementation for // string comparisons. return MethodRef.RUNTIME_COMPARE_NULLABLE_STRING.invoke(stringExpr, other.box()); }
[ "private", "static", "Expression", "doEqualsString", "(", "SoyExpression", "stringExpr", ",", "SoyExpression", "other", ")", "{", "// This is compatible with SharedRuntime.compareString, which interestingly makes == break", "// transitivity. See b/21461181", "SoyRuntimeType", "otherRu...
Compare a string valued expression to another expression using soy == semantics. @param stringExpr An expression that is known to be an unboxed string @param other An expression to compare it to.
[ "Compare", "a", "string", "valued", "expression", "to", "another", "expression", "using", "soy", "==", "semantics", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L611-L629
train
google/closure-templates
java/src/com/google/template/soy/pysrc/restricted/PyFunctionExprBuilder.java
PyFunctionExprBuilder.setUnpackedKwargs
public PyFunctionExprBuilder setUnpackedKwargs(PyExpr mapping) { if (unpackedKwargs != null) { throw new UnsupportedOperationException("Only one kwarg unpacking allowed per expression."); } StringBuilder expr = new StringBuilder("**"); if (mapping.getPrecedence() < Integer.MAX_VALUE) { expr.append("(").append(mapping.getText()).append(")"); } else { expr.append(mapping.getText()); } unpackedKwargs = expr.toString(); return this; }
java
public PyFunctionExprBuilder setUnpackedKwargs(PyExpr mapping) { if (unpackedKwargs != null) { throw new UnsupportedOperationException("Only one kwarg unpacking allowed per expression."); } StringBuilder expr = new StringBuilder("**"); if (mapping.getPrecedence() < Integer.MAX_VALUE) { expr.append("(").append(mapping.getText()).append(")"); } else { expr.append(mapping.getText()); } unpackedKwargs = expr.toString(); return this; }
[ "public", "PyFunctionExprBuilder", "setUnpackedKwargs", "(", "PyExpr", "mapping", ")", "{", "if", "(", "unpackedKwargs", "!=", "null", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Only one kwarg unpacking allowed per expression.\"", ")", ";", "}", ...
Unpacking keyword arguments will expand a dictionary into a series of keyword arguments. <p>NOTE: Keyword unpacking behavior is only guaranteed for mapping expressions. Non-mapping expressions which attempt to unpack will result in Python runtime errors. @param mapping The mapping expression to unpack. @return This PyFunctionExprBuilder instance.
[ "Unpacking", "keyword", "arguments", "will", "expand", "a", "dictionary", "into", "a", "series", "of", "keyword", "arguments", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/restricted/PyFunctionExprBuilder.java#L124-L136
train
google/closure-templates
java/src/com/google/template/soy/pysrc/restricted/PyFunctionExprBuilder.java
PyFunctionExprBuilder.build
public String build() { StringBuilder sb = new StringBuilder(funcName + "("); // Join args and kwargs into simple strings. String args = argList.stream() .map(PyExpr::getText) .filter(Objects::nonNull) .collect(Collectors.joining(", ")); String kwargs = kwargMap.entrySet().stream() .map(entry -> entry.getKey() + "=" + entry.getValue().getText()) .filter(Objects::nonNull) .collect(Collectors.joining(", ")); // Strip empty strings. args = Strings.emptyToNull(args); kwargs = Strings.emptyToNull(kwargs); // Join all pieces together. Joiner.on(", ").skipNulls().appendTo(sb, args, kwargs, unpackedKwargs); sb.append(")"); return sb.toString(); }
java
public String build() { StringBuilder sb = new StringBuilder(funcName + "("); // Join args and kwargs into simple strings. String args = argList.stream() .map(PyExpr::getText) .filter(Objects::nonNull) .collect(Collectors.joining(", ")); String kwargs = kwargMap.entrySet().stream() .map(entry -> entry.getKey() + "=" + entry.getValue().getText()) .filter(Objects::nonNull) .collect(Collectors.joining(", ")); // Strip empty strings. args = Strings.emptyToNull(args); kwargs = Strings.emptyToNull(kwargs); // Join all pieces together. Joiner.on(", ").skipNulls().appendTo(sb, args, kwargs, unpackedKwargs); sb.append(")"); return sb.toString(); }
[ "public", "String", "build", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "funcName", "+", "\"(\"", ")", ";", "// Join args and kwargs into simple strings.", "String", "args", "=", "argList", ".", "stream", "(", ")", ".", "map", "(",...
Returns a valid Python function call as a String.
[ "Returns", "a", "valid", "Python", "function", "call", "as", "a", "String", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/restricted/PyFunctionExprBuilder.java#L139-L163
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java
RenderVisitor.createHelperInstance
protected RenderVisitor createHelperInstance(Appendable outputBuf, SoyRecord data) { return new RenderVisitor( evalVisitorFactory, outputBuf, basicTemplates, deltemplates, data, ijData, activeDelPackageSelector, msgBundle, xidRenamingMap, cssRenamingMap, debugSoyTemplateInfo, pluginInstances); }
java
protected RenderVisitor createHelperInstance(Appendable outputBuf, SoyRecord data) { return new RenderVisitor( evalVisitorFactory, outputBuf, basicTemplates, deltemplates, data, ijData, activeDelPackageSelector, msgBundle, xidRenamingMap, cssRenamingMap, debugSoyTemplateInfo, pluginInstances); }
[ "protected", "RenderVisitor", "createHelperInstance", "(", "Appendable", "outputBuf", ",", "SoyRecord", "data", ")", "{", "return", "new", "RenderVisitor", "(", "evalVisitorFactory", ",", "outputBuf", ",", "basicTemplates", ",", "deltemplates", ",", "data", ",", "ij...
Creates a helper instance for rendering a subtemplate. @param outputBuf The Appendable to append the output to. @param data The template data. @return The newly created RenderVisitor instance.
[ "Creates", "a", "helper", "instance", "for", "rendering", "a", "subtemplate", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java#L239-L253
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java
RenderVisitor.renderTemplate
private void renderTemplate(TemplateNode template, Predicate<String> paramsToTypeCheck) { env = Environment.create(template, data, ijData); checkStrictParamTypes(template, paramsToTypeCheck); visitChildren(template); env = null; // unpin for gc }
java
private void renderTemplate(TemplateNode template, Predicate<String> paramsToTypeCheck) { env = Environment.create(template, data, ijData); checkStrictParamTypes(template, paramsToTypeCheck); visitChildren(template); env = null; // unpin for gc }
[ "private", "void", "renderTemplate", "(", "TemplateNode", "template", ",", "Predicate", "<", "String", ">", "paramsToTypeCheck", ")", "{", "env", "=", "Environment", ".", "create", "(", "template", ",", "data", ",", "ijData", ")", ";", "checkStrictParamTypes", ...
A private helper to render templates with optimized type checking.
[ "A", "private", "helper", "to", "render", "templates", "with", "optimized", "type", "checking", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java#L264-L269
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java
RenderVisitor.eval
private SoyValue eval(ExprNode expr, SoyNode node) { if (expr == null) { throw RenderException.create("Cannot evaluate expression in V1 syntax.") .addStackTraceElement(node); } // Lazily initialize evalVisitor. if (evalVisitor == null) { evalVisitor = evalVisitorFactory.create( env, cssRenamingMap, xidRenamingMap, msgBundle, debugSoyTemplateInfo, pluginInstances); } try { return evalVisitor.exec(expr); } catch (RenderException e) { // RenderExceptions can be thrown when evaluating lazy transclusions. throw RenderException.createFromRenderException( "When evaluating \"" + expr.toSourceString() + "\": " + e.getMessage(), e, node); } catch (Exception e) { throw RenderException.createWithSource( "When evaluating \"" + expr.toSourceString() + "\": " + e.getMessage(), e, node); } }
java
private SoyValue eval(ExprNode expr, SoyNode node) { if (expr == null) { throw RenderException.create("Cannot evaluate expression in V1 syntax.") .addStackTraceElement(node); } // Lazily initialize evalVisitor. if (evalVisitor == null) { evalVisitor = evalVisitorFactory.create( env, cssRenamingMap, xidRenamingMap, msgBundle, debugSoyTemplateInfo, pluginInstances); } try { return evalVisitor.exec(expr); } catch (RenderException e) { // RenderExceptions can be thrown when evaluating lazy transclusions. throw RenderException.createFromRenderException( "When evaluating \"" + expr.toSourceString() + "\": " + e.getMessage(), e, node); } catch (Exception e) { throw RenderException.createWithSource( "When evaluating \"" + expr.toSourceString() + "\": " + e.getMessage(), e, node); } }
[ "private", "SoyValue", "eval", "(", "ExprNode", "expr", ",", "SoyNode", "node", ")", "{", "if", "(", "expr", "==", "null", ")", "{", "throw", "RenderException", ".", "create", "(", "\"Cannot evaluate expression in V1 syntax.\"", ")", ".", "addStackTraceElement", ...
Private helper to evaluate an expression. Always use this helper instead of using evalVisitor directly, because this helper creates and throws a RenderException if there's an error.
[ "Private", "helper", "to", "evaluate", "an", "expression", ".", "Always", "use", "this", "helper", "instead", "of", "using", "evalVisitor", "directly", "because", "this", "helper", "creates", "and", "throws", "a", "RenderException", "if", "there", "s", "an", "...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java#L767-L796
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java
RenderVisitor.append
static void append(Appendable outputBuf, CharSequence cs) { try { outputBuf.append(cs); } catch (IOException e) { throw new RuntimeException(e); } }
java
static void append(Appendable outputBuf, CharSequence cs) { try { outputBuf.append(cs); } catch (IOException e) { throw new RuntimeException(e); } }
[ "static", "void", "append", "(", "Appendable", "outputBuf", ",", "CharSequence", "cs", ")", "{", "try", "{", "outputBuf", ".", "append", "(", "cs", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ...
Helper to append text to the output, propagating any exceptions.
[ "Helper", "to", "append", "text", "to", "the", "output", "propagating", "any", "exceptions", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java#L827-L833
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java
RenderVisitor.append
static void append(Appendable outputBuf, SoyValue value, SoyNode node) { try { value.render(outputBuf); } catch (IOException e) { throw new RuntimeException(e); } catch (RenderException e) { throw e.addStackTraceElement(node); } }
java
static void append(Appendable outputBuf, SoyValue value, SoyNode node) { try { value.render(outputBuf); } catch (IOException e) { throw new RuntimeException(e); } catch (RenderException e) { throw e.addStackTraceElement(node); } }
[ "static", "void", "append", "(", "Appendable", "outputBuf", ",", "SoyValue", "value", ",", "SoyNode", "node", ")", "{", "try", "{", "value", ".", "render", "(", "outputBuf", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "Ru...
Helper to append a SoyValue to the output, propagating any exceptions.
[ "Helper", "to", "append", "a", "SoyValue", "to", "the", "output", "propagating", "any", "exceptions", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java#L836-L844
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java
RenderVisitor.applyDirective
private SoyValue applyDirective( SoyPrintDirective directive, SoyValue value, List<SoyValue> args, SoyNode node) { // Get directive. if (!(directive instanceof SoyJavaPrintDirective)) { throw RenderException.createWithSource( "Failed to find Soy print directive with name '" + directive + "'" + " (tag " + node.toSourceString() + ")", node); } // TODO: Add a pass to check num args at compile time. if (!directive.getValidArgsSizes().contains(args.size())) { throw RenderException.createWithSource( "Print directive '" + directive + "' used with the wrong number of arguments (tag " + node.toSourceString() + ").", node); } try { return ((SoyJavaPrintDirective) directive).applyForJava(value, args); } catch (RuntimeException e) { throw RenderException.createWithSource( String.format( "Failed in applying directive '%s' in tag \"%s\" due to exception: %s", directive, node.toSourceString(), e.getMessage()), e, node); } }
java
private SoyValue applyDirective( SoyPrintDirective directive, SoyValue value, List<SoyValue> args, SoyNode node) { // Get directive. if (!(directive instanceof SoyJavaPrintDirective)) { throw RenderException.createWithSource( "Failed to find Soy print directive with name '" + directive + "'" + " (tag " + node.toSourceString() + ")", node); } // TODO: Add a pass to check num args at compile time. if (!directive.getValidArgsSizes().contains(args.size())) { throw RenderException.createWithSource( "Print directive '" + directive + "' used with the wrong number of arguments (tag " + node.toSourceString() + ").", node); } try { return ((SoyJavaPrintDirective) directive).applyForJava(value, args); } catch (RuntimeException e) { throw RenderException.createWithSource( String.format( "Failed in applying directive '%s' in tag \"%s\" due to exception: %s", directive, node.toSourceString(), e.getMessage()), e, node); } }
[ "private", "SoyValue", "applyDirective", "(", "SoyPrintDirective", "directive", ",", "SoyValue", "value", ",", "List", "<", "SoyValue", ">", "args", ",", "SoyNode", "node", ")", "{", "// Get directive.", "if", "(", "!", "(", "directive", "instanceof", "SoyJavaPr...
Protected helper to apply a print directive. @param directive The directive to apply @param value The value to apply the directive on. @param args The arguments to the directive. @param node The node with the escaping. Only used for error reporting. @return The result of applying the directive with the given arguments to the given value.
[ "Protected", "helper", "to", "apply", "a", "print", "directive", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java#L855-L891
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java
RenderVisitor.checkValueType
private void checkValueType(TemplateParam param, SoyValue value, TemplateNode node) { if (!TofuTypeChecks.isInstance(param.type(), value, node.getSourceLocation())) { // should this be a soydataexception? throw RenderException.createWithSource( "Parameter type mismatch: attempt to bind value '" + (value instanceof UndefinedData ? "(undefined)" : value) + "' (a " + value.getClass().getSimpleName() + ") to parameter '" + param.name() + "' which has a declared type of '" + param.type() + "'.", node); } }
java
private void checkValueType(TemplateParam param, SoyValue value, TemplateNode node) { if (!TofuTypeChecks.isInstance(param.type(), value, node.getSourceLocation())) { // should this be a soydataexception? throw RenderException.createWithSource( "Parameter type mismatch: attempt to bind value '" + (value instanceof UndefinedData ? "(undefined)" : value) + "' (a " + value.getClass().getSimpleName() + ") to parameter '" + param.name() + "' which has a declared type of '" + param.type() + "'.", node); } }
[ "private", "void", "checkValueType", "(", "TemplateParam", "param", ",", "SoyValue", "value", ",", "TemplateNode", "node", ")", "{", "if", "(", "!", "TofuTypeChecks", ".", "isInstance", "(", "param", ".", "type", "(", ")", ",", "value", ",", "node", ".", ...
Check that the value matches the given param type.
[ "Check", "that", "the", "value", "matches", "the", "given", "param", "type", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/RenderVisitor.java#L936-L951
train
google/closure-templates
java/src/com/google/template/soy/types/SoyProtoType.java
SoyProtoType.getDescriptorExpression
public String getDescriptorExpression() { // We only need to import the outermost descriptor. Descriptor descriptor = typeDescriptor; while (descriptor.getContainingType() != null) { descriptor = descriptor.getContainingType(); } return JavaQualifiedNames.getQualifiedName(descriptor) + ".getDescriptor()"; }
java
public String getDescriptorExpression() { // We only need to import the outermost descriptor. Descriptor descriptor = typeDescriptor; while (descriptor.getContainingType() != null) { descriptor = descriptor.getContainingType(); } return JavaQualifiedNames.getQualifiedName(descriptor) + ".getDescriptor()"; }
[ "public", "String", "getDescriptorExpression", "(", ")", "{", "// We only need to import the outermost descriptor.", "Descriptor", "descriptor", "=", "typeDescriptor", ";", "while", "(", "descriptor", ".", "getContainingType", "(", ")", "!=", "null", ")", "{", "descript...
For ParseInfo generation, return a string that represents the Java source expression for the static descriptor constant. @return The Java source expression for this type's descriptor.
[ "For", "ParseInfo", "generation", "return", "a", "string", "that", "represents", "the", "Java", "source", "expression", "for", "the", "static", "descriptor", "constant", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyProtoType.java#L242-L249
train
google/closure-templates
java/src/com/google/template/soy/types/SoyProtoType.java
SoyProtoType.getNameForBackend
public String getNameForBackend(SoyBackendKind backend) { switch (backend) { case JS_SRC: // The 'proto' prefix is JSPB-specific. If we ever support some other // JavaScript proto implementation, we'll need some way to determine which // proto implementation the user wants to use at this point. return ProtoUtils.calculateQualifiedJsName(typeDescriptor); case TOFU: case JBC_SRC: return JavaQualifiedNames.getClassName(typeDescriptor); case PYTHON_SRC: throw new UnsupportedOperationException(); } throw new AssertionError(backend); }
java
public String getNameForBackend(SoyBackendKind backend) { switch (backend) { case JS_SRC: // The 'proto' prefix is JSPB-specific. If we ever support some other // JavaScript proto implementation, we'll need some way to determine which // proto implementation the user wants to use at this point. return ProtoUtils.calculateQualifiedJsName(typeDescriptor); case TOFU: case JBC_SRC: return JavaQualifiedNames.getClassName(typeDescriptor); case PYTHON_SRC: throw new UnsupportedOperationException(); } throw new AssertionError(backend); }
[ "public", "String", "getNameForBackend", "(", "SoyBackendKind", "backend", ")", "{", "switch", "(", "backend", ")", "{", "case", "JS_SRC", ":", "// The 'proto' prefix is JSPB-specific. If we ever support some other", "// JavaScript proto implementation, we'll need some way to deter...
Returns this proto's type name for the given backend.
[ "Returns", "this", "proto", "s", "type", "name", "for", "the", "given", "backend", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyProtoType.java#L269-L283
train
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/VeLogInstrumentationVisitor.java
VeLogInstrumentationVisitor.visitHtmlAttributeNode
@Override protected void visitHtmlAttributeNode(HtmlAttributeNode node) { // Skip attributes that do not have a value. if (!node.hasValue()) { return; } SourceLocation insertionLocation = node.getSourceLocation(); for (FunctionNode function : SoyTreeUtils.getAllNodesOfType(node, FunctionNode.class)) { if (!(function.getSoyFunction() instanceof LoggingFunction)) { continue; } FunctionNode funcNode = new FunctionNode( Identifier.create(VeLogJsSrcLoggingFunction.NAME, insertionLocation), VeLogJsSrcLoggingFunction.INSTANCE, insertionLocation); funcNode.addChild( new StringNode(function.getFunctionName(), QuoteStyle.SINGLE, insertionLocation)); funcNode.addChild(new ListLiteralNode(function.getChildren(), insertionLocation)); StandaloneNode attributeName = node.getChild(0); if (attributeName instanceof RawTextNode) { // If attribute name is a plain text, directly pass it as a function argument. funcNode.addChild( new StringNode( ((RawTextNode) attributeName).getRawText(), QuoteStyle.SINGLE, insertionLocation)); } else { // Otherwise wrap the print node or call node into a let block, and use the let variable // as a function argument. String varName = "$soy_logging_function_attribute_" + node.getId(); LetContentNode letNode = LetContentNode.forVariable( nodeIdGen.genId(), attributeName.getSourceLocation(), varName, attributeName.getSourceLocation(), null); // Adds a let var which references to the original attribute name, and move the name to // the let block. node.replaceChild( attributeName, new PrintNode( nodeIdGen.genId(), insertionLocation, /* isImplicit= */ true, /* expr= */ new VarRefNode( letNode.getVar().name(), insertionLocation, letNode.getVar()), /* attributes= */ ImmutableList.of(), ErrorReporter.exploding())); letNode.addChild(attributeName); node.getParent().addChild(node.getParent().getChildIndex(node), letNode); funcNode.addChild( new VarRefNode(letNode.getVar().name(), insertionLocation, letNode.getVar())); } PrintNode loggingFunctionAttribute = new PrintNode( nodeIdGen.genId(), insertionLocation, /* isImplicit= */ true, /* expr= */ funcNode, /* attributes= */ ImmutableList.of(), ErrorReporter.exploding()); // Append the logging function attribute to its parent int appendIndex = node.getParent().getChildIndex(node) + 1; node.getParent().addChild(appendIndex, loggingFunctionAttribute); // Replace the original attribute value to the placeholder. HtmlAttributeValueNode placeHolder = new HtmlAttributeValueNode(nodeIdGen.genId(), insertionLocation, Quotes.DOUBLE); placeHolder.addChild( new RawTextNode( nodeIdGen.genId(), ((LoggingFunction) function.getSoyFunction()).getPlaceholder(), insertionLocation)); node.replaceChild(node.getChild(1), placeHolder); // We can break here since VeLogValidationPass guarantees that there is exactly one // logging function in a html attribute value. break; } visitChildrenAllowingConcurrentModification(node); }
java
@Override protected void visitHtmlAttributeNode(HtmlAttributeNode node) { // Skip attributes that do not have a value. if (!node.hasValue()) { return; } SourceLocation insertionLocation = node.getSourceLocation(); for (FunctionNode function : SoyTreeUtils.getAllNodesOfType(node, FunctionNode.class)) { if (!(function.getSoyFunction() instanceof LoggingFunction)) { continue; } FunctionNode funcNode = new FunctionNode( Identifier.create(VeLogJsSrcLoggingFunction.NAME, insertionLocation), VeLogJsSrcLoggingFunction.INSTANCE, insertionLocation); funcNode.addChild( new StringNode(function.getFunctionName(), QuoteStyle.SINGLE, insertionLocation)); funcNode.addChild(new ListLiteralNode(function.getChildren(), insertionLocation)); StandaloneNode attributeName = node.getChild(0); if (attributeName instanceof RawTextNode) { // If attribute name is a plain text, directly pass it as a function argument. funcNode.addChild( new StringNode( ((RawTextNode) attributeName).getRawText(), QuoteStyle.SINGLE, insertionLocation)); } else { // Otherwise wrap the print node or call node into a let block, and use the let variable // as a function argument. String varName = "$soy_logging_function_attribute_" + node.getId(); LetContentNode letNode = LetContentNode.forVariable( nodeIdGen.genId(), attributeName.getSourceLocation(), varName, attributeName.getSourceLocation(), null); // Adds a let var which references to the original attribute name, and move the name to // the let block. node.replaceChild( attributeName, new PrintNode( nodeIdGen.genId(), insertionLocation, /* isImplicit= */ true, /* expr= */ new VarRefNode( letNode.getVar().name(), insertionLocation, letNode.getVar()), /* attributes= */ ImmutableList.of(), ErrorReporter.exploding())); letNode.addChild(attributeName); node.getParent().addChild(node.getParent().getChildIndex(node), letNode); funcNode.addChild( new VarRefNode(letNode.getVar().name(), insertionLocation, letNode.getVar())); } PrintNode loggingFunctionAttribute = new PrintNode( nodeIdGen.genId(), insertionLocation, /* isImplicit= */ true, /* expr= */ funcNode, /* attributes= */ ImmutableList.of(), ErrorReporter.exploding()); // Append the logging function attribute to its parent int appendIndex = node.getParent().getChildIndex(node) + 1; node.getParent().addChild(appendIndex, loggingFunctionAttribute); // Replace the original attribute value to the placeholder. HtmlAttributeValueNode placeHolder = new HtmlAttributeValueNode(nodeIdGen.genId(), insertionLocation, Quotes.DOUBLE); placeHolder.addChild( new RawTextNode( nodeIdGen.genId(), ((LoggingFunction) function.getSoyFunction()).getPlaceholder(), insertionLocation)); node.replaceChild(node.getChild(1), placeHolder); // We can break here since VeLogValidationPass guarantees that there is exactly one // logging function in a html attribute value. break; } visitChildrenAllowingConcurrentModification(node); }
[ "@", "Override", "protected", "void", "visitHtmlAttributeNode", "(", "HtmlAttributeNode", "node", ")", "{", "// Skip attributes that do not have a value.", "if", "(", "!", "node", ".", "hasValue", "(", ")", ")", "{", "return", ";", "}", "SourceLocation", "insertionL...
For HtmlAttributeNode that has a logging function as its value, replace the logging function with its place holder, and append a new data attribute that contains all the desired information that are used later by the runtime library.
[ "For", "HtmlAttributeNode", "that", "has", "a", "logging", "function", "as", "its", "value", "replace", "the", "logging", "function", "with", "its", "place", "holder", "and", "append", "a", "new", "data", "attribute", "that", "contains", "all", "the", "desired...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/VeLogInstrumentationVisitor.java#L111-L189
train
google/closure-templates
java/src/com/google/template/soy/data/UnsafeSanitizedContentOrdainer.java
UnsafeSanitizedContentOrdainer.ordainAsSafe
public static SanitizedContent ordainAsSafe(String value, ContentKind kind) { return ordainAsSafe(value, kind, kind.getDefaultDir()); }
java
public static SanitizedContent ordainAsSafe(String value, ContentKind kind) { return ordainAsSafe(value, kind, kind.getDefaultDir()); }
[ "public", "static", "SanitizedContent", "ordainAsSafe", "(", "String", "value", ",", "ContentKind", "kind", ")", "{", "return", "ordainAsSafe", "(", "value", ",", "kind", ",", "kind", ".", "getDefaultDir", "(", ")", ")", ";", "}" ]
Faithfully assumes the provided value is "safe" and marks it not to be re-escaped. The value's direction is assumed to be LTR for JS, URI, ATTRIBUTES, and CSS content, and otherwise unknown. <p>When you "ordain" a string as safe content, it means that Soy will NOT re-escape or validate the contents if printed in the relevant context. You can use this to insert known-safe HTML into a template via a parameter. <p>This doesn't do a lot of strict checking, but makes it easier to differentiate safe constants in your code.
[ "Faithfully", "assumes", "the", "provided", "value", "is", "safe", "and", "marks", "it", "not", "to", "be", "re", "-", "escaped", ".", "The", "value", "s", "direction", "is", "assumed", "to", "be", "LTR", "for", "JS", "URI", "ATTRIBUTES", "and", "CSS", ...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/UnsafeSanitizedContentOrdainer.java#L60-L62
train
google/closure-templates
java/src/com/google/template/soy/parseinfo/passes/GenerateParseInfoVisitor.java
GenerateParseInfoVisitor.findProtoTypesRecurse
private void findProtoTypesRecurse(SoyType type, SortedSet<String> protoTypes) { switch (type.getKind()) { case PROTO: protoTypes.add(((SoyProtoType) type).getDescriptorExpression()); break; case PROTO_ENUM: protoTypes.add(((SoyProtoEnumType) type).getDescriptorExpression()); break; case UNION: for (SoyType member : ((UnionType) type).getMembers()) { findProtoTypesRecurse(member, protoTypes); } break; case LIST: { ListType listType = (ListType) type; findProtoTypesRecurse(listType.getElementType(), protoTypes); break; } case MAP: case LEGACY_OBJECT_MAP: { AbstractMapType mapType = (AbstractMapType) type; findProtoTypesRecurse(mapType.getKeyType(), protoTypes); findProtoTypesRecurse(mapType.getValueType(), protoTypes); break; } case RECORD: { RecordType recordType = (RecordType) type; for (SoyType fieldType : recordType.getMembers().values()) { findProtoTypesRecurse(fieldType, protoTypes); } break; } case VE: { VeType veType = (VeType) type; if (veType.getDataType().isPresent()) { // Don't grab the proto type for ve<null> SoyType soyType = typeRegistry.getType(veType.getDataType().get()); if (soyType.getKind() == Kind.PROTO) { protoTypes.add(((SoyProtoType) soyType).getDescriptorExpression()); } } break; } case ANY: case UNKNOWN: case ERROR: case NULL: case BOOL: case INT: case FLOAT: case STRING: case HTML: case ATTRIBUTES: case JS: case CSS: case URI: case TRUSTED_RESOURCE_URI: case VE_DATA: // continue } }
java
private void findProtoTypesRecurse(SoyType type, SortedSet<String> protoTypes) { switch (type.getKind()) { case PROTO: protoTypes.add(((SoyProtoType) type).getDescriptorExpression()); break; case PROTO_ENUM: protoTypes.add(((SoyProtoEnumType) type).getDescriptorExpression()); break; case UNION: for (SoyType member : ((UnionType) type).getMembers()) { findProtoTypesRecurse(member, protoTypes); } break; case LIST: { ListType listType = (ListType) type; findProtoTypesRecurse(listType.getElementType(), protoTypes); break; } case MAP: case LEGACY_OBJECT_MAP: { AbstractMapType mapType = (AbstractMapType) type; findProtoTypesRecurse(mapType.getKeyType(), protoTypes); findProtoTypesRecurse(mapType.getValueType(), protoTypes); break; } case RECORD: { RecordType recordType = (RecordType) type; for (SoyType fieldType : recordType.getMembers().values()) { findProtoTypesRecurse(fieldType, protoTypes); } break; } case VE: { VeType veType = (VeType) type; if (veType.getDataType().isPresent()) { // Don't grab the proto type for ve<null> SoyType soyType = typeRegistry.getType(veType.getDataType().get()); if (soyType.getKind() == Kind.PROTO) { protoTypes.add(((SoyProtoType) soyType).getDescriptorExpression()); } } break; } case ANY: case UNKNOWN: case ERROR: case NULL: case BOOL: case INT: case FLOAT: case STRING: case HTML: case ATTRIBUTES: case JS: case CSS: case URI: case TRUSTED_RESOURCE_URI: case VE_DATA: // continue } }
[ "private", "void", "findProtoTypesRecurse", "(", "SoyType", "type", ",", "SortedSet", "<", "String", ">", "protoTypes", ")", "{", "switch", "(", "type", ".", "getKind", "(", ")", ")", "{", "case", "PROTO", ":", "protoTypes", ".", "add", "(", "(", "(", ...
Recursively search for protocol buffer types within the given type. @param type The type to search. @param protoTypes Output set.
[ "Recursively", "search", "for", "protocol", "buffer", "types", "within", "the", "given", "type", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parseinfo/passes/GenerateParseInfoVisitor.java#L748-L818
train
google/closure-templates
java/src/com/google/template/soy/parseinfo/passes/GenerateParseInfoVisitor.java
GenerateParseInfoVisitor.buildTemplateNameForJavadoc
private static String buildTemplateNameForJavadoc( SoyFileNode currSoyFile, TemplateMetadata template) { StringBuilder resultSb = new StringBuilder(); if (template.getSourceLocation().getFilePath().equals(currSoyFile.getFilePath()) && template.getTemplateKind() != TemplateMetadata.Kind.DELTEMPLATE) { resultSb.append( template.getTemplateName().substring(template.getTemplateName().lastIndexOf('.'))); } else { switch (template.getTemplateKind()) { case BASIC: case ELEMENT: resultSb.append(template.getTemplateName()); break; case DELTEMPLATE: resultSb.append(template.getDelTemplateName()); if (!template.getDelTemplateVariant().isEmpty()) { resultSb.append(':'); resultSb.append(template.getDelTemplateVariant()); } break; } } if (template.getVisibility() != Visibility.PUBLIC) { resultSb.append(" (private)"); } if (template.getTemplateKind() == TemplateMetadata.Kind.DELTEMPLATE) { resultSb.append(" (delegate)"); } return resultSb.toString(); }
java
private static String buildTemplateNameForJavadoc( SoyFileNode currSoyFile, TemplateMetadata template) { StringBuilder resultSb = new StringBuilder(); if (template.getSourceLocation().getFilePath().equals(currSoyFile.getFilePath()) && template.getTemplateKind() != TemplateMetadata.Kind.DELTEMPLATE) { resultSb.append( template.getTemplateName().substring(template.getTemplateName().lastIndexOf('.'))); } else { switch (template.getTemplateKind()) { case BASIC: case ELEMENT: resultSb.append(template.getTemplateName()); break; case DELTEMPLATE: resultSb.append(template.getDelTemplateName()); if (!template.getDelTemplateVariant().isEmpty()) { resultSb.append(':'); resultSb.append(template.getDelTemplateVariant()); } break; } } if (template.getVisibility() != Visibility.PUBLIC) { resultSb.append(" (private)"); } if (template.getTemplateKind() == TemplateMetadata.Kind.DELTEMPLATE) { resultSb.append(" (delegate)"); } return resultSb.toString(); }
[ "private", "static", "String", "buildTemplateNameForJavadoc", "(", "SoyFileNode", "currSoyFile", ",", "TemplateMetadata", "template", ")", "{", "StringBuilder", "resultSb", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "template", ".", "getSourceLocation", ...
Private helper to build the human-readable string for referring to a template in the generated code's javadoc. @param currSoyFile The current Soy file for which we're generating parse-info code. @param template The template that we want to refer to in the generated javadoc. Note that this template may not be in the current Soy file. @return The human-readable string for referring to the given template in the generated code's javadoc.
[ "Private", "helper", "to", "build", "the", "human", "-", "readable", "string", "for", "referring", "to", "a", "template", "in", "the", "generated", "code", "s", "javadoc", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parseinfo/passes/GenerateParseInfoVisitor.java#L886-L919
train
google/closure-templates
java/src/com/google/template/soy/parseinfo/passes/GenerateParseInfoVisitor.java
GenerateParseInfoVisitor.appendImmutableList
private static void appendImmutableList( IndentedLinesBuilder ilb, String typeParamSnippet, Collection<String> itemSnippets) { appendListOrSetHelper(ilb, "ImmutableList." + typeParamSnippet + "of", itemSnippets); }
java
private static void appendImmutableList( IndentedLinesBuilder ilb, String typeParamSnippet, Collection<String> itemSnippets) { appendListOrSetHelper(ilb, "ImmutableList." + typeParamSnippet + "of", itemSnippets); }
[ "private", "static", "void", "appendImmutableList", "(", "IndentedLinesBuilder", "ilb", ",", "String", "typeParamSnippet", ",", "Collection", "<", "String", ">", "itemSnippets", ")", "{", "appendListOrSetHelper", "(", "ilb", ",", "\"ImmutableList.\"", "+", "typeParamS...
Private helper to append an ImmutableList to the code. @param ilb The builder for the code. @param typeParamSnippet The type parameter for the ImmutableList. @param itemSnippets Code snippets for the items to put into the ImmutableList.
[ "Private", "helper", "to", "append", "an", "ImmutableList", "to", "the", "code", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parseinfo/passes/GenerateParseInfoVisitor.java#L928-L931
train
google/closure-templates
java/src/com/google/template/soy/parseinfo/passes/GenerateParseInfoVisitor.java
GenerateParseInfoVisitor.appendImmutableMap
private static void appendImmutableMap( IndentedLinesBuilder ilb, String typeParamSnippet, Map<String, String> entrySnippetPairs) { if (entrySnippetPairs.isEmpty()) { ilb.appendLineStart("ImmutableMap.", typeParamSnippet, "of()"); } else { ilb.appendLine("ImmutableMap.", typeParamSnippet, "builder()"); for (Map.Entry<String, String> entrySnippetPair : entrySnippetPairs.entrySet()) { ilb.appendLine( " .put(", entrySnippetPair.getKey(), ", ", entrySnippetPair.getValue(), ")"); } ilb.appendLineStart(" .build()"); } }
java
private static void appendImmutableMap( IndentedLinesBuilder ilb, String typeParamSnippet, Map<String, String> entrySnippetPairs) { if (entrySnippetPairs.isEmpty()) { ilb.appendLineStart("ImmutableMap.", typeParamSnippet, "of()"); } else { ilb.appendLine("ImmutableMap.", typeParamSnippet, "builder()"); for (Map.Entry<String, String> entrySnippetPair : entrySnippetPairs.entrySet()) { ilb.appendLine( " .put(", entrySnippetPair.getKey(), ", ", entrySnippetPair.getValue(), ")"); } ilb.appendLineStart(" .build()"); } }
[ "private", "static", "void", "appendImmutableMap", "(", "IndentedLinesBuilder", "ilb", ",", "String", "typeParamSnippet", ",", "Map", "<", "String", ",", "String", ">", "entrySnippetPairs", ")", "{", "if", "(", "entrySnippetPairs", ".", "isEmpty", "(", ")", ")",...
Private helper to append an ImmutableMap to the code. @param ilb The builder for the code. @param typeParamSnippet The type parameter for the ImmutableMap. @param entrySnippetPairs Pairs of (key, value) code snippets for the entries to put into the ImmutableMap.
[ "Private", "helper", "to", "append", "an", "ImmutableMap", "to", "the", "code", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parseinfo/passes/GenerateParseInfoVisitor.java#L969-L982
train
google/closure-templates
java/src/com/google/template/soy/sharedpasses/render/Environment.java
Environment.create
static Environment create(TemplateNode template, SoyRecord data, SoyRecord ijData) { return new Impl(template, data, ijData); }
java
static Environment create(TemplateNode template, SoyRecord data, SoyRecord ijData) { return new Impl(template, data, ijData); }
[ "static", "Environment", "create", "(", "TemplateNode", "template", ",", "SoyRecord", "data", ",", "SoyRecord", "ijData", ")", "{", "return", "new", "Impl", "(", "template", ",", "data", ",", "ijData", ")", ";", "}" ]
The main way to create an environment. <p>Allocates the local variable table for the template and prepopulates it with data from the given SoyRecords.
[ "The", "main", "way", "to", "create", "an", "environment", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/sharedpasses/render/Environment.java#L55-L57
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/EscapingConventions.java
EscapingConventions.getAllEscapers
public static Iterable<CrossLanguageStringXform> getAllEscapers() { // This list is hard coded but is checked by unittests for the contextual auto-escaper. return ImmutableList.of( EscapeHtml.INSTANCE, NormalizeHtml.INSTANCE, EscapeHtmlNospace.INSTANCE, NormalizeHtmlNospace.INSTANCE, EscapeJsString.INSTANCE, EscapeJsRegex.INSTANCE, EscapeCssString.INSTANCE, FilterCssValue.INSTANCE, EscapeUri.INSTANCE, NormalizeUri.INSTANCE, FilterNormalizeUri.INSTANCE, FilterNormalizeMediaUri.INSTANCE, FilterImageDataUri.INSTANCE, FilterSipUri.INSTANCE, FilterSmsUri.INSTANCE, FilterTelUri.INSTANCE, FilterHtmlAttributes.INSTANCE, FilterHtmlElementName.INSTANCE); }
java
public static Iterable<CrossLanguageStringXform> getAllEscapers() { // This list is hard coded but is checked by unittests for the contextual auto-escaper. return ImmutableList.of( EscapeHtml.INSTANCE, NormalizeHtml.INSTANCE, EscapeHtmlNospace.INSTANCE, NormalizeHtmlNospace.INSTANCE, EscapeJsString.INSTANCE, EscapeJsRegex.INSTANCE, EscapeCssString.INSTANCE, FilterCssValue.INSTANCE, EscapeUri.INSTANCE, NormalizeUri.INSTANCE, FilterNormalizeUri.INSTANCE, FilterNormalizeMediaUri.INSTANCE, FilterImageDataUri.INSTANCE, FilterSipUri.INSTANCE, FilterSmsUri.INSTANCE, FilterTelUri.INSTANCE, FilterHtmlAttributes.INSTANCE, FilterHtmlElementName.INSTANCE); }
[ "public", "static", "Iterable", "<", "CrossLanguageStringXform", ">", "getAllEscapers", "(", ")", "{", "// This list is hard coded but is checked by unittests for the contextual auto-escaper.", "return", "ImmutableList", ".", "of", "(", "EscapeHtml", ".", "INSTANCE", ",", "No...
An accessor for all string transforms defined above.
[ "An", "accessor", "for", "all", "string", "transforms", "defined", "above", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/EscapingConventions.java#L1247-L1268
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Statement.java
Statement.returnExpression
public static Statement returnExpression(final Expression expression) { // TODO(lukes): it would be nice to do a checkType operation here to make sure that expression // is compatible with the return type of the method, but i don't know how to get that // information here (reasonably). So it is the caller's responsibility. return new Statement() { @Override protected void doGen(CodeBuilder adapter) { expression.gen(adapter); adapter.returnValue(); } }; }
java
public static Statement returnExpression(final Expression expression) { // TODO(lukes): it would be nice to do a checkType operation here to make sure that expression // is compatible with the return type of the method, but i don't know how to get that // information here (reasonably). So it is the caller's responsibility. return new Statement() { @Override protected void doGen(CodeBuilder adapter) { expression.gen(adapter); adapter.returnValue(); } }; }
[ "public", "static", "Statement", "returnExpression", "(", "final", "Expression", "expression", ")", "{", "// TODO(lukes): it would be nice to do a checkType operation here to make sure that expression", "// is compatible with the return type of the method, but i don't know how to get that", ...
Generates a statement that returns the value produced by the given expression. <p>This does not validate that the return type is appropriate. It is our callers responsibility to do that.
[ "Generates", "a", "statement", "that", "returns", "the", "value", "produced", "by", "the", "given", "expression", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Statement.java#L62-L73
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Statement.java
Statement.throwExpression
public static Statement throwExpression(final Expression expression) { expression.checkAssignableTo(THROWABLE_TYPE); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { expression.gen(adapter); adapter.throwException(); } }; }
java
public static Statement throwExpression(final Expression expression) { expression.checkAssignableTo(THROWABLE_TYPE); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { expression.gen(adapter); adapter.throwException(); } }; }
[ "public", "static", "Statement", "throwExpression", "(", "final", "Expression", "expression", ")", "{", "expression", ".", "checkAssignableTo", "(", "THROWABLE_TYPE", ")", ";", "return", "new", "Statement", "(", ")", "{", "@", "Override", "protected", "void", "d...
Generates a statement that throws the throwable produced by the given expression. <p>This does not validate that the throwable is compatible with the methods throws clause.
[ "Generates", "a", "statement", "that", "throws", "the", "throwable", "produced", "by", "the", "given", "expression", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Statement.java#L80-L89
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Statement.java
Statement.concat
public static Statement concat(final Iterable<? extends Statement> statements) { checkNotNull(statements); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { for (Statement statement : statements) { statement.gen(adapter); } } }; }
java
public static Statement concat(final Iterable<? extends Statement> statements) { checkNotNull(statements); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { for (Statement statement : statements) { statement.gen(adapter); } } }; }
[ "public", "static", "Statement", "concat", "(", "final", "Iterable", "<", "?", "extends", "Statement", ">", "statements", ")", "{", "checkNotNull", "(", "statements", ")", ";", "return", "new", "Statement", "(", ")", "{", "@", "Override", "protected", "void"...
Returns a statement that concatenates all the provided statements.
[ "Returns", "a", "statement", "that", "concatenates", "all", "the", "provided", "statements", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Statement.java#L97-L107
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Statement.java
Statement.labelStart
public final Statement labelStart(final Label label) { return new Statement() { @Override protected void doGen(CodeBuilder adapter) { adapter.mark(label); Statement.this.gen(adapter); } }; }
java
public final Statement labelStart(final Label label) { return new Statement() { @Override protected void doGen(CodeBuilder adapter) { adapter.mark(label); Statement.this.gen(adapter); } }; }
[ "public", "final", "Statement", "labelStart", "(", "final", "Label", "label", ")", "{", "return", "new", "Statement", "(", ")", "{", "@", "Override", "protected", "void", "doGen", "(", "CodeBuilder", "adapter", ")", "{", "adapter", ".", "mark", "(", "label...
Returns a new statement identical to this one but with the given label applied at the start of the statement.
[ "Returns", "a", "new", "statement", "identical", "to", "this", "one", "but", "with", "the", "given", "label", "applied", "at", "the", "start", "of", "the", "statement", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Statement.java#L155-L163
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Statement.java
Statement.then
final Expression then(final Expression expression) { return new Expression(expression.resultType(), expression.features()) { @Override protected void doGen(CodeBuilder adapter) { Statement.this.gen(adapter); expression.gen(adapter); } }; }
java
final Expression then(final Expression expression) { return new Expression(expression.resultType(), expression.features()) { @Override protected void doGen(CodeBuilder adapter) { Statement.this.gen(adapter); expression.gen(adapter); } }; }
[ "final", "Expression", "then", "(", "final", "Expression", "expression", ")", "{", "return", "new", "Expression", "(", "expression", ".", "resultType", "(", ")", ",", "expression", ".", "features", "(", ")", ")", "{", "@", "Override", "protected", "void", ...
Returns an Expression that evaluates this statement followed by the given expression.
[ "Returns", "an", "Expression", "that", "evaluates", "this", "statement", "followed", "by", "the", "given", "expression", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Statement.java#L180-L188
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/api/RenderResult.java
RenderResult.future
public Future<?> future() { Future<?> f = future; if (f == null) { throw new IllegalStateException( "Result.future() can only be called if type() is DETACH, type was: " + type); } return f; }
java
public Future<?> future() { Future<?> f = future; if (f == null) { throw new IllegalStateException( "Result.future() can only be called if type() is DETACH, type was: " + type); } return f; }
[ "public", "Future", "<", "?", ">", "future", "(", ")", "{", "Future", "<", "?", ">", "f", "=", "future", ";", "if", "(", "f", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Result.future() can only be called if type() is DETACH, type ...
Returns the future that soy is waiting for. @throws IllegalStateException if {@link #type()} is not {@link Type#DETACH}.
[ "Returns", "the", "future", "that", "soy", "is", "waiting", "for", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/api/RenderResult.java#L97-L104
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java
AnnotationRef.write
public void write(T instance, ClassVisitor visitor) { doWrite(instance, visitor.visitAnnotation(typeDescriptor, isRuntimeVisible)); }
java
public void write(T instance, ClassVisitor visitor) { doWrite(instance, visitor.visitAnnotation(typeDescriptor, isRuntimeVisible)); }
[ "public", "void", "write", "(", "T", "instance", ",", "ClassVisitor", "visitor", ")", "{", "doWrite", "(", "instance", ",", "visitor", ".", "visitAnnotation", "(", "typeDescriptor", ",", "isRuntimeVisible", ")", ")", ";", "}" ]
Writes the given annotation to the visitor.
[ "Writes", "the", "given", "annotation", "to", "the", "visitor", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java#L101-L103
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java
AnnotationRef.annotationFieldWriter
private static <T extends Annotation> FieldWriter annotationFieldWriter( final String name, final AnnotationRef<T> ref) { return new FieldWriter() { @Override public void write(AnnotationVisitor visitor, Object value) { ref.doWrite(ref.annType.cast(value), visitor.visitAnnotation(name, ref.typeDescriptor)); } }; }
java
private static <T extends Annotation> FieldWriter annotationFieldWriter( final String name, final AnnotationRef<T> ref) { return new FieldWriter() { @Override public void write(AnnotationVisitor visitor, Object value) { ref.doWrite(ref.annType.cast(value), visitor.visitAnnotation(name, ref.typeDescriptor)); } }; }
[ "private", "static", "<", "T", "extends", "Annotation", ">", "FieldWriter", "annotationFieldWriter", "(", "final", "String", "name", ",", "final", "AnnotationRef", "<", "T", ">", "ref", ")", "{", "return", "new", "FieldWriter", "(", ")", "{", "@", "Override"...
Writes an annotation valued field to the writer.
[ "Writes", "an", "annotation", "valued", "field", "to", "the", "writer", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java#L130-L138
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java
AnnotationRef.simpleFieldWriter
private static FieldWriter simpleFieldWriter(final String name) { return new FieldWriter() { @Override public void write(AnnotationVisitor visitor, Object value) { visitor.visit(name, value); } }; }
java
private static FieldWriter simpleFieldWriter(final String name) { return new FieldWriter() { @Override public void write(AnnotationVisitor visitor, Object value) { visitor.visit(name, value); } }; }
[ "private", "static", "FieldWriter", "simpleFieldWriter", "(", "final", "String", "name", ")", "{", "return", "new", "FieldWriter", "(", ")", "{", "@", "Override", "public", "void", "write", "(", "AnnotationVisitor", "visitor", ",", "Object", "value", ")", "{",...
Writes an primitive valued field to the writer. <p>See {@link AnnotationVisitor#visit(String, Object)} for the valid types.
[ "Writes", "an", "primitive", "valued", "field", "to", "the", "writer", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java#L145-L152
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java
AnnotationRef.simpleArrayFieldWriter
private static FieldWriter simpleArrayFieldWriter(final String name) { return new FieldWriter() { @Override public void write(AnnotationVisitor visitor, Object value) { int len = Array.getLength(value); AnnotationVisitor arrayVisitor = visitor.visitArray(name); for (int i = 0; i < len; i++) { arrayVisitor.visit(null, Array.get(value, i)); } arrayVisitor.visitEnd(); } }; }
java
private static FieldWriter simpleArrayFieldWriter(final String name) { return new FieldWriter() { @Override public void write(AnnotationVisitor visitor, Object value) { int len = Array.getLength(value); AnnotationVisitor arrayVisitor = visitor.visitArray(name); for (int i = 0; i < len; i++) { arrayVisitor.visit(null, Array.get(value, i)); } arrayVisitor.visitEnd(); } }; }
[ "private", "static", "FieldWriter", "simpleArrayFieldWriter", "(", "final", "String", "name", ")", "{", "return", "new", "FieldWriter", "(", ")", "{", "@", "Override", "public", "void", "write", "(", "AnnotationVisitor", "visitor", ",", "Object", "value", ")", ...
Writes an simple array valued field to the annotation visitor.
[ "Writes", "an", "simple", "array", "valued", "field", "to", "the", "annotation", "visitor", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java#L155-L167
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java
AnnotationRef.annotationArrayFieldWriter
private static <T extends Annotation> FieldWriter annotationArrayFieldWriter( final String name, final AnnotationRef<T> ref) { return new FieldWriter() { @Override public void write(AnnotationVisitor visitor, Object value) { int len = Array.getLength(value); AnnotationVisitor arrayVisitor = visitor.visitArray(name); for (int i = 0; i < len; i++) { ref.doWrite( ref.annType.cast(Array.get(value, i)), arrayVisitor.visitAnnotation(null, ref.typeDescriptor)); } arrayVisitor.visitEnd(); } }; }
java
private static <T extends Annotation> FieldWriter annotationArrayFieldWriter( final String name, final AnnotationRef<T> ref) { return new FieldWriter() { @Override public void write(AnnotationVisitor visitor, Object value) { int len = Array.getLength(value); AnnotationVisitor arrayVisitor = visitor.visitArray(name); for (int i = 0; i < len; i++) { ref.doWrite( ref.annType.cast(Array.get(value, i)), arrayVisitor.visitAnnotation(null, ref.typeDescriptor)); } arrayVisitor.visitEnd(); } }; }
[ "private", "static", "<", "T", "extends", "Annotation", ">", "FieldWriter", "annotationArrayFieldWriter", "(", "final", "String", "name", ",", "final", "AnnotationRef", "<", "T", ">", "ref", ")", "{", "return", "new", "FieldWriter", "(", ")", "{", "@", "Over...
Writes an annotation array valued field to the annotation visitor.
[ "Writes", "an", "annotation", "array", "valued", "field", "to", "the", "annotation", "visitor", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/AnnotationRef.java#L170-L185
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/LocalVariable.java
LocalVariable.createThisVar
public static LocalVariable createThisVar(TypeInfo owner, Label start, Label end) { return new LocalVariable("this", owner.type(), 0, start, end, Feature.NON_NULLABLE); }
java
public static LocalVariable createThisVar(TypeInfo owner, Label start, Label end) { return new LocalVariable("this", owner.type(), 0, start, end, Feature.NON_NULLABLE); }
[ "public", "static", "LocalVariable", "createThisVar", "(", "TypeInfo", "owner", ",", "Label", "start", ",", "Label", "end", ")", "{", "return", "new", "LocalVariable", "(", "\"this\"", ",", "owner", ".", "type", "(", ")", ",", "0", ",", "start", ",", "en...
parameters to tableEntry?
[ "parameters", "to", "tableEntry?" ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/LocalVariable.java#L53-L55
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/LocalVariable.java
LocalVariable.tableEntry
public void tableEntry(CodeBuilder mv) { mv.visitLocalVariable( variableName(), resultType().getDescriptor(), null, // no generic signature start(), end(), index()); }
java
public void tableEntry(CodeBuilder mv) { mv.visitLocalVariable( variableName(), resultType().getDescriptor(), null, // no generic signature start(), end(), index()); }
[ "public", "void", "tableEntry", "(", "CodeBuilder", "mv", ")", "{", "mv", ".", "visitLocalVariable", "(", "variableName", "(", ")", ",", "resultType", "(", ")", ".", "getDescriptor", "(", ")", ",", "null", ",", "// no generic signature", "start", "(", ")", ...
Write a local variable table entry for this variable. This informs debuggers about variable names, types and lifetime.
[ "Write", "a", "local", "variable", "table", "entry", "for", "this", "variable", ".", "This", "informs", "debuggers", "about", "variable", "names", "types", "and", "lifetime", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/LocalVariable.java#L113-L121
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/LocalVariable.java
LocalVariable.store
private Statement store(final Expression expr, final Optional<Label> firstVarInstruction) { expr.checkAssignableTo(resultType()); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { expr.gen(adapter); if (firstVarInstruction.isPresent()) { adapter.mark(firstVarInstruction.get()); } adapter.visitVarInsn(resultType().getOpcode(Opcodes.ISTORE), index()); } }; }
java
private Statement store(final Expression expr, final Optional<Label> firstVarInstruction) { expr.checkAssignableTo(resultType()); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { expr.gen(adapter); if (firstVarInstruction.isPresent()) { adapter.mark(firstVarInstruction.get()); } adapter.visitVarInsn(resultType().getOpcode(Opcodes.ISTORE), index()); } }; }
[ "private", "Statement", "store", "(", "final", "Expression", "expr", ",", "final", "Optional", "<", "Label", ">", "firstVarInstruction", ")", "{", "expr", ".", "checkAssignableTo", "(", "resultType", "(", ")", ")", ";", "return", "new", "Statement", "(", ")"...
Writes the value at the top of the stack to the local variable.
[ "Writes", "the", "value", "at", "the", "top", "of", "the", "stack", "to", "the", "local", "variable", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/LocalVariable.java#L146-L158
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java
JbcSrcRuntime.resolveSoyValueProvider
public static SoyValue resolveSoyValueProvider(SoyValueProvider provider) { SoyValue value = provider.resolve(); return handleTofuNull(value); }
java
public static SoyValue resolveSoyValueProvider(SoyValueProvider provider) { SoyValue value = provider.resolve(); return handleTofuNull(value); }
[ "public", "static", "SoyValue", "resolveSoyValueProvider", "(", "SoyValueProvider", "provider", ")", "{", "SoyValue", "value", "=", "provider", ".", "resolve", "(", ")", ";", "return", "handleTofuNull", "(", "value", ")", ";", "}" ]
Helper function to translate NullData -> null when resolving a SoyValueProvider.
[ "Helper", "function", "to", "translate", "NullData", "-", ">", "null", "when", "resolving", "a", "SoyValueProvider", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java#L137-L140
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java
JbcSrcRuntime.checkSoyString
public static SoyString checkSoyString(Object o) { // if it isn't a sanitized content we don't want to warn and if it isn't a soystring we should // always fail. if (o instanceof SoyString && o instanceof SanitizedContent && ((SanitizedContent) o).getContentKind() != ContentKind.TEXT && logger.isLoggable(Level.WARNING)) { logger.log( Level.WARNING, String.format( "Passing in sanitized content into a template that accepts only string is forbidden. " + " Please modify the template to take in %s.", ((SanitizedContent) o).getContentKind()), new Exception()); } return (SoyString) o; }
java
public static SoyString checkSoyString(Object o) { // if it isn't a sanitized content we don't want to warn and if it isn't a soystring we should // always fail. if (o instanceof SoyString && o instanceof SanitizedContent && ((SanitizedContent) o).getContentKind() != ContentKind.TEXT && logger.isLoggable(Level.WARNING)) { logger.log( Level.WARNING, String.format( "Passing in sanitized content into a template that accepts only string is forbidden. " + " Please modify the template to take in %s.", ((SanitizedContent) o).getContentKind()), new Exception()); } return (SoyString) o; }
[ "public", "static", "SoyString", "checkSoyString", "(", "Object", "o", ")", "{", "// if it isn't a sanitized content we don't want to warn and if it isn't a soystring we should", "// always fail.", "if", "(", "o", "instanceof", "SoyString", "&&", "o", "instanceof", "SanitizedCo...
Casts the given type to SoyString or throws a ClassCastException.
[ "Casts", "the", "given", "type", "to", "SoyString", "or", "throws", "a", "ClassCastException", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java#L186-L202
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java
JbcSrcRuntime.callLegacySoyFunction
public static SoyValue callLegacySoyFunction( LegacyFunctionAdapter fnAdapter, List<SoyValue> args) { for (int i = 0; i < args.size(); i++) { if (args.get(i) == null) { args.set(i, NullData.INSTANCE); } } return handleTofuNull(fnAdapter.computeForJava(args)); }
java
public static SoyValue callLegacySoyFunction( LegacyFunctionAdapter fnAdapter, List<SoyValue> args) { for (int i = 0; i < args.size(); i++) { if (args.get(i) == null) { args.set(i, NullData.INSTANCE); } } return handleTofuNull(fnAdapter.computeForJava(args)); }
[ "public", "static", "SoyValue", "callLegacySoyFunction", "(", "LegacyFunctionAdapter", "fnAdapter", ",", "List", "<", "SoyValue", ">", "args", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "args", ".", "size", "(", ")", ";", "i", "++", ")"...
Helper function to translate null -> NullData when calling LegacyFunctionAdapters that may expect it. <p>In the long run we should either fix ToFu (and all SoyJavaFunctions) to not use NullData or we should introduce custom SoyFunction implementations for have come from SoyValueProvider.
[ "Helper", "function", "to", "translate", "null", "-", ">", "NullData", "when", "calling", "LegacyFunctionAdapters", "that", "may", "expect", "it", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java#L211-L219
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java
JbcSrcRuntime.applyPrintDirective
public static SoyValue applyPrintDirective( SoyJavaPrintDirective directive, SoyValue value, List<SoyValue> args) { value = value == null ? NullData.INSTANCE : value; for (int i = 0; i < args.size(); i++) { if (args.get(i) == null) { args.set(i, NullData.INSTANCE); } } return directive.applyForJava(value, args); }
java
public static SoyValue applyPrintDirective( SoyJavaPrintDirective directive, SoyValue value, List<SoyValue> args) { value = value == null ? NullData.INSTANCE : value; for (int i = 0; i < args.size(); i++) { if (args.get(i) == null) { args.set(i, NullData.INSTANCE); } } return directive.applyForJava(value, args); }
[ "public", "static", "SoyValue", "applyPrintDirective", "(", "SoyJavaPrintDirective", "directive", ",", "SoyValue", "value", ",", "List", "<", "SoyValue", ">", "args", ")", "{", "value", "=", "value", "==", "null", "?", "NullData", ".", "INSTANCE", ":", "value"...
Helper function to translate null -> NullData when calling SoyJavaPrintDirectives that may expect it.
[ "Helper", "function", "to", "translate", "null", "-", ">", "NullData", "when", "calling", "SoyJavaPrintDirectives", "that", "may", "expect", "it", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java#L225-L234
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java
JbcSrcRuntime.applyEscapers
public static CompiledTemplate applyEscapers( CompiledTemplate delegate, ImmutableList<SoyJavaPrintDirective> directives) { ContentKind kind = delegate.kind(); if (canSkipEscaping(directives, kind)) { return delegate; } return new EscapedCompiledTemplate(delegate, directives, kind); }
java
public static CompiledTemplate applyEscapers( CompiledTemplate delegate, ImmutableList<SoyJavaPrintDirective> directives) { ContentKind kind = delegate.kind(); if (canSkipEscaping(directives, kind)) { return delegate; } return new EscapedCompiledTemplate(delegate, directives, kind); }
[ "public", "static", "CompiledTemplate", "applyEscapers", "(", "CompiledTemplate", "delegate", ",", "ImmutableList", "<", "SoyJavaPrintDirective", ">", "directives", ")", "{", "ContentKind", "kind", "=", "delegate", ".", "kind", "(", ")", ";", "if", "(", "canSkipEs...
Wraps a given template with a collection of escapers to apply. @param delegate The delegate template to render @param directives The set of directives to apply
[ "Wraps", "a", "given", "template", "with", "a", "collection", "of", "escapers", "to", "apply", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java#L242-L249
train
google/closure-templates
java/src/com/google/template/soy/pysrc/internal/MsgFuncGenerator.java
MsgFuncGenerator.getPyExpr
PyStringExpr getPyExpr() { if (this.msgNode.isPlrselMsg()) { return this.msgNode.isPluralMsg() ? pyFuncForPluralMsg() : pyFuncForSelectMsg(); } else { return this.msgNode.isRawTextMsg() ? pyFuncForRawTextMsg() : pyFuncForGeneralMsg(); } }
java
PyStringExpr getPyExpr() { if (this.msgNode.isPlrselMsg()) { return this.msgNode.isPluralMsg() ? pyFuncForPluralMsg() : pyFuncForSelectMsg(); } else { return this.msgNode.isRawTextMsg() ? pyFuncForRawTextMsg() : pyFuncForGeneralMsg(); } }
[ "PyStringExpr", "getPyExpr", "(", ")", "{", "if", "(", "this", ".", "msgNode", ".", "isPlrselMsg", "(", ")", ")", "{", "return", "this", ".", "msgNode", ".", "isPluralMsg", "(", ")", "?", "pyFuncForPluralMsg", "(", ")", ":", "pyFuncForSelectMsg", "(", ")...
Return the PyStringExpr for the render function call, because we know render always return a string in Python runtime.
[ "Return", "the", "PyStringExpr", "for", "the", "render", "function", "call", "because", "we", "know", "render", "always", "return", "a", "string", "in", "Python", "runtime", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/MsgFuncGenerator.java#L117-L123
train
google/closure-templates
java/src/com/google/template/soy/pysrc/internal/MsgFuncGenerator.java
MsgFuncGenerator.collectVarNameListAndToPyExprMap
private Map<PyExpr, PyExpr> collectVarNameListAndToPyExprMap() { Map<PyExpr, PyExpr> nodePyVarToPyExprMap = new LinkedHashMap<>(); for (Map.Entry<String, MsgSubstUnitNode> entry : msgNode.getVarNameToRepNodeMap().entrySet()) { MsgSubstUnitNode substUnitNode = entry.getValue(); PyExpr substPyExpr = null; if (substUnitNode instanceof MsgPlaceholderNode) { SoyNode phInitialNode = ((AbstractParentSoyNode<?>) substUnitNode).getChild(0); if (phInitialNode instanceof PrintNode || phInitialNode instanceof CallNode || phInitialNode instanceof RawTextNode) { substPyExpr = PyExprUtils.concatPyExprs(genPyExprsVisitor.exec(phInitialNode)).toPyString(); } // when the placeholder is generated by HTML tags if (phInitialNode instanceof MsgHtmlTagNode) { substPyExpr = PyExprUtils.concatPyExprs( genPyExprsVisitor.execOnChildren((ParentSoyNode<?>) phInitialNode)) .toPyString(); } } else if (substUnitNode instanceof MsgPluralNode) { // Translates {@link MsgPluralNode#pluralExpr} into a Python lookup expression. // Note that {@code pluralExpr} represents the soy expression of the {@code plural} attr, // i.e. the {@code $numDrafts} in {@code {plural $numDrafts}...{/plural}}. substPyExpr = translateToPyExprVisitor.exec(((MsgPluralNode) substUnitNode).getExpr()); } else if (substUnitNode instanceof MsgSelectNode) { substPyExpr = translateToPyExprVisitor.exec(((MsgSelectNode) substUnitNode).getExpr()); } if (substPyExpr != null) { nodePyVarToPyExprMap.put(new PyStringExpr("'" + entry.getKey() + "'"), substPyExpr); } } return nodePyVarToPyExprMap; }
java
private Map<PyExpr, PyExpr> collectVarNameListAndToPyExprMap() { Map<PyExpr, PyExpr> nodePyVarToPyExprMap = new LinkedHashMap<>(); for (Map.Entry<String, MsgSubstUnitNode> entry : msgNode.getVarNameToRepNodeMap().entrySet()) { MsgSubstUnitNode substUnitNode = entry.getValue(); PyExpr substPyExpr = null; if (substUnitNode instanceof MsgPlaceholderNode) { SoyNode phInitialNode = ((AbstractParentSoyNode<?>) substUnitNode).getChild(0); if (phInitialNode instanceof PrintNode || phInitialNode instanceof CallNode || phInitialNode instanceof RawTextNode) { substPyExpr = PyExprUtils.concatPyExprs(genPyExprsVisitor.exec(phInitialNode)).toPyString(); } // when the placeholder is generated by HTML tags if (phInitialNode instanceof MsgHtmlTagNode) { substPyExpr = PyExprUtils.concatPyExprs( genPyExprsVisitor.execOnChildren((ParentSoyNode<?>) phInitialNode)) .toPyString(); } } else if (substUnitNode instanceof MsgPluralNode) { // Translates {@link MsgPluralNode#pluralExpr} into a Python lookup expression. // Note that {@code pluralExpr} represents the soy expression of the {@code plural} attr, // i.e. the {@code $numDrafts} in {@code {plural $numDrafts}...{/plural}}. substPyExpr = translateToPyExprVisitor.exec(((MsgPluralNode) substUnitNode).getExpr()); } else if (substUnitNode instanceof MsgSelectNode) { substPyExpr = translateToPyExprVisitor.exec(((MsgSelectNode) substUnitNode).getExpr()); } if (substPyExpr != null) { nodePyVarToPyExprMap.put(new PyStringExpr("'" + entry.getKey() + "'"), substPyExpr); } } return nodePyVarToPyExprMap; }
[ "private", "Map", "<", "PyExpr", ",", "PyExpr", ">", "collectVarNameListAndToPyExprMap", "(", ")", "{", "Map", "<", "PyExpr", ",", "PyExpr", ">", "nodePyVarToPyExprMap", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<"...
Private helper to process and collect all variables used within this msg node for code generation. @return A Map populated with all the variables used with in this message node, using {@link MsgPlaceholderInitialNode#genBasePhName}.
[ "Private", "helper", "to", "process", "and", "collect", "all", "variables", "used", "within", "this", "msg", "node", "for", "code", "generation", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/MsgFuncGenerator.java#L201-L239
train
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/TranslateExprNodeVisitor.java
TranslateExprNodeVisitor.genCodeForParamAccess
Expression genCodeForParamAccess(String paramName, VarDefn varDefn) { Expression source = OPT_DATA; if (varDefn.isInjected()) { // Special case for csp_nonce. It is created by the compiler itself, and users should not need // to set it. So, instead of generating opt_ij_data.csp_nonce, we generate opt_ij_data && // opt_ij_data.csp_nonce. // TODO(lukes): we only need to generate this logic if there aren't any other ij params if (paramName.equals(CSP_NONCE_VARIABLE_NAME)) { return OPT_IJ_DATA.and(OPT_IJ_DATA.dotAccess(paramName), codeGenerator); } source = OPT_IJ_DATA; } else if (varDefn.kind() == VarDefn.Kind.STATE) { return genCodeForStateAccess(paramName, (TemplateStateVar) varDefn); } return source.dotAccess(paramName); }
java
Expression genCodeForParamAccess(String paramName, VarDefn varDefn) { Expression source = OPT_DATA; if (varDefn.isInjected()) { // Special case for csp_nonce. It is created by the compiler itself, and users should not need // to set it. So, instead of generating opt_ij_data.csp_nonce, we generate opt_ij_data && // opt_ij_data.csp_nonce. // TODO(lukes): we only need to generate this logic if there aren't any other ij params if (paramName.equals(CSP_NONCE_VARIABLE_NAME)) { return OPT_IJ_DATA.and(OPT_IJ_DATA.dotAccess(paramName), codeGenerator); } source = OPT_IJ_DATA; } else if (varDefn.kind() == VarDefn.Kind.STATE) { return genCodeForStateAccess(paramName, (TemplateStateVar) varDefn); } return source.dotAccess(paramName); }
[ "Expression", "genCodeForParamAccess", "(", "String", "paramName", ",", "VarDefn", "varDefn", ")", "{", "Expression", "source", "=", "OPT_DATA", ";", "if", "(", "varDefn", ".", "isInjected", "(", ")", ")", "{", "// Special case for csp_nonce. It is created by the comp...
Method that returns code to access a named parameter. @param paramName the name of the parameter. @param varDefn The variable definition of the parameter @return The code to access the value of that parameter.
[ "Method", "that", "returns", "code", "to", "access", "a", "named", "parameter", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/TranslateExprNodeVisitor.java#L198-L213
train
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/TranslateExprNodeVisitor.java
TranslateExprNodeVisitor.visitVarRefNode
@Override protected Expression visitVarRefNode(VarRefNode node) { Expression translation = variableMappings.maybeGet(node.getName()); if (translation != null) { // Case 1: In-scope local var. return translation; } else { // Case 2: Data reference. return genCodeForParamAccess(node.getName(), node.getDefnDecl()); } }
java
@Override protected Expression visitVarRefNode(VarRefNode node) { Expression translation = variableMappings.maybeGet(node.getName()); if (translation != null) { // Case 1: In-scope local var. return translation; } else { // Case 2: Data reference. return genCodeForParamAccess(node.getName(), node.getDefnDecl()); } }
[ "@", "Override", "protected", "Expression", "visitVarRefNode", "(", "VarRefNode", "node", ")", "{", "Expression", "translation", "=", "variableMappings", ".", "maybeGet", "(", "node", ".", "getName", "(", ")", ")", ";", "if", "(", "translation", "!=", "null", ...
Implementations for data references.
[ "Implementations", "for", "data", "references", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/TranslateExprNodeVisitor.java#L323-L333
train
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java
NullSafeAccumulator.dotAccess
NullSafeAccumulator dotAccess(FieldAccess access, boolean nullSafe) { if (access instanceof ProtoCall) { ProtoCall protoCall = (ProtoCall) access; Expression maybeUnpack = protoCall.unpackFunction(); if (maybeUnpack != null) { Preconditions.checkState( unpackFunction == null, "this chain will already unpack with %s", unpackFunction); unpackFunction = maybeUnpack; accessType = protoCall.accessType(); } } chain.add(access.toChainAccess(nullSafe)); return this; }
java
NullSafeAccumulator dotAccess(FieldAccess access, boolean nullSafe) { if (access instanceof ProtoCall) { ProtoCall protoCall = (ProtoCall) access; Expression maybeUnpack = protoCall.unpackFunction(); if (maybeUnpack != null) { Preconditions.checkState( unpackFunction == null, "this chain will already unpack with %s", unpackFunction); unpackFunction = maybeUnpack; accessType = protoCall.accessType(); } } chain.add(access.toChainAccess(nullSafe)); return this; }
[ "NullSafeAccumulator", "dotAccess", "(", "FieldAccess", "access", ",", "boolean", "nullSafe", ")", "{", "if", "(", "access", "instanceof", "ProtoCall", ")", "{", "ProtoCall", "protoCall", "=", "(", "ProtoCall", ")", "access", ";", "Expression", "maybeUnpack", "=...
Extends the access chain with a dot access to the given value. @param nullSafe If true, code will be generated to ensure the chain is non-null before dereferencing {@code access}.
[ "Extends", "the", "access", "chain", "with", "a", "dot", "access", "to", "the", "given", "value", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java#L85-L98
train
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java
NullSafeAccumulator.bracketAccess
NullSafeAccumulator bracketAccess(Expression arg, boolean nullSafe) { chain.add(new Bracket(arg, nullSafe)); // With a bracket access we no longer need to unpack the entire list, just a singular object. accessType = AccessType.SINGULAR; return this; }
java
NullSafeAccumulator bracketAccess(Expression arg, boolean nullSafe) { chain.add(new Bracket(arg, nullSafe)); // With a bracket access we no longer need to unpack the entire list, just a singular object. accessType = AccessType.SINGULAR; return this; }
[ "NullSafeAccumulator", "bracketAccess", "(", "Expression", "arg", ",", "boolean", "nullSafe", ")", "{", "chain", ".", "add", "(", "new", "Bracket", "(", "arg", ",", "nullSafe", ")", ")", ";", "// With a bracket access we no longer need to unpack the entire list, just a ...
Extends the access chain with a bracket access to the given value. @param nullSafe If true, code will be generated to ensure the chain is non-null before dereferencing {@code arg}.
[ "Extends", "the", "access", "chain", "with", "a", "bracket", "access", "to", "the", "given", "value", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java#L113-L118
train
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java
NullSafeAccumulator.result
Expression result(CodeChunk.Generator codeGenerator) { Expression accessChain = buildAccessChain(base, codeGenerator, chain.iterator()); if (unpackFunction == null) { return accessChain; } else { return accessType.unpackResult(accessChain, unpackFunction); } }
java
Expression result(CodeChunk.Generator codeGenerator) { Expression accessChain = buildAccessChain(base, codeGenerator, chain.iterator()); if (unpackFunction == null) { return accessChain; } else { return accessType.unpackResult(accessChain, unpackFunction); } }
[ "Expression", "result", "(", "CodeChunk", ".", "Generator", "codeGenerator", ")", "{", "Expression", "accessChain", "=", "buildAccessChain", "(", "base", ",", "codeGenerator", ",", "chain", ".", "iterator", "(", ")", ")", ";", "if", "(", "unpackFunction", "=="...
Returns a code chunk representing the entire access chain. Null-safe accesses in the chain generate code to make sure the chain is non-null before performing the access.
[ "Returns", "a", "code", "chunk", "representing", "the", "entire", "access", "chain", ".", "Null", "-", "safe", "accesses", "in", "the", "chain", "generate", "code", "to", "make", "sure", "the", "chain", "is", "non", "-", "null", "before", "performing", "th...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java#L124-L132
train
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java
NullSafeAccumulator.buildAccessChain
private static Expression buildAccessChain( Expression base, CodeChunk.Generator generator, Iterator<ChainAccess> chain) { if (!chain.hasNext()) { return base; // base case } ChainAccess link = chain.next(); if (link.nullSafe) { if (!base.isCheap()) { base = generator.declarationBuilder().setRhs(base).build().ref(); } return ifExpression(base.doubleEqualsNull(), LITERAL_NULL) .setElse(buildAccessChain(link.extend(base), generator, chain)) .build(generator); } return buildAccessChain(link.extend(base), generator, chain); }
java
private static Expression buildAccessChain( Expression base, CodeChunk.Generator generator, Iterator<ChainAccess> chain) { if (!chain.hasNext()) { return base; // base case } ChainAccess link = chain.next(); if (link.nullSafe) { if (!base.isCheap()) { base = generator.declarationBuilder().setRhs(base).build().ref(); } return ifExpression(base.doubleEqualsNull(), LITERAL_NULL) .setElse(buildAccessChain(link.extend(base), generator, chain)) .build(generator); } return buildAccessChain(link.extend(base), generator, chain); }
[ "private", "static", "Expression", "buildAccessChain", "(", "Expression", "base", ",", "CodeChunk", ".", "Generator", "generator", ",", "Iterator", "<", "ChainAccess", ">", "chain", ")", "{", "if", "(", "!", "chain", ".", "hasNext", "(", ")", ")", "{", "re...
Builds the access chain. <p>For chains with no null-safe accessses this is a simple and direct approach. However, for null safe accesses we will stash base expressions into a temporary variable so we can generate multiple references to it. <p>For example: <ol> <li>{@code $a.b} -> {@code a.b} <li>{@code $a?.b} -> {@code var t = a; t == null ? null : a.b} <li>{@code a?.b?.c} -> {@code var t = a; var r;if (t== null) {var t2 = a.b; r= t2 == null ? null : t2.c}} <li>{@code a?.b?.c.d} {@code var t = a; var r;if (t== null) {var t2 = a.b; r= t2 == null ? null : t2.c.d}} </ol>
[ "Builds", "the", "access", "chain", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java#L152-L167
train
google/closure-templates
java/src/com/google/template/soy/internal/i18n/BidiUtils.java
BidiUtils.isRtlLanguage
public static boolean isRtlLanguage(String locale) { try { return UScript.isRightToLeft( UCharacter.getPropertyValueEnum( UProperty.SCRIPT, ULocale.addLikelySubtags(new ULocale(locale)).getScript())); } catch (IllegalArgumentException e) { return false; } }
java
public static boolean isRtlLanguage(String locale) { try { return UScript.isRightToLeft( UCharacter.getPropertyValueEnum( UProperty.SCRIPT, ULocale.addLikelySubtags(new ULocale(locale)).getScript())); } catch (IllegalArgumentException e) { return false; } }
[ "public", "static", "boolean", "isRtlLanguage", "(", "String", "locale", ")", "{", "try", "{", "return", "UScript", ".", "isRightToLeft", "(", "UCharacter", ".", "getPropertyValueEnum", "(", "UProperty", ".", "SCRIPT", ",", "ULocale", ".", "addLikelySubtags", "(...
Returns whether a locale, given as a string in the ICU syntax, is RTL.
[ "Returns", "whether", "a", "locale", "given", "as", "a", "string", "in", "the", "ICU", "syntax", "is", "RTL", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/i18n/BidiUtils.java#L54-L62
train
google/closure-templates
java/src/com/google/template/soy/incrementaldomsrc/IncrementalDomSrcMain.java
IncrementalDomSrcMain.genJsSrc
public List<String> genJsSrc( SoyFileSetNode soyTree, TemplateRegistry registry, SoyIncrementalDomSrcOptions options, ErrorReporter errorReporter) { SoyJsSrcOptions incrementalJSSrcOptions = options.toJsSrcOptions(); BidiGlobalDir bidiGlobalDir = SoyBidiUtils.decodeBidiGlobalDirFromJsOptions( incrementalJSSrcOptions.getBidiGlobalDir(), incrementalJSSrcOptions.getUseGoogIsRtlForBidiGlobalDir()); try (SoyScopedData.InScope inScope = apiCallScope.enter(/* msgBundle= */ null, bidiGlobalDir)) { // Do the code generation. new HtmlContextVisitor().exec(soyTree); // If any errors are reported in {@code HtmlContextVisitor}, we should not continue. // Return an empty list here, {@code SoyFileSet} will throw an exception. if (errorReporter.hasErrors()) { return Collections.emptyList(); } UnescapingVisitor.unescapeRawTextInHtml(soyTree); new RemoveUnnecessaryEscapingDirectives(bidiGlobalDir).run(soyTree); // some of the above passes may slice up raw text nodes, recombine them. new CombineConsecutiveRawTextNodesPass().run(soyTree); return createVisitor( incrementalJSSrcOptions, registry, typeRegistry, inScope.getBidiGlobalDir(), errorReporter) .gen(soyTree, registry, errorReporter); } }
java
public List<String> genJsSrc( SoyFileSetNode soyTree, TemplateRegistry registry, SoyIncrementalDomSrcOptions options, ErrorReporter errorReporter) { SoyJsSrcOptions incrementalJSSrcOptions = options.toJsSrcOptions(); BidiGlobalDir bidiGlobalDir = SoyBidiUtils.decodeBidiGlobalDirFromJsOptions( incrementalJSSrcOptions.getBidiGlobalDir(), incrementalJSSrcOptions.getUseGoogIsRtlForBidiGlobalDir()); try (SoyScopedData.InScope inScope = apiCallScope.enter(/* msgBundle= */ null, bidiGlobalDir)) { // Do the code generation. new HtmlContextVisitor().exec(soyTree); // If any errors are reported in {@code HtmlContextVisitor}, we should not continue. // Return an empty list here, {@code SoyFileSet} will throw an exception. if (errorReporter.hasErrors()) { return Collections.emptyList(); } UnescapingVisitor.unescapeRawTextInHtml(soyTree); new RemoveUnnecessaryEscapingDirectives(bidiGlobalDir).run(soyTree); // some of the above passes may slice up raw text nodes, recombine them. new CombineConsecutiveRawTextNodesPass().run(soyTree); return createVisitor( incrementalJSSrcOptions, registry, typeRegistry, inScope.getBidiGlobalDir(), errorReporter) .gen(soyTree, registry, errorReporter); } }
[ "public", "List", "<", "String", ">", "genJsSrc", "(", "SoyFileSetNode", "soyTree", ",", "TemplateRegistry", "registry", ",", "SoyIncrementalDomSrcOptions", "options", ",", "ErrorReporter", "errorReporter", ")", "{", "SoyJsSrcOptions", "incrementalJSSrcOptions", "=", "o...
Generates Incremental DOM JS source code given a Soy parse tree, an options object, and an optional bundle of translated messages. @param soyTree The Soy parse tree to generate JS source code for. @param registry The template registry that contains all the template information. @param options The compilation options relevant to this backend. @param errorReporter The Soy error reporter that collects errors during code generation. @return A list of strings where each string represents the JS source code that belongs in one JS file. The generated JS files correspond one-to-one to the original Soy source files.
[ "Generates", "Incremental", "DOM", "JS", "source", "code", "given", "a", "Soy", "parse", "tree", "an", "options", "object", "and", "an", "optional", "bundle", "of", "translated", "messages", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/incrementaldomsrc/IncrementalDomSrcMain.java#L63-L98
train
google/closure-templates
java/src/com/google/template/soy/data/ordainers/GsonOrdainer.java
GsonOrdainer.serializeObject
public static SanitizedContent serializeObject(Gson gson, Object obj) { return ordainJson(gson.toJson(obj)); }
java
public static SanitizedContent serializeObject(Gson gson, Object obj) { return ordainJson(gson.toJson(obj)); }
[ "public", "static", "SanitizedContent", "serializeObject", "(", "Gson", "gson", ",", "Object", "obj", ")", "{", "return", "ordainJson", "(", "gson", ".", "toJson", "(", "obj", ")", ")", ";", "}" ]
Generate sanitized js content with provided Gson serializer. @param gson A Gson serializer. @param obj The object to render as gson. @return SanitizedContent containing the object rendered as a json string.
[ "Generate", "sanitized", "js", "content", "with", "provided", "Gson", "serializer", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/ordainers/GsonOrdainer.java#L58-L60
train