Package com.google.caja.parser

Examples of com.google.caja.parser.ParseTreeNode


    if ("javascript".equals(language) && "concat".equals(rendererType)) {
      return concat(inputs, output, logger);
    }

    boolean passed = true;
    ParseTreeNode outputJs;
    Node outputHtml;
    if ("caja".equals(language)) {
      PluginMeta meta = new PluginMeta(fetcher, policy);
      meta.setPrecajoleMinify("minify".equals(rendererType));
      PluginCompiler compiler = new PluginCompiler(
          BuildInfo.getInstance(), meta, mq);
      compiler.setMessageContext(mc);
      if (Boolean.TRUE.equals(options.get("debug"))) {
        compiler.setGoals(compiler.getGoals()
            .without(PipelineMaker.ONE_CAJOLED_MODULE)
            .with(PipelineMaker.ONE_CAJOLED_MODULE_DEBUG));
      }
      if (Boolean.TRUE.equals(options.get("onlyJsEmitted"))) {
        compiler.setGoals(
            compiler.getGoals().without(PipelineMaker.HTML_SAFE_STATIC));
      }

      // Parse inputs
      for (File f : inputs) {
        try {
          URI fileUri = f.getCanonicalFile().toURI();
          ParseTreeNode parsedInput = new ParserContext(mq)
              .withInput(new InputSource(fileUri))
              .withConfig(meta)
              .build();
          if (parsedInput == null) {
            passed = false;
          } else {
            compiler.addInput(parsedInput, fileUri);
          }
        } catch (IOException ex) {
          logger.println("Failed to read " + f);
          passed = false;
        } catch (ParseException ex) {
          logger.println("Failed to parse " + f);
          ex.toMessageQueue(mq);
          passed = false;
        } catch (IllegalStateException e) {
          logger.println("Failed to configure parser " + e.getMessage());
          passed = false;
        }
      }

      // Cajole
      passed = passed && compiler.run();

      outputJs = passed ? compiler.getJavascript() : null;
      outputHtml = passed ? compiler.getStaticHtml() : null;
    } else if ("javascript".equals(language)) {
      PluginMeta meta = new PluginMeta(fetcher, policy);
      passed = true;
      JsOptimizer optimizer = new JsOptimizer(mq);
      for (File f : inputs) {
        try {
          if (f.getName().endsWith(".env.json")) {
            loadEnvJsonFile(f, optimizer, mq);
          } else {
            ParseTreeNode parsedInput = new ParserContext(mq)
            .withInput(new InputSource(f.getCanonicalFile().toURI()))
            .withConfig(meta)
            .build();
            if (parsedInput != null) {
              optimizer.addInput((Statement) parsedInput);
View Full Code Here


   * emit its value to a variable "moduleResult___" so that it can used as
   * the result of module loading.
   */
  @SuppressWarnings("unchecked")
  public ParseTreeNode returnLast(ParseTreeNode node) {
    ParseTreeNode result = null;
    // Code translated from another language should not be used as the module
    // result.
    if (isForSideEffect(node)) { return node; }
    if (node instanceof ExpressionStmt) {
      result = new ExpressionStmt(
          node.getFilePosition(),
          (Expression) QuasiBuilder.substV(
              "moduleResult___ = @result;",
              "result", ((ExpressionStmt) node).getExpression()));
    } else if (node instanceof ParseTreeNodeContainer) {
      List<ParseTreeNode> nodes = Lists.newArrayList(node.children());
      int lasti = lastRealJavascriptChild(nodes);
      if (lasti >= 0) {
        nodes.set(lasti, returnLast(nodes.get(lasti)));
        result = new ParseTreeNodeContainer(nodes);
      }
    } else if (node instanceof Block) {
      List<Statement> stats = Lists.newArrayList();
      stats.addAll((Collection<? extends Statement>) node.children());
      int lasti = lastRealJavascriptChild(stats);
      if (lasti >= 0) {
        stats.set(lasti, (Statement) returnLast(stats.get(lasti)));
        result = new Block(node.getFilePosition(), stats);
      }
    } else if (node instanceof Conditional) {
      List<ParseTreeNode> nodes = Lists.newArrayList();
      nodes.addAll(node.children());
      int lasti = nodes.size() - 1;
      for (int i = 1; i <= lasti; i += 2) {  // Even are conditions.
        nodes.set(i, returnLast(nodes.get(i)));
      }
      if ((lasti & 1) == 0) {  // else clause
        nodes.set(lasti, returnLast(nodes.get(lasti)));
      }
      result = new Conditional(node.getFilePosition(), null, nodes);
    } else if (node instanceof TryStmt) {
      TryStmt tryer = (TryStmt) node;
      result = new TryStmt(
          node.getFilePosition(),
          (Block) returnLast(tryer.getBody()),
          tryer.getCatchClause(),
          tryer.getFinallyClause());
    }
    if (null == result) { return node; }
    result.getAttributes().putAll(node.getAttributes());
    return result;
  }
View Full Code Here

        "function @a() { @b.@c = @d; @e = @f; }");
    assertTrue(n instanceof SimpleQuasiNode);
  }

  public final void testMultiProps() throws Exception {
    ParseTreeNode n = QuasiBuilder.substV(
        "({ '@k*': @v*, baz: @boo })",
        "k", new ParseTreeNodeContainer(Arrays.asList(
            jsExpr(fromString("'foo'")), jsExpr(fromString("'bar'")))),
        "v", new ParseTreeNodeContainer(Arrays.asList(
            jsExpr(fromString("0")), jsExpr(fromString("1")))),
View Full Code Here

        render(jsExpr(fromString("{ foo: 0, bar: 1, baz: 2 }"))),
        render(n));
  }

  public final void testPropKeys() throws Exception {
    ParseTreeNode n = QuasiBuilder.substV(
        "({ @a: @b, '\\@c': @d })",
        "a", StringLiteral.valueOf(FilePosition.UNKNOWN, "a"),
        "b", StringLiteral.valueOf(FilePosition.UNKNOWN, "b"),
        "c", StringLiteral.valueOf(FilePosition.UNKNOWN, "c"),
        "d", StringLiteral.valueOf(FilePosition.UNKNOWN, "d"));
View Full Code Here

  }

  public final void testIdsWithUnderscores() throws Exception {
    String[] underscoreIds = {"x__", "x\u005f\u005f", "__", "\u005f\u005f" };
    for (String id : underscoreIds) {
      ParseTreeNode specimen = QuasiBuilder.substV(
          "{ var @idWithUnderscore = 1; }",
          "idWithUnderscore", new Identifier(FilePosition.UNKNOWN, id)
      );
      assertTrue("Valid id failed to parse: " + id,
          QuasiBuilder.match("{ var @x__ = 1; }", specimen));
View Full Code Here

  private static void showTree(
      String specimenText,
      String matchPatternText,
      String substPatternText) throws Exception {
    ParseTreeNode specimen = parse(specimenText);
    QuasiNode matchPattern = QuasiBuilder.parseQuasiNode(
        new InputSource(URI.create("built-in:///js-quasi-literals")),
        matchPatternText);
    QuasiNode substPattern = QuasiBuilder.parseQuasiNode(
        new InputSource(URI.create("built-in:///js-quasi-literals")),
        substPatternText);

    System.out.println("specimen = " + format(specimen));
    System.out.println("matchPattern = " + format(matchPattern));
    System.out.println("substPattern = " + format(substPattern));

    if (specimen.children().size() != 1)
      throw new Exception("Top level of specimen does not have exactly 1 child");

    Map<String, ParseTreeNode> matchResult =
      matchPattern.match(specimen.children().get(0));

    System.out.println(
        (matchResult == null) ?
        "match failed" :
        "matchResult = " + format(matchResult));

    if (matchResult == null) return;

    ParseTreeNode substResult = substPattern.substitute(matchResult);

    System.out.println(
        (substResult == null) ?
        "subst failed" :
        "substResult = " + format(substResult));
View Full Code Here

        + "  for (var i = 0, n = arr.length; i < n; ++i) {\n"
        + "    f(arr[i]);\n"
        + "  }\n"
        + "}"));
    ArrayIndexOptimization.optimize(b);
    ParseTreeNode golden = js(fromString(
        ""
        + "function map(f, arr) {\n"
        + "  for (var i = 0, n = arr.length; i < n; ++i) {\n"
        + "    f(arr[+i]);\n"
        + "  }\n"
View Full Code Here

  }

  public void checkReferenceChains() throws Exception {
    Block b = js(fromString(REFERENCE_EXAMPLE));
    ArrayIndexOptimization.optimize(b);
    ParseTreeNode golden = js(fromString(
        ""
        + "function map(f, arr) {\n"
        + "  for (var i = 0, n = arr.length; i < n; ++i) {\n"
        + "    f(arr[+i]);\n"
        + "  }\n"
View Full Code Here

        ""
        + "function lastOf(arr) {\n"
        + "  return arr[arr.length - 1];\n"
        + "}"));
    ArrayIndexOptimization.optimize(b);
    ParseTreeNode golden = js(fromString(
        ""
        + "function lastOf(arr) {\n"
        + "  return arr[+(arr.length - 1)];\n"
        + "}"));
    assertEquals(render(golden), render(b));
View Full Code Here

        + "    s += arr[i];"
        + "  }"
        + "}"
        + "join(myArray[foo + bar]);"));
    ArrayIndexOptimization.optimize(b);
    ParseTreeNode golden = js(fromString(
        ""
        + "function join(arr, sep) {\n"
        + "  var s = '';\n"
        + "  for (var i = 0; i < arr.length; i++) {"
        + "    if (s && arr[+(i + 1)]) { s += sep; }"
View Full Code Here

TOP

Related Classes of com.google.caja.parser.ParseTreeNode

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.