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. 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();
}

8. 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);
}

9. 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();
}

10. 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();
}

11. 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));
}

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. 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;
}

18. 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();
}

19. 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;
}

20. 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);
}

21. 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();
}

22. 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();
    }
}

23. 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;
}

24. 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));
}

25. 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));
}

26. 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);
}

27. 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);
}

28. 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);
}

29. 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);
}

30. 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);
}

31. 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();
}

32. 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();
}

33. DartSuperAccessorsPass#renameProperty()

View license
/**
   * Wraps a property string in a JSCompiler_renameProperty call.
   *
   * <p>Should only be called in phases running before [email protected] RenameProperties},
   * if such a pass is even used (see [email protected] #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;
}

34. 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();
}

35. 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;
}

36. 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);
}

37. 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);
    }
}

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. 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();
}

41. 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();
}

42. 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));
}

43. 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);
    }
}

44. 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);
    }
}

45. 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);
    }
}

46. 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);
}

47. 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);
}

48. 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);
}

49. 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);
}

50. 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);
}

51. 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);
}

52. 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());
}

53. 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());
}

54. 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);
}

55. 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()];");
}

56. 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());
}

57. 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);
    }
}

58. 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);
        }
    }
}

59. 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);
            }
        }
    }
}

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. 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);
}

62. 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);
}

63. 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);
}

64. 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));
}

65. 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));
}

66. 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;
    }
}

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. 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);
        }
    }
}

69. 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;
        }
    }
}

70. 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);
}

71. 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;
}

72. 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;
}

73. 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;
}

74. 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;
}

75. 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();
}

76. 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;
}

77. 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;
}

78. 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;
}

79. PeepholeRemoveDeadCode#tryFoldComma()

View license
private Node tryFoldComma(Node n) {
    // If the left side does nothing replace the comma with the result.
    Node parent = n.getParent();
    Node left = n.getFirstChild();
    Node right = left.getNext();
    left = trySimplifyUnusedResult(left);
    if (left == null || !mayHaveSideEffects(left)) {
        // Fold it!
        n.removeChild(right);
        parent.replaceChild(n, right);
        reportCodeChange();
        return right;
    }
    return n;
}

80. PolymerPassStaticUtils#extractProperties()

View license
/**
   * Extracts a list of [email protected] MemberDefinition}s for the [email protected] properties} block of the given
   * descriptor Object literal.
   */
static ImmutableList<MemberDefinition> extractProperties(Node descriptor) {
    Node properties = NodeUtil.getFirstPropMatchingKey(descriptor, "properties");
    if (properties == null) {
        return ImmutableList.of();
    }
    ImmutableList.Builder<MemberDefinition> members = ImmutableList.builder();
    for (Node keyNode : properties.children()) {
        members.add(new MemberDefinition(NodeUtil.getBestJSDocInfo(keyNode), keyNode, keyNode.getFirstChild()));
    }
    return members.build();
}

81. ReplaceMessages#replaceCallNode()

View license
/**
   * Replaces a CALL node with an inlined message value.
   *  <p>
   * The call tree looks something like:
   * <pre>
   * call
   *  |-- getprop
   *  |   |-- name 'goog'
   *  |   +-- string 'getMsg'
   *  |
   *  |-- string 'Hi {$userName}! Welcome to {$product}.'
   *  +-- objlit
   *      |-- string 'userName'
   *      |-- name 'someUserName'
   *      |-- string 'product'
   *      +-- call
   *          +-- name 'getProductName'
   * <pre>
   * <p>
   * For that example, we'd return:
   * <pre>
   * add
   *  |-- string 'Hi '
   *  +-- add
   *      |-- name someUserName
   *      +-- add
   *          |-- string '! Welcome to '
   *          +-- add
   *              |-- call
   *              |   +-- name 'getProductName'
   *              +-- string '.'
   * </pre>
   * @param message  a message
   * @param callNode  the message's original CALL value node
   * @return a STRING node, or an ADD node that does string concatenation, if
   *   the message has one or more placeholders
   *
   * @throws MalformedException if the passed node's subtree structure is
   *   not as expected
   */
private Node replaceCallNode(JsMessage message, Node callNode) throws MalformedException {
    checkNode(callNode, Token.CALL);
    Node getPropNode = callNode.getFirstChild();
    checkNode(getPropNode, Token.GETPROP);
    Node stringExprNode = getPropNode.getNext();
    checkStringExprNode(stringExprNode);
    Node objLitNode = stringExprNode.getNext();
    // Build the replacement tree.
    return constructStringExprNode(message.parts().iterator(), objLitNode, callNode);
}

82. StatementFusion#fuseIntoOneStatement()

