Search in sources :

Example 11 with SourceLocation

use of com.google.template.soy.base.SourceLocation in project closure-templates by google.

the class TemplateRegistryTest method testSimple.

@Test
public void testSimple() {
    TemplateRegistry registry = SoyFileSetParserBuilder.forSuppliers(SoyFileSupplier.Factory.create("{namespace ns}\n" + "/** Simple template. */\n" + "{template .foo}\n" + "{/template}\n" + "/** Simple deltemplate. */\n" + "{deltemplate bar.baz}\n" + "{/deltemplate}", SoyFileKind.SRC, "example.soy")).parse().registry();
    assertThatRegistry(registry).containsBasicTemplate("ns.foo").definedAt(new SourceLocation("example.soy", 3, 1, 3, 15));
    assertThatRegistry(registry).doesNotContainBasicTemplate("foo");
    assertThatRegistry(registry).containsDelTemplate("bar.baz").definedAt(new SourceLocation("example.soy", 6, 1, 6, 21));
    assertThatRegistry(registry).doesNotContainDelTemplate("ns.bar.baz");
}
Also used : SourceLocation(com.google.template.soy.base.SourceLocation) Test(org.junit.Test)

Example 12 with SourceLocation

use of com.google.template.soy.base.SourceLocation in project closure-templates by google.

the class TemplateRegistryTest method testDelTemplates.

@Test
public void testDelTemplates() {
    TemplateRegistry registry = SoyFileSetParserBuilder.forSuppliers(SoyFileSupplier.Factory.create("{namespace ns}\n" + "/** Deltemplate. */\n" + "{deltemplate foo.bar}\n" + "{/deltemplate}", SoyFileKind.SRC, "foo.soy"), SoyFileSupplier.Factory.create("{delpackage foo}\n" + "{namespace ns}\n" + "/** Deltemplate. */\n" + "{deltemplate foo.bar}\n" + "{/deltemplate}", SoyFileKind.SRC, "bar.soy")).parse().registry();
    assertThatRegistry(registry).containsDelTemplate("foo.bar").definedAt(new SourceLocation("foo.soy", 3, 1, 3, 21));
    assertThatRegistry(registry).containsDelTemplate("foo.bar").definedAt(new SourceLocation("bar.soy", 4, 1, 4, 21));
}
Also used : SourceLocation(com.google.template.soy.base.SourceLocation) Test(org.junit.Test)

Example 13 with SourceLocation

use of com.google.template.soy.base.SourceLocation 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 14 with SourceLocation

use of com.google.template.soy.base.SourceLocation in project closure-templates by google.

the class SoyMsgBundleImplTest method testBasic.

