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/shared/internal/Sanitizers.java | Sanitizers.embedCssIntoHtmlSlow | private static String embedCssIntoHtmlSlow(
String css, int nextReplacement, boolean searchForEndCData, boolean searchForEndTag) {
// use an array instead of a stringbuilder so we can take advantage of the bulk copying
// routine (String.getChars). For some reason StringBuilder doesn't do this.
char[] buf = new char[css.length() + 16];
int endOfPreviousReplacement = 0;
int bufIndex = 0;
do {
int charsToCopy = nextReplacement - endOfPreviousReplacement;
buf = Chars.ensureCapacity(buf, bufIndex + charsToCopy + 4, 16);
css.getChars(endOfPreviousReplacement, nextReplacement, buf, bufIndex);
bufIndex += charsToCopy;
char c = css.charAt(nextReplacement);
if (c == ']') {
buf[bufIndex++] = ']';
buf[bufIndex++] = ']';
buf[bufIndex++] = '\\';
buf[bufIndex++] = '>';
endOfPreviousReplacement = nextReplacement + 3;
} else if (c == '<') {
buf[bufIndex++] = '<';
buf[bufIndex++] = '\\';
buf[bufIndex++] = '/';
endOfPreviousReplacement = nextReplacement + 2;
} else {
throw new AssertionError();
}
nextReplacement = -1;
if (searchForEndTag) {
int indexOfEndTag = css.indexOf("</", endOfPreviousReplacement);
if (indexOfEndTag == -1) {
searchForEndTag = false;
} else {
nextReplacement = indexOfEndTag;
}
}
if (searchForEndCData) {
int indexOfEndCData = css.indexOf("]]>", endOfPreviousReplacement);
if (indexOfEndCData == -1) {
searchForEndCData = false;
} else {
nextReplacement =
nextReplacement == -1 ? indexOfEndCData : Math.min(nextReplacement, indexOfEndCData);
}
}
} while (nextReplacement != -1);
// copy tail
int charsToCopy = css.length() - endOfPreviousReplacement;
buf = Chars.ensureCapacity(buf, bufIndex + charsToCopy, 16);
css.getChars(endOfPreviousReplacement, css.length(), buf, bufIndex);
bufIndex += charsToCopy;
return new String(buf, 0, bufIndex);
} | java | private static String embedCssIntoHtmlSlow(
String css, int nextReplacement, boolean searchForEndCData, boolean searchForEndTag) {
// use an array instead of a stringbuilder so we can take advantage of the bulk copying
// routine (String.getChars). For some reason StringBuilder doesn't do this.
char[] buf = new char[css.length() + 16];
int endOfPreviousReplacement = 0;
int bufIndex = 0;
do {
int charsToCopy = nextReplacement - endOfPreviousReplacement;
buf = Chars.ensureCapacity(buf, bufIndex + charsToCopy + 4, 16);
css.getChars(endOfPreviousReplacement, nextReplacement, buf, bufIndex);
bufIndex += charsToCopy;
char c = css.charAt(nextReplacement);
if (c == ']') {
buf[bufIndex++] = ']';
buf[bufIndex++] = ']';
buf[bufIndex++] = '\\';
buf[bufIndex++] = '>';
endOfPreviousReplacement = nextReplacement + 3;
} else if (c == '<') {
buf[bufIndex++] = '<';
buf[bufIndex++] = '\\';
buf[bufIndex++] = '/';
endOfPreviousReplacement = nextReplacement + 2;
} else {
throw new AssertionError();
}
nextReplacement = -1;
if (searchForEndTag) {
int indexOfEndTag = css.indexOf("</", endOfPreviousReplacement);
if (indexOfEndTag == -1) {
searchForEndTag = false;
} else {
nextReplacement = indexOfEndTag;
}
}
if (searchForEndCData) {
int indexOfEndCData = css.indexOf("]]>", endOfPreviousReplacement);
if (indexOfEndCData == -1) {
searchForEndCData = false;
} else {
nextReplacement =
nextReplacement == -1 ? indexOfEndCData : Math.min(nextReplacement, indexOfEndCData);
}
}
} while (nextReplacement != -1);
// copy tail
int charsToCopy = css.length() - endOfPreviousReplacement;
buf = Chars.ensureCapacity(buf, bufIndex + charsToCopy, 16);
css.getChars(endOfPreviousReplacement, css.length(), buf, bufIndex);
bufIndex += charsToCopy;
return new String(buf, 0, bufIndex);
} | [
"private",
"static",
"String",
"embedCssIntoHtmlSlow",
"(",
"String",
"css",
",",
"int",
"nextReplacement",
",",
"boolean",
"searchForEndCData",
",",
"boolean",
"searchForEndTag",
")",
"{",
"// use an array instead of a stringbuilder so we can take advantage of the bulk copying",... | Called when we know we need to make a replacement.
<p>At least one of {@code searchForEndCData} or {@code searchForEndTag} will be {@code true}.
@param css The css string to modify
@param nextReplacement The location of the first replacement
@param searchForEndCData Whether there are any sequences of {@code ]]>}
@param searchForEndTag Whether there are any sequences of {@code </}
@return The modified string. | [
"Called",
"when",
"we",
"know",
"we",
"need",
"to",
"make",
"a",
"replacement",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L1156-L1208 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/SoyMsgBundle.java | SoyMsgBundle.getMsgParts | public ImmutableList<SoyMsgPart> getMsgParts(long msgId) {
SoyMsg msg = getMsg(msgId);
return msg == null ? ImmutableList.of() : msg.getParts();
} | java | public ImmutableList<SoyMsgPart> getMsgParts(long msgId) {
SoyMsg msg = getMsg(msgId);
return msg == null ? ImmutableList.of() : msg.getParts();
} | [
"public",
"ImmutableList",
"<",
"SoyMsgPart",
">",
"getMsgParts",
"(",
"long",
"msgId",
")",
"{",
"SoyMsg",
"msg",
"=",
"getMsg",
"(",
"msgId",
")",
";",
"return",
"msg",
"==",
"null",
"?",
"ImmutableList",
".",
"of",
"(",
")",
":",
"msg",
".",
"getPar... | Returns the message parts, or an empty array if there is no such message.
<p>This is useful for rendering only usecases when the rest of the {@link SoyMsg} doesn't
matter. The default implementation is just {@link SoyMsg#getParts} but some subclasses may have
more efficient implementations | [
"Returns",
"the",
"message",
"parts",
"or",
"an",
"empty",
"array",
"if",
"there",
"is",
"no",
"such",
"message",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/SoyMsgBundle.java#L64-L67 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java | PyExprUtils.concatPyExprs | public static PyExpr concatPyExprs(List<? extends PyExpr> pyExprs) {
if (pyExprs.isEmpty()) {
return EMPTY_STRING;
}
if (pyExprs.size() == 1) {
// If there's only one element, simply return the expression as a String.
return pyExprs.get(0).toPyString();
}
StringBuilder resultSb = new StringBuilder();
// Use Python's list joining mechanism to speed up concatenation.
resultSb.append("[");
boolean isFirst = true;
for (PyExpr pyExpr : pyExprs) {
if (isFirst) {
isFirst = false;
} else {
resultSb.append(',');
}
resultSb.append(pyExpr.toPyString().getText());
}
resultSb.append("]");
return new PyListExpr(resultSb.toString(), Integer.MAX_VALUE);
} | java | public static PyExpr concatPyExprs(List<? extends PyExpr> pyExprs) {
if (pyExprs.isEmpty()) {
return EMPTY_STRING;
}
if (pyExprs.size() == 1) {
// If there's only one element, simply return the expression as a String.
return pyExprs.get(0).toPyString();
}
StringBuilder resultSb = new StringBuilder();
// Use Python's list joining mechanism to speed up concatenation.
resultSb.append("[");
boolean isFirst = true;
for (PyExpr pyExpr : pyExprs) {
if (isFirst) {
isFirst = false;
} else {
resultSb.append(',');
}
resultSb.append(pyExpr.toPyString().getText());
}
resultSb.append("]");
return new PyListExpr(resultSb.toString(), Integer.MAX_VALUE);
} | [
"public",
"static",
"PyExpr",
"concatPyExprs",
"(",
"List",
"<",
"?",
"extends",
"PyExpr",
">",
"pyExprs",
")",
"{",
"if",
"(",
"pyExprs",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"EMPTY_STRING",
";",
"}",
"if",
"(",
"pyExprs",
".",
"size",
"(",
... | Builds one Python expression that computes the concatenation of the given Python expressions.
<p>Python doesn't allow arbitrary concatentation between types, so to ensure type safety and
consistent behavior, coerce all expressions to Strings before joining them. Python's array
joining mechanism is used in place of traditional concatenation to improve performance.
@param pyExprs The Python expressions to concatenate.
@return One Python expression that computes the concatenation of the given Python expressions. | [
"Builds",
"one",
"Python",
"expression",
"that",
"computes",
"the",
"concatenation",
"of",
"the",
"given",
"Python",
"expressions",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java#L96-L126 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java | PyExprUtils.maybeProtect | public static PyExpr maybeProtect(PyExpr expr, int minSafePrecedence) {
// all python operators are left associative, so if this has equivalent precedence we don't need
// to wrap
if (expr.getPrecedence() >= minSafePrecedence) {
return expr;
} else {
return new PyExpr("(" + expr.getText() + ")", Integer.MAX_VALUE);
}
} | java | public static PyExpr maybeProtect(PyExpr expr, int minSafePrecedence) {
// all python operators are left associative, so if this has equivalent precedence we don't need
// to wrap
if (expr.getPrecedence() >= minSafePrecedence) {
return expr;
} else {
return new PyExpr("(" + expr.getText() + ")", Integer.MAX_VALUE);
}
} | [
"public",
"static",
"PyExpr",
"maybeProtect",
"(",
"PyExpr",
"expr",
",",
"int",
"minSafePrecedence",
")",
"{",
"// all python operators are left associative, so if this has equivalent precedence we don't need",
"// to wrap",
"if",
"(",
"expr",
".",
"getPrecedence",
"(",
")",... | Wraps an expression with parenthesis if it's not above the minimum safe precedence.
<p>NOTE: For the sake of brevity, this implementation loses typing information in the
expressions.
@param expr The expression to wrap.
@param minSafePrecedence The minimum safe precedence (not inclusive).
@return The PyExpr potentially wrapped in parenthesis. | [
"Wraps",
"an",
"expression",
"with",
"parenthesis",
"if",
"it",
"s",
"not",
"above",
"the",
"minimum",
"safe",
"precedence",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java#L154-L162 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java | PyExprUtils.convertMapToOrderedDict | public static PyExpr convertMapToOrderedDict(Map<PyExpr, PyExpr> dict) {
List<String> values = new ArrayList<>();
for (Map.Entry<PyExpr, PyExpr> entry : dict.entrySet()) {
values.add("(" + entry.getKey().getText() + ", " + entry.getValue().getText() + ")");
}
Joiner joiner = Joiner.on(", ");
return new PyExpr("collections.OrderedDict([" + joiner.join(values) + "])", Integer.MAX_VALUE);
} | java | public static PyExpr convertMapToOrderedDict(Map<PyExpr, PyExpr> dict) {
List<String> values = new ArrayList<>();
for (Map.Entry<PyExpr, PyExpr> entry : dict.entrySet()) {
values.add("(" + entry.getKey().getText() + ", " + entry.getValue().getText() + ")");
}
Joiner joiner = Joiner.on(", ");
return new PyExpr("collections.OrderedDict([" + joiner.join(values) + "])", Integer.MAX_VALUE);
} | [
"public",
"static",
"PyExpr",
"convertMapToOrderedDict",
"(",
"Map",
"<",
"PyExpr",
",",
"PyExpr",
">",
"dict",
")",
"{",
"List",
"<",
"String",
">",
"values",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"PyExpr"... | Convert a java Map to valid PyExpr as dict.
@param dict A Map to be converted to PyExpr as a dictionary, both key and value should be
PyExpr. | [
"Convert",
"a",
"java",
"Map",
"to",
"valid",
"PyExpr",
"as",
"dict",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java#L222-L231 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java | PyExprUtils.genExprWithNewToken | public static String genExprWithNewToken(
Operator op, List<? extends TargetExpr> operandExprs, String newToken) {
int opPrec = op.getPrecedence();
boolean isLeftAssociative = op.getAssociativity() == Associativity.LEFT;
StringBuilder exprSb = new StringBuilder();
// Iterate through the operator's syntax elements.
List<SyntaxElement> syntax = op.getSyntax();
for (int i = 0, n = syntax.size(); i < n; i++) {
SyntaxElement syntaxEl = syntax.get(i);
if (syntaxEl instanceof Operand) {
// Retrieve the operand's subexpression.
int operandIndex = ((Operand) syntaxEl).getIndex();
TargetExpr operandExpr = operandExprs.get(operandIndex);
// If left (right) associative, first (last) operand doesn't need protection if it's an
// operator of equal precedence to this one.
boolean needsProtection;
if (i == (isLeftAssociative ? 0 : n - 1)) {
needsProtection = operandExpr.getPrecedence() < opPrec;
} else {
needsProtection = operandExpr.getPrecedence() <= opPrec;
}
// Append the operand's subexpression to the expression we're building (if necessary,
// protected using parentheses).
String subexpr =
needsProtection ? "(" + operandExpr.getText() + ")" : operandExpr.getText();
exprSb.append(subexpr);
} else if (syntaxEl instanceof Token) {
// If a newToken is supplied, then use it, else use the token defined by Soy syntax.
if (newToken != null) {
exprSb.append(newToken);
} else {
exprSb.append(((Token) syntaxEl).getValue());
}
} else if (syntaxEl instanceof Spacer) {
// Spacer is just one space.
exprSb.append(' ');
} else {
throw new AssertionError();
}
}
return exprSb.toString();
} | java | public static String genExprWithNewToken(
Operator op, List<? extends TargetExpr> operandExprs, String newToken) {
int opPrec = op.getPrecedence();
boolean isLeftAssociative = op.getAssociativity() == Associativity.LEFT;
StringBuilder exprSb = new StringBuilder();
// Iterate through the operator's syntax elements.
List<SyntaxElement> syntax = op.getSyntax();
for (int i = 0, n = syntax.size(); i < n; i++) {
SyntaxElement syntaxEl = syntax.get(i);
if (syntaxEl instanceof Operand) {
// Retrieve the operand's subexpression.
int operandIndex = ((Operand) syntaxEl).getIndex();
TargetExpr operandExpr = operandExprs.get(operandIndex);
// If left (right) associative, first (last) operand doesn't need protection if it's an
// operator of equal precedence to this one.
boolean needsProtection;
if (i == (isLeftAssociative ? 0 : n - 1)) {
needsProtection = operandExpr.getPrecedence() < opPrec;
} else {
needsProtection = operandExpr.getPrecedence() <= opPrec;
}
// Append the operand's subexpression to the expression we're building (if necessary,
// protected using parentheses).
String subexpr =
needsProtection ? "(" + operandExpr.getText() + ")" : operandExpr.getText();
exprSb.append(subexpr);
} else if (syntaxEl instanceof Token) {
// If a newToken is supplied, then use it, else use the token defined by Soy syntax.
if (newToken != null) {
exprSb.append(newToken);
} else {
exprSb.append(((Token) syntaxEl).getValue());
}
} else if (syntaxEl instanceof Spacer) {
// Spacer is just one space.
exprSb.append(' ');
} else {
throw new AssertionError();
}
}
return exprSb.toString();
} | [
"public",
"static",
"String",
"genExprWithNewToken",
"(",
"Operator",
"op",
",",
"List",
"<",
"?",
"extends",
"TargetExpr",
">",
"operandExprs",
",",
"String",
"newToken",
")",
"{",
"int",
"opPrec",
"=",
"op",
".",
"getPrecedence",
"(",
")",
";",
"boolean",
... | Generates an expression for the given operator and operands assuming that the expression for
the operator uses the same syntax format as the Soy operator, with the exception that the of a
different token. Associativity, spacing, and precedence are maintained from the original
operator.
<p>Examples:
<pre>
NOT, ["$a"], "!" -> "! $a"
AND, ["$a", "$b"], "&&" -> "$a && $b"
NOT, ["$a * $b"], "!"; -> "! ($a * $b)"
</pre>
@param op The operator.
@param operandExprs The operands.
@param newToken The language specific token equivalent to the operator's original token.
@return The generated expression with a new token. | [
"Generates",
"an",
"expression",
"for",
"the",
"given",
"operator",
"and",
"operands",
"assuming",
"that",
"the",
"expression",
"for",
"the",
"operator",
"uses",
"the",
"same",
"syntax",
"format",
"as",
"the",
"Soy",
"operator",
"with",
"the",
"exception",
"th... | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/restricted/PyExprUtils.java#L300-L349 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/TemplateAnalysis.java | TemplateAnalysis.isListExpressionEmpty | private static StaticAnalysisResult isListExpressionEmpty(ForNode node) {
Optional<RangeArgs> rangeArgs = RangeArgs.createFromNode(node);
if (rangeArgs.isPresent()) {
return isRangeExpressionEmpty(rangeArgs.get());
}
ExprNode expr = node.getExpr().getRoot();
if (expr instanceof ListLiteralNode) {
return ((ListLiteralNode) expr).numChildren() > 0
? StaticAnalysisResult.FALSE
: StaticAnalysisResult.TRUE;
}
return StaticAnalysisResult.UNKNOWN;
} | java | private static StaticAnalysisResult isListExpressionEmpty(ForNode node) {
Optional<RangeArgs> rangeArgs = RangeArgs.createFromNode(node);
if (rangeArgs.isPresent()) {
return isRangeExpressionEmpty(rangeArgs.get());
}
ExprNode expr = node.getExpr().getRoot();
if (expr instanceof ListLiteralNode) {
return ((ListLiteralNode) expr).numChildren() > 0
? StaticAnalysisResult.FALSE
: StaticAnalysisResult.TRUE;
}
return StaticAnalysisResult.UNKNOWN;
} | [
"private",
"static",
"StaticAnalysisResult",
"isListExpressionEmpty",
"(",
"ForNode",
"node",
")",
"{",
"Optional",
"<",
"RangeArgs",
">",
"rangeArgs",
"=",
"RangeArgs",
".",
"createFromNode",
"(",
"node",
")",
";",
"if",
"(",
"rangeArgs",
".",
"isPresent",
"(",... | consider moving this to SoyTreeUtils or some similar place. | [
"consider",
"moving",
"this",
"to",
"SoyTreeUtils",
"or",
"some",
"similar",
"place",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/TemplateAnalysis.java#L537-L549 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/SoyMsgBundleHandler.java | SoyMsgBundleHandler.createFromFile | public SoyMsgBundle createFromFile(File inputFile) throws IOException {
// TODO: This is for backwards-compatibility. Figure out how to get rid of this.
// We special-case English locales because they often don't have translated files and falling
// back to the Soy source should be fine.
if (!inputFile.exists() && FIRST_WORD_IS_EN_PATTERN.matcher(inputFile.getName()).matches()) {
return SoyMsgBundle.EMPTY;
}
try {
// reading the file as a byte array and then invoking the string constructor is the fastest
// way to read a full file as a string. it avoids copies incurred by CharSource and picks a
// faster path for charset decoding.
String inputFileContent = Files.asCharSource(inputFile, UTF_8).read();
return msgPlugin.parseTranslatedMsgsFile(inputFileContent);
} catch (SoyMsgException sme) {
sme.setFileOrResourceName(inputFile.toString());
throw sme;
}
} | java | public SoyMsgBundle createFromFile(File inputFile) throws IOException {
// TODO: This is for backwards-compatibility. Figure out how to get rid of this.
// We special-case English locales because they often don't have translated files and falling
// back to the Soy source should be fine.
if (!inputFile.exists() && FIRST_WORD_IS_EN_PATTERN.matcher(inputFile.getName()).matches()) {
return SoyMsgBundle.EMPTY;
}
try {
// reading the file as a byte array and then invoking the string constructor is the fastest
// way to read a full file as a string. it avoids copies incurred by CharSource and picks a
// faster path for charset decoding.
String inputFileContent = Files.asCharSource(inputFile, UTF_8).read();
return msgPlugin.parseTranslatedMsgsFile(inputFileContent);
} catch (SoyMsgException sme) {
sme.setFileOrResourceName(inputFile.toString());
throw sme;
}
} | [
"public",
"SoyMsgBundle",
"createFromFile",
"(",
"File",
"inputFile",
")",
"throws",
"IOException",
"{",
"// TODO: This is for backwards-compatibility. Figure out how to get rid of this.",
"// We special-case English locales because they often don't have translated files and falling",
"// ba... | Reads a translated messages file and creates a SoyMsgBundle.
@param inputFile The input file to read from.
@return The message bundle created from the messages file.
@throws IOException If there's an error while accessing the file.
@throws SoyMsgException If there's an error while processing the messages. | [
"Reads",
"a",
"translated",
"messages",
"file",
"and",
"creates",
"a",
"SoyMsgBundle",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/SoyMsgBundleHandler.java#L112-L132 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/SoyMsgBundleHandler.java | SoyMsgBundleHandler.createFromResource | public SoyMsgBundle createFromResource(URL inputResource) throws IOException {
try {
String inputFileContent = Resources.asCharSource(inputResource, UTF_8).read();
return msgPlugin.parseTranslatedMsgsFile(inputFileContent);
} catch (SoyMsgException sme) {
sme.setFileOrResourceName(inputResource.toString());
throw sme;
}
} | java | public SoyMsgBundle createFromResource(URL inputResource) throws IOException {
try {
String inputFileContent = Resources.asCharSource(inputResource, UTF_8).read();
return msgPlugin.parseTranslatedMsgsFile(inputFileContent);
} catch (SoyMsgException sme) {
sme.setFileOrResourceName(inputResource.toString());
throw sme;
}
} | [
"public",
"SoyMsgBundle",
"createFromResource",
"(",
"URL",
"inputResource",
")",
"throws",
"IOException",
"{",
"try",
"{",
"String",
"inputFileContent",
"=",
"Resources",
".",
"asCharSource",
"(",
"inputResource",
",",
"UTF_8",
")",
".",
"read",
"(",
")",
";",
... | Reads a translated messages resource and creates a SoyMsgBundle.
@param inputResource The resource to read from.
@return The message bundle created from the messages resource.
@throws IOException If there's an error while accessing the resource.
@throws SoyMsgException If there's an error while processing the messages. | [
"Reads",
"a",
"translated",
"messages",
"resource",
"and",
"creates",
"a",
"SoyMsgBundle",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/SoyMsgBundleHandler.java#L142-L152 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/VeLogNode.java | VeLogNode.getCloseTagNode | @Nullable
public HtmlCloseTagNode getCloseTagNode() {
if (numChildren() > 1) {
return (HtmlCloseTagNode)
getNodeAsHtmlTagNode(getChild(numChildren() - 1), /*openTag=*/ false);
}
return null;
} | java | @Nullable
public HtmlCloseTagNode getCloseTagNode() {
if (numChildren() > 1) {
return (HtmlCloseTagNode)
getNodeAsHtmlTagNode(getChild(numChildren() - 1), /*openTag=*/ false);
}
return null;
} | [
"@",
"Nullable",
"public",
"HtmlCloseTagNode",
"getCloseTagNode",
"(",
")",
"{",
"if",
"(",
"numChildren",
"(",
")",
">",
"1",
")",
"{",
"return",
"(",
"HtmlCloseTagNode",
")",
"getNodeAsHtmlTagNode",
"(",
"getChild",
"(",
"numChildren",
"(",
")",
"-",
"1",
... | Returns the close tag node if it exists. | [
"Returns",
"the",
"close",
"tag",
"node",
"if",
"it",
"exists",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/VeLogNode.java#L148-L155 | train |
google/closure-templates | java/src/com/google/template/soy/i18ndirectives/I18nUtils.java | I18nUtils.parseLocale | public static Locale parseLocale(String localeString) {
if (localeString == null) {
return Locale.US;
}
String[] groups = localeString.split("[-_]");
switch (groups.length) {
case 1:
return new Locale(groups[0]);
case 2:
return new Locale(groups[0], Ascii.toUpperCase(groups[1]));
case 3:
return new Locale(groups[0], Ascii.toUpperCase(groups[1]), groups[2]);
default:
throw new IllegalArgumentException("Malformed localeString: " + localeString);
}
} | java | public static Locale parseLocale(String localeString) {
if (localeString == null) {
return Locale.US;
}
String[] groups = localeString.split("[-_]");
switch (groups.length) {
case 1:
return new Locale(groups[0]);
case 2:
return new Locale(groups[0], Ascii.toUpperCase(groups[1]));
case 3:
return new Locale(groups[0], Ascii.toUpperCase(groups[1]), groups[2]);
default:
throw new IllegalArgumentException("Malformed localeString: " + localeString);
}
} | [
"public",
"static",
"Locale",
"parseLocale",
"(",
"String",
"localeString",
")",
"{",
"if",
"(",
"localeString",
"==",
"null",
")",
"{",
"return",
"Locale",
".",
"US",
";",
"}",
"String",
"[",
"]",
"groups",
"=",
"localeString",
".",
"split",
"(",
"\"[-_... | Given a string representing a Locale, returns the Locale object for that string.
@return A Locale object built from the string provided | [
"Given",
"a",
"string",
"representing",
"a",
"Locale",
"returns",
"the",
"Locale",
"object",
"for",
"that",
"string",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/i18ndirectives/I18nUtils.java#L37-L52 | train |
google/closure-templates | java/src/com/google/template/soy/basetree/CopyState.java | CopyState.updateRefs | public <T> void updateRefs(T oldObject, T newObject) {
checkNotNull(oldObject);
checkNotNull(newObject);
checkArgument(!(newObject instanceof Listener));
Object previousMapping = mappings.put(oldObject, newObject);
if (previousMapping != null) {
if (previousMapping instanceof Listener) {
@SuppressWarnings("unchecked") // Listener<T> can only be registered with a T
Listener<T> listener = (Listener<T>) previousMapping;
listener.newVersion(newObject);
} else {
throw new IllegalStateException("found multiple remappings for " + oldObject);
}
}
} | java | public <T> void updateRefs(T oldObject, T newObject) {
checkNotNull(oldObject);
checkNotNull(newObject);
checkArgument(!(newObject instanceof Listener));
Object previousMapping = mappings.put(oldObject, newObject);
if (previousMapping != null) {
if (previousMapping instanceof Listener) {
@SuppressWarnings("unchecked") // Listener<T> can only be registered with a T
Listener<T> listener = (Listener<T>) previousMapping;
listener.newVersion(newObject);
} else {
throw new IllegalStateException("found multiple remappings for " + oldObject);
}
}
} | [
"public",
"<",
"T",
">",
"void",
"updateRefs",
"(",
"T",
"oldObject",
",",
"T",
"newObject",
")",
"{",
"checkNotNull",
"(",
"oldObject",
")",
";",
"checkNotNull",
"(",
"newObject",
")",
";",
"checkArgument",
"(",
"!",
"(",
"newObject",
"instanceof",
"Liste... | Registers that the old object has been remapped to the new object.
<p>This is useful for auxiliary AST datastructures which may contain back-edges in the AST.
When being copied, the auxiliary data structure is registered with this method then AST nodes
which have references to the old copy can register via {@link #registerRefListener} so that
they can get a reference to the new copy as well. | [
"Registers",
"that",
"the",
"old",
"object",
"has",
"been",
"remapped",
"to",
"the",
"new",
"object",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basetree/CopyState.java#L54-L68 | train |
google/closure-templates | java/src/com/google/template/soy/basetree/CopyState.java | CopyState.checkAllListenersFired | public void checkAllListenersFired() {
for (Map.Entry<Object, Object> entry : mappings.entrySet()) {
if (entry.getValue() instanceof Listener) {
throw new IllegalStateException(
"Listener for " + entry.getKey() + " never fired: " + entry.getValue());
}
}
} | java | public void checkAllListenersFired() {
for (Map.Entry<Object, Object> entry : mappings.entrySet()) {
if (entry.getValue() instanceof Listener) {
throw new IllegalStateException(
"Listener for " + entry.getKey() + " never fired: " + entry.getValue());
}
}
} | [
"public",
"void",
"checkAllListenersFired",
"(",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"Object",
",",
"Object",
">",
"entry",
":",
"mappings",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",
"getValue",
"(",
")",
"instanceof",
... | Asserts that there are no pending listeners.
<p>This can be useful in a test environment to ensure that the copy worked correctly. N.B. it
is possible for a copy to be 'correct' and for not all listeners to fire, this is common when
copying small parts of the AST (anything below a template). | [
"Asserts",
"that",
"there",
"are",
"no",
"pending",
"listeners",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basetree/CopyState.java#L103-L110 | train |
google/closure-templates | java/src/com/google/template/soy/internal/base/UnescapeUtils.java | UnescapeUtils.unescapeHtml | public static String unescapeHtml(String s) {
int amp = s.indexOf('&');
if (amp < 0) { // Fast path.
return s;
}
int n = s.length();
StringBuilder sb = new StringBuilder(n);
int pos = 0;
do {
// All numeric entities and all named entities can be represented in less than 12 chars, so
// avoid any O(n**2) problem on "&&&&&&&&&" by not looking for ; more than 12 chars out.
int end = -1;
int entityLimit = Math.min(n, amp + 12);
for (int i = amp + 1; i < entityLimit; ++i) {
if (s.charAt(i) == ';') {
end = i + 1;
break;
}
}
int cp = -1;
if (end == -1) {
cp = -1;
} else {
if (s.charAt(amp + 1) == '#') { // Decode a numeric entity
char ch = s.charAt(amp + 2);
try {
if (ch == 'x' || ch == 'X') { // hex
// & # x A B C D ;
// ^ ^ ^ ^ ^
// amp + 0 1 2 3 end - 1
cp = Integer.parseInt(s.substring(amp + 3, end - 1), 16);
} else { // decimal
// & # 1 6 0 ;
// ^ ^ ^ ^
// amp + 0 1 2 end - 1
cp = Integer.parseInt(s.substring(amp + 2, end - 1), 10);
}
} catch (NumberFormatException ex) {
cp = -1; // Malformed numeric entity
}
} else {
// & q u o t ;
// ^ ^
// amp end
Integer cpI = HTML_ENTITY_TO_CODEPOINT.get(s.substring(amp, end));
cp = cpI != null ? cpI.intValue() : -1;
}
}
if (cp == -1) { // Don't decode
end = amp + 1;
} else {
sb.append(s, pos, amp);
sb.appendCodePoint(cp);
pos = end;
}
amp = s.indexOf('&', end);
} while (amp >= 0);
return sb.append(s, pos, n).toString();
} | java | public static String unescapeHtml(String s) {
int amp = s.indexOf('&');
if (amp < 0) { // Fast path.
return s;
}
int n = s.length();
StringBuilder sb = new StringBuilder(n);
int pos = 0;
do {
// All numeric entities and all named entities can be represented in less than 12 chars, so
// avoid any O(n**2) problem on "&&&&&&&&&" by not looking for ; more than 12 chars out.
int end = -1;
int entityLimit = Math.min(n, amp + 12);
for (int i = amp + 1; i < entityLimit; ++i) {
if (s.charAt(i) == ';') {
end = i + 1;
break;
}
}
int cp = -1;
if (end == -1) {
cp = -1;
} else {
if (s.charAt(amp + 1) == '#') { // Decode a numeric entity
char ch = s.charAt(amp + 2);
try {
if (ch == 'x' || ch == 'X') { // hex
// & # x A B C D ;
// ^ ^ ^ ^ ^
// amp + 0 1 2 3 end - 1
cp = Integer.parseInt(s.substring(amp + 3, end - 1), 16);
} else { // decimal
// & # 1 6 0 ;
// ^ ^ ^ ^
// amp + 0 1 2 end - 1
cp = Integer.parseInt(s.substring(amp + 2, end - 1), 10);
}
} catch (NumberFormatException ex) {
cp = -1; // Malformed numeric entity
}
} else {
// & q u o t ;
// ^ ^
// amp end
Integer cpI = HTML_ENTITY_TO_CODEPOINT.get(s.substring(amp, end));
cp = cpI != null ? cpI.intValue() : -1;
}
}
if (cp == -1) { // Don't decode
end = amp + 1;
} else {
sb.append(s, pos, amp);
sb.appendCodePoint(cp);
pos = end;
}
amp = s.indexOf('&', end);
} while (amp >= 0);
return sb.append(s, pos, n).toString();
} | [
"public",
"static",
"String",
"unescapeHtml",
"(",
"String",
"s",
")",
"{",
"int",
"amp",
"=",
"s",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"amp",
"<",
"0",
")",
"{",
"// Fast path.",
"return",
"s",
";",
"}",
"int",
"n",
"=",
"s",
"... | Replace all the occurrences of HTML entities with the appropriate code-points.
@param s HTML.
@return Plain text. | [
"Replace",
"all",
"the",
"occurrences",
"of",
"HTML",
"entities",
"with",
"the",
"appropriate",
"code",
"-",
"points",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/base/UnescapeUtils.java#L35-L93 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/PySrcMain.java | PySrcMain.genPySrc | private List<String> genPySrc(
SoyFileSetNode soyTree,
SoyPySrcOptions pySrcOptions,
ImmutableMap<String, String> currentManifest,
ErrorReporter errorReporter) {
BidiGlobalDir bidiGlobalDir =
SoyBidiUtils.decodeBidiGlobalDirFromPyOptions(pySrcOptions.getBidiIsRtlFn());
try (SoyScopedData.InScope inScope = apiCallScope.enter(/* msgBundle= */ null, bidiGlobalDir)) {
return createVisitor(pySrcOptions, inScope.getBidiGlobalDir(), errorReporter, currentManifest)
.gen(soyTree, errorReporter);
}
} | java | private List<String> genPySrc(
SoyFileSetNode soyTree,
SoyPySrcOptions pySrcOptions,
ImmutableMap<String, String> currentManifest,
ErrorReporter errorReporter) {
BidiGlobalDir bidiGlobalDir =
SoyBidiUtils.decodeBidiGlobalDirFromPyOptions(pySrcOptions.getBidiIsRtlFn());
try (SoyScopedData.InScope inScope = apiCallScope.enter(/* msgBundle= */ null, bidiGlobalDir)) {
return createVisitor(pySrcOptions, inScope.getBidiGlobalDir(), errorReporter, currentManifest)
.gen(soyTree, errorReporter);
}
} | [
"private",
"List",
"<",
"String",
">",
"genPySrc",
"(",
"SoyFileSetNode",
"soyTree",
",",
"SoyPySrcOptions",
"pySrcOptions",
",",
"ImmutableMap",
"<",
"String",
",",
"String",
">",
"currentManifest",
",",
"ErrorReporter",
"errorReporter",
")",
"{",
"BidiGlobalDir",
... | Generates Python source code given a Soy parse tree and an options object.
@param soyTree The Soy parse tree to generate Python source code for.
@param pySrcOptions The compilation options relevant to this backend.
@param currentManifest The namespace manifest for current sources.
@param errorReporter The Soy error reporter that collects errors during code generation.
@return A list of strings where each string represents the Python source code that belongs in
one Python file. The generated Python files correspond one-to-one to the original Soy
source files. | [
"Generates",
"Python",
"source",
"code",
"given",
"a",
"Soy",
"parse",
"tree",
"and",
"an",
"options",
"object",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/PySrcMain.java#L70-L82 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/PySrcMain.java | PySrcMain.genPyFiles | public void genPyFiles(
SoyFileSetNode soyTree,
SoyPySrcOptions pySrcOptions,
String outputPathFormat,
ErrorReporter errorReporter)
throws IOException {
ImmutableList<SoyFileNode> srcsToCompile = ImmutableList.copyOf(soyTree.getChildren());
// Determine the output paths.
List<String> soyNamespaces = getSoyNamespaces(soyTree);
Multimap<String, Integer> outputs =
MainEntryPointUtils.mapOutputsToSrcs(null, outputPathFormat, srcsToCompile);
// Generate the manifest and add it to the current manifest.
ImmutableMap<String, String> manifest = generateManifest(soyNamespaces, outputs);
// Generate the Python source.
List<String> pyFileContents = genPySrc(soyTree, pySrcOptions, manifest, errorReporter);
if (srcsToCompile.size() != pyFileContents.size()) {
throw new AssertionError(
String.format(
"Expected to generate %d code chunk(s), got %d",
srcsToCompile.size(), pyFileContents.size()));
}
// Write out the Python outputs.
for (String outputFilePath : outputs.keySet()) {
try (Writer out = Files.newWriter(new File(outputFilePath), StandardCharsets.UTF_8)) {
for (int inputFileIndex : outputs.get(outputFilePath)) {
out.write(pyFileContents.get(inputFileIndex));
}
}
}
// Write out the manifest file.
if (pySrcOptions.namespaceManifestFile() != null) {
try (Writer out =
Files.newWriter(new File(pySrcOptions.namespaceManifestFile()), StandardCharsets.UTF_8)) {
Properties prop = new Properties();
for (String namespace : manifest.keySet()) {
prop.put(namespace, manifest.get(namespace));
}
prop.store(out, null);
}
}
} | java | public void genPyFiles(
SoyFileSetNode soyTree,
SoyPySrcOptions pySrcOptions,
String outputPathFormat,
ErrorReporter errorReporter)
throws IOException {
ImmutableList<SoyFileNode> srcsToCompile = ImmutableList.copyOf(soyTree.getChildren());
// Determine the output paths.
List<String> soyNamespaces = getSoyNamespaces(soyTree);
Multimap<String, Integer> outputs =
MainEntryPointUtils.mapOutputsToSrcs(null, outputPathFormat, srcsToCompile);
// Generate the manifest and add it to the current manifest.
ImmutableMap<String, String> manifest = generateManifest(soyNamespaces, outputs);
// Generate the Python source.
List<String> pyFileContents = genPySrc(soyTree, pySrcOptions, manifest, errorReporter);
if (srcsToCompile.size() != pyFileContents.size()) {
throw new AssertionError(
String.format(
"Expected to generate %d code chunk(s), got %d",
srcsToCompile.size(), pyFileContents.size()));
}
// Write out the Python outputs.
for (String outputFilePath : outputs.keySet()) {
try (Writer out = Files.newWriter(new File(outputFilePath), StandardCharsets.UTF_8)) {
for (int inputFileIndex : outputs.get(outputFilePath)) {
out.write(pyFileContents.get(inputFileIndex));
}
}
}
// Write out the manifest file.
if (pySrcOptions.namespaceManifestFile() != null) {
try (Writer out =
Files.newWriter(new File(pySrcOptions.namespaceManifestFile()), StandardCharsets.UTF_8)) {
Properties prop = new Properties();
for (String namespace : manifest.keySet()) {
prop.put(namespace, manifest.get(namespace));
}
prop.store(out, null);
}
}
} | [
"public",
"void",
"genPyFiles",
"(",
"SoyFileSetNode",
"soyTree",
",",
"SoyPySrcOptions",
"pySrcOptions",
",",
"String",
"outputPathFormat",
",",
"ErrorReporter",
"errorReporter",
")",
"throws",
"IOException",
"{",
"ImmutableList",
"<",
"SoyFileNode",
">",
"srcsToCompil... | Generates Python source files given a Soy parse tree, an options object, and information on
where to put the output files.
@param soyTree The Soy parse tree to generate Python source code for.
@param pySrcOptions The compilation options relevant to this backend.
@param outputPathFormat The format string defining how to build the output file path
corresponding to an input file path.
@param errorReporter The Soy error reporter that collects errors during code generation.
@throws IOException If there is an error in opening/writing an output Python file. | [
"Generates",
"Python",
"source",
"files",
"given",
"a",
"Soy",
"parse",
"tree",
"an",
"options",
"object",
"and",
"information",
"on",
"where",
"to",
"put",
"the",
"output",
"files",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/PySrcMain.java#L95-L142 | train |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/PySrcMain.java | PySrcMain.generateManifest | private static ImmutableMap<String, String> generateManifest(
List<String> soyNamespaces, Multimap<String, Integer> outputs) {
ImmutableMap.Builder<String, String> manifest = new ImmutableMap.Builder<>();
for (String outputFilePath : outputs.keySet()) {
for (int inputFileIndex : outputs.get(outputFilePath)) {
String pythonPath = outputFilePath.replace(".py", "").replace('/', '.');
manifest.put(soyNamespaces.get(inputFileIndex), pythonPath);
}
}
return manifest.build();
} | java | private static ImmutableMap<String, String> generateManifest(
List<String> soyNamespaces, Multimap<String, Integer> outputs) {
ImmutableMap.Builder<String, String> manifest = new ImmutableMap.Builder<>();
for (String outputFilePath : outputs.keySet()) {
for (int inputFileIndex : outputs.get(outputFilePath)) {
String pythonPath = outputFilePath.replace(".py", "").replace('/', '.');
manifest.put(soyNamespaces.get(inputFileIndex), pythonPath);
}
}
return manifest.build();
} | [
"private",
"static",
"ImmutableMap",
"<",
"String",
",",
"String",
">",
"generateManifest",
"(",
"List",
"<",
"String",
">",
"soyNamespaces",
",",
"Multimap",
"<",
"String",
",",
"Integer",
">",
"outputs",
")",
"{",
"ImmutableMap",
".",
"Builder",
"<",
"Stri... | Generate the manifest file by finding the output file paths and converting them into a Python
import format. | [
"Generate",
"the",
"manifest",
"file",
"by",
"finding",
"the",
"output",
"file",
"paths",
"and",
"converting",
"them",
"into",
"a",
"Python",
"import",
"format",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/PySrcMain.java#L148-L159 | train |
google/closure-templates | java/src/com/google/template/soy/conformance/SoyConformance.java | SoyConformance.check | public void check(SoyFileNode file, final ErrorReporter errorReporter) {
// first filter to only the rules that need to be checked for this file.
final List<Rule<?>> rulesForFile = new ArrayList<>(rules.size());
String filePath = file.getFilePath();
for (RuleWithWhitelists rule : rules) {
if (rule.shouldCheckConformanceFor(filePath)) {
rulesForFile.add(rule.getRule());
}
}
if (rulesForFile.isEmpty()) {
return;
}
SoyTreeUtils.visitAllNodes(
file,
new NodeVisitor<Node, VisitDirective>() {
@Override
public VisitDirective exec(Node node) {
for (Rule<?> rule : rulesForFile) {
rule.checkConformance(node, errorReporter);
}
// always visit all children
return VisitDirective.CONTINUE;
}
});
} | java | public void check(SoyFileNode file, final ErrorReporter errorReporter) {
// first filter to only the rules that need to be checked for this file.
final List<Rule<?>> rulesForFile = new ArrayList<>(rules.size());
String filePath = file.getFilePath();
for (RuleWithWhitelists rule : rules) {
if (rule.shouldCheckConformanceFor(filePath)) {
rulesForFile.add(rule.getRule());
}
}
if (rulesForFile.isEmpty()) {
return;
}
SoyTreeUtils.visitAllNodes(
file,
new NodeVisitor<Node, VisitDirective>() {
@Override
public VisitDirective exec(Node node) {
for (Rule<?> rule : rulesForFile) {
rule.checkConformance(node, errorReporter);
}
// always visit all children
return VisitDirective.CONTINUE;
}
});
} | [
"public",
"void",
"check",
"(",
"SoyFileNode",
"file",
",",
"final",
"ErrorReporter",
"errorReporter",
")",
"{",
"// first filter to only the rules that need to be checked for this file.",
"final",
"List",
"<",
"Rule",
"<",
"?",
">",
">",
"rulesForFile",
"=",
"new",
"... | Performs the overall check. | [
"Performs",
"the",
"overall",
"check",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/conformance/SoyConformance.java#L53-L77 | train |
google/closure-templates | java/src/com/google/template/soy/types/SanitizedType.java | SanitizedType.getTypeForContentKind | public static SoyType getTypeForContentKind(SanitizedContentKind contentKind) {
switch (contentKind) {
case ATTRIBUTES:
return AttributesType.getInstance();
case CSS:
return StyleType.getInstance();
case HTML:
return HtmlType.getInstance();
case JS:
return JsType.getInstance();
case URI:
return UriType.getInstance();
case TRUSTED_RESOURCE_URI:
return TrustedResourceUriType.getInstance();
case TEXT:
return StringType.getInstance();
}
throw new AssertionError(contentKind);
} | java | public static SoyType getTypeForContentKind(SanitizedContentKind contentKind) {
switch (contentKind) {
case ATTRIBUTES:
return AttributesType.getInstance();
case CSS:
return StyleType.getInstance();
case HTML:
return HtmlType.getInstance();
case JS:
return JsType.getInstance();
case URI:
return UriType.getInstance();
case TRUSTED_RESOURCE_URI:
return TrustedResourceUriType.getInstance();
case TEXT:
return StringType.getInstance();
}
throw new AssertionError(contentKind);
} | [
"public",
"static",
"SoyType",
"getTypeForContentKind",
"(",
"SanitizedContentKind",
"contentKind",
")",
"{",
"switch",
"(",
"contentKind",
")",
"{",
"case",
"ATTRIBUTES",
":",
"return",
"AttributesType",
".",
"getInstance",
"(",
")",
";",
"case",
"CSS",
":",
"r... | Given a content kind, return the corresponding soy type.
<p>For {@link SanitizedContentKind#TEXT} this returns {@link StringType}, for all other types
it is a {@link SanitizedType}. | [
"Given",
"a",
"content",
"kind",
"return",
"the",
"corresponding",
"soy",
"type",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SanitizedType.java#L44-L68 | train |
google/closure-templates | java/src/com/google/template/soy/SoyCmdLineParser.java | SoyCmdLineParser.instantiateObject | private static <T> T instantiateObject(
String flagName,
String objectType,
Class<T> clazz,
PluginLoader loader,
String instanceClassName) {
try {
return loader.loadPlugin(instanceClassName).asSubclass(clazz).getConstructor().newInstance();
} catch (ClassCastException cce) {
throw new CommandLineError(
String.format(
"%s \"%s\" is not a subclass of %s. Classes passed to %s should be %ss. "
+ "Did you pass it to the wrong flag?",
objectType,
instanceClassName,
clazz.getSimpleName(),
flagName,
clazz.getSimpleName()),
cce);
} catch (ReflectiveOperationException e) {
throw new CommandLineError(
String.format(
"Cannot instantiate %s \"%s\" registered with flag %s. Please make "
+ "sure that the %s exists and is on the compiler classpath and has a public "
+ "zero arguments constructor.",
objectType, instanceClassName, flagName, objectType),
e);
} catch (ExceptionInInitializerError e) {
throw new CommandLineError(
String.format(
"Cannot instantiate %s \"%s\" registered with flag %s. An error was thrown while "
+ "loading the class. There is a bug in the implementation.",
objectType, instanceClassName, flagName),
e);
} catch (SecurityException e) {
throw new CommandLineError(
String.format(
"Cannot instantiate %s \"%s\" registered with flag %s. A security manager is "
+ "preventing instantiation.",
objectType, instanceClassName, flagName),
e);
}
} | java | private static <T> T instantiateObject(
String flagName,
String objectType,
Class<T> clazz,
PluginLoader loader,
String instanceClassName) {
try {
return loader.loadPlugin(instanceClassName).asSubclass(clazz).getConstructor().newInstance();
} catch (ClassCastException cce) {
throw new CommandLineError(
String.format(
"%s \"%s\" is not a subclass of %s. Classes passed to %s should be %ss. "
+ "Did you pass it to the wrong flag?",
objectType,
instanceClassName,
clazz.getSimpleName(),
flagName,
clazz.getSimpleName()),
cce);
} catch (ReflectiveOperationException e) {
throw new CommandLineError(
String.format(
"Cannot instantiate %s \"%s\" registered with flag %s. Please make "
+ "sure that the %s exists and is on the compiler classpath and has a public "
+ "zero arguments constructor.",
objectType, instanceClassName, flagName, objectType),
e);
} catch (ExceptionInInitializerError e) {
throw new CommandLineError(
String.format(
"Cannot instantiate %s \"%s\" registered with flag %s. An error was thrown while "
+ "loading the class. There is a bug in the implementation.",
objectType, instanceClassName, flagName),
e);
} catch (SecurityException e) {
throw new CommandLineError(
String.format(
"Cannot instantiate %s \"%s\" registered with flag %s. A security manager is "
+ "preventing instantiation.",
objectType, instanceClassName, flagName),
e);
}
} | [
"private",
"static",
"<",
"T",
">",
"T",
"instantiateObject",
"(",
"String",
"flagName",
",",
"String",
"objectType",
",",
"Class",
"<",
"T",
">",
"clazz",
",",
"PluginLoader",
"loader",
",",
"String",
"instanceClassName",
")",
"{",
"try",
"{",
"return",
"... | Private helper for creating objects from flags.
@param instanceClassName The name of the class to instantiate.
@return A new instance of the specified plugin module. | [
"Private",
"helper",
"for",
"creating",
"objects",
"from",
"flags",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyCmdLineParser.java#L335-L377 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/JsCodeBuilder.java | JsCodeBuilder.addChunksToOutputVar | public JsCodeBuilder addChunksToOutputVar(List<? extends Expression> codeChunks) {
if (currOutputVarIsInited) {
Expression rhs = CodeChunkUtils.concatChunks(codeChunks);
rhs.collectRequires(requireCollector);
appendLine(currOutputVar.plusEquals(rhs).getCode());
} else {
Expression rhs = CodeChunkUtils.concatChunksForceString(codeChunks);
rhs.collectRequires(requireCollector);
append(
VariableDeclaration.builder(currOutputVar.singleExprOrName().getText())
.setRhs(rhs)
.build());
setOutputVarInited();
}
return this;
} | java | public JsCodeBuilder addChunksToOutputVar(List<? extends Expression> codeChunks) {
if (currOutputVarIsInited) {
Expression rhs = CodeChunkUtils.concatChunks(codeChunks);
rhs.collectRequires(requireCollector);
appendLine(currOutputVar.plusEquals(rhs).getCode());
} else {
Expression rhs = CodeChunkUtils.concatChunksForceString(codeChunks);
rhs.collectRequires(requireCollector);
append(
VariableDeclaration.builder(currOutputVar.singleExprOrName().getText())
.setRhs(rhs)
.build());
setOutputVarInited();
}
return this;
} | [
"public",
"JsCodeBuilder",
"addChunksToOutputVar",
"(",
"List",
"<",
"?",
"extends",
"Expression",
">",
"codeChunks",
")",
"{",
"if",
"(",
"currOutputVarIsInited",
")",
"{",
"Expression",
"rhs",
"=",
"CodeChunkUtils",
".",
"concatChunks",
"(",
"codeChunks",
")",
... | Appends one or more lines representing the concatenation of the values of the given code chunks
saved to the current output variable. | [
"Appends",
"one",
"or",
"more",
"lines",
"representing",
"the",
"concatenation",
"of",
"the",
"values",
"of",
"the",
"given",
"code",
"chunks",
"saved",
"to",
"the",
"current",
"output",
"variable",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsCodeBuilder.java#L164-L179 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/JsCodeBuilder.java | JsCodeBuilder.changeIndentHelper | private JsCodeBuilder changeIndentHelper(int chg) {
int newIndentDepth = indent.length() + chg * INDENT_SIZE;
Preconditions.checkState(newIndentDepth >= 0);
indent = Strings.repeat(" ", newIndentDepth);
return this;
} | java | private JsCodeBuilder changeIndentHelper(int chg) {
int newIndentDepth = indent.length() + chg * INDENT_SIZE;
Preconditions.checkState(newIndentDepth >= 0);
indent = Strings.repeat(" ", newIndentDepth);
return this;
} | [
"private",
"JsCodeBuilder",
"changeIndentHelper",
"(",
"int",
"chg",
")",
"{",
"int",
"newIndentDepth",
"=",
"indent",
".",
"length",
"(",
")",
"+",
"chg",
"*",
"INDENT_SIZE",
";",
"Preconditions",
".",
"checkState",
"(",
"newIndentDepth",
">=",
"0",
")",
";... | Helper for the various indent methods.
@param chg The number of indent levels to change. | [
"Helper",
"for",
"the",
"various",
"indent",
"methods",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsCodeBuilder.java#L205-L210 | train |
google/closure-templates | java/src/com/google/template/soy/data/SanitizedContent.java | SanitizedContent.create | static SanitizedContent create(String content, ContentKind kind) {
checkArgument(
kind != ContentKind.TEXT, "Use UnsanitizedString for SanitizedContent with a kind of TEXT");
if (Flags.stringIsNotSanitizedContent()) {
return new SanitizedContent(content, kind, kind.getDefaultDir());
}
return SanitizedCompatString.create(content, kind, kind.getDefaultDir());
} | java | static SanitizedContent create(String content, ContentKind kind) {
checkArgument(
kind != ContentKind.TEXT, "Use UnsanitizedString for SanitizedContent with a kind of TEXT");
if (Flags.stringIsNotSanitizedContent()) {
return new SanitizedContent(content, kind, kind.getDefaultDir());
}
return SanitizedCompatString.create(content, kind, kind.getDefaultDir());
} | [
"static",
"SanitizedContent",
"create",
"(",
"String",
"content",
",",
"ContentKind",
"kind",
")",
"{",
"checkArgument",
"(",
"kind",
"!=",
"ContentKind",
".",
"TEXT",
",",
"\"Use UnsanitizedString for SanitizedContent with a kind of TEXT\"",
")",
";",
"if",
"(",
"Fla... | Creates a SanitizedContent object with default direction. | [
"Creates",
"a",
"SanitizedContent",
"object",
"with",
"default",
"direction",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SanitizedContent.java#L77-L84 | train |
google/closure-templates | java/src/com/google/template/soy/shared/internal/StreamingEscaper.java | StreamingEscaper.create | public static StreamingEscaper create(
LoggingAdvisingAppendable delegate, CrossLanguageStringXform transform) {
if (delegate instanceof StreamingEscaper) {
StreamingEscaper delegateAsStreamingEscaper = (StreamingEscaper) delegate;
if (delegateAsStreamingEscaper.transform == transform) {
return delegateAsStreamingEscaper;
}
}
return new StreamingEscaper(delegate, transform);
} | java | public static StreamingEscaper create(
LoggingAdvisingAppendable delegate, CrossLanguageStringXform transform) {
if (delegate instanceof StreamingEscaper) {
StreamingEscaper delegateAsStreamingEscaper = (StreamingEscaper) delegate;
if (delegateAsStreamingEscaper.transform == transform) {
return delegateAsStreamingEscaper;
}
}
return new StreamingEscaper(delegate, transform);
} | [
"public",
"static",
"StreamingEscaper",
"create",
"(",
"LoggingAdvisingAppendable",
"delegate",
",",
"CrossLanguageStringXform",
"transform",
")",
"{",
"if",
"(",
"delegate",
"instanceof",
"StreamingEscaper",
")",
"{",
"StreamingEscaper",
"delegateAsStreamingEscaper",
"=",
... | Creates a streaming escaper, or returns the delegate if it is already escaping with the same
settings. | [
"Creates",
"a",
"streaming",
"escaper",
"or",
"returns",
"the",
"delegate",
"if",
"it",
"is",
"already",
"escaping",
"with",
"the",
"same",
"settings",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/StreamingEscaper.java#L37-L46 | train |
google/closure-templates | java/src/com/google/template/soy/exprtree/GlobalNode.java | GlobalNode.onResolve | public void onResolve(ResolutionCallback callback) {
checkState(this.resolveCallback == null, "callback has already been set.");
checkState(this.value == null, "value is resolved.");
this.resolveCallback = checkNotNull(callback);
} | java | public void onResolve(ResolutionCallback callback) {
checkState(this.resolveCallback == null, "callback has already been set.");
checkState(this.value == null, "value is resolved.");
this.resolveCallback = checkNotNull(callback);
} | [
"public",
"void",
"onResolve",
"(",
"ResolutionCallback",
"callback",
")",
"{",
"checkState",
"(",
"this",
".",
"resolveCallback",
"==",
"null",
",",
"\"callback has already been set.\"",
")",
";",
"checkState",
"(",
"this",
".",
"value",
"==",
"null",
",",
"\"v... | Registers a callback that is invoked when this global is resolved to its actual value.
<p>NOTE: there is no guarantee that this will ever be called. | [
"Registers",
"a",
"callback",
"that",
"is",
"invoked",
"when",
"this",
"global",
"is",
"resolved",
"to",
"its",
"actual",
"value",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/exprtree/GlobalNode.java#L103-L107 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Statement.java | Statement.assign | public static Statement assign(Expression lhs, Expression rhs) {
return Assignment.create(lhs, rhs, null);
} | java | public static Statement assign(Expression lhs, Expression rhs) {
return Assignment.create(lhs, rhs, null);
} | [
"public",
"static",
"Statement",
"assign",
"(",
"Expression",
"lhs",
",",
"Expression",
"rhs",
")",
"{",
"return",
"Assignment",
".",
"create",
"(",
"lhs",
",",
"rhs",
",",
"null",
")",
";",
"}"
] | Creates a code chunk that assigns value to a preexisting variable with the given name. | [
"Creates",
"a",
"code",
"chunk",
"that",
"assigns",
"value",
"to",
"a",
"preexisting",
"variable",
"with",
"the",
"given",
"name",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Statement.java#L47-L49 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Statement.java | Statement.assign | public static Statement assign(Expression lhs, Expression rhs, JsDoc jsDoc) {
return Assignment.create(lhs, rhs, jsDoc);
} | java | public static Statement assign(Expression lhs, Expression rhs, JsDoc jsDoc) {
return Assignment.create(lhs, rhs, jsDoc);
} | [
"public",
"static",
"Statement",
"assign",
"(",
"Expression",
"lhs",
",",
"Expression",
"rhs",
",",
"JsDoc",
"jsDoc",
")",
"{",
"return",
"Assignment",
".",
"create",
"(",
"lhs",
",",
"rhs",
",",
"jsDoc",
")",
";",
"}"
] | Creates a code chunk that assigns and prints jsDoc above the assignment. | [
"Creates",
"a",
"code",
"chunk",
"that",
"assigns",
"and",
"prints",
"jsDoc",
"above",
"the",
"assignment",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Statement.java#L52-L54 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Statement.java | Statement.forLoop | public static Statement forLoop(String localVar, Expression limit, Statement body) {
return For.create(localVar, Expression.number(0), limit, Expression.number(1), body);
} | java | public static Statement forLoop(String localVar, Expression limit, Statement body) {
return For.create(localVar, Expression.number(0), limit, Expression.number(1), body);
} | [
"public",
"static",
"Statement",
"forLoop",
"(",
"String",
"localVar",
",",
"Expression",
"limit",
",",
"Statement",
"body",
")",
"{",
"return",
"For",
".",
"create",
"(",
"localVar",
",",
"Expression",
".",
"number",
"(",
"0",
")",
",",
"limit",
",",
"E... | Creates a code chunk representing a for loop, with default values for initial & increment. | [
"Creates",
"a",
"code",
"chunk",
"representing",
"a",
"for",
"loop",
"with",
"default",
"values",
"for",
"initial",
"&",
"increment",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Statement.java#L73-L75 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/BytecodeCompiler.java | BytecodeCompiler.compile | public static Optional<CompiledTemplates> compile(
final TemplateRegistry registry,
final SoyFileSetNode fileSet,
boolean developmentMode,
ErrorReporter reporter,
ImmutableMap<String, SoyFileSupplier> filePathsToSuppliers,
SoyTypeRegistry typeRegistry) {
final Stopwatch stopwatch = Stopwatch.createStarted();
ErrorReporter.Checkpoint checkpoint = reporter.checkpoint();
if (reporter.errorsSince(checkpoint)) {
return Optional.absent();
}
CompiledTemplateRegistry compilerRegistry = new CompiledTemplateRegistry(registry);
if (developmentMode) {
CompiledTemplates templates =
new CompiledTemplates(
compilerRegistry.getDelegateTemplateNames(),
new CompilingClassLoader(
compilerRegistry, fileSet, filePathsToSuppliers, typeRegistry));
if (reporter.errorsSince(checkpoint)) {
return Optional.absent();
}
// TODO(lukes): consider spawning a thread to load all the generated classes in the background
return Optional.of(templates);
}
// TODO(lukes): once most internal users have moved to precompilation eliminate this and just
// use the 'developmentMode' path above. This hybrid only makes sense for production services
// that are doing runtime compilation. Hopefully, this will become an anomaly.
List<ClassData> classes =
compileTemplates(
compilerRegistry,
fileSet,
reporter,
typeRegistry,
new CompilerListener<List<ClassData>>() {
final List<ClassData> compiledClasses = new ArrayList<>();
int numBytes = 0;
int numFields = 0;
int numDetachStates = 0;
@Override
public void onCompile(ClassData clazz) {
numBytes += clazz.data().length;
numFields += clazz.numberOfFields();
numDetachStates += clazz.numberOfDetachStates();
compiledClasses.add(clazz);
}
@Override
public List<ClassData> getResult() {
logger.log(
Level.FINE,
"Compilation took {0}\n"
+ " templates: {1}\n"
+ " classes: {2}\n"
+ " bytes: {3}\n"
+ " fields: {4}\n"
+ " detachStates: {5}",
new Object[] {
stopwatch.toString(),
registry.getAllTemplates().size(),
compiledClasses.size(),
numBytes,
numFields,
numDetachStates
});
return compiledClasses;
}
});
if (reporter.errorsSince(checkpoint)) {
return Optional.absent();
}
CompiledTemplates templates =
new CompiledTemplates(
compilerRegistry.getDelegateTemplateNames(), new MemoryClassLoader(classes));
stopwatch.reset().start();
templates.loadAll(compilerRegistry.getTemplateNames());
logger.log(Level.FINE, "Loaded all classes in {0}", stopwatch);
return Optional.of(templates);
} | java | public static Optional<CompiledTemplates> compile(
final TemplateRegistry registry,
final SoyFileSetNode fileSet,
boolean developmentMode,
ErrorReporter reporter,
ImmutableMap<String, SoyFileSupplier> filePathsToSuppliers,
SoyTypeRegistry typeRegistry) {
final Stopwatch stopwatch = Stopwatch.createStarted();
ErrorReporter.Checkpoint checkpoint = reporter.checkpoint();
if (reporter.errorsSince(checkpoint)) {
return Optional.absent();
}
CompiledTemplateRegistry compilerRegistry = new CompiledTemplateRegistry(registry);
if (developmentMode) {
CompiledTemplates templates =
new CompiledTemplates(
compilerRegistry.getDelegateTemplateNames(),
new CompilingClassLoader(
compilerRegistry, fileSet, filePathsToSuppliers, typeRegistry));
if (reporter.errorsSince(checkpoint)) {
return Optional.absent();
}
// TODO(lukes): consider spawning a thread to load all the generated classes in the background
return Optional.of(templates);
}
// TODO(lukes): once most internal users have moved to precompilation eliminate this and just
// use the 'developmentMode' path above. This hybrid only makes sense for production services
// that are doing runtime compilation. Hopefully, this will become an anomaly.
List<ClassData> classes =
compileTemplates(
compilerRegistry,
fileSet,
reporter,
typeRegistry,
new CompilerListener<List<ClassData>>() {
final List<ClassData> compiledClasses = new ArrayList<>();
int numBytes = 0;
int numFields = 0;
int numDetachStates = 0;
@Override
public void onCompile(ClassData clazz) {
numBytes += clazz.data().length;
numFields += clazz.numberOfFields();
numDetachStates += clazz.numberOfDetachStates();
compiledClasses.add(clazz);
}
@Override
public List<ClassData> getResult() {
logger.log(
Level.FINE,
"Compilation took {0}\n"
+ " templates: {1}\n"
+ " classes: {2}\n"
+ " bytes: {3}\n"
+ " fields: {4}\n"
+ " detachStates: {5}",
new Object[] {
stopwatch.toString(),
registry.getAllTemplates().size(),
compiledClasses.size(),
numBytes,
numFields,
numDetachStates
});
return compiledClasses;
}
});
if (reporter.errorsSince(checkpoint)) {
return Optional.absent();
}
CompiledTemplates templates =
new CompiledTemplates(
compilerRegistry.getDelegateTemplateNames(), new MemoryClassLoader(classes));
stopwatch.reset().start();
templates.loadAll(compilerRegistry.getTemplateNames());
logger.log(Level.FINE, "Loaded all classes in {0}", stopwatch);
return Optional.of(templates);
} | [
"public",
"static",
"Optional",
"<",
"CompiledTemplates",
">",
"compile",
"(",
"final",
"TemplateRegistry",
"registry",
",",
"final",
"SoyFileSetNode",
"fileSet",
",",
"boolean",
"developmentMode",
",",
"ErrorReporter",
"reporter",
",",
"ImmutableMap",
"<",
"String",
... | Compiles all the templates in the given registry.
@param registry All the templates to compile
@param developmentMode Whether or not we are in development mode. In development mode we
compile classes lazily
@param reporter The error reporter
@return CompiledTemplates or {@code absent()} if compilation fails, in which case errors will
have been reported to the error reporter. | [
"Compiles",
"all",
"the",
"templates",
"in",
"the",
"given",
"registry",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/BytecodeCompiler.java#L78-L157 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/MethodRef.java | MethodRef.invokeUnchecked | public void invokeUnchecked(CodeBuilder cb) {
cb.visitMethodInsn(
opcode(),
owner().internalName(),
method().getName(),
method().getDescriptor(),
// This is for whether the methods owner is an interface. This is mostly to handle java8
// default methods on interfaces. We don't care about those currently, but ASM requires
// this.
opcode() == Opcodes.INVOKEINTERFACE);
} | java | public void invokeUnchecked(CodeBuilder cb) {
cb.visitMethodInsn(
opcode(),
owner().internalName(),
method().getName(),
method().getDescriptor(),
// This is for whether the methods owner is an interface. This is mostly to handle java8
// default methods on interfaces. We don't care about those currently, but ASM requires
// this.
opcode() == Opcodes.INVOKEINTERFACE);
} | [
"public",
"void",
"invokeUnchecked",
"(",
"CodeBuilder",
"cb",
")",
"{",
"cb",
".",
"visitMethodInsn",
"(",
"opcode",
"(",
")",
",",
"owner",
"(",
")",
".",
"internalName",
"(",
")",
",",
"method",
"(",
")",
".",
"getName",
"(",
")",
",",
"method",
"... | Writes an invoke instruction for this method to the given adapter. Useful when the expression
is not useful for representing operations. For example, explicit dup operations are awkward in
the Expression api. | [
"Writes",
"an",
"invoke",
"instruction",
"for",
"this",
"method",
"to",
"the",
"given",
"adapter",
".",
"Useful",
"when",
"the",
"expression",
"is",
"not",
"useful",
"for",
"representing",
"operations",
".",
"For",
"example",
"explicit",
"dup",
"operations",
"... | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/MethodRef.java#L576-L586 | train |
google/closure-templates | java/src/com/google/template/soy/data/SoyData.java | SoyData.createFromExistingData | @Deprecated
protected static SoyData createFromExistingData(Object obj) {
if (obj instanceof SoyData) {
return (SoyData) obj;
} else if (obj instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, ?> objCast = (Map<String, ?>) obj;
return new SoyMapData(objCast);
} else if (obj instanceof Iterable<?>) {
return new SoyListData((Iterable<?>) obj);
} else if (obj instanceof Future<?>) {
// Note: In the old SoyData, we don't support late-resolution of Futures. We immediately
// resolve the Future object here. For late-resolution, use SoyValueConverter.convert().
try {
return createFromExistingData(((Future<?>) obj).get());
} catch (InterruptedException e) {
throw new SoyDataException(
"Encountered InterruptedException when resolving Future object.", e);
} catch (ExecutionException e) {
throw new SoyDataException(
"Encountered ExecutionException when resolving Future object.", e);
}
} else {
SoyValue soyValue = SoyValueConverter.INSTANCE.convert(obj).resolve();
if (soyValue instanceof SoyData) {
return (SoyData) soyValue;
}
throw new SoyDataException(
"Attempting to convert unrecognized object to Soy data (object type "
+ obj.getClass().getName()
+ ").");
}
} | java | @Deprecated
protected static SoyData createFromExistingData(Object obj) {
if (obj instanceof SoyData) {
return (SoyData) obj;
} else if (obj instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, ?> objCast = (Map<String, ?>) obj;
return new SoyMapData(objCast);
} else if (obj instanceof Iterable<?>) {
return new SoyListData((Iterable<?>) obj);
} else if (obj instanceof Future<?>) {
// Note: In the old SoyData, we don't support late-resolution of Futures. We immediately
// resolve the Future object here. For late-resolution, use SoyValueConverter.convert().
try {
return createFromExistingData(((Future<?>) obj).get());
} catch (InterruptedException e) {
throw new SoyDataException(
"Encountered InterruptedException when resolving Future object.", e);
} catch (ExecutionException e) {
throw new SoyDataException(
"Encountered ExecutionException when resolving Future object.", e);
}
} else {
SoyValue soyValue = SoyValueConverter.INSTANCE.convert(obj).resolve();
if (soyValue instanceof SoyData) {
return (SoyData) soyValue;
}
throw new SoyDataException(
"Attempting to convert unrecognized object to Soy data (object type "
+ obj.getClass().getName()
+ ").");
}
} | [
"@",
"Deprecated",
"protected",
"static",
"SoyData",
"createFromExistingData",
"(",
"Object",
"obj",
")",
"{",
"if",
"(",
"obj",
"instanceof",
"SoyData",
")",
"{",
"return",
"(",
"SoyData",
")",
"obj",
";",
"}",
"else",
"if",
"(",
"obj",
"instanceof",
"Map... | Creates deprecated SoyData objects from standard Java data structures.
@param obj The existing object or data structure to convert.
@return A SoyData object or tree that corresponds to the given object.
@throws SoyDataException If the given object cannot be converted to SoyData.
@deprecated It's best to pass whatever object you have directly to the Soy templates you're
using -- Soy understands primitives, lists, and maps natively, and if you install runtime
support you can also pass protocol buffers. If you're interacting directly with the Soy
runtime and need SoyValue objects, use SoyValueConverter instead. | [
"Creates",
"deprecated",
"SoyData",
"objects",
"from",
"standard",
"Java",
"data",
"structures",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SoyData.java#L42-L74 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/restricted/MsgPartUtils.java | MsgPartUtils.hasPlrselPart | public static boolean hasPlrselPart(List<SoyMsgPart> msgParts) {
for (SoyMsgPart origMsgPart : msgParts) {
if (origMsgPart instanceof SoyMsgPluralPart || origMsgPart instanceof SoyMsgSelectPart) {
return true;
}
}
return false;
} | java | public static boolean hasPlrselPart(List<SoyMsgPart> msgParts) {
for (SoyMsgPart origMsgPart : msgParts) {
if (origMsgPart instanceof SoyMsgPluralPart || origMsgPart instanceof SoyMsgSelectPart) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"hasPlrselPart",
"(",
"List",
"<",
"SoyMsgPart",
">",
"msgParts",
")",
"{",
"for",
"(",
"SoyMsgPart",
"origMsgPart",
":",
"msgParts",
")",
"{",
"if",
"(",
"origMsgPart",
"instanceof",
"SoyMsgPluralPart",
"||",
"origMsgPart",
"insta... | Checks whether a given list of msg parts has any plural or select parts.
@param msgParts The msg parts to check.
@return Whether there are any plural or select parts. | [
"Checks",
"whether",
"a",
"given",
"list",
"of",
"msg",
"parts",
"has",
"any",
"plural",
"or",
"select",
"parts",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/restricted/MsgPartUtils.java#L35-L42 | train |
google/closure-templates | java/src/com/google/template/soy/data/SoyListData.java | SoyListData.set | public void set(int index, SoyData value) {
if (index == list.size()) {
list.add(ensureValidValue(value));
} else {
list.set(index, ensureValidValue(value));
}
} | java | public void set(int index, SoyData value) {
if (index == list.size()) {
list.add(ensureValidValue(value));
} else {
list.set(index, ensureValidValue(value));
}
} | [
"public",
"void",
"set",
"(",
"int",
"index",
",",
"SoyData",
"value",
")",
"{",
"if",
"(",
"index",
"==",
"list",
".",
"size",
"(",
")",
")",
"{",
"list",
".",
"add",
"(",
"ensureValidValue",
"(",
"value",
")",
")",
";",
"}",
"else",
"{",
"list"... | Sets a data value at a given index.
@param index The index.
@param value The data to set. | [
"Sets",
"a",
"data",
"value",
"at",
"a",
"given",
"index",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SoyListData.java#L240-L246 | train |
google/closure-templates | java/src/com/google/template/soy/data/SoyListData.java | SoyListData.get | @Override
public SoyData get(int index) {
try {
return list.get(index);
} catch (IndexOutOfBoundsException ioobe) {
return null;
}
} | java | @Override
public SoyData get(int index) {
try {
return list.get(index);
} catch (IndexOutOfBoundsException ioobe) {
return null;
}
} | [
"@",
"Override",
"public",
"SoyData",
"get",
"(",
"int",
"index",
")",
"{",
"try",
"{",
"return",
"list",
".",
"get",
"(",
"index",
")",
";",
"}",
"catch",
"(",
"IndexOutOfBoundsException",
"ioobe",
")",
"{",
"return",
"null",
";",
"}",
"}"
] | Gets the data value at a given index.
@param index The index.
@return The data at the given index, or null of the index is undefined. | [
"Gets",
"the",
"data",
"value",
"at",
"a",
"given",
"index",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SoyListData.java#L307-L314 | train |
google/closure-templates | java/src/com/google/template/soy/error/SoyErrors.java | SoyErrors.getDidYouMeanMessage | public static String getDidYouMeanMessage(Iterable<String> allNames, String wrongName) {
String closestName = getClosest(allNames, wrongName);
if (closestName != null) {
return String.format(" Did you mean '%s'?", closestName);
}
return "";
} | java | public static String getDidYouMeanMessage(Iterable<String> allNames, String wrongName) {
String closestName = getClosest(allNames, wrongName);
if (closestName != null) {
return String.format(" Did you mean '%s'?", closestName);
}
return "";
} | [
"public",
"static",
"String",
"getDidYouMeanMessage",
"(",
"Iterable",
"<",
"String",
">",
"allNames",
",",
"String",
"wrongName",
")",
"{",
"String",
"closestName",
"=",
"getClosest",
"(",
"allNames",
",",
"wrongName",
")",
";",
"if",
"(",
"closestName",
"!="... | Given a collection of strings and a name that isn't contained in it. Return a message that
suggests one of the names.
<p>Returns the empty string if {@code allNames} is empty or there is no close match. | [
"Given",
"a",
"collection",
"of",
"strings",
"and",
"a",
"name",
"that",
"isn",
"t",
"contained",
"in",
"it",
".",
"Return",
"a",
"message",
"that",
"suggests",
"one",
"of",
"the",
"names",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/error/SoyErrors.java#L37-L43 | train |
google/closure-templates | java/src/com/google/template/soy/error/SoyErrors.java | SoyErrors.distance | private static int distance(String s, String t, int maxDistance) {
// create two work vectors of integer distances
// it is possible to reduce this to only one array, but performance isn't that important here.
// We could also avoid calculating a lot of the entries by taking maxDistance into account in
// the inner loop. This would only be worth optimizing if it showed up in a profile.
int[] v0 = new int[t.length() + 1];
int[] v1 = new int[t.length() + 1];
// initialize v0 (the previous row of distances)
// this row is A[0][i]: edit distance for an empty s
// the distance is just the number of characters to delete from t
for (int i = 0; i < v0.length; i++) {
v0[i] = i;
}
for (int i = 0; i < s.length(); i++) {
// calculate v1 (current row distances) from the previous row v0
// first element of v1 is A[i+1][0]
// edit distance is delete (i+1) chars from s to match empty t
v1[0] = i + 1;
int bestThisRow = v1[0];
char sChar = Ascii.toLowerCase(s.charAt(i));
// use formula to fill in the rest of the row
for (int j = 0; j < t.length(); j++) {
char tChar = Ascii.toLowerCase(t.charAt(j));
v1[j + 1] =
Math.min(
v1[j] + 1, // deletion
Math.min(
v0[j + 1] + 1, // insertion
v0[j] + ((sChar == tChar) ? 0 : 1))); // substitution
bestThisRow = Math.min(bestThisRow, v1[j + 1]);
}
if (bestThisRow > maxDistance) {
// if we couldn't possibly do better than maxDistance, stop trying.
return maxDistance + 1;
}
// swap v1 (current row) to v0 (previous row) for next iteration. no need to clear previous
// row since we always update all of v1 on each iteration.
int[] tmp = v0;
v0 = v1;
v1 = tmp;
}
// The best answer is the last slot in v0 (due to the swap on the last iteration)
return v0[t.length()];
} | java | private static int distance(String s, String t, int maxDistance) {
// create two work vectors of integer distances
// it is possible to reduce this to only one array, but performance isn't that important here.
// We could also avoid calculating a lot of the entries by taking maxDistance into account in
// the inner loop. This would only be worth optimizing if it showed up in a profile.
int[] v0 = new int[t.length() + 1];
int[] v1 = new int[t.length() + 1];
// initialize v0 (the previous row of distances)
// this row is A[0][i]: edit distance for an empty s
// the distance is just the number of characters to delete from t
for (int i = 0; i < v0.length; i++) {
v0[i] = i;
}
for (int i = 0; i < s.length(); i++) {
// calculate v1 (current row distances) from the previous row v0
// first element of v1 is A[i+1][0]
// edit distance is delete (i+1) chars from s to match empty t
v1[0] = i + 1;
int bestThisRow = v1[0];
char sChar = Ascii.toLowerCase(s.charAt(i));
// use formula to fill in the rest of the row
for (int j = 0; j < t.length(); j++) {
char tChar = Ascii.toLowerCase(t.charAt(j));
v1[j + 1] =
Math.min(
v1[j] + 1, // deletion
Math.min(
v0[j + 1] + 1, // insertion
v0[j] + ((sChar == tChar) ? 0 : 1))); // substitution
bestThisRow = Math.min(bestThisRow, v1[j + 1]);
}
if (bestThisRow > maxDistance) {
// if we couldn't possibly do better than maxDistance, stop trying.
return maxDistance + 1;
}
// swap v1 (current row) to v0 (previous row) for next iteration. no need to clear previous
// row since we always update all of v1 on each iteration.
int[] tmp = v0;
v0 = v1;
v1 = tmp;
}
// The best answer is the last slot in v0 (due to the swap on the last iteration)
return v0[t.length()];
} | [
"private",
"static",
"int",
"distance",
"(",
"String",
"s",
",",
"String",
"t",
",",
"int",
"maxDistance",
")",
"{",
"// create two work vectors of integer distances",
"// it is possible to reduce this to only one array, but performance isn't that important here.",
"// We could als... | Performs a case insensitive Levenshtein edit distance based on the 2 rows implementation.
@param s The first string
@param t The second string
@param maxDistance The distance to beat, if we can't do better, stop trying
@return an integer describing the number of edits needed to transform s into t
@see "https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows" | [
"Performs",
"a",
"case",
"insensitive",
"Levenshtein",
"edit",
"distance",
"based",
"on",
"the",
"2",
"rows",
"implementation",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/error/SoyErrors.java#L101-L148 | train |
google/closure-templates | java/src/com/google/template/soy/error/SoyErrors.java | SoyErrors.formatErrors | public static String formatErrors(Iterable<SoyError> errors) {
int numErrors = 0;
int numWarnings = 0;
for (SoyError error : errors) {
if (error.isWarning()) {
numWarnings++;
} else {
numErrors++;
}
}
if (numErrors + numWarnings == 0) {
throw new IllegalArgumentException("cannot format 0 errors");
}
StringBuilder sb =
new StringBuilder(numErrors == 0 ? "warnings" : "errors")
.append(" during Soy compilation\n");
Joiner.on('\n').appendTo(sb, errors);
if (numErrors > 0) {
formatNumber(numErrors, "error", sb);
}
if (numWarnings > 0) {
if (numErrors > 0) {
sb.append(' ');
}
formatNumber(numWarnings, "warning", sb);
}
return sb.append('\n').toString();
} | java | public static String formatErrors(Iterable<SoyError> errors) {
int numErrors = 0;
int numWarnings = 0;
for (SoyError error : errors) {
if (error.isWarning()) {
numWarnings++;
} else {
numErrors++;
}
}
if (numErrors + numWarnings == 0) {
throw new IllegalArgumentException("cannot format 0 errors");
}
StringBuilder sb =
new StringBuilder(numErrors == 0 ? "warnings" : "errors")
.append(" during Soy compilation\n");
Joiner.on('\n').appendTo(sb, errors);
if (numErrors > 0) {
formatNumber(numErrors, "error", sb);
}
if (numWarnings > 0) {
if (numErrors > 0) {
sb.append(' ');
}
formatNumber(numWarnings, "warning", sb);
}
return sb.append('\n').toString();
} | [
"public",
"static",
"String",
"formatErrors",
"(",
"Iterable",
"<",
"SoyError",
">",
"errors",
")",
"{",
"int",
"numErrors",
"=",
"0",
";",
"int",
"numWarnings",
"=",
"0",
";",
"for",
"(",
"SoyError",
"error",
":",
"errors",
")",
"{",
"if",
"(",
"error... | Formats the errors in a standard way for displaying to a user. | [
"Formats",
"the",
"errors",
"in",
"a",
"standard",
"way",
"for",
"displaying",
"to",
"a",
"user",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/error/SoyErrors.java#L151-L178 | train |
google/closure-templates | java/src/com/google/template/soy/data/SoyDataException.java | SoyDataException.prependKeyToDataPath | public void prependKeyToDataPath(String key) {
if (dataPath == null) {
dataPath = key;
} else {
dataPath = key + ((dataPath.charAt(0) == '[') ? "" : ".") + dataPath;
}
} | java | public void prependKeyToDataPath(String key) {
if (dataPath == null) {
dataPath = key;
} else {
dataPath = key + ((dataPath.charAt(0) == '[') ? "" : ".") + dataPath;
}
} | [
"public",
"void",
"prependKeyToDataPath",
"(",
"String",
"key",
")",
"{",
"if",
"(",
"dataPath",
"==",
"null",
")",
"{",
"dataPath",
"=",
"key",
";",
"}",
"else",
"{",
"dataPath",
"=",
"key",
"+",
"(",
"(",
"dataPath",
".",
"charAt",
"(",
"0",
")",
... | Prepends a key to the data path where this error occurred. E.g. if the dataPath was previously
'foo.goo' and the key to prepend is 'boo', then the new data path will be 'boo.foo.goo'.
@param key The key to prepend. | [
"Prepends",
"a",
"key",
"to",
"the",
"data",
"path",
"where",
"this",
"error",
"occurred",
".",
"E",
".",
"g",
".",
"if",
"the",
"dataPath",
"was",
"previously",
"foo",
".",
"goo",
"and",
"the",
"key",
"to",
"prepend",
"is",
"boo",
"then",
"the",
"ne... | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SoyDataException.java#L66-L72 | train |
google/closure-templates | java/src/com/google/template/soy/base/internal/Identifier.java | Identifier.type | @Memoized
public Type type() {
int dotIndex = identifier().indexOf('.');
if (dotIndex == 0) {
checkArgument(BaseUtils.isIdentifierWithLeadingDot(identifier()));
return Type.DOT_IDENT;
} else {
checkArgument(BaseUtils.isDottedIdentifier(identifier()));
return dotIndex == -1 ? Type.SINGLE_IDENT : Type.DOTTED_IDENT;
}
} | java | @Memoized
public Type type() {
int dotIndex = identifier().indexOf('.');
if (dotIndex == 0) {
checkArgument(BaseUtils.isIdentifierWithLeadingDot(identifier()));
return Type.DOT_IDENT;
} else {
checkArgument(BaseUtils.isDottedIdentifier(identifier()));
return dotIndex == -1 ? Type.SINGLE_IDENT : Type.DOTTED_IDENT;
}
} | [
"@",
"Memoized",
"public",
"Type",
"type",
"(",
")",
"{",
"int",
"dotIndex",
"=",
"identifier",
"(",
")",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"dotIndex",
"==",
"0",
")",
"{",
"checkArgument",
"(",
"BaseUtils",
".",
"isIdentifierWithLead... | This field is only rarely accessed, memoize it. | [
"This",
"field",
"is",
"only",
"rarely",
"accessed",
"memoize",
"it",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/internal/Identifier.java#L69-L79 | train |
google/closure-templates | java/src/com/google/template/soy/base/internal/Identifier.java | Identifier.extractPartAfterLastDot | public Identifier extractPartAfterLastDot() {
String part = BaseUtils.extractPartAfterLastDot(identifier());
return Identifier.create(
part, location().offsetStartCol(identifier().length() - part.length()));
} | java | public Identifier extractPartAfterLastDot() {
String part = BaseUtils.extractPartAfterLastDot(identifier());
return Identifier.create(
part, location().offsetStartCol(identifier().length() - part.length()));
} | [
"public",
"Identifier",
"extractPartAfterLastDot",
"(",
")",
"{",
"String",
"part",
"=",
"BaseUtils",
".",
"extractPartAfterLastDot",
"(",
"identifier",
"(",
")",
")",
";",
"return",
"Identifier",
".",
"create",
"(",
"part",
",",
"location",
"(",
")",
".",
"... | Gets the part after the last dot in a dotted identifier. If there are no dots, returns the
whole identifier.
<p><b>Important:</b> The input must be a dotted identifier. This is not checked. | [
"Gets",
"the",
"part",
"after",
"the",
"last",
"dot",
"in",
"a",
"dotted",
"identifier",
".",
"If",
"there",
"are",
"no",
"dots",
"returns",
"the",
"whole",
"identifier",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/internal/Identifier.java#L87-L91 | train |
google/closure-templates | java/src/com/google/template/soy/data/internalutils/InternalValueUtils.java | InternalValueUtils.convertPrimitiveDataToExpr | @Nullable
public static PrimitiveNode convertPrimitiveDataToExpr(
PrimitiveData primitiveData, SourceLocation location) {
if (primitiveData instanceof StringData) {
return new StringNode(primitiveData.stringValue(), QuoteStyle.SINGLE, location);
} else if (primitiveData instanceof BooleanData) {
return new BooleanNode(primitiveData.booleanValue(), location);
} else if (primitiveData instanceof IntegerData) {
// NOTE: We only support numbers in the range of JS [MIN_SAFE_INTEGER, MAX_SAFE_INTEGER]
if (!IntegerNode.isInRange(primitiveData.longValue())) {
return null;
} else {
return new IntegerNode(primitiveData.longValue(), location);
}
} else if (primitiveData instanceof FloatData) {
return new FloatNode(primitiveData.floatValue(), location);
} else if (primitiveData instanceof NullData) {
return new NullNode(location);
} else {
throw new IllegalArgumentException();
}
} | java | @Nullable
public static PrimitiveNode convertPrimitiveDataToExpr(
PrimitiveData primitiveData, SourceLocation location) {
if (primitiveData instanceof StringData) {
return new StringNode(primitiveData.stringValue(), QuoteStyle.SINGLE, location);
} else if (primitiveData instanceof BooleanData) {
return new BooleanNode(primitiveData.booleanValue(), location);
} else if (primitiveData instanceof IntegerData) {
// NOTE: We only support numbers in the range of JS [MIN_SAFE_INTEGER, MAX_SAFE_INTEGER]
if (!IntegerNode.isInRange(primitiveData.longValue())) {
return null;
} else {
return new IntegerNode(primitiveData.longValue(), location);
}
} else if (primitiveData instanceof FloatData) {
return new FloatNode(primitiveData.floatValue(), location);
} else if (primitiveData instanceof NullData) {
return new NullNode(location);
} else {
throw new IllegalArgumentException();
}
} | [
"@",
"Nullable",
"public",
"static",
"PrimitiveNode",
"convertPrimitiveDataToExpr",
"(",
"PrimitiveData",
"primitiveData",
",",
"SourceLocation",
"location",
")",
"{",
"if",
"(",
"primitiveData",
"instanceof",
"StringData",
")",
"{",
"return",
"new",
"StringNode",
"("... | Converts a primitive data object into a primitive expression node.
@param primitiveData The primitive data object to convert. Must not be undefined.
@param location The node's source location.
@return The resulting primitive expression node. | [
"Converts",
"a",
"primitive",
"data",
"object",
"into",
"a",
"primitive",
"expression",
"node",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/internalutils/InternalValueUtils.java#L57-L78 | train |
google/closure-templates | java/src/com/google/template/soy/data/internalutils/InternalValueUtils.java | InternalValueUtils.convertPrimitiveExprToData | public static PrimitiveData convertPrimitiveExprToData(PrimitiveNode primitiveNode) {
if (primitiveNode instanceof StringNode) {
return StringData.forValue(((StringNode) primitiveNode).getValue());
} else if (primitiveNode instanceof BooleanNode) {
return BooleanData.forValue(((BooleanNode) primitiveNode).getValue());
} else if (primitiveNode instanceof IntegerNode) {
return IntegerData.forValue(((IntegerNode) primitiveNode).getValue());
} else if (primitiveNode instanceof FloatNode) {
return FloatData.forValue(((FloatNode) primitiveNode).getValue());
} else if (primitiveNode instanceof NullNode) {
return NullData.INSTANCE;
} else {
throw new IllegalArgumentException();
}
} | java | public static PrimitiveData convertPrimitiveExprToData(PrimitiveNode primitiveNode) {
if (primitiveNode instanceof StringNode) {
return StringData.forValue(((StringNode) primitiveNode).getValue());
} else if (primitiveNode instanceof BooleanNode) {
return BooleanData.forValue(((BooleanNode) primitiveNode).getValue());
} else if (primitiveNode instanceof IntegerNode) {
return IntegerData.forValue(((IntegerNode) primitiveNode).getValue());
} else if (primitiveNode instanceof FloatNode) {
return FloatData.forValue(((FloatNode) primitiveNode).getValue());
} else if (primitiveNode instanceof NullNode) {
return NullData.INSTANCE;
} else {
throw new IllegalArgumentException();
}
} | [
"public",
"static",
"PrimitiveData",
"convertPrimitiveExprToData",
"(",
"PrimitiveNode",
"primitiveNode",
")",
"{",
"if",
"(",
"primitiveNode",
"instanceof",
"StringNode",
")",
"{",
"return",
"StringData",
".",
"forValue",
"(",
"(",
"(",
"StringNode",
")",
"primitiv... | Converts a primitive expression node into a primitive data object.
@param primitiveNode The primitive expression node to convert.
@return The resulting primitive data object. | [
"Converts",
"a",
"primitive",
"expression",
"node",
"into",
"a",
"primitive",
"data",
"object",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/internalutils/InternalValueUtils.java#L86-L101 | train |
google/closure-templates | java/src/com/google/template/soy/data/internalutils/InternalValueUtils.java | InternalValueUtils.convertCompileTimeGlobalsMap | public static ImmutableMap<String, PrimitiveData> convertCompileTimeGlobalsMap(
Map<String, ?> compileTimeGlobalsMap) {
ImmutableMap.Builder<String, PrimitiveData> resultMapBuilder = ImmutableMap.builder();
for (Map.Entry<String, ?> entry : compileTimeGlobalsMap.entrySet()) {
Object valueObj = entry.getValue();
PrimitiveData value;
boolean isValidValue = true;
try {
SoyValue value0 = SoyValueConverter.INSTANCE.convert(valueObj).resolve();
if (!(value0 instanceof PrimitiveData)) {
isValidValue = false;
}
value = (PrimitiveData) value0;
} catch (SoyDataException sde) {
isValidValue = false;
value = null; // make compiler happy
}
if (!isValidValue) {
throw new IllegalArgumentException(
"Compile-time globals map contains invalid value: "
+ valueObj
+ " for key: "
+ entry.getKey());
}
resultMapBuilder.put(entry.getKey(), value);
}
return resultMapBuilder.build();
} | java | public static ImmutableMap<String, PrimitiveData> convertCompileTimeGlobalsMap(
Map<String, ?> compileTimeGlobalsMap) {
ImmutableMap.Builder<String, PrimitiveData> resultMapBuilder = ImmutableMap.builder();
for (Map.Entry<String, ?> entry : compileTimeGlobalsMap.entrySet()) {
Object valueObj = entry.getValue();
PrimitiveData value;
boolean isValidValue = true;
try {
SoyValue value0 = SoyValueConverter.INSTANCE.convert(valueObj).resolve();
if (!(value0 instanceof PrimitiveData)) {
isValidValue = false;
}
value = (PrimitiveData) value0;
} catch (SoyDataException sde) {
isValidValue = false;
value = null; // make compiler happy
}
if (!isValidValue) {
throw new IllegalArgumentException(
"Compile-time globals map contains invalid value: "
+ valueObj
+ " for key: "
+ entry.getKey());
}
resultMapBuilder.put(entry.getKey(), value);
}
return resultMapBuilder.build();
} | [
"public",
"static",
"ImmutableMap",
"<",
"String",
",",
"PrimitiveData",
">",
"convertCompileTimeGlobalsMap",
"(",
"Map",
"<",
"String",
",",
"?",
">",
"compileTimeGlobalsMap",
")",
"{",
"ImmutableMap",
".",
"Builder",
"<",
"String",
",",
"PrimitiveData",
">",
"... | Converts a compile-time globals map in user-provided format into one in the internal format.
<p>The returned map will have the same iteration order as the provided map.
@param compileTimeGlobalsMap Map from compile-time global name to value. The values can be any
of the Soy primitive types: null, boolean, integer, float (Java double), or string.
@return An equivalent map in the internal format.
@throws IllegalArgumentException If the map contains an invalid value. | [
"Converts",
"a",
"compile",
"-",
"time",
"globals",
"map",
"in",
"user",
"-",
"provided",
"format",
"into",
"one",
"in",
"the",
"internal",
"format",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/internalutils/InternalValueUtils.java#L113-L145 | train |
google/closure-templates | java/src/com/google/template/soy/conformance/RuleWithWhitelists.java | RuleWithWhitelists.shouldCheckConformanceFor | boolean shouldCheckConformanceFor(String filePath) {
for (String whitelistedPath : getWhitelistedPaths()) {
if (filePath.contains(whitelistedPath)) {
return false;
}
}
ImmutableList<String> onlyApplyToPaths = getOnlyApplyToPaths();
if (onlyApplyToPaths.isEmpty()) {
return true;
}
// If only_apply_to field is presented in the configuration, check it.
for (String onlyApplyToPath : onlyApplyToPaths) {
if (filePath.contains(onlyApplyToPath)) {
return true;
}
}
return false;
} | java | boolean shouldCheckConformanceFor(String filePath) {
for (String whitelistedPath : getWhitelistedPaths()) {
if (filePath.contains(whitelistedPath)) {
return false;
}
}
ImmutableList<String> onlyApplyToPaths = getOnlyApplyToPaths();
if (onlyApplyToPaths.isEmpty()) {
return true;
}
// If only_apply_to field is presented in the configuration, check it.
for (String onlyApplyToPath : onlyApplyToPaths) {
if (filePath.contains(onlyApplyToPath)) {
return true;
}
}
return false;
} | [
"boolean",
"shouldCheckConformanceFor",
"(",
"String",
"filePath",
")",
"{",
"for",
"(",
"String",
"whitelistedPath",
":",
"getWhitelistedPaths",
"(",
")",
")",
"{",
"if",
"(",
"filePath",
".",
"contains",
"(",
"whitelistedPath",
")",
")",
"{",
"return",
"fals... | A file should be checked against a rule unless it contains one of the whitelisted paths. | [
"A",
"file",
"should",
"be",
"checked",
"against",
"a",
"rule",
"unless",
"it",
"contains",
"one",
"of",
"the",
"whitelisted",
"paths",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/conformance/RuleWithWhitelists.java#L44-L61 | train |
google/closure-templates | java/src/com/google/template/soy/passes/CheckNonEmptyMsgNodesPass.java | CheckNonEmptyMsgNodesPass.isEmpty | private static boolean isEmpty(MsgNode msg) {
for (SoyNode child : msg.getChildren()) {
if (child instanceof RawTextNode && ((RawTextNode) child).getRawText().isEmpty()) {
continue;
}
return false;
}
return true;
} | java | private static boolean isEmpty(MsgNode msg) {
for (SoyNode child : msg.getChildren()) {
if (child instanceof RawTextNode && ((RawTextNode) child).getRawText().isEmpty()) {
continue;
}
return false;
}
return true;
} | [
"private",
"static",
"boolean",
"isEmpty",
"(",
"MsgNode",
"msg",
")",
"{",
"for",
"(",
"SoyNode",
"child",
":",
"msg",
".",
"getChildren",
"(",
")",
")",
"{",
"if",
"(",
"child",
"instanceof",
"RawTextNode",
"&&",
"(",
"(",
"RawTextNode",
")",
"child",
... | If the only children are empty raw text nodes, then the node is empty.
<p>Empty raw text nodes are inserted by the parser to keep track of trimmed whitespace for the
html parser and removed later in the compiler. | [
"If",
"the",
"only",
"children",
"are",
"empty",
"raw",
"text",
"nodes",
"then",
"the",
"node",
"is",
"empty",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/CheckNonEmptyMsgNodesPass.java#L68-L76 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Inferences.java | Inferences.setEscapingDirectives | public void setEscapingDirectives(
SoyNode node, Context context, List<EscapingMode> escapingModes) {
Preconditions.checkArgument(
(node instanceof PrintNode)
|| (node instanceof CallNode)
|| (node instanceof MsgFallbackGroupNode),
"Escaping directives may only be set for {print}, {msg}, or {call} nodes");
if (escapingModes != null) {
nodeToEscapingModes.put(node, ImmutableList.copyOf(escapingModes));
}
nodeToContext.put(node, context);
} | java | public void setEscapingDirectives(
SoyNode node, Context context, List<EscapingMode> escapingModes) {
Preconditions.checkArgument(
(node instanceof PrintNode)
|| (node instanceof CallNode)
|| (node instanceof MsgFallbackGroupNode),
"Escaping directives may only be set for {print}, {msg}, or {call} nodes");
if (escapingModes != null) {
nodeToEscapingModes.put(node, ImmutableList.copyOf(escapingModes));
}
nodeToContext.put(node, context);
} | [
"public",
"void",
"setEscapingDirectives",
"(",
"SoyNode",
"node",
",",
"Context",
"context",
",",
"List",
"<",
"EscapingMode",
">",
"escapingModes",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"(",
"node",
"instanceof",
"PrintNode",
")",
"||",
"(",
... | Records inferred escaping modes so a directive can be later added to the Soy parse tree. | [
"Records",
"inferred",
"escaping",
"modes",
"so",
"a",
"directive",
"can",
"be",
"later",
"added",
"to",
"the",
"Soy",
"parse",
"tree",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Inferences.java#L100-L111 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/Inferences.java | Inferences.getEscapingModesForNode | public ImmutableList<EscapingMode> getEscapingModesForNode(SoyNode node) {
ImmutableList<EscapingMode> modes = nodeToEscapingModes.get(node);
if (modes == null) {
modes = ImmutableList.of();
}
return modes;
} | java | public ImmutableList<EscapingMode> getEscapingModesForNode(SoyNode node) {
ImmutableList<EscapingMode> modes = nodeToEscapingModes.get(node);
if (modes == null) {
modes = ImmutableList.of();
}
return modes;
} | [
"public",
"ImmutableList",
"<",
"EscapingMode",
">",
"getEscapingModesForNode",
"(",
"SoyNode",
"node",
")",
"{",
"ImmutableList",
"<",
"EscapingMode",
">",
"modes",
"=",
"nodeToEscapingModes",
".",
"get",
"(",
"node",
")",
";",
"if",
"(",
"modes",
"==",
"null... | The escaping modes for the print command with the given ID in the order in which they should be
applied.
@param node a node instance | [
"The",
"escaping",
"modes",
"for",
"the",
"print",
"command",
"with",
"the",
"given",
"ID",
"in",
"the",
"order",
"in",
"which",
"they",
"should",
"be",
"applied",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/Inferences.java#L119-L125 | train |
google/closure-templates | java/src/com/google/template/soy/xliffmsgplugin/XliffParser.java | XliffParser.parseXliffTargetMsgs | static SoyMsgBundle parseXliffTargetMsgs(String xliffContent) throws SAXException {
// Get a SAX parser.
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser;
try {
saxParser = saxParserFactory.newSAXParser();
} catch (ParserConfigurationException pce) {
throw new AssertionError("Could not get SAX parser for XML.");
}
// Construct the handler for SAX parsing.
XliffSaxHandler xliffSaxHandler = new XliffSaxHandler();
// Parse the XLIFF content.
try {
saxParser.parse(new InputSource(new StringReader(xliffContent)), xliffSaxHandler);
} catch (IOException e) {
throw new AssertionError("Should not fail in reading a string.");
}
// Build a SoyMsgBundle from the parsed data (stored in xliffSaxHandler).
return new SoyMsgBundleImpl(xliffSaxHandler.getTargetLocaleString(), xliffSaxHandler.getMsgs());
} | java | static SoyMsgBundle parseXliffTargetMsgs(String xliffContent) throws SAXException {
// Get a SAX parser.
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser;
try {
saxParser = saxParserFactory.newSAXParser();
} catch (ParserConfigurationException pce) {
throw new AssertionError("Could not get SAX parser for XML.");
}
// Construct the handler for SAX parsing.
XliffSaxHandler xliffSaxHandler = new XliffSaxHandler();
// Parse the XLIFF content.
try {
saxParser.parse(new InputSource(new StringReader(xliffContent)), xliffSaxHandler);
} catch (IOException e) {
throw new AssertionError("Should not fail in reading a string.");
}
// Build a SoyMsgBundle from the parsed data (stored in xliffSaxHandler).
return new SoyMsgBundleImpl(xliffSaxHandler.getTargetLocaleString(), xliffSaxHandler.getMsgs());
} | [
"static",
"SoyMsgBundle",
"parseXliffTargetMsgs",
"(",
"String",
"xliffContent",
")",
"throws",
"SAXException",
"{",
"// Get a SAX parser.",
"SAXParserFactory",
"saxParserFactory",
"=",
"SAXParserFactory",
".",
"newInstance",
"(",
")",
";",
"SAXParser",
"saxParser",
";",
... | Parses the content of a translated XLIFF file and creates a SoyMsgBundle.
@param xliffContent The XLIFF content to parse.
@return The resulting SoyMsgBundle.
@throws SAXException If there's an error parsing the data.
@throws SoyMsgException If there's an error in parsing the data. | [
"Parses",
"the",
"content",
"of",
"a",
"translated",
"XLIFF",
"file",
"and",
"creates",
"a",
"SoyMsgBundle",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/xliffmsgplugin/XliffParser.java#L56-L79 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/SoyNodeCompiler.java | SoyNodeCompiler.create | static SoyNodeCompiler create(
CompiledTemplateRegistry registry,
InnerClasses innerClasses,
FieldRef stateField,
Expression thisVar,
AppendableExpression appendableVar,
TemplateVariableManager variables,
TemplateParameterLookup parameterLookup,
ErrorReporter reporter,
SoyTypeRegistry typeRegistry) {
DetachState detachState = new DetachState(variables, thisVar, stateField);
ExpressionCompiler expressionCompiler =
ExpressionCompiler.create(detachState, parameterLookup, variables, reporter, typeRegistry);
ExpressionToSoyValueProviderCompiler soyValueProviderCompiler =
ExpressionToSoyValueProviderCompiler.create(variables, expressionCompiler, parameterLookup);
return new SoyNodeCompiler(
thisVar,
registry,
detachState,
variables,
parameterLookup,
appendableVar,
expressionCompiler,
soyValueProviderCompiler,
new LazyClosureCompiler(
registry,
innerClasses,
parameterLookup,
variables,
soyValueProviderCompiler,
reporter,
typeRegistry));
} | java | static SoyNodeCompiler create(
CompiledTemplateRegistry registry,
InnerClasses innerClasses,
FieldRef stateField,
Expression thisVar,
AppendableExpression appendableVar,
TemplateVariableManager variables,
TemplateParameterLookup parameterLookup,
ErrorReporter reporter,
SoyTypeRegistry typeRegistry) {
DetachState detachState = new DetachState(variables, thisVar, stateField);
ExpressionCompiler expressionCompiler =
ExpressionCompiler.create(detachState, parameterLookup, variables, reporter, typeRegistry);
ExpressionToSoyValueProviderCompiler soyValueProviderCompiler =
ExpressionToSoyValueProviderCompiler.create(variables, expressionCompiler, parameterLookup);
return new SoyNodeCompiler(
thisVar,
registry,
detachState,
variables,
parameterLookup,
appendableVar,
expressionCompiler,
soyValueProviderCompiler,
new LazyClosureCompiler(
registry,
innerClasses,
parameterLookup,
variables,
soyValueProviderCompiler,
reporter,
typeRegistry));
} | [
"static",
"SoyNodeCompiler",
"create",
"(",
"CompiledTemplateRegistry",
"registry",
",",
"InnerClasses",
"innerClasses",
",",
"FieldRef",
"stateField",
",",
"Expression",
"thisVar",
",",
"AppendableExpression",
"appendableVar",
",",
"TemplateVariableManager",
"variables",
"... | Creates a SoyNodeCompiler
@param innerClasses The current set of inner classes
@param stateField The field on the current class that holds the state variable
@param thisVar An expression that returns 'this'
@param appendableVar An expression that returns the current AdvisingAppendable that we are
rendering into
@param variables The variable set for generating locals and fields
@param parameterLookup The variable lookup table for reading locals. | [
"Creates",
"a",
"SoyNodeCompiler"
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/SoyNodeCompiler.java#L136-L168 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/SoyNodeCompiler.java | SoyNodeCompiler.computeRangeValue | private Expression computeRangeValue(
SyntheticVarName varName,
Optional<ExprNode> expression,
int defaultValue,
Scope scope,
final ImmutableList.Builder<Statement> initStatements) {
if (!expression.isPresent()) {
return constant(defaultValue);
} else if (expression.get() instanceof IntegerNode
&& ((IntegerNode) expression.get()).isInt()) {
int value = Ints.checkedCast(((IntegerNode) expression.get()).getValue());
return constant(value);
} else {
Label startDetachPoint = new Label();
// Note: If the value of rangeArgs.start() is above 32 bits, Ints.checkedCast() will fail at
// runtime with IllegalArgumentException.
Expression startExpression =
MethodRef.INTS_CHECKED_CAST.invoke(
exprCompiler.compile(expression.get(), startDetachPoint).unboxAsLong());
if (!startExpression.isCheap()) {
// bounce it into a local variable
Variable startVar = scope.createSynthetic(varName, startExpression, STORE);
initStatements.add(startVar.initializer().labelStart(startDetachPoint));
startExpression = startVar.local();
}
return startExpression;
}
} | java | private Expression computeRangeValue(
SyntheticVarName varName,
Optional<ExprNode> expression,
int defaultValue,
Scope scope,
final ImmutableList.Builder<Statement> initStatements) {
if (!expression.isPresent()) {
return constant(defaultValue);
} else if (expression.get() instanceof IntegerNode
&& ((IntegerNode) expression.get()).isInt()) {
int value = Ints.checkedCast(((IntegerNode) expression.get()).getValue());
return constant(value);
} else {
Label startDetachPoint = new Label();
// Note: If the value of rangeArgs.start() is above 32 bits, Ints.checkedCast() will fail at
// runtime with IllegalArgumentException.
Expression startExpression =
MethodRef.INTS_CHECKED_CAST.invoke(
exprCompiler.compile(expression.get(), startDetachPoint).unboxAsLong());
if (!startExpression.isCheap()) {
// bounce it into a local variable
Variable startVar = scope.createSynthetic(varName, startExpression, STORE);
initStatements.add(startVar.initializer().labelStart(startDetachPoint));
startExpression = startVar.local();
}
return startExpression;
}
} | [
"private",
"Expression",
"computeRangeValue",
"(",
"SyntheticVarName",
"varName",
",",
"Optional",
"<",
"ExprNode",
">",
"expression",
",",
"int",
"defaultValue",
",",
"Scope",
"scope",
",",
"final",
"ImmutableList",
".",
"Builder",
"<",
"Statement",
">",
"initSta... | Computes a single range argument.
@param varName The variable name to use if this value should be stored in a local
@param expression The expression
@param defaultValue The value to use if there is no expression
@param scope The current variable scope to add variables to
@param initStatements Initializing statements, if any. | [
"Computes",
"a",
"single",
"range",
"argument",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/SoyNodeCompiler.java#L497-L524 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/SoyNodeCompiler.java | SoyNodeCompiler.shouldCheckBuffer | private static boolean shouldCheckBuffer(PrintNode node) {
if (!(node.getExpr().getRoot() instanceof FunctionNode)) {
return true;
}
FunctionNode fn = (FunctionNode) node.getExpr().getRoot();
if (!(fn.getSoyFunction() instanceof BuiltinFunction)) {
return true;
}
BuiltinFunction bfn = (BuiltinFunction) fn.getSoyFunction();
if (bfn != BuiltinFunction.XID && bfn != BuiltinFunction.CSS) {
return true;
}
return false;
} | java | private static boolean shouldCheckBuffer(PrintNode node) {
if (!(node.getExpr().getRoot() instanceof FunctionNode)) {
return true;
}
FunctionNode fn = (FunctionNode) node.getExpr().getRoot();
if (!(fn.getSoyFunction() instanceof BuiltinFunction)) {
return true;
}
BuiltinFunction bfn = (BuiltinFunction) fn.getSoyFunction();
if (bfn != BuiltinFunction.XID && bfn != BuiltinFunction.CSS) {
return true;
}
return false;
} | [
"private",
"static",
"boolean",
"shouldCheckBuffer",
"(",
"PrintNode",
"node",
")",
"{",
"if",
"(",
"!",
"(",
"node",
".",
"getExpr",
"(",
")",
".",
"getRoot",
"(",
")",
"instanceof",
"FunctionNode",
")",
")",
"{",
"return",
"true",
";",
"}",
"FunctionNo... | Returns true if the print expression should check the rendering buffer and generate a detach.
<p>We do not generate detaches for css() and xid() builtin functions, since they are typically
very short. | [
"Returns",
"true",
"if",
"the",
"print",
"expression",
"should",
"check",
"the",
"rendering",
"buffer",
"and",
"generate",
"a",
"detach",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/SoyNodeCompiler.java#L712-L728 | train |
google/closure-templates | java/src/com/google/template/soy/passes/VeLogValidationPass.java | VeLogValidationPass.validateVeLogNode | private void validateVeLogNode(VeLogNode node) {
if (node.getVeDataExpression().getRoot().getType().getKind() != Kind.VE_DATA) {
reporter.report(
node.getVeDataExpression().getSourceLocation(),
INVALID_VE,
node.getVeDataExpression().getRoot().getType());
}
if (node.getLogonlyExpression() != null) {
// check to see if it is in a msg node. logonly is disallowed in msg nodes because we don't
// have an implementation strategy.
if (isInMsgNode(node)) {
reporter.report(node.getLogonlyExpression().getSourceLocation(), LOGONLY_DISALLOWED_IN_MSG);
}
SoyType type = node.getLogonlyExpression().getType();
if (type.getKind() != Kind.BOOL) {
reporter.report(
node.getLogonlyExpression().getSourceLocation(),
WRONG_TYPE,
BoolType.getInstance(),
type);
}
}
} | java | private void validateVeLogNode(VeLogNode node) {
if (node.getVeDataExpression().getRoot().getType().getKind() != Kind.VE_DATA) {
reporter.report(
node.getVeDataExpression().getSourceLocation(),
INVALID_VE,
node.getVeDataExpression().getRoot().getType());
}
if (node.getLogonlyExpression() != null) {
// check to see if it is in a msg node. logonly is disallowed in msg nodes because we don't
// have an implementation strategy.
if (isInMsgNode(node)) {
reporter.report(node.getLogonlyExpression().getSourceLocation(), LOGONLY_DISALLOWED_IN_MSG);
}
SoyType type = node.getLogonlyExpression().getType();
if (type.getKind() != Kind.BOOL) {
reporter.report(
node.getLogonlyExpression().getSourceLocation(),
WRONG_TYPE,
BoolType.getInstance(),
type);
}
}
} | [
"private",
"void",
"validateVeLogNode",
"(",
"VeLogNode",
"node",
")",
"{",
"if",
"(",
"node",
".",
"getVeDataExpression",
"(",
")",
".",
"getRoot",
"(",
")",
".",
"getType",
"(",
")",
".",
"getKind",
"(",
")",
"!=",
"Kind",
".",
"VE_DATA",
")",
"{",
... | Type checks the VE and logonly expressions. | [
"Type",
"checks",
"the",
"VE",
"and",
"logonly",
"expressions",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/VeLogValidationPass.java#L183-L205 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/JsSrcNameGenerators.java | JsSrcNameGenerators.forLocalVariables | public static UniqueNameGenerator forLocalVariables() {
UniqueNameGenerator generator = new UniqueNameGenerator(DANGEROUS_CHARACTERS, "$$");
generator.reserve(JsSrcUtils.JS_LITERALS);
generator.reserve(JsSrcUtils.JS_RESERVED_WORDS);
return generator;
} | java | public static UniqueNameGenerator forLocalVariables() {
UniqueNameGenerator generator = new UniqueNameGenerator(DANGEROUS_CHARACTERS, "$$");
generator.reserve(JsSrcUtils.JS_LITERALS);
generator.reserve(JsSrcUtils.JS_RESERVED_WORDS);
return generator;
} | [
"public",
"static",
"UniqueNameGenerator",
"forLocalVariables",
"(",
")",
"{",
"UniqueNameGenerator",
"generator",
"=",
"new",
"UniqueNameGenerator",
"(",
"DANGEROUS_CHARACTERS",
",",
"\"$$\"",
")",
";",
"generator",
".",
"reserve",
"(",
"JsSrcUtils",
".",
"JS_LITERAL... | Returns a name generator suitable for generating local variable names. | [
"Returns",
"a",
"name",
"generator",
"suitable",
"for",
"generating",
"local",
"variable",
"names",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsSrcNameGenerators.java#L34-L39 | train |
google/closure-templates | java/src/com/google/template/soy/shared/SoyAstCache.java | SoyAstCache.put | public synchronized void put(String fileName, VersionedFile versionedFile) {
cache.put(fileName, versionedFile.copy());
} | java | public synchronized void put(String fileName, VersionedFile versionedFile) {
cache.put(fileName, versionedFile.copy());
} | [
"public",
"synchronized",
"void",
"put",
"(",
"String",
"fileName",
",",
"VersionedFile",
"versionedFile",
")",
"{",
"cache",
".",
"put",
"(",
"fileName",
",",
"versionedFile",
".",
"copy",
"(",
")",
")",
";",
"}"
] | Stores a cached version of the AST.
<p>Please treat this as superpackage-private for Soy internals.
@param fileName The name of the file.
@param versionedFile The compiled AST at the particular version. The node is defensively
copied; the caller is free to modify it. | [
"Stores",
"a",
"cached",
"version",
"of",
"the",
"AST",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/SoyAstCache.java#L80-L82 | train |
google/closure-templates | java/src/com/google/template/soy/shared/SoyAstCache.java | SoyAstCache.get | public synchronized VersionedFile get(String fileName, Version version) {
VersionedFile entry = cache.get(fileName);
if (entry != null) {
if (entry.version().equals(version)) {
// Make a defensive copy since the caller might run further passes on it.
return entry.copy();
} else {
// Aggressively purge to save memory.
cache.remove(fileName);
}
}
return null;
} | java | public synchronized VersionedFile get(String fileName, Version version) {
VersionedFile entry = cache.get(fileName);
if (entry != null) {
if (entry.version().equals(version)) {
// Make a defensive copy since the caller might run further passes on it.
return entry.copy();
} else {
// Aggressively purge to save memory.
cache.remove(fileName);
}
}
return null;
} | [
"public",
"synchronized",
"VersionedFile",
"get",
"(",
"String",
"fileName",
",",
"Version",
"version",
")",
"{",
"VersionedFile",
"entry",
"=",
"cache",
".",
"get",
"(",
"fileName",
")",
";",
"if",
"(",
"entry",
"!=",
"null",
")",
"{",
"if",
"(",
"entry... | Retrieves a cached version of this file supplier AST, if any.
<p>Please treat this as superpackage-private for Soy internals.
@param fileName The name of the file
@param version The current file version.
@return A fresh copy of the tree that may be modified by the caller, or null if no entry was
found in the cache. | [
"Retrieves",
"a",
"cached",
"version",
"of",
"this",
"file",
"supplier",
"AST",
"if",
"any",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/SoyAstCache.java#L94-L106 | train |
google/closure-templates | java/src/com/google/template/soy/internal/proto/ProtoUtils.java | ProtoUtils.isSanitizedContentField | public static boolean isSanitizedContentField(FieldDescriptor fieldDescriptor) {
return fieldDescriptor.getType() == Type.MESSAGE
&& SAFE_PROTO_TYPES.contains(fieldDescriptor.getMessageType().getFullName());
} | java | public static boolean isSanitizedContentField(FieldDescriptor fieldDescriptor) {
return fieldDescriptor.getType() == Type.MESSAGE
&& SAFE_PROTO_TYPES.contains(fieldDescriptor.getMessageType().getFullName());
} | [
"public",
"static",
"boolean",
"isSanitizedContentField",
"(",
"FieldDescriptor",
"fieldDescriptor",
")",
"{",
"return",
"fieldDescriptor",
".",
"getType",
"(",
")",
"==",
"Type",
".",
"MESSAGE",
"&&",
"SAFE_PROTO_TYPES",
".",
"contains",
"(",
"fieldDescriptor",
"."... | Returns true if fieldDescriptor holds a sanitized proto type. | [
"Returns",
"true",
"if",
"fieldDescriptor",
"holds",
"a",
"sanitized",
"proto",
"type",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/ProtoUtils.java#L66-L69 | train |
google/closure-templates | java/src/com/google/template/soy/internal/proto/ProtoUtils.java | ProtoUtils.isSanitizedContentMap | public static boolean isSanitizedContentMap(FieldDescriptor fieldDescriptor) {
if (!fieldDescriptor.isMapField()) {
return false;
}
Descriptor valueDesc = getMapValueMessageType(fieldDescriptor);
if (valueDesc == null) {
return false;
}
return SAFE_PROTO_TYPES.contains(valueDesc.getFullName());
} | java | public static boolean isSanitizedContentMap(FieldDescriptor fieldDescriptor) {
if (!fieldDescriptor.isMapField()) {
return false;
}
Descriptor valueDesc = getMapValueMessageType(fieldDescriptor);
if (valueDesc == null) {
return false;
}
return SAFE_PROTO_TYPES.contains(valueDesc.getFullName());
} | [
"public",
"static",
"boolean",
"isSanitizedContentMap",
"(",
"FieldDescriptor",
"fieldDescriptor",
")",
"{",
"if",
"(",
"!",
"fieldDescriptor",
".",
"isMapField",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"Descriptor",
"valueDesc",
"=",
"getMapValueMessageT... | Returns true if fieldDescriptor holds a map where the values are a sanitized proto type. | [
"Returns",
"true",
"if",
"fieldDescriptor",
"holds",
"a",
"map",
"where",
"the",
"values",
"are",
"a",
"sanitized",
"proto",
"type",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/ProtoUtils.java#L72-L81 | train |
google/closure-templates | java/src/com/google/template/soy/internal/proto/ProtoUtils.java | ProtoUtils.getMapValueMessageType | @Nullable
public static Descriptor getMapValueMessageType(FieldDescriptor mapField) {
FieldDescriptor valueDesc = mapField.getMessageType().findFieldByName("value");
if (valueDesc.getType() == FieldDescriptor.Type.MESSAGE) {
return valueDesc.getMessageType();
} else {
return null;
}
} | java | @Nullable
public static Descriptor getMapValueMessageType(FieldDescriptor mapField) {
FieldDescriptor valueDesc = mapField.getMessageType().findFieldByName("value");
if (valueDesc.getType() == FieldDescriptor.Type.MESSAGE) {
return valueDesc.getMessageType();
} else {
return null;
}
} | [
"@",
"Nullable",
"public",
"static",
"Descriptor",
"getMapValueMessageType",
"(",
"FieldDescriptor",
"mapField",
")",
"{",
"FieldDescriptor",
"valueDesc",
"=",
"mapField",
".",
"getMessageType",
"(",
")",
".",
"findFieldByName",
"(",
"\"value\"",
")",
";",
"if",
"... | Returns the descriptor representing the type of the value of the map field. Returns null if the
map value isn't a message. | [
"Returns",
"the",
"descriptor",
"representing",
"the",
"type",
"of",
"the",
"value",
"of",
"the",
"map",
"field",
".",
"Returns",
"null",
"if",
"the",
"map",
"value",
"isn",
"t",
"a",
"message",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/ProtoUtils.java#L87-L95 | train |
google/closure-templates | java/src/com/google/template/soy/internal/proto/ProtoUtils.java | ProtoUtils.getJsExtensionImport | public static String getJsExtensionImport(FieldDescriptor desc) {
Descriptor scope = desc.getExtensionScope();
if (scope != null) {
while (scope.getContainingType() != null) {
scope = scope.getContainingType();
}
return calculateQualifiedJsName(scope);
}
return getJsPackage(desc.getFile()) + "." + computeJsExtensionName(desc);
} | java | public static String getJsExtensionImport(FieldDescriptor desc) {
Descriptor scope = desc.getExtensionScope();
if (scope != null) {
while (scope.getContainingType() != null) {
scope = scope.getContainingType();
}
return calculateQualifiedJsName(scope);
}
return getJsPackage(desc.getFile()) + "." + computeJsExtensionName(desc);
} | [
"public",
"static",
"String",
"getJsExtensionImport",
"(",
"FieldDescriptor",
"desc",
")",
"{",
"Descriptor",
"scope",
"=",
"desc",
".",
"getExtensionScope",
"(",
")",
";",
"if",
"(",
"scope",
"!=",
"null",
")",
"{",
"while",
"(",
"scope",
".",
"getContainin... | Returns the JS name of the import for the given extension, suitable for goog.require. | [
"Returns",
"the",
"JS",
"name",
"of",
"the",
"import",
"for",
"the",
"given",
"extension",
"suitable",
"for",
"goog",
".",
"require",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/ProtoUtils.java#L118-L127 | train |
google/closure-templates | java/src/com/google/template/soy/internal/proto/ProtoUtils.java | ProtoUtils.computeJsExtensionName | private static String computeJsExtensionName(FieldDescriptor field) {
String name = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field.getName());
return field.isRepeated() ? name + "List" : name;
} | java | private static String computeJsExtensionName(FieldDescriptor field) {
String name = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field.getName());
return field.isRepeated() ? name + "List" : name;
} | [
"private",
"static",
"String",
"computeJsExtensionName",
"(",
"FieldDescriptor",
"field",
")",
"{",
"String",
"name",
"=",
"CaseFormat",
".",
"LOWER_UNDERSCORE",
".",
"to",
"(",
"CaseFormat",
".",
"LOWER_CAMEL",
",",
"field",
".",
"getName",
"(",
")",
")",
";"... | Performs camelcase translation. | [
"Performs",
"camelcase",
"translation",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/ProtoUtils.java#L139-L142 | train |
google/closure-templates | java/src/com/google/template/soy/internal/proto/ProtoUtils.java | ProtoUtils.getJsPackage | private static String getJsPackage(FileDescriptor file) {
String protoPackage = file.getPackage();
if (!protoPackage.isEmpty()) {
return "proto." + protoPackage;
}
return "proto";
} | java | private static String getJsPackage(FileDescriptor file) {
String protoPackage = file.getPackage();
if (!protoPackage.isEmpty()) {
return "proto." + protoPackage;
}
return "proto";
} | [
"private",
"static",
"String",
"getJsPackage",
"(",
"FileDescriptor",
"file",
")",
"{",
"String",
"protoPackage",
"=",
"file",
".",
"getPackage",
"(",
")",
";",
"if",
"(",
"!",
"protoPackage",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"\"proto.\"",
"+"... | Returns the expected javascript package for protos based on the .proto file. | [
"Returns",
"the",
"expected",
"javascript",
"package",
"for",
"protos",
"based",
"on",
"the",
".",
"proto",
"file",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/ProtoUtils.java#L145-L151 | train |
google/closure-templates | java/src/com/google/template/soy/internal/proto/ProtoUtils.java | ProtoUtils.hasJsType | public static boolean hasJsType(FieldDescriptor fieldDescriptor) {
if (!JS_TYPEABLE_FIELDS.contains(fieldDescriptor.getType())) {
return false;
}
if (fieldDescriptor.getOptions().hasJstype()) {
return true;
}
return false;
} | java | public static boolean hasJsType(FieldDescriptor fieldDescriptor) {
if (!JS_TYPEABLE_FIELDS.contains(fieldDescriptor.getType())) {
return false;
}
if (fieldDescriptor.getOptions().hasJstype()) {
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"hasJsType",
"(",
"FieldDescriptor",
"fieldDescriptor",
")",
"{",
"if",
"(",
"!",
"JS_TYPEABLE_FIELDS",
".",
"contains",
"(",
"fieldDescriptor",
".",
"getType",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
... | Returns true if this field has a valid jstype annotation. | [
"Returns",
"true",
"if",
"this",
"field",
"has",
"a",
"valid",
"jstype",
"annotation",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/ProtoUtils.java#L162-L170 | train |
google/closure-templates | java/src/com/google/template/soy/internal/proto/ProtoUtils.java | ProtoUtils.isUnsigned | public static boolean isUnsigned(FieldDescriptor descriptor) {
switch (descriptor.getType()) {
case FIXED32:
case FIXED64:
case UINT32:
case UINT64:
return true;
default:
return false;
}
} | java | public static boolean isUnsigned(FieldDescriptor descriptor) {
switch (descriptor.getType()) {
case FIXED32:
case FIXED64:
case UINT32:
case UINT64:
return true;
default:
return false;
}
} | [
"public",
"static",
"boolean",
"isUnsigned",
"(",
"FieldDescriptor",
"descriptor",
")",
"{",
"switch",
"(",
"descriptor",
".",
"getType",
"(",
")",
")",
"{",
"case",
"FIXED32",
":",
"case",
"FIXED64",
":",
"case",
"UINT32",
":",
"case",
"UINT64",
":",
"ret... | Returns true if this field is an unsigned integer. | [
"Returns",
"true",
"if",
"this",
"field",
"is",
"an",
"unsigned",
"integer",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/ProtoUtils.java#L173-L183 | train |
google/closure-templates | java/src/com/google/template/soy/internal/proto/ProtoUtils.java | ProtoUtils.shouldCheckFieldPresenceToEmulateJspbNullability | static boolean shouldCheckFieldPresenceToEmulateJspbNullability(FieldDescriptor desc) {
boolean hasBrokenSemantics = false;
if (desc.hasDefaultValue() || desc.isRepeated()) {
return false;
} else if (desc.getFile().getSyntax() == Syntax.PROTO3 || !hasBrokenSemantics) {
// in proto3 or proto2 with non-broken semantics we only need to check for presence for
// message typed fields.
return desc.getJavaType() == JavaType.MESSAGE;
} else {
return true;
}
} | java | static boolean shouldCheckFieldPresenceToEmulateJspbNullability(FieldDescriptor desc) {
boolean hasBrokenSemantics = false;
if (desc.hasDefaultValue() || desc.isRepeated()) {
return false;
} else if (desc.getFile().getSyntax() == Syntax.PROTO3 || !hasBrokenSemantics) {
// in proto3 or proto2 with non-broken semantics we only need to check for presence for
// message typed fields.
return desc.getJavaType() == JavaType.MESSAGE;
} else {
return true;
}
} | [
"static",
"boolean",
"shouldCheckFieldPresenceToEmulateJspbNullability",
"(",
"FieldDescriptor",
"desc",
")",
"{",
"boolean",
"hasBrokenSemantics",
"=",
"false",
";",
"if",
"(",
"desc",
".",
"hasDefaultValue",
"(",
")",
"||",
"desc",
".",
"isRepeated",
"(",
")",
"... | Returns whether or not we should check for presence to emulate jspb nullability semantics in
server side soy. | [
"Returns",
"whether",
"or",
"not",
"we",
"should",
"check",
"for",
"presence",
"to",
"emulate",
"jspb",
"nullability",
"semantics",
"in",
"server",
"side",
"soy",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/ProtoUtils.java#L217-L228 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/MsgPlaceholderNode.java | MsgPlaceholderNode.shouldUseSameVarNameAs | @Override
public boolean shouldUseSameVarNameAs(MsgSubstUnitNode other) {
return (other instanceof MsgPlaceholderNode)
&& this.initialNodeKind == ((MsgPlaceholderNode) other).initialNodeKind
&& this.samenessKey.equals(((MsgPlaceholderNode) other).samenessKey);
} | java | @Override
public boolean shouldUseSameVarNameAs(MsgSubstUnitNode other) {
return (other instanceof MsgPlaceholderNode)
&& this.initialNodeKind == ((MsgPlaceholderNode) other).initialNodeKind
&& this.samenessKey.equals(((MsgPlaceholderNode) other).samenessKey);
} | [
"@",
"Override",
"public",
"boolean",
"shouldUseSameVarNameAs",
"(",
"MsgSubstUnitNode",
"other",
")",
"{",
"return",
"(",
"other",
"instanceof",
"MsgPlaceholderNode",
")",
"&&",
"this",
".",
"initialNodeKind",
"==",
"(",
"(",
"MsgPlaceholderNode",
")",
"other",
"... | Returns whether this node and the given other node are the same, such that they should be
represented by the same placeholder. | [
"Returns",
"whether",
"this",
"node",
"and",
"the",
"given",
"other",
"node",
"are",
"the",
"same",
"such",
"that",
"they",
"should",
"be",
"represented",
"by",
"the",
"same",
"placeholder",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/MsgPlaceholderNode.java#L99-L104 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/internal/IcuSyntaxUtils.java | IcuSyntaxUtils.icuEscape | @VisibleForTesting
static String icuEscape(String rawText) {
Matcher matcher = ICU_SYNTAX_CHAR_NEEDING_ESCAPE_PATTERN.matcher(rawText);
if (!matcher.find()) {
return rawText;
}
StringBuffer escapedTextSb = new StringBuffer();
do {
String repl = ICU_SYNTAX_CHAR_ESCAPE_MAP.get(matcher.group());
matcher.appendReplacement(escapedTextSb, repl);
} while (matcher.find());
matcher.appendTail(escapedTextSb);
return escapedTextSb.toString();
} | java | @VisibleForTesting
static String icuEscape(String rawText) {
Matcher matcher = ICU_SYNTAX_CHAR_NEEDING_ESCAPE_PATTERN.matcher(rawText);
if (!matcher.find()) {
return rawText;
}
StringBuffer escapedTextSb = new StringBuffer();
do {
String repl = ICU_SYNTAX_CHAR_ESCAPE_MAP.get(matcher.group());
matcher.appendReplacement(escapedTextSb, repl);
} while (matcher.find());
matcher.appendTail(escapedTextSb);
return escapedTextSb.toString();
} | [
"@",
"VisibleForTesting",
"static",
"String",
"icuEscape",
"(",
"String",
"rawText",
")",
"{",
"Matcher",
"matcher",
"=",
"ICU_SYNTAX_CHAR_NEEDING_ESCAPE_PATTERN",
".",
"matcher",
"(",
"rawText",
")",
";",
"if",
"(",
"!",
"matcher",
".",
"find",
"(",
")",
")",... | Escapes ICU syntax characters in raw text.
@param rawText The raw text to escaped.
@return The escaped raw text. If the given raw text doesn't need escaping, then the same string
object is returned. | [
"Escapes",
"ICU",
"syntax",
"characters",
"in",
"raw",
"text",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/internal/IcuSyntaxUtils.java#L240-L255 | train |
google/closure-templates | java/src/com/google/template/soy/msgs/restricted/RenderOnlySoyMsgBundleImpl.java | RenderOnlySoyMsgBundleImpl.resurrectMsg | @SuppressWarnings("unchecked") // The constructor guarantees the type of ImmutableList.
private SoyMsg resurrectMsg(long id, ImmutableList<SoyMsgPart> parts) {
return SoyMsg.builder()
.setId(id)
.setLocaleString(localeString)
.setIsPlrselMsg(MsgPartUtils.hasPlrselPart(parts))
.setParts(parts)
.build();
} | java | @SuppressWarnings("unchecked") // The constructor guarantees the type of ImmutableList.
private SoyMsg resurrectMsg(long id, ImmutableList<SoyMsgPart> parts) {
return SoyMsg.builder()
.setId(id)
.setLocaleString(localeString)
.setIsPlrselMsg(MsgPartUtils.hasPlrselPart(parts))
.setParts(parts)
.build();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"// The constructor guarantees the type of ImmutableList.",
"private",
"SoyMsg",
"resurrectMsg",
"(",
"long",
"id",
",",
"ImmutableList",
"<",
"SoyMsgPart",
">",
"parts",
")",
"{",
"return",
"SoyMsg",
".",
"builder",
... | Brings a message back to life from only its ID and parts. | [
"Brings",
"a",
"message",
"back",
"to",
"life",
"from",
"only",
"its",
"ID",
"and",
"parts",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/restricted/RenderOnlySoyMsgBundleImpl.java#L103-L111 | train |
google/closure-templates | java/src/com/google/template/soy/exprtree/VarRefNode.java | VarRefNode.isPossibleHeaderVar | public Boolean isPossibleHeaderVar() {
if (defn == null) {
throw new NullPointerException(getSourceLocation().toString());
}
return defn.kind() == VarDefn.Kind.PARAM
|| defn.kind() == VarDefn.Kind.STATE
|| defn.kind() == VarDefn.Kind.UNDECLARED;
} | java | public Boolean isPossibleHeaderVar() {
if (defn == null) {
throw new NullPointerException(getSourceLocation().toString());
}
return defn.kind() == VarDefn.Kind.PARAM
|| defn.kind() == VarDefn.Kind.STATE
|| defn.kind() == VarDefn.Kind.UNDECLARED;
} | [
"public",
"Boolean",
"isPossibleHeaderVar",
"(",
")",
"{",
"if",
"(",
"defn",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"getSourceLocation",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"defn",
".",
"kind",
"("... | Returns whether this might be header variable reference. A header variable is declared in Soy
with the @param or @state annotation. | [
"Returns",
"whether",
"this",
"might",
"be",
"header",
"variable",
"reference",
".",
"A",
"header",
"variable",
"is",
"declared",
"in",
"Soy",
"with",
"the"
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/exprtree/VarRefNode.java#L121-L128 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/AbstractParentCommandNode.java | AbstractParentCommandNode.firstChildThatMatches | @Nullable
public SoyNode firstChildThatMatches(Predicate<SoyNode> condition) {
int firstChildIndex = 0;
while (firstChildIndex < numChildren() && !condition.test(getChild(firstChildIndex))) {
firstChildIndex++;
}
if (firstChildIndex < numChildren()) {
return getChild(firstChildIndex);
}
return null;
} | java | @Nullable
public SoyNode firstChildThatMatches(Predicate<SoyNode> condition) {
int firstChildIndex = 0;
while (firstChildIndex < numChildren() && !condition.test(getChild(firstChildIndex))) {
firstChildIndex++;
}
if (firstChildIndex < numChildren()) {
return getChild(firstChildIndex);
}
return null;
} | [
"@",
"Nullable",
"public",
"SoyNode",
"firstChildThatMatches",
"(",
"Predicate",
"<",
"SoyNode",
">",
"condition",
")",
"{",
"int",
"firstChildIndex",
"=",
"0",
";",
"while",
"(",
"firstChildIndex",
"<",
"numChildren",
"(",
")",
"&&",
"!",
"condition",
".",
... | Returns the template's first child node that matches the given condition. | [
"Returns",
"the",
"template",
"s",
"first",
"child",
"node",
"that",
"matches",
"the",
"given",
"condition",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/AbstractParentCommandNode.java#L140-L150 | train |
google/closure-templates | java/src/com/google/template/soy/soytree/AbstractParentCommandNode.java | AbstractParentCommandNode.lastChildThatMatches | @Nullable
public SoyNode lastChildThatMatches(Predicate<SoyNode> condition) {
int lastChildIndex = numChildren() - 1;
while (lastChildIndex >= 0 && !condition.test(getChild(lastChildIndex))) {
lastChildIndex--;
}
if (lastChildIndex >= 0) {
return getChild(lastChildIndex);
}
return null;
} | java | @Nullable
public SoyNode lastChildThatMatches(Predicate<SoyNode> condition) {
int lastChildIndex = numChildren() - 1;
while (lastChildIndex >= 0 && !condition.test(getChild(lastChildIndex))) {
lastChildIndex--;
}
if (lastChildIndex >= 0) {
return getChild(lastChildIndex);
}
return null;
} | [
"@",
"Nullable",
"public",
"SoyNode",
"lastChildThatMatches",
"(",
"Predicate",
"<",
"SoyNode",
">",
"condition",
")",
"{",
"int",
"lastChildIndex",
"=",
"numChildren",
"(",
")",
"-",
"1",
";",
"while",
"(",
"lastChildIndex",
">=",
"0",
"&&",
"!",
"condition... | Returns the template's last child node that matches the given condition. | [
"Returns",
"the",
"template",
"s",
"last",
"child",
"node",
"that",
"matches",
"the",
"given",
"condition",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/AbstractParentCommandNode.java#L153-L163 | train |
google/closure-templates | java/src/com/google/template/soy/soyparse/SoyParseUtils.java | SoyParseUtils.calculateFullCalleeName | @SuppressWarnings("unused") // called in SoyFileParser.jj
public static final String calculateFullCalleeName(
Identifier ident, SoyFileHeaderInfo header, ErrorReporter errorReporter) {
String name = ident.identifier();
switch (ident.type()) {
case DOT_IDENT:
// Case 1: Source callee name is partial.
return header.getNamespace() + name;
case DOTTED_IDENT:
// Case 2: Source callee name is a proper dotted ident, which might start with an alias.
return header.resolveAlias(name);
case SINGLE_IDENT:
// Case 3: Source callee name is a single ident (not dotted).
if (header.hasAlias(name)) {
// Case 3a: This callee collides with a namespace alias, which likely means the alias
// incorrectly references a template.
errorReporter.report(ident.location(), CALL_COLLIDES_WITH_NAMESPACE_ALIAS, name);
} else {
// Case 3b: The callee name needs a namespace.
errorReporter.report(ident.location(), MISSING_CALLEE_NAMESPACE, name);
}
return name;
}
throw new AssertionError(ident.type());
} | java | @SuppressWarnings("unused") // called in SoyFileParser.jj
public static final String calculateFullCalleeName(
Identifier ident, SoyFileHeaderInfo header, ErrorReporter errorReporter) {
String name = ident.identifier();
switch (ident.type()) {
case DOT_IDENT:
// Case 1: Source callee name is partial.
return header.getNamespace() + name;
case DOTTED_IDENT:
// Case 2: Source callee name is a proper dotted ident, which might start with an alias.
return header.resolveAlias(name);
case SINGLE_IDENT:
// Case 3: Source callee name is a single ident (not dotted).
if (header.hasAlias(name)) {
// Case 3a: This callee collides with a namespace alias, which likely means the alias
// incorrectly references a template.
errorReporter.report(ident.location(), CALL_COLLIDES_WITH_NAMESPACE_ALIAS, name);
} else {
// Case 3b: The callee name needs a namespace.
errorReporter.report(ident.location(), MISSING_CALLEE_NAMESPACE, name);
}
return name;
}
throw new AssertionError(ident.type());
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"// called in SoyFileParser.jj",
"public",
"static",
"final",
"String",
"calculateFullCalleeName",
"(",
"Identifier",
"ident",
",",
"SoyFileHeaderInfo",
"header",
",",
"ErrorReporter",
"errorReporter",
")",
"{",
"String",
... | Given a template call and file header info, return the expanded callee name if possible. | [
"Given",
"a",
"template",
"call",
"and",
"file",
"header",
"info",
"return",
"the",
"expanded",
"callee",
"name",
"if",
"possible",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soyparse/SoyParseUtils.java#L41-L66 | train |
google/closure-templates | java/src/com/google/template/soy/soyparse/SoyParseUtils.java | SoyParseUtils.unescapeString | @SuppressWarnings("unused") // called in SoyFileParser.jj
public static String unescapeString(String s, ErrorReporter errorReporter, SourceLocation loc) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); ) {
char c = s.charAt(i);
if (c == '\\') {
i = doUnescape(s, i + 1, sb, errorReporter, loc);
} else {
sb.append(c);
i++;
}
}
return sb.toString();
} | java | @SuppressWarnings("unused") // called in SoyFileParser.jj
public static String unescapeString(String s, ErrorReporter errorReporter, SourceLocation loc) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); ) {
char c = s.charAt(i);
if (c == '\\') {
i = doUnescape(s, i + 1, sb, errorReporter, loc);
} else {
sb.append(c);
i++;
}
}
return sb.toString();
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"// called in SoyFileParser.jj",
"public",
"static",
"String",
"unescapeString",
"(",
"String",
"s",
",",
"ErrorReporter",
"errorReporter",
",",
"SourceLocation",
"loc",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"S... | Unescapes a Soy string, according to JavaScript rules. | [
"Unescapes",
"a",
"Soy",
"string",
"according",
"to",
"JavaScript",
"rules",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soyparse/SoyParseUtils.java#L69-L82 | train |
google/closure-templates | java/src/com/google/template/soy/soyparse/SoyParseUtils.java | SoyParseUtils.doUnescape | private static int doUnescape(
String s, int i, StringBuilder sb, ErrorReporter errorReporter, SourceLocation loc) {
checkArgument(i < s.length(), "Found escape sequence at the end of a string.");
char c = s.charAt(i++);
switch (c) {
case 'n':
sb.append('\n');
break;
case 'r':
sb.append('\r');
break;
case 't':
sb.append('\t');
break;
case 'b':
sb.append('\b');
break;
case 'f':
sb.append('\f');
break;
case '\\':
case '\"':
case '\'':
case '>':
sb.append(c);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
--i; // backup to first octal digit
int nOctalDigits = 1;
int digitLimit = c < '4' ? 3 : 2;
while (nOctalDigits < digitLimit
&& i + nOctalDigits < s.length()
&& isOctal(s.charAt(i + nOctalDigits))) {
++nOctalDigits;
}
sb.append((char) Integer.parseInt(s.substring(i, i + nOctalDigits), 8));
i += nOctalDigits;
break;
case 'x':
case 'u':
String hexCode;
int nHexDigits = (c == 'u' ? 4 : 2);
try {
hexCode = s.substring(i, i + nHexDigits);
} catch (IndexOutOfBoundsException ioobe) {
errorReporter.report(loc.offsetStartCol(i + 1), INVALID_UNICODE_SEQUENCE, s.substring(i));
return i + nHexDigits;
}
int unicodeValue;
try {
unicodeValue = Integer.parseInt(hexCode, 16);
} catch (NumberFormatException nfe) {
errorReporter.report(loc.offsetStartCol(i + 1), INVALID_UNICODE_SEQUENCE, hexCode);
return i + nHexDigits;
}
sb.append((char) unicodeValue);
i += nHexDigits;
break;
default:
errorReporter.report(loc.offsetStartCol(i), UNKNOWN_ESCAPE_CODE, c);
return i;
}
return i;
} | java | private static int doUnescape(
String s, int i, StringBuilder sb, ErrorReporter errorReporter, SourceLocation loc) {
checkArgument(i < s.length(), "Found escape sequence at the end of a string.");
char c = s.charAt(i++);
switch (c) {
case 'n':
sb.append('\n');
break;
case 'r':
sb.append('\r');
break;
case 't':
sb.append('\t');
break;
case 'b':
sb.append('\b');
break;
case 'f':
sb.append('\f');
break;
case '\\':
case '\"':
case '\'':
case '>':
sb.append(c);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
--i; // backup to first octal digit
int nOctalDigits = 1;
int digitLimit = c < '4' ? 3 : 2;
while (nOctalDigits < digitLimit
&& i + nOctalDigits < s.length()
&& isOctal(s.charAt(i + nOctalDigits))) {
++nOctalDigits;
}
sb.append((char) Integer.parseInt(s.substring(i, i + nOctalDigits), 8));
i += nOctalDigits;
break;
case 'x':
case 'u':
String hexCode;
int nHexDigits = (c == 'u' ? 4 : 2);
try {
hexCode = s.substring(i, i + nHexDigits);
} catch (IndexOutOfBoundsException ioobe) {
errorReporter.report(loc.offsetStartCol(i + 1), INVALID_UNICODE_SEQUENCE, s.substring(i));
return i + nHexDigits;
}
int unicodeValue;
try {
unicodeValue = Integer.parseInt(hexCode, 16);
} catch (NumberFormatException nfe) {
errorReporter.report(loc.offsetStartCol(i + 1), INVALID_UNICODE_SEQUENCE, hexCode);
return i + nHexDigits;
}
sb.append((char) unicodeValue);
i += nHexDigits;
break;
default:
errorReporter.report(loc.offsetStartCol(i), UNKNOWN_ESCAPE_CODE, c);
return i;
}
return i;
} | [
"private",
"static",
"int",
"doUnescape",
"(",
"String",
"s",
",",
"int",
"i",
",",
"StringBuilder",
"sb",
",",
"ErrorReporter",
"errorReporter",
",",
"SourceLocation",
"loc",
")",
"{",
"checkArgument",
"(",
"i",
"<",
"s",
".",
"length",
"(",
")",
",",
"... | Looks for an escape code starting at index i of s, and appends it to sb.
@return the index of the first character in s after the escape code. | [
"Looks",
"for",
"an",
"escape",
"code",
"starting",
"at",
"index",
"i",
"of",
"s",
"and",
"appends",
"it",
"to",
"sb",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soyparse/SoyParseUtils.java#L89-L163 | train |
google/closure-templates | java/src/com/google/template/soy/soyparse/SoyParseUtils.java | SoyParseUtils.unescapeCommandAttributeValue | static String unescapeCommandAttributeValue(String s, QuoteStyle quoteStyle) {
// NOTE: we don't just use String.replace since it internally allocates/compiles a regular
// expression. Instead we have a handrolled loop.
int index = s.indexOf(quoteStyle == QuoteStyle.DOUBLE ? "\\\"" : "\\\'");
if (index == -1) {
return s;
}
StringBuilder buf = new StringBuilder(s.length());
buf.append(s);
boolean nextIsQ = buf.charAt(s.length() - 1) == quoteStyle.getQuoteChar();
for (int i = s.length() - 2; i >= index; i--) {
char c = buf.charAt(i);
if (c == '\\' && nextIsQ) {
buf.deleteCharAt(i);
}
nextIsQ = c == quoteStyle.getQuoteChar();
}
return buf.toString();
} | java | static String unescapeCommandAttributeValue(String s, QuoteStyle quoteStyle) {
// NOTE: we don't just use String.replace since it internally allocates/compiles a regular
// expression. Instead we have a handrolled loop.
int index = s.indexOf(quoteStyle == QuoteStyle.DOUBLE ? "\\\"" : "\\\'");
if (index == -1) {
return s;
}
StringBuilder buf = new StringBuilder(s.length());
buf.append(s);
boolean nextIsQ = buf.charAt(s.length() - 1) == quoteStyle.getQuoteChar();
for (int i = s.length() - 2; i >= index; i--) {
char c = buf.charAt(i);
if (c == '\\' && nextIsQ) {
buf.deleteCharAt(i);
}
nextIsQ = c == quoteStyle.getQuoteChar();
}
return buf.toString();
} | [
"static",
"String",
"unescapeCommandAttributeValue",
"(",
"String",
"s",
",",
"QuoteStyle",
"quoteStyle",
")",
"{",
"// NOTE: we don't just use String.replace since it internally allocates/compiles a regular",
"// expression. Instead we have a handrolled loop.",
"int",
"index",
"=",
... | Unescapes backslash quote sequences in an attribute value to just the quote. | [
"Unescapes",
"backslash",
"quote",
"sequences",
"in",
"an",
"attribute",
"value",
"to",
"just",
"the",
"quote",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soyparse/SoyParseUtils.java#L170-L188 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java | FieldRef.defineField | public void defineField(ClassVisitor cv) {
cv.visitField(
accessFlags(),
name(),
type().getDescriptor(),
null /* no generic signature */,
null /* no initializer */);
} | java | public void defineField(ClassVisitor cv) {
cv.visitField(
accessFlags(),
name(),
type().getDescriptor(),
null /* no generic signature */,
null /* no initializer */);
} | [
"public",
"void",
"defineField",
"(",
"ClassVisitor",
"cv",
")",
"{",
"cv",
".",
"visitField",
"(",
"accessFlags",
"(",
")",
",",
"name",
"(",
")",
",",
"type",
"(",
")",
".",
"getDescriptor",
"(",
")",
",",
"null",
"/* no generic signature */",
",",
"nu... | Defines the given field as member of the class. | [
"Defines",
"the",
"given",
"field",
"as",
"member",
"of",
"the",
"class",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java#L140-L147 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java | FieldRef.accessor | public Expression accessor(final Expression owner) {
checkState(!isStatic());
checkArgument(owner.resultType().equals(this.owner().type()));
Features features = Features.of();
if (owner.isCheap()) {
features = features.plus(Feature.CHEAP);
}
if (!isNullable()) {
features = features.plus(Feature.NON_NULLABLE);
}
return new Expression(type(), features) {
@Override
protected void doGen(CodeBuilder mv) {
owner.gen(mv);
mv.getField(owner().type(), FieldRef.this.name(), resultType());
}
};
} | java | public Expression accessor(final Expression owner) {
checkState(!isStatic());
checkArgument(owner.resultType().equals(this.owner().type()));
Features features = Features.of();
if (owner.isCheap()) {
features = features.plus(Feature.CHEAP);
}
if (!isNullable()) {
features = features.plus(Feature.NON_NULLABLE);
}
return new Expression(type(), features) {
@Override
protected void doGen(CodeBuilder mv) {
owner.gen(mv);
mv.getField(owner().type(), FieldRef.this.name(), resultType());
}
};
} | [
"public",
"Expression",
"accessor",
"(",
"final",
"Expression",
"owner",
")",
"{",
"checkState",
"(",
"!",
"isStatic",
"(",
")",
")",
";",
"checkArgument",
"(",
"owner",
".",
"resultType",
"(",
")",
".",
"equals",
"(",
"this",
".",
"owner",
"(",
")",
"... | Returns an accessor that accesses this field on the given owner. | [
"Returns",
"an",
"accessor",
"that",
"accesses",
"this",
"field",
"on",
"the",
"given",
"owner",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java#L157-L174 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java | FieldRef.accessor | public Expression accessor() {
checkState(isStatic());
Features features = Features.of(Feature.CHEAP);
if (!isNullable()) {
features = features.plus(Feature.NON_NULLABLE);
}
return new Expression(type(), features) {
@Override
protected void doGen(CodeBuilder mv) {
accessStaticUnchecked(mv);
}
};
} | java | public Expression accessor() {
checkState(isStatic());
Features features = Features.of(Feature.CHEAP);
if (!isNullable()) {
features = features.plus(Feature.NON_NULLABLE);
}
return new Expression(type(), features) {
@Override
protected void doGen(CodeBuilder mv) {
accessStaticUnchecked(mv);
}
};
} | [
"public",
"Expression",
"accessor",
"(",
")",
"{",
"checkState",
"(",
"isStatic",
"(",
")",
")",
";",
"Features",
"features",
"=",
"Features",
".",
"of",
"(",
"Feature",
".",
"CHEAP",
")",
";",
"if",
"(",
"!",
"isNullable",
"(",
")",
")",
"{",
"featu... | Returns an expression that accesses this static field. | [
"Returns",
"an",
"expression",
"that",
"accesses",
"this",
"static",
"field",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java#L177-L189 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java | FieldRef.accessStaticUnchecked | void accessStaticUnchecked(CodeBuilder mv) {
checkState(isStatic());
mv.getStatic(owner().type(), FieldRef.this.name(), type());
} | java | void accessStaticUnchecked(CodeBuilder mv) {
checkState(isStatic());
mv.getStatic(owner().type(), FieldRef.this.name(), type());
} | [
"void",
"accessStaticUnchecked",
"(",
"CodeBuilder",
"mv",
")",
"{",
"checkState",
"(",
"isStatic",
"(",
")",
")",
";",
"mv",
".",
"getStatic",
"(",
"owner",
"(",
")",
".",
"type",
"(",
")",
",",
"FieldRef",
".",
"this",
".",
"name",
"(",
")",
",",
... | Accesses a static field. | [
"Accesses",
"a",
"static",
"field",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java#L192-L195 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java | FieldRef.putUnchecked | public void putUnchecked(CodeBuilder adapter) {
checkState(!isStatic(), "This field is static!");
adapter.putField(owner().type(), name(), type());
} | java | public void putUnchecked(CodeBuilder adapter) {
checkState(!isStatic(), "This field is static!");
adapter.putField(owner().type(), name(), type());
} | [
"public",
"void",
"putUnchecked",
"(",
"CodeBuilder",
"adapter",
")",
"{",
"checkState",
"(",
"!",
"isStatic",
"(",
")",
",",
"\"This field is static!\"",
")",
";",
"adapter",
".",
"putField",
"(",
"owner",
"(",
")",
".",
"type",
"(",
")",
",",
"name",
"... | Adds code to place the top item of the stack into this field.
@throws IllegalStateException if this is a static field | [
"Adds",
"code",
"to",
"place",
"the",
"top",
"item",
"of",
"the",
"stack",
"into",
"this",
"field",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java#L240-L243 | train |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/TemplateFactoryCompiler.java | TemplateFactoryCompiler.compile | void compile() {
TypeInfo factoryType = innerClasses.registerInnerClass(FACTORY_CLASS, FACTORY_ACCESS);
SoyClassWriter cw =
SoyClassWriter.builder(factoryType)
.implementing(FACTORY_TYPE)
.setAccess(FACTORY_ACCESS)
.sourceFileName(templateNode.getSourceLocation().getFileName())
.build();
innerClasses.registerAsInnerClass(cw, factoryType);
generateStaticInitializer(cw);
defineDefaultConstructor(cw, factoryType);
generateCreateMethod(cw, factoryType);
cw.visitEnd();
innerClasses.add(cw.toClassData());
} | java | void compile() {
TypeInfo factoryType = innerClasses.registerInnerClass(FACTORY_CLASS, FACTORY_ACCESS);
SoyClassWriter cw =
SoyClassWriter.builder(factoryType)
.implementing(FACTORY_TYPE)
.setAccess(FACTORY_ACCESS)
.sourceFileName(templateNode.getSourceLocation().getFileName())
.build();
innerClasses.registerAsInnerClass(cw, factoryType);
generateStaticInitializer(cw);
defineDefaultConstructor(cw, factoryType);
generateCreateMethod(cw, factoryType);
cw.visitEnd();
innerClasses.add(cw.toClassData());
} | [
"void",
"compile",
"(",
")",
"{",
"TypeInfo",
"factoryType",
"=",
"innerClasses",
".",
"registerInnerClass",
"(",
"FACTORY_CLASS",
",",
"FACTORY_ACCESS",
")",
";",
"SoyClassWriter",
"cw",
"=",
"SoyClassWriter",
".",
"builder",
"(",
"factoryType",
")",
".",
"impl... | Compiles the factory. | [
"Compiles",
"the",
"factory",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/TemplateFactoryCompiler.java#L86-L101 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/RawTextContextUpdater.java | RawTextContextUpdater.processNextToken | private int processNextToken(RawTextNode node, final int offset, String text) {
// Find the transition whose pattern matches earliest in the raw text (and is applicable)
int numCharsConsumed;
Context next;
int earliestStart = Integer.MAX_VALUE;
int earliestEnd = -1;
Transition earliestTransition = null;
Matcher earliestMatcher = null;
List<Transition> ts = TRANSITIONS.get(context.state);
if (ts == null) {
throw new NullPointerException(
"no transitions for state: "
+ context.state
+ " @"
+ node.substringLocation(offset, offset + 1));
}
for (Transition transition : ts) {
if (transition.pattern != null) {
Matcher matcher = transition.pattern.matcher(text);
// For each transition:
// look for matches, if the match is later than the current earliest match, give up
// otherwise if the match is applicable, store it.
// NOTE: matcher.find() returns matches in sequential order.
try {
while (matcher.find() && matcher.start() < earliestStart) {
int start = matcher.start();
int end = matcher.end();
if (transition.isApplicableTo(context, matcher)) {
earliestStart = start;
earliestEnd = end;
earliestTransition = transition;
earliestMatcher = matcher;
break;
}
}
} catch (StackOverflowError soe) {
// catch and annotate with the pattern.
throw new RuntimeException(
String.format(
"StackOverflow while trying to match: '%s' in context %s starting @ %s",
transition.pattern, context, node.substringLocation(offset, offset + 1)),
soe);
}
} else if (transition.literal != null) {
int start = 0;
int index;
String needle = transition.literal;
while ((index = text.indexOf(needle, start)) != -1 && index < earliestStart) {
if (transition.isApplicableTo(context, null)) {
earliestStart = index;
earliestEnd = index + needle.length();
earliestTransition = transition;
earliestMatcher = null;
break;
}
}
} else {
if (text.length() < earliestStart && transition.isApplicableTo(context, null)) {
earliestStart = text.length();
earliestEnd = text.length();
earliestTransition = transition;
earliestMatcher = null;
}
}
}
if (earliestTransition != null) {
int transitionOffset = offset;
// the earliest start might be at the end for null transitions.
if (earliestStart < text.length()) {
transitionOffset += earliestStart;
}
next =
earliestTransition.computeNextContext(node, transitionOffset, context, earliestMatcher);
numCharsConsumed = earliestEnd;
} else {
throw SoyAutoescapeException.createWithNode(
"Error determining next state when encountering \"" + text + "\" in " + context,
// calculate a raw text node that points at the beginning of the string that couldn't
// bet matched.
node.substring(Integer.MAX_VALUE /* bogus id */, offset));
}
if (numCharsConsumed == 0 && next.state == context.state) {
throw new IllegalStateException("Infinite loop at `" + text + "` / " + context);
}
this.context = next;
return numCharsConsumed;
} | java | private int processNextToken(RawTextNode node, final int offset, String text) {
// Find the transition whose pattern matches earliest in the raw text (and is applicable)
int numCharsConsumed;
Context next;
int earliestStart = Integer.MAX_VALUE;
int earliestEnd = -1;
Transition earliestTransition = null;
Matcher earliestMatcher = null;
List<Transition> ts = TRANSITIONS.get(context.state);
if (ts == null) {
throw new NullPointerException(
"no transitions for state: "
+ context.state
+ " @"
+ node.substringLocation(offset, offset + 1));
}
for (Transition transition : ts) {
if (transition.pattern != null) {
Matcher matcher = transition.pattern.matcher(text);
// For each transition:
// look for matches, if the match is later than the current earliest match, give up
// otherwise if the match is applicable, store it.
// NOTE: matcher.find() returns matches in sequential order.
try {
while (matcher.find() && matcher.start() < earliestStart) {
int start = matcher.start();
int end = matcher.end();
if (transition.isApplicableTo(context, matcher)) {
earliestStart = start;
earliestEnd = end;
earliestTransition = transition;
earliestMatcher = matcher;
break;
}
}
} catch (StackOverflowError soe) {
// catch and annotate with the pattern.
throw new RuntimeException(
String.format(
"StackOverflow while trying to match: '%s' in context %s starting @ %s",
transition.pattern, context, node.substringLocation(offset, offset + 1)),
soe);
}
} else if (transition.literal != null) {
int start = 0;
int index;
String needle = transition.literal;
while ((index = text.indexOf(needle, start)) != -1 && index < earliestStart) {
if (transition.isApplicableTo(context, null)) {
earliestStart = index;
earliestEnd = index + needle.length();
earliestTransition = transition;
earliestMatcher = null;
break;
}
}
} else {
if (text.length() < earliestStart && transition.isApplicableTo(context, null)) {
earliestStart = text.length();
earliestEnd = text.length();
earliestTransition = transition;
earliestMatcher = null;
}
}
}
if (earliestTransition != null) {
int transitionOffset = offset;
// the earliest start might be at the end for null transitions.
if (earliestStart < text.length()) {
transitionOffset += earliestStart;
}
next =
earliestTransition.computeNextContext(node, transitionOffset, context, earliestMatcher);
numCharsConsumed = earliestEnd;
} else {
throw SoyAutoescapeException.createWithNode(
"Error determining next state when encountering \"" + text + "\" in " + context,
// calculate a raw text node that points at the beginning of the string that couldn't
// bet matched.
node.substring(Integer.MAX_VALUE /* bogus id */, offset));
}
if (numCharsConsumed == 0 && next.state == context.state) {
throw new IllegalStateException("Infinite loop at `" + text + "` / " + context);
}
this.context = next;
return numCharsConsumed;
} | [
"private",
"int",
"processNextToken",
"(",
"RawTextNode",
"node",
",",
"final",
"int",
"offset",
",",
"String",
"text",
")",
"{",
"// Find the transition whose pattern matches earliest in the raw text (and is applicable)",
"int",
"numCharsConsumed",
";",
"Context",
"next",
... | Consume a portion of text and compute the next context. Output is stored in member variables.
@param node The node currently being processed
@param offset The offset into the node where text starts
@param text Non empty.
@return the number of characters consumed | [
"Consume",
"a",
"portion",
"of",
"text",
"and",
"compute",
"the",
"next",
"context",
".",
"Output",
"is",
"stored",
"in",
"member",
"variables",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/RawTextContextUpdater.java#L120-L207 | train |
google/closure-templates | java/src/com/google/template/soy/parsepasses/contextautoesc/RawTextContextUpdater.java | RawTextContextUpdater.getNextUriPart | private static UriPart getNextUriPart(
RawTextNode node, int offset, UriPart uriPart, char matchChar) {
// This switch statement is designed to process a URI in order via a sequence of fall throughs.
switch (uriPart) {
case MAYBE_SCHEME:
case MAYBE_VARIABLE_SCHEME:
// From the RFC: https://tools.ietf.org/html/rfc3986#section-3.1
// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
// At this point, our goal is to try to prove that we've safely left the scheme, and then
// transition to a more specific state.
if (matchChar == ':') {
// Ah, it looks like we might be able to conclude we've set the scheme, but...
if (uriPart == UriPart.MAYBE_VARIABLE_SCHEME) {
// At the start of a URL, and we already saw a print statement, and now we suddenly
// see a colon. While this could be relatively safe if it's a {$host}:{$port} pair,
// at compile-time, we can't be sure that "$host" isn't something like "javascript"
// and "$port" isn't "deleteMyAccount()".
throw SoyAutoescapeException.createWithNode(
"Soy can't safely process a URI that might start with a variable scheme. "
+ "For example, {$x}:{$y} could have an XSS if $x is 'javascript' and $y is "
+ "attacker-controlled. Either use a hard-coded scheme, or introduce "
+ "disambiguating characters (e.g. http://{$x}:{$y}, ./{$x}:{$y}, or "
+ "{$x}?foo=:{$y})",
node.substring(/* newId= */ Integer.MAX_VALUE, offset));
} else {
// At the start of the URL, and we just saw some hard-coded characters and a colon,
// like http:. This is safe (assuming it's a good scheme), and now we're on our way to
// the authority. Note if javascript: was seen, we would have scanned it already and
// entered a separate state (unless the developer is malicious and tries to obscure it
// via a conditional).
return UriPart.AUTHORITY_OR_PATH;
}
}
if (matchChar == '/') {
// Upon seeing a slash, it's impossible to set a valid scheme anymore. Either we're in the
// path, or we're starting a protocol-relative URI. (For all we know, we *could* be
// in the query, e.g. {$base}/foo if $base has a question mark, but sadly we have to go
// by what we know statically. However, usually query param groups tend to contain
// ampersands and equal signs, which we check for later heuristically.)
return UriPart.AUTHORITY_OR_PATH;
}
if ((matchChar == '=' || matchChar == '&') && uriPart == UriPart.MAYBE_VARIABLE_SCHEME) {
// This case is really special, and is only seen in cases like href="{$x}&foo={$y}" or
// href="{$x}foo={$y}". While in this case we can never be sure that we're in the query
// part, we do know two things:
//
// 1) We can't possibly set a dangerous scheme, since no valid scheme contains = or &
// 2) Within QUERY, all print statements are encoded as a URI component, which limits
// the damage that can be done; it can't even break into another path segment.
// Therefore, it is secure to assume this.
//
// Note we can safely handle ampersand even in HTML contexts because attribute values
// are processed unescaped.
return UriPart.QUERY;
}
// fall through
case AUTHORITY_OR_PATH:
// fall through
case UNKNOWN_PRE_FRAGMENT:
if (matchChar == '?') {
// Upon a ? we can be pretty sure we're in the query. While it's possible for something
// like {$base}?foo=bar to be in the fragment if $base contains a #, it's safe to assume
// we're in the query, because query params are escaped more strictly than the fragment.
return UriPart.QUERY;
}
// fall through
case QUERY:
case UNKNOWN:
if (matchChar == '#') {
// A # anywhere proves we're in the fragment, even if we're already in the fragment.
return UriPart.FRAGMENT;
}
// fall through
case FRAGMENT:
// No transitions for fragment.
return uriPart;
case DANGEROUS_SCHEME:
// Dangerous schemes remain dangerous.
return UriPart.DANGEROUS_SCHEME;
case TRUSTED_RESOURCE_URI_END:
throw new AssertionError("impossible");
case NONE:
// generally impossible
case START:
// fall-through. this should have been handled by our callers
}
throw new AssertionError("Unanticipated URI part: " + uriPart);
} | java | private static UriPart getNextUriPart(
RawTextNode node, int offset, UriPart uriPart, char matchChar) {
// This switch statement is designed to process a URI in order via a sequence of fall throughs.
switch (uriPart) {
case MAYBE_SCHEME:
case MAYBE_VARIABLE_SCHEME:
// From the RFC: https://tools.ietf.org/html/rfc3986#section-3.1
// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
// At this point, our goal is to try to prove that we've safely left the scheme, and then
// transition to a more specific state.
if (matchChar == ':') {
// Ah, it looks like we might be able to conclude we've set the scheme, but...
if (uriPart == UriPart.MAYBE_VARIABLE_SCHEME) {
// At the start of a URL, and we already saw a print statement, and now we suddenly
// see a colon. While this could be relatively safe if it's a {$host}:{$port} pair,
// at compile-time, we can't be sure that "$host" isn't something like "javascript"
// and "$port" isn't "deleteMyAccount()".
throw SoyAutoescapeException.createWithNode(
"Soy can't safely process a URI that might start with a variable scheme. "
+ "For example, {$x}:{$y} could have an XSS if $x is 'javascript' and $y is "
+ "attacker-controlled. Either use a hard-coded scheme, or introduce "
+ "disambiguating characters (e.g. http://{$x}:{$y}, ./{$x}:{$y}, or "
+ "{$x}?foo=:{$y})",
node.substring(/* newId= */ Integer.MAX_VALUE, offset));
} else {
// At the start of the URL, and we just saw some hard-coded characters and a colon,
// like http:. This is safe (assuming it's a good scheme), and now we're on our way to
// the authority. Note if javascript: was seen, we would have scanned it already and
// entered a separate state (unless the developer is malicious and tries to obscure it
// via a conditional).
return UriPart.AUTHORITY_OR_PATH;
}
}
if (matchChar == '/') {
// Upon seeing a slash, it's impossible to set a valid scheme anymore. Either we're in the
// path, or we're starting a protocol-relative URI. (For all we know, we *could* be
// in the query, e.g. {$base}/foo if $base has a question mark, but sadly we have to go
// by what we know statically. However, usually query param groups tend to contain
// ampersands and equal signs, which we check for later heuristically.)
return UriPart.AUTHORITY_OR_PATH;
}
if ((matchChar == '=' || matchChar == '&') && uriPart == UriPart.MAYBE_VARIABLE_SCHEME) {
// This case is really special, and is only seen in cases like href="{$x}&foo={$y}" or
// href="{$x}foo={$y}". While in this case we can never be sure that we're in the query
// part, we do know two things:
//
// 1) We can't possibly set a dangerous scheme, since no valid scheme contains = or &
// 2) Within QUERY, all print statements are encoded as a URI component, which limits
// the damage that can be done; it can't even break into another path segment.
// Therefore, it is secure to assume this.
//
// Note we can safely handle ampersand even in HTML contexts because attribute values
// are processed unescaped.
return UriPart.QUERY;
}
// fall through
case AUTHORITY_OR_PATH:
// fall through
case UNKNOWN_PRE_FRAGMENT:
if (matchChar == '?') {
// Upon a ? we can be pretty sure we're in the query. While it's possible for something
// like {$base}?foo=bar to be in the fragment if $base contains a #, it's safe to assume
// we're in the query, because query params are escaped more strictly than the fragment.
return UriPart.QUERY;
}
// fall through
case QUERY:
case UNKNOWN:
if (matchChar == '#') {
// A # anywhere proves we're in the fragment, even if we're already in the fragment.
return UriPart.FRAGMENT;
}
// fall through
case FRAGMENT:
// No transitions for fragment.
return uriPart;
case DANGEROUS_SCHEME:
// Dangerous schemes remain dangerous.
return UriPart.DANGEROUS_SCHEME;
case TRUSTED_RESOURCE_URI_END:
throw new AssertionError("impossible");
case NONE:
// generally impossible
case START:
// fall-through. this should have been handled by our callers
}
throw new AssertionError("Unanticipated URI part: " + uriPart);
} | [
"private",
"static",
"UriPart",
"getNextUriPart",
"(",
"RawTextNode",
"node",
",",
"int",
"offset",
",",
"UriPart",
"uriPart",
",",
"char",
"matchChar",
")",
"{",
"// This switch statement is designed to process a URI in order via a sequence of fall throughs.",
"switch",
"(",... | Matching at the end is lowest possible precedence. | [
"Matching",
"at",
"the",
"end",
"is",
"lowest",
"possible",
"precedence",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/RawTextContextUpdater.java#L356-L446 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Expression.java | Expression.fromExpr | public static Expression fromExpr(JsExpr expr, Iterable<GoogRequire> requires) {
return Leaf.create(expr, /* isCheap= */ false, requires);
} | java | public static Expression fromExpr(JsExpr expr, Iterable<GoogRequire> requires) {
return Leaf.create(expr, /* isCheap= */ false, requires);
} | [
"public",
"static",
"Expression",
"fromExpr",
"(",
"JsExpr",
"expr",
",",
"Iterable",
"<",
"GoogRequire",
">",
"requires",
")",
"{",
"return",
"Leaf",
".",
"create",
"(",
"expr",
",",
"/* isCheap= */",
"false",
",",
"requires",
")",
";",
"}"
] | Creates a new code chunk from the given expression. The expression's precedence is preserved. | [
"Creates",
"a",
"new",
"code",
"chunk",
"from",
"the",
"given",
"expression",
".",
"The",
"expression",
"s",
"precedence",
"is",
"preserved",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Expression.java#L73-L75 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Expression.java | Expression.regexLiteral | public static Expression regexLiteral(String contents) {
int firstSlash = contents.indexOf('/');
int lastSlash = contents.lastIndexOf('/');
checkArgument(
firstSlash < lastSlash && firstSlash != -1,
"expected regex to start with a '/' and have a second '/' near the end, got %s",
contents);
return Leaf.create(contents, /* isCheap= */ false);
} | java | public static Expression regexLiteral(String contents) {
int firstSlash = contents.indexOf('/');
int lastSlash = contents.lastIndexOf('/');
checkArgument(
firstSlash < lastSlash && firstSlash != -1,
"expected regex to start with a '/' and have a second '/' near the end, got %s",
contents);
return Leaf.create(contents, /* isCheap= */ false);
} | [
"public",
"static",
"Expression",
"regexLiteral",
"(",
"String",
"contents",
")",
"{",
"int",
"firstSlash",
"=",
"contents",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"int",
"lastSlash",
"=",
"contents",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"check... | Creates a code chunk representing a JavaScript regular expression literal.
@param contents The regex literal (including the opening and closing slashes). | [
"Creates",
"a",
"code",
"chunk",
"representing",
"a",
"JavaScript",
"regular",
"expression",
"literal",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Expression.java#L144-L152 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Expression.java | Expression.number | public static Expression number(long value) {
Preconditions.checkArgument(
IntegerNode.isInRange(value), "Number is outside JS safe integer range: %s", value);
return Leaf.create(Long.toString(value), /* isCheap= */ true);
} | java | public static Expression number(long value) {
Preconditions.checkArgument(
IntegerNode.isInRange(value), "Number is outside JS safe integer range: %s", value);
return Leaf.create(Long.toString(value), /* isCheap= */ true);
} | [
"public",
"static",
"Expression",
"number",
"(",
"long",
"value",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"IntegerNode",
".",
"isInRange",
"(",
"value",
")",
",",
"\"Number is outside JS safe integer range: %s\"",
",",
"value",
")",
";",
"return",
"L... | Creates a code chunk representing a JavaScript number literal. | [
"Creates",
"a",
"code",
"chunk",
"representing",
"a",
"JavaScript",
"number",
"literal",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Expression.java#L155-L159 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Expression.java | Expression.function | public static Expression function(JsDoc parameters, Statement body) {
return FunctionDeclaration.create(parameters, body);
} | java | public static Expression function(JsDoc parameters, Statement body) {
return FunctionDeclaration.create(parameters, body);
} | [
"public",
"static",
"Expression",
"function",
"(",
"JsDoc",
"parameters",
",",
"Statement",
"body",
")",
"{",
"return",
"FunctionDeclaration",
".",
"create",
"(",
"parameters",
",",
"body",
")",
";",
"}"
] | Creates a code chunk representing an anonymous function literal. | [
"Creates",
"a",
"code",
"chunk",
"representing",
"an",
"anonymous",
"function",
"literal",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Expression.java#L167-L169 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Expression.java | Expression.arrowFunction | public static Expression arrowFunction(JsDoc parameters, Statement body) {
return FunctionDeclaration.createArrowFunction(parameters, body);
} | java | public static Expression arrowFunction(JsDoc parameters, Statement body) {
return FunctionDeclaration.createArrowFunction(parameters, body);
} | [
"public",
"static",
"Expression",
"arrowFunction",
"(",
"JsDoc",
"parameters",
",",
"Statement",
"body",
")",
"{",
"return",
"FunctionDeclaration",
".",
"createArrowFunction",
"(",
"parameters",
",",
"body",
")",
";",
"}"
] | Creates a code chunk representing an arrow function. | [
"Creates",
"a",
"code",
"chunk",
"representing",
"an",
"arrow",
"function",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Expression.java#L172-L174 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Expression.java | Expression.operation | public static Expression operation(Operator op, List<Expression> operands) {
Preconditions.checkArgument(operands.size() == op.getNumOperands());
Preconditions.checkArgument(
op != Operator.AND && op != Operator.OR && op != Operator.CONDITIONAL);
switch (op.getNumOperands()) {
case 1:
return PrefixUnaryOperation.create(op, operands.get(0));
case 2:
return BinaryOperation.create(op, operands.get(0), operands.get(1));
default:
throw new AssertionError();
}
} | java | public static Expression operation(Operator op, List<Expression> operands) {
Preconditions.checkArgument(operands.size() == op.getNumOperands());
Preconditions.checkArgument(
op != Operator.AND && op != Operator.OR && op != Operator.CONDITIONAL);
switch (op.getNumOperands()) {
case 1:
return PrefixUnaryOperation.create(op, operands.get(0));
case 2:
return BinaryOperation.create(op, operands.get(0), operands.get(1));
default:
throw new AssertionError();
}
} | [
"public",
"static",
"Expression",
"operation",
"(",
"Operator",
"op",
",",
"List",
"<",
"Expression",
">",
"operands",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"operands",
".",
"size",
"(",
")",
"==",
"op",
".",
"getNumOperands",
"(",
")",
")"... | Creates a code chunk representing the given Soy operator applied to the given operands.
<p>Cannot be used for {@link Operator#AND}, {@link Operator#OR}, or {@link
Operator#CONDITIONAL}, as they require access to a {@link Generator} to generate temporary
variables for short-circuiting. Use {@link Expression#and}, {@link Expression#or}, and {@link
Generator#conditionalExpression} instead. | [
"Creates",
"a",
"code",
"chunk",
"representing",
"the",
"given",
"Soy",
"operator",
"applied",
"to",
"the",
"given",
"operands",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Expression.java#L198-L210 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Expression.java | Expression.arrayLiteral | public static Expression arrayLiteral(Iterable<? extends Expression> elements) {
return ArrayLiteral.create(ImmutableList.copyOf(elements));
} | java | public static Expression arrayLiteral(Iterable<? extends Expression> elements) {
return ArrayLiteral.create(ImmutableList.copyOf(elements));
} | [
"public",
"static",
"Expression",
"arrayLiteral",
"(",
"Iterable",
"<",
"?",
"extends",
"Expression",
">",
"elements",
")",
"{",
"return",
"ArrayLiteral",
".",
"create",
"(",
"ImmutableList",
".",
"copyOf",
"(",
"elements",
")",
")",
";",
"}"
] | Creates a code chunk representing a javascript array literal. | [
"Creates",
"a",
"code",
"chunk",
"representing",
"a",
"javascript",
"array",
"literal",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Expression.java#L213-L215 | train |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Expression.java | Expression.withInitialStatements | public final Expression withInitialStatements(Iterable<? extends Statement> initialStatements) {
// If there are no new initial statements, return the current chunk.
if (Iterables.isEmpty(initialStatements)) {
return this;
}
// Otherwise, return a code chunk that includes all of the dependent code.
return Composite.create(ImmutableList.copyOf(initialStatements), this);
} | java | public final Expression withInitialStatements(Iterable<? extends Statement> initialStatements) {
// If there are no new initial statements, return the current chunk.
if (Iterables.isEmpty(initialStatements)) {
return this;
}
// Otherwise, return a code chunk that includes all of the dependent code.
return Composite.create(ImmutableList.copyOf(initialStatements), this);
} | [
"public",
"final",
"Expression",
"withInitialStatements",
"(",
"Iterable",
"<",
"?",
"extends",
"Statement",
">",
"initialStatements",
")",
"{",
"// If there are no new initial statements, return the current chunk.",
"if",
"(",
"Iterables",
".",
"isEmpty",
"(",
"initialStat... | Returns a chunk whose output expression is the same as this chunk's, but which includes the
given initial statements.
<p>This method is designed for interoperability with parts of the JS codegen system that do not
understand code chunks. For example, when applying plugin functions, {@link
com.google.template.soy.jssrc.internal.TranslateExprNodeVisitor#visitFunctionNode} needs to
downgrade the plugin arguments from CodeChunk.WithValues to {@link JsExpr}s for the plugin API
to process. The result (a JsExpr) needs to be upgraded back to a CodeChunk.Expression that
includes the initial statements from the original arguments. | [
"Returns",
"a",
"chunk",
"whose",
"output",
"expression",
"is",
"the",
"same",
"as",
"this",
"chunk",
"s",
"but",
"which",
"includes",
"the",
"given",
"initial",
"statements",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Expression.java#L384-L391 | train |
google/closure-templates | java/src/com/google/template/soy/passes/htmlmatcher/HtmlMatcherTagNode.java | HtmlMatcherTagNode.getTagKind | public TagKind getTagKind() {
if (htmlTagNode instanceof HtmlOpenTagNode) {
HtmlOpenTagNode openTagNode = (HtmlOpenTagNode) htmlTagNode;
if (openTagNode.isSelfClosing() || openTagNode.getTagName().isDefinitelyVoid()) {
return TagKind.VOID_TAG;
}
return TagKind.OPEN_TAG;
} else {
return TagKind.CLOSE_TAG;
}
} | java | public TagKind getTagKind() {
if (htmlTagNode instanceof HtmlOpenTagNode) {
HtmlOpenTagNode openTagNode = (HtmlOpenTagNode) htmlTagNode;
if (openTagNode.isSelfClosing() || openTagNode.getTagName().isDefinitelyVoid()) {
return TagKind.VOID_TAG;
}
return TagKind.OPEN_TAG;
} else {
return TagKind.CLOSE_TAG;
}
} | [
"public",
"TagKind",
"getTagKind",
"(",
")",
"{",
"if",
"(",
"htmlTagNode",
"instanceof",
"HtmlOpenTagNode",
")",
"{",
"HtmlOpenTagNode",
"openTagNode",
"=",
"(",
"HtmlOpenTagNode",
")",
"htmlTagNode",
";",
"if",
"(",
"openTagNode",
".",
"isSelfClosing",
"(",
")... | Returns the tag kind. | [
"Returns",
"the",
"tag",
"kind",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/htmlmatcher/HtmlMatcherTagNode.java#L60-L70 | train |
google/closure-templates | java/src/com/google/template/soy/types/UnionType.java | UnionType.of | public static SoyType of(Collection<SoyType> members) {
// sort and flatten the set of types
ImmutableSortedSet.Builder<SoyType> builder = ImmutableSortedSet.orderedBy(MEMBER_ORDER);
for (SoyType type : members) {
// simplify unions containing these types
if (type.getKind() == Kind.UNKNOWN
|| type.getKind() == Kind.ERROR
|| type.getKind() == Kind.ANY) {
return type;
}
if (type.getKind() == Kind.UNION) {
builder.addAll(((UnionType) type).members);
} else {
builder.add(type);
}
}
ImmutableSet<SoyType> flattenedMembers = builder.build();
if (flattenedMembers.size() == 1) {
return Iterables.getOnlyElement(flattenedMembers);
}
return new UnionType(flattenedMembers);
} | java | public static SoyType of(Collection<SoyType> members) {
// sort and flatten the set of types
ImmutableSortedSet.Builder<SoyType> builder = ImmutableSortedSet.orderedBy(MEMBER_ORDER);
for (SoyType type : members) {
// simplify unions containing these types
if (type.getKind() == Kind.UNKNOWN
|| type.getKind() == Kind.ERROR
|| type.getKind() == Kind.ANY) {
return type;
}
if (type.getKind() == Kind.UNION) {
builder.addAll(((UnionType) type).members);
} else {
builder.add(type);
}
}
ImmutableSet<SoyType> flattenedMembers = builder.build();
if (flattenedMembers.size() == 1) {
return Iterables.getOnlyElement(flattenedMembers);
}
return new UnionType(flattenedMembers);
} | [
"public",
"static",
"SoyType",
"of",
"(",
"Collection",
"<",
"SoyType",
">",
"members",
")",
"{",
"// sort and flatten the set of types",
"ImmutableSortedSet",
".",
"Builder",
"<",
"SoyType",
">",
"builder",
"=",
"ImmutableSortedSet",
".",
"orderedBy",
"(",
"MEMBER_... | Create a union from a collection of types.
@param members Member types of the union.
@return Union of those types. If there is exactly one distinct type in members, then this will
not be a UnionType. | [
"Create",
"a",
"union",
"from",
"a",
"collection",
"of",
"types",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/UnionType.java#L74-L95 | train |
google/closure-templates | java/src/com/google/template/soy/types/UnionType.java | UnionType.isNullable | public boolean isNullable() {
return members.stream().anyMatch(t -> t.getKind() == SoyType.Kind.NULL);
} | java | public boolean isNullable() {
return members.stream().anyMatch(t -> t.getKind() == SoyType.Kind.NULL);
} | [
"public",
"boolean",
"isNullable",
"(",
")",
"{",
"return",
"members",
".",
"stream",
"(",
")",
".",
"anyMatch",
"(",
"t",
"->",
"t",
".",
"getKind",
"(",
")",
"==",
"SoyType",
".",
"Kind",
".",
"NULL",
")",
";",
"}"
] | Returns true if the union includes the null type. | [
"Returns",
"true",
"if",
"the",
"union",
"includes",
"the",
"null",
"type",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/UnionType.java#L120-L122 | train |
google/closure-templates | java/src/com/google/template/soy/types/UnionType.java | UnionType.removeNullability | public SoyType removeNullability() {
if (isNullable()) {
return of(
members.stream()
.filter(t -> t.getKind() != SoyType.Kind.NULL)
.collect(Collectors.toList()));
}
return this;
} | java | public SoyType removeNullability() {
if (isNullable()) {
return of(
members.stream()
.filter(t -> t.getKind() != SoyType.Kind.NULL)
.collect(Collectors.toList()));
}
return this;
} | [
"public",
"SoyType",
"removeNullability",
"(",
")",
"{",
"if",
"(",
"isNullable",
"(",
")",
")",
"{",
"return",
"of",
"(",
"members",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"t",
"->",
"t",
".",
"getKind",
"(",
")",
"!=",
"SoyType",
".",
"Kind... | Returns a Soy type that is equivalent to this one but with 'null' removed. | [
"Returns",
"a",
"Soy",
"type",
"that",
"is",
"equivalent",
"to",
"this",
"one",
"but",
"with",
"null",
"removed",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/UnionType.java#L125-L133 | train |
google/closure-templates | java/src/com/google/template/soy/basetree/MixinParentNode.java | MixinParentNode.addChild | public void addChild(N child) {
checkNotNull(child);
tryRemoveFromOldParent(child);
children.add(child);
child.setParent(master);
} | java | public void addChild(N child) {
checkNotNull(child);
tryRemoveFromOldParent(child);
children.add(child);
child.setParent(master);
} | [
"public",
"void",
"addChild",
"(",
"N",
"child",
")",
"{",
"checkNotNull",
"(",
"child",
")",
";",
"tryRemoveFromOldParent",
"(",
"child",
")",
";",
"children",
".",
"add",
"(",
"child",
")",
";",
"child",
".",
"setParent",
"(",
"master",
")",
";",
"}"... | Adds the given child.
@param child The child to add. | [
"Adds",
"the",
"given",
"child",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basetree/MixinParentNode.java#L118-L123 | train |
google/closure-templates | java/src/com/google/template/soy/basetree/MixinParentNode.java | MixinParentNode.removeChild | public void removeChild(int index) {
N child = children.remove(index);
child.setParent(null);
} | java | public void removeChild(int index) {
N child = children.remove(index);
child.setParent(null);
} | [
"public",
"void",
"removeChild",
"(",
"int",
"index",
")",
"{",
"N",
"child",
"=",
"children",
".",
"remove",
"(",
"index",
")",
";",
"child",
".",
"setParent",
"(",
"null",
")",
";",
"}"
] | Removes the child at the given index.
@param index The index of the child to remove. | [
"Removes",
"the",
"child",
"at",
"the",
"given",
"index",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basetree/MixinParentNode.java#L143-L146 | train |
google/closure-templates | java/src/com/google/template/soy/basetree/MixinParentNode.java | MixinParentNode.replaceChild | public void replaceChild(int index, N newChild) {
checkNotNull(newChild);
tryRemoveFromOldParent(newChild);
N oldChild = children.set(index, newChild);
oldChild.setParent(null);
newChild.setParent(master);
} | java | public void replaceChild(int index, N newChild) {
checkNotNull(newChild);
tryRemoveFromOldParent(newChild);
N oldChild = children.set(index, newChild);
oldChild.setParent(null);
newChild.setParent(master);
} | [
"public",
"void",
"replaceChild",
"(",
"int",
"index",
",",
"N",
"newChild",
")",
"{",
"checkNotNull",
"(",
"newChild",
")",
";",
"tryRemoveFromOldParent",
"(",
"newChild",
")",
";",
"N",
"oldChild",
"=",
"children",
".",
"set",
"(",
"index",
",",
"newChil... | Replaces the child at the given index with the given new child.
@param index The index of the child to replace.
@param newChild The new child. | [
"Replaces",
"the",
"child",
"at",
"the",
"given",
"index",
"with",
"the",
"given",
"new",
"child",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basetree/MixinParentNode.java#L164-L170 | train |
google/closure-templates | java/src/com/google/template/soy/basetree/MixinParentNode.java | MixinParentNode.clearChildren | public void clearChildren() {
for (int i = 0; i < children.size(); i++) {
children.get(i).setParent(null);
}
children.clear();
} | java | public void clearChildren() {
for (int i = 0; i < children.size(); i++) {
children.get(i).setParent(null);
}
children.clear();
} | [
"public",
"void",
"clearChildren",
"(",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"children",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"children",
".",
"get",
"(",
"i",
")",
".",
"setParent",
"(",
"null",
")",
";",
"}... | Clears the list of children. | [
"Clears",
"the",
"list",
"of",
"children",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basetree/MixinParentNode.java#L183-L188 | train |
google/closure-templates | java/src/com/google/template/soy/basetree/MixinParentNode.java | MixinParentNode.addChildren | @SuppressWarnings("unchecked")
public void addChildren(List<? extends N> children) {
// NOTE: if the input list comes from another node, this could cause
// ConcurrentModificationExceptions as nodes are moved from one parent to another. To avoid
// this we make a copy of the input list.
for (Node child : children.toArray(new Node[0])) {
addChild((N) child);
}
} | java | @SuppressWarnings("unchecked")
public void addChildren(List<? extends N> children) {
// NOTE: if the input list comes from another node, this could cause
// ConcurrentModificationExceptions as nodes are moved from one parent to another. To avoid
// this we make a copy of the input list.
for (Node child : children.toArray(new Node[0])) {
addChild((N) child);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"addChildren",
"(",
"List",
"<",
"?",
"extends",
"N",
">",
"children",
")",
"{",
"// NOTE: if the input list comes from another node, this could cause",
"// ConcurrentModificationExceptions as nodes are moved... | Adds the given children.
@param children The children to add. | [
"Adds",
"the",
"given",
"children",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basetree/MixinParentNode.java#L195-L203 | train |
google/closure-templates | java/src/com/google/template/soy/basetree/MixinParentNode.java | MixinParentNode.appendSourceStringForChildren | public void appendSourceStringForChildren(StringBuilder sb) {
for (N child : children) {
sb.append(child.toSourceString());
}
} | java | public void appendSourceStringForChildren(StringBuilder sb) {
for (N child : children) {
sb.append(child.toSourceString());
}
} | [
"public",
"void",
"appendSourceStringForChildren",
"(",
"StringBuilder",
"sb",
")",
"{",
"for",
"(",
"N",
"child",
":",
"children",
")",
"{",
"sb",
".",
"append",
"(",
"child",
".",
"toSourceString",
"(",
")",
")",
";",
"}",
"}"
] | Appends the source strings for all the children to the given StringBuilder.
@param sb The StringBuilder to which to append the children's source strings. | [
"Appends",
"the",
"source",
"strings",
"for",
"all",
"the",
"children",
"to",
"the",
"given",
"StringBuilder",
"."
] | cc61e1dff70ae97f24f417a57410081bc498bd56 | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/basetree/MixinParentNode.java#L229-L233 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.