Java Code Examples for com.google.javascript.rhino.Node#checkTreeEquals()

The following examples show how to use com.google.javascript.rhino.Node#checkTreeEquals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IntegrationTestCase.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Asserts that when compiling with the given compiler options,
 * {@code original} is transformed into {@code compiled}.
 */
protected void test(CompilerOptions options,
    String[] original, String[] compiled) {
  Compiler compiler = compile(options, original);
  assertEquals("Expected no warnings or errors\n" +
      "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) +
      "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()),
      0, compiler.getErrors().length + compiler.getWarnings().length);

  Node root = compiler.getRoot().getLastChild();
  Node expectedRoot = parse(compiled, options, normalizeResults);
  String explanation = expectedRoot.checkTreeEquals(root);
  assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
      "\nResult: " + compiler.toSource(root) +
      "\n" + explanation, explanation);
}
 
Example 2
Source File: IntegrationTestCase.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Asserts that when compiling with the given compiler options,
 * there is an error or warning.
 */
protected void test(CompilerOptions options,
    String[] original, String[] compiled, DiagnosticType warning) {
  Compiler compiler = compile(options, original);
  checkUnexpectedErrorsOrWarnings(compiler, 1);
  assertEquals("Expected exactly one warning or error",
      1, compiler.getErrors().length + compiler.getWarnings().length);
  if (compiler.getErrors().length > 0) {
    assertEquals(warning, compiler.getErrors()[0].getType());
  } else {
    assertEquals(warning, compiler.getWarnings()[0].getType());
  }

  if (compiled != null) {
    Node root = compiler.getRoot().getLastChild();
    Node expectedRoot = parse(compiled, options, normalizeResults);
    String explanation = expectedRoot.checkTreeEquals(root);
    assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
        "\nResult: " + compiler.toSource(root) +
        "\n" + explanation, explanation);
  }
}
 
Example 3
Source File: CommandLineRunnerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Asserts that when compiling with the given compiler options,
 * {@code original} is transformed into {@code compiled}.
 * If {@code warning} is non-null, we will also check if the given
 * warning type was emitted.
 */
private void test(String[] original, String[] compiled,
                  DiagnosticType warning) {
  Compiler compiler = compile(original);

  if (warning == null) {
    assertEquals("Expected no warnings or errors\n" +
        "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) +
        "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()),
        0, compiler.getErrors().length + compiler.getWarnings().length);
  } else {
    assertEquals(1, compiler.getWarnings().length);
    assertEquals(warning, compiler.getWarnings()[0].getType());
  }

  Node root = compiler.getRoot().getLastChild();
  if (useStringComparison) {
    assertEquals(Joiner.on("").join(compiled), compiler.toSource());
  } else {
    Node expectedRoot = parse(compiled);
    String explanation = expectedRoot.checkTreeEquals(root);
    assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
        "\nResult: " + compiler.toSource(root) +
        "\n" + explanation, explanation);
  }
}
 
Example 4
Source File: JsonMLConversionTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void testJsonMLToAstConversion(Node astRoot, JsonML jsonmlRoot,
    String js) {
  Compiler compiler = new Compiler();
  JsonMLAst ast = new JsonMLAst(jsonmlRoot);
  Node resultAstRoot = ast.getAstRoot(compiler);

  String explanation = resultAstRoot.checkTreeEquals(astRoot);
  assertNull("JsonML -> AST converter returned incorect result for " + js
     + "\n" + explanation, explanation);
}
 
Example 5
Source File: IntegrationTestCase.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Asserts that when compiling with the given compiler options,
 * there is an error or warning.
 */
protected void test(CompilerOptions options,
    String[] original, String[] compiled, DiagnosticType[] warnings) {
  Compiler compiler = compile(options, original);
  checkUnexpectedErrorsOrWarnings(compiler, warnings.length);

  if (compiled != null) {
    Node root = compiler.getRoot().getLastChild();
    Node expectedRoot = parse(compiled, options, normalizeResults);
    String explanation = expectedRoot.checkTreeEquals(root);
    assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
        "\nResult: " + compiler.toSource(root) +
        "\n" + explanation, explanation);
  }
}
 
