com.google.javascript.rhino.Node

Here are the examples of the java api class com.google.javascript.rhino.Node taken from open source projects.

1. GatherSideEffectSubexpressionsCallbackTest#getSideEffectsHookNode()

View license
private Node getSideEffectsHookNode() {
    Node hookNode = new Node(Token.HOOK);
    Node assign1 = new Node(Token.ASSIGN);
    assign1.addChildToBack(Node.newString(Token.NAME, "bar"));
    assign1.addChildToBack(Node.newNumber(0));
    Node assign2 = new Node(Token.ASSIGN);
    assign2.addChildToBack(Node.newString(Token.NAME, "baz"));
    assign2.addChildToBack(Node.newNumber(0));
    hookNode.addChildToBack(Node.newString(Token.NAME, "foo"));
    hookNode.addChildToBack(assign1);
    hookNode.addChildToBack(assign2);
    return hookNode;
}

2. NodeUtilTest#testLhsByDestructuring1b()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring1b() {
    Node root = parse("var {a: c, b: d} = obj;");
    Node destructLhs = root.getFirstFirstChild();
    Preconditions.checkArgument(destructLhs.isDestructuringLhs());
    Node destructPat = destructLhs.getFirstChild();
    Preconditions.checkArgument(destructPat.isObjectPattern());
    Node strKeyNodeA = destructPat.getFirstChild();
    Node strKeyNodeB = strKeyNodeA.getNext();
    Node nameNodeC = strKeyNodeA.getFirstChild();
    Node nameNodeD = strKeyNodeB.getFirstChild();
    Preconditions.checkState(strKeyNodeA.getString().equals("a"), strKeyNodeA);
    Preconditions.checkState(strKeyNodeB.getString().equals("b"), strKeyNodeB);
    Preconditions.checkState(nameNodeC.getString().equals("c"), nameNodeC);
    Preconditions.checkState(nameNodeD.getString().equals("d"), nameNodeD);
    Node nameNodeObj = destructPat.getNext();
    Preconditions.checkState(nameNodeObj.getString().equals("obj"), nameNodeObj);
    assertNotLhsByDestructuring(strKeyNodeA);
    assertNotLhsByDestructuring(strKeyNodeB);
    assertLhsByDestructuring(nameNodeC);
    assertLhsByDestructuring(nameNodeD);
    assertNotLhsByDestructuring(nameNodeObj);
}

3. TypeCheckTest#testNameNode()

Project: closure-compiler
Source File: TypeCheckTest.java
View license
/**
   * Type checks a NAME node and retrieve its type.
   */
private JSType testNameNode(String name) {
    Node node = Node.newString(Token.NAME, name);
    Node parent = new Node(Token.SCRIPT, node);
    parent.setInputId(new InputId("code"));
    Node externs = new Node(Token.SCRIPT);
    externs.setInputId(new InputId("externs"));
    Node externAndJsRoot = new Node(Token.BLOCK, externs, parent);
    externAndJsRoot.setIsSyntheticBlock(true);
    makeTypeCheck().processForTesting(null, parent);
    return node.getJSType();
}

4. NodeUtilTest#testLhsByDestructuring2()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring2() {
    Node root = parse("var [a, [b, c]] = obj;");
    Node destructLhs = root.getFirstFirstChild();
    Preconditions.checkArgument(destructLhs.isDestructuringLhs());
    Node destructPat = destructLhs.getFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Node nameNodeB = nameNodeA.getNext().getFirstChild();
    Node nameNodeC = nameNodeB.getNext();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    Preconditions.checkState(nameNodeB.getString().equals("b"), nameNodeB);
    Preconditions.checkState(nameNodeC.getString().equals("c"), nameNodeC);
    Node nameNodeObj = destructPat.getNext();
    Preconditions.checkState(nameNodeObj.getString().equals("obj"), nameNodeObj);
    assertLhsByDestructuring(nameNodeA);
    assertLhsByDestructuring(nameNodeB);
    assertLhsByDestructuring(nameNodeC);
    assertNotLhsByDestructuring(nameNodeObj);
}

5. NodeUtilTest#testLhsByDestructuring3()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring3() {
    Node root = parse("var [a, b] = [c, d];");
    Node destructLhs = root.getFirstFirstChild();
    Preconditions.checkArgument(destructLhs.isDestructuringLhs());
    Node destructPat = destructLhs.getFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Node nameNodeB = nameNodeA.getNext();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    Preconditions.checkState(nameNodeB.getString().equals("b"), nameNodeB);
    Node nameNodeC = destructLhs.getLastChild().getFirstChild();
    Node nameNodeD = nameNodeC.getNext();
    Preconditions.checkState(nameNodeC.getString().equals("c"), nameNodeC);
    Preconditions.checkState(nameNodeD.getString().equals("d"), nameNodeD);
    assertLhsByDestructuring(nameNodeA);
    assertLhsByDestructuring(nameNodeB);
    assertNotLhsByDestructuring(nameNodeC);
    assertNotLhsByDestructuring(nameNodeD);
}

6. NodeUtilTest#testLhsByDestructuring3b()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring3b() {
    Node root = parse("var {a: c, b: d} = {a: 1, b: 2};");
    Node destructLhs = root.getFirstFirstChild();
    Preconditions.checkArgument(destructLhs.isDestructuringLhs());
    Node destructPat = destructLhs.getFirstChild();
    Preconditions.checkArgument(destructPat.isObjectPattern());
    Node strKeyNodeA = destructPat.getFirstChild();
    Node strKeyNodeB = strKeyNodeA.getNext();
    Node nameNodeC = strKeyNodeA.getFirstChild();
    Node nameNodeD = strKeyNodeB.getFirstChild();
    Preconditions.checkState(strKeyNodeA.getString().equals("a"), strKeyNodeA);
    Preconditions.checkState(strKeyNodeB.getString().equals("b"), strKeyNodeB);
    Preconditions.checkState(nameNodeC.getString().equals("c"), nameNodeC);
    Preconditions.checkState(nameNodeD.getString().equals("d"), nameNodeD);
    assertNotLhsByDestructuring(strKeyNodeA);
    assertNotLhsByDestructuring(strKeyNodeB);
    assertLhsByDestructuring(nameNodeC);
    assertLhsByDestructuring(nameNodeD);
}

7. Es6TypedToEs6Converter#createPropertyDefinition()

View license
private Node createPropertyDefinition(Node member, String className) {
    member.detachFromParent();
    className = maybePrependCurrNamespace(className);
    Node nameAccess = NodeUtil.newQName(compiler, className);
    Node prototypeAccess = NodeUtil.newPropertyAccess(compiler, nameAccess, "prototype");
    Node qualifiedMemberAccess = getQualifiedMemberAccess(compiler, member, nameAccess, prototypeAccess);
    // Copy type information.
    maybeVisitColonType(member, member);
    maybeAddVisibility(member);
    qualifiedMemberAccess.setJSDocInfo(member.getJSDocInfo());
    Node newNode = NodeUtil.newExpr(qualifiedMemberAccess);
    return newNode.useSourceInfoIfMissingFromForTree(member);
}

8. ExportTestFunctions#exportTestFunctionAsSymbol()

View license
// Adds exportSymbol(testFunctionName, testFunction);
private void exportTestFunctionAsSymbol(String testFunctionName, Node node, Node scriptNode) {
    Node exportCallTarget = NodeUtil.newQName(compiler, exportSymbolFunction, node, testFunctionName);
    Node call = IR.call(exportCallTarget);
    if (exportCallTarget.isName()) {
        call.putBooleanProp(Node.FREE_CALL, true);
    }
    call.addChildToBack(IR.string(testFunctionName));
    call.addChildToBack(NodeUtil.newQName(compiler, testFunctionName, node, testFunctionName));
    Node expression = IR.exprResult(call);
    scriptNode.addChildAfter(expression, node);
    compiler.reportCodeChange();
}

9. ExpressionDecomposer#moveExpression()

View license
// TODO(johnlenz): This is not currently used by the function inliner,
// as moving the call out of the expression before the actual function call
// causes additional variables to be introduced.  As the variable
// inliner is improved, this might be a viable option.
/**
   * Extract the specified expression from its parent expression.
   * @see #canExposeExpression
   */
void moveExpression(Node expression) {
    String resultName = getResultValueName();
    Node injectionPoint = findInjectionPoint(expression);
    Preconditions.checkNotNull(injectionPoint);
    Node injectionPointParent = injectionPoint.getParent();
    Preconditions.checkNotNull(injectionPointParent);
    Preconditions.checkState(NodeUtil.isStatementBlock(injectionPointParent));
    // Replace the expression with a reference to the new name.
    Node expressionParent = expression.getParent();
    expressionParent.replaceChild(expression, IR.name(resultName));
    // Re-add the expression at the appropriate place.
    Node newExpressionRoot = NodeUtil.newVarNode(resultName, expression);
    injectionPointParent.addChildBefore(newExpressionRoot, injectionPoint);
    compiler.reportCodeChange();
}

10. J2clConstantHoisterPass#hoistConstantLikeField()

View license
private void hoistConstantLikeField(Node clinitAssignment, Node declarationAssignment) {
    Node clinitAssignedValue = clinitAssignment.getSecondChild();
    Node declarationInClass = declarationAssignment.getFirstChild();
    Node declarationAssignedValue = declarationInClass.getFirstChild();
    // Remove the clinit initialization
    NodeUtil.removeChild(clinitAssignment.getParent(), clinitAssignment);
    // Replace the assignment in declaration with the value from clinit
    clinitAssignedValue.detachFromParent();
    declarationInClass.replaceChild(declarationAssignedValue, clinitAssignedValue);
    declarationInClass.putBooleanProp(Node.IS_CONSTANT_VAR, true);
    // Sanity check
    checkState(NodeUtil.isLiteralValue(declarationAssignedValue, false));
}

