idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
35,000
@ SuppressWarnings ( "unchecked" ) public final Set < String > getDirectives ( ) { return ( Set < String > ) getProp ( Prop . DIRECTIVES ) ; }
Returns the set of ES5 directives for this node .
35,001
@ GwtIncompatible ( "ObjectOutput" ) private void writeEncodedInt ( ObjectOutput out , int value ) throws IOException { while ( value > 0X7f || value < 0 ) { out . writeByte ( ( ( value & 0X7f ) | 0x80 ) ) ; value >>>= 7 ; } out . writeByte ( value ) ; }
Encode integers using variable length encoding .
35,002
private static Node normalizeAssignmentOp ( Node n ) { Node lhs = n . getFirstChild ( ) ; Node rhs = n . getLastChild ( ) ; Node newRhs = new Node ( NodeUtil . getOpFromAssignmentOp ( n ) , lhs . cloneTree ( ) , rhs . cloneTree ( ) ) . srcrefTree ( n ) ; return replace ( n , IR . assign ( lhs . cloneTree ( ) , newRhs )...
Transforms a + = b to a = a + b .
35,003
private Node renameProperty ( Node propertyName ) { checkArgument ( propertyName . isString ( ) ) ; if ( ! renameProperties ) { return propertyName ; } Node call = IR . call ( IR . name ( NodeUtil . JSC_PROPERTY_NAME_FN ) . srcref ( propertyName ) , propertyName ) ; call . srcref ( propertyName ) ; call . putBooleanPro...
Wraps a property string in a JSCompiler_renameProperty call .
35,004
private void replaceGetCompilerOverridesCalls ( List < TweakFunctionCall > calls ) { for ( TweakFunctionCall call : calls ) { Node callNode = call . callNode ; Node objNode = createCompilerDefaultValueOverridesVarNode ( callNode ) ; callNode . replaceWith ( objNode ) ; compiler . reportChangeToEnclosingScope ( objNode ...
Passes the compiler default value overrides to the JS by replacing calls to goog . tweak . getCompilerOverrids_ with a map of tweak ID - > default value ;
35,005
private void stripAllCalls ( Map < String , TweakInfo > tweakInfos ) { for ( TweakInfo tweakInfo : tweakInfos . values ( ) ) { boolean isRegistered = tweakInfo . isRegistered ( ) ; for ( TweakFunctionCall functionCall : tweakInfo . functionCalls ) { Node callNode = functionCall . callNode ; Node parent = callNode . get...
Removes all CALL nodes in the given TweakInfos replacing calls to getter functions with the tweak s default value .
35,006
private Node createCompilerDefaultValueOverridesVarNode ( Node sourceInformationNode ) { Node objNode = IR . objectlit ( ) . srcref ( sourceInformationNode ) ; for ( Entry < String , Node > entry : compilerDefaultValueOverrides . entrySet ( ) ) { Node objKeyNode = IR . stringKey ( entry . getKey ( ) ) . useSourceInfoIf...
Creates a JS object that holds a map of tweakId - > default value override .
35,007
private void applyCompilerDefaultValueOverrides ( Map < String , TweakInfo > tweakInfos ) { for ( Entry < String , Node > entry : compilerDefaultValueOverrides . entrySet ( ) ) { String tweakId = entry . getKey ( ) ; TweakInfo tweakInfo = tweakInfos . get ( tweakId ) ; if ( tweakInfo == null ) { compiler . report ( JSE...
Sets the default values of tweaks based on compiler options .
35,008
private Node tryFoldTry ( Node n ) { checkState ( n . isTry ( ) , n ) ; Node body = n . getFirstChild ( ) ; Node catchBlock = body . getNext ( ) ; Node finallyBlock = catchBlock . getNext ( ) ; if ( ! catchBlock . hasChildren ( ) && ( finallyBlock == null || ! finallyBlock . hasChildren ( ) ) ) { n . removeChild ( body...
Remove try blocks without catch blocks and with empty or not existent finally blocks . Or only leave the finally blocks if try body blocks are empty
35,009
private Node tryFoldExpr ( Node subtree ) { Node result = trySimplifyUnusedResult ( subtree . getFirstChild ( ) ) ; if ( result == null ) { Node parent = subtree . getParent ( ) ; if ( parent . isLabel ( ) ) { Node replacement = IR . block ( ) . srcref ( subtree ) ; parent . replaceChild ( subtree , replacement ) ; sub...
Try folding EXPR_RESULT nodes by removing useless Ops and expressions .
35,010
private Node tryOptimizeSwitch ( Node n ) { checkState ( n . isSwitch ( ) , n ) ; Node defaultCase = tryOptimizeDefaultCase ( n ) ; if ( defaultCase == null || n . getLastChild ( ) . isDefaultCase ( ) ) { Node cond = n . getFirstChild ( ) ; Node prev = null ; Node next = null ; Node cur ; for ( cur = cond . getNext ( )...
Remove useless switches and cases .
35,011
private void removeCase ( Node switchNode , Node caseNode ) { NodeUtil . redeclareVarsInsideBranch ( caseNode ) ; switchNode . removeChild ( caseNode ) ; reportChangeToEnclosingScope ( switchNode ) ; }
Remove the case from the switch redeclaring any variables declared in it .
35,012
Node tryOptimizeBlock ( Node n ) { for ( Node c = n . getFirstChild ( ) ; c != null ; ) { Node next = c . getNext ( ) ; if ( ! isUnremovableNode ( c ) && ! mayHaveSideEffects ( c ) ) { checkNormalization ( ! NodeUtil . isFunctionDeclaration ( n ) , "function declaration" ) ; n . removeChild ( c ) ; reportChangeToEnclos...
Try removing unneeded block nodes and their useless children
35,013
private void tryOptimizeConditionalAfterAssign ( Node n ) { Node next = n . getNext ( ) ; if ( isSimpleAssignment ( n ) && isConditionalStatement ( next ) ) { Node lhsAssign = getSimpleAssignmentName ( n ) ; Node condition = getConditionalStatementCondition ( next ) ; if ( lhsAssign . isName ( ) && condition . isName (...
Attempt to replace the condition of if or hook immediately that is a reference to a name that is assigned immediately before .
35,014
Node tryFoldWhile ( Node n ) { checkArgument ( n . isWhile ( ) ) ; Node cond = NodeUtil . getConditionExpression ( n ) ; if ( NodeUtil . getPureBooleanValue ( cond ) != TernaryValue . FALSE ) { return n ; } NodeUtil . redeclareVarsInsideBranch ( n ) ; reportChangeToEnclosingScope ( n . getParent ( ) ) ; NodeUtil . remo...
Removes WHILEs that always evaluate to false .
35,015
Node tryFoldFor ( Node n ) { checkArgument ( n . isVanillaFor ( ) ) ; Node init = n . getFirstChild ( ) ; Node cond = init . getNext ( ) ; Node increment = cond . getNext ( ) ; if ( ! init . isEmpty ( ) && ! NodeUtil . isNameDeclaration ( init ) ) { init = trySimplifyUnusedResult ( init ) ; if ( init == null ) { init =...
Removes FORs that always evaluate to false .
35,016
Node tryFoldDoAway ( Node n ) { checkArgument ( n . isDo ( ) ) ; Node cond = NodeUtil . getConditionExpression ( n ) ; if ( NodeUtil . getImpureBooleanValue ( cond ) != TernaryValue . FALSE ) { return n ; } Node block = NodeUtil . getLoopCodeBlock ( n ) ; if ( n . getParent ( ) . isLabel ( ) || hasUnnamedBreakOrContinu...
Removes DOs that always evaluate to false . This leaves the statements that were in the loop in a BLOCK node . The block will be removed in a later pass if possible .
35,017
Node tryFoldEmptyDo ( Node n ) { checkArgument ( n . isDo ( ) ) ; Node body = NodeUtil . getLoopCodeBlock ( n ) ; if ( body . isBlock ( ) && ! body . hasChildren ( ) ) { Node cond = NodeUtil . getConditionExpression ( n ) ; Node forNode = IR . forNode ( IR . empty ( ) . srcref ( n ) , cond . detach ( ) , IR . empty ( )...
Removes DOs that have empty bodies into FORs which are much easier for the CFA to analyze .
35,018
Node tryOptimizeObjectPattern ( Node pattern ) { checkArgument ( pattern . isObjectPattern ( ) , pattern ) ; if ( pattern . hasChildren ( ) && pattern . getLastChild ( ) . isRest ( ) ) { return pattern ; } for ( Node child = pattern . getFirstChild ( ) ; child != null ; ) { Node key = child ; child = key . getNext ( ) ...
Removes string keys with an empty pattern as their child
35,019
Node tryOptimizeArrayPattern ( Node pattern ) { checkArgument ( pattern . isArrayPattern ( ) , pattern ) ; for ( Node lastChild = pattern . getLastChild ( ) ; lastChild != null ; ) { if ( lastChild . isEmpty ( ) || isRemovableDestructuringTarget ( lastChild ) ) { Node prev = lastChild . getPrevious ( ) ; pattern . remo...
Removes trailing EMPTY nodes and empty array patterns
35,020
static boolean hasUnnamedBreakOrContinue ( Node n ) { return NodeUtil . has ( n , IS_UNNAMED_BREAK_PREDICATE , CAN_CONTAIN_BREAK_PREDICATE ) || NodeUtil . has ( n , IS_UNNAMED_CONTINUE_PREDICATE , CAN_CONTAIN_CONTINUE_PREDICATE ) ; }
Returns whether a node has any unhandled breaks or continue .
35,021
private void tryFoldForCondition ( Node forCondition ) { if ( NodeUtil . getPureBooleanValue ( forCondition ) == TernaryValue . TRUE ) { reportChangeToEnclosingScope ( forCondition ) ; forCondition . replaceWith ( IR . empty ( ) ) ; } }
Remove always true loop conditions .
35,022
private void visitBlockScopedName ( NodeTraversal t , Node decl , Node nameNode ) { Scope scope = t . getScope ( ) ; Node parent = decl . getParent ( ) ; if ( ( decl . isLet ( ) || decl . isConst ( ) ) && ! nameNode . hasChildren ( ) && ( parent == null || ! parent . isForIn ( ) ) && inLoop ( decl ) ) { Node undefined ...
Renames block - scoped declarations that shadow a variable in an outer scope
35,023
private boolean inLoop ( Node n ) { Node enclosingNode = NodeUtil . getEnclosingNode ( n , isLoopOrFunction ) ; return enclosingNode != null && ! enclosingNode . isFunction ( ) ; }
Whether n is inside a loop . If n is inside a function which is inside a loop we do not consider it to be inside a loop .
35,024
private Node createAssignNode ( Node lhs , Node rhs ) { Node assignNode = IR . assign ( lhs , rhs ) ; if ( shouldAddTypesOnNewAstNodes ) { assignNode . setJSType ( rhs . getJSType ( ) ) ; } return assignNode ; }
Creates an ASSIGN node with type information matching its RHS .
35,025
private Node createCommaNode ( Node expr1 , Node expr2 ) { Node commaNode = IR . comma ( expr1 , expr2 ) ; if ( shouldAddTypesOnNewAstNodes ) { commaNode . setJSType ( expr2 . getJSType ( ) ) ; } return commaNode ; }
Creates a COMMA node with type information matching its second argument .
35,026
public String getLine ( int lineNumber ) { findLineOffsets ( ) ; if ( lineNumber > lineOffsets . length ) { return null ; } if ( lineNumber < 1 ) { lineNumber = 1 ; } int pos = lineOffsets [ lineNumber - 1 ] ; String js = "" ; try { js = getCode ( ) ; } catch ( IOException e ) { return null ; } if ( js . indexOf ( '\n'...
Gets the source line for the indicated line number .
35,027
public Region getRegion ( int lineNumber ) { String js = "" ; try { js = getCode ( ) ; } catch ( IOException e ) { return null ; } int pos = 0 ; int startLine = Math . max ( 1 , lineNumber - ( SOURCE_EXCERPT_REGION_LENGTH + 1 ) / 2 + 1 ) ; for ( int n = 1 ; n < startLine ; n ++ ) { int nextpos = js . indexOf ( '\n' , p...
Get a region around the indicated line number . The exact definition of a region is implementation specific but it must contain the line indicated by the line number . A region must not start or end by a carriage return .
35,028
@ GwtIncompatible ( "com.google.io.Files" ) public void save ( String filename ) throws IOException { Files . write ( toBytes ( ) , new File ( filename ) ) ; }
Saves the variable map to a file .
35,029
@ GwtIncompatible ( "java.io.ByteArrayOutputStream" ) public byte [ ] toBytes ( ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; Writer writer = new OutputStreamWriter ( baos , UTF_8 ) ; try { for ( Map . Entry < String , String > entry : ImmutableSortedSet . copyOf ( comparingByKey ( ) , map . entrySet...
Serializes the variable map to a byte array .
35,030
public boolean parseTypeTransformation ( ) { Config config = Config . builder ( ) . setLanguageMode ( Config . LanguageMode . ECMASCRIPT6 ) . setStrictMode ( Config . StrictMode . SLOPPY ) . build ( ) ; ParseResult result = ParserRunner . parse ( sourceFile , typeTransformationString , config , errorReporter ) ; Node a...
Takes a type transformation expression transforms it to an AST using the ParserRunner of the JSCompiler and then verifies that it is a valid AST .
35,031
private boolean validBooleanExpression ( Node expr ) { if ( isBooleanOperation ( expr ) ) { return validBooleanOperation ( expr ) ; } if ( ! isOperation ( expr ) ) { warnInvalidExpression ( "boolean" , expr ) ; return false ; } if ( ! isValidPredicate ( getCallName ( expr ) ) ) { warnInvalid ( "boolean predicate" , exp...
A boolean expression must be a boolean predicate or a boolean type predicate
35,032
private boolean validOperationExpression ( Node expr ) { String name = getCallName ( expr ) ; Keywords keyword = nameToKeyword ( name ) ; switch ( keyword ) { case COND : return validConditionalExpression ( expr ) ; case MAPUNION : return validMapunionExpression ( expr ) ; case MAPRECORD : return validMaprecordExpressi...
An operation expression is a cond or a mapunion
35,033
private boolean validTypeTransformationExpression ( Node expr ) { if ( ! isValidExpression ( expr ) ) { warnInvalidExpression ( "type transformation" , expr ) ; return false ; } if ( isTypeVar ( expr ) || isTypeName ( expr ) ) { return true ; } String name = getCallName ( expr ) ; if ( ! isValidKeyword ( name ) ) { war...
Checks the structure of the AST of a type transformation expression in
35,034
private boolean removeIIFEWrapper ( Node root ) { checkState ( root . isScript ( ) ) ; Node n = root . getFirstChild ( ) ; while ( n != null && n . isEmpty ( ) ) { n = n . getNext ( ) ; } if ( n == null || ! n . isExprResult ( ) || n . getNext ( ) != null ) { return false ; } if ( n != null && n . getFirstChild ( ) != ...
UMD modules are often wrapped in an IIFE for cases where they are used as scripts instead of modules . Remove the wrapper .
35,035
private void removeWebpackModuleShim ( Node root ) { checkState ( root . isScript ( ) ) ; Node n = root . getFirstChild ( ) ; while ( n != null && n . isEmpty ( ) ) { n = n . getNext ( ) ; } if ( n == null || ! n . isExprResult ( ) || n . getNext ( ) != null ) { return ; } Node call = n . getFirstChild ( ) ; if ( call ...
For AMD wrappers webpack adds a shim for the module variable . We need that to be a free var so we remove the shim .
35,036
public static LinkedFlowScope createEntryLattice ( TypedScope scope ) { return new LinkedFlowScope ( HamtPMap . < TypedScope , OverlayScope > empty ( ) , scope , scope ) ; }
Creates an entry lattice for the flow .
35,037
public StaticTypedSlot getSlot ( String name ) { OverlayScope scope = getOverlayScopeForVar ( name , false ) ; return scope != null ? scope . getSlot ( name ) : syntacticScope . getSlot ( name ) ; }
Get the slot for the given symbol .
35,038
private static boolean equalSlots ( StaticTypedSlot slotA , StaticTypedSlot slotB ) { return slotA == slotB || ! slotA . getType ( ) . differsFrom ( slotB . getType ( ) ) ; }
Determines whether two slots are meaningfully different for the purposes of data flow analysis .
35,039
void updateAfterDeserialize ( Node jsRoot ) { this . jsRoot = jsRoot ; if ( ! tracksAstSize ( ) ) { return ; } this . initAstSize = this . astSize = NodeUtil . countAstSize ( this . jsRoot ) ; if ( ! tracksSize ( ) ) { return ; } PerformanceTrackerCodeSizeEstimator estimator = PerformanceTrackerCodeSizeEstimator . esti...
Updates the saved jsRoot and resets the size tracking fields accordingly .
35,040
void recordPassStop ( String passName , long runtime ) { int allocMem = getAllocatedMegabytes ( ) ; Stats logStats = this . currentPass . pop ( ) ; checkState ( passName . equals ( logStats . pass ) ) ; this . log . add ( logStats ) ; logStats . runtime = runtime ; logStats . allocMem = allocMem ; logStats . runs = 1 ;...
Collects information about a pass P after P finishes running eg how much time P took and what was its impact on code size .
35,041
private void loadGraph ( ) throws ServiceException { dependencies . clear ( ) ; logger . info ( "Loading dependency graph" ) ; ErrorManager errorManager = new LoggerErrorManager ( logger ) ; DepsFileParser parser = new DepsFileParser ( errorManager ) ; List < DependencyInfo > depInfos = parser . parseFile ( getName ( )...
Loads the dependency graph .
35,042
Node createIf ( Node cond , Node then ) { return IR . ifNode ( cond , then ) ; }
Returns a new IF node .
35,043
Node createFor ( Node init , Node cond , Node incr , Node body ) { return IR . forNode ( init , cond , incr , body ) ; }
Returns a new FOR node .
35,044
Node createThisForFunction ( Node functionNode ) { final Node result = IR . thisNode ( ) ; if ( isAddingTypes ( ) ) { result . setJSType ( getTypeOfThisForFunctionNode ( functionNode ) ) ; } return result ; }
Creates a THIS node with the correct type for the given function node .
35,045
Node createSuperForFunction ( Node functionNode ) { final Node result = IR . superNode ( ) ; if ( isAddingTypes ( ) ) { result . setJSType ( getTypeOfSuperForFunctionNode ( functionNode ) ) ; } return result ; }
Creates a SUPER node with the correct type for the given function node .
35,046
Node createThisAliasReferenceForFunction ( String aliasName , Node functionNode ) { final Node result = IR . name ( aliasName ) ; if ( isAddingTypes ( ) ) { result . setJSType ( getTypeOfThisForFunctionNode ( functionNode ) ) ; } return result ; }
Creates a NAME node having the type of this appropriate for the given function node .
35,047
Node createThisAliasDeclarationForFunction ( String aliasName , Node functionNode ) { return createSingleConstNameDeclaration ( aliasName , createThis ( getTypeOfThisForFunctionNode ( functionNode ) ) ) ; }
Creates a statement declaring a const alias for this to be used in the given function node .
35,048
Node createSingleConstNameDeclaration ( String variableName , Node value ) { return IR . constNode ( createName ( variableName , value . getJSType ( ) ) , value ) ; }
Creates a new const declaration statement for a single variable name .
35,049
Node createArgumentsReference ( ) { Node result = IR . name ( "arguments" ) ; if ( isAddingTypes ( ) ) { result . setJSType ( argumentsTypeSupplier . get ( ) ) ; } return result ; }
Creates a reference to arguments with the type specified in externs or unknown if the externs for it weren t included .
35,050
Node createObjectDotAssignCall ( Scope scope , JSType returnType , Node ... args ) { Node objAssign = createQName ( scope , "Object.assign" ) ; Node result = createCall ( objAssign , args ) ; if ( isAddingTypes ( ) ) { JSType objAssignType = registry . createFunctionTypeWithVarArgs ( returnType , registry . getNativeTy...
Creates a call to Object . assign that returns the specified type .
35,051
Node createAssignStatement ( Node lhs , Node rhs ) { return exprResult ( createAssign ( lhs , rhs ) ) ; }
Creates a statement lhs = rhs ; .
35,052
Node createAssign ( Node lhs , Node rhs ) { Node result = IR . assign ( lhs , rhs ) ; if ( isAddingTypes ( ) ) { result . setJSType ( rhs . getJSType ( ) ) ; } return result ; }
Creates an assignment expression lhs = rhs
35,053
private JSType getVarNameType ( Scope scope , String name ) { Var var = scope . getVar ( name ) ; JSType type = null ; if ( var != null ) { Node nameDefinitionNode = var . getNode ( ) ; if ( nameDefinitionNode != null ) { type = nameDefinitionNode . getJSType ( ) ; } } if ( type == null ) { type = unknownType ; } retur...
Look up the correct type for the given name in the given scope .
35,054
private static boolean nodesHaveSameControlFlow ( Node node1 , Node node2 ) { Node node1DeepestControlDependentBlock = closestControlDependentAncestor ( node1 ) ; Node node2DeepestControlDependentBlock = closestControlDependentAncestor ( node2 ) ; if ( node1DeepestControlDependentBlock == node2DeepestControlDependentBl...
Returns true if the two nodes have the same control flow properties that is is node1 be executed every time node2 is executed and vice versa?
35,055
private static boolean isControlDependentChild ( Node child ) { Node parent = child . getParent ( ) ; if ( parent == null ) { return false ; } ArrayList < Node > siblings = new ArrayList < > ( ) ; Iterables . addAll ( siblings , parent . children ( ) ) ; int indexOfChildInParent = siblings . indexOf ( child ) ; switch ...
Returns true if the number of times the child executes depends on the parent .
35,056
private static boolean nodeHasCall ( Node node ) { return NodeUtil . has ( node , new Predicate < Node > ( ) { public boolean apply ( Node input ) { return input . isCall ( ) || input . isNew ( ) || input . isTaggedTemplateLit ( ) ; } } , NOT_FUNCTION_PREDICATE ) ; }
Returns true if a node has a CALL or a NEW descendant .
35,057
public static List < SourceFile > prepareExterns ( CompilerOptions . Environment env , Map < String , SourceFile > externs ) { List < SourceFile > out = new ArrayList < > ( ) ; for ( String key : BUILTIN_LANG_EXTERNS ) { Preconditions . checkState ( externs . containsKey ( key ) , "Externs must contain builtin: %s" , k...
Filters and orders the passed externs for the specified environment .
35,058
void setValidityCheck ( PassFactory validityCheck ) { this . validityCheck = validityCheck ; this . changeVerifier = new ChangeVerifier ( compiler ) . snapshot ( jsRoot ) ; }
Adds a checker to be run after every pass . Intended for development .
35,059
public void process ( Node externs , Node root ) { progress = 0.0 ; progressStep = 0.0 ; if ( progressRange != null ) { progressStep = ( progressRange . maxValue - progressRange . initialValue ) / passes . size ( ) ; progress = progressRange . initialValue ; } for ( CompilerPass pass : passes ) { if ( Thread . interrup...
Run all the passes in the optimizer .
35,060
private void maybeRunValidityCheck ( String passName , Node externs , Node root ) { if ( validityCheck == null ) { return ; } try { validityCheck . create ( compiler ) . process ( externs , root ) ; changeVerifier . checkRecordedChanges ( passName , jsRoot ) ; } catch ( Exception e ) { throw new IllegalStateException (...
Runs the validity check if it is available .
35,061
private boolean canDecomposeSimply ( Node classNode ) { Node enclosingStatement = checkNotNull ( NodeUtil . getEnclosingStatement ( classNode ) , classNode ) ; if ( enclosingStatement == classNode ) { return true ; } else { Node classNodeParent = classNode . getParent ( ) ; if ( NodeUtil . isNameDeclaration ( enclosing...
Find common cases where we can safely decompose class extends expressions which are not qualified names . Enables transpilation of complex extends expressions .
35,062
private void decomposeInIIFE ( NodeTraversal t , Node classNode ) { Node functionBody = IR . block ( ) ; Node function = IR . function ( IR . name ( "" ) , IR . paramList ( ) , functionBody ) ; Node call = NodeUtil . newCallNode ( function ) ; classNode . replaceWith ( call ) ; functionBody . addChildToBack ( IR . retu...
When a class is used in an expressions where adding an alias as the previous statement might change execution order of a side - effect causing statement wrap the class in an IIFE so that decomposition can happen safely .
35,063
boolean provablyExecutesBefore ( BasicBlock thatBlock ) { BasicBlock currentBlock ; for ( currentBlock = thatBlock ; currentBlock != null && currentBlock != this ; currentBlock = currentBlock . getParent ( ) ) { } if ( currentBlock == this ) { return true ; } return isGlobalScopeBlock ( ) && thatBlock . isGlobalScopeBl...
Determines whether this block is guaranteed to begin executing before the given block does .
35,064
private void maybeCollapseIntoForStatements ( Node n , Node parent ) { if ( parent == null || ! NodeUtil . isStatementBlock ( parent ) ) { return ; } if ( ! n . isExprResult ( ) && ! n . isVar ( ) ) { return ; } Node nextSibling = n . getNext ( ) ; if ( nextSibling == null ) { return ; } else if ( nextSibling . isForIn...
Collapse VARs and EXPR_RESULT node into FOR loop initializers where possible .
35,065
private static String longToPaddedString ( long v , int digitsColumnWidth ) { int digitWidth = numDigits ( v ) ; StringBuilder sb = new StringBuilder ( ) ; appendSpaces ( sb , digitsColumnWidth - digitWidth ) ; sb . append ( v ) ; return sb . toString ( ) ; }
Converts v to a string and pads it with up to 16 spaces for improved alignment .
35,066
static void appendSpaces ( StringBuilder sb , int numSpaces ) { if ( numSpaces > 16 ) { logger . warning ( "Tracer.appendSpaces called with large numSpaces" ) ; numSpaces = 16 ; } while ( numSpaces >= 5 ) { sb . append ( " " ) ; numSpaces -= 5 ; } switch ( numSpaces ) { case 1 : sb . append ( " " ) ; break ; case 2...
Gets a string of spaces of the length specified .
35,067
static int addTracingStatistic ( TracingStatistic tracingStatistic ) { if ( tracingStatistic . enable ( ) ) { extraTracingStatistics . add ( tracingStatistic ) ; return extraTracingStatistics . lastIndexOf ( tracingStatistic ) ; } else { return - 1 ; } }
Adds a new tracing statistic to a trace
35,068
long stop ( int silenceThreshold ) { checkState ( Thread . currentThread ( ) == startThread ) ; ThreadTrace trace = getThreadTrace ( ) ; if ( ! trace . isInitialized ( ) ) { return 0 ; } stopTimeMs = clock . currentTimeMillis ( ) ; if ( extraTracingValues != null ) { for ( int i = 0 ; i < extraTracingValues . length ; ...
Stop the trace . This may only be done once and must be done from the same thread that started it .
35,069
static void initCurrentThreadTrace ( ) { ThreadTrace events = getThreadTrace ( ) ; if ( ! events . isEmpty ( ) ) { logger . log ( Level . WARNING , "Non-empty timer log:\n" + events , new Throwable ( ) ) ; clearThreadTrace ( ) ; events = getThreadTrace ( ) ; } events . init ( ) ; }
Initialize the trace associated with the current thread by clearing out any existing trace . There shouldn t be a trace so if one is found we log it as an error .
35,070
static void logCurrentThreadTrace ( ) { ThreadTrace trace = getThreadTrace ( ) ; if ( ! trace . isInitialized ( ) ) { logger . log ( Level . INFO , "Tracer log requested for this thread but was not " + "initialized using Tracer.initCurrentThreadTrace()." , new Throwable ( ) ) ; return ; } if ( ! trace . isEmpty ( ) ) {...
Logs a timer report similar to the one described in the class comment .
35,071
static Stat getStatsForType ( String type ) { Stat stat = getThreadTrace ( ) . stats . get ( type ) ; return stat != null ? stat : ZERO_STAT ; }
Gets the Stat for a tracer type ; never returns null
35,072
static ThreadTrace getThreadTrace ( ) { ThreadTrace t = traces . get ( ) ; if ( t == null ) { t = new ThreadTrace ( ) ; t . prettyPrint = defaultPrettyPrint ; traces . set ( t ) ; } return t ; }
Get the ThreadTrace for the current thread creating one if necessary .
35,073
private void addScopeVariables ( ) { int num = 0 ; for ( Var v : orderedVars ) { scopeVariables . put ( v . getName ( ) , num ) ; num ++ ; } }
Parameters belong to the function scope but variables defined in the function body belong to the function body scope . Assign a unique index to each variable regardless of which scope it s in .
35,074
void markAllParametersEscaped ( ) { Node paramList = NodeUtil . getFunctionParameters ( jsScope . getRootNode ( ) ) ; for ( Node arg = paramList . getFirstChild ( ) ; arg != null ; arg = arg . getNext ( ) ) { if ( arg . isRest ( ) || arg . isDefaultValue ( ) ) { escaped . add ( jsScope . getVar ( arg . getFirstChild ( ...
Give up computing liveness of formal parameter by putting all the parameter names in the escaped set .
35,075
public CheckLevel level ( JSError error ) { return error . sourceName != null && error . sourceName . contains ( part ) ? super . level ( error ) : null ; }
Does not touch warnings in other paths .
35,076
public Iterable < ObjectType > getCtorImplementedInterfaces ( ) { LinkedHashSet < ObjectType > resolvedImplementedInterfaces = new LinkedHashSet < > ( ) ; for ( ObjectType obj : getReferencedObjTypeInternal ( ) . getCtorImplementedInterfaces ( ) ) { resolvedImplementedInterfaces . add ( obj . visit ( replacer ) . toObj...
an UnsupportedOperationException .
35,077
private void checkTypeDeprecation ( NodeTraversal t , Node n ) { if ( ! shouldEmitDeprecationWarning ( t , n ) ) { return ; } ObjectType instanceType = n . getJSType ( ) . toMaybeFunctionType ( ) . getInstanceType ( ) ; String deprecationInfo = getTypeDeprecationInfo ( instanceType ) ; if ( deprecationInfo == null ) { ...
Reports deprecation issue with regard to a type usage .
35,078
private void checkNameDeprecation ( NodeTraversal t , Node n ) { if ( ! n . isName ( ) ) { return ; } if ( ! shouldEmitDeprecationWarning ( t , n ) ) { return ; } Var var = t . getScope ( ) . getVar ( n . getString ( ) ) ; JSDocInfo docInfo = var == null ? null : var . getJSDocInfo ( ) ; if ( docInfo != null && docInfo...
Checks the given NAME node to ensure that access restrictions are obeyed .
35,079
private void checkPropertyDeprecation ( NodeTraversal t , PropertyReference propRef ) { if ( ! shouldEmitDeprecationWarning ( t , propRef ) ) { return ; } if ( propRef . getSourceNode ( ) . getParent ( ) . isNew ( ) ) { return ; } ObjectType objectType = castToObject ( dereference ( propRef . getReceiverType ( ) ) ) ; ...
Checks the given GETPROP node to ensure that access restrictions are obeyed .
35,080
private void checkKeyVisibilityConvention ( Node key , Node parent ) { JSDocInfo info = key . getJSDocInfo ( ) ; if ( info == null ) { return ; } if ( ! isPrivateByConvention ( key . getString ( ) ) ) { return ; } Node assign = parent . getParent ( ) ; if ( assign == null || ! assign . isAssign ( ) ) { return ; } Node ...
Determines whether the given OBJECTLIT property visibility violates the coding convention .
35,081
private void checkNameVisibility ( Scope scope , Node name ) { if ( ! name . isName ( ) ) { return ; } Var var = scope . getVar ( name . getString ( ) ) ; if ( var == null ) { return ; } Visibility v = checkPrivateNameConvention ( AccessControlUtils . getEffectiveNameVisibility ( name , var , defaultVisibilityForFiles ...
Reports an error if the given name is not visible in the current context .
35,082
private void checkFinalClassOverrides ( Node ctor ) { if ( ! isFunctionOrClass ( ctor ) ) { return ; } JSType type = ctor . getJSType ( ) . toMaybeFunctionType ( ) ; if ( type != null && type . isConstructor ( ) ) { JSType finalParentClass = getSuperClassInstanceIfFinal ( bestInstanceTypeForMethodOrCtor ( ctor ) ) ; if...
Checks if a constructor is trying to override a final class .
35,083
static ObjectType getCanonicalInstance ( ObjectType obj ) { FunctionType ctor = obj . getConstructor ( ) ; return ctor == null ? obj : ctor . getInstanceType ( ) ; }
Return an object with the same nominal type as obj but without any possible extra properties that exist on obj .
35,084
private void checkPropertyVisibility ( PropertyReference propRef ) { if ( NodeUtil . isEs6ConstructorMemberFunctionDef ( propRef . getSourceNode ( ) ) ) { return ; } JSType rawReferenceType = typeOrUnknown ( propRef . getReceiverType ( ) ) . autobox ( ) ; ObjectType referenceType = castToObject ( rawReferenceType ) ; S...
Reports an error if the given property is not visible in the current context .
35,085
private boolean canAccessDeprecatedTypes ( NodeTraversal t ) { Node scopeRoot = t . getClosestHoistScopeRoot ( ) ; if ( NodeUtil . isFunctionBlock ( scopeRoot ) ) { scopeRoot = scopeRoot . getParent ( ) ; } Node scopeRootParent = scopeRoot . getParent ( ) ; return ( deprecationDepth > 0 ) || ( getTypeDeprecationInfo ( ...
Returns whether it s currently OK to access deprecated names and properties .
35,086
private static String getTypeDeprecationInfo ( JSType type ) { if ( type == null ) { return null ; } String depReason = getDeprecationReason ( type . getJSDocInfo ( ) ) ; if ( depReason != null ) { return depReason ; } ObjectType objType = castToObject ( type ) ; if ( objType != null ) { ObjectType implicitProto = objT...
Returns the deprecation reason for the type if it is marked as being deprecated . Returns empty string if the type is deprecated but no reason was given . Returns null if the type is not deprecated .
35,087
private boolean isPropertyDeclaredConstant ( ObjectType objectType , String prop ) { if ( enforceCodingConventions && compiler . getCodingConvention ( ) . isConstant ( prop ) ) { return true ; } for ( ; objectType != null ; objectType = objectType . getImplicitPrototype ( ) ) { JSDocInfo docInfo = objectType . getOwnPr...
Returns if a property is declared constant .
35,088
private static String getPropertyDeprecationInfo ( ObjectType type , String prop ) { String depReason = getDeprecationReason ( type . getOwnPropertyJSDocInfo ( prop ) ) ; if ( depReason != null ) { return depReason ; } ObjectType implicitProto = type . getImplicitPrototype ( ) ; if ( implicitProto != null ) { return ge...
Returns the deprecation reason for the property if it is marked as being deprecated . Returns empty string if the property is deprecated but no reason was given . Returns null if the property is not deprecated .
35,089
private void visitArrayLitOrCallWithSpread ( Node spreadParent ) { if ( spreadParent . isArrayLit ( ) ) { visitArrayLitContainingSpread ( spreadParent ) ; } else if ( spreadParent . isCall ( ) ) { visitCallContainingSpread ( spreadParent ) ; } else { checkArgument ( spreadParent . isNew ( ) , spreadParent ) ; visitNewW...
Processes array literals or calls to eliminate spreads .
35,090
private void visitArrayLitContainingSpread ( Node spreadParent ) { checkArgument ( spreadParent . isArrayLit ( ) ) ; List < Node > groups = extractSpreadGroups ( spreadParent ) ; final Node baseArrayLit ; if ( groups . get ( 0 ) . isArrayLit ( ) ) { baseArrayLit = groups . remove ( 0 ) ; } else { baseArrayLit = arrayLi...
Processes array literals containing spreads .
35,091
private void visitCallContainingSpread ( Node spreadParent ) { checkArgument ( spreadParent . isCall ( ) ) ; Node callee = spreadParent . getFirstChild ( ) ; boolean calleeMayHaveSideEffects = NodeUtil . mayHaveSideEffects ( callee , compiler ) ; spreadParent . removeChild ( callee ) ; final Node joinedGroups ; if ( sp...
Processes calls containing spreads .
35,092
private void visitNewWithSpread ( Node spreadParent ) { checkArgument ( spreadParent . isNew ( ) ) ; Node callee = spreadParent . removeFirstChild ( ) ; List < Node > groups = extractSpreadGroups ( spreadParent ) ; final Node baseArrayLit ; if ( groups . get ( 0 ) . isArrayLit ( ) ) { baseArrayLit = groups . remove ( 0...
Processes new calls containing spreads .
35,093
private static boolean checkPostExpressions ( Node n , Node expressionRoot , Predicate < Node > predicate ) { for ( Node p = n ; p != expressionRoot ; p = p . getParent ( ) ) { for ( Node cur = p . getNext ( ) ; cur != null ; cur = cur . getNext ( ) ) { if ( predicate . apply ( cur ) ) { return true ; } } } return fals...
Given an expression by its root and sub - expression n return true if the predicate is true for some expression evaluated after n .
35,094
private static boolean checkPreExpressions ( Node n , Node expressionRoot , Predicate < Node > predicate ) { for ( Node p = n ; p != expressionRoot ; p = p . getParent ( ) ) { Node oldestSibling = p . getParent ( ) . getFirstChild ( ) ; if ( oldestSibling . isDestructuringPattern ( ) ) { if ( p . isDestructuringPattern...
Given an expression by its root and sub - expression n return true if the predicate is true for some expression evaluated before n .
35,095
static PolymerClassDefinition extractFromClassNode ( Node classNode , AbstractCompiler compiler , GlobalNamespace globalNames ) { checkState ( classNode != null && classNode . isClass ( ) ) ; Node propertiesDescriptor = null ; Node propertiesGetter = NodeUtil . getFirstGetterMatchingKey ( NodeUtil . getClassMembers ( c...
Validates the class definition and if valid extracts the class definition from the AST . As opposed to the Polymer 1 extraction this operation is non - destructive .
35,096
private static void overwriteMembersIfPresent ( List < MemberDefinition > list , List < MemberDefinition > newMembers ) { for ( MemberDefinition newMember : newMembers ) { for ( MemberDefinition member : list ) { if ( member . name . getString ( ) . equals ( newMember . name . getString ( ) ) ) { list . remove ( member...
Appends a list of new MemberDefinitions to the end of a list and removes any previous MemberDefinition in the list which has the same name as the new member .
35,097
private void tryReplaceSuper ( Node superNode ) { checkState ( ! superclasses . isEmpty ( ) , "`super` cannot appear outside a function" ) ; Optional < Node > currentSuperclass = superclasses . peek ( ) ; if ( ! currentSuperclass . isPresent ( ) || ! currentSuperclass . get ( ) . isQualifiedName ( ) ) { return ; } Node...
Replaces super with Super . Class if in a static class method with a qname superclass
35,098
private boolean isSafeValue ( Scope scope , Node argument ) { if ( NodeUtil . isSomeCompileTimeConstStringValue ( argument ) ) { return true ; } else if ( argument . isAdd ( ) ) { Node left = argument . getFirstChild ( ) ; Node right = argument . getLastChild ( ) ; return isSafeValue ( scope , left ) && isSafeValue ( s...
Checks if the method call argument is made of constant string literals .
35,099
final void remove ( AbstractCompiler compiler ) { if ( isDetached ( ) ) { return ; } Node statement = getRemovableNode ( ) ; NodeUtil . deleteNode ( statement , compiler ) ; statement . removeChildren ( ) ; }
Remove this potential declaration completely . Usually this is because the same symbol has already been declared in this file .