Example 6
Source File: ExpressionDecomposerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void helperExposeExpression(
    String code,
    String fnName,
    String expectedResult,
    Set<String> knownConstants
    ) {
  Compiler compiler = getCompiler();
  if (knownConstants == null) {
    knownConstants = Sets.newHashSet();
  }
  ExpressionDecomposer decomposer = new ExpressionDecomposer(
      compiler, compiler.getUniqueNameIdSupplier(), knownConstants);
  decomposer.setTempNamePrefix("temp");
  decomposer.setResultNamePrefix("result");
  Node expectedRoot = parse(compiler, expectedResult);
  Node tree = parse(compiler, code);
  assertNotNull(tree);

  Node externsRoot = new Node(Token.EMPTY);
  Node mainRoot = tree;

  Node callSite = findCall(tree, fnName);
  assertNotNull("Call to " + fnName + " was not found.", callSite);

  DecompositionType result = decomposer.canExposeExpression(callSite);
  assertTrue(result == DecompositionType.DECOMPOSABLE);

  compiler.resetUniqueNameId();
  decomposer.exposeExpression(callSite);
  validateSourceInfo(compiler, tree);
  String explanation = expectedRoot.checkTreeEquals(tree);
  assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
      "\nResult: " + compiler.toSource(tree) +
      "\n" + explanation, explanation);
}
 
Example 7
Source File: ExpressionDecomposerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void helperMoveExpression(
    String code,
    String fnName,
    String expectedResult,
    Set<String> knownConstants
    ) {
  Compiler compiler = getCompiler();
  if (knownConstants == null) {
    knownConstants = Sets.newHashSet();
  }

  ExpressionDecomposer decomposer = new ExpressionDecomposer(
      compiler, compiler.getUniqueNameIdSupplier(), knownConstants);
  decomposer.setTempNamePrefix("temp");
  decomposer.setResultNamePrefix("result");
  Node expectedRoot = parse(compiler, expectedResult);
  Node tree = parse(compiler, code);
  assertNotNull(tree);

  Node externsRoot = new Node(Token.EMPTY);
  Node mainRoot = tree;

  Node callSite = findCall(tree, fnName);
  assertNotNull("Call to " + fnName + " was not found.", callSite);

  compiler.resetUniqueNameId();
  decomposer.moveExpression(callSite);
  validateSourceInfo(compiler, tree);
  String explanation = expectedRoot.checkTreeEquals(tree);
  assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
      "\nResult: " + compiler.toSource(tree) +
      "\n" + explanation, explanation);
}
 
Example 8
Source File: CodePrinterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void testReparse(String code) {
  Compiler compiler = new Compiler();
  Node parse1 = parse(code);
  Node parse2 = parse(new CodePrinter.Builder(parse1).build());
  String explanation = parse1.checkTreeEquals(parse2);
  assertNull("\nExpected: " + compiler.toSource(parse1) +
      "\nResult: " + compiler.toSource(parse2) +
      "\n" + explanation, explanation);
}
 
Example 9
Source File: ReplaceMessages.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Updates the descendants of a FUNCTION node to represent a message's value.
 * <p>
 * The tree looks something like:
 * <pre>
 * function
 *  |-- name
 *  |-- lp
 *  |   |-- name <arg1>
 *  |    -- name <arg2>
 *   -- block
 *      |
 *       --return
 *           |
 *            --add
 *               |-- string foo
 *                -- name <arg1>
 * </pre>
 *
 * @param message  a message
 * @param functionNode  the message's original FUNCTION value node
 *
 * @throws MalformedException if the passed node's subtree structure is
 *         not as expected
 */
private void updateFunctionNode(JsMessage message, Node functionNode)
    throws MalformedException {
  checkNode(functionNode, Token.FUNCTION);
  Node nameNode = functionNode.getFirstChild();
  checkNode(nameNode, Token.NAME);
  Node argListNode = nameNode.getNext();
  checkNode(argListNode, Token.PARAM_LIST);
  Node oldBlockNode = argListNode.getNext();
  checkNode(oldBlockNode, Token.BLOCK);

  Iterator<CharSequence> iterator = message.parts().iterator();
  Node valueNode = iterator.hasNext()
      ? constructAddOrStringNode(iterator, argListNode)
      : IR.string("");
  Node newBlockNode = IR.block(IR.returnNode(valueNode));

  // TODO(user): checkTreeEqual is overkill. I am in process of rewriting
  // these functions.
  if (newBlockNode.checkTreeEquals(oldBlockNode) != null) {
    newBlockNode.copyInformationFromForTree(oldBlockNode);
    functionNode.replaceChild(oldBlockNode, newBlockNode);
    compiler.reportCodeChange();
  }
}
 