11. CheckSideEffects#addExtern()

View license
private void addExtern() {
    Node name = IR.name(PROTECTOR_FN);
    name.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    Node var = IR.var(name);
    // Add "@noalias" so we can strip the method when AliasExternals is enabled.
    JSDocInfoBuilder builder = new JSDocInfoBuilder(false);
    builder.recordNoAlias();
    var.setJSDocInfo(builder.build());
    CompilerInput input = compiler.getSynthesizedExternsInput();
    name.setStaticSourceFile(input.getSourceFile());
    var.setStaticSourceFile(input.getSourceFile());
    input.getAstRoot(compiler).addChildrenToBack(var);
    compiler.reportCodeChange();
}

12. GatherSideEffectSubexpressionsCallbackTest#getSideEffectsAndNode()

View license
private Node getSideEffectsAndNode() {
    Node andNode = new Node(Token.AND);
    Node assign = new Node(Token.ASSIGN);
    assign.addChildToBack(Node.newString(Token.NAME, "bar"));
    assign.addChildToBack(Node.newNumber(0));
    andNode.addChildToBack(Node.newString(Token.NAME, "foo"));
    andNode.addChildToBack(assign);
    return andNode;
}

13. MinimizedConditionTest#parseExpr()

View license
private static Node parseExpr(String code) {
    Compiler compiler = new Compiler();
    List<SourceFile> input = ImmutableList.of(SourceFile.fromCode("code", code));
    List<SourceFile> externs = new ArrayList<>();
    compiler.init(externs, input, new CompilerOptions());
    Node root = compiler.parseInputs();
    assertNotNull("Unexpected parse error(s): " + Joiner.on("\n").join(compiler.getErrors()), root);
    Node externsRoot = root.getFirstChild();
    Node mainRoot = externsRoot.getNext();
    Node script = mainRoot.getFirstChild();
    Node exprResult = script.getFirstChild();
    return exprResult.getFirstChild();
}

14. NodeUtilTest#testLhsByDestructuring1()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring1() {
    Node root = parse("var [a, b] = obj;");
    Node destructLhs = root.getFirstFirstChild();
    Preconditions.checkArgument(destructLhs.isDestructuringLhs());
    Node destructPat = destructLhs.getFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Node nameNodeB = nameNodeA.getNext();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    Preconditions.checkState(nameNodeB.getString().equals("b"), nameNodeB);
    Node nameNodeObj = destructPat.getNext();
    Preconditions.checkState(nameNodeObj.getString().equals("obj"), nameNodeObj);
    assertLhsByDestructuring(nameNodeA);
    assertLhsByDestructuring(nameNodeB);
    assertNotLhsByDestructuring(nameNodeObj);
}

15. NodeUtilTest#testLhsByDestructuring1c()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring1c() {
    Node root = parse("var {a, b} = obj;");
    Node destructLhs = root.getFirstFirstChild();
    Preconditions.checkArgument(destructLhs.isDestructuringLhs());
    Node destructPat = destructLhs.getFirstChild();
    Preconditions.checkArgument(destructPat.isObjectPattern());
    Node strKeyNodeA = destructPat.getFirstChild();
    Node strKeyNodeB = strKeyNodeA.getNext();
    Preconditions.checkState(strKeyNodeA.getString().equals("a"), strKeyNodeA);
    Preconditions.checkState(strKeyNodeB.getString().equals("b"), strKeyNodeB);
    Node nameNodeObj = destructPat.getNext();
    Preconditions.checkState(nameNodeObj.getString().equals("obj"), nameNodeObj);
    assertLhsByDestructuring(strKeyNodeA);
    assertLhsByDestructuring(strKeyNodeB);
    assertNotLhsByDestructuring(nameNodeObj);
}

16. NodeUtilTest#testLhsByDestructuring5()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring5() {
    Node root = parse("function fn([a, b] = [c, d]){}");
    Node destructPat = root.getFirstChild().getSecondChild().getFirstFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Node nameNodeB = destructPat.getLastChild();
    Node nameNodeC = destructPat.getNext().getFirstChild();
    Node nameNodeD = destructPat.getNext().getLastChild();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    Preconditions.checkState(nameNodeB.getString().equals("b"), nameNodeB);
    Preconditions.checkState(nameNodeC.getString().equals("c"), nameNodeC);
    Preconditions.checkState(nameNodeD.getString().equals("d"), nameNodeD);
    assertLhsByDestructuring(nameNodeA);
    assertLhsByDestructuring(nameNodeB);
    assertNotLhsByDestructuring(nameNodeC);
    assertNotLhsByDestructuring(nameNodeD);
}

17. ReplaceMessages#updateFunctionNode()

View license
/**
   * 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));
    // these functions.
    if (newBlockNode.checkTreeEquals(oldBlockNode) != null) {
        newBlockNode.useSourceInfoIfMissingFromForTree(oldBlockNode);
        functionNode.replaceChild(oldBlockNode, newBlockNode);
        compiler.reportCodeChange();
    }
}

18. CombinedCompilerPassTest#createPostOrderAlphabet()

View license
/**
   * Returns a Node tree with the post-order traversal a b c d e f g h i j k l m
   * and the in-order traversal m d a b c h e f g l i j k:
   *
   *                                   m
   *                         ,---------|---------.
   *                         d         h         l
   *                      ,--|--.   ,--|--.   ,--|--.
   *                      a  b  c   e  f  g   i  j  k
   *
   */
private static Node createPostOrderAlphabet() {
    Node a = Node.newString("a");
    Node b = Node.newString("b");
    Node c = Node.newString("c");
    Node d = Node.newString("d");
    Node e = Node.newString("e");
    Node f = Node.newString("f");
    Node g = Node.newString("g");
    Node h = Node.newString("h");
    Node i = Node.newString("i");
    Node j = Node.newString("j");
    Node k = Node.newString("k");
    Node l = Node.newString("l");
    Node m = Node.newString("m");
    d.addChildToBack(a);
    d.addChildToBack(b);
    d.addChildToBack(c);
    h.addChildrenToBack(e);
    h.addChildrenToBack(f);
    h.addChildrenToBack(g);
    l.addChildToBack(i);
    l.addChildToBack(j);
    l.addChildToBack(k);
    m.addChildToBack(d);
    m.addChildToBack(h);
    m.addChildToBack(l);
    return m;
}

19. Es6SyntacticScopeCreatorTest#testCatchInFunction()

View license
public void testCatchInFunction() {
    String js = "function f(e) { try {} catch (e) {} }";
    Node root = getRoot(js);
    Node fNode = root.getFirstChild();
    Scope globalScope = scopeCreator.createScope(root, null);
    Scope fScope = scopeCreator.createScope(fNode, globalScope);
    assertTrue(fScope.isDeclared("e", false));
    Node fBlock = fNode.getLastChild();
    Scope fBlockScope = scopeCreator.createScope(fBlock, fScope);
    Node tryBlock = fBlock.getFirstFirstChild();
    Scope tryScope = scopeCreator.createScope(tryBlock, fBlockScope);
    Node catchBlock = tryBlock.getNext();
    Scope catchScope = scopeCreator.createScope(catchBlock, tryScope);
    assertTrue(catchScope.isDeclared("e", false));
}

20. NodeUtilTest#testIsControlStructureCodeBlock()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testIsControlStructureCodeBlock() {
    Node root = parse("if (x) foo(); else boo();");
    Node ifNode = root.getFirstChild();
    Node ifCondition = ifNode.getFirstChild();
    Node ifCase = ifNode.getSecondChild();
    Node elseCase = ifNode.getLastChild();
    assertFalse(NodeUtil.isControlStructureCodeBlock(ifNode, ifCondition));
    assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, ifCase));
    assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, elseCase));
}

21. NodeUtilTest#testLhsByDestructuring6()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring6() {
    Node root = parse("for ([{a: b}] of c) {}");
    Node destructPat = root.getFirstFirstChild().getFirstChild();
    Preconditions.checkArgument(destructPat.isObjectPattern() && destructPat.getParent().isArrayPattern());
    Node strKeyNodeA = destructPat.getFirstChild();
    Node nameNodeB = strKeyNodeA.getFirstChild();
    Node nameNodeC = destructPat.getParent().getNext();
    Preconditions.checkState(strKeyNodeA.getString().equals("a"), strKeyNodeA);
    Preconditions.checkState(nameNodeB.getString().equals("b"), nameNodeB);
    Preconditions.checkState(nameNodeC.getString().equals("c"), nameNodeC);
    assertNotLhsByDestructuring(strKeyNodeA);
    assertLhsByDestructuring(nameNodeB);
    assertNotLhsByDestructuring(nameNodeC);
}

22. NodeUtilTest#testLhsByDestructuring6b()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring6b() {
    Node root = parse("for ([{a: b}] in c) {}");
    Node destructPat = root.getFirstFirstChild().getFirstChild();
    Preconditions.checkArgument(destructPat.isObjectPattern() && destructPat.getParent().isArrayPattern());
    Node strKeyNodeA = destructPat.getFirstChild();
    Node nameNodeB = strKeyNodeA.getFirstChild();
    Node nameNodeC = destructPat.getParent().getNext();
    Preconditions.checkState(strKeyNodeA.getString().equals("a"), strKeyNodeA);
    Preconditions.checkState(nameNodeB.getString().equals("b"), nameNodeB);
    Preconditions.checkState(nameNodeC.getString().equals("c"), nameNodeC);
    assertNotLhsByDestructuring(strKeyNodeA);
    assertLhsByDestructuring(nameNodeB);
    assertNotLhsByDestructuring(nameNodeC);
}

