Package com.google.caja.parser.js

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


  private static <T> ArrayConstructor mapToJsArray(
      Iterable<? extends T> it,
      Function<? super T, Expression> f) {
    FilePosition unk = FilePosition.UNKNOWN;
    ArrayConstructor arr = new ArrayConstructor(
        unk, Collections.<Expression>emptyList());
    for (T el : it) {
      arr.appendChild(el == null ? new NullLiteral(unk) : f.apply(el));
    }
    return arr;
  }
View Full Code Here


    Statement poolDecls = null;
    if (!stringPool.isEmpty()) {
      poolDecls = joinDeclarations(
          poolDecls,
          new Declaration(unk, new Identifier(unk, "s"),
              new ArrayConstructor(unk, stringPool)));
    }
    if (!regexPool.isEmpty()) {
      poolDecls = joinDeclarations(
          poolDecls,
          new Declaration(unk, new Identifier(unk, "c"),
              new ArrayConstructor(unk, regexPool)));
    }

    // Given keyword sets like
    // [['red','blue','green','transparent','inherit',;none'],
    //  ['red','blue','green'],
    //  ['inherit','none','bold','bolder']]
    // recognize that ['red','blue','green'] probably occurs frequently and
    // create a partition like
    // [['red','blue','green'],['bold','bolder'],['inherit',none'],
    //  ['transparent']]
    // and then store indices into the array of partition elements with
    // CSS property names so they can be unioned as needed.
    List<Set<String>> literalSets = Lists.newArrayList();
    for (Pair<CssSchema.CssPropertyInfo, CssPropertyData> p : propData) {
      literalSets.add(p.b.literals);
    }
    Partitions.Partition<String> litPartition = Partitions.partition(
        literalSets, String.class, null);
    List<ArrayConstructor> literalSetArrs = Lists.newArrayList();
    for (int[] literalIndices : litPartition.partition) {
      List<StringLiteral> literalArr = Lists.newArrayList();
      for (int litIndex : literalIndices) {
        literalArr.add(StringLiteral.valueOf(
            unk, litPartition.universe[litIndex]));
      }
      literalSetArrs.add(new ArrayConstructor(unk, literalArr));
    }
    if (!literalSetArrs.isEmpty()) {
      poolDecls = joinDeclarations(
          poolDecls,
          new Declaration(unk, new Identifier(unk, "L"),
              new ArrayConstructor(unk, literalSetArrs)));
    }

    List<ValueProperty> cssSchemaProps = Lists.newArrayList();
    StringLiteral propbitsObjKey = new StringLiteral(unk, "cssPropBits");
    StringLiteral litgroupObjKey = new StringLiteral(unk, "cssLitGroup");
    StringLiteral fnsObjKey = new StringLiteral(unk, "cssFns");

    // Keep track of the JS we generate so we can reuse data-objects for
    // CSS properties whose filtering schemes are functionally equivalent.
    Map<String, String> dataJsToKey = Maps.newHashMap();
    boolean hasAliases = false;

    for (int propIndex = 0, n = propData.size(); propIndex < n; ++propIndex) {
      Pair<CssSchema.CssPropertyInfo, CssPropertyData> d
          = propData.get(propIndex);
      CssPropertyData data = d.b;

      ObjectConstructor dataObj = new ObjectConstructor(unk);

      int propBits = 0;
      for (CssPropBit b : data.properties) {
        propBits |= b.jsValue;
      }

      dataObj.appendChild(
          new ValueProperty(propbitsObjKey, new IntegerLiteral(unk, propBits)));

      List<Expression> litGroups = Lists.newArrayList();
      for (int groupIndex : litPartition.unions[propIndex]) {
        litGroups.add((Expression) QuasiBuilder.substV(
            "L[@i]", "i", new IntegerLiteral(unk, groupIndex)));
      }
      if (!litGroups.isEmpty()) {
        dataObj.appendChild(new ValueProperty(
            litgroupObjKey, new ArrayConstructor(unk, litGroups)));
      }

      List<Expression> fnKeyStrs = Lists.newArrayList();
      for (CssPropertySignature.CallSignature fn : data.fns) {
        String fnKey = fnSigToData.get(fn).key;
        fnKeyStrs.add(StringLiteral.valueOf(unk, fnKey));
      }
      ArrayConstructor fnKeyArray = new ArrayConstructor(unk, fnKeyStrs);
      dataObj.appendChild(new ValueProperty(fnsObjKey, fnKeyArray));

      String dataJs;
      {
        StringBuilder js = new StringBuilder();
View Full Code Here

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

    EmbeddedJsExpressionTokenConsumer cssToJsArrayElements
        = new EmbeddedJsExpressionTokenConsumer();
    ss.render(new RenderContext(cssToJsArrayElements));
    cssToJsArrayElements.noMoreTokens();

    return new ArrayConstructor(
        ss.getFilePosition(), cssToJsArrayElements.getArrayMembers());
  }
View Full Code Here

    List<Expression> cssParts = Lists.newArrayList();
    // Accumulate static CSS that can be embedded in the DOM.
    StringBuilder css = new StringBuilder();
    FilePosition staticPos = null, dynamicPos = null;
    for (ValidatedStylesheet ss : validatedStylesheets) {
      ArrayConstructor ac = CssDynamicExpressionRewriter.cssToJs(ss.ss);
      List<? extends Expression> children = ac.children();
      if (children.isEmpty()) { continue; }
      FilePosition acPos = ac.getFilePosition();
      Expression child0 = children.get(0);
      // The CssDynamicExpressionRewriter gets to distinguish between static and
      // dynamic. If the output is a single string, then joining it on the
      // idClass would not add any information, so we can put it in the static
      // HTML.
      if (children.size() == 1 && child0 instanceof StringLiteral) {
        css.append('\n').append(((StringLiteral) child0).getUnquotedValue());
        staticPos = staticPos == null
            ? acPos : FilePosition.span(staticPos, acPos);
      } else {
        // Don't just push all onto the list since that would create an
        // extra, spurious separator after they're joined.
        // To avoid the spurious separator, we concatenate the last item
        // already on cssParts with child0.
        int n = cssParts.size();
        if (n == 0) {
          cssParts.addAll(children);
        } else {
          JsConcatenator cat = new JsConcatenator();
          cat.append(cssParts.get(n - 1));
          cat.append(FilePosition.startOf(child0.getFilePosition()), "\n");
          cat.append(child0);
          cssParts.set(n - 1, cat.toExpression(false));
          cssParts.addAll(children.subList(1, children.size()));
        }
        dynamicPos = dynamicPos == null
            ? acPos : FilePosition.span(dynamicPos, acPos);
      }
    }

    ExpressionStmt dynamicCss = null;
    Element staticCss = null;
    // Emit any dynamic CSS.
    if (!cssParts.isEmpty()) {
      // The CSS rule
      //     p { color: purple }
      // is converted to the JavaScript
      //     IMPORTS___.emitCss___(
      //         ['.', ' p { color: purple }']
      //         .join(IMPORTS___.getIdClass___()));
      //
      // If IMPORTS___.getIdClass() returns "g123___", then the resulting
      //     .g123___ p { color: purple }
      // will only make purple paragraphs that are under a node with class
      // g123__.
      dynamicCss = new ExpressionStmt(
          dynamicPos,
          (Expression) QuasiBuilder.substV(
              ReservedNames.IMPORTS
              + ".emitCss___(@cssParts./*@synthetic*/join("
              + ReservedNames.IMPORTS + ".getIdClass___()))",
              "cssParts", new ArrayConstructor(dynamicPos, cssParts)));
    }

    // Emit any static CSS.
    if (css.length() != 0) {
      String nsUri = Namespaces.HTML_NAMESPACE_URI;
View Full Code Here

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

  private static IntegerLiteral lit(int i) {
    return new IntegerLiteral(FilePosition.UNKNOWN, i);
  }

  private static ArrayConstructor arr(List<? extends Expression> items) {
    return new ArrayConstructor(FilePosition.UNKNOWN, items);
  }
View Full Code Here

      }
      CajoledModule validated = (CajoledModule) result;
      it.set(env.withJob(Job.cajoledJob(validated)));

      if (env.cacheKeys.iterator().hasNext()) {
        ArrayConstructor deps = validated.getInlinedModules();
        if (deps != null) {
          for (Expression moduleName : deps.children()) {
            String moduleUri = ((StringLiteral) moduleName).getUnquotedValue();
            JobCache.Keys forUri = keys.get(moduleUri);
            if (forUri == null) {
              forUri = env.cacheKeys;
            } else {
View Full Code Here

  private ArrayConstructor toArrayList(String... values) {
    List<StringLiteral> literals = new ArrayList<StringLiteral>();
    for (String value : values) {
      literals.add(StringLiteral.valueOf(FilePosition.UNKNOWN, value));
    }
    return new ArrayConstructor(FilePosition.UNKNOWN,literals);
  }
View Full Code Here

    Statement poolDecls = null;
    if (!stringPool.isEmpty()) {
      poolDecls = joinDeclarations(
          poolDecls,
          new Declaration(unk, new Identifier(unk, "s"),
              new ArrayConstructor(unk, stringPool)));
    }
    if (!regexPool.isEmpty()) {
      poolDecls = joinDeclarations(
          poolDecls,
          new Declaration(unk, new Identifier(unk, "c"),
              new ArrayConstructor(unk, regexPool)));
    }

    // Given keyword sets like
    // [['red','blue','green','transparent','inherit',;none'],
    //  ['red','blue','green'],
    //  ['inherit','none','bold','bolder']]
    // recognize that ['red','blue','green'] probably occurs frequently and
    // create a partition like
    // [['red','blue','green'],['bold','bolder'],['inherit',none'],
    //  ['transparent']]
    // and then store indices into the array of partition elements with
    // CSS property names so they can be unioned as needed.
    List<Set<String>> literalSets = Lists.newArrayList();
    for (Pair<CssSchema.CssPropertyInfo, CssPropertyData> p : propData) {
      literalSets.add(p.b.literals);
    }
    Partitions.Partition<String> litPartition = Partitions.partition(
        literalSets, String.class, null);
    List<ArrayConstructor> literalSetArrs = Lists.newArrayList();
    for (int[] literalIndices : litPartition.partition) {
      List<StringLiteral> literalArr = Lists.newArrayList();
      for (int litIndex : literalIndices) {
        literalArr.add(StringLiteral.valueOf(
            unk, litPartition.universe[litIndex]));
      }
      literalSetArrs.add(new ArrayConstructor(unk, literalArr));
    }
    if (!literalSetArrs.isEmpty()) {
      poolDecls = joinDeclarations(
          poolDecls,
          new Declaration(unk, new Identifier(unk, "L"),
              new ArrayConstructor(unk, literalSetArrs)));
    }

    List<ValueProperty> cssSchemaProps = Lists.newArrayList();
    StringLiteral regexObjKey = new StringLiteral(unk, "cssExtra");
    StringLiteral alternatesObjKey = new StringLiteral(unk, "cssAlternates");
    StringLiteral propbitsObjKey = new StringLiteral(unk, "cssPropBits");
    StringLiteral litgroupObjKey = new StringLiteral(unk, "cssLitGroup");

    for (int propIndex = 0, n = propData.size(); propIndex < n; ++propIndex) {
      Pair<CssSchema.CssPropertyInfo, CssPropertyData> d
          = propData.get(propIndex);
      CssSchema.CssPropertyInfo prop = d.a;
      CssPropertyData data = d.b;

      ObjectConstructor dataObj = new ObjectConstructor(unk);

      String regex = data.regex;
      if (regex != null) {
        int poolIndex = regexPoolMap.get(regex)[0];
        Expression re = poolIndex < 0
            ? makeRegexp(commonSubstringMap, regex)
            : (Expression) QuasiBuilder.substV(
                "c[@i]", "i", new IntegerLiteral(unk, poolIndex));
        dataObj.appendChild(new ValueProperty(regexObjKey, re));
      }

      String dom2property = propertyNameToDom2Property(prop.name);
      ArrayConstructor altNames = null;
      for (String altDom2Property : prop.dom2properties) {
        if (altDom2Property.equals(dom2property)) { continue; }
        if (altNames == null) {
          altNames = new ArrayConstructor(
              unk, Collections.<Expression>emptyList());
        }
        altNames.appendChild(StringLiteral.valueOf(unk, altDom2Property));
      }
      if (altNames != null) {
        dataObj.appendChild(new ValueProperty(alternatesObjKey, altNames));
      }

      cssSchemaProps.add(new ValueProperty(
          unk, StringLiteral.valueOf(unk, prop.name.getCanonicalForm()),
          dataObj));

      int propBits = 0;
      for (CssPropBit b : data.properties) {
        propBits |= b.jsValue;
      }
      if (LinkStyleWhitelist.HISTORY_INSENSITIVE_STYLE_WHITELIST
          .contains(prop.name)) {
        propBits |= CssPropBit.HISTORY_INSENSITIVE.jsValue;
      } else if (LinkStyleWhitelist.PROPERTIES_ALLOWED_IN_LINK_CLASSES
                 .contains(prop.name)) {
        propBits |= CssPropBit.ALLOWED_IN_LINK.jsValue;
      }
      dataObj.appendChild(
          new ValueProperty(propbitsObjKey, new IntegerLiteral(unk, propBits)));

      List<Expression> litGroups = Lists.newArrayList();
      for (int groupIndex : litPartition.unions[propIndex]) {
        litGroups.add((Expression) QuasiBuilder.substV(
            "L[@i]", "i", new IntegerLiteral(unk, groupIndex)));
      }
      if (!litGroups.isEmpty()) {
        dataObj.appendChild(new ValueProperty(
            litgroupObjKey, new ArrayConstructor(unk, litGroups)));
      }
    }

    ObjectConstructor cssSchema = new ObjectConstructor(unk, cssSchemaProps);
View Full Code Here

TOP

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

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.