private void maybeCollapseIntoForStatements ( Node n , Node parent ) { // Only SCRIPT, BLOCK, and LABELs can have FORs that can be collapsed into. // LABELs are not supported here. if ( parent == null || ! NodeUtil . isStatementBlock ( parent ) ) { return ; } // Is the current node something that can be in a for loop initializer? if ( ! n . isExprResult ( ) && ! n . isVar ( ) ) { return ; } // Is the next statement a valid FOR? Node nextSibling = n . getNext ( ) ; if ( nextSibling == null ) { return ; } else if ( nextSibling . isForIn ( ) || nextSibling . isForOf ( ) ) { Node forNode = nextSibling ; Node forVar = forNode . getFirstChild ( ) ; if ( forVar . isName ( ) && n . isVar ( ) && n . hasOneChild ( ) ) { Node name = n . getFirstChild ( ) ; if ( ! name . hasChildren ( ) && forVar . getString ( ) . equals ( name . getString ( ) ) ) { // OK, the names match, and the var declaration does not have an // initializer. Move it into the loop. parent . removeChild ( n ) ; forNode . replaceChild ( forVar , n ) ; compiler . reportChangeToEnclosingScope ( parent ) ; } } } else if ( nextSibling . isVanillaFor ( ) && nextSibling . getFirstChild ( ) . isEmpty ( ) ) { // Does the current node contain an in operator? If so, embedding // the expression in a for loop can cause some JavaScript parsers (such // as the PlayStation 3's browser based on Access's NetFront // browser) to fail to parse the code. // See bug 1778863 for details. if ( NodeUtil . containsType ( n , Token . IN ) ) { return ; } // Move the current node into the FOR loop initializer. Node forNode = nextSibling ; Node oldInitializer = forNode . getFirstChild ( ) ; parent . removeChild ( n ) ; Node newInitializer ; if ( n . isVar ( ) ) { newInitializer = n ; } else { // Extract the expression from EXPR_RESULT node. checkState ( n . hasOneChild ( ) , n ) ; newInitializer = n . getFirstChild ( ) ; n . removeChild ( newInitializer ) ; } forNode . replaceChild ( oldInitializer , newInitializer ) ; compiler . reportChangeToEnclosingScope ( forNode ) ; } }
Collapse VARs and EXPR_RESULT node into FOR loop initializers where possible .