23. NodeUtilTest#testLhsByDestructuring6c()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring6c() {
    Node root = parse("for (var [{a: b}] = [{a: 1}];;) {}");
    Node destructArr = root.getFirstFirstChild().getFirstFirstChild();
    Preconditions.checkArgument(destructArr.isArrayPattern());
    Node destructPat = destructArr.getFirstChild();
    Preconditions.checkArgument(destructPat.isObjectPattern() && destructPat.getParent().isArrayPattern());
    Node strKeyNodeA = destructPat.getFirstChild();
    Node nameNodeB = strKeyNodeA.getFirstChild();
    Preconditions.checkState(strKeyNodeA.getString().equals("a"), strKeyNodeA);
    Preconditions.checkState(nameNodeB.getString().equals("b"), nameNodeB);
    assertNotLhsByDestructuring(strKeyNodeA);
    assertLhsByDestructuring(nameNodeB);
}

24. TypeCheckTest#testTypeCheckStandaloneAST()

Project: closure-compiler
Source File: TypeCheckTest.java
View license
public void testTypeCheckStandaloneAST() {
    Node n = compiler.parseTestCode("function Foo() { }");
    typeCheck(n);
    MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator(new TypedScopeCreator(compiler));
    TypedScope topScope = scopeCreator.createScope(n, null);
    Node second = compiler.parseTestCode("new Foo");
    Node externs = new Node(Token.BLOCK);
    Node externAndJsRoot = new Node(Token.BLOCK, externs, second);
    externAndJsRoot.setIsSyntheticBlock(true);
    new TypeCheck(compiler, new SemanticReverseAbstractInterpreter(registry), registry, topScope, scopeCreator, CheckLevel.WARNING).process(null, second);
    assertEquals(1, compiler.getWarningCount());
    assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description);
}

25. ClosureRewriteModule#exportTheEmptyBinaryNamespaceAt()

View license
/**
   * Add the missing "var module$exports$pkg$Foo = {};" line.
   */
private void exportTheEmptyBinaryNamespaceAt(Node atNode, AddAt addAt) {
    if (currentScript.declareLegacyNamespace) {
        return;
    }
    Node binaryNamespaceName = IR.name(currentScript.getBinaryNamespace());
    binaryNamespaceName.putProp(Node.ORIGINALNAME_PROP, currentScript.legacyNamespace);
    Node binaryNamespaceExportNode = IR.var(binaryNamespaceName, IR.objectlit());
    if (addAt == AddAt.BEFORE) {
        atNode.getParent().addChildBefore(binaryNamespaceExportNode, atNode);
    } else if (addAt == AddAt.AFTER) {
        atNode.getParent().addChildAfter(binaryNamespaceExportNode, atNode);
    }
    binaryNamespaceExportNode.putBooleanProp(Node.IS_NAMESPACE, true);
    binaryNamespaceExportNode.srcrefTree(atNode);
    markConst(binaryNamespaceExportNode);
    compiler.reportCodeChange();
    currentScript.hasCreatedExportObject = true;
}

26. CollapseProperties#flattenSimpleStubDeclaration()

View license
/**
   * Flattens a stub declaration.
   * This is mostly a hack to support legacy users.
   */
private void flattenSimpleStubDeclaration(Name name, String alias) {
    Ref ref = Iterables.getOnlyElement(name.getRefs());
    Node nameNode = NodeUtil.newName(compiler, alias, ref.node, name.getFullName());
    Node varNode = IR.var(nameNode).useSourceInfoIfMissingFrom(nameNode);
    Preconditions.checkState(ref.node.getParent().isExprResult());
    Node parent = ref.node.getParent();
    Node grandparent = parent.getParent();
    grandparent.replaceChild(parent, varNode);
    compiler.reportCodeChange();
}

27. Es6TypedToEs6Converter#createIObject()

View license
private JSTypeExpression createIObject(Node indexSignature) {
    Node indexType = convertWithLocation(indexSignature.getFirstChild().getDeclaredTypeExpression());
    Node declaredType = convertWithLocation(indexSignature.getDeclaredTypeExpression());
    Node block = new Node(Token.BLOCK, indexType, declaredType);
    Node iObject = IR.string("IObject");
    iObject.addChildrenToFront(block);
    JSTypeExpression bang = new JSTypeExpression(new Node(Token.BANG, iObject).useSourceInfoIfMissingFromForTree(indexSignature), indexSignature.getSourceFileName());
    indexSignature.detachFromParent();
    compiler.reportCodeChange();
    return bang;
}

28. ExtractPrototypeMemberDeclarations#replacePrototypeMemberDeclaration()

View license
/**
   * Replaces a member declaration to an assignment to the temp prototype
   * object.
   */
private void replacePrototypeMemberDeclaration(PrototypeMemberDeclaration declar) {
    // x.prototype.y = ...  ->  t.y = ...
    Node assignment = declar.node.getFirstChild();
    Node lhs = assignment.getFirstChild();
    Node name = NodeUtil.newQName(compiler, prototypeAlias + "." + declar.memberName, declar.node, declar.memberName);
    // Save the full prototype path on the left hand side of the assignment
    // for debugging purposes.
    // declar.lhs = x.prototype.y so first child of the first child
    // is 'x'.
    Node accessNode = declar.lhs.getFirstFirstChild();
    String originalName = accessNode.getOriginalName();
    String className = originalName != null ? originalName : "?";
    NodeUtil.setDebugInformation(name.getFirstChild(), lhs, className + ".prototype");
    assignment.replaceChild(lhs, name);
}

29. J2clEqualitySameRewriterPass#trySubstituteEqualitySame()

View license
private void trySubstituteEqualitySame(Node callNode) {
    Node firstExpr = callNode.getSecondChild();
    Node secondExpr = callNode.getLastChild();
    if (!NodeUtil.isLiteralValue(firstExpr, true) && !NodeUtil.isLiteralValue(secondExpr, true)) {
        return;
    }
    // At least one is literal value. So we can replace w/ a simpler form.
    firstExpr.detachFromParent();
    secondExpr.detachFromParent();
    Node replacement = asEqOperation(firstExpr, secondExpr);
    callNode.getParent().replaceChild(callNode, replacement.useSourceInfoIfMissingFrom(callNode));
    compiler.reportCodeChange();
}

30. ExpressionDecomposer#findInjectionPoint()

View license
/**
   * @return For the subExpression, find the nearest statement Node before which
   * it can be inlined.  Null if no such location can be found.
   */
static Node findInjectionPoint(Node subExpression) {
    Node expressionRoot = findExpressionRoot(subExpression);
    Preconditions.checkNotNull(expressionRoot);
    Node injectionPoint = expressionRoot;
    Node parent = injectionPoint.getParent();
    while (parent.isLabel()) {
        injectionPoint = parent;
        parent = injectionPoint.getParent();
    }
    Preconditions.checkState(NodeUtil.isStatementBlock(injectionPoint.getParent()));
    return injectionPoint;
}

31. GenerateExports#addStatement()

View license
private void addStatement(Node context, Node stmt) {
    CodingConvention convention = compiler.getCodingConvention();
    Node n = context;
    Node exprRoot = n;
    while (!NodeUtil.isStatementBlock(exprRoot.getParent())) {
        exprRoot = exprRoot.getParent();
    }
    // come right after the class definition, so move the export after that.
    while (true) {
        Node next = exprRoot.getNext();
        if (next != null && NodeUtil.isExprCall(next) && convention.getClassesDefinedByCall(next.getFirstChild()) != null) {
            exprRoot = next;
        } else {
            break;
        }
    }
    Node block = exprRoot.getParent();
    block.addChildAfter(stmt, exprRoot);
}

32. CheckInterfaces#visit()

View license
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
    if (!isInterface(n)) {
        return;
    }
    Node args = n.getSecondChild();
    if (args.hasChildren()) {
        t.report(args.getFirstChild(), INTERFACE_SHOULD_NOT_TAKE_ARGS);
    }
    Node block = n.getLastChild();
    if (block.hasChildren()) {
        t.report(block.getFirstChild(), INTERFACE_FUNCTION_NOT_EMPTY);
    }
}

33. AstValidator#validateClassHelper()

Project: closure-compiler
Source File: AstValidator.java
View license
private void validateClassHelper(Node n, boolean isAmbient) {
    validateEs6Feature("classes", n);
    validateNodeType(Token.CLASS, n);
    validateChildCount(n);
    Node name = n.getFirstChild();
    if (name.isEmpty()) {
        validateChildless(name);
    } else {
        validateName(name);
    }
    Node superClass = name.getNext();
    if (superClass.isEmpty()) {
        validateChildless(superClass);
    } else {
        validateExpression(superClass);
    }
    validateClassMembers(n.getLastChild(), isAmbient);
}

34. ClosureOptimizePrimitives#processRenamePropertyCall()

View license
/**
   * Converts all of the given call nodes to object literals that are safe to
   * do so.
   */
private void processRenamePropertyCall(Node callNode) {
    Node nameNode = callNode.getFirstChild();
    if (nameNode.matchesQualifiedName(NodeUtil.JSC_PROPERTY_NAME_FN)) {
        return;
    }
    Node newTarget = IR.name(NodeUtil.JSC_PROPERTY_NAME_FN).copyInformationFrom(nameNode);
    newTarget.setOriginalName(nameNode.getOriginalQualifiedName());
    callNode.replaceChild(nameNode, newTarget);
    callNode.putBooleanProp(Node.FREE_CALL, true);
    compiler.reportCodeChange();
}

