Search in sources :

Example 16 with ExprNode

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();
}
Also used : SourceLocation(com.google.template.soy.base.SourceLocation) ExprNode(com.google.template.soy.exprtree.ExprNode) PrimitiveNode(com.google.template.soy.exprtree.ExprNode.PrimitiveNode) PrimitiveData(com.google.template.soy.data.restricted.PrimitiveData) ErrorReporter(com.google.template.soy.error.ErrorReporter) VarRefNode(com.google.template.soy.exprtree.VarRefNode) Matcher(java.util.regex.Matcher) BufferedReader(java.io.BufferedReader) GlobalNode(com.google.template.soy.exprtree.GlobalNode)

Example 17 with ExprNode

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);
}
Also used : ExprNode(com.google.template.soy.exprtree.ExprNode) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) SoyFunction(com.google.template.soy.shared.restricted.SoyFunction) FunctionNode(com.google.template.soy.exprtree.FunctionNode) PrintNode(com.google.template.soy.soytree.PrintNode)

Example 18 with ExprNode

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);
}
Also used : ExprNode(com.google.template.soy.exprtree.ExprNode)

Example 19 with ExprNode

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);
    }
}
Also used : ExprNode(com.google.template.soy.exprtree.ExprNode) PyExpr(com.google.template.soy.pysrc.restricted.PyExpr) SoyFileSetNode(com.google.template.soy.soytree.SoyFileSetNode) PrintNode(com.google.template.soy.soytree.PrintNode)

Example 20 with ExprNode

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();
}
Also used : ParentExprNode(com.google.template.soy.exprtree.ExprNode.ParentExprNode) ExprNode(com.google.template.soy.exprtree.ExprNode) ParentExprNode(com.google.template.soy.exprtree.ExprNode.ParentExprNode) VarRefNode(com.google.template.soy.exprtree.VarRefNode) SoyType(com.google.template.soy.types.SoyType) FunctionNode(com.google.template.soy.exprtree.FunctionNode) HashSet(java.util.HashSet)

Aggregations

ExprNode (com.google.template.soy.exprtree.ExprNode)38 ParentExprNode (com.google.template.soy.exprtree.ExprNode.ParentExprNode)7 IntegerNode (com.google.template.soy.exprtree.IntegerNode)7 StringNode (com.google.template.soy.exprtree.StringNode)7 FunctionNode (com.google.template.soy.exprtree.FunctionNode)5 Test (org.junit.Test)5 ImmutableList (com.google.common.collect.ImmutableList)4 SoyValue (com.google.template.soy.data.SoyValue)4 GlobalNode (com.google.template.soy.exprtree.GlobalNode)4 VarRefNode (com.google.template.soy.exprtree.VarRefNode)4 CodeChunk (com.google.template.soy.jssrc.dsl.CodeChunk)4 SoyType (com.google.template.soy.types.SoyType)4 LinkedHashMap (java.util.LinkedHashMap)4 AbstractParentExprNode (com.google.template.soy.exprtree.AbstractParentExprNode)3 FloatNode (com.google.template.soy.exprtree.FloatNode)3 SourceLocation (com.google.template.soy.base.SourceLocation)2 ErrorReporter (com.google.template.soy.error.ErrorReporter)2 BooleanNode (com.google.template.soy.exprtree.BooleanNode)2 PrimitiveNode (com.google.template.soy.exprtree.ExprNode.PrimitiveNode)2 ExprRootNode (com.google.template.soy.exprtree.ExprRootNode)2