Package com.google.caja.parser

Examples of com.google.caja.parser.ParseTreeNodeContainer


        + "  args = @varArgsDestructuring(args);"
        + "  return [ @unwraps* ];"
        + "}",
        "arityCheck", getArityCheck(m),
        "varArgsDestructuring", getVarArgsDestructuring(m),
        "unwraps", new ParseTreeNodeContainer(unwraps));
  }
View Full Code Here


              + "var @handlerName = ___./*@synthetic*/markFuncFreeze("
              + "    /*@synthetic*/function ("
              + "        event, " + ReservedNames.THIS_NODE + ") { @body*; });",
              "handlerName", SyntheticNodes.s(
                  new Identifier(FilePosition.UNKNOWN, handlerFnName)),
              "body", new ParseTreeNodeContainer(b.children()));
          handlers.add(new EventHandler(attr.env, handler));
          handlerCache.put(value, handlerFnName);
        }

        FunctionConstructor eventAdapter
            = (FunctionConstructor) QuasiBuilder.substV(
            ""
            + "(/*@synthetic*/ function (event) {"
            + "  return /*@synthetic*/ (___.plugin_dispatchEvent___("
            + "      /*@synthetic*/this, event, "
            + "      ___./*@synthetic*/getId(IMPORTS___), @tail));"
            + "})",
            "tail", new Reference(SyntheticNodes.s(
                new Identifier(pos, handlerFnName))));
        eventAdapter.setFilePosition(pos);
        eventAdapter.getAttributes().set(HANDLER_NAME, handlerFnName);
        dynamicValue = eventAdapter;
        break;
      case STYLE:
        CssTree.DeclarationGroup decls = styleFromAttrib(attr);
        if (decls == null || decls.children().isEmpty()) {
          return noResult(attr);
        }

        // The validator will check that property values are well-formed,
        // marking those that aren't, and identifies all URLs.
        CssValidator v = new CssValidator(cssSchema, htmlSchema, mq)
            .withInvalidNodeMessageLevel(MessageLevel.WARNING);
        v.validateCss(AncestorChain.instance(decls));
        // The rewriter will remove any unsafe constructs.
        // and put URLs in the proper filename namespace
        new CssRewriter(meta.getUriPolicy(), cssSchema, htmlSchema, mq)
            .withInvalidNodeMessageLevel(MessageLevel.WARNING)
            .rewrite(AncestorChain.instance(decls));
        new CssDynamicExpressionRewriter(meta).rewriteCss(decls);
        ArrayConstructor jsValue = CssDynamicExpressionRewriter.cssToJs(decls);

        if (jsValue.children().size() == 0) {
          // No declarations remain after sanitizing
          return noResult(attr);
        } else if (jsValue.children().size() == 1) {
          // Declarations have been reduced to a single, statically known
          // StringLiteral or dynamically computed Expression
          dynamicValue = jsValue.children().get(0);
        } else {
          throw new SomethingWidgyHappenedError(
              "Rewriter thinks STYLE attribute should contain plugin ID");
        }
        break;
      case URI:
        if (attributeContent.containsKey(attr.src)) {  // A javascript: URI
          Block b = this.jsFromAttrib(attr);
          if (b == null || b.children().isEmpty()) { return noResult(attr); }

          String handlerIndexName = meta.generateUniqueName("c");
          Identifier handlerIndex = SyntheticNodes.s(new Identifier(
              FilePosition.UNKNOWN, handlerIndexName));
          Statement handler = (Statement) QuasiBuilder.substV(
              ""
              + "var @handlerIndex = IMPORTS___.handlers___.push("
              + "    ___./*@synthetic*/markFuncFreeze("
              // There is no node or event object available to code in
              // javascript: URIs.
              + "        /*@synthetic*/function () { @body*; })) - 1;",
              "handlerIndex", handlerIndex,
              "body", new ParseTreeNodeContainer(b.children()));
          handlers.add(new EventHandler(attr.env, handler));
          handlerCache.put(value, handlerIndexName);

          Operation urlAdapter = (Operation) QuasiBuilder.substV(
              ""
View Full Code Here

    }
    return new ExpressionStmt(unk,
        (Expression) QuasiBuilder.substV(
            "html4.@i = { @k*: @v* };",
            "i", new Reference(new Identifier(unk, key)),
            "k", new ParseTreeNodeContainer(keys),
            "v", new ParseTreeNodeContainer(values)));
  }