35. DartSuperAccessorsPass#visitSuperSet()

View license
private void visitSuperSet(Node superSet) {
    Preconditions.checkArgument(superSet.isAssign());
    // First, recurse on the assignment's right-hand-side.
    NodeTraversal.traverseEs6(compiler, superSet.getLastChild(), this);
    Node rhs = superSet.getLastChild();
    Node superGet = superSet.getFirstChild();
    Node name = superGet.getLastChild().cloneTree();
    Node callSuperSet = IR.call(NodeUtil.newQName(compiler, CALL_SUPER_SET).srcrefTree(superSet), IR.thisNode().srcref(superSet), superGet.isGetProp() ? renameProperty(name) : name, rhs.cloneTree());
    replace(superSet, callSuperSet);
    reportEs6Change();
}

36. DartSuperAccessorsPass#renameProperty()

View license
/**
   * Wraps a property string in a JSCompiler_renameProperty call.
   *
   * <p>Should only be called in phases running before {@link RenameProperties},
   * if such a pass is even used (see {@link #renameProperties}).
   */
private Node renameProperty(Node propertyName) {
    Preconditions.checkArgument(propertyName.isString());
    if (!renameProperties) {
        return propertyName;
    }
    Node call = IR.call(IR.name(NodeUtil.JSC_PROPERTY_NAME_FN).srcref(propertyName), propertyName);
    call.srcref(propertyName);
    call.putBooleanProp(Node.FREE_CALL, true);
    call.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    return call;
}

37. Es6RewriteGenerators#visitYieldExpr()

View license
private void visitYieldExpr(Node n, Node parent) {
    Node enclosingStatement = NodeUtil.getEnclosingStatement(n);
    Node yieldStatement = IR.exprResult(n.hasChildren() ? IR.yield(n.removeFirstChild()) : IR.yield());
    Node yieldResult = IR.name(GENERATOR_NEXT_ARG + generatorCounter.get());
    Node yieldResultDecl = IR.var(yieldResult.cloneTree(), IR.name(GENERATOR_NEXT_ARG));
    parent.replaceChild(n, yieldResult);
    enclosingStatement.getParent().addChildBefore(yieldStatement, enclosingStatement);
    enclosingStatement.getParent().addChildBefore(yieldResultDecl, enclosingStatement);
    visitYieldThrows(yieldStatement, yieldStatement.getParent());
    compiler.reportCodeChange();
}

38. NewTypeInference#isAllowedToNotReturn()

View license
private static boolean isAllowedToNotReturn(NTIScope methodScope) {
    Node fn = methodScope.getRoot();
    if (fn.isFromExterns()) {
        return true;
    }
    if (!NodeUtil.isPrototypeMethod(fn)) {
        return false;
    }
    JSType maybeInterface;
    Node ntQnameNode = NodeUtil.getPrototypeClassName(fn.getParent().getFirstChild());
    if (ntQnameNode.isName()) {
        maybeInterface = methodScope.getDeclaredTypeOf(ntQnameNode.getString());
    } else {
        QualifiedName ntQname = QualifiedName.fromNode(ntQnameNode);
        JSType rootNamespace = methodScope.getDeclaredTypeOf(ntQname.getLeftmostName());
        maybeInterface = rootNamespace == null ? null : rootNamespace.getProp(ntQname.getAllButLeftmost());
    }
    return maybeInterface != null && maybeInterface.isInterfaceDefinition();
}

39. PeepholeCollectPropertyAssignments#isPropertyAssignmentToName()

View license
private static boolean isPropertyAssignmentToName(Node propertyCandidate) {
    if (propertyCandidate == null) {
        return false;
    }
    // Must be an assignment...
    if (!NodeUtil.isExprAssign(propertyCandidate)) {
        return false;
    }
    Node expr = propertyCandidate.getFirstChild();
    // to a property...
    Node lhs = expr.getFirstChild();
    if (!NodeUtil.isGet(lhs)) {
        return false;
    }
    // of a variable.
    Node obj = lhs.getFirstChild();
    return obj.isName();
}

40. ParserTest#testVarSourceLocations()

Project: closure-compiler
Source File: ParserTest.java
View license
/** @bug 19100575 */
public void testVarSourceLocations() {
    isIdeMode = true;
    Node n = parse("var x, y = 1;");
    Node var = n.getFirstChild();
    assertNode(var).hasType(Token.VAR);
    Node x = var.getFirstChild();
    assertNode(x).hasType(Token.NAME);
    assertNode(x).hasCharno("var ".length());
    Node y = x.getNext();
    assertNode(y).hasType(Token.NAME);
    assertNode(y).hasCharno("var x, ".length());
    assertNode(y).hasLength("y = 1".length());
}

41. ProcessClosurePrimitivesTest#testSourcePositionPreservation()

View license
public void testSourcePositionPreservation() {
    test("goog.provide('foo.bar.baz');", "/** @const */ var foo = {};" + "/** @const */ foo.bar = {};" + "/** @const */ foo.bar.baz = {};");
    Node root = getLastCompiler().getRoot();
    Node fooDecl = findQualifiedNameNode("foo", root);
    Node fooBarDecl = findQualifiedNameNode("foo.bar", root);
    Node fooBarBazDecl = findQualifiedNameNode("foo.bar.baz", root);
    assertEquals(1, fooDecl.getLineno());
    assertEquals(14, fooDecl.getCharno());
    assertEquals(1, fooBarDecl.getLineno());
    assertEquals(18, fooBarDecl.getCharno());
    assertEquals(1, fooBarBazDecl.getLineno());
    assertEquals(22, fooBarBazDecl.getCharno());
}

42. TypeCheckTest#parseAndTypeCheckWithScope()

Project: closure-compiler
Source File: TypeCheckTest.java
View license
private TypeCheckResult parseAndTypeCheckWithScope(String externs, String js) {
    compiler.init(ImmutableList.of(SourceFile.fromCode("[externs]", externs)), ImmutableList.of(SourceFile.fromCode("[testcode]", js)), compiler.getOptions());
    Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler);
    Node externsNode = compiler.getInput(new InputId("[externs]")).getAstRoot(compiler);
    Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n);
    externAndJsRoot.setIsSyntheticBlock(true);
    assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount());
    TypedScope s = makeTypeCheck().processForTesting(externsNode, n);
    return new TypeCheckResult(n, s);
}

43. ApplySuggestedFixesTest#testApplySuggestedFixes_multipleFixesInJsdoc()

View license
@Test
public void testApplySuggestedFixes_multipleFixesInJsdoc() throws Exception {
    String code = "/** @type {Array<Foo>} */\nvar arr = [new Foo()];";
    Compiler compiler = getCompiler(code);
    Node root = compileToScriptRoot(compiler);
    Node varNode = root.getFirstChild();
    Node jsdocRoot = Iterables.getOnlyElement(varNode.getJSDocInfo().getTypeNodes());
    SuggestedFix fix1 = new SuggestedFix.Builder().insertBefore(jsdocRoot, "!").build();
    Node foo = jsdocRoot.getFirstFirstChild();
    SuggestedFix fix2 = new SuggestedFix.Builder().insertBefore(foo, "!").build();
    List<SuggestedFix> fixes = ImmutableList.of(fix1, fix2);
    Map<String, String> codeMap = ImmutableMap.of("test", code);
    Map<String, String> newCodeMap = ApplySuggestedFixes.applySuggestedFixesToCode(fixes, codeMap);
    assertThat(newCodeMap).hasSize(1);
    assertThat(newCodeMap).containsEntry("test", "/** @type {!Array<!Foo>} */\nvar arr = [new Foo()];");
}

44. ProcessClosurePrimitives#replaceGoogDefines()

View license
/**
   * @param n
   */
private void replaceGoogDefines(Node n) {
    Node parent = n.getParent();
    Preconditions.checkState(parent.isExprResult());
    String name = n.getSecondChild().getString();
    Node value = n.getChildAtIndex(2).detachFromParent();
    Node replacement = NodeUtil.newQNameDeclaration(compiler, name, value, n.getJSDocInfo());
    replacement.useSourceInfoIfMissingFromForTree(parent);
    parent.getParent().replaceChild(parent, replacement);
    compiler.reportCodeChange();
}

45. ErrorToFixMapper#getFixForUnsortedRequiresOrProvides()

View license
private static SuggestedFix getFixForUnsortedRequiresOrProvides(String closureFunction, JSError error, AbstractCompiler compiler) {
    SuggestedFix.Builder fix = new SuggestedFix.Builder();
    fix.setOriginalMatchedNode(error.node);
    Node script = NodeUtil.getEnclosingScript(error.node);
    RequireProvideSorter cb = new RequireProvideSorter(closureFunction);
    NodeTraversal.traverseEs6(compiler, script, cb);
    Node first = cb.calls.get(0);
    Node last = Iterables.getLast(cb.calls);
    cb.sortCallsAlphabetically();
    StringBuilder sb = new StringBuilder();
    for (Node n : cb.calls) {
        String statement = fix.generateCode(compiler, n);
        JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(n);
        if (jsDoc != null) {
            statement = jsDoc.getOriginalCommentString() + "\n" + statement;
        }
        sb.append(statement);
    }
    // Trim to remove the newline after the last goog.require/provide.
    String newContent = sb.toString().trim();
    return fix.replaceRange(first, last, newContent).build();
}

