idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
35,100
private void simplifyEnumValues ( AbstractCompiler compiler ) { if ( getRhs ( ) . isObjectLit ( ) && getRhs ( ) . hasChildren ( ) ) { for ( Node key : getRhs ( ) . children ( ) ) { removeStringKeyValue ( key ) ; } compiler . reportChangeToEnclosingScope ( getRhs ( ) ) ; } }
Remove values from enums
35,101
Map < String , ProvidedName > collectProvidedNames ( Node externs , Node root ) { if ( this . providedNames . isEmpty ( ) ) { providedNames . put ( GOOG , new ProvidedName ( GOOG , null , null , false , false ) ) ; NodeTraversal . traverseRoots ( compiler , new CollectDefinitions ( ) , externs , root ) ; } return this . providedNames ; }
Collects all goog . provides in the given namespace and warns on invalid code
35,102
void rewriteProvidesAndRequires ( Node externs , Node root ) { checkState ( ! hasRewritingOccurred , "Cannot call rewriteProvidesAndRequires twice per instance" ) ; hasRewritingOccurred = true ; collectProvidedNames ( externs , root ) ; for ( ProvidedName pn : providedNames . values ( ) ) { pn . replace ( ) ; } deleteNamespaceInitializationsFromPreviousProvides ( ) ; if ( requiresLevel . isOn ( ) ) { for ( UnrecognizedRequire r : unrecognizedRequires ) { checkForLateOrMissingProvide ( r ) ; } } for ( Node closureRequire : requiresToBeRemoved ) { compiler . reportChangeToEnclosingScope ( closureRequire ) ; closureRequire . detach ( ) ; } for ( Node forwardDeclare : forwardDeclaresToRemove ) { NodeUtil . deleteNode ( forwardDeclare , compiler ) ; } }
Rewrites all provides and requires in the given namespace .
35,103
private void processRequireCall ( NodeTraversal t , Node n , Node parent ) { Node left = n . getFirstChild ( ) ; Node arg = left . getNext ( ) ; String method = left . getFirstChild ( ) . getNext ( ) . getString ( ) ; if ( verifyLastArgumentIsString ( left , arg ) ) { String ns = arg . getString ( ) ; ProvidedName provided = providedNames . get ( ns ) ; if ( provided == null || ! provided . isExplicitlyProvided ( ) ) { unrecognizedRequires . add ( new UnrecognizedRequire ( n , ns , method . equals ( "requireType" ) ) ) ; } else { JSModule providedModule = provided . explicitModule ; if ( ! provided . isFromExterns ( ) ) { checkNotNull ( providedModule , n ) ; JSModule module = t . getModule ( ) ; if ( module != providedModule && ! moduleGraph . dependsOn ( module , providedModule ) && ! method . equals ( "requireType" ) ) { compiler . report ( JSError . make ( n , ProcessClosurePrimitives . XMODULE_REQUIRE_ERROR , ns , providedModule . getName ( ) , module . getName ( ) ) ) ; } } } maybeAddNameToSymbolTable ( left ) ; maybeAddStringToSymbolTable ( arg ) ; if ( ! preserveGoogProvidesAndRequires && ( provided != null || requiresLevel . isOn ( ) ) ) { requiresToBeRemoved . add ( parent ) ; } } }
Handles a goog . require or goog . requireType call .
35,104
private void processLegacyModuleCall ( String namespace , Node googModuleCall , JSModule module ) { registerAnyProvidedPrefixes ( namespace , googModuleCall , module ) ; providedNames . put ( namespace , new ProvidedName ( namespace , googModuleCall , module , true , false ) ) ; }
Handles a goog . module that is a legacy namespace .
35,105
private void processProvideCall ( NodeTraversal t , Node n , Node parent ) { checkState ( n . isCall ( ) ) ; Node left = n . getFirstChild ( ) ; Node arg = left . getNext ( ) ; if ( verifyProvide ( left , arg ) ) { String ns = arg . getString ( ) ; maybeAddNameToSymbolTable ( left ) ; maybeAddStringToSymbolTable ( arg ) ; if ( providedNames . containsKey ( ns ) ) { ProvidedName previouslyProvided = providedNames . get ( ns ) ; if ( ! previouslyProvided . isExplicitlyProvided ( ) || previouslyProvided . isPreviouslyProvided ) { previouslyProvided . addProvide ( parent , t . getModule ( ) , true ) ; } else { String explicitSourceName = previouslyProvided . explicitNode . getSourceFileName ( ) ; compiler . report ( JSError . make ( n , ProcessClosurePrimitives . DUPLICATE_NAMESPACE_ERROR , ns , explicitSourceName ) ) ; } } else { registerAnyProvidedPrefixes ( ns , parent , t . getModule ( ) ) ; providedNames . put ( ns , new ProvidedName ( ns , parent , t . getModule ( ) , true , false ) ) ; } } }
Handles a goog . provide call .
35,106
private void handleCandidateProvideDefinition ( NodeTraversal t , Node n , Node parent ) { if ( t . inGlobalHoistScope ( ) ) { String name = null ; if ( n . isName ( ) && NodeUtil . isNameDeclaration ( parent ) ) { name = n . getString ( ) ; } else if ( n . isAssign ( ) && parent . isExprResult ( ) ) { name = n . getFirstChild ( ) . getQualifiedName ( ) ; } if ( name != null ) { if ( parent . getBooleanProp ( Node . IS_NAMESPACE ) ) { processProvideFromPreviousPass ( t , name , parent ) ; } else { ProvidedName pn = providedNames . get ( name ) ; if ( pn != null ) { pn . addDefinition ( parent , t . getModule ( ) ) ; } } } } }
Handles a candidate definition for a goog . provided name .
35,107
private void processProvideFromPreviousPass ( NodeTraversal t , String name , Node parent ) { JSModule module = t . getModule ( ) ; if ( providedNames . containsKey ( name ) ) { ProvidedName provided = providedNames . get ( name ) ; provided . addDefinition ( parent , module ) ; if ( isNamespacePlaceholder ( parent ) ) { previouslyProvidedDefinitions . add ( parent ) ; } } else { registerAnyProvidedPrefixes ( name , parent , module ) ; ProvidedName provided = new ProvidedName ( name , parent , module , true , true ) ; providedNames . put ( name , provided ) ; provided . addDefinition ( parent , module ) ; } }
Processes the output of processed - provide from a previous pass . This will update our data structures in the same manner as if the provide had been processed in this pass .
35,108
private void registerAnyProvidedPrefixes ( String ns , Node node , JSModule module ) { int pos = ns . indexOf ( '.' ) ; while ( pos != - 1 ) { String prefixNs = ns . substring ( 0 , pos ) ; pos = ns . indexOf ( '.' , pos + 1 ) ; if ( providedNames . containsKey ( prefixNs ) ) { providedNames . get ( prefixNs ) . addProvide ( node , module , false ) ; } else { providedNames . put ( prefixNs , new ProvidedName ( prefixNs , node , module , false , false ) ) ; } } }
Registers ProvidedNames for prefix namespaces if they haven t already been defined . The prefix namespaces must be registered in order from shortest to longest .
35,109
private boolean mayBeGlobalAlias ( Ref alias ) { if ( alias . scope . isGlobal ( ) ) { return true ; } Node aliasParent = alias . getNode ( ) . getParent ( ) ; if ( ! aliasParent . isAssign ( ) && ! aliasParent . isName ( ) ) { return true ; } Node aliasLhsNode = aliasParent . isName ( ) ? aliasParent : aliasParent . getFirstChild ( ) ; if ( ! aliasLhsNode . isName ( ) ) { return true ; } String aliasVarName = aliasLhsNode . getString ( ) ; Var aliasVar = alias . scope . getVar ( aliasVarName ) ; if ( aliasVar != null ) { return aliasVar . isGlobal ( ) ; } return true ; }
Returns true if the alias is possibly defined in the global scope which we handle with more caution than with locally scoped variables . May return false positives .
35,110
private void inlineAliasIfPossible ( Name name , Ref alias , GlobalNamespace namespace ) { Node aliasParent = alias . getNode ( ) . getParent ( ) ; if ( aliasParent . isName ( ) || aliasParent . isAssign ( ) ) { Node aliasLhsNode = aliasParent . isName ( ) ? aliasParent : aliasParent . getFirstChild ( ) ; String aliasVarName = aliasLhsNode . getString ( ) ; Var aliasVar = alias . scope . getVar ( aliasVarName ) ; checkState ( aliasVar != null , "Expected variable to be defined in scope" , aliasVarName ) ; ReferenceCollectingCallback collector = new ReferenceCollectingCallback ( compiler , ReferenceCollectingCallback . DO_NOTHING_BEHAVIOR , new Es6SyntacticScopeCreator ( compiler ) , Predicates . equalTo ( aliasVar ) ) ; Scope aliasScope = aliasVar . getScope ( ) ; collector . processScope ( aliasScope ) ; ReferenceCollection aliasRefs = collector . getReferences ( aliasVar ) ; Set < AstChange > newNodes = new LinkedHashSet < > ( ) ; if ( aliasRefs . isWellDefined ( ) && aliasRefs . isAssignedOnceInLifetime ( ) ) { int size = aliasRefs . references . size ( ) ; int firstRead = aliasRefs . references . get ( 0 ) . isInitializingDeclaration ( ) ? 1 : 2 ; for ( int i = firstRead ; i < size ; i ++ ) { Reference aliasRef = aliasRefs . references . get ( i ) ; newNodes . add ( replaceAliasReference ( alias , aliasRef ) ) ; } tryReplacingAliasingAssignment ( alias , aliasLhsNode ) ; namespace . scanNewNodes ( newNodes ) ; return ; } if ( name . isConstructor ( ) ) { if ( ! partiallyInlineAlias ( alias , namespace , aliasRefs , aliasLhsNode ) ) { if ( referencesCollapsibleProperty ( aliasRefs , name , namespace ) ) { compiler . report ( JSError . make ( aliasParent , UNSAFE_CTOR_ALIASING , aliasVarName ) ) ; } } } } }
Attempts to inline a non - global alias of a global name .
35,111
private boolean partiallyInlineAlias ( Ref alias , GlobalNamespace namespace , ReferenceCollection aliasRefs , Node aliasLhsNode ) { BasicBlock aliasBlock = null ; for ( Reference aliasRef : aliasRefs ) { Node aliasRefNode = aliasRef . getNode ( ) ; if ( aliasRefNode == aliasLhsNode ) { aliasBlock = aliasRef . getBasicBlock ( ) ; continue ; } else if ( aliasRef . isLvalue ( ) ) { return false ; } } Set < AstChange > newNodes = new LinkedHashSet < > ( ) ; boolean alreadySeenInitialAlias = false ; boolean foundNonReplaceableAlias = false ; for ( Reference aliasRef : aliasRefs ) { Node aliasRefNode = aliasRef . getNode ( ) ; if ( aliasRefNode == aliasLhsNode ) { alreadySeenInitialAlias = true ; continue ; } else if ( aliasRef . isDeclaration ( ) ) { continue ; } BasicBlock refBlock = aliasRef . getBasicBlock ( ) ; if ( ( refBlock != aliasBlock && aliasBlock . provablyExecutesBefore ( refBlock ) ) || ( refBlock == aliasBlock && alreadySeenInitialAlias ) ) { codeChanged = true ; newNodes . add ( replaceAliasReference ( alias , aliasRef ) ) ; } else { foundNonReplaceableAlias = true ; } } if ( ! foundNonReplaceableAlias ) { tryReplacingAliasingAssignment ( alias , aliasLhsNode ) ; } if ( codeChanged ) { namespace . scanNewNodes ( newNodes ) ; } return ! foundNonReplaceableAlias ; }
Inlines some references to an alias with its value . This handles cases where the alias is not declared at initialization . It does nothing if the alias is reassigned after being initialized unless the reassignment occurs because of an enclosing function or a loop .
35,112
private boolean tryReplacingAliasingAssignment ( Ref alias , Node aliasLhsNode ) { Node assignment = aliasLhsNode . getParent ( ) ; if ( ! NodeUtil . isNameDeclaration ( assignment ) && NodeUtil . isExpressionResultUsed ( assignment ) ) { return false ; } Node aliasParent = alias . getNode ( ) . getParent ( ) ; aliasParent . replaceChild ( alias . getNode ( ) , IR . nullNode ( ) ) ; alias . name . removeRef ( alias ) ; codeChanged = true ; compiler . reportChangeToEnclosingScope ( aliasParent ) ; return true ; }
Replaces the rhs of an aliasing assignment with null unless the assignment result is used in a complex expression .
35,113
private boolean referencesCollapsibleProperty ( ReferenceCollection aliasRefs , Name aliasedName , GlobalNamespace namespace ) { for ( Reference ref : aliasRefs . references ) { if ( ref . getParent ( ) == null ) { continue ; } if ( ref . getParent ( ) . isGetProp ( ) ) { Node propertyNode = ref . getNode ( ) . getNext ( ) ; String propertyName = propertyNode . getString ( ) ; String originalPropertyName = aliasedName . getName ( ) + "." + propertyName ; Name originalProperty = namespace . getOwnSlot ( originalPropertyName ) ; if ( originalProperty == null || ! originalProperty . canCollapse ( ) ) { continue ; } return true ; } } return false ; }
Returns whether a ReferenceCollection for some aliasing variable references a property on the original aliased variable that may be collapsed in CollapseProperties .
35,114
private void rewriteAliasReferences ( Name aliasingName , Ref aliasingRef , Set < AstChange > newNodes ) { List < Ref > refs = new ArrayList < > ( aliasingName . getRefs ( ) ) ; for ( Ref ref : refs ) { switch ( ref . type ) { case SET_FROM_GLOBAL : continue ; case DIRECT_GET : case ALIASING_GET : case PROTOTYPE_GET : case CALL_GET : case SUBCLASSING_GET : if ( ref . getTwin ( ) != null ) { checkState ( ref . type == Type . ALIASING_GET , ref ) ; break ; } if ( ref . getNode ( ) . isStringKey ( ) ) { DestructuringGlobalNameExtractor . reassignDestructringLvalue ( ref . getNode ( ) , aliasingRef . getNode ( ) . cloneTree ( ) , newNodes , ref , compiler ) ; } else { checkState ( ref . getNode ( ) . isGetProp ( ) || ref . getNode ( ) . isName ( ) ) ; Node newNode = aliasingRef . getNode ( ) . cloneTree ( ) ; Node node = ref . getNode ( ) ; node . replaceWith ( newNode ) ; compiler . reportChangeToEnclosingScope ( newNode ) ; newNodes . add ( new AstChange ( ref . module , ref . scope , newNode ) ) ; } aliasingName . removeRef ( ref ) ; break ; default : throw new IllegalStateException ( ) ; } } }
Replaces all reads of a name with the name it aliases
35,115
private void rewriteNestedAliasReference ( Node value , int depth , Set < AstChange > newNodes , Name prop ) { rewriteAliasProps ( prop , value , depth + 1 , newNodes ) ; List < Ref > refs = new ArrayList < > ( prop . getRefs ( ) ) ; for ( Ref ref : refs ) { Node target = ref . getNode ( ) ; if ( target . isStringKey ( ) && target . getParent ( ) . isDestructuringPattern ( ) ) { checkState ( target . getGrandparent ( ) . isAssign ( ) || target . getGrandparent ( ) . isDestructuringLhs ( ) , "Did not expect GlobalNamespace to create Ref for key in nested object pattern %s" , target ) ; continue ; } for ( int i = 0 ; i <= depth ; i ++ ) { if ( target . isGetProp ( ) ) { target = target . getFirstChild ( ) ; } else if ( NodeUtil . isObjectLitKey ( target ) ) { Node gparent = target . getGrandparent ( ) ; if ( gparent . isAssign ( ) ) { target = gparent . getFirstChild ( ) ; } else { checkState ( NodeUtil . isObjectLitKey ( gparent ) ) ; target = gparent ; } } else { throw new IllegalStateException ( "unexpected node: " + target ) ; } } checkState ( target . isGetProp ( ) || target . isName ( ) ) ; Node newValue = value . cloneTree ( ) ; target . replaceWith ( newValue ) ; compiler . reportChangeToEnclosingScope ( newValue ) ; prop . removeRef ( ref ) ; newNodes . add ( new AstChange ( ref . module , ref . scope , ref . getNode ( ) ) ) ; codeChanged = true ; } }
Replaces references to an alias that are nested inside a longer getprop chain or an object literal
35,116
private static Node getSubclassForEs6Superclass ( Node superclass ) { Node classNode = superclass . getParent ( ) ; checkArgument ( classNode . isClass ( ) , classNode ) ; if ( NodeUtil . isNameDeclaration ( classNode . getGrandparent ( ) ) ) { return classNode . getParent ( ) ; } else if ( superclass . getGrandparent ( ) . isAssign ( ) ) { return classNode . getPrevious ( ) ; } else if ( NodeUtil . isClassDeclaration ( classNode ) ) { return classNode . getFirstChild ( ) ; } return null ; }
Tries to find an lvalue for the subclass given the superclass node in an class ... extends clause
35,117
public void visit ( final NodeTraversal t , final Node n , final Node p ) { final JSDocInfo info = n . getJSDocInfo ( ) ; if ( info == null ) { return ; } final JSTypeRegistry registry = compiler . getTypeRegistry ( ) ; final List < Node > thrownTypes = transform ( info . getThrownTypes ( ) , new Function < JSTypeExpression , Node > ( ) { public Node apply ( JSTypeExpression expr ) { return expr . getRoot ( ) ; } } ) ; final Scope scope = t . getScope ( ) ; for ( Node typeRoot : info . getTypeNodes ( ) ) { NodeUtil . visitPreOrder ( typeRoot , new NodeUtil . Visitor ( ) { public void visit ( Node node ) { if ( ! node . isString ( ) ) { return ; } if ( thrownTypes . contains ( node ) ) { return ; } Node parent = node . getParent ( ) ; if ( parent != null ) { switch ( parent . getToken ( ) ) { case BANG : case QMARK : case THIS : case NEW : case TYPEOF : return ; case PIPE : { Node gp = parent . getParent ( ) ; if ( gp != null && gp . getToken ( ) == Token . QMARK ) { return ; } for ( Node child : parent . children ( ) ) { if ( ( child . isString ( ) && child . getString ( ) . equals ( "null" ) ) || child . getToken ( ) == Token . QMARK ) { return ; } } break ; } default : break ; } } String typeName = node . getString ( ) ; if ( typeName . equals ( "null" ) || registry . getType ( scope , typeName ) == null ) { return ; } JSType type = registry . createTypeFromCommentNode ( node ) ; if ( type . isNullable ( ) ) { compiler . report ( JSError . make ( node , IMPLICITLY_NULLABLE_JSDOC , typeName ) ) ; } } } , Predicates . alwaysTrue ( ) ) ; } }
Crawls the JSDoc of the given node to find any names in JSDoc that are implicitly null .
35,118
private static List < ImportStatement > canonicalizeImports ( Multimap < String , ImportStatement > importsByNamespace ) { List < ImportStatement > canonicalImports = new ArrayList < > ( ) ; for ( String namespace : importsByNamespace . keySet ( ) ) { Collection < ImportStatement > allImports = importsByNamespace . get ( namespace ) ; ImportPrimitive strongestPrimitive = allImports . stream ( ) . map ( ImportStatement :: primitive ) . reduce ( ImportPrimitive . WEAKEST , ImportPrimitive :: stronger ) ; boolean hasAliasing = false ; for ( ImportStatement stmt : Iterables . filter ( allImports , ImportStatement :: isAliasing ) ) { canonicalImports . add ( stmt . upgrade ( strongestPrimitive ) ) ; hasAliasing = true ; } boolean hasDestructuring = false ; ImmutableList < Node > destructuringNodes = allImports . stream ( ) . filter ( ImportStatement :: isDestructuring ) . flatMap ( i -> i . nodes ( ) . stream ( ) ) . collect ( toImmutableList ( ) ) ; ImmutableList < DestructuringBinding > destructures = allImports . stream ( ) . filter ( ImportStatement :: isDestructuring ) . flatMap ( i -> i . destructures ( ) . stream ( ) ) . distinct ( ) . sorted ( ) . collect ( toImmutableList ( ) ) ; if ( ! destructures . isEmpty ( ) ) { canonicalImports . add ( ImportStatement . of ( destructuringNodes , strongestPrimitive , namespace , null , destructures ) ) ; hasDestructuring = true ; } if ( ! hasAliasing && ! hasDestructuring ) { ImmutableList < Node > standaloneNodes = allImports . stream ( ) . filter ( ImportStatement :: isStandalone ) . flatMap ( i -> i . nodes ( ) . stream ( ) ) . collect ( toImmutableList ( ) ) ; canonicalImports . add ( ImportStatement . of ( standaloneNodes , strongestPrimitive , namespace , null , null ) ) ; } } Collections . sort ( canonicalImports ) ; return canonicalImports ; }
Canonicalizes a list of import statements by deduplicating and merging imports for the same namespace and sorting the result .
35,119
private String getReplacementName ( String oldName ) { for ( Renamer renamer : renamerStack ) { String newName = renamer . getReplacementName ( oldName ) ; if ( newName != null ) { return newName ; } } return null ; }
Walks the stack of name maps and finds the replacement name for the current scope .
35,120
private static Node fuseIntoOneStatement ( Node parent , Node first , Node last ) { if ( first . getNext ( ) == last ) { return first ; } 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 ) ; } first . addChildToBack ( commaTree ) ; return first ; }
Given a block fuse a list of statements with comma s .
35,121
public N getPartitionSuperNode ( N node ) { checkNotNull ( colorToNodeMap , "No coloring founded. color() should be called first." ) ; Color color = graph . getNode ( node ) . getAnnotation ( ) ; N headNode = colorToNodeMap [ color . value ] ; if ( headNode == null ) { colorToNodeMap [ color . value ] = node ; return node ; } else { return headNode ; } }
Using the coloring as partitions finds the node that represents that partition as the super node . The first to retrieve its partition will become the super node .
35,122
static Node inject ( AbstractCompiler compiler , Node node , Node parent , Map < String , Node > replacements ) { return inject ( compiler , node , parent , replacements , true ) ; }
With the map provided replace the names with expression trees .
35,123
static ImmutableMap < String , Node > getFunctionCallParameterMap ( final Node fnNode , Node callNode , Supplier < String > safeNameIdSupplier ) { checkNotNull ( fnNode ) ; ImmutableMap . Builder < String , Node > argMap = ImmutableMap . builder ( ) ; Node cArg = callNode . getSecondChild ( ) ; if ( cArg != null && NodeUtil . isFunctionObjectCall ( callNode ) ) { argMap . put ( THIS_MARKER , cArg ) ; cArg = cArg . getNext ( ) ; } else { checkState ( ! NodeUtil . isFunctionObjectApply ( callNode ) , callNode ) ; argMap . put ( THIS_MARKER , NodeUtil . newUndefinedNode ( callNode ) ) ; } for ( Node fnParam : NodeUtil . getFunctionParameters ( fnNode ) . children ( ) ) { if ( cArg != null ) { if ( fnParam . isRest ( ) ) { checkState ( fnParam . getOnlyChild ( ) . isName ( ) , fnParam . getOnlyChild ( ) ) ; Node array = IR . arraylit ( ) ; array . useSourceInfoIfMissingFromForTree ( cArg ) ; while ( cArg != null ) { array . addChildToBack ( cArg . cloneTree ( ) ) ; cArg = cArg . getNext ( ) ; } argMap . put ( fnParam . getOnlyChild ( ) . getString ( ) , array ) ; return argMap . build ( ) ; } else { checkState ( fnParam . isName ( ) , fnParam ) ; argMap . put ( fnParam . getString ( ) , cArg ) ; } cArg = cArg . getNext ( ) ; } else { if ( fnParam . isRest ( ) ) { checkState ( fnParam . getOnlyChild ( ) . isName ( ) , fnParam ) ; Node array = IR . arraylit ( ) ; argMap . put ( fnParam . getOnlyChild ( ) . getString ( ) , array ) ; } else { checkState ( fnParam . isName ( ) , fnParam ) ; Node srcLocation = callNode ; argMap . put ( fnParam . getString ( ) , NodeUtil . newUndefinedNode ( srcLocation ) ) ; } } } while ( cArg != null ) { String uniquePlaceholder = getUniqueAnonymousParameterName ( safeNameIdSupplier ) ; argMap . put ( uniquePlaceholder , cArg ) ; cArg = cArg . getNext ( ) ; } return argMap . build ( ) ; }
Get a mapping for function parameter names to call arguments .
35,124
static void maybeAddTempsForCallArguments ( AbstractCompiler compiler , Node fnNode , ImmutableMap < String , Node > argMap , Set < String > namesNeedingTemps , CodingConvention convention ) { if ( argMap . isEmpty ( ) ) { return ; } checkArgument ( fnNode . isFunction ( ) , fnNode ) ; Node block = fnNode . getLastChild ( ) ; int argCount = argMap . size ( ) ; boolean isTrivialBody = ( ! block . hasChildren ( ) || ( block . hasOneChild ( ) && ! bodyMayHaveConditionalCode ( block . getLastChild ( ) ) ) ) ; boolean hasMinimalParameters = NodeUtil . isUndefined ( argMap . get ( THIS_MARKER ) ) && argCount <= 2 ; ImmutableSet < String > namesAfterSideEffects = findParametersReferencedAfterSideEffect ( argMap . keySet ( ) , block ) ; for ( Map . Entry < String , Node > entry : argMap . entrySet ( ) ) { String argName = entry . getKey ( ) ; if ( namesNeedingTemps . contains ( argName ) ) { continue ; } Node cArg = entry . getValue ( ) ; boolean safe = true ; int references = NodeUtil . getNameReferenceCount ( block , argName ) ; boolean argSideEffects = NodeUtil . mayHaveSideEffects ( cArg , compiler ) ; if ( ! argSideEffects && references == 0 ) { safe = true ; } else if ( isTrivialBody && hasMinimalParameters && references == 1 && ! ( NodeUtil . canBeSideEffected ( cArg ) && namesAfterSideEffects . contains ( argName ) ) ) { safe = true ; } else if ( NodeUtil . mayEffectMutableState ( cArg , compiler ) && references > 0 ) { safe = false ; } else if ( argSideEffects ) { safe = false ; } else if ( NodeUtil . canBeSideEffected ( cArg ) && namesAfterSideEffects . contains ( argName ) ) { safe = false ; } else if ( references > 1 ) { switch ( cArg . getToken ( ) ) { case NAME : String name = cArg . getString ( ) ; safe = ! ( convention . isExported ( name ) ) ; break ; case THIS : safe = true ; break ; case STRING : safe = ( cArg . getString ( ) . length ( ) < 2 ) ; break ; default : safe = NodeUtil . isImmutableValue ( cArg ) ; break ; } } if ( ! safe ) { namesNeedingTemps . add ( argName ) ; } } }
Updates the set of parameter names in set unsafe to include any arguments from the call site that require aliases .
35,125
static boolean bodyMayHaveConditionalCode ( Node n ) { if ( ! n . isReturn ( ) && ! n . isExprResult ( ) ) { return true ; } return mayHaveConditionalCode ( n ) ; }
We consider a return or expression trivial if it doesn t contain a conditional expression or a function .
35,126
static boolean mayHaveConditionalCode ( Node n ) { for ( Node c = n . getFirstChild ( ) ; c != null ; c = c . getNext ( ) ) { switch ( c . getToken ( ) ) { case FUNCTION : case AND : case OR : case HOOK : return true ; default : break ; } if ( mayHaveConditionalCode ( c ) ) { return true ; } } return false ; }
We consider an expression trivial if it doesn t contain a conditional expression or a function .
35,127
private static ImmutableSet < String > findParametersReferencedAfterSideEffect ( ImmutableSet < String > parameters , Node root ) { Set < String > locals = new HashSet < > ( parameters ) ; gatherLocalNames ( root , locals ) ; ReferencedAfterSideEffect collector = new ReferencedAfterSideEffect ( parameters , ImmutableSet . copyOf ( locals ) ) ; NodeUtil . visitPostOrder ( root , collector , collector ) ; return collector . getResults ( ) ; }
Bootstrap a traversal to look for parameters referenced after a non - local side - effect .
35,128
private static void gatherLocalNames ( Node n , Set < String > names ) { if ( n . isFunction ( ) ) { if ( NodeUtil . isFunctionDeclaration ( n ) ) { names . add ( n . getFirstChild ( ) . getString ( ) ) ; } return ; } else if ( n . isName ( ) ) { switch ( n . getParent ( ) . getToken ( ) ) { case VAR : case LET : case CONST : case CATCH : names . add ( n . getString ( ) ) ; break ; default : break ; } } for ( Node c = n . getFirstChild ( ) ; c != null ; c = c . getNext ( ) ) { gatherLocalNames ( c , names ) ; } }
Gather any names declared in the local scope .
35,129
private static ImmutableSet < String > getFunctionParameterSet ( Node fnNode ) { ImmutableSet . Builder < String > builder = ImmutableSet . builder ( ) ; for ( Node n : NodeUtil . getFunctionParameters ( fnNode ) . children ( ) ) { if ( n . isRest ( ) ) { builder . add ( REST_MARKER ) ; } else if ( n . isDefaultValue ( ) || n . isObjectPattern ( ) || n . isArrayPattern ( ) ) { throw new IllegalStateException ( "Not supported: " + n ) ; } else { builder . add ( n . getString ( ) ) ; } } return builder . build ( ) ; }
Get a set of function parameter names .
35,130
public static ConformanceConfig loadGlobalConformance ( Class < ? > clazz ) { ConformanceConfig . Builder builder = ConformanceConfig . newBuilder ( ) ; if ( resourceExists ( clazz , "global_conformance.binarypb" ) ) { try { builder . mergeFrom ( clazz . getResourceAsStream ( "global_conformance.binarypb" ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } return builder . build ( ) ; }
Load the global ConformanceConfig
35,131
private boolean isLoneBlock ( Node n ) { Node parent = n . getParent ( ) ; if ( parent != null && ( parent . isScript ( ) || ( parent . isBlock ( ) && ! parent . isSyntheticBlock ( ) && ! parent . isAddedBlock ( ) ) ) ) { return ! n . isSyntheticBlock ( ) && ! n . isAddedBlock ( ) ; } return false ; }
A lone block is a non - synthetic not - added BLOCK that is a direct child of another non - synthetic not - added BLOCK or a SCRIPT node .
35,132
private void allowLoneBlock ( Node parent ) { if ( loneBlocks . isEmpty ( ) ) { return ; } if ( loneBlocks . peek ( ) == parent ) { loneBlocks . pop ( ) ; } }
Remove the enclosing block of a block - scoped declaration from the loneBlocks stack .
35,133
void maybeExposeExpression ( Node expression ) { int i = 0 ; while ( DecompositionType . DECOMPOSABLE == canExposeExpression ( expression ) ) { exposeExpression ( expression ) ; i ++ ; if ( i > MAX_ITERATIONS ) { throw new IllegalStateException ( "DecomposeExpression depth exceeded on:\n" + expression . toStringTree ( ) ) ; } } }
If required rewrite the statement containing the expression .
35,134
void moveExpression ( Node expression ) { String resultName = getResultValueName ( ) ; Node injectionPoint = findInjectionPoint ( expression ) ; checkNotNull ( injectionPoint ) ; Node injectionPointParent = injectionPoint . getParent ( ) ; checkNotNull ( injectionPointParent ) ; checkState ( NodeUtil . isStatementBlock ( injectionPointParent ) ) ; Node expressionParent = expression . getParent ( ) ; expressionParent . replaceChild ( expression , withType ( IR . name ( resultName ) , expression . getJSType ( ) ) ) ; Node newExpressionRoot = NodeUtil . newVarNode ( resultName , expression ) ; newExpressionRoot . getFirstChild ( ) . setJSType ( expression . getJSType ( ) ) ; injectionPointParent . addChildBefore ( newExpressionRoot , injectionPoint ) ; compiler . reportChangeToEnclosingScope ( injectionPointParent ) ; }
Extract the specified expression from its parent expression .
35,135
private static Node buildResultExpression ( Node expr , boolean needResult , String tempName ) { if ( needResult ) { JSType type = expr . getJSType ( ) ; return withType ( IR . assign ( withType ( IR . name ( tempName ) , type ) , expr ) , type ) . srcrefTree ( expr ) ; } else { return expr ; } }
Create an expression tree for an expression .
35,136
private Node rewriteCallExpression ( Node call , DecompositionState state ) { checkArgument ( call . isCall ( ) , call ) ; Node first = call . getFirstChild ( ) ; checkArgument ( NodeUtil . isGet ( first ) , first ) ; JSType fnType = first . getJSType ( ) ; JSType fnCallType = null ; if ( fnType != null ) { fnCallType = fnType . isFunctionType ( ) ? fnType . toMaybeFunctionType ( ) . getPropertyType ( "call" ) : unknownType ; } Node getVarNode = extractExpression ( first , state . extractBeforeStatement ) ; state . extractBeforeStatement = getVarNode ; Node getExprNode = getVarNode . getFirstFirstChild ( ) ; checkArgument ( NodeUtil . isGet ( getExprNode ) , getExprNode ) ; Node thisVarNode = extractExpression ( getExprNode . getFirstChild ( ) , state . extractBeforeStatement ) ; state . extractBeforeStatement = thisVarNode ; Node thisNameNode = thisVarNode . getFirstChild ( ) ; Node functionNameNode = getVarNode . getFirstChild ( ) ; Node newCall = IR . call ( withType ( IR . getprop ( functionNameNode . cloneNode ( ) , withType ( IR . string ( "call" ) , stringType ) ) , fnCallType ) , thisNameNode . cloneNode ( ) ) . setJSType ( call . getJSType ( ) ) . useSourceInfoIfMissingFromForTree ( call ) ; call . removeFirstChild ( ) ; if ( call . hasChildren ( ) ) { newCall . addChildrenToBack ( call . removeChildren ( ) ) ; } call . replaceWith ( newCall ) ; return newCall ; }
Rewrite the call so this is preserved .
35,137
private String getTempConstantValueName ( ) { String name = tempNamePrefix + "_const" + ContextualRenamer . UNIQUE_ID_SEPARATOR + safeNameIdSupplier . get ( ) ; this . knownConstants . add ( name ) ; return name ; }
Create a constant unique temp name .
35,138
private static EvaluationDirection getEvaluationDirection ( Node node ) { switch ( node . getToken ( ) ) { case DESTRUCTURING_LHS : case ASSIGN : case DEFAULT_VALUE : if ( node . getFirstChild ( ) . isDestructuringPattern ( ) ) { return EvaluationDirection . REVERSE ; } default : return EvaluationDirection . FORWARD ; } }
Returns the order in which the given node s children should be evaluated .
35,139
Node mutateWithoutRenaming ( String fnName , Node fnNode , Node callNode , String resultName , boolean needsDefaultResult , boolean isCallInLoop ) { return mutateInternal ( fnName , fnNode , callNode , resultName , needsDefaultResult , isCallInLoop , false ) ; }
Used where the inlining occurs into an isolated scope such as a module . Renaming is avoided since the associated JSDoc annotations are not updated .
35,140
private static void fixUninitializedVarDeclarations ( Node n , Node containingBlock ) { if ( NodeUtil . isLoopStructure ( n ) ) { return ; } if ( ( n . isVar ( ) || n . isLet ( ) ) && n . hasOneChild ( ) ) { Node name = n . getFirstChild ( ) ; if ( ! name . hasChildren ( ) ) { Node srcLocation = name ; name . addChildToBack ( NodeUtil . newUndefinedNode ( srcLocation ) ) ; containingBlock . addChildToFront ( n . detach ( ) ) ; } return ; } for ( Node c = n . getFirstChild ( ) ; c != null ; c = c . getNext ( ) ) { fixUninitializedVarDeclarations ( c , containingBlock ) ; } }
For all VAR node with uninitialized declarations set the values to be undefined .
35,141
private void makeLocalNamesUnique ( Node fnNode , boolean isCallInLoop ) { Supplier < String > idSupplier = compiler . getUniqueNameIdSupplier ( ) ; NodeTraversal . traverseScopeRoots ( compiler , null , ImmutableList . of ( fnNode ) , new MakeDeclaredNamesUnique ( new InlineRenamer ( compiler . getCodingConvention ( ) , idSupplier , "inline_" , isCallInLoop , true , null ) , false ) , true ) ; new RenameLabels ( compiler , new LabelNameSupplier ( idSupplier ) , false , false ) . process ( null , fnNode ) ; }
Fix - up all local names to be unique for this subtree .
35,142
private String getLabelNameForFunction ( String fnName ) { String name = ( isNullOrEmpty ( fnName ) ) ? "anon" : fnName ; return "JSCompiler_inline_label_" + name + "_" + safeNameIdSupplier . get ( ) ; }
Create a unique label name .
35,143
private Node aliasAndInlineArguments ( Node fnTemplateRoot , ImmutableMap < String , Node > argMap , Set < String > namesToAlias ) { if ( namesToAlias == null || namesToAlias . isEmpty ( ) ) { Node result = FunctionArgumentInjector . inject ( compiler , fnTemplateRoot , null , argMap ) ; checkState ( result == fnTemplateRoot ) ; return result ; } else { Map < String , Node > newArgMap = new HashMap < > ( argMap ) ; List < Node > newVars = new ArrayList < > ( ) ; for ( Entry < String , Node > entry : argMap . entrySet ( ) ) { String name = entry . getKey ( ) ; if ( namesToAlias . contains ( name ) ) { if ( name . equals ( THIS_MARKER ) ) { boolean referencesThis = NodeUtil . referencesThis ( fnTemplateRoot ) ; Node value = entry . getValue ( ) ; if ( ! value . isThis ( ) && ( referencesThis || NodeUtil . mayHaveSideEffects ( value , compiler ) ) ) { String newName = getUniqueThisName ( ) ; Node newValue = entry . getValue ( ) . cloneTree ( ) ; Node newNode = NodeUtil . newVarNode ( newName , newValue ) . useSourceInfoIfMissingFromForTree ( newValue ) ; newVars . add ( 0 , newNode ) ; newArgMap . put ( THIS_MARKER , IR . name ( newName ) . srcrefTree ( newValue ) ) ; } } else { Node newValue = entry . getValue ( ) . cloneTree ( ) ; Node newNode = NodeUtil . newVarNode ( name , newValue ) . useSourceInfoIfMissingFromForTree ( newValue ) ; newVars . add ( 0 , newNode ) ; newArgMap . remove ( name ) ; } } } Node result = FunctionArgumentInjector . inject ( compiler , fnTemplateRoot , null , newArgMap ) ; checkState ( result == fnTemplateRoot ) ; for ( Node n : newVars ) { fnTemplateRoot . addChildToFront ( n ) ; } return result ; } }
Inlines the arguments within the node tree using the given argument map replaces unsafe names with local aliases .
35,144
private static Node createAssignStatementNode ( String name , Node expression ) { Node nameNode = IR . name ( name ) ; Node assign = IR . assign ( nameNode , expression ) ; return NodeUtil . newExpr ( assign ) ; }
Create a valid statement Node containing an assignment to name of the given expression .
35,145
private List < JSModule > makeWeakModule ( List < JSModule > modulesInDepOrder ) { boolean hasWeakModule = false ; for ( JSModule module : modulesInDepOrder ) { if ( module . getName ( ) . equals ( JSModule . WEAK_MODULE_NAME ) ) { hasWeakModule = true ; Set < JSModule > allOtherModules = new HashSet < > ( modulesInDepOrder ) ; allOtherModules . remove ( module ) ; checkState ( module . getAllDependencies ( ) . containsAll ( allOtherModules ) , "A weak module already exists but it does not depend on every other module." ) ; checkState ( module . getAllDependencies ( ) . size ( ) == allOtherModules . size ( ) , "The weak module cannot have extra dependencies." ) ; break ; } } if ( hasWeakModule ) { for ( JSModule module : modulesInDepOrder ) { for ( CompilerInput input : module . getInputs ( ) ) { if ( module . getName ( ) . equals ( JSModule . WEAK_MODULE_NAME ) ) { checkState ( input . getSourceFile ( ) . isWeak ( ) , "A weak module already exists but strong sources were found in it." ) ; } else { checkState ( ! input . getSourceFile ( ) . isWeak ( ) , "A weak module already exists but weak sources were found in other modules." ) ; } } } } else { JSModule weakModule = new JSModule ( JSModule . WEAK_MODULE_NAME ) ; for ( JSModule module : modulesInDepOrder ) { weakModule . addDependency ( module ) ; } modulesInDepOrder = new ArrayList < > ( modulesInDepOrder ) ; modulesInDepOrder . add ( weakModule ) ; } return modulesInDepOrder ; }
If a weak module doesn t already exist creates a weak module depending on every other module .
35,146
Iterable < CompilerInput > getAllInputs ( ) { return Iterables . concat ( Iterables . transform ( Arrays . asList ( modules ) , JSModule :: getInputs ) ) ; }
Gets an iterable over all input source files in dependency order .
35,147
Map < String , JSModule > getModulesByName ( ) { Map < String , JSModule > result = new HashMap < > ( ) ; for ( JSModule m : modules ) { result . put ( m . getName ( ) , m ) ; } return result ; }
Gets all modules indexed by name .
35,148
public boolean dependsOn ( JSModule src , JSModule m ) { return src != m && selfPlusTransitiveDeps [ src . getIndex ( ) ] . get ( m . getIndex ( ) ) ; }
Determines whether this module depends on a given module . Note that a module never depends on itself as that dependency would be cyclic .
35,149
public JSModule getSmallestCoveringSubtree ( JSModule parentTree , BitSet dependentModules ) { checkState ( ! dependentModules . isEmpty ( ) ) ; int minDependentModuleIndex = modules . length ; final BitSet candidates = new BitSet ( modules . length ) ; candidates . set ( 0 , modules . length , true ) ; for ( int dependentIndex = dependentModules . nextSetBit ( 0 ) ; dependentIndex >= 0 ; dependentIndex = dependentModules . nextSetBit ( dependentIndex + 1 ) ) { minDependentModuleIndex = Math . min ( minDependentModuleIndex , dependentIndex ) ; candidates . and ( selfPlusTransitiveDeps [ dependentIndex ] ) ; } checkState ( ! candidates . isEmpty ( ) , "No common dependency found for %s" , dependentModules ) ; int parentTreeIndex = parentTree . getIndex ( ) ; int bestCandidateIndex = parentTreeIndex ; for ( int candidateIndex = candidates . previousSetBit ( minDependentModuleIndex ) ; candidateIndex >= 0 ; candidateIndex = candidates . previousSetBit ( candidateIndex - 1 ) ) { BitSet candidatePlusTransitiveDeps = selfPlusTransitiveDeps [ candidateIndex ] ; if ( candidatePlusTransitiveDeps . get ( parentTreeIndex ) ) { candidates . andNot ( candidatePlusTransitiveDeps ) ; if ( subtreeSize [ candidateIndex ] < subtreeSize [ bestCandidateIndex ] ) { bestCandidateIndex = candidateIndex ; } } } return modules [ bestCandidateIndex ] ; }
Finds the module with the fewest transitive dependents on which all of the given modules depend and that is a subtree of the given parent module tree .
35,150
JSModule getDeepestCommonDependency ( JSModule m1 , JSModule m2 ) { int m1Depth = m1 . getDepth ( ) ; int m2Depth = m2 . getDepth ( ) ; for ( int depth = Math . min ( m1Depth , m2Depth ) - 1 ; depth >= 0 ; depth -- ) { List < JSModule > modulesAtDepth = modulesByDepth . get ( depth ) ; for ( int i = modulesAtDepth . size ( ) - 1 ; i >= 0 ; i -- ) { JSModule m = modulesAtDepth . get ( i ) ; if ( dependsOn ( m1 , m ) && dependsOn ( m2 , m ) ) { return m ; } } } return null ; }
Finds the deepest common dependency of two modules not including the two modules themselves .
35,151
public JSModule getDeepestCommonDependencyInclusive ( JSModule m1 , JSModule m2 ) { if ( m2 == m1 || dependsOn ( m2 , m1 ) ) { return m1 ; } else if ( dependsOn ( m1 , m2 ) ) { return m2 ; } return getDeepestCommonDependency ( m1 , m2 ) ; }
Finds the deepest common dependency of two modules including the modules themselves .
35,152
public JSModule getDeepestCommonDependencyInclusive ( Collection < JSModule > modules ) { Iterator < JSModule > iter = modules . iterator ( ) ; JSModule dep = iter . next ( ) ; while ( iter . hasNext ( ) ) { dep = getDeepestCommonDependencyInclusive ( dep , iter . next ( ) ) ; } return dep ; }
Returns the deepest common dependency of the given modules .
35,153
private Set < JSModule > getTransitiveDeps ( JSModule m ) { Set < JSModule > deps = dependencyMap . computeIfAbsent ( m , JSModule :: getAllDependencies ) ; return deps ; }
Returns the transitive dependencies of the module .
35,154
private List < CompilerInput > getDepthFirstDependenciesOf ( CompilerInput rootInput , Set < CompilerInput > unreachedInputs , Map < String , CompilerInput > inputsByProvide ) { List < CompilerInput > orderedInputs = new ArrayList < > ( ) ; if ( ! unreachedInputs . remove ( rootInput ) ) { return orderedInputs ; } for ( String importedNamespace : rootInput . getRequiredSymbols ( ) ) { CompilerInput dependency = null ; if ( inputsByProvide . containsKey ( importedNamespace ) && unreachedInputs . contains ( inputsByProvide . get ( importedNamespace ) ) ) { dependency = inputsByProvide . get ( importedNamespace ) ; } if ( dependency != null ) { orderedInputs . addAll ( getDepthFirstDependenciesOf ( dependency , unreachedInputs , inputsByProvide ) ) ; } } orderedInputs . add ( rootInput ) ; return orderedInputs ; }
Given an input and set of unprocessed inputs return the input and it s strong dependencies by performing a recursive depth - first traversal .
35,155
private void computeDependence ( final Definition def , Node rValue ) { NodeTraversal . traverse ( compiler , rValue , new AbstractCfgNodeTraversalCallback ( ) { public void visit ( NodeTraversal t , Node n , Node parent ) { if ( n . isName ( ) ) { Var dep = allVarsInFn . get ( n . getString ( ) ) ; if ( dep == null ) { def . unknownDependencies = true ; } else { def . depends . add ( dep ) ; } } } } ) ; }
Computes all the local variables that rValue reads from and store that in the def s depends set .
35,156
Definition getDef ( String name , Node useNode ) { checkArgument ( getCfg ( ) . hasNode ( useNode ) ) ; GraphNode < Node , Branch > n = getCfg ( ) . getNode ( useNode ) ; FlowState < MustDef > state = n . getAnnotation ( ) ; return state . getIn ( ) . reachingDef . get ( allVarsInFn . get ( name ) ) ; }
Gets the must reaching definition of a given node .
35,157
public void appendTo ( Appendable out , DependencyInfo info , File content , Charset contentCharset ) throws IOException { appendTo ( out , info , Files . asCharSource ( content , contentCharset ) ) ; }
Append the contents of the file to the supplied appendable .
35,158
public void appendTo ( Appendable out , DependencyInfo info , CharSource content ) throws IOException { if ( info . isModule ( ) ) { mode . appendGoogModule ( transpile ( content . read ( ) ) , out , sourceUrl ) ; } else if ( "es6" . equals ( info . getLoadFlags ( ) . get ( "module" ) ) && transpiler == Transpiler . NULL ) { mode . appendTraditional ( transpileEs6Module ( content . read ( ) ) , out , sourceUrl ) ; } else { mode . appendTraditional ( transpile ( content . read ( ) ) , out , sourceUrl ) ; } }
Append the contents of the CharSource to the supplied appendable .
35,159
private ResolveBehaviorNameResult resolveBehaviorName ( Node nameNode ) { String name = getQualifiedNameThroughCast ( nameNode ) ; if ( name == null ) { return null ; } Name globalName = globalNames . getSlot ( name ) ; if ( globalName == null ) { return null ; } boolean isGlobalDeclaration = true ; Ref declarationRef = globalName . getDeclaration ( ) ; if ( declarationRef == null ) { for ( Ref ref : globalName . getRefs ( ) ) { if ( ref . isSet ( ) ) { isGlobalDeclaration = false ; declarationRef = ref ; break ; } } } if ( declarationRef == null ) { return null ; } Node declarationNode = declarationRef . getNode ( ) ; if ( declarationNode == null ) { return null ; } Node rValue = NodeUtil . getRValueOfLValue ( declarationNode ) ; if ( rValue == null ) { return null ; } if ( rValue . isQualifiedName ( ) ) { return resolveBehaviorName ( rValue ) ; } JSDocInfo behaviorInfo = NodeUtil . getBestJSDocInfo ( declarationNode ) ; if ( behaviorInfo == null || ! behaviorInfo . isPolymerBehavior ( ) ) { compiler . report ( JSError . make ( declarationNode , PolymerPassErrors . POLYMER_UNANNOTATED_BEHAVIOR ) ) ; } return new ResolveBehaviorNameResult ( rValue , isGlobalDeclaration ) ; }
Resolve an identifier which is presumed to refer to a Polymer Behavior declaration using the global namespace . Recurses to resolve assignment chains of any length .
35,160
private static ImmutableList < Rule > initRules ( AbstractCompiler compiler , ImmutableList < ConformanceConfig > configs ) { ImmutableList . Builder < Rule > builder = ImmutableList . builder ( ) ; List < Requirement > requirements = mergeRequirements ( compiler , configs ) ; for ( Requirement requirement : requirements ) { Rule rule = initRule ( compiler , requirement ) ; if ( rule != null ) { builder . add ( rule ) ; } } return builder . build ( ) ; }
Build the data structures need by this pass from the provided configurations .
35,161
static List < Requirement > mergeRequirements ( AbstractCompiler compiler , List < ConformanceConfig > configs ) { List < Requirement . Builder > builders = new ArrayList < > ( ) ; Map < String , Requirement . Builder > extendable = new HashMap < > ( ) ; for ( ConformanceConfig config : configs ) { for ( Requirement requirement : config . getRequirementList ( ) ) { Requirement . Builder builder = requirement . toBuilder ( ) ; if ( requirement . hasRuleId ( ) ) { if ( requirement . getRuleId ( ) . isEmpty ( ) ) { reportInvalidRequirement ( compiler , requirement , "empty rule_id" ) ; continue ; } if ( extendable . containsKey ( requirement . getRuleId ( ) ) ) { reportInvalidRequirement ( compiler , requirement , "two requirements with the same rule_id: " + requirement . getRuleId ( ) ) ; continue ; } extendable . put ( requirement . getRuleId ( ) , builder ) ; } if ( ! requirement . hasExtends ( ) ) { builders . add ( builder ) ; } } } for ( ConformanceConfig config : configs ) { for ( Requirement requirement : config . getRequirementList ( ) ) { if ( requirement . hasExtends ( ) ) { Requirement . Builder existing = extendable . get ( requirement . getExtends ( ) ) ; if ( existing == null ) { reportInvalidRequirement ( compiler , requirement , "no requirement with rule_id: " + requirement . getExtends ( ) ) ; continue ; } for ( Descriptors . FieldDescriptor field : requirement . getAllFields ( ) . keySet ( ) ) { if ( ! EXTENDABLE_FIELDS . contains ( field . getName ( ) ) ) { reportInvalidRequirement ( compiler , requirement , "extending rules allow only " + EXTENDABLE_FIELDS ) ; } } existing . addAllWhitelist ( requirement . getWhitelistList ( ) ) ; existing . addAllWhitelistRegexp ( requirement . getWhitelistRegexpList ( ) ) ; existing . addAllOnlyApplyTo ( requirement . getOnlyApplyToList ( ) ) ; existing . addAllOnlyApplyToRegexp ( requirement . getOnlyApplyToRegexpList ( ) ) ; existing . addAllWhitelistEntry ( requirement . getWhitelistEntryList ( ) ) ; } } } List < Requirement > requirements = new ArrayList < > ( builders . size ( ) ) ; for ( Requirement . Builder builder : builders ) { removeDuplicates ( builder ) ; requirements . add ( builder . build ( ) ) ; } return requirements ; }
Gets requirements from all configs . Merges whitelists of requirements with extends equal to rule_id of other rule .
35,162
public DependencyInfo parseFile ( String filePath , String closureRelativePath , String fileContents ) { return parseReader ( filePath , closureRelativePath , new StringReader ( fileContents ) ) ; }
Parses the given file and returns the dependency information that it contained .
35,163
protected boolean parseLine ( String line ) throws ParseException { boolean lineHasProvidesOrRequires = false ; if ( line . startsWith ( BUNDLED_GOOG_MODULE_START ) ) { seenLoadModule = true ; } if ( line . contains ( "provide" ) || line . contains ( "require" ) || line . contains ( "module" ) || line . contains ( "addDependency" ) || line . contains ( "declareModuleId" ) ) { googMatcher . reset ( line ) ; while ( googMatcher . find ( ) ) { lineHasProvidesOrRequires = true ; if ( includeGoogBase && ! fileHasProvidesOrRequires ) { fileHasProvidesOrRequires = true ; requires . add ( Require . BASE ) ; } String methodName = googMatcher . group ( "func" ) ; char firstChar = methodName . charAt ( 0 ) ; boolean isDeclareModuleNamespace = firstChar == 'd' ; boolean isModule = ! isDeclareModuleNamespace && firstChar == 'm' ; boolean isProvide = firstChar == 'p' ; boolean providesNamespace = isProvide || isModule || isDeclareModuleNamespace ; boolean isRequire = firstChar == 'r' ; if ( isModule && ! seenLoadModule ) { providesNamespace = setModuleType ( ModuleType . GOOG_MODULE ) ; } if ( isProvide ) { providesNamespace = setModuleType ( ModuleType . GOOG_PROVIDE ) ; } if ( providesNamespace || isRequire ) { String arg = parseJsString ( googMatcher . group ( "args" ) ) ; if ( isRequire ) { if ( "requireType" . equals ( methodName ) ) { typeRequires . add ( arg ) ; } else if ( ! "goog" . equals ( arg ) ) { Require require = Require . googRequireSymbol ( arg ) ; requires . add ( require ) ; } } else { provides . add ( arg ) ; } } } } if ( line . startsWith ( "import" ) || line . startsWith ( "export" ) ) { es6Matcher . reset ( line ) ; while ( es6Matcher . find ( ) ) { setModuleType ( ModuleType . ES6_MODULE ) ; lineHasProvidesOrRequires = true ; String arg = es6Matcher . group ( 1 ) ; if ( arg != null ) { if ( arg . startsWith ( "goog:" ) ) { requires . add ( Require . googRequireSymbol ( arg . substring ( 5 ) ) ) ; } else { ModuleLoader . ModulePath path = file . resolveJsModule ( arg , filePath , lineNum , es6Matcher . start ( ) ) ; if ( path == null ) { path = file . resolveModuleAsPath ( arg ) ; } requires . add ( Require . es6Import ( path . toModuleName ( ) , arg ) ) ; } } } if ( moduleType != ModuleType . ES6_MODULE && ES6_EXPORT_PATTERN . matcher ( line ) . lookingAt ( ) ) { setModuleType ( ModuleType . ES6_MODULE ) ; } } return ! shortcutMode || lineHasProvidesOrRequires || CharMatcher . whitespace ( ) . matchesAllOf ( line ) || ! line . contains ( ";" ) || line . contains ( "goog.setTestOnly" ) || line . contains ( "goog.module.declareLegacyNamespace" ) ; }
Parses a line of JavaScript extracting goog . provide and goog . require information .
35,164
private static ImmutableList < Node > paramNamesOf ( Node paramList ) { checkArgument ( paramList . isParamList ( ) , paramList ) ; ImmutableList . Builder < Node > builder = ImmutableList . builder ( ) ; paramNamesOf ( paramList , builder ) ; return builder . build ( ) ; }
Returns the NAME parameter nodes of a FUNCTION .
35,165
private static void paramNamesOf ( Node node , ImmutableList . Builder < Node > names ) { switch ( node . getToken ( ) ) { case NAME : names . add ( node ) ; break ; case REST : case DEFAULT_VALUE : paramNamesOf ( node . getFirstChild ( ) , names ) ; break ; case PARAM_LIST : case ARRAY_PATTERN : for ( Node child = node . getFirstChild ( ) ; child != null ; child = child . getNext ( ) ) { paramNamesOf ( child , names ) ; } break ; case OBJECT_PATTERN : for ( Node child = node . getFirstChild ( ) ; child != null ; child = child . getNext ( ) ) { checkArgument ( child . isStringKey ( ) || child . isComputedProp ( ) , child ) ; paramNamesOf ( child . getLastChild ( ) , names ) ; } break ; default : checkArgument ( false , node ) ; break ; } }
Recursively collects the NAME parameter nodes of a FUNCTION .
35,166
public void setIdGenerators ( Set < String > idGenerators ) { RenamingMap gen = new UniqueRenamingToken ( ) ; ImmutableMap . Builder < String , RenamingMap > builder = ImmutableMap . builder ( ) ; for ( String name : idGenerators ) { builder . put ( name , gen ) ; } this . idGenerators = builder . build ( ) ; }
Sets the id generators to replace .
35,167
public void setInlineVariables ( Reach reach ) { switch ( reach ) { case ALL : this . inlineVariables = true ; this . inlineLocalVariables = true ; break ; case LOCAL_ONLY : this . inlineVariables = false ; this . inlineLocalVariables = true ; break ; case NONE : this . inlineVariables = false ; this . inlineLocalVariables = false ; break ; default : throw new IllegalStateException ( "unexpected" ) ; } }
Set the variable inlining policy for the compiler .
35,168
public void setRemoveUnusedVariables ( Reach reach ) { switch ( reach ) { case ALL : this . removeUnusedVars = true ; this . removeUnusedLocalVars = true ; break ; case LOCAL_ONLY : this . removeUnusedVars = false ; this . removeUnusedLocalVars = true ; break ; case NONE : this . removeUnusedVars = false ; this . removeUnusedLocalVars = false ; break ; default : throw new IllegalStateException ( "unexpected" ) ; } }
Set the variable removal policy for the compiler .
35,169
public void setReplaceStringsConfiguration ( String placeholderToken , List < String > functionDescriptors ) { this . replaceStringsPlaceholderToken = placeholderToken ; this . replaceStringsFunctionDescriptions = new ArrayList < > ( functionDescriptors ) ; }
Sets the functions whose debug strings to replace .
35,170
public void setLanguage ( LanguageMode language ) { checkState ( language != LanguageMode . NO_TRANSPILE ) ; checkState ( language != LanguageMode . UNSUPPORTED ) ; this . setLanguageIn ( language ) ; this . setLanguageOut ( language ) ; }
Sets ECMAScript version to use .
35,171
public void setLanguageOut ( LanguageMode languageOut ) { checkState ( languageOut != LanguageMode . UNSUPPORTED ) ; if ( languageOut == LanguageMode . NO_TRANSPILE ) { languageOutIsDefaultStrict = Optional . absent ( ) ; outputFeatureSet = Optional . absent ( ) ; } else { languageOut = languageOut == LanguageMode . STABLE ? LanguageMode . STABLE_OUT : languageOut ; languageOutIsDefaultStrict = Optional . of ( languageOut . isDefaultStrict ( ) ) ; setOutputFeatureSet ( languageOut . toFeatureSet ( ) ) ; } }
Sets ECMAScript version to use for the output .
35,172
@ GwtIncompatible ( "Conformance" ) public void setConformanceConfigs ( List < ConformanceConfig > configs ) { this . conformanceConfigs = ImmutableList . < ConformanceConfig > builder ( ) . add ( ResourceLoader . loadGlobalConformance ( CompilerOptions . class ) ) . addAll ( configs ) . build ( ) ; }
Both enable and configure conformance checks if non - null .
35,173
@ GwtIncompatible ( "ObjectOutputStream" ) public void serialize ( OutputStream objectOutputStream ) throws IOException { new java . io . ObjectOutputStream ( objectOutputStream ) . writeObject ( this ) ; }
Serializes compiler options to a stream .
35,174
@ GwtIncompatible ( "ObjectInputStream" ) public static CompilerOptions deserialize ( InputStream objectInputStream ) throws IOException , ClassNotFoundException { return ( CompilerOptions ) new java . io . ObjectInputStream ( objectInputStream ) . readObject ( ) ; }
Deserializes compiler options from a stream .
35,175
private static boolean isHoistableFunction ( NodeTraversal t , Node node ) { return node . isFunction ( ) && t . getScope ( ) . getVarCount ( ) == 0 ; }
Returns whether the specified rValue is a function which does not receive any variables from its containing scope and is thus hoistable .
35,176
private void moveSiblingExclusive ( Node dest , Node start , Node end ) { checkNotNull ( start ) ; checkNotNull ( end ) ; while ( start . getNext ( ) != end ) { Node child = start . getNext ( ) . detach ( ) ; dest . addChildToBack ( child ) ; } }
Move the Nodes between start and end from the source block to the destination block . If start is null move the first child of the block . If end is null move the last child of the block .
35,177
public static boolean isEs6ModuleRoot ( Node scriptNode ) { checkArgument ( scriptNode . isScript ( ) , scriptNode ) ; if ( scriptNode . getBooleanProp ( Node . GOOG_MODULE ) ) { return false ; } return scriptNode . hasChildren ( ) && scriptNode . getFirstChild ( ) . isModuleBody ( ) ; }
Return whether or not the given script node represents an ES6 module file .
35,178
private void processFile ( Node root ) { checkArgument ( isEs6ModuleRoot ( root ) , root ) ; clearState ( ) ; root . putBooleanProp ( Node . TRANSPILED , true ) ; NodeTraversal . traverse ( compiler , root , this ) ; }
Rewrite a single ES6 module file to a global script version .
35,179
private ModuleMetadata getFallbackMetadataForNamespace ( String namespace ) { ModuleMetadata . Builder builder = ModuleMetadata . builder ( ) . moduleType ( ModuleMetadataMap . ModuleType . GOOG_PROVIDE ) . usesClosure ( true ) . isTestOnly ( false ) ; builder . googNamespacesBuilder ( ) . add ( namespace ) ; return builder . build ( ) ; }
Gets some made - up metadata for the given Closure namespace .
35,180
static String toDot ( Node n , ControlFlowGraph < Node > inCFG ) throws IOException { StringBuilder builder = new StringBuilder ( ) ; new DotFormatter ( n , inCFG , builder , false ) ; return builder . toString ( ) ; }
Converts an AST to dot representation .
35,181
public static String toDot ( GraphvizGraph graph ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( graph . isDirected ( ) ? "digraph" : "graph" ) ; builder . append ( INDENT ) ; builder . append ( graph . getName ( ) ) ; builder . append ( " {\n" ) ; builder . append ( INDENT ) ; builder . append ( "node [color=lightblue2, style=filled];\n" ) ; final String edgeSymbol = graph . isDirected ( ) ? ARROW : LINE ; List < GraphvizNode > nodes = graph . getGraphvizNodes ( ) ; String [ ] nodeNames = new String [ nodes . size ( ) ] ; for ( int i = 0 ; i < nodeNames . length ; i ++ ) { GraphvizNode gNode = nodes . get ( i ) ; nodeNames [ i ] = gNode . getId ( ) + " [label=\"" + gNode . getLabel ( ) + "\" color=\"" + gNode . getColor ( ) + "\"]" ; } Arrays . sort ( nodeNames ) ; for ( String nodeName : nodeNames ) { builder . append ( INDENT ) ; builder . append ( nodeName ) ; builder . append ( ";\n" ) ; } List < GraphvizEdge > edges = graph . getGraphvizEdges ( ) ; String [ ] edgeNames = new String [ edges . size ( ) ] ; for ( int i = 0 ; i < edgeNames . length ; i ++ ) { GraphvizEdge edge = edges . get ( i ) ; edgeNames [ i ] = edge . getNode1Id ( ) + edgeSymbol + edge . getNode2Id ( ) ; } Arrays . sort ( edgeNames ) ; for ( String edgeName : edgeNames ) { builder . append ( INDENT ) ; builder . append ( edgeName ) ; builder . append ( ";\n" ) ; } builder . append ( "}\n" ) ; return builder . toString ( ) ; }
Outputs a string in DOT format that presents the graph .
35,182
static void appendDot ( Node n , ControlFlowGraph < Node > inCFG , Appendable builder ) throws IOException { new DotFormatter ( n , inCFG , builder , false ) ; }
Converts an AST to dot representation and appends it to the given buffer .
35,183
private ParseTree parseFunctionDeclaration ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( Keywords . FUNCTION . type ) ; boolean isGenerator = eatOpt ( TokenType . STAR ) != null ; FunctionDeclarationTree . Builder builder = FunctionDeclarationTree . builder ( FunctionDeclarationTree . Kind . DECLARATION ) . setName ( eatId ( ) ) ; parseFunctionTail ( builder , isGenerator ? FunctionFlavor . GENERATOR : FunctionFlavor . NORMAL ) ; return builder . build ( getTreeLocation ( start ) ) ; }
13 Function Definition
35,184
private VariableStatementTree parseVariableStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; VariableDeclarationListTree declarations = parseVariableDeclarationList ( ) ; eatPossibleImplicitSemiColon ( ) ; return new VariableStatementTree ( getTreeLocation ( start ) , declarations ) ; }
12 . 2 Variable Statement
35,185
private EmptyStatementTree parseEmptyStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . SEMI_COLON ) ; return new EmptyStatementTree ( getTreeLocation ( start ) ) ; }
12 . 3 Empty Statement
35,186
private ExpressionStatementTree parseExpressionStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; ParseTree expression = parseExpression ( ) ; eatPossibleImplicitSemiColon ( ) ; return new ExpressionStatementTree ( getTreeLocation ( start ) , expression ) ; }
12 . 4 Expression Statement
35,187
private IfStatementTree parseIfStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . IF ) ; eat ( TokenType . OPEN_PAREN ) ; ParseTree condition = parseExpression ( ) ; eat ( TokenType . CLOSE_PAREN ) ; ParseTree ifClause = parseStatement ( ) ; ParseTree elseClause = null ; if ( peek ( TokenType . ELSE ) ) { eat ( TokenType . ELSE ) ; elseClause = parseStatement ( ) ; } return new IfStatementTree ( getTreeLocation ( start ) , condition , ifClause , elseClause ) ; }
12 . 5 If Statement
35,188
private ParseTree parseDoWhileStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . DO ) ; ParseTree body = parseStatement ( ) ; eat ( TokenType . WHILE ) ; eat ( TokenType . OPEN_PAREN ) ; ParseTree condition = parseExpression ( ) ; eat ( TokenType . CLOSE_PAREN ) ; if ( peek ( TokenType . SEMI_COLON ) ) { eat ( TokenType . SEMI_COLON ) ; } return new DoWhileStatementTree ( getTreeLocation ( start ) , body , condition ) ; }
12 . 6 . 1 The do - while Statement
35,189
private ParseTree parseWhileStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . WHILE ) ; eat ( TokenType . OPEN_PAREN ) ; ParseTree condition = parseExpression ( ) ; eat ( TokenType . CLOSE_PAREN ) ; ParseTree body = parseStatement ( ) ; return new WhileStatementTree ( getTreeLocation ( start ) , condition , body ) ; }
12 . 6 . 2 The while Statement
35,190
private ParseTree parseForStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . FOR ) ; boolean awaited = peekPredefinedString ( AWAIT ) ; if ( awaited ) { eatPredefinedString ( AWAIT ) ; } eat ( TokenType . OPEN_PAREN ) ; if ( peekVariableDeclarationList ( ) ) { VariableDeclarationListTree variables = parseVariableDeclarationListNoIn ( ) ; if ( peek ( TokenType . IN ) ) { if ( awaited ) { reportError ( "for-await-of is the only allowed asynchronous iteration" ) ; } if ( variables . declarations . size ( ) > 1 ) { reportError ( "for-in statement may not have more than one variable declaration" ) ; } VariableDeclarationTree declaration = variables . declarations . get ( 0 ) ; if ( declaration . initializer != null ) { if ( config . atLeast6 ) { reportError ( "for-in statement may not have initializer" ) ; } else { errorReporter . reportWarning ( declaration . location . start , "for-in statement should not have initializer" ) ; } } return parseForInStatement ( start , variables ) ; } else if ( peekPredefinedString ( PredefinedName . OF ) ) { if ( variables . declarations . size ( ) > 1 ) { if ( awaited ) { reportError ( "for-await-of statement may not have more than one variable declaration" ) ; } else { reportError ( "for-of statement may not have more than one variable declaration" ) ; } } VariableDeclarationTree declaration = variables . declarations . get ( 0 ) ; if ( declaration . initializer != null ) { if ( awaited ) { reportError ( "for-await-of statement may not have initializer" ) ; } else { reportError ( "for-of statement may not have initializer" ) ; } } if ( awaited ) { return parseForAwaitOfStatement ( start , variables ) ; } else { return parseForOfStatement ( start , variables ) ; } } else { checkVanillaForInitializers ( variables ) ; return parseForStatement ( start , variables ) ; } } if ( peek ( TokenType . SEMI_COLON ) ) { return parseForStatement ( start , null ) ; } ParseTree initializer = parseExpressionNoIn ( ) ; if ( peek ( TokenType . IN ) || peek ( TokenType . EQUAL ) || peekPredefinedString ( PredefinedName . OF ) ) { initializer = transformLeftHandSideExpression ( initializer ) ; if ( ! initializer . isValidAssignmentTarget ( ) ) { reportError ( "invalid assignment target" ) ; } } if ( peek ( TokenType . IN ) || peekPredefinedString ( PredefinedName . OF ) ) { if ( initializer . type != ParseTreeType . BINARY_OPERATOR && initializer . type != ParseTreeType . COMMA_EXPRESSION ) { if ( peek ( TokenType . IN ) ) { return parseForInStatement ( start , initializer ) ; } else { if ( awaited ) { return parseForAwaitOfStatement ( start , initializer ) ; } else { return parseForOfStatement ( start , initializer ) ; } } } } return parseForStatement ( start , initializer ) ; }
The for - await - of Statement
35,191
private void checkVanillaForInitializers ( VariableDeclarationListTree variables ) { for ( VariableDeclarationTree declaration : variables . declarations ) { if ( declaration . initializer == null ) { maybeReportNoInitializer ( variables . declarationType , declaration . lvalue ) ; } } }
Checks variable declarations in for statements .
35,192
private void maybeReportNoInitializer ( TokenType token , ParseTree lvalue ) { if ( token == TokenType . CONST ) { reportError ( "const variables must have an initializer" ) ; } else if ( lvalue . isPattern ( ) ) { reportError ( "destructuring must have an initializer" ) ; } }
Reports if declaration requires an initializer assuming initializer is absent .
35,193
private ParseTree parseForStatement ( SourcePosition start , ParseTree initializer ) { if ( initializer == null ) { initializer = new NullTree ( getTreeLocation ( getTreeStartLocation ( ) ) ) ; } eat ( TokenType . SEMI_COLON ) ; ParseTree condition ; if ( ! peek ( TokenType . SEMI_COLON ) ) { condition = parseExpression ( ) ; } else { condition = new NullTree ( getTreeLocation ( getTreeStartLocation ( ) ) ) ; } eat ( TokenType . SEMI_COLON ) ; ParseTree increment ; if ( ! peek ( TokenType . CLOSE_PAREN ) ) { increment = parseExpression ( ) ; } else { increment = new NullTree ( getTreeLocation ( getTreeStartLocation ( ) ) ) ; } eat ( TokenType . CLOSE_PAREN ) ; ParseTree body = parseStatement ( ) ; return new ForStatementTree ( getTreeLocation ( start ) , initializer , condition , increment , body ) ; }
12 . 6 . 3 The for Statement
35,194
private ParseTree parseForInStatement ( SourcePosition start , ParseTree initializer ) { eat ( TokenType . IN ) ; ParseTree collection = parseExpression ( ) ; eat ( TokenType . CLOSE_PAREN ) ; ParseTree body = parseStatement ( ) ; return new ForInStatementTree ( getTreeLocation ( start ) , initializer , collection , body ) ; }
12 . 6 . 4 The for - in Statement
35,195
private ParseTree parseContinueStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . CONTINUE ) ; IdentifierToken name = null ; if ( ! peekImplicitSemiColon ( ) ) { name = eatIdOpt ( ) ; } eatPossibleImplicitSemiColon ( ) ; return new ContinueStatementTree ( getTreeLocation ( start ) , name ) ; }
12 . 7 The continue Statement
35,196
private ParseTree parseBreakStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . BREAK ) ; IdentifierToken name = null ; if ( ! peekImplicitSemiColon ( ) ) { name = eatIdOpt ( ) ; } eatPossibleImplicitSemiColon ( ) ; return new BreakStatementTree ( getTreeLocation ( start ) , name ) ; }
12 . 8 The break Statement
35,197
private ParseTree parseReturnStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . RETURN ) ; ParseTree expression = null ; if ( ! peekImplicitSemiColon ( ) ) { expression = parseExpression ( ) ; } eatPossibleImplicitSemiColon ( ) ; return new ReturnStatementTree ( getTreeLocation ( start ) , expression ) ; }
12 . 9 The return Statement
35,198
private ParseTree parseWithStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . WITH ) ; eat ( TokenType . OPEN_PAREN ) ; ParseTree expression = parseExpression ( ) ; eat ( TokenType . CLOSE_PAREN ) ; ParseTree body = parseStatement ( ) ; return new WithStatementTree ( getTreeLocation ( start ) , expression , body ) ; }
12 . 10 The with Statement
35,199
private ParseTree parseSwitchStatement ( ) { SourcePosition start = getTreeStartLocation ( ) ; eat ( TokenType . SWITCH ) ; eat ( TokenType . OPEN_PAREN ) ; ParseTree expression = parseExpression ( ) ; eat ( TokenType . CLOSE_PAREN ) ; eat ( TokenType . OPEN_CURLY ) ; ImmutableList < ParseTree > caseClauses = parseCaseClauses ( ) ; eat ( TokenType . CLOSE_CURLY ) ; return new SwitchStatementTree ( getTreeLocation ( start ) , expression , caseClauses ) ; }
12 . 11 The switch Statement