View Full Code Here

        }
      }
      definitions.appendChild(new ExpressionStmt(unk, (Expression)
          QuasiBuilder.substV(
              "html4.ATTRIBS = { @k*: @v* };",
              "k", new ParseTreeNodeContainer(keys),
              "v", new ParseTreeNodeContainer(values))));
    }

    definitions.appendChild(mapFromEnum(
        EnumSet.allOf(EFlag.class),
        "eflags",
        new Function<EFlag, String>() {
          public String apply(EFlag f) {
            return f.name();
          }
        },
        new Function<EFlag, Integer>() {
          public Integer apply(EFlag f) {
            return f.bitMask;
          }
        })
    );

    {
      List<StringLiteral> keys = new ArrayList<StringLiteral>();
      List<IntegerLiteral> values = new ArrayList<IntegerLiteral>();
      for (Map.Entry<ElKey, EnumSet<EFlag>> e : eflags.entrySet()) {
        ElKey key = e.getKey();
        int value = 0;
        for (EFlag f : e.getValue()) { value |= f.bitMask; }
        keys.add(StringLiteral.valueOf(unk, key.toString()));
        values.add(new IntegerLiteral(unk, value));
      }
      definitions.appendChild(new ExpressionStmt(unk, (Expression)
          QuasiBuilder.substV(
              "html4.ELEMENTS = { @k*: @v* };",
              "k", new ParseTreeNodeContainer(keys),
              "v", new ParseTreeNodeContainer(values))));
    }

    definitions.appendChild(mapFromEnum(
        EnumSet.allOf(UriEffect.class),
        "ueffects",
View Full Code Here

    }
    if (scope.hasFreeThis()) {
      stmts.add(QuasiBuilder.substV(
          "var dis___ = (this && this.___) ? void 0 : this;"));
    }
    return new ParseTreeNodeContainer(stmts);
  }
View Full Code Here

    } 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);
View Full Code Here

  }

  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")))),
        "boo", new IntegerLiteral(FilePosition.UNKNOWN, 2));
    assertEquals(
        render(jsExpr(fromString("{ foo: 0, bar: 1, baz: 2 }"))),
        render(n));
View Full Code Here

  public final void testStartStatementsForParseTreeNodeContainer()
      throws Exception {
    Scope s0 = fromProgram(js(fromString("{}")));
    Scope s1 = Scope.fromParseTreeNodeContainer(
        s0,
        new ParseTreeNodeContainer(new ArrayList<ParseTreeNode>()));

    assertEquals(0, s0.getStartStatements().size());
    assertEquals(0, s1.getStartStatements().size());

    s1.addStartStatement(js(fromString("{}")));
View Full Code Here

          } else {
            s2 = Scope.fromPlainBlock(scope);
          }
          return QuasiBuilder.substV(
              "@startStmts*; @body*;",
              "startStmts", new ParseTreeNodeContainer(s2.getStartStatements()),
              "body", expandAll(
                  new ParseTreeNodeContainer(node.children()), s2));
        }
        return NONE;
      }
    });
    w.addRule(new Rule() {
      @Override
      @RuleDescription(
          name="fnDeclarations",
          reason="function declarations contain function constructors but don't"
              + " have the same discrepencies on IE 6 as function constructors",
          synopsis="")
      public ParseTreeNode fire(ParseTreeNode node, Scope scope) {
        if (node instanceof FunctionDeclaration) {
          FunctionDeclaration decl = ((FunctionDeclaration) node);
          FunctionConstructor ctor = decl.getInitializer();

          Scope s2 = Scope.fromFunctionConstructor(scope, ctor);
          FunctionConstructor rewritten
              = (FunctionConstructor) QuasiBuilder.substV(
                  "function @ident(@formals*) { @stmts*; @body*; }",
                  "ident", ctor.getIdentifier(),
                  "formals", expandAll(
                      new ParseTreeNodeContainer(ctor.getParams()), s2),
                  "stmts", new ParseTreeNodeContainer(s2.getStartStatements()),
                  "body", expandAll(
                      new ParseTreeNodeContainer(ctor.getBody().children()), s2)
                  );
          return new FunctionDeclaration(rewritten);
        }
        return NONE;
      }
    });
    w.addRule(new Rule() {
      @Override
      @RuleDescription(
          name="ie6functions",
          reason="simulate IE 6's broken scoping of function constructors as "
              + "described in JScript Deviations Section 2.3",
          synopsis="")
      public ParseTreeNode fire(ParseTreeNode node, Scope scope) {
        if (node instanceof FunctionConstructor) {
          FunctionConstructor ctor = (FunctionConstructor) node;
          Scope s2 = Scope.fromFunctionConstructor(scope, ctor);
          if (ctor.getIdentifierName() == null) {
            return expandAll(node, s2);
          }
          Identifier ident = ctor.getIdentifier();
          Reference identRef = new Reference(ident);
          identRef.setFilePosition(ident.getFilePosition());
          scope.addStartStatement(
              new Declaration(FilePosition.UNKNOWN, ident, identRef));
          return QuasiBuilder.substV(
              "(@var = function @ident(@formals*) { @stmts*; @body*; })",
              "var", identRef,
              "ident", ident,
              "formals", new ParseTreeNodeContainer(ctor.getParams()),
              "stmts", new ParseTreeNodeContainer(s2.getStartStatements()),
              "body", expandAll(
                  new ParseTreeNodeContainer(ctor.getBody().children()), s2)
              );
        }
        return NONE;
      }
    });