46. Es6SyntacticScopeCreatorTest#testOnlyOneDeclaration()

View license
public void testOnlyOneDeclaration() {
    String js = "function f(x) { if (!x) var x = 6; }";
    Node root = getRoot(js);
    Node fNode = root.getFirstChild();
    Scope globalScope = scopeCreator.createScope(root, null);
    Scope fScope = scopeCreator.createScope(fNode, globalScope);
    assertTrue(fScope.isDeclared("x", false));
    Node fBlock = fNode.getLastChild();
    Scope fBlockScope = scopeCreator.createScope(fBlock, fScope);
    assertTrue(fBlockScope.isDeclared("x", false));
    Node ifBlock = fBlock.getFirstChild().getLastChild();
    Scope ifBlockScope = scopeCreator.createScope(ifBlock, fBlockScope);
    assertFalse(ifBlockScope.isDeclared("x", false));
}

47. NodeUtilTest#testRemoveChildBlock()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testRemoveChildBlock() {
    // Test removing the inner block.
    Node actual = parse("{{x()}}");
    Node outerBlockNode = actual.getFirstChild();
    Node innerBlockNode = outerBlockNode.getFirstChild();
    innerBlockNode.setIsSyntheticBlock(true);
    NodeUtil.removeChild(outerBlockNode, innerBlockNode);
    String expected = "{{}}";
    String difference = parse(expected).checkTreeEquals(actual);
    if (difference != null) {
        fail("Nodes do not match:\n" + difference);
    }
}

48. NodeUtilTest#testRemoveTryChild3()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testRemoveTryChild3() {
    // Test removing the catch clause.
    Node actual = parse("try {foo()} catch(e) {} finally {}");
    Node tryNode = actual.getFirstChild();
    Node catchBlocks = tryNode.getSecondChild();
    Node catchBlock = catchBlocks.getFirstChild();
    NodeUtil.removeChild(catchBlocks, catchBlock);
    String expected = "try {foo()} finally {}";
    String difference = parse(expected).checkTreeEquals(actual);
    if (difference != null) {
        fail("Nodes do not match:\n" + difference);
    }
}

49. NodeUtilTest#testRemoveTryChild5()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testRemoveTryChild5() {
    Node actual = parse("try {foo()} catch(e) {} finally {}");
    Node tryNode = actual.getFirstChild();
    Node catchBlocks = tryNode.getSecondChild();
    Node catchBlock = catchBlocks.getFirstChild();
    NodeUtil.removeChild(catchBlocks, catchBlock);
    String expected = "try {foo()} finally {}";
    String difference = parse(expected).checkTreeEquals(actual);
    if (difference != null) {
        fail("Nodes do not match:\n" + difference);
    }
}

50. NodeUtilTest#testLhsByDestructuring4()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring4() {
    Node root = parse("for ([a, b] of X){}");
    Node destructPat = root.getFirstFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Node nameNodeB = destructPat.getLastChild();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    Preconditions.checkState(nameNodeB.getString().equals("b"), nameNodeB);
    assertLhsByDestructuring(nameNodeA);
    assertLhsByDestructuring(nameNodeB);
}

51. NodeUtilTest#testLhsByDestructuring7()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring7() {
    Node root = parse("for ([a] of c) {}");
    Node destructPat = root.getFirstFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Node nameNodeC = destructPat.getNext();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    Preconditions.checkState(nameNodeC.getString().equals("c"), nameNodeC);
    assertLhsByDestructuring(nameNodeA);
    assertNotLhsByDestructuring(nameNodeC);
}

52. NodeUtilTest#testLhsByDestructuring7b()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring7b() {
    Node root = parse("for ([a] in c) {}");
    Node destructPat = root.getFirstFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Node nameNodeC = destructPat.getNext();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    Preconditions.checkState(nameNodeC.getString().equals("c"), nameNodeC);
    assertLhsByDestructuring(nameNodeA);
    assertNotLhsByDestructuring(nameNodeC);
}

53. NodeUtilTest#testLhsByDestructuring7c()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring7c() {
    Node root = parse("for (var [a] = [1];;) {}");
    Node destructLhs = root.getFirstFirstChild().getFirstChild();
    Preconditions.checkArgument(destructLhs.isDestructuringLhs());
    Node destructPat = destructLhs.getFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    assertLhsByDestructuring(nameNodeA);
}

54. NodeUtilTest#testLhsByDestructuring7d()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring7d() {
    Node root = parse("for (let [a] = [1];;) {}");
    Node destructLhs = root.getFirstFirstChild().getFirstChild();
    Preconditions.checkArgument(destructLhs.isDestructuringLhs());
    Node destructPat = destructLhs.getFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    assertLhsByDestructuring(nameNodeA);
}

55. NodeUtilTest#testLhsByDestructuring7e()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testLhsByDestructuring7e() {
    Node root = parse("for (const [a] = [1];;) {}");
    Node destructLhs = root.getFirstFirstChild().getFirstChild();
    Preconditions.checkArgument(destructLhs.isDestructuringLhs());
    Node destructPat = destructLhs.getFirstChild();
    Preconditions.checkArgument(destructPat.isArrayPattern());
    Node nameNodeA = destructPat.getFirstChild();
    Preconditions.checkState(nameNodeA.getString().equals("a"), nameNodeA);
    assertLhsByDestructuring(nameNodeA);
}

56. Es6SyntacticScopeCreatorTest#testVarAfterLet()

View license
public void testVarAfterLet() {
    String js = Joiner.on('\n').join("function f() {", "  if (a) {", "    let x;", "  }", "  var y;", "}");
    Node root = getRoot(js);
    Node fBlock = root.getFirstChild().getLastChild();
    Scope fBlockScope = scopeCreator.createScope(fBlock, null);
    assertFalse(fBlockScope.isDeclared("x", false));
    assertTrue(fBlockScope.isDeclared("y", false));
    Node ifBlock = fBlock.getFirstChild().getLastChild();
    Scope ifBlockScope = scopeCreator.createScope(ifBlock, fBlockScope);
    assertTrue(ifBlockScope.isDeclared("x", false));
    assertFalse(ifBlockScope.isDeclared("y", false));
}

57. CoverageInstrumentationPass#createConditionalObjectDecl()

View license
private Node createConditionalObjectDecl(String name, Node srcref) {
    String jscovData;
    if (instrumentOption != InstrumentOption.LINE_ONLY) {
        jscovData = "{fileNames:[], instrumentedLines: [], executedLines: []," + "branchPrsent:[], branchesInLine: []}";
    } else {
        jscovData = "{fileNames:[], instrumentedLines: [], executedLines: []}";
    }
    String jscovDecl = " var " + name + " = window.top.__jscov || " + "(window.top.__jscov = " + jscovData + ");";
    Node script = compiler.parseSyntheticCode(jscovDecl);
    Node var = script.removeFirstChild();
    return var.useSourceInfoIfMissingFromForTree(srcref);
}

58. CoverageInstrumentationCallback#newInstrumentationNode()

View license
/**
   * Creates and return a new instrumentation node. The instrumentation Node is
   * of the form: "arrayName[lineNumber] = true;"
   * Note 1: Node returns a 1-based line number.
   * Note 2: Line numbers in instrumentation are made 0-based. This is done to
   * map to their bit representation in BitField. Thus, there's a one-to-one
   * correspondence of the line number seen on instrumented files and their bit
   * encodings.
   *
   * @return an instrumentation node corresponding to the line number
   */
private Node newInstrumentationNode(NodeTraversal traversal, Node node) {
    int lineNumber = node.getLineno();
    String arrayName = createArrayName(traversal);
    // Create instrumentation Node
    Node getElemNode = IR.getelem(IR.name(arrayName), // Make line number 0-based
    IR.number(lineNumber - 1));
    Node exprNode = IR.exprResult(IR.assign(getElemNode, IR.trueNode()));
    // Note line as instrumented
    String fileName = getFileName(traversal);
    if (!instrumentationData.containsKey(fileName)) {
        instrumentationData.put(fileName, new FileInstrumentationData(fileName, arrayName));
    }
    instrumentationData.get(fileName).setLineAsInstrumented(lineNumber);
    return exprNode.useSourceInfoIfMissingFromForTree(node);
}

59. Compiler#addNewScript()

Project: closure-compiler
Source File: Compiler.java
View license
/**
   * Adds a new Script AST to the compile state. If a script for the same file
   * already exists the script will not be added, instead a call to
   * #replaceScript should be used.
   *
   * @param ast the ast of the new file
   */
public void addNewScript(JsAst ast) {
    if (!addNewSourceAst(ast)) {
        return;
    }
    Node emptyScript = new Node(Token.SCRIPT);
    InputId inputId = ast.getInputId();
    emptyScript.setInputId(inputId);
    emptyScript.setStaticSourceFile(SourceFile.fromCode(inputId.getIdName(), ""));
    processNewScript(ast, emptyScript);
}

60. ClosureRewriteModule#maybeSplitMultiVar()

View license
private void maybeSplitMultiVar(Node rhsNode) {
    Node statementNode = rhsNode.getParent().getParent();
    if (!statementNode.isVar() || !statementNode.hasMoreThanOneChild()) {
        return;
    }
    Node nameNode = rhsNode.getParent();
    nameNode.detachFromParent();
    rhsNode.detachFromParent();
    statementNode.getParent().addChildBefore(IR.var(nameNode, rhsNode), statementNode);
}

61. ClosureRewriteModule#maybeUpdateExportObjectLiteral()

