idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
35,300
public final S getGlobalScope ( ) { S result = thisScope ( ) ; while ( result . getParent ( ) != null ) { result = result . getParent ( ) ; } return result ; }
Walks up the tree to find the global scope .
35,301
final void undeclare ( V var ) { checkState ( var . scope == this ) ; checkState ( vars . get ( var . name ) . equals ( var ) ) ; undeclareInteral ( var ) ; }
Undeclares a variable to be used when the compiler optimizes out a variable and removes it from the scope .
35,302
public V getVar ( String name ) { ImplicitVar implicit = name != null ? ImplicitVar . of ( name ) : null ; if ( implicit != null ) { return getImplicitVar ( implicit , true ) ; } S scope = thisScope ( ) ; while ( scope != null ) { V var = scope . getOwnSlot ( name ) ; if ( var != null ) { return var ; } scope = scope . getParent ( ) ; } return null ; }
Non - final for jsdev tests
35,303
private final V getImplicitVar ( ImplicitVar var , boolean allowDeclaredVars ) { S scope = thisScope ( ) ; while ( scope != null ) { if ( var . isMadeByScope ( scope ) ) { V result = ( ( AbstractScope < S , V > ) scope ) . implicitVars . get ( var ) ; if ( result == null ) { ( ( AbstractScope < S , V > ) scope ) . implicitVars . put ( var , result = scope . makeImplicitVar ( var ) ) ; } return result ; } V result = allowDeclaredVars ? scope . getOwnSlot ( var . name ) : null ; if ( result != null ) { return result ; } scope = scope . getParent ( ) ; } return null ; }
Get a unique Var object of the given implicit var type .
35,304
public final boolean hasSlot ( String name ) { S scope = thisScope ( ) ; while ( scope != null ) { if ( scope . hasOwnSlot ( name ) ) { return true ; } scope = scope . getParent ( ) ; } return false ; }
Returns true if a variable is declared in this or any parent scope .
35,305
final boolean canDeclare ( String name ) { return ! hasOwnSlot ( name ) && ( ! isFunctionBlockScope ( ) || ! getParent ( ) . hasOwnSlot ( name ) || isBleedingFunctionName ( name ) ) ; }
Returns true if the name can be declared on this scope without causing illegal shadowing . Specifically this is aware of the connection between function container scopes and function block scopes and returns false for redeclaring parameters on the block scope .
35,306
private boolean isBleedingFunctionName ( String name ) { V var = getVar ( name ) ; return var != null && var . getNode ( ) . getParent ( ) . isFunction ( ) ; }
Returns true if the given name is a bleeding function name in this scope . Local variables in the function block are not allowed to shadow parameters but they are allowed to shadow a bleeding function name .
35,307
public final S getClosestHoistScope ( ) { S current = thisScope ( ) ; while ( current != null ) { if ( current . isHoistScope ( ) ) { return current ; } current = current . getParent ( ) ; } return null ; }
If a var were declared in this scope return the scope it would be hoisted to .
35,308
public final S getClosestContainerScope ( ) { S scope = getClosestHoistScope ( ) ; if ( scope . isBlockScope ( ) ) { scope = scope . getParent ( ) ; checkState ( ! scope . isBlockScope ( ) ) ; } return scope ; }
Returns the closest container scope . This is equivalent to what the current scope would have been for non - ES6 scope creators and is thus useful for migrating code to use block scopes .
35,309
final void checkChildScope ( S parent ) { checkNotNull ( parent ) ; checkArgument ( NodeUtil . createsScope ( rootNode ) , rootNode ) ; checkArgument ( rootNode != parent . getRootNode ( ) , "rootNode should not be the parent's root node: %s" , rootNode ) ; }
Performs simple validity checks on when constructing a child scope .
35,310
final void checkRootScope ( ) { checkArgument ( NodeUtil . createsScope ( rootNode ) || rootNode . isScript ( ) || rootNode . isRoot ( ) , rootNode ) ; }
Performs simple validity checks on when constructing a root scope .
35,311
S getCommonParent ( S other ) { S left = thisScope ( ) ; S right = other ; while ( left != null && right != null && left != right ) { int leftDepth = left . getDepth ( ) ; int rightDepth = right . getDepth ( ) ; if ( leftDepth >= rightDepth ) { left = left . getParent ( ) ; } if ( leftDepth <= rightDepth ) { right = right . getParent ( ) ; } } checkState ( left != null && left == right ) ; return left ; }
Returns the nearest common parent between two scopes .
35,312
private void collapseAssign ( Node assign , Node expr , Node exprParent ) { Node leftValue = assign . getFirstChild ( ) ; Node rightValue = leftValue . getNext ( ) ; if ( leftValue . isDestructuringPattern ( ) ) { return ; } else if ( isCollapsibleValue ( leftValue , true ) && collapseAssignEqualTo ( expr , exprParent , leftValue ) ) { } else if ( isCollapsibleValue ( rightValue , false ) && collapseAssignEqualTo ( expr , exprParent , rightValue ) ) { } else if ( rightValue . isAssign ( ) ) { collapseAssign ( rightValue , expr , exprParent ) ; } }
Try to collapse the given assign into subsequent expressions .
35,313
private static boolean isCollapsibleValue ( Node value , boolean isLValue ) { switch ( value . getToken ( ) ) { case GETPROP : return ! isLValue || value . getFirstChild ( ) . isThis ( ) ; case NAME : return true ; default : return NodeUtil . isImmutableValue ( value ) ; } }
Determines whether we know enough about the given value to be able to collapse it into subsequent expressions .
35,314
private boolean collapseAssignEqualTo ( Node expr , Node exprParent , Node value ) { Node assign = expr . getFirstChild ( ) ; Node parent = exprParent ; Node next = expr . getNext ( ) ; while ( next != null ) { switch ( next . getToken ( ) ) { case AND : case OR : case HOOK : case IF : case RETURN : case EXPR_RESULT : parent = next ; next = next . getFirstChild ( ) ; break ; case CONST : case LET : case VAR : if ( next . getFirstChild ( ) . hasChildren ( ) ) { parent = next . getFirstChild ( ) ; next = parent . getFirstChild ( ) ; break ; } return false ; case GETPROP : case NAME : if ( next . isQualifiedName ( ) ) { if ( value . isQualifiedName ( ) && next . matchesQualifiedName ( value ) ) { if ( ! isSafeReplacement ( next , assign ) ) { return false ; } exprParent . removeChild ( expr ) ; expr . removeChild ( assign ) ; parent . replaceChild ( next , assign ) ; reportChangeToEnclosingScope ( parent ) ; return true ; } } return false ; case ASSIGN : Node leftSide = next . getFirstChild ( ) ; if ( leftSide . isName ( ) || ( leftSide . isGetProp ( ) && leftSide . getFirstChild ( ) . isThis ( ) ) ) { parent = next ; next = leftSide . getNext ( ) ; break ; } else { return false ; } default : if ( NodeUtil . isImmutableValue ( next ) && next . isEquivalentTo ( value ) ) { exprParent . removeChild ( expr ) ; expr . removeChild ( assign ) ; parent . replaceChild ( next , assign ) ; reportChangeToEnclosingScope ( parent ) ; return true ; } return false ; } } return false ; }
Collapse the given assign expression into the expression directly following it if possible .
35,315
private boolean isSafeReplacement ( Node node , Node replacement ) { if ( node . isName ( ) ) { return true ; } checkArgument ( node . isGetProp ( ) ) ; while ( node . isGetProp ( ) ) { node = node . getFirstChild ( ) ; } return ! ( node . isName ( ) && isNameAssignedTo ( node . getString ( ) , replacement ) ) ; }
Checks name referenced in node to determine if it might have changed .
35,316
public static boolean matchesWholeInput ( RegExpTree t , String flags ) { if ( flags . indexOf ( 'm' ) >= 0 ) { return false ; } if ( ! ( t instanceof Concatenation ) ) { return false ; } Concatenation c = ( Concatenation ) t ; if ( c . elements . isEmpty ( ) ) { return false ; } RegExpTree first = c . elements . get ( 0 ) , last = Iterables . getLast ( c . elements ) ; if ( ! ( first instanceof Anchor && last instanceof Anchor ) ) { return false ; } return ( ( Anchor ) first ) . type == '^' && ( ( Anchor ) last ) . type == '$' ; }
True if but not necessarily always when the given regular expression must match the whole input or none of it .
35,317
private List < PassFactory > getMainOptimizationLoop ( ) { List < PassFactory > passes = new ArrayList < > ( ) ; if ( options . inlineGetters ) { passes . add ( inlineSimpleMethods ) ; } passes . addAll ( getCodeRemovingPasses ( ) ) ; if ( options . getInlineFunctionsLevel ( ) != Reach . NONE ) { passes . add ( inlineFunctions ) ; } if ( options . shouldInlineProperties ( ) && options . isTypecheckingEnabled ( ) ) { passes . add ( inlineProperties ) ; } if ( options . removeUnusedVars || options . removeUnusedLocalVars ) { if ( options . deadAssignmentElimination ) { passes . add ( deadAssignmentsElimination ) ; if ( options . polymerVersion == null ) { passes . add ( deadPropertyAssignmentElimination ) ; } } } if ( options . optimizeCalls ) { passes . add ( optimizeCalls ) ; } if ( options . j2clPassMode . shouldAddJ2clPasses ( ) ) { passes . add ( j2clConstantHoisterPass ) ; passes . add ( j2clClinitPass ) ; } assertAllLoopablePasses ( passes ) ; return passes ; }
Creates the passes for the main optimization loop .
35,318
private List < PassFactory > getCodeRemovingPasses ( ) { List < PassFactory > passes = new ArrayList < > ( ) ; if ( options . collapseObjectLiterals ) { passes . add ( collapseObjectLiterals ) ; } if ( options . inlineVariables || options . inlineLocalVariables ) { passes . add ( inlineVariables ) ; } else if ( options . inlineConstantVars ) { passes . add ( inlineConstants ) ; } if ( options . foldConstants ) { passes . add ( peepholeOptimizations ) ; } if ( options . removeDeadCode ) { passes . add ( removeUnreachableCode ) ; } if ( shouldRunRemoveUnusedCode ( ) ) { passes . add ( removeUnusedCode ) ; } assertAllLoopablePasses ( passes ) ; return passes ; }
Creates several passes aimed at removing code .
35,319
private static void assertAllOneTimePasses ( List < PassFactory > passes ) { for ( PassFactory pass : passes ) { checkState ( pass . isOneTimePass ( ) ) ; } }
Verify that all the passes are one - time passes .
35,320
private static void assertAllLoopablePasses ( List < PassFactory > passes ) { for ( PassFactory pass : passes ) { checkState ( ! pass . isOneTimePass ( ) ) ; } }
Verify that all the passes are multi - run passes .
35,321
private static CompilerPass createPeepholeOptimizationsPass ( AbstractCompiler compiler , String passName ) { final boolean late = false ; final boolean useTypesForOptimization = compiler . getOptions ( ) . useTypesForLocalOptimization ; List < AbstractPeepholeOptimization > optimizations = new ArrayList < > ( ) ; optimizations . add ( new MinimizeExitPoints ( ) ) ; optimizations . add ( new PeepholeMinimizeConditions ( late ) ) ; optimizations . add ( new PeepholeSubstituteAlternateSyntax ( late ) ) ; optimizations . add ( new PeepholeReplaceKnownMethods ( late , useTypesForOptimization ) ) ; optimizations . add ( new PeepholeRemoveDeadCode ( ) ) ; if ( compiler . getOptions ( ) . j2clPassMode . shouldAddJ2clPasses ( ) ) { optimizations . add ( new J2clEqualitySameRewriterPass ( useTypesForOptimization ) ) ; optimizations . add ( new J2clStringValueOfRewriterPass ( ) ) ; } optimizations . add ( new PeepholeFoldConstants ( late , useTypesForOptimization ) ) ; optimizations . add ( new PeepholeCollectPropertyAssignments ( ) ) ; return new PeepholeOptimizationsPass ( compiler , passName , optimizations ) ; }
Various peephole optimizations .
35,322
private static CompilerPass runInSerial ( final Collection < CompilerPass > passes ) { return new CompilerPass ( ) { public void process ( Node externs , Node root ) { for ( CompilerPass pass : passes ) { pass . process ( externs , root ) ; } } } ; }
Create a compiler pass that runs the given passes in serial .
35,323
public List < DependencyInfo > parseFile ( String filePath ) throws IOException { return parseFileReader ( filePath , Files . newReader ( new File ( filePath ) , StandardCharsets . UTF_8 ) ) ; }
Parses the given file and returns a list of dependency information that it contained .
35,324
public List < DependencyInfo > parseFile ( String filePath , String fileContents ) { return parseFileReader ( filePath , new StringReader ( fileContents ) ) ; }
Parses the given file and returns a list of dependency information that it contained . It uses the passed in fileContents instead of reading the file .
35,325
public List < DependencyInfo > parseFileReader ( String filePath , Reader reader ) { depInfos = new ArrayList < > ( ) ; if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Parsing Dep: " + filePath ) ; } doParse ( filePath , reader ) ; return depInfos ; }
Parses the file from the given reader and returns a list of dependency information that it contained .
35,326
private void checkReferenceEquality ( Node n , String typeName , String fileName ) { if ( n . getToken ( ) == Token . SHEQ || n . getToken ( ) == Token . EQ || n . getToken ( ) == Token . SHNE || n . getToken ( ) == Token . NE ) { JSType firstJsType = n . getFirstChild ( ) . getJSType ( ) ; JSType lastJsType = n . getLastChild ( ) . getJSType ( ) ; boolean hasType = isType ( firstJsType , fileName ) || isType ( lastJsType , fileName ) ; boolean hasNullType = isNullType ( firstJsType ) || isNullType ( lastJsType ) ; if ( hasType && ! hasNullType ) { compiler . report ( JSError . make ( n , J2CL_REFERENCE_EQUALITY , typeName ) ) ; } } }
Reports an error if the node is a reference equality check of the specified type .
35,327
public static Result createResultForStage1 ( Result result ) { VariableMap emptyVariableMap = new VariableMap ( ImmutableMap . of ( ) ) ; return new Result ( result . errors , result . warnings , emptyVariableMap , emptyVariableMap , emptyVariableMap , null , null , "" , null , null , null ) ; }
Returns an almost empty result that is used for multistage compilation .
35,328
public List < SuggestedFix > drive ( Scanner scanner , Pattern includeFilePattern ) { JsFlumeCallback callback = new JsFlumeCallback ( scanner , includeFilePattern ) ; NodeTraversal . traverse ( compiler , rootNode , callback ) ; List < SuggestedFix > fixes = callback . getFixes ( ) ; fixes . addAll ( scanner . processAllMatches ( callback . getMatches ( ) ) ) ; return fixes ; }
Run a refactoring and return any suggested fixes as a result .
35,329
public static CompilerOptions getCompilerOptions ( ) { CompilerOptions options = new CompilerOptions ( ) ; options . setLanguageIn ( LanguageMode . ECMASCRIPT_NEXT ) ; options . setLanguageOut ( LanguageMode . ECMASCRIPT5 ) ; options . setSummaryDetailLevel ( 0 ) ; options . setDependencyOptions ( DependencyOptions . sortOnly ( ) ) ; options . setChecksOnly ( true ) ; options . setContinueAfterErrors ( true ) ; options . setParseJsDocDocumentation ( Config . JsDocParsing . INCLUDE_DESCRIPTIONS_NO_WHITESPACE ) ; options . setCheckSuspiciousCode ( true ) ; options . setCheckSymbols ( true ) ; options . setCheckTypes ( true ) ; options . setBrokenClosureRequiresLevel ( CheckLevel . OFF ) ; options . setClosurePass ( true ) ; options . setGenerateExports ( true ) ; options . setPreserveClosurePrimitives ( true ) ; options . setWarningLevel ( DiagnosticGroups . STRICT_MISSING_REQUIRE , CheckLevel . WARNING ) ; options . setWarningLevel ( DiagnosticGroups . EXTRA_REQUIRE , CheckLevel . WARNING ) ; options . setWarningLevel ( DiagnosticGroups . LINT_CHECKS , CheckLevel . WARNING ) ; return options ; }
don t need to call it directly .
35,330
private static boolean isPropertyTree ( Node expectedGetprop ) { if ( ! expectedGetprop . isGetProp ( ) ) { return false ; } Node leftChild = expectedGetprop . getFirstChild ( ) ; if ( ! leftChild . isThis ( ) && ! isPropertyTree ( leftChild ) ) { return false ; } Node retVal = leftChild . getNext ( ) ; return NodeUtil . getStringValue ( retVal ) != null ; }
Returns true if the provided node is a getprop for which the left child is this or a valid property tree and for which the right side is a string .
35,331
private static void replaceThis ( Node expectedGetprop , Node replacement ) { Node leftChild = expectedGetprop . getFirstChild ( ) ; if ( leftChild . isThis ( ) ) { expectedGetprop . replaceChild ( leftChild , replacement ) ; } else { replaceThis ( leftChild , replacement ) ; } }
Finds the occurrence of this in the provided property tree and replaces it with replacement
35,332
private static Node returnedExpression ( Node fn ) { Node expectedBlock = NodeUtil . getFunctionBody ( fn ) ; if ( ! expectedBlock . hasOneChild ( ) ) { return null ; } Node expectedReturn = expectedBlock . getFirstChild ( ) ; if ( ! expectedReturn . isReturn ( ) ) { return null ; } if ( ! expectedReturn . hasOneChild ( ) ) { return null ; } return expectedReturn . getOnlyChild ( ) ; }
Return the node that represents the expression returned by the method given a FUNCTION node .
35,333
private void inlinePropertyReturn ( Node parent , Node call , Node returnedValue ) { Node getProp = returnedValue . cloneTree ( ) ; replaceThis ( getProp , call . getFirstChild ( ) . removeFirstChild ( ) ) ; parent . replaceChild ( call , getProp ) ; compiler . reportChangeToEnclosingScope ( getProp ) ; }
Replace the provided method call with the tree specified in returnedValue
35,334
private void inlineConstReturn ( Node parent , Node call , Node returnedValue ) { Node retValue = returnedValue . cloneTree ( ) ; parent . replaceChild ( call , retValue ) ; compiler . reportChangeToEnclosingScope ( retValue ) ; }
Replace the provided object and its method call with the tree specified in returnedValue . Should be called only if the object reference has no side effects .
35,335
private void inlineEmptyMethod ( NodeTraversal t , Node parent , Node call ) { if ( NodeUtil . isExprCall ( parent ) ) { parent . replaceWith ( IR . empty ( ) ) ; NodeUtil . markFunctionsDeleted ( parent , compiler ) ; } else { Node srcLocation = call ; parent . replaceChild ( call , NodeUtil . newUndefinedNode ( srcLocation ) ) ; NodeUtil . markFunctionsDeleted ( call , compiler ) ; } t . reportCodeChange ( ) ; }
Remove the provided object and its method call .
35,336
private boolean argsMayHaveSideEffects ( Node call ) { for ( Node currentChild = call . getSecondChild ( ) ; currentChild != null ; currentChild = currentChild . getNext ( ) ) { if ( NodeUtil . mayHaveSideEffects ( currentChild , compiler ) ) { return true ; } } return false ; }
Check whether the given method call s arguments have side effects .
35,337
public void setWarning ( String value ) { if ( "default" . equalsIgnoreCase ( value ) ) { this . warningLevel = WarningLevel . DEFAULT ; } else if ( "quiet" . equalsIgnoreCase ( value ) ) { this . warningLevel = WarningLevel . QUIET ; } else if ( "verbose" . equalsIgnoreCase ( value ) ) { this . warningLevel = WarningLevel . VERBOSE ; } else { throw new BuildException ( "Unrecognized 'warning' option value (" + value + ")" ) ; } }
Set the warning level .
35,338
public void setEnvironment ( String value ) { switch ( value ) { case "BROWSER" : this . environment = CompilerOptions . Environment . BROWSER ; break ; case "CUSTOM" : this . environment = CompilerOptions . Environment . CUSTOM ; break ; default : throw new BuildException ( "Unrecognized 'environment' option value (" + value + ")" ) ; } }
Set the environment which determines the builtin extern set .
35,339
public void setCompilationLevel ( String value ) { if ( "simple" . equalsIgnoreCase ( value ) ) { this . compilationLevel = CompilationLevel . SIMPLE_OPTIMIZATIONS ; } else if ( "advanced" . equalsIgnoreCase ( value ) ) { this . compilationLevel = CompilationLevel . ADVANCED_OPTIMIZATIONS ; } else if ( "whitespace" . equalsIgnoreCase ( value ) ) { this . compilationLevel = CompilationLevel . WHITESPACE_ONLY ; } else { throw new BuildException ( "Unrecognized 'compilation' option value (" + value + ")" ) ; } }
Set the compilation level .
35,340
private List < SourceFile > findJavaScriptFiles ( ResourceCollection rc ) { List < SourceFile > files = new ArrayList < > ( ) ; Iterator < Resource > iter = rc . iterator ( ) ; while ( iter . hasNext ( ) ) { FileResource fr = ( FileResource ) iter . next ( ) ; java . nio . file . Path path = Paths . get ( "" ) . toAbsolutePath ( ) . relativize ( fr . getFile ( ) . toPath ( ) ) ; files . add ( SourceFile . fromPath ( path , Charset . forName ( encoding ) ) ) ; } return files ; }
Translates an Ant resource collection into the file list format that the compiler expects .
35,341
private List < SourceFile > getBuiltinExterns ( CompilerOptions options ) { try { return CommandLineRunner . getBuiltinExterns ( options . getEnvironment ( ) ) ; } catch ( IOException e ) { throw new BuildException ( e ) ; } }
Gets the default externs set .
35,342
private long getLastModifiedTime ( List < ? > fileLists ) { long lastModified = 0 ; for ( Object entry : fileLists ) { if ( entry instanceof FileList ) { FileList list = ( FileList ) entry ; for ( String fileName : list . getFiles ( this . getProject ( ) ) ) { File path = list . getDir ( this . getProject ( ) ) ; File file = new File ( path , fileName ) ; lastModified = Math . max ( getLastModifiedTime ( file ) , lastModified ) ; } } else if ( entry instanceof Path ) { Path path = ( Path ) entry ; for ( String src : path . list ( ) ) { File file = new File ( src ) ; lastModified = Math . max ( getLastModifiedTime ( file ) , lastModified ) ; } } } return lastModified ; }
Returns the most recent modified timestamp of the file collection .
35,343
private static long getLastModifiedTime ( File file ) { long fileLastModified = file . lastModified ( ) ; if ( fileLastModified == 0 ) { fileLastModified = new Date ( ) . getTime ( ) ; } return fileLastModified ; }
Returns the last modified timestamp of the given File .
35,344
private void reusePropertyNames ( Set < String > reservedNames , Collection < Property > allProps ) { for ( Property prop : allProps ) { String prevName = prevUsedPropertyMap . lookupNewName ( prop . oldName ) ; if ( ! generatePseudoNames && prevName != null ) { if ( reservedNames . contains ( prevName ) ) { continue ; } prop . newName = prevName ; reservedNames . add ( prevName ) ; } } }
Runs through the list of properties and renames as many as possible with names from the previous compilation . Also updates reservedNames with the set of reused names .
35,345
private void generateNames ( Set < Property > props , Set < String > reservedNames ) { nameGenerator . reset ( reservedNames , "" , reservedFirstCharacters , reservedNonFirstCharacters ) ; for ( Property p : props ) { if ( generatePseudoNames ) { p . newName = "$" + p . oldName + "$" ; } else { if ( p . newName == null ) { p . newName = nameGenerator . generateNextName ( ) ; } } reservedNames . add ( p . newName ) ; } }
Generates new names for properties .
35,346
private void addAtConstructor ( Node node ) { JSDocInfoBuilder builder = JSDocInfoBuilder . maybeCopyFrom ( node . getJSDocInfo ( ) ) ; builder . recordConstructor ( ) ; node . setJSDocInfo ( builder . build ( ) ) ; }
Add at - constructor to the JSDoc of the given node .
35,347
static void quoteListenerAndHostAttributeKeys ( Node objLit , AbstractCompiler compiler ) { checkState ( objLit . isObjectLit ( ) ) ; for ( Node keyNode : objLit . children ( ) ) { if ( keyNode . isComputedProp ( ) ) { continue ; } if ( ! keyNode . getString ( ) . equals ( "listeners" ) && ! keyNode . getString ( ) . equals ( "hostAttributes" ) ) { continue ; } for ( Node keyToQuote : keyNode . getFirstChild ( ) . children ( ) ) { if ( ! keyToQuote . isQuotedString ( ) ) { keyToQuote . setQuotedString ( ) ; compiler . reportChangeToEnclosingScope ( keyToQuote ) ; } } } }
Makes sure that the keys for listeners and hostAttributes blocks are quoted to avoid renaming .
35,348
private static void collectConstructorPropertyJsDoc ( Node node , Map < String , JSDocInfo > map ) { checkNotNull ( node ) ; for ( Node child : node . children ( ) ) { if ( child . isGetProp ( ) && child . getFirstChild ( ) . isThis ( ) && child . getSecondChild ( ) . isString ( ) ) { map . put ( child . getSecondChild ( ) . getString ( ) , NodeUtil . getBestJSDocInfo ( child ) ) ; } else { collectConstructorPropertyJsDoc ( child , map ) ; } } }
Find the properties that are initialized in the given constructor and return a map from each property name to its JSDoc .
35,349
static JSTypeExpression getTypeFromProperty ( MemberDefinition property , AbstractCompiler compiler ) { if ( property . info != null && property . info . hasType ( ) ) { return property . info . getType ( ) ; } String typeString ; if ( property . value . isObjectLit ( ) ) { Node typeValue = NodeUtil . getFirstPropMatchingKey ( property . value , "type" ) ; if ( typeValue == null || ! typeValue . isName ( ) ) { compiler . report ( JSError . make ( property . name , PolymerPassErrors . POLYMER_INVALID_PROPERTY ) ) ; return null ; } typeString = typeValue . getString ( ) ; } else if ( property . value . isName ( ) ) { typeString = property . value . getString ( ) ; } else { typeString = "" ; } Node typeNode ; switch ( typeString ) { case "Boolean" : case "String" : case "Number" : typeNode = IR . string ( typeString . toLowerCase ( ) ) ; break ; case "Array" : case "Function" : case "Object" : case "Date" : typeNode = new Node ( Token . BANG , IR . string ( typeString ) ) ; break ; default : compiler . report ( JSError . make ( property . name , PolymerPassErrors . POLYMER_INVALID_PROPERTY ) ) ; return null ; } return new JSTypeExpression ( typeNode , VIRTUAL_FILE ) ; }
Gets the JSTypeExpression for a given property using its type key .
35,350
Var declare ( String name , Node nameNode , CompilerInput input ) { checkArgument ( ! name . isEmpty ( ) ) ; checkState ( getOwnSlot ( name ) == null ) ; Var var = new Var ( name , nameNode , this , getVarCount ( ) , input ) ; declareInternal ( name , var ) ; return var ; }
Non - final for PersisteneScope .
35,351
public static SuggestedFix getFixForJsError ( JSError error , AbstractCompiler compiler ) { switch ( error . getType ( ) . key ) { case "JSC_REDECLARED_VARIABLE" : return getFixForRedeclaration ( error , compiler ) ; case "JSC_REFERENCE_BEFORE_DECLARE" : return getFixForEarlyReference ( error , compiler ) ; case "JSC_MISSING_SEMICOLON" : return getFixForMissingSemicolon ( error , compiler ) ; case "JSC_REQUIRES_NOT_SORTED" : return getFixForUnsortedRequires ( error , compiler ) ; case "JSC_PROVIDES_NOT_SORTED" : return getFixForUnsortedProvides ( error , compiler ) ; case "JSC_DEBUGGER_STATEMENT_PRESENT" : return removeNode ( error , compiler ) ; case "JSC_USELESS_EMPTY_STATEMENT" : return removeEmptyStatement ( error , compiler ) ; case "JSC_INEXISTENT_PROPERTY" : return getFixForInexistentProperty ( error , compiler ) ; case "JSC_MISSING_CALL_TO_SUPER" : return getFixForMissingSuper ( error , compiler ) ; case "JSC_INVALID_SUPER_CALL_WITH_SUGGESTION" : return getFixForInvalidSuper ( error , compiler ) ; case "JSC_MISSING_REQUIRE_WARNING" : case "JSC_MISSING_REQUIRE_STRICT_WARNING" : return getFixForMissingRequire ( error , compiler ) ; case "JSC_EXTRA_REQUIRE_WARNING" : return getFixForExtraRequire ( error , compiler ) ; case "JSC_REFERENCE_TO_SHORT_IMPORT_BY_LONG_NAME_INCLUDING_SHORT_NAME" : case "JSC_JSDOC_REFERENCE_TO_SHORT_IMPORT_BY_LONG_NAME_INCLUDING_SHORT_NAME" : case "JSC_REFERENCE_TO_FULLY_QUALIFIED_IMPORT_NAME" : return getFixForReferenceToShortImportByLongName ( error , compiler ) ; case "JSC_REDUNDANT_NULLABILITY_MODIFIER_JSDOC" : return getFixForRedundantNullabilityModifierJsDoc ( error , compiler ) ; default : return null ; } }
Creates a SuggestedFix for the given error . Note that some errors have multiple fixes so getFixesForJsError should often be used instead of this .
35,352
protected FlowScope firstPreciserScopeKnowingConditionOutcome ( Node condition , FlowScope blindScope , boolean outcome ) { return firstLink . getPreciserScopeKnowingConditionOutcome ( condition , blindScope , outcome ) ; }
Calculates the preciser scope starting with the first link .
35,353
protected FlowScope nextPreciserScopeKnowingConditionOutcome ( Node condition , FlowScope blindScope , boolean outcome ) { return nextLink != null ? nextLink . getPreciserScopeKnowingConditionOutcome ( condition , blindScope , outcome ) : blindScope ; }
Delegates the calculation of the preciser scope to the next link . If there is no next link returns the blind scope .
35,354
protected JSType getTypeIfRefinable ( Node node , FlowScope scope ) { switch ( node . getToken ( ) ) { case NAME : StaticTypedSlot nameVar = scope . getSlot ( node . getString ( ) ) ; if ( nameVar != null ) { JSType nameVarType = nameVar . getType ( ) ; if ( nameVarType == null ) { nameVarType = node . getJSType ( ) ; } return nameVarType ; } return null ; case GETPROP : String qualifiedName = node . getQualifiedName ( ) ; if ( qualifiedName == null ) { return null ; } StaticTypedSlot propVar = scope . getSlot ( qualifiedName ) ; JSType propVarType = null ; if ( propVar != null ) { propVarType = propVar . getType ( ) ; } if ( propVarType == null ) { propVarType = node . getJSType ( ) ; } if ( propVarType == null ) { propVarType = getNativeType ( UNKNOWN_TYPE ) ; } return propVarType ; default : break ; } return null ; }
Returns the type of a node in the given scope if the node corresponds to a name whose type is capable of being refined .
35,355
protected final JSType getRestrictedWithoutUndefined ( JSType type ) { return type == null ? null : type . visit ( restrictUndefinedVisitor ) ; }
Returns a version of type where undefined is not present .
35,356
protected final JSType getRestrictedWithoutNull ( JSType type ) { return type == null ? null : type . visit ( restrictNullVisitor ) ; }
Returns a version of type where null is not present .
35,357
private JSType getNativeTypeForTypeOf ( String value ) { switch ( value ) { case "number" : return getNativeType ( NUMBER_TYPE ) ; case "boolean" : return getNativeType ( BOOLEAN_TYPE ) ; case "string" : return getNativeType ( STRING_TYPE ) ; case "symbol" : return getNativeType ( SYMBOL_TYPE ) ; case "undefined" : return getNativeType ( VOID_TYPE ) ; case "function" : return getNativeType ( U2U_CONSTRUCTOR_TYPE ) ; default : return null ; } }
If we definitely know what a type is based on the typeof result return it . Otherwise return null .
35,358
protected void reconcileOptionsWithGuards ( ) { if ( options . enables ( DiagnosticGroups . CHECK_TYPES ) ) { options . checkTypes = true ; } else if ( options . disables ( DiagnosticGroups . CHECK_TYPES ) ) { options . checkTypes = false ; } else if ( ! options . checkTypes ) { options . setWarningLevel ( DiagnosticGroup . forType ( RhinoErrorReporter . TYPE_PARSE_ERROR ) , CheckLevel . OFF ) ; } if ( options . checkGlobalThisLevel . isOn ( ) && ! options . disables ( DiagnosticGroups . GLOBAL_THIS ) ) { options . setWarningLevel ( DiagnosticGroups . GLOBAL_THIS , options . checkGlobalThisLevel ) ; } if ( options . expectStrictModeInput ( ) ) { options . setWarningLevel ( DiagnosticGroups . ES5_STRICT , CheckLevel . ERROR ) ; } if ( ! options . checkSymbols && ! options . enables ( DiagnosticGroups . CHECK_VARIABLES ) ) { options . setWarningLevel ( DiagnosticGroups . CHECK_VARIABLES , CheckLevel . OFF ) ; } if ( options . skipNonTranspilationPasses && ! options . enables ( DiagnosticGroups . CHECK_VARIABLES ) ) { options . setWarningLevel ( DiagnosticGroups . CHECK_VARIABLES , CheckLevel . OFF ) ; } if ( options . skipNonTranspilationPasses && ! options . enables ( DiagnosticGroups . MISSING_PROVIDE ) ) { options . setWarningLevel ( DiagnosticGroups . MISSING_PROVIDE , CheckLevel . OFF ) ; } if ( options . brokenClosureRequiresLevel == CheckLevel . OFF ) { options . setWarningLevel ( DiagnosticGroups . MISSING_PROVIDE , CheckLevel . OFF ) ; } }
When the CompilerOptions and its WarningsGuard overlap reconcile any discrepancies .
35,359
public final < T1 extends SourceFile , T2 extends SourceFile > void init ( List < T1 > externs , List < T2 > sources , CompilerOptions options ) { JSModule module = new JSModule ( JSModule . STRONG_MODULE_NAME ) ; for ( SourceFile source : sources ) { module . add ( new CompilerInput ( source ) ) ; } List < JSModule > modules = new ArrayList < > ( 1 ) ; modules . add ( module ) ; initModules ( externs , modules , options ) ; addFilesToSourceMap ( sources ) ; }
Initializes the instance state needed for a compile job .
35,360
public < T extends SourceFile > void initModules ( List < T > externs , List < JSModule > modules , CompilerOptions options ) { initOptions ( options ) ; checkFirstModule ( modules ) ; this . externs = makeExternInputs ( externs ) ; try { this . moduleGraph = new JSModuleGraph ( modules ) ; } catch ( JSModuleGraph . ModuleDependenceException e ) { report ( JSError . make ( MODULE_DEPENDENCY_ERROR , e . getModule ( ) . getName ( ) , e . getDependentModule ( ) . getName ( ) ) ) ; return ; } fillEmptyModules ( getModules ( ) ) ; this . commentsPerFile = new ConcurrentHashMap < > ( moduleGraph . getInputCount ( ) ) ; initBasedOnOptions ( ) ; initInputsByIdMap ( ) ; initAST ( ) ; }
Initializes the instance state needed for a compile job if the sources are in modules .
35,361
public void initBasedOnOptions ( ) { inputSourceMaps . putAll ( options . inputSourceMaps ) ; if ( options . sourceMapOutputPath != null ) { sourceMap = options . sourceMapFormat . getInstance ( ) ; sourceMap . setPrefixMappings ( options . sourceMapLocationMappings ) ; if ( options . applyInputSourceMaps ) { sourceMap . setSourceFileMapping ( this ) ; if ( options . sourceMapIncludeSourcesContent ) { for ( SourceMapInput inputSourceMap : inputSourceMaps . values ( ) ) { addSourceMapSourceFiles ( inputSourceMap ) ; } } } } }
Do any initialization that is dependent on the compiler options .
35,362
private void checkFirstModule ( List < JSModule > modules ) { if ( modules . isEmpty ( ) ) { report ( JSError . make ( EMPTY_MODULE_LIST_ERROR ) ) ; } else if ( modules . get ( 0 ) . getInputs ( ) . isEmpty ( ) && modules . size ( ) > 1 ) { report ( JSError . make ( EMPTY_ROOT_MODULE_ERROR , modules . get ( 0 ) . getName ( ) ) ) ; } }
Verifies that at least one module has been provided and that the first one has at least one source code input .
35,363
private void fillEmptyModules ( Iterable < JSModule > modules ) { for ( JSModule module : modules ) { if ( ! module . getName ( ) . equals ( JSModule . WEAK_MODULE_NAME ) && module . getInputs ( ) . isEmpty ( ) ) { CompilerInput input = new CompilerInput ( SourceFile . fromCode ( createFillFileName ( module . getName ( ) ) , "" ) ) ; input . setCompiler ( this ) ; module . add ( input ) ; } } }
Fill any empty modules with a place holder file . It makes any cross module motion easier .
35,364
void initInputsByIdMap ( ) { inputsById . clear ( ) ; for ( CompilerInput input : externs ) { InputId id = input . getInputId ( ) ; CompilerInput previous = putCompilerInput ( id , input ) ; if ( previous != null ) { report ( JSError . make ( DUPLICATE_EXTERN_INPUT , input . getName ( ) ) ) ; } } for ( CompilerInput input : moduleGraph . getAllInputs ( ) ) { InputId id = input . getInputId ( ) ; CompilerInput previous = putCompilerInput ( id , input ) ; if ( previous != null ) { report ( JSError . make ( DUPLICATE_INPUT , input . getName ( ) ) ) ; } } }
Creates a map to make looking up an input by name fast . Also checks for duplicate inputs .
35,365
public Result compile ( SourceFile extern , SourceFile input , CompilerOptions options ) { return compile ( ImmutableList . of ( extern ) , ImmutableList . of ( input ) , options ) ; }
Compiles a single source file and a single externs file .
35,366
public < T1 extends SourceFile , T2 extends SourceFile > Result compile ( List < T1 > externs , List < T2 > inputs , CompilerOptions options ) { checkState ( jsRoot == null ) ; try { init ( externs , inputs , options ) ; if ( options . printConfig ) { printConfig ( System . err ) ; } if ( ! hasErrors ( ) ) { parseForCompilation ( ) ; } if ( ! hasErrors ( ) ) { if ( options . getInstrumentForCoverageOnly ( ) ) { instrumentForCoverage ( ) ; } else { stage1Passes ( ) ; if ( ! hasErrors ( ) ) { stage2Passes ( ) ; } } performPostCompilationTasks ( ) ; } } finally { generateReport ( ) ; } return getResult ( ) ; }
Compiles a list of inputs .
35,367
public < T extends SourceFile > Result compileModules ( List < T > externs , List < JSModule > modules , CompilerOptions options ) { checkState ( jsRoot == null ) ; try { initModules ( externs , modules , options ) ; if ( options . printConfig ) { printConfig ( System . err ) ; } if ( ! hasErrors ( ) ) { parseForCompilation ( ) ; } if ( ! hasErrors ( ) ) { if ( options . getInstrumentForCoverageOnly ( ) ) { instrumentForCoverage ( ) ; } else { stage1Passes ( ) ; if ( ! hasErrors ( ) ) { stage2Passes ( ) ; } } performPostCompilationTasks ( ) ; } } finally { generateReport ( ) ; } return getResult ( ) ; }
Compiles a list of modules .
35,368
public void stage1Passes ( ) { checkState ( moduleGraph != null , "No inputs. Did you call init() or initModules()?" ) ; checkState ( ! hasErrors ( ) ) ; checkState ( ! options . getInstrumentForCoverageOnly ( ) ) ; runInCompilerThread ( ( ) -> { performChecksAndTranspilation ( ) ; return null ; } ) ; }
Perform compiler passes for stage 1 of compilation .
35,369
public void stage2Passes ( ) { checkState ( moduleGraph != null , "No inputs. Did you call init() or initModules()?" ) ; checkState ( ! hasErrors ( ) ) ; checkState ( ! options . getInstrumentForCoverageOnly ( ) ) ; JSModule weakModule = moduleGraph . getModuleByName ( JSModule . WEAK_MODULE_NAME ) ; if ( weakModule != null ) { for ( CompilerInput i : moduleGraph . getAllInputs ( ) ) { if ( i . getSourceFile ( ) . isWeak ( ) ) { checkState ( i . getModule ( ) == weakModule , "Expected all weak files to be in the weak module." ) ; } } } runInCompilerThread ( ( ) -> { if ( options . shouldOptimize ( ) ) { performOptimizations ( ) ; } return null ; } ) ; }
Perform compiler passes for stage 2 of compilation .
35,370
< T > T runInCompilerThread ( Callable < T > callable ) { return compilerExecutor . runInCompilerThread ( callable , options != null && options . getTracerMode ( ) . isOn ( ) ) ; }
The primary purpose of this method is to run the provided code with a larger than standard stack .
35,371
private void performPostCompilationTasksInternal ( ) { if ( options . devMode == DevMode . START_AND_END ) { runValidityCheck ( ) ; } setProgress ( 1.0 , "recordFunctionInformation" ) ; if ( tracker != null ) { tracker . outputTracerReport ( ) ; } }
Performs all the bookkeeping required at the end of a compilation .
35,372
public void instrumentForCoverage ( ) { checkState ( moduleGraph != null , "No inputs. Did you call init() or initModules()?" ) ; checkState ( ! hasErrors ( ) ) ; runInCompilerThread ( ( ) -> { checkState ( options . getInstrumentForCoverageOnly ( ) ) ; checkState ( ! hasErrors ( ) ) ; instrumentForCoverageInternal ( options . instrumentBranchCoverage ) ; return null ; } ) ; }
Instrument code for coverage .
35,373
void startPass ( String passName ) { checkState ( currentTracer == null ) ; currentPassName = passName ; currentTracer = newTracer ( passName ) ; beforePass ( passName ) ; }
Marks the beginning of a pass .
35,374
void endPass ( String passName ) { checkState ( currentTracer != null , "Tracer should not be null at the end of a pass." ) ; stopTracer ( currentTracer , currentPassName ) ; afterPass ( passName ) ; currentPassName = null ; currentTracer = null ; maybeRunValidityCheck ( ) ; }
Marks the end of a pass .
35,375
Tracer newTracer ( String passName ) { String comment = passName + ( recentChange . hasCodeChanged ( ) ? " on recently changed AST" : "" ) ; if ( options . getTracerMode ( ) . isOn ( ) && tracker != null ) { tracker . recordPassStart ( passName , true ) ; } return new Tracer ( "Compiler" , comment ) ; }
Returns a new tracer for the given pass name .
35,376
public Result getResult ( ) { Set < SourceFile > transpiledFiles = new HashSet < > ( ) ; if ( jsRoot != null ) { for ( Node scriptNode : jsRoot . children ( ) ) { if ( scriptNode . getBooleanProp ( Node . TRANSPILED ) ) { transpiledFiles . add ( getSourceFileByName ( scriptNode . getSourceFileName ( ) ) ) ; } } } return new Result ( getErrors ( ) , getWarnings ( ) , this . variableMap , this . propertyMap , this . anonymousFunctionNameMap , this . stringMap , this . sourceMap , this . externExports , this . cssNames , this . idGeneratorMap , transpiledFiles ) ; }
Returns the result of the compilation .
35,377
public CompilerInput getInput ( InputId id ) { if ( id == null ) { return null ; } return inputsById . get ( id ) ; }
interface and which ones should always be injected .
35,378
protected void removeExternInput ( InputId id ) { CompilerInput input = getInput ( id ) ; if ( input == null ) { return ; } checkState ( input . isExtern ( ) , "Not an extern input: %s" , input . getName ( ) ) ; inputsById . remove ( id ) ; externs . remove ( input ) ; Node root = checkNotNull ( input . getAstRoot ( this ) ) ; if ( root != null ) { root . detach ( ) ; } }
Removes an input file from AST .
35,379
boolean replaceIncrementalSourceAst ( JsAst ast ) { CompilerInput oldInput = getInput ( ast . getInputId ( ) ) ; checkNotNull ( oldInput , "No input to replace: %s" , ast . getInputId ( ) . getIdName ( ) ) ; Node newRoot = checkNotNull ( ast . getAstRoot ( this ) ) ; Node oldRoot = oldInput . getAstRoot ( this ) ; oldRoot . replaceWith ( newRoot ) ; CompilerInput newInput = new CompilerInput ( ast ) ; putCompilerInput ( ast . getInputId ( ) , newInput ) ; JSModule module = oldInput . getModule ( ) ; if ( module != null ) { module . addAfter ( newInput , oldInput ) ; module . remove ( oldInput ) ; } checkState ( newInput . getInputId ( ) . equals ( oldInput . getInputId ( ) ) ) ; InputId inputIdOnAst = newInput . getAstRoot ( this ) . getInputId ( ) ; checkState ( newInput . getInputId ( ) . equals ( inputIdOnAst ) ) ; return true ; }
Replace a source input dynamically . Intended for incremental re - compilation .
35,380
private void findModulesFromEntryPoints ( boolean supportEs6Modules , boolean supportCommonJSModules ) { maybeDoThreadedParsing ( ) ; List < CompilerInput > entryPoints = new ArrayList < > ( ) ; Map < String , CompilerInput > inputsByProvide = new HashMap < > ( ) ; Map < String , CompilerInput > inputsByIdentifier = new HashMap < > ( ) ; for ( CompilerInput input : moduleGraph . getAllInputs ( ) ) { if ( ! options . getDependencyOptions ( ) . shouldDropMoochers ( ) && input . getProvides ( ) . isEmpty ( ) ) { entryPoints . add ( input ) ; } inputsByIdentifier . put ( ModuleIdentifier . forFile ( input . getPath ( ) . toString ( ) ) . toString ( ) , input ) ; for ( String provide : input . getProvides ( ) ) { if ( ! provide . startsWith ( "module$" ) ) { inputsByProvide . put ( provide , input ) ; } } } for ( ModuleIdentifier moduleIdentifier : options . getDependencyOptions ( ) . getEntryPoints ( ) ) { CompilerInput input = inputsByProvide . get ( moduleIdentifier . toString ( ) ) ; if ( input == null ) { input = inputsByIdentifier . get ( moduleIdentifier . toString ( ) ) ; } if ( input != null ) { entryPoints . add ( input ) ; } } Set < CompilerInput > workingInputSet = Sets . newHashSet ( moduleGraph . getAllInputs ( ) ) ; for ( CompilerInput entryPoint : entryPoints ) { findModulesFromInput ( entryPoint , false , workingInputSet , inputsByIdentifier , inputsByProvide , supportEs6Modules , supportCommonJSModules ) ; } }
Find modules by recursively traversing dependencies starting with the entry points .
35,381
private void findModulesFromInput ( CompilerInput input , boolean wasImportedByModule , Set < CompilerInput > inputs , Map < String , CompilerInput > inputsByIdentifier , Map < String , CompilerInput > inputsByProvide , boolean supportEs6Modules , boolean supportCommonJSModules ) { if ( ! inputs . remove ( input ) ) { if ( wasImportedByModule && input . getJsModuleType ( ) == CompilerInput . ModuleType . NONE ) { input . setJsModuleType ( CompilerInput . ModuleType . IMPORTED_SCRIPT ) ; } return ; } FindModuleDependencies findDeps = new FindModuleDependencies ( this , supportEs6Modules , supportCommonJSModules , inputPathByWebpackId ) ; findDeps . process ( checkNotNull ( input . getAstRoot ( this ) ) ) ; if ( wasImportedByModule && input . getJsModuleType ( ) == CompilerInput . ModuleType . NONE ) { input . setJsModuleType ( CompilerInput . ModuleType . IMPORTED_SCRIPT ) ; } this . moduleTypesByName . put ( input . getPath ( ) . toModuleName ( ) , input . getJsModuleType ( ) ) ; Iterable < String > allDeps = Iterables . concat ( input . getRequiredSymbols ( ) , input . getDynamicRequires ( ) , input . getTypeRequires ( ) ) ; for ( String requiredNamespace : allDeps ) { CompilerInput requiredInput = null ; boolean requiredByModuleImport = false ; if ( inputsByProvide . containsKey ( requiredNamespace ) ) { requiredInput = inputsByProvide . get ( requiredNamespace ) ; } else if ( inputsByIdentifier . containsKey ( requiredNamespace ) ) { requiredByModuleImport = true ; requiredInput = inputsByIdentifier . get ( requiredNamespace ) ; } if ( requiredInput != null ) { findModulesFromInput ( requiredInput , requiredByModuleImport , inputs , inputsByIdentifier , inputsByProvide , supportEs6Modules , supportCommonJSModules ) ; } } }
Traverse an input s dependencies to find additional modules .
35,382
private boolean hoistIfExtern ( CompilerInput input ) { if ( input . getHasExternsAnnotation ( ) ) { externsRoot . addChildToBack ( input . getAstRoot ( this ) ) ; JSModule module = input . getModule ( ) ; if ( module != null ) { module . remove ( input ) ; } externs . add ( input ) ; return true ; } return false ; }
Hoists a compiler input to externs if it contains the
35,383
private void markExterns ( ImmutableList < CompilerInput > originalInputs ) { for ( CompilerInput input : originalInputs ) { if ( input . getHasExternsAnnotation ( ) ) { input . setIsExtern ( ) ; } } }
Marks inputs with the
35,384
Map < String , String > processJsonInputs ( Iterable < CompilerInput > inputsToProcess ) { RewriteJsonToModule rewriteJson = new RewriteJsonToModule ( this ) ; for ( CompilerInput input : inputsToProcess ) { if ( ! input . getSourceFile ( ) . getOriginalPath ( ) . endsWith ( ".json" ) ) { continue ; } input . setCompiler ( this ) ; try { input . getSourceFile ( ) . setCode ( "(" + input . getSourceFile ( ) . getCode ( ) + ")" ) ; } catch ( IOException e ) { continue ; } Node root = checkNotNull ( input . getAstRoot ( this ) ) ; input . setJsModuleType ( CompilerInput . ModuleType . JSON ) ; rewriteJson . process ( null , root ) ; } return rewriteJson . getPackageJsonMainEntries ( ) ; }
Transforms JSON files to a module export that closure compiler can process and keeps track of any main entries in package . json files .
35,385
void processAMDModules ( Iterable < CompilerInput > inputs ) { for ( CompilerInput input : inputs ) { input . setCompiler ( this ) ; Node root = checkNotNull ( input . getAstRoot ( this ) ) ; new TransformAMDToCJSModule ( this ) . process ( null , root ) ; } }
Transforms AMD to CJS modules
35,386
public String toSource ( ) { return runInCompilerThread ( ( ) -> { Tracer tracer = newTracer ( "toSource" ) ; try { CodeBuilder cb = new CodeBuilder ( ) ; if ( jsRoot != null ) { int i = 0 ; if ( options . shouldPrintExterns ( ) ) { for ( Node scriptNode = externsRoot . getFirstChild ( ) ; scriptNode != null ; scriptNode = scriptNode . getNext ( ) ) { toSource ( cb , i ++ , scriptNode ) ; } } for ( Node scriptNode = jsRoot . getFirstChild ( ) ; scriptNode != null ; scriptNode = scriptNode . getNext ( ) ) { toSource ( cb , i ++ , scriptNode ) ; } } return cb . toString ( ) ; } finally { stopTracer ( tracer , "toSource" ) ; } } ) ; }
Converts the main parse tree back to JS code .
35,387
public String toSource ( final JSModule module ) { return runInCompilerThread ( ( ) -> { List < CompilerInput > inputs = module . getInputs ( ) ; int numInputs = inputs . size ( ) ; if ( numInputs == 0 ) { return "" ; } CodeBuilder cb = new CodeBuilder ( ) ; for ( int i = 0 ; i < numInputs ; i ++ ) { Node scriptNode = inputs . get ( i ) . getAstRoot ( Compiler . this ) ; if ( scriptNode == null ) { throw new IllegalArgumentException ( "Bad module: " + module . getName ( ) ) ; } toSource ( cb , i , scriptNode ) ; } return cb . toString ( ) ; } ) ; }
Converts the parse tree for a module back to JS code .
35,388
public void toSource ( final CodeBuilder cb , final int inputSeqNum , final Node root ) { runInCompilerThread ( ( ) -> { if ( options . printInputDelimiter ) { if ( ( cb . getLength ( ) > 0 ) && ! cb . endsWith ( "\n" ) ) { cb . append ( "\n" ) ; } checkState ( root . isScript ( ) ) ; String delimiter = options . inputDelimiter ; String inputName = root . getInputId ( ) . getIdName ( ) ; String sourceName = root . getSourceFileName ( ) ; checkState ( sourceName != null ) ; checkState ( ! sourceName . isEmpty ( ) ) ; delimiter = delimiter . replace ( "%name%" , Matcher . quoteReplacement ( inputName ) ) . replace ( "%num%" , String . valueOf ( inputSeqNum ) ) . replace ( "%n%" , "\n" ) ; cb . append ( delimiter ) . append ( "\n" ) ; } if ( root . getJSDocInfo ( ) != null ) { String license = root . getJSDocInfo ( ) . getLicense ( ) ; if ( license != null && cb . addLicense ( license ) ) { cb . append ( "/*\n" ) . append ( license ) . append ( "*/\n" ) ; } } if ( options . sourceMapOutputPath != null ) { sourceMap . setStartingPosition ( cb . getLineIndex ( ) , cb . getColumnIndex ( ) ) ; } String code = toSource ( root , sourceMap , inputSeqNum == 0 ) ; if ( ! code . isEmpty ( ) ) { cb . append ( code ) ; int length = code . length ( ) ; char lastChar = code . charAt ( length - 1 ) ; char secondLastChar = length >= 2 ? code . charAt ( length - 2 ) : '\0' ; boolean hasSemiColon = lastChar == ';' || ( lastChar == '\n' && secondLastChar == ';' ) ; if ( ! hasSemiColon ) { cb . append ( ";" ) ; } } return null ; } ) ; }
Writes out JS code from a root node . If printing input delimiters this method will attach a comment to the start of the text indicating which input the output derived from . If there were any preserve annotations within the root s source they will also be printed in a block comment at the beginning of the output .
35,389
public String toSource ( Node n ) { initCompilerOptionsIfTesting ( ) ; return toSource ( n , null , true ) ; }
Generates JavaScript source code for an AST doesn t generate source map info .
35,390
private String toSource ( Node n , SourceMap sourceMap , boolean firstOutput ) { CodePrinter . Builder builder = new CodePrinter . Builder ( n ) ; builder . setTypeRegistry ( getTypeRegistry ( ) ) ; builder . setCompilerOptions ( options ) ; builder . setSourceMap ( sourceMap ) ; builder . setTagAsTypeSummary ( ! n . isFromExterns ( ) && options . shouldGenerateTypedExterns ( ) ) ; builder . setTagAsStrict ( firstOutput && options . shouldEmitUseStrict ( ) ) ; return builder . build ( ) ; }
Generates JavaScript source code for an AST .
35,391
public String [ ] toSourceArray ( ) { return runInCompilerThread ( ( ) -> { Tracer tracer = newTracer ( "toSourceArray" ) ; try { int numInputs = moduleGraph . getInputCount ( ) ; String [ ] sources = new String [ numInputs ] ; CodeBuilder cb = new CodeBuilder ( ) ; int i = 0 ; for ( CompilerInput input : moduleGraph . getAllInputs ( ) ) { Node scriptNode = input . getAstRoot ( Compiler . this ) ; cb . reset ( ) ; toSource ( cb , i , scriptNode ) ; sources [ i ] = cb . toString ( ) ; i ++ ; } return sources ; } finally { stopTracer ( tracer , "toSourceArray" ) ; } } ) ; }
Converts the parse tree for each input back to JS code .
35,392
public String [ ] toSourceArray ( final JSModule module ) { return runInCompilerThread ( ( ) -> { List < CompilerInput > inputs = module . getInputs ( ) ; int numInputs = inputs . size ( ) ; if ( numInputs == 0 ) { return new String [ 0 ] ; } String [ ] sources = new String [ numInputs ] ; CodeBuilder cb = new CodeBuilder ( ) ; for ( int i = 0 ; i < numInputs ; i ++ ) { Node scriptNode = inputs . get ( i ) . getAstRoot ( Compiler . this ) ; if ( scriptNode == null ) { throw new IllegalArgumentException ( "Bad module input: " + inputs . get ( i ) . getName ( ) ) ; } cb . reset ( ) ; toSource ( cb , i , scriptNode ) ; sources [ i ] = cb . toString ( ) ; } return sources ; } ) ; }
Converts the parse tree for each input in a module back to JS code .
35,393
ControlFlowGraph < Node > computeCFG ( ) { logger . fine ( "Computing Control Flow Graph" ) ; Tracer tracer = newTracer ( "computeCFG" ) ; ControlFlowAnalysis cfa = new ControlFlowAnalysis ( this , true , false ) ; process ( cfa ) ; stopTracer ( tracer , "computeCFG" ) ; return cfa . getCfg ( ) ; }
Control Flow Analysis .
35,394
private synchronized void addSourceMapSourceFiles ( SourceMapInput inputSourceMap ) { SourceMapConsumerV3 consumer = inputSourceMap . getSourceMap ( errorManager ) ; if ( consumer == null ) { return ; } Collection < String > sourcesContent = consumer . getOriginalSourcesContent ( ) ; if ( sourcesContent == null ) { return ; } Iterator < String > content = sourcesContent . iterator ( ) ; Iterator < String > sources = consumer . getOriginalSources ( ) . iterator ( ) ; while ( sources . hasNext ( ) && content . hasNext ( ) ) { String code = content . next ( ) ; SourceFile source = SourceMapResolver . getRelativePath ( inputSourceMap . getOriginalPath ( ) , sources . next ( ) ) ; if ( source != null ) { sourceMap . addSourceFile ( source . getOriginalPath ( ) , code ) ; } } if ( sources . hasNext ( ) || content . hasNext ( ) ) { throw new RuntimeException ( "Source map's \"sources\" and \"sourcesContent\" lengths do not match." ) ; } }
Adds file name to content mappings for all sources found in a source map . This is used to populate sourcesContent array in the output source map even for sources embedded in the input source map .
35,395
public String getAstDotGraph ( ) throws IOException { if ( jsRoot != null ) { ControlFlowAnalysis cfa = new ControlFlowAnalysis ( this , true , false ) ; cfa . process ( null , jsRoot ) ; return DotFormatter . toDot ( jsRoot , cfa . getCfg ( ) ) ; } else { return "" ; } }
Gets the DOT graph of the AST generated at the end of compilation .
35,396
public void replaceScript ( JsAst ast ) { CompilerInput input = this . getInput ( ast . getInputId ( ) ) ; if ( ! replaceIncrementalSourceAst ( ast ) ) { return ; } Node originalRoot = checkNotNull ( input . getAstRoot ( this ) ) ; processNewScript ( ast , originalRoot ) ; }
Replaces one file in a hot - swap mode . The given JsAst should be made from a new version of a file that already was present in the last compile call . If the file is new this will silently ignored .
35,397
private void runHotSwap ( Node originalRoot , Node js , PassConfig passConfig ) { for ( PassFactory passFactory : passConfig . getChecks ( ) ) { runHotSwapPass ( originalRoot , js , passFactory ) ; } }
Execute the passes from a PassConfig instance over a single replaced file .
35,398
@ GwtIncompatible ( "java.util.ResourceBundle" ) public static String getReleaseVersion ( ) { ResourceBundle config = ResourceBundle . getBundle ( CONFIG_RESOURCE ) ; return config . getString ( "compiler.version" ) ; }
Returns the compiler version baked into the jar .
35,399
@ GwtIncompatible ( "java.util.ResourceBundle" ) public static String getReleaseDate ( ) { ResourceBundle config = ResourceBundle . getBundle ( CONFIG_RESOURCE ) ; return config . getString ( "compiler.date" ) ; }
Returns the compiler date baked into the jar .