View Full Code Here

              + "var @handlerName = ___./*@synthetic*/markFuncFreeze("
              + "    /*@synthetic*/function ("
              + "        event, " + ReservedNames.THIS_NODE + ") { @body*; });",
              "handlerName", SyntheticNodes.s(
                  new Identifier(FilePosition.UNKNOWN, handlerFnName)),
              "body", new ParseTreeNodeContainer(b.children()));
          handlers.add(new EventHandler(attr.env, handler));
          handlerCache.put(value, handlerFnName);
        }

        FunctionConstructor eventAdapter
            = (FunctionConstructor) QuasiBuilder.substV(
            ""
            + "(/*@synthetic*/ function (event) {"
            + "  return /*@synthetic*/ (___.plugin_dispatchEvent___("
            + "      /*@synthetic*/this, event, "
            + "      ___./*@synthetic*/getId(IMPORTS___), @tail));"
            + "})",
            "tail", new Reference(SyntheticNodes.s(
                new Identifier(pos, handlerFnName))));
        eventAdapter.setFilePosition(pos);
        eventAdapter.getAttributes().set(HANDLER_NAME, handlerFnName);
        dynamicValue = eventAdapter;
        break;
      case STYLE:
        CssTree.DeclarationGroup decls = styleFromAttrib(attr);
        if (decls == null || decls.children().isEmpty()) {
          return noResult(attr);
        }

        // The validator will check that property values are well-formed,
        // marking those that aren't, and identifies all URLs.
        CssValidator v = new CssValidator(cssSchema, htmlSchema, mq)
            .withInvalidNodeMessageLevel(MessageLevel.WARNING);
        v.validateCss(AncestorChain.instance(decls));
        // The rewriter will remove any unsafe constructs.
        // and put URLs in the proper filename namespace
        new CssRewriter(meta.getUriPolicy(), cssSchema, mq)
            .withInvalidNodeMessageLevel(MessageLevel.WARNING)
            .rewrite(AncestorChain.instance(decls));
        new CssDynamicExpressionRewriter(meta).rewriteCss(decls);
        ArrayConstructor jsValue = CssDynamicExpressionRewriter.cssToJs(decls);

        if (jsValue.children().size() == 0) {
          // No declarations remain after sanitizing
          return noResult(attr);
        } else if (jsValue.children().size() == 1) {
          // Declarations have been reduced to a single, statically known
          // StringLiteral or dynamically computed Expression
          dynamicValue = jsValue.children().get(0);
        } else {
          throw new SomethingWidgyHappenedError(
              "Rewriter thinks STYLE attribute should contain plugin ID");
        }
        break;
      case URI:
        if (attributeContent.containsKey(attr.src)) {  // A javascript: URI
          Block b = this.jsFromAttrib(attr);
          if (b == null || b.children().isEmpty()) { return noResult(attr); }

          String handlerIndexName = meta.generateUniqueName("c");
          Identifier handlerIndex = SyntheticNodes.s(new Identifier(
              FilePosition.UNKNOWN, handlerIndexName));
          Statement handler = (Statement) QuasiBuilder.substV(
              ""
              + "var @handlerIndex = IMPORTS___.handlers___.push("
              + "    ___./*@synthetic*/markFuncFreeze("
              // There is no node or event object available to code in
              // javascript: URIs.
              + "        /*@synthetic*/function () { @body*; })) - 1;",
              "handlerIndex", handlerIndex,
              "body", new ParseTreeNodeContainer(b.children()));
          handlers.add(new EventHandler(attr.env, handler));
          handlerCache.put(value, handlerIndexName);

          Operation urlAdapter = (Operation) QuasiBuilder.substV(
              ""
View Full Code Here

TOP

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

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.