View license
/**
   * For exports like "exports = {prop: value}" update the declarations to enforce
   * @const ness (and typedef exports).
   */
private void maybeUpdateExportObjectLiteral(NodeTraversal t, Node n) {
    if (!currentScript.isModule) {
        return;
    }
    Node parent = n.getParent();
    Node rhs = parent.getLastChild();
    if (rhs.isObjectLit()) {
        for (Node c = rhs.getFirstChild(); c != null; c = c.getNext()) {
            if (c.isComputedProp()) {
                t.report(c, INVALID_EXPORT_COMPUTED_PROPERTY);
            } else if (c.isStringKey()) {
                if (!c.hasChildren()) {
                    c.addChildToBack(IR.name(c.getString()).useSourceInfoFrom(c));
                }
                Node value = c.getFirstChild();
                maybeUpdateExportDeclToNode(t, c, value);
            }
        }
    }
}

62. CheckRequiresForConstructors#visitImportNode()

View license
private void visitImportNode(Node importNode) {
    Node defaultImport = importNode.getFirstChild();
    if (defaultImport.isName()) {
        visitRequire(defaultImport.getString(), importNode);
    }
    Node namedImports = defaultImport.getNext();
    if (namedImports.getType() == Token.IMPORT_SPECS) {
        for (Node importSpec : namedImports.children()) {
            visitRequire(importSpec.getLastChild().getString(), importNode);
        }
    }
}

63. AstValidator#validateObjectLitGetKey()

Project: closure-compiler
Source File: AstValidator.java
View license
private void validateObjectLitGetKey(Node n) {
    validateNodeType(Token.GETTER_DEF, n);
    validateChildCount(n);
    validateObjectLiteralKeyName(n);
    Node function = n.getFirstChild();
    validateFunctionExpression(function);
    // objlit get functions must be nameless, and must have zero parameters.
    if (!function.getFirstChild().getString().isEmpty()) {
        violation("Expected unnamed function expression.", n);
    }
    Node functionParams = function.getSecondChild();
    if (functionParams.hasChildren()) {
        violation("get methods must not have parameters.", n);
    }
}

64. AstValidator#validateInterface()

Project: closure-compiler
Source File: AstValidator.java
View license
private void validateInterface(Node n) {
    validateEs6TypedFeature("interface", n);
    validateNodeType(Token.INTERFACE, n);
    validateChildCount(n);
    Node name = n.getFirstChild();
    validateName(name);
    Node superTypes = name.getNext();
    if (superTypes.isEmpty()) {
        validateChildless(superTypes);
    } else {
        validateInterfaceExtends(superTypes);
    }
    validateInterfaceMembers(n.getLastChild());
}

65. MinimizeExitPoints#tryMinimizeSwitchCaseExits()

View license
/**
   * Attempt to remove explicit exits from switch cases that also occur implicitly
   * after the switch.
   */
void tryMinimizeSwitchCaseExits(Node n, Token exitType, @Nullable String labelName) {
    Preconditions.checkState(NodeUtil.isSwitchCase(n));
    Preconditions.checkState(n != n.getParent().getLastChild());
    Node block = n.getLastChild();
    Node maybeBreak = block.getLastChild();
    if (maybeBreak == null || !maybeBreak.isBreak() || maybeBreak.hasChildren()) {
        // Can not minimize exits from a case without an explicit break from the switch.
        return;
    }
    // Now try to minimize the exits of the last child before the break, if it is removed
    // look at what has become the child before the break.
    Node childBeforeBreak = block.getChildBefore(maybeBreak);
    while (childBeforeBreak != null) {
        Node c = childBeforeBreak;
        tryMinimizeExits(c, exitType, labelName);
        // If the node is still the last child, we are done.
        childBeforeBreak = block.getChildBefore(maybeBreak);
        if (c == childBeforeBreak) {
            break;
        }
    }
}

66. CheckJSDocStyle#checkInlineParams()

View license
/**
   * Checks that the inline type annotations are correct.
   */
private void checkInlineParams(NodeTraversal t, Node function) {
    Node paramList = NodeUtil.getFunctionParameters(function);
    for (Node param : paramList.children()) {
        JSDocInfo jsDoc = param.getJSDocInfo();
        if (jsDoc == null) {
            t.report(param, MISSING_PARAMETER_JSDOC);
            return;
        } else {
            JSTypeExpression paramType = jsDoc.getType();
            Preconditions.checkNotNull(paramType, "Inline JSDoc info should always have a type");
            checkParam(t, param, null, paramType);
        }
    }
}

67. InlineSimpleMethods#returnedExpression()

View license
/**
   * Return the node that represents the expression returned
   * by the method, given a FUNCTION node.
   */
private static Node returnedExpression(Node fn) {
    Node expectedBlock = getMethodBlock(fn);
    if (!expectedBlock.hasOneChild()) {
        return null;
    }
    Node expectedReturn = expectedBlock.getFirstChild();
    if (!expectedReturn.isReturn()) {
        return null;
    }
    if (!expectedReturn.hasOneChild()) {
        return null;
    }
    return expectedReturn.getLastChild();
}

68. GatherSideEffectSubexpressionsCallback#processHook()

View license
/**
   * Processes a HOOK expression.
   *
   * @return true to continue traversal, false otherwise
   */
boolean processHook(Node node) {
    Preconditions.checkArgument(node.isHook(), "Expected: HOOK, Got: %s", node.getType());
    Node condition = node.getFirstChild();
    Node ifBranch = condition.getNext();
    Node elseBranch = ifBranch.getNext();
    boolean thenHasSideEffects = NodeUtil.mayHaveSideEffects(ifBranch, compiler);
    boolean elseHasSideEffects = NodeUtil.mayHaveSideEffects(elseBranch, compiler);
    if (thenHasSideEffects || elseHasSideEffects) {
        accumulator.keepSimplifiedHookExpression(node, thenHasSideEffects, elseHasSideEffects);
        return false;
    } else {
        return true;
    }
}

69. ExternExportsPass#handleSymbolExportCall()

View license
private void handleSymbolExportCall(Node parent) {
    // (plus the GETPROP node itself).
    if (parent.getChildCount() != 3) {
        return;
    }
    Node thisNode = parent.getFirstChild();
    Node nameArg = thisNode.getNext();
    Node valueArg = nameArg.getNext();
    // then we have an export that we cannot statically identify.
    if (!nameArg.isString()) {
        return;
    }
    // Add the export to the list.
    this.exports.add(new SymbolExport(nameArg.getString(), valueArg));
}

70. Es6TypedToEs6Converter#convertNamedType()

View license
private Node convertNamedType(Node type) {
    Node oldNameNode = type.getFirstChild();
    Node newNameNode = maybeGetQualifiedNameNode(oldNameNode);
    if (newNameNode != oldNameNode) {
        type.replaceChild(oldNameNode, newNameNode);
    }
    Node propTree = type.getFirstChild();
    String dotted = propTree.getQualifiedName();
    // the type variables in scope, and use them during transpilation.
    return new Node(Token.BANG, IR.string(dotted));
}

71. TypeTransformationParser#validNativeTypeExpr()

View license
private boolean validNativeTypeExpr(Node expr) {
    // - A string
    if (!checkParameterCount(expr, Keywords.TYPEEXPR)) {
        return false;
    }
    Node typeString = getCallArgument(expr, 0);
    if (!typeString.isString()) {
        warnInvalidExpression("native type", expr);
        warnInvalidInside(Keywords.TYPEEXPR.name, expr);
        return false;
    }
    Node typeExpr = JsDocInfoParser.parseTypeString(typeString.getString());
    typeString.detachFromParent();
    expr.addChildToBack(typeExpr);
    return true;
}

72. JsDocInfoParser#parseRecordType()

View license
/**
   * RecordType := '{' FieldTypeList '}'
   */
private Node parseRecordType(JsDocToken token) {
    Node recordType = newNode(Token.LC);
    Node fieldTypeList = parseFieldTypeList(token);
    if (fieldTypeList == null) {
        return reportGenericTypeSyntaxWarning();
    }
    skipEOLs();
    if (!match(JsDocToken.RIGHT_CURLY)) {
        return reportTypeSyntaxWarning("msg.jsdoc.missing.rc");
    }
    next();
    recordType.addChildToBack(fieldTypeList);
    return recordType;
}

73. JsDocInfoParser#parseTypeExpressionList()

View license
/**
   * TypeExpressionList := TopLevelTypeExpression
   *     | TopLevelTypeExpression ',' TypeExpressionList
   */
private Node parseTypeExpressionList(JsDocToken token) {
    Node typeExpr = parseTopLevelTypeExpression(token);
    if (typeExpr == null) {
        return null;
    }
    Node typeList = IR.block();
    typeList.addChildToBack(typeExpr);
    while (match(JsDocToken.COMMA)) {
        next();
        skipEOLs();
        typeExpr = parseTopLevelTypeExpression(next());
        if (typeExpr == null) {
            return null;
        }
        typeList.addChildToBack(typeExpr);
    }
    return typeList;
}

74. OptimizeParameters#addVariableToFunction()

View license
/**
   * Adds a variable to the top of a function block.
   * @param function A function node.
   * @param varName The name of the variable.
   * @param value The initial value of the variable.
   */
private void addVariableToFunction(Node function, Node varName, Node value) {
    Preconditions.checkArgument(function.isFunction(), "Node must be a function.");
    Node block = function.getLastChild();
    Preconditions.checkArgument(block.isBlock(), "Node must be a block.");
    Preconditions.checkState(value.getParent() == null);
    Node stmt;
    if (varName != null) {
        stmt = NodeUtil.newVarNode(varName.getString(), value);
    } else {
        stmt = IR.exprResult(value);
    }
    block.addChildToFront(stmt);
    compiler.reportCodeChange();
}

