Package com.google.caja.parser

Examples of com.google.caja.parser.ParseTreeNode


  @Override
  protected void childrenChanged() {
    super.childrenChanged();
    List<? extends ParseTreeNode> children = children();
    ParseTreeNode valueExpr = children.get(0);
    if (!(valueExpr instanceof Expression)) {
      throw new ClassCastException(
          "Expected " + Expression.class.getName() + " not "
          + valueExpr.getClass().getName());
    }
    for (ParseTreeNode node : children.subList(1, children.size())) {
      if (!(node instanceof SwitchCase)) {
        throw new ClassCastException(
            "Expected " + SwitchCase.class.getName() + " not "
View Full Code Here


    if (args.length % 2 != 0) {
      throw new SomethingWidgyHappenedError("Wrong # of args for subst()");
    }
    Map<String, ParseTreeNode> bindings = makeBindings();
    for (int i = 0; i < args.length; i += 2) {
      ParseTreeNode value = (ParseTreeNode) args[i + 1];
      if (value != null) {
        // TODO(felix8a): can't do this because of ArrayIndexOptimization
        //value.makeImmutable();
      }
      bindings.put((String) args[i], value);
    }
    ParseTreeNode result = subst(patternText, bindings);
    if (result == null) {
      throw new NullPointerException(
          "'" + patternText + "' > " + bindings.keySet());
    }
    return result;
View Full Code Here

  public static QuasiNode parseQuasiNode(
      InputSource inputSource, String pattern)
      throws ParseException {
    // The top-level node returned from the parser is always a Block.
    Block topLevelBlock = (Block) parse(inputSource, pattern);
    ParseTreeNode topLevelNode = topLevelBlock;

    // If the top-level Block contains a single child, promote it to allow it to
    // match anywhere.
    if (topLevelNode.children().size() == 1) {
      topLevelNode = topLevelNode.children().get(0);
    }

    // If the top level is an ExpressionStmt, with one child, then promote its
    // single child to the top level to allow the contained expression to match
    // anywhere.
    if (topLevelNode instanceof ExpressionStmt) {
      topLevelNode = topLevelNode.children().get(0);
    }

    // If the top level is a FunctionDeclaration, promote its single child to
    // the top level to allow the contained FunctionConstructor to match in any
    // context.
View Full Code Here

  private static boolean attachScopes(AncestorChain<?> ac, ScopeInfo scope) {
    // We infect scopes root-wards if we see a problematic construct like
    // "eval" or "with" which would change behavior if variables in scope where
    // it is declared were renamed.
    boolean infected = false;
    ParseTreeNode n = ac.node;
    n.getAttributes().set(SCOPE, scope);
    if (n instanceof FunctionConstructor) {
      FunctionConstructor fc = (FunctionConstructor) n;
      scope = new ScopeInfo(scope, Scope.fromFunctionConstructor(scope.s, fc));
      if (fc.getIdentifierName() != null) {
        scope.fns.add(ac.cast(FunctionConstructor.class));
      }
      // A ctor's name is apparent in its scope, unlike a fn declarations name
      // which is apparent in the containing scope.
      n.getAttributes().set(SCOPE, scope);
    } else if (n instanceof CatchStmt) {
      CatchStmt cs = (CatchStmt) n;
      scope = new ScopeInfo(scope, Scope.fromCatchStmt(scope.s, cs));
      // Normally, declaration in a catch block are hoisted to the parent.
      // Since the logic below does that, make sure that the exception
      // declaration is not hoisted.
      scope.decls.add(AncestorChain.instance(ac, cs.getException()));
      cs.getException().getAttributes().set(SCOPE, scope);
      // And recurse to the body manually so as to avoid recursing to the
      // exception declaration.
      attachScopes(AncestorChain.instance(ac, cs.getBody()), scope);
      return false;
    } else if (n instanceof Reference) {
      Reference r = (Reference) n;
      String rName = r.getIdentifierName();
      Scope definingScope = scope.s.thatDefines(rName);
      assert (definingScope != null) || scope.s.isOuter(rName) : rName;
      scope.uses.add(new Use(scope.withScope(definingScope), rName));
      if ("eval".equals(rName)) { infected = true; }
      infected = infected || "eval".equals(rName);
    } else if (n instanceof Declaration) {
      ScopeInfo declaring = scope;
      // Hoist out of catch block scopes.
      while (declaring.s.getType() == ScopeType.CATCH) {
        declaring = declaring.parent;
      }
      declaring.decls.add(ac.cast(Declaration.class));
    } else if (n instanceof WithStmt) {
      // References inside with(...){} could be variable names or they could
      // be property names.
      infected = true;
    } else if (Operation.is(n, Operator.MEMBER_ACCESS)) {
      // Do not let the property name reference be treated as a reference to
      // a var or global.
      attachScopes(AncestorChain.instance(ac, n.children().get(0)), scope);
      return false;
    }
    for (ParseTreeNode child : n.children()) {
      infected |= attachScopes(AncestorChain.instance(ac, child), scope);
    }
    if (infected) { scope.setDynamicUsePossible(); }
    return infected;
  }
View Full Code Here

    if (Block.class.isAssignableFrom(clazz)) {
      // Move directive prologues to the front since they are only syntactically
      // significant there.
      for (int i = 1, n = children.size(); i < n; ++i) {
        ParseTreeNode child = children.get(i);
        if (child instanceof DirectivePrologue) {
          if (children.get(0) instanceof DirectivePrologue) {
            DirectivePrologue dp0 = (DirectivePrologue) children.get(0);
            DirectivePrologue dp1 = (DirectivePrologue) child;
            if (!dp1.children().isEmpty()) {
              List<Directive> all = Lists.newArrayList(dp0.children());
              all.addAll(dp1.children());
              children.set(
                  0,
                  new DirectivePrologue(
                      FilePosition.span(
                          dp0.getFilePosition(), dp1.getFilePosition()),
                      all));
            }
            children.remove(i);
          } else {
            for (int j = i; j >= 1; --j) {
              children.set(j, children.get(j - 1));
            }
            children.set(0, child);
          }
        }
      }
    }

    ParseTreeNode node = ParseTreeNodes.newNodeInstance(
        clazz, FilePosition.UNKNOWN, value, children);
    substitutes.add(node);

    return true;
  }
View Full Code Here

  protected boolean createSubstitutes(
      List<ParseTreeNode> substitutes,
      Map<String, ParseTreeNode> bindings) {
    if (bindings.containsKey(keyIdentifier)
        && bindings.containsKey(valueIdentifier)) {
      ParseTreeNode keyNode = bindings.get(keyIdentifier);
      ParseTreeNode valueNode = bindings.get(valueIdentifier);
      assert keyNode.children().size() == valueNode.children().size();
      List<ObjProperty> children = Lists.newArrayList();
      for (int i = 0; i < keyNode.children().size(); i++) {
        children.add(
            new ValueProperty(
                (StringLiteral) keyNode.children().get(i),
                (Expression) valueNode.children().get(i)));
      }
      substitutes.addAll(children);
      return true;
    }
    return false;
View Full Code Here

      final List<FunctionConstructor> inners) {
    final List<Pair<AncestorChain<Statement>, Statement>> changes
        = Lists.newArrayList();
    node.acceptPreOrder(new Visitor() {
      public boolean visit(AncestorChain<?> chain) {
        ParseTreeNode node = chain.node;
        if (node instanceof Declaration
            && !(node instanceof FunctionDeclaration)) {
          if (chain.parent.node instanceof CatchStmt) { return true; }
          Declaration decl = (Declaration) node;
          Identifier id = decl.getIdentifier();
          removedIdents.add(id);
          Expression init = decl.getInitializer();
          Statement replacement;
          if (init != null) {
            replacement = new ExpressionStmt(toAssignment(decl));
          } else if (chain.parent.node instanceof ForEachLoop) {
            replacement = new ExpressionStmt(new Reference(id));
          } else {
            replacement = new Noop(decl.getFilePosition());
          }
          changes.add(Pair.pair(chain.cast(Statement.class), replacement));
          return true;
        } else if (node instanceof MultiDeclaration) {
          List<Expression> replacements = Lists.newArrayList();
          for (Declaration decl : ((MultiDeclaration) node).children()) {
            removedIdents.add(decl.getIdentifier());
            if (decl.getInitializer() == null) { continue; }
            visit(chain.child(decl).child(decl.getInitializer()));
            Expression assign = toAssignment(decl);
            replacements.add(assign);
          }
          Statement replacement;
          if (replacements.isEmpty()) {
            replacement = new Noop(node.getFilePosition());
          } else if (replacements.size() == 1) {
            Expression e = replacements.get(0);
            replacement = new ExpressionStmt(e.getFilePosition(), e);
          } else if (chain.parent.node instanceof Block) {
            List<Statement> stmts = Lists.newArrayList();
            for (Expression e : replacements) {
              stmts.add(new ExpressionStmt(e));
            }
            replacement = new Block(node.getFilePosition(), stmts);
          } else {
            Expression combo = null;
            for (Expression e : replacements) {
              combo = combo == null
                  ? e : Operation.createInfix(Operator.COMMA, combo, e);
            }
            replacement = new ExpressionStmt(node.getFilePosition(), combo);
          }
          changes.add(Pair.pair(chain.cast(Statement.class), replacement));
          return false;
        } else if (node instanceof FunctionConstructor) {
          inners.add((FunctionConstructor) node);
View Full Code Here

    }
  }

  private void renderParam(int i, RenderContext rc) {
    TokenConsumer out = rc.getOut();
    ParseTreeNode e = children().get(i);
    out.mark(e.getFilePosition());
    if (!parenthesize(op, 0 == i, (Expression) e)) {
      e.render(rc);
    } else {
      out.consume("(");
      e.render(rc);
      out.mark(FilePosition.endOfOrNull(getFilePosition()));
      out.consume(")");
    }
  }
View Full Code Here

  }

  @Override
  protected boolean createSubstitutes(
      List<ParseTreeNode> substitutes, Map<String, ParseTreeNode> bindings) {
    ParseTreeNode n = bindings.get(getIdentifier());
    if (n == null || !(n instanceof Identifier)) { return false; }
    Identifier withoutSuffix = (Identifier) n;
    Identifier withSuffix = new Identifier(
        withoutSuffix.getFilePosition(), n.getValue() + trailing);
    withSuffix.getAttributes().putAll(withoutSuffix.getAttributes());
    substitutes.add(withSuffix);
    return true;
  }
View Full Code Here

  private ModuleCacheKey key(String codeSnippet, boolean isHtml) throws Exception {
    MessageQueue mq = new EchoingMessageQueue(
        new PrintWriter(System.err, true), new MessageContext());
    InputSource is = new InputSource(new URI("test:///" + getName()));
    ParseTreeNode node = CajaContentRewriter.parse(
        is, CharProducer.Factory.fromString(codeSnippet, is),
        isHtml ? "text/html" : "text/javascript",
        mq);
    return new ModuleCacheKey(isHtml ? ContentType.HTML : ContentType.JS, node);
  }
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.