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()

Project: closure-compiler
File: GatherSideEffectSubexpressionsCallbackTest.java
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. TypeCheckTest#testNameNode()

Project: closure-compiler
File: TypeCheckTest.java
/**
   * 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();
}

3. NodeUtilTest#testLhsByDestructuring1b()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

4. NodeUtilTest#testLhsByDestructuring3b()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

5. NodeUtilTest#testLhsByDestructuring3()

Project: closure-compiler
File: NodeUtilTest.java
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#testLhsByDestructuring2()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

7. NodeUtilTest#testLhsByDestructuring5()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

8. NodeUtilTest#testLhsByDestructuring1c()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

9. NodeUtilTest#testLhsByDestructuring1()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

10. MinimizedConditionTest#parseExpr()

Project: closure-compiler
File: MinimizedConditionTest.java
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();
}

11. GatherSideEffectSubexpressionsCallbackTest#getSideEffectsAndNode()

Project: closure-compiler
File: GatherSideEffectSubexpressionsCallbackTest.java
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;
}

12. CheckSideEffects#addExtern()

Project: closure-compiler
File: CheckSideEffects.java
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();
}

13. J2clConstantHoisterPass#hoistConstantLikeField()

Project: closure-compiler
File: J2clConstantHoisterPass.java
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));
}

14. ExpressionDecomposer#moveExpression()

Project: closure-compiler
File: ExpressionDecomposer.java
// 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();
}

15. ExportTestFunctions#exportTestFunctionAsSymbol()

Project: closure-compiler
File: ExportTestFunctions.java
// 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();
}

16. Es6TypedToEs6Converter#createPropertyDefinition()

Project: closure-compiler
File: Es6TypedToEs6Converter.java
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);
}

17. J2clEqualitySameRewriterPass#trySubstituteEqualitySame()

Project: closure-compiler
File: J2clEqualitySameRewriterPass.java
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();
}

18. ExtractPrototypeMemberDeclarations#replacePrototypeMemberDeclaration()

Project: closure-compiler
File: ExtractPrototypeMemberDeclarations.java
/**
   * 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);
}

19. Es6TypedToEs6Converter#createIObject()

Project: closure-compiler
File: Es6TypedToEs6Converter.java
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;
}

20. CollapseProperties#flattenSimpleStubDeclaration()

Project: closure-compiler
File: CollapseProperties.java
/**
   * 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();
}

21. ClosureRewriteModule#exportTheEmptyBinaryNamespaceAt()

Project: closure-compiler
File: ClosureRewriteModule.java
/**
   * 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;
}

22. TypeCheckTest#testTypeCheckStandaloneAST()

Project: closure-compiler
File: TypeCheckTest.java
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);
}

23. NodeUtilTest#testLhsByDestructuring6c()

Project: closure-compiler
File: NodeUtilTest.java
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. NodeUtilTest#testLhsByDestructuring6b()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

25. NodeUtilTest#testLhsByDestructuring6()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

26. NodeUtilTest#testIsControlStructureCodeBlock()

Project: closure-compiler
File: NodeUtilTest.java
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));
}

27. Es6SyntacticScopeCreatorTest#testCatchInFunction()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
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));
}

28. CombinedCompilerPassTest#createPostOrderAlphabet()

Project: closure-compiler
File: CombinedCompilerPassTest.java
/**
   * 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;
}

29. ReplaceMessages#updateFunctionNode()

Project: closure-compiler
File: ReplaceMessages.java
/**
   * 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();
    }
}

30. NodeUtilTest#testLhsByDestructuring7e()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

31. NodeUtilTest#testLhsByDestructuring7d()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

32. NodeUtilTest#testLhsByDestructuring7c()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

33. NodeUtilTest#testLhsByDestructuring7b()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

34. NodeUtilTest#testLhsByDestructuring7()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

35. NodeUtilTest#testLhsByDestructuring4()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

36. NodeUtilTest#testRemoveTryChild5()

Project: closure-compiler
File: NodeUtilTest.java
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);
    }
}

37. NodeUtilTest#testRemoveTryChild3()

Project: closure-compiler
File: NodeUtilTest.java
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);
    }
}

38. NodeUtilTest#testRemoveChildBlock()

Project: closure-compiler
File: NodeUtilTest.java
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);
    }
}

39. Es6SyntacticScopeCreatorTest#testOnlyOneDeclaration()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
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));
}

40. ErrorToFixMapper#getFixForUnsortedRequiresOrProvides()

Project: closure-compiler
File: ErrorToFixMapper.java
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();
}

41. ProcessClosurePrimitives#replaceGoogDefines()

Project: closure-compiler
File: ProcessClosurePrimitives.java
/**
   * @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();
}

42. ApplySuggestedFixesTest#testApplySuggestedFixes_multipleFixesInJsdoc()

Project: closure-compiler
File: ApplySuggestedFixesTest.java
@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()];");
}

43. TypeCheckTest#parseAndTypeCheckWithScope()

Project: closure-compiler
File: TypeCheckTest.java
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);
}

44. ProcessClosurePrimitivesTest#testSourcePositionPreservation()

Project: closure-compiler
File: ProcessClosurePrimitivesTest.java
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());
}

45. ParserTest#testVarSourceLocations()

Project: closure-compiler
File: ParserTest.java
/** @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());
}

46. PeepholeCollectPropertyAssignments#isPropertyAssignmentToName()

Project: closure-compiler
File: PeepholeCollectPropertyAssignments.java
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();
}

47. NewTypeInference#isAllowedToNotReturn()

Project: closure-compiler
File: NewTypeInference.java
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();
}

48. Es6RewriteGenerators#visitYieldExpr()

Project: closure-compiler
File: Es6RewriteGenerators.java
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();
}

49. DartSuperAccessorsPass#renameProperty()

Project: closure-compiler
File: DartSuperAccessorsPass.java
/**
   * 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;
}

50. DartSuperAccessorsPass#visitSuperSet()

Project: closure-compiler
File: DartSuperAccessorsPass.java
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();
}

51. ClosureOptimizePrimitives#processRenamePropertyCall()

Project: closure-compiler
File: ClosureOptimizePrimitives.java
/**
   * 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();
}

52. AstValidator#validateClassHelper()

Project: closure-compiler
File: AstValidator.java
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);
}

53. CheckInterfaces#visit()

Project: closure-compiler
File: CheckInterfaces.java
@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);
    }
}

54. GenerateExports#addStatement()

Project: closure-compiler
File: GenerateExports.java
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);
}

55. ExpressionDecomposer#findInjectionPoint()

Project: closure-compiler
File: ExpressionDecomposer.java
/**
   * @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;
}

56. CoverageInstrumentationPass#createConditionalObjectDecl()

Project: closure-compiler
File: CoverageInstrumentationPass.java
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);
}

57. CoverageInstrumentationCallback#newInstrumentationNode()

Project: closure-compiler
File: CoverageInstrumentationCallback.java
/**
   * 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);
}

58. Compiler#addNewScript()

Project: closure-compiler
File: Compiler.java
/**
   * 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);
}

59. ClosureRewriteModule#maybeSplitMultiVar()

Project: closure-compiler
File: ClosureRewriteModule.java
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);
}

60. ClosureRewriteModule#maybeUpdateExportObjectLiteral()

Project: closure-compiler
File: ClosureRewriteModule.java
/**
   * 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);
            }
        }
    }
}

61. CheckRequiresForConstructors#visitImportNode()

Project: closure-compiler
File: CheckRequiresForConstructors.java
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);
        }
    }
}

62. AstValidator#validateObjectLitGetKey()

Project: closure-compiler
File: AstValidator.java
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);
    }
}

63. AstValidator#validateInterface()

Project: closure-compiler
File: AstValidator.java
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());
}

64. MinimizeExitPoints#tryMinimizeSwitchCaseExits()

Project: closure-compiler
File: MinimizeExitPoints.java
/**
   * 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;
        }
    }
}

65. CheckJSDocStyle#checkInlineParams()

Project: closure-compiler
File: CheckJSDocStyle.java
/**
   * 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);
        }
    }
}

66. InlineSimpleMethods#returnedExpression()

Project: closure-compiler
File: InlineSimpleMethods.java
/**
   * 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();
}

67. GatherSideEffectSubexpressionsCallback#processHook()

Project: closure-compiler
File: GatherSideEffectSubexpressionsCallback.java
/**
   * 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;
    }
}

68. ExternExportsPass#handleSymbolExportCall()

Project: closure-compiler
File: ExternExportsPass.java
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));
}

69. Es6TypedToEs6Converter#convertNamedType()

Project: closure-compiler
File: Es6TypedToEs6Converter.java
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));
}

70. TypeTransformationParser#validNativeTypeExpr()

Project: closure-compiler
File: TypeTransformationParser.java
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;
}

71. JsDocInfoParser#parseRecordType()

Project: closure-compiler
File: JsDocInfoParser.java
/**
   * 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;
}

72. JsDocInfoParser#parseTypeExpressionList()

Project: closure-compiler
File: JsDocInfoParser.java
/**
   * 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;
}

73. OptimizeParameters#addVariableToFunction()

Project: closure-compiler
File: OptimizeParameters.java
/**
   * 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();
}

74. NodeUtil#getObjectDefinedPropertiesKeys()

Project: closure-compiler
File: NodeUtil.java
/**
   * @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;
}

75. NodeUtil#newQNameDeclaration()

Project: closure-compiler
File: NodeUtil.java
/**
   * 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;
}

76. NewTypeInference#analyzeGetElemBwd()

Project: closure-compiler
File: NewTypeInference.java
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;
}

77. NewTypeInference#analyzeAssignBwd()

Project: closure-compiler
File: NewTypeInference.java
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;
}

78. NewTypeInference#analyzeHookFwd()

Project: closure-compiler
File: NewTypeInference.java
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);
}

79. AttachJsdocsTest#testOldJsdocSwitch7()

Project: closure-compiler
File: AttachJsdocsTest.java
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();
}

80. NodeUtilTest#testMergeBlock3()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

81. NodeUtilTest#testMergeBlock1()

Project: closure-compiler
File: NodeUtilTest.java
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);
}

82. NodeUtilTest#testRemoveLabelChild2()

Project: closure-compiler
File: NodeUtilTest.java
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);
    }
}

83. NodeUtilTest#testRemoveLabelChild1()

Project: closure-compiler
File: NodeUtilTest.java
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);
    }
}

84. NodeUtilTest#testRemoveTryChild4()

Project: closure-compiler
File: NodeUtilTest.java
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);
    }
}

85. NodeUtilTest#testRemoveTryChild2()

Project: closure-compiler
File: NodeUtilTest.java
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);
    }
}

86. NodeUtilTest#testRemoveTryChild1()

Project: closure-compiler
File: NodeUtilTest.java
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);
    }
}

87. LiveVariableAnalysisTest#computeLiveness()

Project: closure-compiler
File: LiveVariableAnalysisTest.java
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;
}

88. JsdocToEs6TypedConverterTest#testCreateRecordType()

Project: closure-compiler
File: JsdocToEs6TypedConverterTest.java
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));
}

89. IntegrationTestCase#parse()

Project: closure-compiler
File: IntegrationTestCase.java
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;
}

90. FunctionArgumentInjectorTest#testNeededTemps()

Project: closure-compiler
File: FunctionArgumentInjectorTest.java
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);
}

91. ExpressionDecomposerTest#helperCanExposeFunctionExpression()

Project: closure-compiler
File: ExpressionDecomposerTest.java
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);
}

92. Es6SyntacticScopeCreatorTest#testClassExpressionInForLoopInitializer()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
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));
}

93. Es6SyntacticScopeCreatorTest#testFunctionExpressionInForLoopInitializer()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
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));
}

94. Es6SyntacticScopeCreatorTest#testSimpleFunctionParam()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
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));
}

95. Es6SyntacticScopeCreatorTest#testVarAfterLet()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
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));
}

96. Es6SyntacticScopeCreatorTest#testIsCatchBlockScoped()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
public void testIsCatchBlockScoped() {
    String js = "try { var x = 2; } catch (e) { var y = 3; let z = 4; }";
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    assertTrue(globalScope.isDeclared("x", false));
    assertTrue(globalScope.isDeclared("y", false));
    assertFalse(globalScope.isDeclared("z", false));
    assertFalse(globalScope.isDeclared("e", false));
    Node tryBlock = root.getFirstFirstChild();
    Scope tryBlockScope = scopeCreator.createScope(tryBlock, globalScope);
    assertFalse(tryBlockScope.isDeclared("x", false));
    assertFalse(tryBlockScope.isDeclared("y", false));
    assertFalse(tryBlockScope.isDeclared("z", false));
    assertFalse(tryBlockScope.isDeclared("e", false));
    Node catchBlock = tryBlock.getNext();
    Scope catchBlockScope = scopeCreator.createScope(catchBlock, tryBlockScope);
    assertFalse(catchBlockScope.isDeclared("x", false));
    assertFalse(catchBlockScope.isDeclared("y", false));
    assertTrue(catchBlockScope.isDeclared("z", false));
    assertTrue(catchBlockScope.isDeclared("e", false));
}

97. Es6SyntacticScopeCreatorTest#testForOfLoopScope()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
public void testForOfLoopScope() {
    String js = "for (let i of arr) { let x; }";
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    assertFalse(globalScope.isDeclared("i", false));
    assertFalse(globalScope.isDeclared("x", false));
    Node forNode = root.getFirstChild();
    Scope forScope = scopeCreator.createScope(forNode, globalScope);
    assertTrue(forScope.isDeclared("i", false));
    assertFalse(forScope.isDeclared("x", false));
    Node forBlock = forNode.getLastChild();
    Scope forBlockScope = scopeCreator.createScope(forBlock, forScope);
    assertFalse(forBlockScope.isDeclared("i", false));
    assertTrue(forBlockScope.isDeclared("x", false));
}

98. Es6SyntacticScopeCreatorTest#testForLoopScope()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
public void testForLoopScope() {
    String js = "for (let i = 0;;) { let x; }";
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    assertFalse(globalScope.isDeclared("i", false));
    assertFalse(globalScope.isDeclared("x", false));
    Node forNode = root.getFirstChild();
    Scope forScope = scopeCreator.createScope(forNode, globalScope);
    assertTrue(forScope.isDeclared("i", false));
    assertFalse(forScope.isDeclared("x", false));
    Node forBlock = forNode.getLastChild();
    Scope forBlockScope = scopeCreator.createScope(forBlock, forScope);
    assertFalse(forBlockScope.isDeclared("i", false));
    assertTrue(forBlockScope.isDeclared("x", false));
}

99. Es6SyntacticScopeCreatorTest#testBlockScopeWithClass()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
public void testBlockScopeWithClass() {
    String js = "if (true) { if (true) { class X {} } }";
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    assertFalse(globalScope.isDeclared("X", false));
    Node firstLevelBlock = root.getFirstChild().getLastChild();
    Scope firstLevelBlockScope = scopeCreator.createScope(firstLevelBlock, globalScope);
    assertFalse(firstLevelBlockScope.isDeclared("X", false));
    Node secondLevelBlock = firstLevelBlock.getFirstChild().getLastChild();
    Scope secondLevelBLockScope = scopeCreator.createScope(secondLevelBlock, firstLevelBlockScope);
    assertTrue(secondLevelBLockScope.isDeclared("X", false));
}

100. Es6SyntacticScopeCreatorTest#testBlockScopeWithLet()

Project: closure-compiler
File: Es6SyntacticScopeCreatorTest.java
public void testBlockScopeWithLet() {
    String js = "if (true) { if (true) { let x; } }";
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    assertFalse(globalScope.isDeclared("x", false));
    Node firstLevelBlock = root.getFirstChild().getLastChild();
    Scope firstLevelBlockScope = scopeCreator.createScope(firstLevelBlock, globalScope);
    assertFalse(firstLevelBlockScope.isDeclared("x", false));
    Node secondLevelBlock = firstLevelBlock.getFirstChild().getLastChild();
    Scope secondLevelBLockScope = scopeCreator.createScope(secondLevelBlock, firstLevelBlockScope);
    assertTrue(secondLevelBLockScope.isDeclared("x", false));
}