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 ( line...
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...
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 ( ) ; s...
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 ) {...
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 ) ; skipEOL...
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 ( ...
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 ) { replaceSt...
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 . strin...
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 sizeOf...
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 . numOccurrence...
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 . ...
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 ( thi...
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 , INVA...
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 ...
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...
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 TypeDeclara...
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 ( hasNoInl...
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...
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 . c...
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 ) ; ...
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 ( ) || ! inliningLowersCos...
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 ( ...
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 . toStringTre...
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 , topS...
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 . ge...
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...
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 . getSecondC...
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 W...
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 , isPropertyAs...
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...
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 . safeNameIdSupplie...
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 ...
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...
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 ; } }...
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 = fal...
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 check...
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...
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 ( ...
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 ( ) != UNMAPP...
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 = ...
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 , ...
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 ( ) ...
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...
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" ...
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...
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 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" . e...
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...
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...
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 . isQualif...
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 ...
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...
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 fa...
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 ( ) ) ; d...
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 ( ) ; } ...
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 L...
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 f...
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 ( ) ; c...
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 .