Package com.google.caja.parser

Examples of com.google.caja.parser.ParseTreeNode


    // Parse the javascript
    try {
      StringReader strReader = new StringReader(resp.getContent());
      CharProducer cp = CharProducer.Factory.create(strReader, is);
      JsTokenQueue tq = new JsTokenQueue(new JsLexer(cp), is);
      ParseTreeNode input = new Parser(tq, mq).parse();
      tq.expectEmpty();

      compiler.addInput(AncestorChain.instance(input).node, contextUri.toJavaUri());
    } catch (ParseException e) {
      // Don't bother continuing.
View Full Code Here


  private Block jsFromAttrib(AttrValue v) {
    EmbeddedContent c = attributeContent.get(v.src);
    if (c == null) { return null; }
    try {
      ParseTreeNode n = c.parse(meta.getUriFetcher(), mq);
      if (n instanceof Block) { return (Block) n; }
    } catch (ParseException ex) {
      ex.toMessageQueue(mq);
    }
    return null;
View Full Code Here

  private CssTree.DeclarationGroup styleFromAttrib(AttrValue v) {
    EmbeddedContent c = attributeContent.get(v.src);
    if (c == null) { return null; }
    try {
      ParseTreeNode n = c.parse(meta.getUriFetcher(), mq);
      if (n instanceof CssTree.DeclarationGroup) {
        return (CssTree.DeclarationGroup) n;
      }
    } catch (ParseException ex) {
      ex.toMessageQueue(mq);
View Full Code Here

      String base, String url, String input,
      boolean debugMode, String opt_idClass) {
    MessageContext mc = new MessageContext();
    MessageQueue mq = new SimpleMessageQueue();

    ParseTreeNode outputJs;
    Node outputHtml;

    Map<InputSource, ? extends CharSequence> originalSources
        = Collections.singletonMap(new InputSource(guessURI(base, url)), input);

    PluginMeta meta = new PluginMeta(fetcher, null);
    if (opt_idClass != null && opt_idClass.length() != 0) {
      meta.setIdClass(opt_idClass);
    }
    PluginCompiler compiler = makePluginCompiler(meta, mq);
    compiler.setJobCache(new AppEngineJobCache());
    compiler.setMessageContext(mc);

    URI uri = guessURI(base, url);
    InputSource is = new InputSource(uri);
    CharProducer cp = CharProducer.Factory.fromString(input, is);
    boolean okToContinue = true;
    Dom inputNode = null;
    try {
      DomParser p = new DomParser(new HtmlLexer(cp), false, is, mq);
      inputNode = Dom.transplant(p.parseDocument());
      p.getTokenQueue().expectEmpty();
    } catch (ParseException e) {
      mq.addMessage(e.getCajaMessage());
      okToContinue = false;
    }

    if (okToContinue && inputNode != null) {
      compiler.addInput(inputNode, uri);
      okToContinue &= compiler.run();
    }

    outputJs = okToContinue ? compiler.getJavascript() : null;
    outputHtml = okToContinue ? compiler.getStaticHtml() : null;

    String[] messages = formatMessages(originalSources, mc, mq);

    StringBuilder jsOut = new StringBuilder();
    TokenConsumer renderer = new JsPrettyPrinter(jsOut);
    RenderContext rc = new RenderContext(renderer);
    String htmlOut = outputHtml != null ? Nodes.render(outputHtml) : null;

    if (outputJs != null) {
      outputJs.render(rc);
      rc.getOut().noMoreTokens();
      return new CajolingServiceResult(htmlOut, jsOut.toString(), messages);
    } else {
      return new CajolingServiceResult(htmlOut, null, messages);
    }
View Full Code Here

            }
          }
        }
      }
      boolean isLoopy(AncestorChain<?> ac) {
        ParseTreeNode node = ac.node;
        return node instanceof ForEachLoop || node instanceof Loop;
      }
    };
    List<LexicalScope> scopes = sa.computeLexicalScopes(ac);
    LexicalScope globalScope = scopes.get(0);
