private Node tryFoldLiteralConstructor ( Node n ) { checkArgument ( n . isCall ( ) || n . isNew ( ) ) ; Node constructorNameNode = n . getFirstChild ( ) ; Node newLiteralNode = null ; // We require the AST to be normalized to ensure that, say, // Object() really refers to the built-in Object constructor // and not a user-defined constructor with the same name. if ( isASTNormalized ( ) && constructorNameNode . isName ( ) ) { String className = constructorNameNode . getString ( ) ; if ( "RegExp" . equals ( className ) ) { // "RegExp("boo", "g")" --> /boo/g return tryFoldRegularExpressionConstructor ( n ) ; } else { boolean constructorHasArgs = constructorNameNode . getNext ( ) != null ; if ( "Object" . equals ( className ) && ! constructorHasArgs ) { // "Object()" --> "{}" newLiteralNode = IR . objectlit ( ) ; } else if ( "Array" . equals ( className ) ) { // "Array(arg0, arg1, ...)" --> "[arg0, arg1, ...]" Node arg0 = constructorNameNode . getNext ( ) ; FoldArrayAction action = isSafeToFoldArrayConstructor ( arg0 ) ; if ( action == FoldArrayAction . SAFE_TO_FOLD_WITH_ARGS || action == FoldArrayAction . SAFE_TO_FOLD_WITHOUT_ARGS ) { newLiteralNode = IR . arraylit ( ) ; n . removeFirstChild ( ) ; // discard the function name Node elements = n . removeChildren ( ) ; if ( action == FoldArrayAction . SAFE_TO_FOLD_WITH_ARGS ) { newLiteralNode . addChildrenToFront ( elements ) ; } } } if ( newLiteralNode != null ) { n . replaceWith ( newLiteralNode ) ; reportChangeToEnclosingScope ( newLiteralNode ) ; return newLiteralNode ; } } } return n ; }
Replaces a new Array Object or RegExp node with a literal unless the call is to a local constructor function with the same name .