use of com.google.template.soy.exprtree.ExprNode in project closure-templates by google.
the class SoyUtils method parseCompileTimeGlobals.
/**
* Parses a globals file in the format created by {@link #generateCompileTimeGlobalsFile} into a
* map from global name to primitive value.
*
* @param inputSource A source that returns a reader for the globals file.
* @return The parsed globals map.
* @throws IOException If an error occurs while reading the globals file.
* @throws IllegalStateException If the globals file is not in the correct format.
*/
public static ImmutableMap<String, PrimitiveData> parseCompileTimeGlobals(CharSource inputSource) throws IOException {
Builder<String, PrimitiveData> compileTimeGlobalsBuilder = ImmutableMap.builder();
ErrorReporter errorReporter = ErrorReporter.exploding();
try (BufferedReader reader = inputSource.openBufferedStream()) {
int lineNum = 1;
for (String line = reader.readLine(); line != null; line = reader.readLine(), ++lineNum) {
if (line.startsWith("//") || line.trim().length() == 0) {
continue;
}
SourceLocation sourceLocation = new SourceLocation("globals", lineNum, 1, lineNum, 1);
Matcher matcher = COMPILE_TIME_GLOBAL_LINE.matcher(line);
if (!matcher.matches()) {
errorReporter.report(sourceLocation, INVALID_FORMAT, line);
continue;
}
String name = matcher.group(1);
String valueText = matcher.group(2).trim();
ExprNode valueExpr = SoyFileParser.parseExprOrDie(valueText);
// TODO: Consider allowing non-primitives (e.g. list/map literals).
if (!(valueExpr instanceof PrimitiveNode)) {
if (valueExpr instanceof GlobalNode || valueExpr instanceof VarRefNode) {
errorReporter.report(sourceLocation, INVALID_VALUE, valueExpr.toSourceString());
} else {
errorReporter.report(sourceLocation, NON_PRIMITIVE_VALUE, valueExpr.toSourceString());
}
continue;
}
// Default case.
compileTimeGlobalsBuilder.put(name, InternalValueUtils.convertPrimitiveExprToData((PrimitiveNode) valueExpr));
}
}
return compileTimeGlobalsBuilder.build();
}
use of com.google.template.soy.exprtree.ExprNode in project closure-templates by google.
the class EvalVisitorTest method eval.
/**
* Evaluates the given expression and returns the result.
*
* @param expression The expression to evaluate.
* @return The expression result.
* @throws Exception If there's an error.
*/
private SoyValue eval(String expression) throws Exception {
PrintNode code = (PrintNode) SoyFileSetParserBuilder.forTemplateContents(// wrap in a function so we don't run into the 'can't print bools' error message
untypedTemplateBodyForExpression("fakeFunction(" + expression + ")")).addSoyFunction(new SoyFunction() {
@Override
public String getName() {
return "fakeFunction";
}
@Override
public Set<Integer> getValidArgsSizes() {
return ImmutableSet.of(1);
}
}).parse().fileSet().getChild(0).getChild(0).getChild(0);
ExprNode expr = ((FunctionNode) code.getExpr().getChild(0)).getChild(0);
EvalVisitor evalVisitor = new EvalVisitorFactoryImpl().create(TestingEnvironment.createForTest(testData, LOCALS), TEST_IJ_DATA, cssRenamingMap, xidRenamingMap, null, /* debugSoyTemplateInfo= */
false);
return evalVisitor.exec(expr);
}
use of com.google.template.soy.exprtree.ExprNode in project closure-templates by google.
the class ExpressionSubject method generatesASTWithRootOfType.
void generatesASTWithRootOfType(Class<? extends ExprNode> clazz) {
ExprNode root = isValidExpression();
if (!clazz.isInstance(root)) {
failWithBadResults("generates an ast with root of type", clazz, "has type", root.getClass());
}
Truth.assertThat(root).isInstanceOf(clazz);
}
use of com.google.template.soy.exprtree.ExprNode in project closure-templates by google.
the class SoyExprForPySubject method translatesTo.
/**
* Asserts the subject translates to the expected PyExpr including verification of the exact
* PyExpr class (e.g. {@code PyStringExpr.class}).
*
* @param expectedPyExpr the expected result of translation
* @param expectedClass the expected class of the resulting PyExpr
*/
public void translatesTo(PyExpr expectedPyExpr, Class<? extends PyExpr> expectedClass) {
SoyFileSetNode soyTree = SoyFileSetParserBuilder.forTemplateContents(untypedTemplateBodyForExpression(getSubject())).options(opts).parse().fileSet();
PrintNode node = (PrintNode) SharedTestUtils.getNode(soyTree, 0);
ExprNode exprNode = node.getExpr();
PyExpr actualPyExpr = new TranslateToPyExprVisitor(localVarExprs, ErrorReporter.exploding()).exec(exprNode);
assertThat(actualPyExpr.getText()).isEqualTo(expectedPyExpr.getText());
assertThat(actualPyExpr.getPrecedence()).isEqualTo(expectedPyExpr.getPrecedence());
if (expectedClass != null) {
assertThat(actualPyExpr.getClass()).isEqualTo(expectedClass);
}
}
use of com.google.template.soy.exprtree.ExprNode in project closure-templates by google.
the class SharedTestUtils method createTemplateBodyForExpression.
/**
* Returns a template body for the given soy expression. With type specializations.
*/
public static String createTemplateBodyForExpression(String soyExpr, final Map<String, SoyType> typeMap) {
ExprNode expr = SoyFileParser.parseExpression(soyExpr, PluginResolver.nullResolver(Mode.ALLOW_UNDEFINED, ErrorReporter.exploding()), ErrorReporter.exploding());
final Set<String> loopVarNames = new HashSet<>();
final Set<String> names = new HashSet<>();
new AbstractExprNodeVisitor<Void>() {
@Override
protected void visitVarRefNode(VarRefNode node) {
if (!node.isDollarSignIjParameter()) {
names.add(node.getName());
}
}
@Override
protected void visitFunctionNode(FunctionNode node) {
switch(node.getFunctionName()) {
case "index":
case "isFirst":
case "isLast":
loopVarNames.add(((VarRefNode) node.getChild(0)).getName());
break;
// fall out
default:
}
visitChildren(node);
}
@Override
protected void visitExprNode(ExprNode node) {
if (node instanceof ParentExprNode) {
visitChildren((ParentExprNode) node);
}
}
}.exec(expr);
final StringBuilder templateBody = new StringBuilder();
for (String varName : Sets.difference(names, loopVarNames)) {
SoyType type = typeMap.get(varName);
if (type == null) {
type = UnknownType.getInstance();
}
templateBody.append("{@param " + varName + ": " + type + "}\n");
}
String contents = "{" + soyExpr + "}\n";
for (String loopVar : loopVarNames) {
contents = "{for $" + loopVar + " in [null]}\n" + contents + "\n{/for}";
}
templateBody.append(contents);
return templateBody.toString();
}
Aggregations