75. NodeUtil#getObjectDefinedPropertiesKeys()

Project: closure-compiler
Source File: NodeUtil.java
View license
/**
   * @return A list of STRING_KEY properties defined by a Object.defineProperties(o, {...}) call
   */
static Iterable<Node> getObjectDefinedPropertiesKeys(Node definePropertiesCall) {
    Preconditions.checkArgument(NodeUtil.isObjectDefinePropertiesDefinition(definePropertiesCall));
    List<Node> properties = new ArrayList<>();
    Node objectLiteral = definePropertiesCall.getLastChild();
    for (Node key : objectLiteral.children()) {
        if (!key.isStringKey()) {
            continue;
        }
        properties.add(key);
    }
    return properties;
}

76. NodeUtil#newQNameDeclaration()

Project: closure-compiler
Source File: NodeUtil.java
View license
/**
   * Creates a node representing a qualified name.
   *
   * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
   * @return A VAR node, or an EXPR_RESULT node containing an ASSIGN or NAME node.
   */
public static Node newQNameDeclaration(AbstractCompiler compiler, String name, Node value, JSDocInfo info) {
    Node result;
    Node nameNode = newQName(compiler, name);
    if (nameNode.isName()) {
        result = value == null ? IR.var(nameNode) : IR.var(nameNode, value);
        result.setJSDocInfo(info);
    } else if (value != null) {
        result = IR.exprResult(IR.assign(nameNode, value));
        result.getFirstChild().setJSDocInfo(info);
    } else {
        result = IR.exprResult(nameNode);
        result.getFirstChild().setJSDocInfo(info);
    }
    return result;
}

77. NewTypeInference#analyzeGetElemBwd()

View license
private EnvTypePair analyzeGetElemBwd(Node expr, TypeEnv outEnv, JSType requiredType) {
    Node receiver = expr.getFirstChild();
    Node index = expr.getLastChild();
    JSType reqObjType = pickReqObjType(expr);
    EnvTypePair pair = analyzeExprBwd(receiver, outEnv, reqObjType);
    JSType recvType = pair.type;
    JSType indexType = recvType.getIndexType();
    if (indexType != null) {
        pair = analyzeExprBwd(index, pair.env, indexType);
        pair.type = getIndexedTypeOrUnknown(recvType);
        return pair;
    }
    if (index.isString()) {
        return analyzePropAccessBwd(receiver, index.getString(), outEnv, requiredType);
    }
    pair = analyzeExprBwd(index, outEnv);
    pair = analyzeExprBwd(receiver, pair.env, reqObjType);
    pair.type = requiredType;
    return pair;
}

78. NewTypeInference#analyzeAssignBwd()

View license
private EnvTypePair analyzeAssignBwd(Node expr, TypeEnv outEnv, JSType requiredType) {
    if (expr.getBooleanProp(Node.ANALYZED_DURING_GTI)) {
        return new EnvTypePair(outEnv, requiredType);
    }
    Node lhs = expr.getFirstChild();
    Node rhs = expr.getLastChild();
    if (lhs.getBooleanProp(Node.ANALYZED_DURING_GTI)) {
        return analyzeExprBwd(rhs, outEnv, markAndGetTypeOfPreanalyzedNode(lhs, outEnv, false));
    }
    // Here we analyze the LHS twice:
    // Once to find out what should be removed for the slicedEnv,
    // and again to take into account the side effects of the LHS itself.
    LValueResultBwd lvalue = analyzeLValueBwd(lhs, outEnv, requiredType, true);
    TypeEnv slicedEnv = lvalue.env;
    JSType rhsReqType = specializeKeep2ndWhenBottom(lvalue.type, requiredType);
    EnvTypePair pair = analyzeExprBwd(rhs, slicedEnv, rhsReqType);
    pair.env = analyzeLValueBwd(lhs, pair.env, requiredType, true).env;
    return pair;
}

79. NewTypeInference#analyzeHookFwd()

View license
private EnvTypePair analyzeHookFwd(Node expr, TypeEnv inEnv, JSType requiredType, JSType specializedType) {
    Node cond = expr.getFirstChild();
    Node thenBranch = cond.getNext();
    Node elseBranch = thenBranch.getNext();
    TypeEnv trueEnv = analyzeExprFwd(cond, inEnv, JSType.UNKNOWN, JSType.TRUTHY).env;
    TypeEnv falseEnv = analyzeExprFwd(cond, inEnv, JSType.UNKNOWN, JSType.FALSY).env;
    EnvTypePair thenPair = analyzeExprFwd(thenBranch, trueEnv, requiredType, specializedType);
    EnvTypePair elsePair = analyzeExprFwd(elseBranch, falseEnv, requiredType, specializedType);
    return EnvTypePair.join(thenPair, elsePair);
}

80. AttachJsdocsTest#testOldJsdocSwitch7()

View license
public void testOldJsdocSwitch7() {
    Node root = parse("switch (x) {" + "  case 1: " + "    /** attach */ y;" + "    /** attach */ z;" + "}");
    Node sw = root.getFirstChild();
    Node caseBody = sw.getSecondChild().getLastChild();
    assertThat(caseBody.getFirstFirstChild().getJSDocInfo()).isNotNull();
    assertThat(caseBody.getSecondChild().getFirstChild().getJSDocInfo()).isNotNull();
}

81. NodeUtilTest#testMergeBlock3()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testMergeBlock3() {
    // Test removing the initializer.
    String code = "foo:{a();boo()}";
    Node actual = parse("foo:{a();boo()}");
    Node parentLabel = actual.getFirstChild();
    Node childBlock = parentLabel.getLastChild();
    assertFalse(NodeUtil.tryMergeBlock(childBlock));
    String expected = code;
    String difference = parse(expected).checkTreeEquals(actual);
    assertNull("Nodes do not match:\n" + difference, difference);
}

82. NodeUtilTest#testMergeBlock1()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testMergeBlock1() {
    // Test removing the initializer.
    Node actual = parse("{{a();b();}}");
    Node parentBlock = actual.getFirstChild();
    Node childBlock = parentBlock.getFirstChild();
    assertTrue(NodeUtil.tryMergeBlock(childBlock));
    String expected = "{a();b();}";
    String difference = parse(expected).checkTreeEquals(actual);
    assertNull("Nodes do not match:\n" + difference, difference);
}

83. NodeUtilTest#testRemoveLabelChild2()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testRemoveLabelChild2() {
    // Test removing the first child.
    Node actual = parse("achoo: foo: goo()");
    Node labelNode = actual.getFirstChild();
    Node callExpressNode = labelNode.getLastChild();
    NodeUtil.removeChild(labelNode, callExpressNode);
    String expected = "";
    String difference = parse(expected).checkTreeEquals(actual);
    if (difference != null) {
        fail("Nodes do not match:\n" + difference);
    }
}

84. NodeUtilTest#testRemoveLabelChild1()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testRemoveLabelChild1() {
    // Test removing the first child.
    Node actual = parse("foo: goo()");
    Node labelNode = actual.getFirstChild();
    Node callExpressNode = labelNode.getLastChild();
    NodeUtil.removeChild(labelNode, callExpressNode);
    String expected = "";
    String difference = parse(expected).checkTreeEquals(actual);
    if (difference != null) {
        fail("Nodes do not match:\n" + difference);
    }
}

85. NodeUtilTest#testRemoveTryChild4()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testRemoveTryChild4() {
    // Test removing the catch clause without a finally.
    Node actual = parse("try {foo()} catch(e) {} finally {}");
    Node tryNode = actual.getFirstChild();
    Node catchBlocks = tryNode.getSecondChild();
    NodeUtil.removeChild(tryNode, catchBlocks);
    String expected = "try {foo()} finally {}";
    String difference = parse(expected).checkTreeEquals(actual);
    if (difference != null) {
        fail("Nodes do not match:\n" + difference);
    }
}

86. NodeUtilTest#testRemoveTryChild2()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testRemoveTryChild2() {
    // Test removing the try clause.
    Node actual = parse("try {foo()} catch(e) {} finally {}");
    Node tryNode = actual.getFirstChild();
    Node tryBlock = tryNode.getFirstChild();
    NodeUtil.removeChild(tryNode, tryBlock);
    String expected = "try {} catch(e) {} finally {}";
    String difference = parse(expected).checkTreeEquals(actual);
    if (difference != null) {
        fail("Nodes do not match:\n" + difference);
    }
}

87. NodeUtilTest#testRemoveTryChild1()

Project: closure-compiler
Source File: NodeUtilTest.java
View license
public void testRemoveTryChild1() {
    // Test removing the finally clause.
    Node actual = parse("try {foo()} catch(e) {} finally {}");
    Node tryNode = actual.getFirstChild();
    Node finallyBlock = tryNode.getLastChild();
    NodeUtil.removeChild(tryNode, finallyBlock);
    String expected = "try {foo()} catch(e) {}";
    String difference = parse(expected).checkTreeEquals(actual);
    if (difference != null) {
        fail("Nodes do not match:\n" + difference);
    }
}

88. LiveVariableAnalysisTest#computeLiveness()