Example 10
Source File: FunctionInjectorTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public void helperInlineReferenceToFunction(
    String code, final String expectedResult,
    final String fnName, final InliningMode mode,
    final boolean decompose) {
  final Compiler compiler = new Compiler();
  final FunctionInjector injector = new FunctionInjector(
      compiler, compiler.getUniqueNameIdSupplier(), decompose,
      assumeStrictThis,
      assumeMinimumCapture);

  List<SourceFile> externsInputs = Lists.newArrayList(
      SourceFile.fromCode("externs", ""));

  CompilerOptions options = new CompilerOptions();
  options.setCodingConvention(new GoogleCodingConvention());
  compiler.init(externsInputs, Lists.newArrayList(
      SourceFile.fromCode("code", code)), options);
  Node parseRoot = compiler.parseInputs();
  Node externsRoot = parseRoot.getFirstChild();
  final Node tree = parseRoot.getLastChild();
  assertNotNull(tree);
  assertTrue(tree != externsRoot);

  final Node expectedRoot = parseExpected(new Compiler(), expectedResult);

  Node mainRoot = tree;
  MarkNoSideEffectCalls mark = new MarkNoSideEffectCalls(compiler);
  mark.process(externsRoot, mainRoot);

  Normalize normalize = new Normalize(compiler, false);
  normalize.process(externsRoot, mainRoot);
  compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED);

  final Node fnNode = findFunction(tree, fnName);
  assertNotNull(fnNode);
  final Set<String> unsafe =
      FunctionArgumentInjector.findModifiedParameters(fnNode);
  assertNotNull(fnNode);

  // inline tester
  Method tester = new Method() {
    @Override
    public boolean call(NodeTraversal t, Node n, Node parent) {

      CanInlineResult canInline = injector.canInlineReferenceToFunction(
          t, n, fnNode, unsafe, mode,
          NodeUtil.referencesThis(fnNode),
          NodeUtil.containsFunction(NodeUtil.getFunctionBody(fnNode)));
      assertTrue("canInlineReferenceToFunction should not be CAN_NOT_INLINE",
          CanInlineResult.NO != canInline);
      if (decompose) {
        assertTrue("canInlineReferenceToFunction " +
            "should be CAN_INLINE_AFTER_DECOMPOSITION",
            CanInlineResult.AFTER_PREPARATION == canInline);

        Set<String> knownConstants = Sets.newHashSet();
        ExpressionDecomposer decomposer = new ExpressionDecomposer(
            compiler, compiler.getUniqueNameIdSupplier(), knownConstants);
        injector.setKnownConstants(knownConstants);
        injector.maybePrepareCall(n);

        assertTrue("canInlineReferenceToFunction " +
            "should be CAN_INLINE",
            CanInlineResult.YES != canInline);
      }

      Node result = injector.inline(
          t, n, fnName, fnNode, mode);
      validateSourceInfo(compiler, result);
      String explanation = expectedRoot.checkTreeEquals(tree.getFirstChild());
      assertNull("\nExpected: " + toSource(expectedRoot) +
          "\nResult: " + toSource(tree.getFirstChild()) +
          "\n" + explanation, explanation);
      return true;
    }
  };

  compiler.resetUniqueNameId();
  TestCallback test = new TestCallback(fnName, tester);
  NodeTraversal.traverse(compiler, tree, test);
}
 
Example 11
Source File: FunctionToBlockMutatorTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public void helperMutate(
    String code, final String expectedResult, final String fnName,
    final String resultName,
    final boolean needsDefaultResult,
    final boolean isCallInLoop) {
  final Compiler compiler = new Compiler();
  final FunctionToBlockMutator mutator = new FunctionToBlockMutator(
      compiler, compiler.getUniqueNameIdSupplier());
  Node expectedRoot = parse(compiler, expectedResult);
  Preconditions.checkState(compiler.getErrorCount() == 0);
  final Node expected = expectedRoot.getFirstChild();
  final Node tree = parse(compiler, code);
  Preconditions.checkState(compiler.getErrorCount() == 0);

  Node externsRoot = new Node(Token.EMPTY);
  Node mainRoot = tree;
  MarkNoSideEffectCalls mark = new MarkNoSideEffectCalls(compiler);
  mark.process(externsRoot, mainRoot);

  final Node fnNode = findFunction(tree, fnName);
  final Set<String> unsafe =
      FunctionArgumentInjector.findModifiedParameters(fnNode);

  // Fake precondition.
  compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED);

  // inline tester
  Method tester = new Method() {
    @Override
    public boolean call(NodeTraversal t, Node n, Node parent) {

      Node result = mutator.mutate(
          fnName, fnNode, n, resultName,
          needsDefaultResult, isCallInLoop);
      validateSourceInfo(compiler, result);
      String explanation = expected.checkTreeEquals(result);
      assertNull("\nExpected: " + compiler.toSource(expected) +
          "\nResult: " + compiler.toSource(result) +
          "\n" + explanation, explanation);
      return true;
    }
  };

  compiler.resetUniqueNameId();
  TestCallback test = new TestCallback(fnName, tester);
  NodeTraversal.traverse(compiler, tree, test);
}
 
Example 12
Source File: ParserTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private void assertNodeEquality(Node expected, Node found) {
  String message = expected.checkTreeEquals(found);
  if (message != null) {
    fail(message);
  }
}