View Full Code Here

            op.getPropertyNameNode().getFilePosition(),
            MessagePart.Factory.valueOf(key));
      }
    }
    if (Operation.is(node, Operator.MEMBER_ACCESS)) {
      ParseTreeNode right = node.children().get(1);
      if (right instanceof Reference) {
        String key = ((Reference) right).getIdentifierName();
        if (Keyword.isKeyword(key)) {
          mq.addMessage(LinterMessageType.BARE_KEYWORD,
              right.getFilePosition(),
              MessagePart.Factory.valueOf(key));
        }
      }
    }
    for (ParseTreeNode child : node.children()) {
View Full Code Here

  /** Get rid of rules like <code>p { }</code>. */
  private void removeEmptyDeclarationsAndSelectors(
      AncestorChain<? extends CssTree> t) {
    t.node.acceptPreOrder(new Visitor() {
        public boolean visit(AncestorChain<?> ancestors) {
          ParseTreeNode node = ancestors.node;
          if (node instanceof CssTree.EmptyDeclaration) {
            ParseTreeNode parent = ancestors.getParentNode();
            if (parent instanceof MutableParseTreeNode) {
              ((MutableParseTreeNode) parent).removeChild(node);
            }
            return false;
          } else if (node instanceof CssTree.Selector) {
            CssTree.Selector sel = (CssTree.Selector) node;
            if (sel.children().isEmpty()
                || !(sel.children().get(0) instanceof CssTree.SimpleSelector)) {
              // Remove from parent
              ParseTreeNode parent = ancestors.getParentNode();
              if (parent instanceof MutableParseTreeNode) {
                ((MutableParseTreeNode) parent).removeChild(sel);
              }
            }
            return false;
View Full Code Here

      }, t.parent);
  }
  private void removeEmptyRuleSets(AncestorChain<? extends CssTree> t) {
    t.node.acceptPreOrder(new Visitor() {
        public boolean visit(AncestorChain<?> ancestors) {
          ParseTreeNode node = ancestors.node;
          if (!(node instanceof CssTree.RuleSet)) { return true; }
          CssTree.RuleSet rset = (CssTree.RuleSet) node;
          List<? extends CssTree> children = rset.children();
          if (children.isEmpty()
              || (children.get(children.size() - 1)
                  instanceof CssTree.Selector)
              || !(children.get(0) instanceof CssTree.Selector)) {
            // No declarations or no selectors, so either the properties apply
            // to nothing or there are no properties to apply.
            ParseTreeNode parent = ancestors.getParentNode();
            if (parent instanceof MutableParseTreeNode) {
              ((MutableParseTreeNode) parent).removeChild(rset);
            }
          }
          return false;
View Full Code Here

    // 2) Ban content properties, and attr pseudo classes, and any other
    //    pseudo selectors that don't match the whitelist
    t.node.acceptPreOrder(new Visitor() {
        public boolean visit(AncestorChain<?> ancestors) {
          ParseTreeNode node = ancestors.node;
          if (node instanceof CssTree.Pseudo) {
            boolean remove = false;
            CssTree child = ((CssTree.Pseudo) node).children().get(0);
            if (child instanceof CssTree.IdentLiteral) {
              Name pseudoName = Name.css(
                  ((CssTree.IdentLiteral) child).getValue());
              if (!ALLOWED_PSEUDO_CLASSES.contains(pseudoName)) {
                // Allow the visited pseudo selector but not with any styles
                // that can be fetched via getComputedStyle in DOMita's
                // COMPUTED_STYLE_WHITELIST.
                if (!(LINK_PSEUDO_CLASSES.contains(pseudoName)
                      && strippedPropertiesBannedInLinkClasses(
                          ancestors.parent.parent.cast(CssTree.Selector.class)
                          ))) {
                  mq.addMessage(PluginMessageType.UNSAFE_CSS_PSEUDO_SELECTOR,
                                invalidNodeMessageLevel, node.getFilePosition(),
                                node);
                  remove = true;
                }
              }
            } else {
              StringBuilder rendered = new StringBuilder();
              TokenConsumer tc = new CssPrettyPrinter(rendered);
              node.render(new RenderContext(tc));
              tc.noMoreTokens();
              mq.addMessage(PluginMessageType.UNSAFE_CSS_PSEUDO_SELECTOR,
                            invalidNodeMessageLevel, node.getFilePosition(),
                            MessagePart.Factory.valueOf(rendered.toString()));
              remove = true;
            }
            if (remove) {
              // Delete the containing selector, since otherwise we'd broaden
              // the rule.
              selectorFor(ancestors).getAttributes().set(
                  CssValidator.INVALID, Boolean.TRUE);
            }
          }
          return true;
        }
      }, t.parent);
    // 3) Remove any properties and attributes that didn't validate
    t.node.acceptPreOrder(new Visitor() {
        public boolean visit(AncestorChain<?> ancestors) {
          ParseTreeNode node = ancestors.node;
          if (node instanceof CssTree.Property) {
            if (node.getAttributes().is(CssValidator.INVALID)) {
              declarationFor(ancestors).getAttributes().set(
                  CssValidator.INVALID, Boolean.TRUE);
            }
          } else if (node instanceof CssTree.Attrib) {
            if (node.getAttributes().is(CssValidator.INVALID)) {
              simpleSelectorFor(ancestors).getAttributes().set(
                  CssValidator.INVALID, Boolean.TRUE);
            }
          } else if (node instanceof CssTree.Term
                     && (CssPropertyPartType.URI == propertyPartType(node))) {

            boolean remove = false;
            Message removeMsg = null;

            CssTree term = (CssTree.Term) node;
            CssTree.CssLiteral content =
                (CssTree.CssLiteral) term.children().get(0);

            if (content instanceof CssTree.Substitution) {
              return true// Handled by later pass.
            }

            String uriStr = content.getValue();
            try {
              URI baseUri = content.getFilePosition().source().getUri();
              URI relUri = new URI(uriStr);
              URI uri = baseUri.resolve(relUri);
              ExternalReference ref = new ExternalReference(
                  uri, baseUri, relUri, content.getFilePosition());
              Name propertyPart = propertyPart(node)// TODO
              if (uriPolicy != null) {
                String rewritten = UriPolicyNanny.apply(
                    uriPolicy,
                    ref, UriEffect.SAME_DOCUMENT, LoaderType.SANDBOXED,
                    Collections.singletonMap(
                        UriPolicyHintKey.CSS_PROP.key, propertyPart));
                if (rewritten == null) {
                  removeMsg = new Message(
                      PluginMessageType.DISALLOWED_URI,
                      node.getFilePosition(),
                      MessagePart.Factory.valueOf(uriStr));
                  remove = true;
                }
              }
            } catch (URISyntaxException ex) {
              removeMsg = new Message(
                  PluginMessageType.DISALLOWED_URI,
                  node.getFilePosition(), MessagePart.Factory.valueOf(uriStr));
              remove = true;
            }

            if (remove) {
              // condemn the containing declaration
              CssTree.Declaration decl = declarationFor(ancestors);
              if (null != decl) {
                if (!decl.getAttributes().is(CssValidator.INVALID)) {
                  if (null != removeMsg) { mq.getMessages().add(removeMsg); }
                  decl.getAttributes().set(CssValidator.INVALID, Boolean.TRUE);
                }
              }
            }
          }
          return true;
        }
      }, t.parent);

    // 4) Remove invalid nodes
    removeInvalidNodes(t);

    // 5) Cleanup.  Remove any rulesets with empty selectors
    // Since this is a post order traversal, we will first remove empty
    // selectors, and then consider any rulesets that have become empty due to
    // a lack of selectors.
    t.node.acceptPreOrder(new Visitor() {
        public boolean visit(AncestorChain<?> ancestors) {
          ParseTreeNode node = ancestors.node;
          if ((node instanceof CssTree.Selector && node.children().isEmpty())
              || (node instanceof CssTree.RuleSet
                  && (node.children().isEmpty()
                      || node.children().get(0) instanceof CssTree.Declaration))
              ) {
            ((MutableParseTreeNode) ancestors.parent.node).removeChild(node);
            return false;
          }
          return true;
View Full Code Here

   * The list of parse trees that comprise the plugin after run has been called.
   * Valid after run has been called.
   */
  public List<? extends ParseTreeNode> getOutputs() {
    List<ParseTreeNode> outputs = Lists.newArrayList();
    ParseTreeNode js = getJavascript();
    if (js != null) { outputs.add(js); }
    return outputs;
  }
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.