View license
private static LiveVariablesAnalysis computeLiveness(String src) {
    Compiler compiler = new Compiler();
    CompilerOptions options = new CompilerOptions();
    options.setCodingConvention(new GoogleCodingConvention());
    compiler.initOptions(options);
    src = "function _FUNCTION(param1, param2){" + src + "}";
    Node n = compiler.parseTestCode(src).removeFirstChild();
    Node script = new Node(Token.SCRIPT, n);
    script.setInputId(new InputId("test"));
    assertEquals(0, compiler.getErrorCount());
    Scope scope = SyntacticScopeCreator.makeUntyped(compiler).createScope(n, Scope.createGlobalScope(script));
    ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, true);
    cfa.process(null, n);
    ControlFlowGraph<Node> cfg = cfa.getCfg();
    LiveVariablesAnalysis analysis = new LiveVariablesAnalysis(cfg, scope, compiler);
    analysis.analyze();
    return analysis;
}

89. JsdocToEs6TypedConverterTest#testCreateRecordType()

View license
public void testCreateRecordType() throws Exception {
    LinkedHashMap<String, TypeDeclarationNode> properties = new LinkedHashMap<>();
    properties.put("myNum", numberType());
    properties.put("myObject", null);
    TypeDeclarationNode node = recordType(properties);
    Node prop1 = IR.stringKey("myNum");
    prop1.addChildToFront(new TypeDeclarationNode(NUMBER_TYPE));
    Node prop2 = IR.stringKey("myObject");
    assertNode(node).isEqualTo(new TypeDeclarationNode(RECORD_TYPE, prop1, prop2));
}

90. IntegrationTestCase#parse()

View license
protected Node parse(String[] original, CompilerOptions options, boolean normalize) {
    Compiler compiler = new Compiler();
    List<SourceFile> inputs = new ArrayList<>();
    for (int i = 0; i < original.length; i++) {
        inputs.add(SourceFile.fromCode("input" + i, original[i]));
    }
    compiler.init(externs, inputs, options);
    checkUnexpectedErrorsOrWarnings(compiler, 0);
    Node all = compiler.parseInputs();
    checkUnexpectedErrorsOrWarnings(compiler, 0);
    Node n = all.getLastChild();
    Node externs = all.getFirstChild();
    (new CreateSyntheticBlocks(compiler, "synStart", "synEnd")).process(externs, n);
    if (normalize) {
        compiler.normalize();
    }
    return n;
}

91. FunctionArgumentInjectorTest#testNeededTemps()

View license
private void testNeededTemps(String code, String fnName, Set<String> expectedTemps) {
    Node n = parse(code);
    Node fn = findFunction(n, fnName);
    assertNotNull(fn);
    Node call = findCall(n, fnName);
    assertNotNull(call);
    Map<String, Node> args = FunctionArgumentInjector.getFunctionCallParameterMap(fn, call, getNameSupplier());
    Set<String> actualTemps = new HashSet<>();
    FunctionArgumentInjector.maybeAddTempsForCallArguments(fn, args, actualTemps, new ClosureCodingConvention());
    assertEquals(expectedTemps, actualTemps);
}

92. ExpressionDecomposerTest#helperCanExposeFunctionExpression()

View license
private void helperCanExposeFunctionExpression(DecompositionType expectedResult, String code, int call) {
    Compiler compiler = getCompiler();
    Set<String> knownConstants = new HashSet<>();
    ExpressionDecomposer decomposer = new ExpressionDecomposer(compiler, compiler.getUniqueNameIdSupplier(), knownConstants, newScope());
    Node tree = parse(compiler, code);
    assertNotNull(tree);
    Node externsRoot = parse(compiler, "function goo() {}" + "function foo() {}");
    assertNotNull(externsRoot);
    Node callSite = findCall(tree, null, 2);
    assertNotNull("Call " + call + " was not found.", callSite);
    compiler.resetUniqueNameId();
    DecompositionType result = decomposer.canExposeExpression(callSite);
    assertEquals(expectedResult, result);
}

93. Es6SyntacticScopeCreatorTest#testClassExpressionInForLoopInitializer()

View license
public void testClassExpressionInForLoopInitializer() {
    Node root = getRoot("for (class Clazz {};;) {}");
    Scope globalScope = scopeCreator.createScope(root, null);
    assertFalse(globalScope.isDeclared("Clazz", false));
    Node forNode = root.getFirstChild();
    Scope forScope = scopeCreator.createScope(forNode, globalScope);
    assertFalse(forScope.isDeclared("Clazz", false));
    Node classNode = forNode.getFirstChild();
    Scope classScope = scopeCreator.createScope(classNode, forScope);
    assertTrue(classScope.isDeclared("Clazz", false));
}

94. Es6SyntacticScopeCreatorTest#testFunctionExpressionInForLoopInitializer()

View license
public void testFunctionExpressionInForLoopInitializer() {
    Node root = getRoot("for (function foo() {};;) {}");
    Scope globalScope = scopeCreator.createScope(root, null);
    assertFalse(globalScope.isDeclared("foo", false));
    Node forNode = root.getFirstChild();
    Scope forScope = scopeCreator.createScope(forNode, globalScope);
    assertFalse(forScope.isDeclared("foo", false));
    Node fNode = forNode.getFirstChild();
    Scope fScope = scopeCreator.createScope(fNode, forScope);
    assertTrue(fScope.isDeclared("foo", false));
}

95. Es6SyntacticScopeCreatorTest#testSimpleFunctionParam()

View license
public void testSimpleFunctionParam() {
    String js = "function f(x) {}";
    Node root = getRoot(js);
    Node fNode = root.getFirstChild();
    Scope globalScope = scopeCreator.createScope(root, null);
    Scope fScope = scopeCreator.createScope(fNode, globalScope);
    assertTrue(fScope.isDeclared("x", false));
    Node fBlock = fNode.getLastChild();
    Scope fBlockScope = scopeCreator.createScope(fBlock, null);
    assertFalse(fBlockScope.isDeclared("x", false));
}

96. TypeCheckTest#testSheqRefinedScope()

Project: closure-compiler
Source File: TypeCheckTest.java
View license
public void testSheqRefinedScope() {
    Node n = parseAndTypeCheck("/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + "  b.p();\n" + "  if (a === b) {\n" + "    b.p();\n" + "  }\n" + "}");
    Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild().getLastChild().getLastChild();
    JSType typeC = nodeC.getJSType();
    assertTrue(typeC.isNumber());
    Node nodeB = nodeC.getFirstFirstChild();
    JSType typeB = nodeB.getJSType();
    assertEquals("B", typeB.toString());
}

97. ApplySuggestedFixesTest#testApplySuggestedFixes_insideJSDoc()

View license
@Test
public void testApplySuggestedFixes_insideJSDoc() throws Exception {
    String code = "/** @type {Foo} */\nvar foo = new Foo()";
    Compiler compiler = getCompiler(code);
    Node root = compileToScriptRoot(compiler);
    Node varNode = root.getFirstChild();
    Node jsdocRoot = Iterables.getOnlyElement(varNode.getJSDocInfo().getTypeNodes());
    SuggestedFix fix = new SuggestedFix.Builder().insertBefore(jsdocRoot, "!").build();
    List<SuggestedFix> fixes = ImmutableList.of(fix);
    Map<String, String> codeMap = ImmutableMap.of("test", code);
    Map<String, String> newCodeMap = ApplySuggestedFixes.applySuggestedFixesToCode(fixes, codeMap);
    assertThat(newCodeMap).hasSize(1);
    assertThat(newCodeMap).containsEntry("test", "/** @type {!Foo} */\nvar foo = new Foo()");
}

98. TypeCheckTest#testObjectLiteral()

Project: closure-compiler
Source File: TypeCheckTest.java
View license
public void testObjectLiteral() {
    Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}");
    Node nameNode = n.getFirstFirstChild();
    Node objectNode = nameNode.getFirstChild();
    // node extraction
    assertEquals(Token.NAME, nameNode.getType());
    assertEquals(Token.OBJECTLIT, objectNode.getType());
    // value's type
    ObjectType objectType = (ObjectType) objectNode.getJSType();
    assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1"));
    assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2"));
    // variable's type
    assertTypeEquals(objectType, nameNode.getJSType());
}

99. MatchersTest#testNewClass_specificClass()

Project: closure-compiler
Source File: MatchersTest.java
View license
@Test
public void testNewClass_specificClass() {
    String externs = "" + "/** @constructor */\n" + "function Foo() {};\n" + "/** @constructor */\n" + "function Bar() {};";
    String input = "var foo = new Foo();";
    Compiler compiler = getCompiler(externs, input);
    NodeMetadata metadata = new NodeMetadata(compiler);
    Node root = compileToScriptRoot(compiler);
    Node varNode = root.getFirstChild();
    Node newNode = varNode.getFirstFirstChild();
    assertTrue(newNode.isNew());
    assertTrue(Matchers.newClass("Foo").matches(newNode, metadata));
    assertFalse(Matchers.newClass("Bar").matches(newNode, metadata));
    assertFalse(Matchers.newClass("Foo").matches(newNode.getFirstChild(), metadata));
}

100. SyntacticScopeCreatorTest#testNestedFunctionScope()

View license
public void testNestedFunctionScope() {
    Node root = getRoot("function f(x) { function g(y) {} }");
    Scope globalScope = scopeCreator.createScope(root, null);
    Node fNode = root.getFirstChild();
    Scope outerFScope = scopeCreator.createScope(fNode, globalScope);
    assertTrue(outerFScope.isDeclared("x", false));
    Node innerFNode = fNode.getLastChild().getFirstChild();
    Scope innerFScope = scopeCreator.createScope(innerFNode, outerFScope);
    assertFalse(innerFScope.isDeclared("x", false));
    assertTrue(innerFScope.isDeclared("y", false));
}