@Test
public void testBasic() {
    List<SoyMsg> inMsgs = Lists.newArrayList();
    SourceLocation source1 = new SourceLocation("/path/to/source1", 10, 1, 10, 10);
    inMsgs.add(SoyMsg.builder().setId(0x123).setLocaleString("x-zz").setDesc("Boo message.").setSourceLocation(source1).setParts(ImmutableList.<SoyMsgPart>of(SoyMsgRawTextPart.of("Boo!"))).build());
    inMsgs.add(SoyMsg.builder().setId(0xABC).setLocaleString("x-zz").setMeaning("abc").setDesc("").setIsHidden(true).setContentType("text/html").setParts(ImmutableList.<SoyMsgPart>of(SoyMsgRawTextPart.of("Hello, "), new SoyMsgPlaceholderPart("NAME", /* placeholderExample= */
    null), SoyMsgRawTextPart.of("!"))).build());
    SourceLocation source2 = new SourceLocation("/path/to/source2", 20, 1, 20, 10);
    inMsgs.add(SoyMsg.builder().setId(0x123).setLocaleString("x-zz").setDesc("Boo message 2.").setIsHidden(false).setSourceLocation(source2).setParts(ImmutableList.<SoyMsgPart>of(SoyMsgRawTextPart.of("Boo 2!"))).build());
    SoyMsgBundle msgBundle = new SoyMsgBundleImpl("x-zz", inMsgs);
    assertThat(msgBundle.getLocaleString()).isEqualTo("x-zz");
    assertThat(msgBundle.isRtl()).isFalse();
    assertThat(msgBundle).hasSize(2);
    List<SoyMsg> outMsgs = Lists.newArrayList();
    for (SoyMsg msg : msgBundle) {
        outMsgs.add(msg);
    }
    assertThat(outMsgs).hasSize(2);
    SoyMsg booMsg = msgBundle.getMsg(0x123);
    assertThat(outMsgs.get(0)).isEqualTo(booMsg);
    assertThat(booMsg.getId()).isEqualTo(0x123);
    assertThat(booMsg.getLocaleString()).isEqualTo("x-zz");
    assertThat(booMsg.getMeaning()).isEqualTo(null);
    assertThat(booMsg.getDesc()).isEqualTo("Boo message.");
    assertThat(booMsg.isHidden()).isFalse();
    assertThat(booMsg.getContentType()).isEqualTo(null);
    assertThat(booMsg.getSourceLocations()).hasSize(2);
    assertThat(booMsg.getSourceLocations()).containsExactly(source1, source2);
    List<SoyMsgPart> booMsgParts = booMsg.getParts();
    assertThat(booMsgParts).hasSize(1);
    assertThat(((SoyMsgRawTextPart) booMsgParts.get(0)).getRawText()).isEqualTo("Boo!");
    SoyMsg helloMsg = msgBundle.getMsg(0xABC);
    assertThat(outMsgs.get(1)).isEqualTo(helloMsg);
    assertThat(helloMsg.getId()).isEqualTo(0xABC);
    assertThat(helloMsg.getLocaleString()).isEqualTo("x-zz");
    assertThat(helloMsg.getMeaning()).isEqualTo("abc");
    assertThat(helloMsg.getDesc()).isEmpty();
    assertThat(helloMsg.isHidden()).isTrue();
    assertThat(helloMsg.getContentType()).isEqualTo("text/html");
    assertThat(helloMsg.getSourceLocations()).isEmpty();
    List<SoyMsgPart> helloMsgParts = helloMsg.getParts();
    assertThat(helloMsgParts).hasSize(3);
    assertThat(((SoyMsgRawTextPart) helloMsgParts.get(0)).getRawText()).isEqualTo("Hello, ");
    assertThat(((SoyMsgPlaceholderPart) helloMsgParts.get(1)).getPlaceholderName()).isEqualTo("NAME");
    assertThat(((SoyMsgRawTextPart) helloMsgParts.get(2)).getRawText()).isEqualTo("!");
}
Also used : SourceLocation(com.google.template.soy.base.SourceLocation) SoyMsgBundle(com.google.template.soy.msgs.SoyMsgBundle) Test(org.junit.Test)

Example 15 with SourceLocation

use of com.google.template.soy.base.SourceLocation in project closure-templates by google.

the class VeLogInstrumentationVisitor method visitHtmlAttributeNode.

/**
 * For HtmlAttributeNode that has a logging function as its value, replace the logging function
 * with its place holder, and append a new data attribute that contains all the desired
 * information that are used later by the runtime library.
 */
