idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
34,500
private Node parseAndRecordTypeNode ( JsDocToken token , int lineno , int startCharno , boolean matchingLC , boolean onlyParseSimpleNames ) { Node typeNode ; if ( onlyParseSimpleNames ) { typeNode = parseTypeNameAnnotation ( token ) ; } else { typeNode = parseTypeExpressionAnnotation ( token ) ; } recordTypeNode ( lineno , startCharno , typeNode , matchingLC ) ; return typeNode ; }
Looks for a parameter type expression at the current token and if found returns it . Note that this method consumes input .
34,501
private ExtractionInfo extractSingleLineBlock ( ) { stream . update ( ) ; int lineno = stream . getLineno ( ) ; int charno = stream . getCharno ( ) + 1 ; String line = getRemainingJSDocLine ( ) . trim ( ) ; if ( line . length ( ) > 0 ) { jsdocBuilder . markText ( line , lineno , charno , lineno , charno + line . length ( ) ) ; } return new ExtractionInfo ( line , next ( ) ) ; }
Extracts the text found on the current line starting at token . Note that token = token . info ; should be called after this method is used to update the token properly in the parser .
34,502
private ExtractionInfo extractMultilineComment ( JsDocToken token , WhitespaceOption option , boolean isMarker , boolean includeAnnotations ) { StringBuilder builder = new StringBuilder ( ) ; int startLineno = - 1 ; int startCharno = - 1 ; if ( isMarker ) { stream . update ( ) ; startLineno = stream . getLineno ( ) ; startCharno = stream . getCharno ( ) + 1 ; String line = getRemainingJSDocLine ( ) ; if ( option != WhitespaceOption . PRESERVE ) { line = line . trim ( ) ; } builder . append ( line ) ; state = State . SEARCHING_ANNOTATION ; token = next ( ) ; } boolean ignoreStar = false ; int lineStartChar = - 1 ; do { switch ( token ) { case STAR : if ( ignoreStar ) { lineStartChar = stream . getCharno ( ) + 1 ; ignoreStar = false ; } else { padLine ( builder , lineStartChar , option ) ; lineStartChar = - 1 ; builder . append ( '*' ) ; } token = next ( ) ; while ( token == JsDocToken . STAR ) { if ( lineStartChar != - 1 ) { padLine ( builder , lineStartChar , option ) ; lineStartChar = - 1 ; } builder . append ( '*' ) ; token = next ( ) ; } continue ; case EOL : if ( option != WhitespaceOption . SINGLE_LINE ) { builder . append ( '\n' ) ; } ignoreStar = true ; lineStartChar = 0 ; token = next ( ) ; continue ; default : ignoreStar = false ; state = State . SEARCHING_ANNOTATION ; boolean isEOC = token == JsDocToken . EOC ; if ( ! isEOC ) { padLine ( builder , lineStartChar , option ) ; lineStartChar = - 1 ; } if ( token == JsDocToken . EOC || token == JsDocToken . EOF || ( token == JsDocToken . ANNOTATION && ! includeAnnotations ) ) { String multilineText = builder . toString ( ) ; if ( option != WhitespaceOption . PRESERVE ) { multilineText = multilineText . trim ( ) ; } if ( isMarker && ! multilineText . isEmpty ( ) ) { int endLineno = stream . getLineno ( ) ; int endCharno = stream . getCharno ( ) ; jsdocBuilder . markText ( multilineText , startLineno , startCharno , endLineno , endCharno ) ; } return new ExtractionInfo ( multilineText , token ) ; } builder . append ( toString ( token ) ) ; String line = getRemainingJSDocLine ( ) ; if ( option != WhitespaceOption . PRESERVE ) { line = trimEnd ( line ) ; } builder . append ( line ) ; token = next ( ) ; } } while ( true ) ; }
Extracts text from the stream until the end of the comment end of the file or an annotation token is encountered . If the text is being extracted for a JSDoc marker the first line in the stream will always be included in the extract text .
34,503
private Node parseParametersType ( JsDocToken token ) { Node paramsType = newNode ( Token . PARAM_LIST ) ; boolean isVarArgs = false ; Node paramType = null ; if ( token != JsDocToken . RIGHT_PAREN ) { do { if ( paramType != null ) { next ( ) ; skipEOLs ( ) ; token = next ( ) ; } if ( token == JsDocToken . ELLIPSIS ) { skipEOLs ( ) ; if ( match ( JsDocToken . RIGHT_PAREN ) ) { paramType = newNode ( Token . ELLIPSIS ) ; } else { skipEOLs ( ) ; paramType = wrapNode ( Token . ELLIPSIS , parseTypeExpression ( next ( ) ) ) ; skipEOLs ( ) ; } isVarArgs = true ; } else { paramType = parseTypeExpression ( token ) ; if ( match ( JsDocToken . EQUALS ) ) { skipEOLs ( ) ; next ( ) ; paramType = wrapNode ( Token . EQUALS , paramType ) ; } } if ( paramType == null ) { return null ; } paramsType . addChildToBack ( paramType ) ; if ( isVarArgs ) { break ; } } while ( match ( JsDocToken . COMMA ) ) ; } if ( isVarArgs && match ( JsDocToken . COMMA ) ) { return reportTypeSyntaxWarning ( "msg.jsdoc.function.varargs" ) ; } return paramsType ; }
order - checking in two places we just do all of it in type resolution .
34,504
private Node parseUnionTypeWithAlternate ( JsDocToken token , Node alternate ) { Node union = newNode ( Token . PIPE ) ; if ( alternate != null ) { union . addChildToBack ( alternate ) ; } Node expr = null ; do { if ( expr != null ) { skipEOLs ( ) ; token = next ( ) ; checkState ( token == JsDocToken . PIPE ) ; skipEOLs ( ) ; token = next ( ) ; } expr = parseTypeExpression ( token ) ; if ( expr == null ) { return null ; } union . addChildToBack ( expr ) ; } while ( match ( JsDocToken . PIPE ) ) ; if ( alternate == null ) { skipEOLs ( ) ; if ( ! match ( JsDocToken . RIGHT_PAREN ) ) { return reportTypeSyntaxWarning ( "msg.jsdoc.missing.rp" ) ; } next ( ) ; } if ( union . hasOneChild ( ) ) { Node firstChild = union . getFirstChild ( ) ; union . removeChild ( firstChild ) ; return firstChild ; } return union ; }
Create a new union type with an alternate that has already been parsed . The alternate may be null .
34,505
private boolean match ( JsDocToken token1 , JsDocToken token2 ) { unreadToken = next ( ) ; return unreadToken == token1 || unreadToken == token2 ; }
Tests that the next symbol of the token stream matches one of the specified tokens .
34,506
private boolean lookAheadFor ( char expect ) { boolean matched = false ; int c ; while ( true ) { c = stream . getChar ( ) ; if ( c == ' ' ) { continue ; } else if ( c == expect ) { matched = true ; break ; } else { break ; } } stream . ungetChar ( c ) ; return matched ; }
Look ahead by advancing the character stream . Does not modify the token stream .
34,507
private ImmutableList < Node > getCallParams ( Node n ) { Preconditions . checkArgument ( n . isCall ( ) , "Expected a call node, found %s" , n ) ; ImmutableList . Builder < Node > builder = new ImmutableList . Builder < > ( ) ; for ( int i = 0 ; i < getCallParamCount ( n ) ; i ++ ) { builder . add ( getCallArgument ( n , i ) ) ; } return builder . build ( ) ; }
Copying is unnecessarily inefficient .
34,508
private void replaceStringsWithAliases ( ) { for ( Entry < String , StringInfo > entry : stringInfoMap . entrySet ( ) ) { String literal = entry . getKey ( ) ; StringInfo info = entry . getValue ( ) ; if ( shouldReplaceWithAlias ( literal , info ) ) { for ( StringOccurrence occurrence : info . occurrences ) { replaceStringWithAliasName ( occurrence , info . getVariableName ( literal ) , info ) ; } } } }
Replace strings with references to alias variables .
34,509
private void addAliasDeclarationNodes ( ) { for ( Entry < String , StringInfo > entry : stringInfoMap . entrySet ( ) ) { StringInfo info = entry . getValue ( ) ; if ( ! info . isAliased ) { continue ; } String alias = info . getVariableName ( entry . getKey ( ) ) ; Node var = IR . var ( IR . name ( alias ) , IR . string ( entry . getKey ( ) ) ) ; var . useSourceInfoFromForTree ( info . parentForNewVarDecl ) ; if ( info . siblingToInsertVarDeclBefore == null ) { info . parentForNewVarDecl . addChildToFront ( var ) ; } else { info . parentForNewVarDecl . addChildBefore ( var , info . siblingToInsertVarDeclBefore ) ; } compiler . reportChangeToEnclosingScope ( var ) ; } }
Creates a var declaration for each aliased string . Var declarations are inserted as close to the first use of the string as possible .
34,510
private static boolean shouldReplaceWithAlias ( String str , StringInfo info ) { int sizeOfLiteral = 2 + str . length ( ) ; int sizeOfStrings = info . numOccurrences * sizeOfLiteral ; int sizeOfVariable = 3 ; int sizeOfAliases = 6 + sizeOfVariable + sizeOfLiteral + info . numOccurrences * sizeOfVariable ; return sizeOfAliases < sizeOfStrings ; }
Dictates the policy for replacing a string with an alias .
34,511
private void replaceStringWithAliasName ( StringOccurrence occurrence , String name , StringInfo info ) { Node nameNode = IR . name ( name ) ; occurrence . parent . replaceChild ( occurrence . node , nameNode ) ; info . isAliased = true ; compiler . reportChangeToEnclosingScope ( nameNode ) ; }
Replaces a string literal with a reference to the string s alias variable .
34,512
private void outputStringUsage ( ) { StringBuilder sb = new StringBuilder ( "Strings used more than once:\n" ) ; for ( Entry < String , StringInfo > stringInfoEntry : stringInfoMap . entrySet ( ) ) { StringInfo info = stringInfoEntry . getValue ( ) ; if ( info . numOccurrences > 1 ) { sb . append ( info . numOccurrences ) ; sb . append ( ": " ) ; sb . append ( stringInfoEntry . getKey ( ) ) ; sb . append ( '\n' ) ; } } logger . fine ( sb . toString ( ) ) ; }
Outputs a log of all strings used more than once in the code .
34,513
private void processDefineCall ( NodeTraversal t , Node n , Node parent ) { Node left = n . getFirstChild ( ) ; Node args = left . getNext ( ) ; if ( verifyDefine ( t , parent , left , args ) ) { Node nameNode = args ; maybeAddNameToSymbolTable ( left ) ; maybeAddStringToSymbolTable ( nameNode ) ; this . defineCalls . add ( n ) ; } }
Handles a goog . define call .
34,514
private void processBaseClassCall ( NodeTraversal t , Node n ) { t . report ( n , USE_OF_GOOG_BASE ) ; if ( baseUsedInClass ( n ) ) { reportBadGoogBaseUse ( n , "goog.base in ES6 class is not allowed. Use super instead." ) ; return ; } Node callee = n . getFirstChild ( ) ; Node thisArg = callee . getNext ( ) ; if ( thisArg == null || ! thisArg . isThis ( ) ) { reportBadGoogBaseUse ( n , "First argument must be 'this'." ) ; return ; } Node enclosingFnNameNode = getEnclosingDeclNameNode ( n ) ; if ( enclosingFnNameNode == null ) { reportBadGoogBaseUse ( n , "Could not find enclosing method." ) ; return ; } String enclosingQname = enclosingFnNameNode . getQualifiedName ( ) ; if ( ! enclosingQname . contains ( ".prototype." ) ) { Node enclosingParent = enclosingFnNameNode . getParent ( ) ; Node maybeInheritsExpr = ( enclosingParent . isAssign ( ) ? enclosingParent . getParent ( ) : enclosingParent ) . getNext ( ) ; Node baseClassNode = null ; if ( maybeInheritsExpr != null && maybeInheritsExpr . isExprResult ( ) && maybeInheritsExpr . getFirstChild ( ) . isCall ( ) ) { Node callNode = maybeInheritsExpr . getFirstChild ( ) ; if ( callNode . getFirstChild ( ) . matchesQualifiedName ( "goog.inherits" ) && callNode . getLastChild ( ) . isQualifiedName ( ) ) { baseClassNode = callNode . getLastChild ( ) ; } } if ( baseClassNode == null ) { reportBadGoogBaseUse ( n , "Could not find goog.inherits for base class" ) ; return ; } Node newCallee = NodeUtil . newQName ( compiler , baseClassNode . getQualifiedName ( ) + ".call" , callee , "goog.base" ) ; n . replaceChild ( callee , newCallee ) ; compiler . reportChangeToEnclosingScope ( newCallee ) ; } else { Node methodNameNode = thisArg . getNext ( ) ; if ( methodNameNode == null || ! methodNameNode . isString ( ) ) { reportBadGoogBaseUse ( n , "Second argument must name a method." ) ; return ; } String methodName = methodNameNode . getString ( ) ; String ending = ".prototype." + methodName ; if ( enclosingQname == null || ! enclosingQname . endsWith ( ending ) ) { reportBadGoogBaseUse ( n , "Enclosing method does not match " + methodName ) ; return ; } Node className = enclosingFnNameNode . getFirstFirstChild ( ) ; n . replaceChild ( callee , NodeUtil . newQName ( compiler , className . getQualifiedName ( ) + ".superClass_." + methodName + ".call" , callee , "goog.base" ) ) ; n . removeChild ( methodNameNode ) ; compiler . reportChangeToEnclosingScope ( n ) ; } }
Processes the base class call .
34,515
private void processInheritsCall ( Node n ) { if ( n . getChildCount ( ) == 3 ) { Node subClass = n . getSecondChild ( ) ; Node superClass = subClass . getNext ( ) ; if ( subClass . isUnscopedQualifiedName ( ) && superClass . isUnscopedQualifiedName ( ) ) { knownClosureSubclasses . add ( subClass . getQualifiedName ( ) ) ; } } }
Processes the goog . inherits call .
34,516
private static Node getEnclosingDeclNameNode ( Node n ) { Node fn = NodeUtil . getEnclosingFunction ( n ) ; return fn == null ? null : NodeUtil . getNameNode ( fn ) ; }
Returns the qualified name node of the function whose scope we re in or null if it cannot be found .
34,517
private boolean baseUsedInClass ( Node n ) { for ( Node curr = n ; curr != null ; curr = curr . getParent ( ) ) { if ( curr . isClassMembers ( ) ) { return true ; } } return false ; }
Verify if goog . base call is used in a class
34,518
private boolean verifyProvide ( Node methodName , Node arg ) { if ( ! verifyLastArgumentIsString ( methodName , arg ) ) { return false ; } if ( ! NodeUtil . isValidQualifiedName ( compiler . getOptions ( ) . getLanguageIn ( ) . toFeatureSet ( ) , arg . getString ( ) ) ) { compiler . report ( JSError . make ( arg , INVALID_PROVIDE_ERROR , arg . getString ( ) , compiler . getOptions ( ) . getLanguageIn ( ) . toString ( ) ) ) ; return false ; } return true ; }
Verifies that a provide method call has exactly one argument and that it s a string literal and that the contents of the string are valid JS tokens . Reports a compile error if it doesn t .
34,519
private boolean verifyDefine ( NodeTraversal t , Node parent , Node methodName , Node args ) { if ( ! compiler . getOptions ( ) . shouldPreserveGoogModule ( ) && ! t . inGlobalHoistScope ( ) ) { compiler . report ( JSError . make ( methodName . getParent ( ) , INVALID_CLOSURE_CALL_SCOPE_ERROR ) ) ; return false ; } if ( parent . isAssign ( ) && parent . getParent ( ) . isExprResult ( ) ) { parent = parent . getParent ( ) ; } else if ( parent . isName ( ) && NodeUtil . isNameDeclaration ( parent . getParent ( ) ) ) { parent = parent . getParent ( ) ; } else if ( ! parent . isExprResult ( ) ) { compiler . report ( JSError . make ( methodName . getParent ( ) , INVALID_CLOSURE_CALL_SCOPE_ERROR ) ) ; return false ; } Node arg = args ; if ( ! verifyNotNull ( methodName , arg ) || ! verifyOfType ( methodName , arg , Token . STRING ) ) { return false ; } arg = arg . getNext ( ) ; if ( ! args . isFromExterns ( ) && ( ! verifyNotNull ( methodName , arg ) || ! verifyIsLast ( methodName , arg ) ) ) { return false ; } String name = args . getString ( ) ; if ( ! NodeUtil . isValidQualifiedName ( compiler . getOptions ( ) . getLanguageIn ( ) . toFeatureSet ( ) , name ) ) { compiler . report ( JSError . make ( args , INVALID_DEFINE_NAME_ERROR , name ) ) ; return false ; } JSDocInfo info = ( parent . isExprResult ( ) ? parent . getFirstChild ( ) : parent ) . getJSDocInfo ( ) ; if ( info == null || ! info . isDefine ( ) ) { compiler . report ( JSError . make ( parent , MISSING_DEFINE_ANNOTATION ) ) ; return false ; } return true ; }
Verifies that a goog . define method call has exactly two arguments with the first a string literal whose contents is a valid JS qualified name . Reports a compile error if it doesn t .
34,520
private boolean verifyLastArgumentIsString ( Node methodName , Node arg ) { return verifyNotNull ( methodName , arg ) && verifyOfType ( methodName , arg , Token . STRING ) && verifyIsLast ( methodName , arg ) ; }
Verifies that a method call has exactly one argument and that it s a string literal . Reports a compile error if it doesn t .
34,521
private boolean verifySetCssNameMapping ( Node methodName , Node firstArg ) { DiagnosticType diagnostic = null ; if ( firstArg == null ) { diagnostic = NULL_ARGUMENT_ERROR ; } else if ( ! firstArg . isObjectLit ( ) ) { diagnostic = EXPECTED_OBJECTLIT_ERROR ; } else if ( firstArg . getNext ( ) != null ) { Node secondArg = firstArg . getNext ( ) ; if ( ! secondArg . isString ( ) ) { diagnostic = EXPECTED_STRING_ERROR ; } else if ( secondArg . getNext ( ) != null ) { diagnostic = TOO_MANY_ARGUMENTS_ERROR ; } } if ( diagnostic != null ) { compiler . report ( JSError . make ( methodName , diagnostic , methodName . getQualifiedName ( ) ) ) ; return false ; } return true ; }
Verifies that setCssNameMapping is called with the correct methods .
34,522
public static JSTypeExpression makeOptionalArg ( JSTypeExpression expr ) { if ( expr . isOptionalArg ( ) || expr . isVarArgs ( ) ) { return expr ; } else { return new JSTypeExpression ( new Node ( Token . EQUALS , expr . root ) , expr . sourceName ) ; } }
Make the given type expression into an optional type expression if possible .
34,523
public static TypeDeclarationNode namedType ( Iterable < String > segments ) { Iterator < String > segmentsIt = segments . iterator ( ) ; Node node = IR . name ( segmentsIt . next ( ) ) ; while ( segmentsIt . hasNext ( ) ) { node = IR . getprop ( node , IR . string ( segmentsIt . next ( ) ) ) ; } return new TypeDeclarationNode ( Token . NAMED_TYPE , node ) ; }
Produces a tree structure similar to the Rhino AST of a qualified name expression under a top - level NAMED_TYPE node .
34,524
void maybeAddFunction ( Function fn , JSModule module ) { String name = fn . getName ( ) ; FunctionState functionState = getOrCreateFunctionState ( name ) ; if ( functionState . hasExistingFunctionDefinition ( ) ) { functionState . disallowInlining ( ) ; return ; } Node fnNode = fn . getFunctionNode ( ) ; if ( hasNoInlineAnnotation ( fnNode ) ) { functionState . disallowInlining ( ) ; return ; } if ( enforceMaxSizeAfterInlining && ! isAlwaysInlinable ( fnNode ) && maxSizeAfterInlining <= NodeUtil . countAstSizeUpToLimit ( fnNode , maxSizeAfterInlining ) ) { functionState . disallowInlining ( ) ; return ; } if ( functionState . canInline ( ) ) { functionState . setFn ( fn ) ; if ( FunctionInjector . isDirectCallNodeReplacementPossible ( fn . getFunctionNode ( ) ) ) { functionState . inlineDirectly ( true ) ; } if ( hasNonInlinableParam ( NodeUtil . getFunctionParameters ( fnNode ) ) ) { functionState . disallowInlining ( ) ; } if ( ! isCandidateFunction ( fn ) ) { functionState . disallowInlining ( ) ; } if ( functionState . canInline ( ) ) { functionState . setModule ( module ) ; Set < String > namesToAlias = FunctionArgumentInjector . findModifiedParameters ( fnNode ) ; if ( ! namesToAlias . isEmpty ( ) ) { functionState . inlineDirectly ( false ) ; functionState . setNamesToAlias ( namesToAlias ) ; } Node block = NodeUtil . getFunctionBody ( fnNode ) ; if ( NodeUtil . referencesThis ( block ) ) { functionState . setReferencesThis ( true ) ; } if ( NodeUtil . containsFunction ( block ) ) { functionState . setHasInnerFunctions ( true ) ; if ( ! assumeMinimumCapture && hasLocalNames ( fnNode ) ) { functionState . disallowInlining ( ) ; } } } if ( fnNode . getGrandparent ( ) . isVar ( ) ) { Node block = functionState . getFn ( ) . getDeclaringBlock ( ) ; if ( block . isBlock ( ) && ! block . getParent ( ) . isFunction ( ) && ( NodeUtil . containsType ( block , Token . LET ) || NodeUtil . containsType ( block , Token . CONST ) ) ) { functionState . disallowInlining ( ) ; } } if ( fnNode . isGeneratorFunction ( ) ) { functionState . disallowInlining ( ) ; } if ( fnNode . isAsyncFunction ( ) ) { functionState . disallowInlining ( ) ; } } }
Updates the FunctionState object for the given function . Checks if the given function matches the criteria for an inlinable function .
34,525
private boolean isCandidateFunction ( Function fn ) { String fnName = fn . getName ( ) ; if ( compiler . getCodingConvention ( ) . isExported ( fnName ) ) { return false ; } if ( compiler . getCodingConvention ( ) . isPropertyRenameFunction ( fnName ) ) { return false ; } Node fnNode = fn . getFunctionNode ( ) ; return injector . doesFunctionMeetMinimumRequirements ( fnName , fnNode ) ; }
Checks if the given function matches the criteria for an inlinable function .
34,526
private void trimCandidatesNotMeetingMinimumRequirements ( ) { Iterator < Entry < String , FunctionState > > i ; for ( i = fns . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { FunctionState functionState = i . next ( ) . getValue ( ) ; if ( ! functionState . hasExistingFunctionDefinition ( ) || ! functionState . canInline ( ) ) { i . remove ( ) ; } } }
Remove entries that aren t a valid inline candidates from the list of encountered names .
34,527
private void trimCandidatesUsingOnCost ( ) { Iterator < Entry < String , FunctionState > > i ; for ( i = fns . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { FunctionState functionState = i . next ( ) . getValue ( ) ; if ( functionState . hasReferences ( ) ) { boolean lowersCost = minimizeCost ( functionState ) ; if ( ! lowersCost ) { i . remove ( ) ; } } else if ( ! functionState . canRemove ( ) ) { i . remove ( ) ; } } }
Remove entries from the list of candidates that can t be inlined .
34,528
private boolean minimizeCost ( FunctionState functionState ) { if ( ! inliningLowersCost ( functionState ) ) { if ( functionState . hasBlockInliningReferences ( ) ) { functionState . setRemove ( false ) ; functionState . removeBlockInliningReferences ( ) ; if ( ! functionState . hasReferences ( ) || ! inliningLowersCost ( functionState ) ) { return false ; } } else { return false ; } } return true ; }
Determines if the function is worth inlining and potentially trims references that increase the cost .
34,529
private Set < String > findCalledFunctions ( Node node ) { Set < String > changed = new HashSet < > ( ) ; findCalledFunctions ( NodeUtil . getFunctionBody ( node ) , changed ) ; return changed ; }
This functions that may be called directly .
34,530
private void decomposeExpressions ( ) { for ( FunctionState functionState : fns . values ( ) ) { if ( functionState . canInline ( ) ) { for ( Reference ref : functionState . getReferences ( ) ) { if ( ref . requiresDecomposition ) { injector . maybePrepareCall ( ref ) ; } } } } }
For any call - site that needs it prepare the call - site for inlining by rewriting the containing expression .
34,531
void removeInlinedFunctions ( ) { for ( Map . Entry < String , FunctionState > entry : fns . entrySet ( ) ) { String name = entry . getKey ( ) ; FunctionState functionState = entry . getValue ( ) ; if ( functionState . canRemove ( ) ) { Function fn = functionState . getFn ( ) ; checkState ( functionState . canInline ( ) ) ; checkState ( fn != null ) ; verifyAllReferencesInlined ( name , functionState ) ; fn . remove ( ) ; NodeUtil . markFunctionsDeleted ( fn . getFunctionNode ( ) , compiler ) ; } } }
Removed inlined functions that no longer have any references .
34,532
void verifyAllReferencesInlined ( String name , FunctionState functionState ) { for ( Reference ref : functionState . getReferences ( ) ) { if ( ! ref . inlined ) { Node parent = ref . callNode . getParent ( ) ; throw new IllegalStateException ( "Call site missed (" + name + ").\n call: " + ref . callNode . toStringTree ( ) + "\n parent: " + ( ( parent == null ) ? "null" : parent . toStringTree ( ) ) ) ; } } }
Check to verify that expression rewriting didn t make a call inaccessible .
34,533
public static DiagnosticType error ( String name , String descriptionFormat ) { return make ( name , CheckLevel . ERROR , descriptionFormat ) ; }
Create a DiagnosticType at level CheckLevel . ERROR
34,534
public static DiagnosticType warning ( String name , String descriptionFormat ) { return make ( name , CheckLevel . WARNING , descriptionFormat ) ; }
Create a DiagnosticType at level CheckLevel . WARNING
34,535
public static DiagnosticType disabled ( String name , String descriptionFormat ) { return make ( name , CheckLevel . OFF , descriptionFormat ) ; }
Create a DiagnosticType at level CheckLevel . OFF
34,536
public static DiagnosticType make ( String name , CheckLevel level , String descriptionFormat ) { return new DiagnosticType ( name , level , new MessageFormat ( descriptionFormat ) ) ; }
Create a DiagnosticType at a given CheckLevel .
34,537
public void process ( Node externsRoot , Node jsRoot ) { Node externsAndJs = jsRoot . getParent ( ) ; checkState ( externsAndJs != null ) ; checkState ( externsRoot == null || externsAndJs . hasChild ( externsRoot ) ) ; inferAllScopes ( externsAndJs ) ; }
Main entry point for type inference when running over the whole tree .
34,538
void inferAllScopes ( Node node ) { ( new NodeTraversal ( compiler , new FirstScopeBuildingCallback ( ) , scopeCreator ) ) . traverseWithScope ( node , topScope ) ; scopeCreator . resolveTypes ( ) ; ( new NodeTraversal ( compiler , new SecondScopeBuildingCallback ( ) , scopeCreator ) ) . traverseWithScope ( node , topScope ) ; compiler . getTypeRegistry ( ) . resolveTypes ( ) ; }
Entry point for type inference when running over part of the tree .
34,539
@ SuppressWarnings ( "fallthrough" ) public Node optimizeSubtree ( Node node ) { switch ( node . getToken ( ) ) { case THROW : case RETURN : { Node result = tryRemoveRedundantExit ( node ) ; if ( result != node ) { return result ; } return tryReplaceExitWithBreak ( node ) ; } case NOT : tryMinimizeCondition ( node . getFirstChild ( ) ) ; return tryMinimizeNot ( node ) ; case IF : performConditionSubstitutions ( node . getFirstChild ( ) ) ; return tryMinimizeIf ( node ) ; case EXPR_RESULT : performConditionSubstitutions ( node . getFirstChild ( ) ) ; return tryMinimizeExprResult ( node ) ; case HOOK : performConditionSubstitutions ( node . getFirstChild ( ) ) ; return tryMinimizeHook ( node ) ; case WHILE : case DO : tryMinimizeCondition ( NodeUtil . getConditionExpression ( node ) ) ; return node ; case FOR : tryJoinForCondition ( node ) ; tryMinimizeCondition ( NodeUtil . getConditionExpression ( node ) ) ; return node ; case BLOCK : return tryReplaceIf ( node ) ; default : return node ; } }
Tries to apply our various peephole minimizations on the passed in node .
34,540
private Node tryMinimizeExprResult ( Node n ) { Node originalExpr = n . getFirstChild ( ) ; MinimizedCondition minCond = MinimizedCondition . fromConditionNode ( originalExpr ) ; MeasuredNode mNode = minCond . getMinimized ( MinimizationStyle . ALLOW_LEADING_NOT ) ; if ( mNode . isNot ( ) ) { replaceNode ( originalExpr , mNode . withoutNot ( ) ) ; } else { replaceNode ( originalExpr , mNode ) ; } return n ; }
Try to remove leading NOTs from EXPR_RESULTS .
34,541
private Node tryMinimizeHook ( Node n ) { Node originalCond = n . getFirstChild ( ) ; MinimizedCondition minCond = MinimizedCondition . fromConditionNode ( originalCond ) ; MeasuredNode mNode = minCond . getMinimized ( MinimizationStyle . ALLOW_LEADING_NOT ) ; if ( mNode . isNot ( ) ) { Node thenBranch = n . getSecondChild ( ) ; replaceNode ( originalCond , mNode . withoutNot ( ) ) ; n . removeChild ( thenBranch ) ; n . addChildToBack ( thenBranch ) ; reportChangeToEnclosingScope ( n ) ; } else { replaceNode ( originalCond , mNode ) ; } return n ; }
Try flipping HOOKs that have negated conditions .
34,542
private static boolean consumesDanglingElse ( Node n ) { while ( true ) { switch ( n . getToken ( ) ) { case IF : if ( n . getChildCount ( ) < 3 ) { return true ; } n = n . getLastChild ( ) ; continue ; case BLOCK : if ( ! n . hasOneChild ( ) ) { return false ; } n = n . getLastChild ( ) ; continue ; case WITH : case WHILE : case FOR : case FOR_IN : n = n . getLastChild ( ) ; continue ; default : return false ; } } }
Does a statement consume a dangling else ? A statement consumes a dangling else if an else token following the statement would be considered by the parser to be part of the statement .
34,543
private static boolean isPropertyAssignmentInExpression ( Node n ) { Predicate < Node > isPropertyAssignmentInExpressionPredicate = new Predicate < Node > ( ) { public boolean apply ( Node input ) { return ( input . isGetProp ( ) && input . getParent ( ) . isAssign ( ) ) ; } } ; return NodeUtil . has ( n , isPropertyAssignmentInExpressionPredicate , NodeUtil . MATCH_NOT_FUNCTION ) ; }
Does the expression contain a property assignment?
34,544
private Node tryMinimizeCondition ( Node n ) { n = performConditionSubstitutions ( n ) ; MinimizedCondition minCond = MinimizedCondition . fromConditionNode ( n ) ; return replaceNode ( n , minCond . getMinimized ( MinimizationStyle . PREFER_UNNEGATED ) ) ; }
Try to minimize condition expression as there are additional assumptions that can be made when it is known that the final result is a boolean .
34,545
private Node maybeReplaceChildWithNumber ( Node n , Node parent , int num ) { Node newNode = IR . number ( num ) ; if ( ! newNode . isEquivalentTo ( n ) ) { parent . replaceChild ( n , newNode ) ; reportChangeToEnclosingScope ( newNode ) ; markFunctionsDeleted ( n ) ; return newNode ; } return n ; }
Replaces a node with a number node if the new number node is not equivalent to the current node .
34,546
public boolean enables ( DiagnosticGroup group ) { for ( WarningsGuard guard : guards ) { if ( guard . enables ( group ) ) { return true ; } else if ( guard . disables ( group ) ) { return false ; } } return false ; }
Determines whether this guard will elevate the status of any disabled diagnostic type in the group to a warning or an error .
34,547
ComposeWarningsGuard makeEmergencyFailSafeGuard ( ) { ComposeWarningsGuard safeGuard = new ComposeWarningsGuard ( ) ; safeGuard . demoteErrors = true ; for ( WarningsGuard guard : guards . descendingSet ( ) ) { safeGuard . addGuard ( guard ) ; } return safeGuard ; }
Make a warnings guard that s the same as this one but demotes all errors to warnings .
34,548
private boolean isSupportedCallType ( Node callNode ) { if ( ! callNode . getFirstChild ( ) . isName ( ) ) { if ( NodeUtil . isFunctionObjectCall ( callNode ) ) { if ( ! assumeStrictThis ) { Node thisValue = callNode . getSecondChild ( ) ; if ( thisValue == null || ! thisValue . isThis ( ) ) { return false ; } } } else if ( NodeUtil . isFunctionObjectApply ( callNode ) ) { return false ; } } return true ; }
Only . call calls and direct calls to functions are supported .
34,549
Node inline ( Reference ref , String fnName , Node fnNode ) { checkState ( compiler . getLifeCycleStage ( ) . isNormalized ( ) ) ; return internalInline ( ref , fnName , fnNode ) ; }
Inline a function into the call site .
34,550
private Node inlineReturnValue ( Reference ref , Node fnNode ) { Node callNode = ref . callNode ; Node block = fnNode . getLastChild ( ) ; Node callParentNode = callNode . getParent ( ) ; Map < String , Node > argMap = FunctionArgumentInjector . getFunctionCallParameterMap ( fnNode , callNode , this . safeNameIdSupplier ) ; Node newExpression ; if ( ! block . hasChildren ( ) ) { Node srcLocation = block ; newExpression = NodeUtil . newUndefinedNode ( srcLocation ) ; } else { Node returnNode = block . getFirstChild ( ) ; checkArgument ( returnNode . isReturn ( ) , returnNode ) ; Node safeReturnNode = returnNode . cloneTree ( ) ; Node inlineResult = FunctionArgumentInjector . inject ( null , safeReturnNode , null , argMap ) ; checkArgument ( safeReturnNode == inlineResult ) ; newExpression = safeReturnNode . removeFirstChild ( ) ; NodeUtil . markNewScopesChanged ( newExpression , compiler ) ; } JSType typeBeforeCast = callNode . getJSTypeBeforeCast ( ) ; if ( typeBeforeCast != null ) { newExpression . setJSTypeBeforeCast ( typeBeforeCast ) ; newExpression . setJSType ( callNode . getJSType ( ) ) ; } callParentNode . replaceChild ( callNode , newExpression ) ; NodeUtil . markFunctionsDeleted ( callNode , compiler ) ; return newExpression ; }
Inline a function that fulfills the requirements of canInlineReferenceDirectly into the call site replacing only the CALL node .
34,551
private CallSiteType classifyCallSite ( Reference ref ) { Node callNode = ref . callNode ; Node parent = callNode . getParent ( ) ; Node grandParent = parent . getParent ( ) ; if ( NodeUtil . isExprCall ( parent ) ) { return CallSiteType . SIMPLE_CALL ; } else if ( NodeUtil . isExprAssign ( grandParent ) && ! NodeUtil . isNameDeclOrSimpleAssignLhs ( callNode , parent ) && parent . getFirstChild ( ) . isName ( ) && ! NodeUtil . isConstantName ( parent . getFirstChild ( ) ) ) { return CallSiteType . SIMPLE_ASSIGNMENT ; } else if ( parent . isName ( ) && ! NodeUtil . isConstantName ( parent ) && grandParent . isVar ( ) && grandParent . hasOneChild ( ) ) { return CallSiteType . VAR_DECL_SIMPLE_ASSIGNMENT ; } else { ExpressionDecomposer decomposer = getDecomposer ( ref . scope ) ; switch ( decomposer . canExposeExpression ( callNode ) ) { case MOVABLE : return CallSiteType . EXPRESSION ; case DECOMPOSABLE : return CallSiteType . DECOMPOSABLE_EXPRESSION ; case UNDECOMPOSABLE : break ; } } return CallSiteType . UNSUPPORTED ; }
Determine which if any of the supported types the call site is .
34,552
void maybePrepareCall ( Reference ref ) { CallSiteType callSiteType = classifyCallSite ( ref ) ; callSiteType . prepare ( this , ref ) ; }
If required rewrite the statement containing the call expression .
34,553
private Node inlineFunction ( Reference ref , Node fnNode , String fnName ) { Node callNode = ref . callNode ; Node parent = callNode . getParent ( ) ; Node grandParent = parent . getParent ( ) ; CallSiteType callSiteType = classifyCallSite ( ref ) ; checkArgument ( callSiteType != CallSiteType . UNSUPPORTED ) ; String resultName = null ; boolean needsDefaultReturnResult = true ; switch ( callSiteType ) { case SIMPLE_ASSIGNMENT : resultName = parent . getFirstChild ( ) . getString ( ) ; removeConstantVarAnnotation ( ref . scope , resultName ) ; break ; case VAR_DECL_SIMPLE_ASSIGNMENT : resultName = parent . getString ( ) ; removeConstantVarAnnotation ( ref . scope , resultName ) ; break ; case SIMPLE_CALL : resultName = null ; needsDefaultReturnResult = false ; break ; case EXPRESSION : throw new IllegalStateException ( "Movable expressions must be moved before inlining." ) ; case DECOMPOSABLE_EXPRESSION : throw new IllegalStateException ( "Decomposable expressions must be decomposed before inlining." ) ; default : throw new IllegalStateException ( "Unexpected call site type." ) ; } FunctionToBlockMutator mutator = new FunctionToBlockMutator ( compiler , this . safeNameIdSupplier ) ; boolean isCallInLoop = NodeUtil . isWithinLoop ( callNode ) ; Node newBlock = mutator . mutate ( fnName , fnNode , callNode , resultName , needsDefaultReturnResult , isCallInLoop ) ; NodeUtil . markNewScopesChanged ( newBlock , compiler ) ; Node greatGrandParent = grandParent . getParent ( ) ; switch ( callSiteType ) { case VAR_DECL_SIMPLE_ASSIGNMENT : Node firstChild = parent . removeFirstChild ( ) ; NodeUtil . markFunctionsDeleted ( firstChild , compiler ) ; Preconditions . checkState ( parent . getFirstChild ( ) == null ) ; greatGrandParent . addChildAfter ( newBlock , grandParent ) ; break ; case SIMPLE_ASSIGNMENT : Preconditions . checkState ( grandParent . isExprResult ( ) ) ; greatGrandParent . replaceChild ( grandParent , newBlock ) ; NodeUtil . markFunctionsDeleted ( grandParent , compiler ) ; break ; case SIMPLE_CALL : Preconditions . checkState ( parent . isExprResult ( ) ) ; grandParent . replaceChild ( parent , newBlock ) ; NodeUtil . markFunctionsDeleted ( parent , compiler ) ; break ; default : throw new IllegalStateException ( "Unexpected call site type." ) ; } return newBlock ; }
Inline a function which fulfills the requirements of canInlineReferenceAsStatementBlock into the call site replacing the parent expression .
34,554
static boolean isDirectCallNodeReplacementPossible ( Node fnNode ) { Node block = NodeUtil . getFunctionBody ( fnNode ) ; if ( ! block . hasChildren ( ) ) { return true ; } else if ( block . hasOneChild ( ) ) { if ( block . getFirstChild ( ) . isReturn ( ) && block . getFirstFirstChild ( ) != null ) { return true ; } } return false ; }
Checks if the given function matches the criteria for an inlinable function and if so adds it to our set of inlinable functions .
34,555
private boolean callMeetsBlockInliningRequirements ( Reference ref , final Node fnNode , ImmutableSet < String > namesToAlias ) { boolean fnContainsVars = NodeUtil . has ( NodeUtil . getFunctionBody ( fnNode ) , new NodeUtil . MatchDeclaration ( ) , new NodeUtil . MatchShallowStatement ( ) ) ; boolean forbidTemps = false ; if ( ! ref . scope . getClosestHoistScope ( ) . isGlobal ( ) ) { Node fnCallerBody = ref . scope . getClosestHoistScope ( ) . getRootNode ( ) ; Predicate < Node > match = new Predicate < Node > ( ) { public boolean apply ( Node n ) { if ( n . isName ( ) ) { return n . getString ( ) . equals ( "eval" ) ; } if ( ! assumeMinimumCapture && n . isFunction ( ) ) { return n != fnNode ; } return false ; } } ; forbidTemps = NodeUtil . has ( fnCallerBody , match , NodeUtil . MATCH_NOT_FUNCTION ) ; } if ( fnContainsVars && forbidTemps ) { return false ; } if ( forbidTemps ) { ImmutableMap < String , Node > args = FunctionArgumentInjector . getFunctionCallParameterMap ( fnNode , ref . callNode , this . safeNameIdSupplier ) ; boolean hasArgs = ! args . isEmpty ( ) ; if ( hasArgs ) { Set < String > allNamesToAlias = new HashSet < > ( namesToAlias ) ; FunctionArgumentInjector . maybeAddTempsForCallArguments ( compiler , fnNode , args , allNamesToAlias , compiler . getCodingConvention ( ) ) ; if ( ! allNamesToAlias . isEmpty ( ) ) { return false ; } } } return true ; }
Determines whether a function can be inlined at a particular call site . - Don t inline if the calling function contains an inner function and inlining would introduce new globals .
34,556
boolean inliningLowersCost ( JSModule fnModule , Node fnNode , Collection < ? extends Reference > refs , Set < String > namesToAlias , boolean isRemovable , boolean referencesThis ) { int referenceCount = refs . size ( ) ; if ( referenceCount == 0 ) { return true ; } int referencesUsingBlockInlining = 0 ; boolean checkModules = isRemovable && fnModule != null ; JSModuleGraph moduleGraph = compiler . getModuleGraph ( ) ; for ( Reference ref : refs ) { if ( ref . mode == InliningMode . BLOCK ) { referencesUsingBlockInlining ++ ; } if ( checkModules && ref . module != null ) { if ( ref . module != fnModule && ! moduleGraph . dependsOn ( ref . module , fnModule ) ) { isRemovable = false ; checkModules = false ; } } } int referencesUsingDirectInlining = referenceCount - referencesUsingBlockInlining ; if ( referenceCount == 1 && isRemovable && referencesUsingDirectInlining == 1 ) { return true ; } int callCost = estimateCallCost ( fnNode , referencesThis ) ; int overallCallCost = callCost * referenceCount ; int costDeltaDirect = inlineCostDelta ( fnNode , namesToAlias , InliningMode . DIRECT ) ; int costDeltaBlock = inlineCostDelta ( fnNode , namesToAlias , InliningMode . BLOCK ) ; return doesLowerCost ( fnNode , overallCallCost , referencesUsingDirectInlining , costDeltaDirect , referencesUsingBlockInlining , costDeltaBlock , isRemovable ) ; }
Determine if inlining the function is likely to reduce the code size .
34,557
private static int search ( ArrayList < Entry > entries , int target , int start , int end ) { while ( true ) { int mid = ( ( end - start ) / 2 ) + start ; int compare = compareEntry ( entries , mid , target ) ; if ( compare == 0 ) { return mid ; } else if ( compare < 0 ) { start = mid + 1 ; if ( start > end ) { return end ; } } else { end = mid - 1 ; if ( end < start ) { return end ; } } } }
Perform a binary search on the array to find a section that covers the target column .
34,558
private static int compareEntry ( ArrayList < Entry > entries , int entry , int target ) { return entries . get ( entry ) . getGeneratedColumn ( ) - target ; }
Compare an array entry s column value to the target column value .
34,559
private OriginalMapping getPreviousMapping ( int lineNumber ) { do { if ( lineNumber == 0 ) { return null ; } lineNumber -- ; } while ( lines . get ( lineNumber ) == null ) ; ArrayList < Entry > entries = lines . get ( lineNumber ) ; return getOriginalMappingForEntry ( Iterables . getLast ( entries ) ) ; }
Returns the mapping entry that proceeds the supplied line or null if no such entry exists .
34,560
private OriginalMapping getOriginalMappingForEntry ( Entry entry ) { if ( entry . getSourceFileId ( ) == UNMAPPED ) { return null ; } else { Builder x = OriginalMapping . newBuilder ( ) . setOriginalFile ( sources [ entry . getSourceFileId ( ) ] ) . setLineNumber ( entry . getSourceLine ( ) + 1 ) . setColumnPosition ( entry . getSourceColumn ( ) + 1 ) ; if ( entry . getNameId ( ) != UNMAPPED ) { x . setIdentifier ( names [ entry . getNameId ( ) ] ) ; } return x . build ( ) ; } }
Creates an OriginalMapping object for the given entry object .
34,561
private void createReverseMapping ( ) { reverseSourceMapping = new HashMap < > ( ) ; for ( int targetLine = 0 ; targetLine < lines . size ( ) ; targetLine ++ ) { ArrayList < Entry > entries = lines . get ( targetLine ) ; if ( entries != null ) { for ( Entry entry : entries ) { if ( entry . getSourceFileId ( ) != UNMAPPED && entry . getSourceLine ( ) != UNMAPPED ) { String originalFile = sources [ entry . getSourceFileId ( ) ] ; if ( ! reverseSourceMapping . containsKey ( originalFile ) ) { reverseSourceMapping . put ( originalFile , new HashMap < Integer , Collection < OriginalMapping > > ( ) ) ; } Map < Integer , Collection < OriginalMapping > > lineToCollectionMap = reverseSourceMapping . get ( originalFile ) ; int sourceLine = entry . getSourceLine ( ) ; if ( ! lineToCollectionMap . containsKey ( sourceLine ) ) { lineToCollectionMap . put ( sourceLine , new ArrayList < OriginalMapping > ( 1 ) ) ; } Collection < OriginalMapping > mappings = lineToCollectionMap . get ( sourceLine ) ; Builder builder = OriginalMapping . newBuilder ( ) . setLineNumber ( targetLine ) . setColumnPosition ( entry . getGeneratedColumn ( ) ) ; mappings . add ( builder . build ( ) ) ; } } } } }
Reverse the source map ; the created mapping will allow us to quickly go from a source file and line number to a collection of target OriginalMappings .
34,562
private void visitScript ( NodeTraversal t , Node n ) { if ( ! n . hasOneChild ( ) || ! n . getFirstChild ( ) . isExprResult ( ) ) { compiler . report ( JSError . make ( n , JSON_UNEXPECTED_TOKEN ) ) ; return ; } Node jsonObject = n . getFirstFirstChild ( ) . detach ( ) ; n . removeFirstChild ( ) ; String moduleName = t . getInput ( ) . getPath ( ) . toModuleName ( ) ; n . addChildToFront ( IR . var ( IR . name ( moduleName ) . useSourceInfoFrom ( jsonObject ) , jsonObject ) . useSourceInfoFrom ( jsonObject ) ) ; n . addChildToFront ( IR . exprResult ( IR . call ( IR . getprop ( IR . name ( "goog" ) , IR . string ( "provide" ) ) , IR . string ( moduleName ) ) ) . useSourceInfoIfMissingFromForTree ( n ) ) ; String inputPath = t . getInput ( ) . getSourceFile ( ) . getOriginalPath ( ) ; if ( inputPath . endsWith ( "/package.json" ) && jsonObject . isObjectLit ( ) ) { List < String > possibleMainEntries = compiler . getOptions ( ) . getPackageJsonEntryNames ( ) ; for ( String entryName : possibleMainEntries ) { Node entry = NodeUtil . getFirstPropMatchingKey ( jsonObject , entryName ) ; if ( entry != null && ( entry . isString ( ) || entry . isObjectLit ( ) ) ) { String dirName = inputPath . substring ( 0 , inputPath . length ( ) - "package.json" . length ( ) ) ; if ( entry . isString ( ) ) { packageJsonMainEntries . put ( inputPath , dirName + entry . getString ( ) ) ; break ; } else if ( entry . isObjectLit ( ) ) { checkState ( entryName . equals ( "browser" ) , entryName ) ; processBrowserFieldAdvancedUsage ( dirName , entry ) ; } } } } t . reportCodeChange ( ) ; }
For script nodes of JSON objects add a module variable assignment so the result is exported .
34,563
void forceToEs6Module ( Node root ) { if ( Es6RewriteModules . isEs6ModuleRoot ( root ) ) { return ; } Node moduleNode = new Node ( Token . MODULE_BODY ) . srcref ( root ) ; moduleNode . addChildrenToBack ( root . removeChildren ( ) ) ; root . addChildToBack ( moduleNode ) ; compiler . reportChangeToChangeScope ( root ) ; }
Force rewriting of a script into an ES6 module such as for imported files that contain no import or export statements .
34,564
public String decode ( String encodedStr ) { String [ ] suppliedBits = encodedStr . split ( ARGUMENT_PLACE_HOLDER , - 1 ) ; String originalStr = originalToNewNameMap . get ( suppliedBits [ 0 ] ) ; if ( originalStr == null ) { return encodedStr ; } String [ ] originalBits = originalStr . split ( ARGUMENT_PLACE_HOLDER , - 1 ) ; StringBuilder sb = new StringBuilder ( originalBits [ 0 ] ) ; for ( int i = 1 ; i < Math . max ( originalBits . length , suppliedBits . length ) ; i ++ ) { sb . append ( i < suppliedBits . length ? suppliedBits [ i ] : "-" ) ; sb . append ( i < originalBits . length ? originalBits [ i ] : "-" ) ; } return sb . toString ( ) ; }
Decodes an encoded string from the JS Compiler ReplaceStrings pass .
34,565
@ SuppressWarnings ( "fallthrough" ) public Node optimizeSubtree ( Node node ) { switch ( node . getToken ( ) ) { case ASSIGN_SUB : return reduceSubstractionAssignment ( node ) ; case TRUE : case FALSE : return reduceTrueFalse ( node ) ; case NEW : node = tryFoldStandardConstructors ( node ) ; if ( ! node . isCall ( ) ) { return node ; } case CALL : Node result = tryFoldLiteralConstructor ( node ) ; if ( result == node ) { result = tryFoldSimpleFunctionCall ( node ) ; if ( result == node ) { result = tryFoldImmediateCallToBoundFunction ( node ) ; } } return result ; case RETURN : return tryReduceReturn ( node ) ; case COMMA : return trySplitComma ( node ) ; case NAME : return tryReplaceUndefined ( node ) ; case ARRAYLIT : return tryMinimizeArrayLiteral ( node ) ; case GETPROP : return tryMinimizeWindowRefs ( node ) ; case TEMPLATELIT : return tryTurnTemplateStringsToStrings ( node ) ; case MUL : case AND : case OR : case BITOR : case BITXOR : case BITAND : return tryRotateAssociativeOperator ( node ) ; default : return node ; } }
Tries apply our various peephole minimizations on the passed in node .
34,566
private Node tryReplaceUndefined ( Node n ) { if ( isASTNormalized ( ) && NodeUtil . isUndefined ( n ) && ! NodeUtil . isLValue ( n ) ) { Node replacement = NodeUtil . newUndefinedNode ( n ) ; n . replaceWith ( replacement ) ; reportChangeToEnclosingScope ( replacement ) ; return replacement ; } return n ; }
Use void 0 in place of undefined
34,567
private Node tryReduceReturn ( Node n ) { Node result = n . getFirstChild ( ) ; if ( result != null ) { switch ( result . getToken ( ) ) { case VOID : Node operand = result . getFirstChild ( ) ; if ( ! mayHaveSideEffects ( operand ) ) { n . removeFirstChild ( ) ; reportChangeToEnclosingScope ( n ) ; } break ; case NAME : String name = result . getString ( ) ; if ( name . equals ( "undefined" ) ) { n . removeFirstChild ( ) ; reportChangeToEnclosingScope ( n ) ; } break ; default : break ; } } return n ; }
Reduce return undefined or return void 0 to simply return .
34,568
private Node tryFoldLiteralConstructor ( Node n ) { checkArgument ( n . isCall ( ) || n . isNew ( ) ) ; Node constructorNameNode = n . getFirstChild ( ) ; Node newLiteralNode = null ; if ( isASTNormalized ( ) && constructorNameNode . isName ( ) ) { String className = constructorNameNode . getString ( ) ; if ( "RegExp" . equals ( className ) ) { return tryFoldRegularExpressionConstructor ( n ) ; } else { boolean constructorHasArgs = constructorNameNode . getNext ( ) != null ; if ( "Object" . equals ( className ) && ! constructorHasArgs ) { newLiteralNode = IR . objectlit ( ) ; } else if ( "Array" . equals ( className ) ) { 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 ( ) ; 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 .
34,569
private static String pickDelimiter ( String [ ] strings ) { boolean allLength1 = true ; for ( String s : strings ) { if ( s . length ( ) != 1 ) { allLength1 = false ; break ; } } if ( allLength1 ) { return "" ; } String [ ] delimiters = new String [ ] { " " , ";" , "," , "{" , "}" , null } ; int i = 0 ; NEXT_DELIMITER : for ( ; delimiters [ i ] != null ; i ++ ) { for ( String cur : strings ) { if ( cur . contains ( delimiters [ i ] ) ) { continue NEXT_DELIMITER ; } } break ; } return delimiters [ i ] ; }
Find a delimiter that does not occur in the given strings
34,570
static boolean containsUnicodeEscape ( String s ) { String esc = REGEXP_ESCAPER . regexpEscape ( s ) ; for ( int i = - 1 ; ( i = esc . indexOf ( "\\u" , i + 1 ) ) >= 0 ; ) { int nSlashes = 0 ; while ( i - nSlashes > 0 && '\\' == esc . charAt ( i - nSlashes - 1 ) ) { ++ nSlashes ; } if ( 0 == ( nSlashes & 1 ) ) { return true ; } } return false ; }
true if the JavaScript string would contain a Unicode escape when written out as the body of a regular expression literal .
34,571
static String getArrayElementStringValue ( Node n ) { return ( NodeUtil . isNullOrUndefined ( n ) || n . isEmpty ( ) ) ? "" : getStringValue ( n ) ; }
When converting arrays to string using Array . prototype . toString or Array . prototype . join the rules for conversion to String are different than converting each element individually . Specifically null and undefined are converted to an empty string .
34,572
static boolean isImmutableValue ( Node n ) { switch ( n . getToken ( ) ) { case STRING : case NUMBER : case NULL : case TRUE : case FALSE : return true ; case CAST : case NOT : case VOID : case NEG : return isImmutableValue ( n . getFirstChild ( ) ) ; case NAME : String name = n . getString ( ) ; return "undefined" . equals ( name ) || "Infinity" . equals ( name ) || "NaN" . equals ( name ) ; case TEMPLATELIT : for ( Node child = n . getFirstChild ( ) ; child != null ; child = child . getNext ( ) ) { if ( child . isTemplateLitSub ( ) ) { if ( ! isImmutableValue ( child . getFirstChild ( ) ) ) { return false ; } } } return true ; default : checkArgument ( ! n . isTemplateLitString ( ) ) ; break ; } return false ; }
Returns true if this is an immutable value .
34,573
static boolean isSymmetricOperation ( Node n ) { switch ( n . getToken ( ) ) { case EQ : case NE : case SHEQ : case SHNE : case MUL : return true ; default : break ; } return false ; }
Returns true if the operator on this node is symmetric
34,574
static boolean isRelationalOperation ( Node n ) { switch ( n . getToken ( ) ) { case GT : case GE : case LT : case LE : return true ; default : break ; } return false ; }
Returns true if the operator on this node is relational . the returned set does not include the equalities .
34,575
static boolean isSomeCompileTimeConstStringValue ( Node node ) { if ( node . isString ( ) || ( node . isTemplateLit ( ) && node . hasOneChild ( ) ) ) { return true ; } else if ( node . isAdd ( ) ) { checkState ( node . hasTwoChildren ( ) , node ) ; Node left = node . getFirstChild ( ) ; Node right = node . getLastChild ( ) ; return isSomeCompileTimeConstStringValue ( left ) && isSomeCompileTimeConstStringValue ( right ) ; } else if ( node . isHook ( ) ) { Node left = node . getSecondChild ( ) ; Node right = node . getLastChild ( ) ; return isSomeCompileTimeConstStringValue ( left ) && isSomeCompileTimeConstStringValue ( right ) ; } return false ; }
Returns true iff the value associated with the node is a JS string literal a concatenation thereof or a ternary operator choosing between string literals .
34,576
static boolean isEmptyBlock ( Node block ) { if ( ! block . isBlock ( ) ) { return false ; } for ( Node n = block . getFirstChild ( ) ; n != null ; n = n . getNext ( ) ) { if ( ! n . isEmpty ( ) ) { return false ; } } return true ; }
Returns whether this a BLOCK node with no children .
34,577
static boolean isBinaryOperatorType ( Token type ) { switch ( type ) { case OR : case AND : case BITOR : case BITXOR : case BITAND : case EQ : case NE : case SHEQ : case SHNE : case LT : case GT : case LE : case GE : case INSTANCEOF : case IN : case LSH : case RSH : case URSH : case ADD : case SUB : case MUL : case DIV : case MOD : case EXPONENT : return true ; default : return false ; } }
An operator with two operands that does not assign a value to either . Once you cut through the layers of rules these all parse similarly taking LeftHandSideExpression operands on either side . Comma is not included because it takes AssignmentExpression operands making its syntax different .
34,578
static boolean isUnaryOperatorType ( Token type ) { switch ( type ) { case DELPROP : case VOID : case TYPEOF : case POS : case NEG : case BITNOT : case NOT : return true ; default : return false ; } }
An operator taking only one operand . These all parse very similarly taking LeftHandSideExpression operands .
34,579
static boolean isAliasedConstDefinition ( Node lhs ) { JSDocInfo jsdoc = getBestJSDocInfo ( lhs ) ; if ( jsdoc == null && ! lhs . isFromExterns ( ) ) { return false ; } if ( jsdoc != null && ! jsdoc . hasConstAnnotation ( ) ) { return false ; } Node rhs = getRValueOfLValue ( lhs ) ; if ( rhs == null || ! rhs . isQualifiedName ( ) ) { return false ; } Node parent = lhs . getParent ( ) ; return ( lhs . isName ( ) && parent . isVar ( ) ) || ( lhs . isGetProp ( ) && lhs . isQualifiedName ( ) && parent . isAssign ( ) && parent . getParent ( ) . isExprResult ( ) ) ; }
True for aliases defined with
34,580
public static boolean isFromTypeSummary ( Node n ) { checkArgument ( n . isScript ( ) , n ) ; JSDocInfo info = n . getJSDocInfo ( ) ; return info != null && info . isTypeSummary ( ) ; }
Determine if the given SCRIPT is a
34,581
static boolean mayEffectMutableState ( Node n , AbstractCompiler compiler ) { checkNotNull ( compiler ) ; return checkForStateChangeHelper ( n , true , compiler ) ; }
Returns true if the node may create new mutable state or change existing state .
34,582
static boolean constructorCallHasSideEffects ( Node callNode ) { checkArgument ( callNode . isNew ( ) , "Expected NEW node, got %s" , callNode . getToken ( ) ) ; if ( callNode . isNoSideEffectsCall ( ) ) { return false ; } if ( callNode . isOnlyModifiesArgumentsCall ( ) && allArgsUnescapedLocal ( callNode ) ) { return false ; } Node nameNode = callNode . getFirstChild ( ) ; return ! nameNode . isName ( ) || ! CONSTRUCTORS_WITHOUT_SIDE_EFFECTS . contains ( nameNode . getString ( ) ) ; }
Do calls to this constructor have side effects?
34,583
static boolean nodeTypeMayHaveSideEffects ( Node n , AbstractCompiler compiler ) { if ( isAssignmentOp ( n ) ) { return true ; } switch ( n . getToken ( ) ) { case DELPROP : case DEC : case INC : case YIELD : case THROW : case AWAIT : case FOR_IN : case FOR_OF : case FOR_AWAIT_OF : return true ; case CALL : case TAGGED_TEMPLATELIT : return NodeUtil . functionCallHasSideEffects ( n , compiler ) ; case NEW : return NodeUtil . constructorCallHasSideEffects ( n ) ; case NAME : return n . hasChildren ( ) ; case REST : case SPREAD : return NodeUtil . iteratesImpureIterable ( n ) ; default : break ; } return false ; }
Returns true if the current node s type implies side effects .
34,584
static boolean mayBeString ( Node n , boolean useType ) { if ( useType ) { JSType type = n . getJSType ( ) ; if ( type != null ) { if ( type . isStringValueType ( ) ) { return true ; } else if ( type . isNumberValueType ( ) || type . isBooleanValueType ( ) || type . isNullType ( ) || type . isVoidType ( ) ) { return false ; } } } return mayBeString ( getKnownValueType ( n ) ) ; }
Return if the node is possibly a string .
34,585
public static Node getEnclosingType ( Node n , final Token type ) { return getEnclosingNode ( n , new Predicate < Node > ( ) { public boolean apply ( Node n ) { return n . getToken ( ) == type ; } } ) ; }
Gets the closest ancestor to the given node of the provided type .
34,586
static boolean referencesThis ( Node n ) { if ( n . isFunction ( ) ) { return referencesThis ( NodeUtil . getFunctionParameters ( n ) ) || referencesThis ( NodeUtil . getFunctionBody ( n ) ) ; } else { return has ( n , Node :: isThis , MATCH_ANYTHING_BUT_NON_ARROW_FUNCTION ) ; } }
Returns true if the shallow scope contains references to this keyword
34,587
static boolean referencesSuper ( Node n ) { Node curr = n . getFirstChild ( ) ; while ( curr != null ) { if ( containsType ( curr , Token . SUPER , node -> ! node . isClass ( ) ) ) { return true ; } curr = curr . getNext ( ) ; } return false ; }
Returns true if the current scope contains references to the super keyword . Note that if there are classes declared inside the current class super calls which reference those classes are not reported .
34,588
static boolean isBlockScopedDeclaration ( Node n ) { if ( n . isName ( ) ) { switch ( n . getParent ( ) . getToken ( ) ) { case LET : case CONST : case CATCH : return true ; case CLASS : return n . getParent ( ) . getFirstChild ( ) == n ; case FUNCTION : return isBlockScopedFunctionDeclaration ( n . getParent ( ) ) ; default : break ; } } return false ; }
Is this node the name of a block - scoped declaration? Checks for let const class or block - scoped function declarations .
34,589
public static boolean isNameDeclaration ( Node n ) { return n != null && ( n . isVar ( ) || n . isLet ( ) || n . isConst ( ) ) ; }
Is this node a name declaration?
34,590
public static Node getAssignedValue ( Node n ) { checkState ( n . isName ( ) || n . isGetProp ( ) , n ) ; Node parent = n . getParent ( ) ; if ( NodeUtil . isNameDeclaration ( parent ) ) { return n . getFirstChild ( ) ; } else if ( parent . isAssign ( ) && parent . getFirstChild ( ) == n ) { return n . getNext ( ) ; } else { return null ; } }
For an assignment or variable declaration get the assigned value .
34,591
static boolean isLoopStructure ( Node n ) { switch ( n . getToken ( ) ) { case FOR : case FOR_IN : case FOR_OF : case FOR_AWAIT_OF : case DO : case WHILE : return true ; default : return false ; } }
Determines whether the given node is a FOR DO or WHILE node .
34,592
public static boolean isControlStructure ( Node n ) { switch ( n . getToken ( ) ) { case FOR : case FOR_IN : case FOR_OF : case FOR_AWAIT_OF : case DO : case WHILE : case WITH : case IF : case LABEL : case TRY : case CATCH : case SWITCH : case CASE : case DEFAULT_CASE : return true ; default : return false ; } }
Determines whether the given node is a FOR DO WHILE WITH or IF node .
34,593
static boolean isControlStructureCodeBlock ( Node parent , Node n ) { switch ( parent . getToken ( ) ) { case DO : return parent . getFirstChild ( ) == n ; case TRY : return parent . getFirstChild ( ) == n || parent . getLastChild ( ) == n ; case FOR : case FOR_IN : case FOR_OF : case FOR_AWAIT_OF : case WHILE : case LABEL : case WITH : case CATCH : return parent . getLastChild ( ) == n ; case IF : case SWITCH : case CASE : return parent . getFirstChild ( ) != n ; case DEFAULT_CASE : return true ; default : checkState ( isControlStructure ( parent ) , parent ) ; return false ; } }
Determines whether the given node is code node for FOR DO WHILE WITH or IF node .
34,594
static boolean createsBlockScope ( Node n ) { switch ( n . getToken ( ) ) { case BLOCK : Node parent = n . getParent ( ) ; return parent != null && ! isSwitchCase ( parent ) && ! parent . isCatch ( ) ; case FOR : case FOR_IN : case FOR_OF : case FOR_AWAIT_OF : case SWITCH : case CLASS : return true ; default : return false ; } }
A block scope is created by a non - synthetic block node a for loop node or a for - of loop node .
34,595
static boolean isTryFinallyNode ( Node parent , Node child ) { return parent . isTry ( ) && parent . hasXChildren ( 3 ) && child == parent . getLastChild ( ) ; }
Whether the child node is the FINALLY block of a try .
34,596
static boolean isTryCatchNodeContainer ( Node n ) { Node parent = n . getParent ( ) ; return parent . isTry ( ) && parent . getSecondChild ( ) == n ; }
Whether the node is a CATCH container BLOCK .
34,597
public static void deleteChildren ( Node n , AbstractCompiler compiler ) { while ( n . hasChildren ( ) ) { deleteNode ( n . getFirstChild ( ) , compiler ) ; } }
Permanently delete all the children of the given node including reporting changes .
34,598
public static void removeChild ( Node parent , Node node ) { if ( isTryFinallyNode ( parent , node ) ) { if ( NodeUtil . hasCatchHandler ( getCatchBlock ( parent ) ) ) { parent . removeChild ( node ) ; } else { node . detachChildren ( ) ; } } else if ( node . isCatch ( ) ) { Node tryNode = node . getGrandparent ( ) ; checkState ( NodeUtil . hasFinally ( tryNode ) ) ; node . detach ( ) ; } else if ( isTryCatchNodeContainer ( node ) ) { Node tryNode = node . getParent ( ) ; checkState ( NodeUtil . hasFinally ( tryNode ) ) ; node . detachChildren ( ) ; } else if ( node . isBlock ( ) ) { node . detachChildren ( ) ; } else if ( isStatementBlock ( parent ) || isSwitchCase ( node ) || node . isMemberFunctionDef ( ) ) { parent . removeChild ( node ) ; } else if ( isNameDeclaration ( parent ) || parent . isExprResult ( ) ) { if ( parent . hasMoreThanOneChild ( ) ) { parent . removeChild ( node ) ; } else { parent . removeChild ( node ) ; removeChild ( parent . getParent ( ) , parent ) ; } } else if ( parent . isLabel ( ) && node == parent . getLastChild ( ) ) { parent . removeChild ( node ) ; removeChild ( parent . getParent ( ) , parent ) ; } else if ( parent . isVanillaFor ( ) ) { parent . replaceChild ( node , IR . empty ( ) ) ; } else if ( parent . isObjectPattern ( ) ) { parent . removeChild ( node ) ; } else if ( parent . isArrayPattern ( ) ) { if ( node == parent . getLastChild ( ) ) { parent . removeChild ( node ) ; } else { parent . replaceChild ( node , IR . empty ( ) ) ; } } else if ( parent . isDestructuringLhs ( ) ) { parent . removeChild ( node ) ; if ( parent . getParent ( ) . hasChildren ( ) ) { removeChild ( parent . getParent ( ) , parent ) ; } } else if ( parent . isRest ( ) ) { parent . detach ( ) ; } else if ( parent . isParamList ( ) ) { parent . removeChild ( node ) ; } else if ( parent . isImport ( ) ) { if ( node == parent . getFirstChild ( ) ) { parent . replaceChild ( node , IR . empty ( ) ) ; } else { throw new IllegalStateException ( "Invalid attempt to remove: " + node + " from " + parent ) ; } } else { throw new IllegalStateException ( "Invalid attempt to remove node: " + node + " of " + parent ) ; } }
Safely remove children while maintaining a valid node structure . In some cases this is done by removing the parent from the AST as well .
34,599
static void maybeAddFinally ( Node tryNode ) { checkState ( tryNode . isTry ( ) ) ; if ( ! NodeUtil . hasFinally ( tryNode ) ) { tryNode . addChildToBack ( IR . block ( ) . srcref ( tryNode ) ) ; } }
Add a finally block if one does not exist .