View license
/**
   * Given a block, fuse a list of statements with comma's.
   *
   * @param parent The parent that contains the statements.
   * @param first The first statement to fuse (inclusive)
   * @param last The last statement to fuse (exclusive)
   * @return A single statement that contains all the fused statement as one.
   */
private static Node fuseIntoOneStatement(Node parent, Node first, Node last) {
    // Nothing to fuse if there is only one statement.
    if (first.getNext() == last) {
        return first;
    }
    // Step one: Create a comma tree that contains all the statements.
    Node commaTree = first.removeFirstChild();
    Node next = null;
    for (Node cur = first.getNext(); cur != last; cur = next) {
        commaTree = fuseExpressionIntoExpression(commaTree, cur.removeFirstChild());
        next = cur.getNext();
        parent.removeChild(cur);
    }
    // Step two: The last EXPR_RESULT will now hold the comma tree with all
    // the fused statements.
    first.addChildToBack(commaTree);
    return first;
}

83. TemplateAstMatcher#initTemplate()

View license
/**
   * Prepare an template AST to use when performing matches.
   *
   * @param templateFunctionNode The template declaration function to extract
   *     the template AST from.
   * @return The first node of the template AST sequence to use when matching.
   */
private Node initTemplate(Node templateFunctionNode) {
    Node prepped = templateFunctionNode.cloneTree();
    prepTemplatePlaceholders(prepped);
    Node body = prepped.getLastChild();
    Node startNode;
    if (body.hasOneChild() && body.getFirstChild().isExprResult()) {
        // When matching an expression, don't require it to be a complete
        // statement.
        startNode = body.getFirstFirstChild();
    } else {
        startNode = body.getFirstChild();
    }
    for (int i = 0; i < templateLocals.size(); i++) {
        // reserve space in the locals array.
        this.localVarMatches.add(null);
    }
    for (int i = 0; i < templateParams.size(); i++) {
        // reserve space in the params array.
        this.paramNodeMatches.add(null);
    }
    return startNode;
}

84. CollapsePropertiesTest#testPreserveConstructorDoc()

View license
public void testPreserveConstructorDoc() {
    test("var foo = {};" + "/** @constructor */\n" + "foo.bar = function() {}", "var foo$bar = function() {}");
    Node root = getLastCompiler().getRoot();
    Node fooBarNode = findQualifiedNameNode("foo$bar", root);
    Node varNode = fooBarNode.getParent();
    assertTrue(varNode.isVar());
    assertTrue(varNode.getJSDocInfo().isConstructor());
}

85. DotFormatterTest#testKeyAssignementOncePerNode()

View license
/**
   * Tests that keys are assigned once per node.
   */
public void testKeyAssignementOncePerNode() throws Exception {
    DotFormatter dot = DotFormatter.newInstanceForTesting();
    Node node0 = new Node(Token.BLOCK);
    Node node1 = new Node(Token.BLOCK);
    Node node2 = new Node(Token.BLOCK);
    assertEquals(0, dot.key(node0));
    assertEquals(1, dot.key(node1));
    assertEquals(2, dot.key(node2));
    assertEquals(0, dot.key(node0));
    assertEquals(1, dot.key(node1));
    assertEquals(2, dot.key(node2));
}

86. DotFormatterTest#testToDot3Elements()

View license
/**
   * Tests the formatting (3 element tree).
   */
public void testToDot3Elements() throws Exception {
    Node ast = new Node(Token.BLOCK);
    ast.addChildToBack(new Node(Token.NAME));
    ast.addChildToBack(new Node(Token.STRING));
    String expected = "digraph AST {\n" + "  node [color=lightblue2, style=filled];\n" + "  node0 [label=\"BLOCK\"];\n" + "  node1 [label=\"NAME\"];\n" + "  node0 -> node1 [weight=1];\n" + "  node2 [label=\"STRING\"];\n" + "  node0 -> node2 [weight=1];\n" + "}\n";
    test(expected, ast);
}

87. Es6SyntacticScopeCreatorTest#testArrayDestructuringVarInBlock()

View license
public void testArrayDestructuringVarInBlock() {
    String js = "" + "function foo() {\n" + "  var [a, b] = getVars();" + "  if (true) {" + "    var [x, y] = getMoreVars();" + "  }" + "}";
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    Node functionNode = root.getFirstChild();
    Scope functionScope = scopeCreator.createScope(functionNode, globalScope);
    Node functionBlock = functionNode.getLastChild();
    Scope functionBlockScope = scopeCreator.createScope(functionBlock, functionScope);
    assertTrue(functionBlockScope.isDeclared("a", false));
    assertTrue(functionBlockScope.isDeclared("b", false));
    assertTrue(functionBlockScope.isDeclared("x", false));
    assertTrue(functionBlockScope.isDeclared("y", false));
}