@Override
protected void visitHtmlAttributeNode(HtmlAttributeNode node) {
    // Skip attributes that do not have a value.
    if (!node.hasValue()) {
        return;
    }
    SourceLocation insertionLocation = node.getSourceLocation();
    for (FunctionNode function : SoyTreeUtils.getAllNodesOfType(node, FunctionNode.class)) {
        if (!(function.getSoyFunction() instanceof LoggingFunction)) {
            continue;
        }
        FunctionNode funcNode = new FunctionNode(VeLogJsSrcLoggingFunction.INSTANCE, insertionLocation);
        funcNode.addChild(new StringNode(function.getFunctionName(), QuoteStyle.SINGLE, insertionLocation));
        funcNode.addChild(new ListLiteralNode(function.getChildren(), insertionLocation));
        StandaloneNode attributeName = node.getChild(0);
        if (attributeName instanceof RawTextNode) {
            // If attribute name is a plain text, directly pass it as a function argument.
            funcNode.addChild(new StringNode(((RawTextNode) attributeName).getRawText(), QuoteStyle.SINGLE, insertionLocation));
        } else {
            // Otherwise wrap the print node or call node into a let block, and use the let variable
            // as a function argument.
            String varName = "soy_logging_function_attribute_" + counter;
            LetContentNode letNode = LetContentNode.forVariable(nodeIdGen.genId(), attributeName.getSourceLocation(), varName, null);
            // Adds a let var which references to the original attribute name, and move the name to
            // the let block.
            node.replaceChild(attributeName, new PrintNode(nodeIdGen.genId(), insertionLocation, /* isImplicit= */
            true, /* expr= */
            new VarRefNode(varName, insertionLocation, false, letNode.getVar()), /* attributes= */
            ImmutableList.of(), ErrorReporter.exploding()));
            letNode.addChild(attributeName);
            node.getParent().addChild(node.getParent().getChildIndex(node), letNode);
            funcNode.addChild(new VarRefNode(varName, insertionLocation, false, letNode.getVar()));
        }
        funcNode.addChild(new IntegerNode(counter++, insertionLocation));
        PrintNode loggingFunctionAttribute = new PrintNode(nodeIdGen.genId(), insertionLocation, /* isImplicit= */
        true, /* expr= */
        funcNode, /* attributes= */
        ImmutableList.of(), ErrorReporter.exploding());
        // Append the logging function attribute to its parent
        int appendIndex = node.getParent().getChildIndex(node) + 1;
        node.getParent().addChild(appendIndex, loggingFunctionAttribute);
        // Replace the original attribute value to the placeholder.
        HtmlAttributeValueNode placeHolder = new HtmlAttributeValueNode(nodeIdGen.genId(), insertionLocation, Quotes.DOUBLE);
        placeHolder.addChild(new RawTextNode(nodeIdGen.genId(), ((LoggingFunction) function.getSoyFunction()).getPlaceholder(), insertionLocation));
        node.replaceChild(node.getChild(1), placeHolder);
        // logging function in a html attribute value.
        break;
    }
    visitChildren(node);
}
Also used : SourceLocation(com.google.template.soy.base.SourceLocation) ListLiteralNode(com.google.template.soy.exprtree.ListLiteralNode) IntegerNode(com.google.template.soy.exprtree.IntegerNode) FunctionNode(com.google.template.soy.exprtree.FunctionNode) StandaloneNode(com.google.template.soy.soytree.SoyNode.StandaloneNode) VarRefNode(com.google.template.soy.exprtree.VarRefNode) StringNode(com.google.template.soy.exprtree.StringNode) LoggingFunction(com.google.template.soy.logging.LoggingFunction) PrintNode(com.google.template.soy.soytree.PrintNode) RawTextNode(com.google.template.soy.soytree.RawTextNode) LetContentNode(com.google.template.soy.soytree.LetContentNode) HtmlAttributeValueNode(com.google.template.soy.soytree.HtmlAttributeValueNode)

Aggregations

SourceLocation (com.google.template.soy.base.SourceLocation)23 Test (org.junit.Test)8 VarRefNode (com.google.template.soy.exprtree.VarRefNode)5 TemplateNode (com.google.template.soy.soytree.TemplateNode)4 IntegerNode (com.google.template.soy.exprtree.IntegerNode)3 Matcher (java.util.regex.Matcher)3 CharMatcher (com.google.common.base.CharMatcher)2 ExprNode (com.google.template.soy.exprtree.ExprNode)2 FunctionNode (com.google.template.soy.exprtree.FunctionNode)2 NullNode (com.google.template.soy.exprtree.NullNode)2 HtmlOpenTagNode (com.google.template.soy.soytree.HtmlOpenTagNode)2 PrintNode (com.google.template.soy.soytree.PrintNode)2 RawTextNode (com.google.template.soy.soytree.RawTextNode)2 TemplateParam (com.google.template.soy.soytree.defn.TemplateParam)2 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 ImmutableSet (com.google.common.collect.ImmutableSet)1 Point (com.google.template.soy.base.SourceLocation.Point)1 Identifier (com.google.template.soy.base.internal.Identifier)1 SanitizedContentKind (com.google.template.soy.base.internal.SanitizedContentKind)1