Package com.google.caja.parser.js

Examples of com.google.caja.parser.js.Block


        RewriterMessageType.CANNOT_MASK_IDENTIFIER, MessageLevel.FATAL_ERROR,
        MessagePart.Factory.valueOf("Array"));
  }

  public final void testUnmaskableFormals() throws Exception {
    Block b = js(fromString("function NaN(Infinity, arguments) {}"));
    Scope top = fromProgram(b);
    FunctionDeclaration fn = ((FunctionDeclaration) b.children().get(0));
    Scope.fromFunctionConstructor(top, fn.getInitializer());
    assertMessage(
        RewriterMessageType.CANNOT_MASK_IDENTIFIER, MessageLevel.FATAL_ERROR,
        MessagePart.Factory.valueOf("NaN"));
    assertMessage(
View Full Code Here


    Map<ElKey, EnumSet<EFlag>> eflags = elementFlags(schema);
    Map<ElKey, String> einterfaces = elementDOMInterfaces(schema);
    Map<AttribKey, UriEffect> uriEffects = uriEffects(schema);
    Map<AttribKey, LoaderType> ltypes = loaderTypes(schema);

    Block definitions = new Block();
    definitions.appendChild(QuasiBuilder.substV("var html4 = {};"));

    definitions.appendChild(mapFromEnum(
        EnumSet.allOf(HTML.Attribute.Type.class),
        "atype",
        new Function<HTML.Attribute.Type, String>() {
          public String apply(HTML.Attribute.Type f) {
            return f.name();
          }
        },
        new Function<HTML.Attribute.Type, Integer>() {
          public Integer apply(HTML.Attribute.Type f) {
            return A_TYPE_MAP.get(f);
          }
        })
    );

    {
      List<StringLiteral> keys = new ArrayList<StringLiteral>();
      List<IntegerLiteral> values = new ArrayList<IntegerLiteral>();
      for (Map.Entry<AttribKey, HTML.Attribute.Type> e : atypes.entrySet()) {
        AttribKey key = e.getKey();
        if (ElKey.HTML_WILDCARD.equals(key.el)
            || schema.isElementAllowed(key.el)
            // Whitelisted to allow dynamic script loading via proxy
            || SCRIPT_SRC.equals(key)) {
          keys.add(StringLiteral.valueOf(unk, key.toString()));
          values.add(new IntegerLiteral(unk, A_TYPE_MAP.get(e.getValue())));
        }
      }
      definitions.appendChild(export("ATTRIBS",
          (Expression) QuasiBuilder.substV(
              "({ @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;
          }
        })
    );

    definitions.appendChild(mapFromMap(
        eflags,
        "ELEMENTS",
        new Function<EnumSet<EFlag>, Expression>() {
          public Expression apply(EnumSet<EFlag> flags) {
            int value = 0;
            for (EFlag f : flags) { value |= f.bitMask; }
            return new IntegerLiteral(unk, value);
          }
        })
    );

    definitions.appendChild(mapFromMap(
        einterfaces,
        "ELEMENT_DOM_INTERFACES",
        new Function<String, Expression>() {
          public Expression apply(String domInterface) {
            return new StringLiteral(unk, domInterface);
          }
        })
    );

    definitions.appendChild(mapFromEnum(
        EnumSet.allOf(UriEffect.class),
        "ueffects",
        new Function<UriEffect, String>() {
          public String apply(UriEffect f) {
            return f.name();
          }
        },
        new Function<UriEffect, Integer>() {
          public Integer apply(UriEffect f) {
            return A_UEFFECT_MAP.get(f);
          }
        })
    );

    definitions.appendChild(mapFromEnum(
        uriEffects.entrySet(),
        "URIEFFECTS",
        new Function<Entry<AttribKey, UriEffect>, String>() {
          public String apply(Entry<AttribKey, UriEffect> f) {
            return f.getKey().toString();
          }
        },
        new Function<Entry<AttribKey, UriEffect>, Integer>() {
          public Integer apply(Entry<AttribKey, UriEffect> f) {
            return A_UEFFECT_MAP.get(f.getValue());
          }
        })
    );

    definitions.appendChild(mapFromEnum(
        EnumSet.allOf(LoaderType.class),
        "ltypes",
        new Function<LoaderType, String>() {
          public String apply(LoaderType f) {
            return f.name();
          }
        },
        new Function<LoaderType, Integer>() {
          public Integer apply(LoaderType f) {
            return L_TYPE_MAP.get(f);
          }
        })
    );

    definitions.appendChild(mapFromEnum(
        ltypes.entrySet(),
        "LOADERTYPES",
        new Function<Entry<AttribKey, LoaderType>, String>() {
          public String apply(Entry<AttribKey, LoaderType> f) {
            return f.getKey().toString();
View Full Code Here

    out.write("// Copyright Google Inc.\n");
    out.write("// Licensed under the Apache Licence Version 2.0\n");
    out.write("// Autogenerated at " + currentDate + "\n");
    out.write("// @overrides window\n");
    out.write("// @provides html4\n");
    Block node = generateJavascriptDefinitions(schema);
    RenderContext rc = new RenderContext(node.makeRenderer(out, null))
        .withPropertyNameQuotingMode(
            PropertyNameQuotingMode.PRESERVE_QUOTES);
    renderFlattenedBlocks(node, rc);
    rc.getOut().noMoreTokens();
    out.write("\n");
View Full Code Here

    }
  }

  private static void optimizeWithin(FunctionConstructor fc) {
    final Map<LitVal, LitVal> uses = Maps.newLinkedHashMap();
    Block body = fc.getBody();
    body.acceptPreOrder(new Visitor() {
      public boolean visit(AncestorChain<?> chain) {
        if (chain.node instanceof Literal
            && !(chain.node instanceof RegexpLiteral)) {
          AncestorChain<Literal> litAc = chain.cast(Literal.class);
          LitVal key = new LitVal(litAc);
          LitVal stored = uses.get(key);
          if (stored == null) {
            uses.put(key, stored = key);
          }
          stored.uses.add(litAc);
        } else if (chain.node instanceof ObjectConstructor) {
          List<? extends ObjProperty> children = chain
              .cast(ObjectConstructor.class).node.children();
          for (ObjProperty prop : children) {
            visit(chain.child(prop).child(prop.children().get(1)));
          }
          return false;
        }
        return true;
      }
    }, null);
    List<Declaration> decls = Lists.newArrayList();
    FilePosition pos = FilePosition.startOf(body.getFilePosition());
    for (LitVal v : uses.values()) {
      // Size now = canonLen * nUses.
      // Size after = "var aa=".length + canonLen + ";".length + "aa" * nUses
      // Switch if now > after;
      //           canonLen * nUses > 8 + canonLen + 2 * nUses
      int requiredSavings = 30// TUNING PARAMETER
      int canonLen = v.canonForm().length();
      int nUses = v.uses.size();
      if (canonLen * nUses > 8 + canonLen + 2 * nUses + requiredSavings) {
        // TODO(mikesamuel): choose a guaranteed non-interfering name.
        String name = "$_$__litpool__" + decls.size() + "$_$";
        decls.add(new Declaration(
            pos, new Identifier(pos, name), v.uses.get(0).node));
        for (AncestorChain<Literal> use : v.uses) {
          Reference ref = new Reference(
              new Identifier(use.node.getFilePosition(), name));
          use.parent.cast(MutableParseTreeNode.class).node
              .replaceChild(ref, use.node);
        }
      }
    }
    if (!decls.isEmpty()) {
      Statement first = body.children().get(0);
      MultiDeclaration md;
      if (first instanceof MultiDeclaration) {
        md = (MultiDeclaration) first;
      } else if (first instanceof Declaration) {
        md = new MultiDeclaration(
            FilePosition.span(pos, first.getFilePosition()),
            Collections.singletonList((Declaration) first));
        body.replaceChild(md, first);
      } else if (decls.size() == 1) {
        body.insertBefore(decls.get(0), first);
        return;
      } else {
        md = new MultiDeclaration(pos, Collections.<Declaration>emptyList());
        body.insertBefore(md, first);
      }
      MutableParseTreeNode.Mutation mut = md.createMutation();
      Declaration firstDecl = md.children().get(0);
      for (Declaration decl : decls) {
        mut = mut.insertBefore(decl, firstDecl);
View Full Code Here

    finishInference();
    while (true) {
      Result out = new Result();
      Scope s = Scope.fromProgram(js, mq);
      optimize(s, js, false, false, false, false, out);
      Block optimized = ConstLocalOptimization.optimize((Block) out.node);
      if (optimized == js) { return optimized; }
      js = optimized;
    }
  }
View Full Code Here

            } else if (!(out.node instanceof Noop)) {
              stmts.add((Statement) out.node);
            }
            if (!stmts.isEmpty()) {
              newChildren.add(
                  stmts.size() == 1 ? stmts.get(0) : new Block(UNK, stmts));
            }
            sb = addDigest(newDigest, sb);
            sb = addDigest(out.digest, sb);
            n = nEmitted = i + 1;
            break;
View Full Code Here

                opt.getClass(), opt.getFilePosition(), sl.newName,
                opt.children());
          } else {
            if (opt instanceof LabeledStatement) {
              // Add a block so we don't get ambiguity
              opt = new Block(opt.getFilePosition(), Arrays.asList(opt));
            }
            return new LabeledStmtWrapper(n.getFilePosition(), sl.newName, opt);
          }
        }
        return opt;
View Full Code Here

          case 0: return new Noop(n.getFilePosition());
          case 1: return (newChildren == null ? children : newChildren).get(0);
        }
      }
      return newChildren != null
          ? new Block(n.getFilePosition(), newChildren) : n;
    } else if (n instanceof SwitchStmt) {
      return optimizeSwitch((SwitchStmt) n);
    } else if (n instanceof ReturnStmt) {
      ReturnStmt rs = (ReturnStmt) n;
      Expression returnValue = rs.getReturnValue();
View Full Code Here

    // optimize them out where possible.
    boolean hasDefault = false;
    for (int i = newChildren.size(); --i >= 1;) {
      SwitchCase cs = (SwitchCase) newChildren.get(i);
      if (!(cs instanceof DefaultCaseStmt)) { continue; }
      Block body = cs.getBody();
      if (body.children().isEmpty()) {
        changed = true;
        newChildren.remove(i);
      } else if (isBlankBreak(body)) {
        if (i != 1 || !exits(((SwitchCase) newChildren.get(i - 1)).getBody())) {
          // Move the break into the preceding case.
          SwitchCase prev = (SwitchCase) newChildren.get(i - 1);
          newChildren.set(i - 1, withBody(prev, combine(prev.getBody(), body)));
          changed = true;
        }
        newChildren.remove(i);
        changed = true;
      } else {
        hasDefault = true;
      }
    }
    // Eliminate unnecessary breaks
    if (!hasDefault) {
      for (int i = newChildren.size(); --i >= 1;) {
        CaseStmt cs = (CaseStmt) newChildren.get(i);
        Block body = cs.getBody();
        if (!isBlankBreak(body)) { continue; }
        if (cs.getCaseValue().simplifyForSideEffect() != null) { continue; }
        if (i != 1) {
          SwitchCase prev = (SwitchCase) newChildren.get(i - 1);
          if (!exits(prev.getBody())) {
            // Move the break into the preceding case.
            newChildren.set(
                i - 1, withBody(prev, combine(prev.getBody(), body)));
          }
        }
        newChildren.remove(i);
        changed = true;
      }
    }
    // Eliminate duplicate cases
    SwitchCase last = null;
    for (int i = 1; i < newChildren.size(); ++i) {
      SwitchCase cs = (SwitchCase) newChildren.get(i);
      if (last != null && !last.getBody().children().isEmpty()
          && ParseTreeNodes.deepEquals(last.getBody(), cs.getBody())) {
        newChildren.set(i - 1, withoutBody(last));
        changed = true;
      }
      last = cs;
    }
    while (newChildren.size() > 1) {
      int lastIndex = newChildren.size() - 1;
      last = (SwitchCase) newChildren.get(lastIndex);

      Block lastBody = last.getBody();
      boolean changedOne = false;
      if (!lastBody.children().isEmpty()) {
        // Eliminate trailing break statement.
        List<? extends Statement> stmts = lastBody.children();
        int n = stmts.size();
        if (n > 0 && isBlankBreak(stmts.get(n - 1))) {
          stmts = stmts.subList(0, n - 1);
          Block newBody = new Block(lastBody.getFilePosition(), stmts);
          newChildren.set(newChildren.size() - 1, withBody(last, newBody));
          changedOne = true;
        }
      } else if (isBlankBreak(lastBody)) {
        //    switch (...) { default: ... case foo: break; }
View Full Code Here

    return changed
        ? new SwitchStmt(ss.getFilePosition(), ss.getLabel(), newChildren) : ss;
  }

  private static SwitchCase withoutBody(SwitchCase sc) {
    return withBody(sc, new Block(sc.getBody().getFilePosition()));
  }
View Full Code Here

TOP

Related Classes of com.google.caja.parser.js.Block

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.