88. Es6SyntacticScopeCreatorTest#testObjectDestructuring()

View license
public void testObjectDestructuring() {
    String js = Joiner.on('\n').join("function foo() {", "  var {a, b} = bar();", "}");
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    Node functionNode = root.getFirstChild();
    Scope functionScope = scopeCreator.createScope(functionNode, globalScope);
    Node functionBlock = functionNode.getLastChild();
    Scope functionBlockScope = scopeCreator.createScope(functionBlock, functionScope);
    assertTrue(functionBlockScope.isDeclared("a", false));
    assertTrue(functionBlockScope.isDeclared("b", false));
}

89. Es6SyntacticScopeCreatorTest#testObjectDestructuring2()

View license
public void testObjectDestructuring2() {
    String js = Joiner.on('\n').join("function foo() {", "  var {a: b = 1} = bar();", "}");
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    Node functionNode = root.getFirstChild();
    Scope functionScope = scopeCreator.createScope(functionNode, globalScope);
    Node functionBlock = functionNode.getLastChild();
    Scope functionBlockScope = scopeCreator.createScope(functionBlock, functionScope);
    assertFalse(functionBlockScope.isDeclared("a", false));
    assertTrue(functionBlockScope.isDeclared("b", false));
}

90. Es6SyntacticScopeCreatorTest#testObjectDestructuringComputedProp()

View license
public void testObjectDestructuringComputedProp() {
    String js = Joiner.on('\n').join("function foo() {", "  var {['s']: a} = bar();", "}");
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    Node functionNode = root.getFirstChild();
    Scope functionScope = scopeCreator.createScope(functionNode, globalScope);
    Node functionBlock = functionNode.getLastChild();
    Scope functionBlockScope = scopeCreator.createScope(functionBlock, functionScope);
    assertTrue(functionBlockScope.isDeclared("a", false));
}

91. Es6SyntacticScopeCreatorTest#testObjectDestructuringNested()

View license
public void testObjectDestructuringNested() {
    String js = Joiner.on('\n').join("function foo() {", "  var {a:{b}} = bar();", "}");
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    Node functionNode = root.getFirstChild();
    Scope functionScope = scopeCreator.createScope(functionNode, globalScope);
    Node functionBlock = functionNode.getLastChild();
    Scope functionBlockScope = scopeCreator.createScope(functionBlock, functionScope);
    assertFalse(functionBlockScope.isDeclared("a", false));
    assertTrue(functionBlockScope.isDeclared("b", false));
}

92. Es6SyntacticScopeCreatorTest#testObjectDestructuringWithInitializer()

View license
public void testObjectDestructuringWithInitializer() {
    String js = Joiner.on('\n').join("function foo() {", "  var {a=1} = bar();", "}");
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    Node functionNode = root.getFirstChild();
    Scope functionScope = scopeCreator.createScope(functionNode, globalScope);
    Node functionBlock = functionNode.getLastChild();
    Scope functionBlockScope = scopeCreator.createScope(functionBlock, functionScope);
    assertTrue(functionBlockScope.isDeclared("a", false));
}

93. Es6SyntacticScopeCreatorTest#testObjectDestructuringInForOfParam()

View license
public void testObjectDestructuringInForOfParam() {
    String js = "{for (let {length: x} of gen()) {}}";
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    Node block = root.getFirstChild();
    Scope blockScope = scopeCreator.createScope(block, globalScope);
    Node forOf = block.getFirstChild();
    Scope forOfScope = scopeCreator.createScope(forOf, blockScope);
    assertTrue(forOfScope.isDeclared("x", false));
}

94. Es6SyntacticScopeCreatorTest#testBlockScopeWithVar()

View license
public void testBlockScopeWithVar() {
    String js = "if (true) { if (true) { var x; } }";
    Node root = getRoot(js);
    Scope globalScope = scopeCreator.createScope(root, null);
    assertTrue(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);
    assertFalse(secondLevelBLockScope.isDeclared("x", false));
}

95. Es6SyntacticScopeCreatorTest#testBlockScopeWithLet()

View license
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));
}

96. Es6SyntacticScopeCreatorTest#testBlockScopeWithClass()

View license
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));
}

97. Es6SyntacticScopeCreatorTest#testForLoopScope()

View license
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));
}

98. Es6SyntacticScopeCreatorTest#testForOfLoopScope()

View license
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));
}

99. Es6SyntacticScopeCreatorTest#testIsCatchBlockScoped()

View license
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));
}

100. 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));
}