idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
34,200
boolean addImplementedInterface ( JSTypeExpression interfaceName ) { lazyInitInfo ( ) ; if ( info . implementedInterfaces == null ) { info . implementedInterfaces = new ArrayList < > ( 2 ) ; } if ( info . implementedInterfaces . contains ( interfaceName ) ) { return false ; } info . implementedInterfaces . add ( interfaceName ) ; return true ; }
Adds an implemented interface . Returns whether the interface was added . If the interface was already present in the list it won t get added again .
34,201
public List < JSTypeExpression > getExtendedInterfaces ( ) { if ( info == null || info . extendedInterfaces == null ) { return ImmutableList . of ( ) ; } return Collections . unmodifiableList ( info . extendedInterfaces ) ; }
Returns the interfaces extended by an interface
34,202
public Set < String > getSuppressions ( ) { Set < String > suppressions = info == null ? null : info . suppressions ; return suppressions == null ? Collections . < String > emptySet ( ) : suppressions ; }
Returns the set of suppressed warnings .
34,203
public Set < String > getModifies ( ) { Set < String > modifies = info == null ? null : info . modifies ; return modifies == null ? Collections . < String > emptySet ( ) : modifies ; }
Returns the set of sideeffect notations .
34,204
public boolean hasDescriptionForParameter ( String name ) { if ( documentation == null || documentation . parameters == null ) { return false ; } return documentation . parameters . containsKey ( name ) ; }
Returns whether a description exists for the parameter with the specified name .
34,205
public String getDescriptionForParameter ( String name ) { if ( documentation == null || documentation . parameters == null ) { return null ; } return documentation . parameters . get ( name ) ; }
Returns the description for the parameter with the given name if its exists .
34,206
public Collection < Marker > getMarkers ( ) { return ( documentation == null || documentation . markers == null ) ? ImmutableList . < Marker > of ( ) : documentation . markers ; }
Gets the list of all markers for the documentation in this JSDoc .
34,207
public ImmutableMap < String , Node > getTypeTransformations ( ) { if ( info == null || info . typeTransformations == null ) { return ImmutableMap . < String , Node > of ( ) ; } return ImmutableMap . copyOf ( info . typeTransformations ) ; }
Gets the type transformations .
34,208
void removeScopesForScript ( String scriptName ) { memoized . keySet ( ) . removeIf ( n -> scriptName . equals ( NodeUtil . getSourceName ( n ) ) ) ; }
Removes all scopes with root nodes from a given script file .
34,209
TypedScope createScope ( Node n ) { TypedScope s = memoized . get ( n ) ; return s != null ? s : createScope ( n , createScope ( NodeUtil . getEnclosingScopeRoot ( n . getParent ( ) ) ) ) ; }
Create a scope if it doesn t already exist looking up in the map for the parent scope .
34,210
public TypedScope createScope ( Node root , AbstractScope < ? , ? > parent ) { checkArgument ( parent == null || parent instanceof TypedScope ) ; TypedScope typedParent = ( TypedScope ) parent ; TypedScope scope = memoized . get ( root ) ; if ( scope != null ) { checkState ( typedParent == scope . getParent ( ) ) ; } else { scope = createScopeInternal ( root , typedParent ) ; memoized . put ( root , scope ) ; } return scope ; }
Creates a scope with all types declared . Declares newly discovered types and type properties in the type registry .
34,211
private void initializeModuleScope ( Node moduleBody , Module module , TypedScope moduleScope ) { if ( module . metadata ( ) . isGoogModule ( ) ) { declareExportsInModuleScope ( module , moduleBody , moduleScope ) ; markGoogModuleExportsAsConst ( module ) ; } }
Builds the beginning of a module - scope . This can be an ES module or a goog . module .
34,212
private void declareExportsInModuleScope ( Module googModule , Node moduleBody , TypedScope moduleScope ) { if ( ! googModule . namespace ( ) . containsKey ( Export . NAMESPACE ) ) { moduleScope . declare ( "exports" , googModule . metadata ( ) . rootNode ( ) , typeRegistry . createAnonymousObjectType ( null ) , compiler . getInput ( moduleBody . getInputId ( ) ) , false ) ; } }
Ensures that the name exports is declared in goog . module scope .
34,213
private void gatherAllProvides ( Node root ) { if ( ! processClosurePrimitives ) { return ; } Node externs = root . getFirstChild ( ) ; Node js = root . getSecondChild ( ) ; Map < String , ProvidedName > providedNames = new ProcessClosureProvidesAndRequires ( compiler , null , CheckLevel . OFF , true ) . collectProvidedNames ( externs , js ) ; for ( ProvidedName name : providedNames . values ( ) ) { if ( name . getCandidateDefinition ( ) != null ) { Node firstDefinitionNode = name . getCandidateDefinition ( ) ; if ( NodeUtil . isExprAssign ( firstDefinitionNode ) && firstDefinitionNode . getFirstFirstChild ( ) . isName ( ) ) { undeclaredNamesForClosure . add ( firstDefinitionNode . getFirstFirstChild ( ) ) ; } } else if ( name . getFirstProvideCall ( ) != null && NodeUtil . isExprCall ( name . getFirstProvideCall ( ) ) ) { providedNamesFromCall . put ( name . getFirstProvideCall ( ) , name ) ; } } }
Gathers all namespaces created by goog . provide and any definitions in code .
34,214
void patchGlobalScope ( TypedScope globalScope , Node scriptRoot ) { checkState ( scriptRoot . isScript ( ) ) ; checkNotNull ( globalScope ) ; checkState ( globalScope . isGlobal ( ) ) ; String scriptName = NodeUtil . getSourceName ( scriptRoot ) ; checkNotNull ( scriptName ) ; Predicate < Node > inScript = n -> scriptName . equals ( NodeUtil . getSourceName ( n ) ) ; escapedVarNames . removeIf ( var -> inScript . test ( var . getScopeRoot ( ) ) ) ; assignedVarNames . removeIf ( var -> inScript . test ( var . getScopeRoot ( ) ) ) ; functionsWithNonEmptyReturns . removeIf ( inScript ) ; new FirstOrderFunctionAnalyzer ( ) . process ( null , scriptRoot ) ; List < TypedVar > varsToRemove = new ArrayList < > ( ) ; for ( TypedVar oldVar : globalScope . getVarIterable ( ) ) { if ( scriptName . equals ( oldVar . getInputName ( ) ) ) { varsToRemove . add ( oldVar ) ; } } for ( TypedVar var : varsToRemove ) { String typeName = var . getName ( ) ; globalScope . undeclare ( var ) ; globalScope . getTypeOfThis ( ) . toObjectType ( ) . removeProperty ( typeName ) ; if ( typeRegistry . getType ( globalScope , typeName ) != null ) { typeRegistry . removeType ( globalScope , typeName ) ; } } NormalScopeBuilder scopeBuilder = new NormalScopeBuilder ( globalScope , null ) ; NodeTraversal . traverse ( compiler , scriptRoot , scopeBuilder ) ; }
Patches a given global scope by removing variables previously declared in a script and re - traversing a new version of that script .
34,215
void setDeferredType ( Node node , JSType type ) { node . setJSType ( type ) ; deferredSetTypes . add ( new DeferredSetType ( node , type ) ) ; }
Set the type for a node now and enqueue it to be updated with a resolved type later .
34,216
CharPriority [ ] reserveCharacters ( char [ ] chars , char [ ] reservedCharacters ) { if ( reservedCharacters == null || reservedCharacters . length == 0 ) { CharPriority [ ] result = new CharPriority [ chars . length ] ; for ( int i = 0 ; i < chars . length ; i ++ ) { result [ i ] = priorityLookupMap . get ( chars [ i ] ) ; } return result ; } Set < Character > charSet = new LinkedHashSet < > ( Chars . asList ( chars ) ) ; for ( char reservedCharacter : reservedCharacters ) { charSet . remove ( reservedCharacter ) ; } CharPriority [ ] result = new CharPriority [ charSet . size ( ) ] ; int index = 0 ; for ( char c : charSet ) { result [ index ++ ] = priorityLookupMap . get ( c ) ; } return result ; }
Provides the array of available characters based on the specified arrays .
34,217
private void checkPrefix ( String prefix ) { if ( prefix . length ( ) > 0 ) { if ( ! contains ( firstChars , prefix . charAt ( 0 ) ) ) { char [ ] chars = new char [ firstChars . length ] ; for ( int i = 0 ; i < chars . length ; i ++ ) { chars [ i ] = firstChars [ i ] . name ; } throw new IllegalArgumentException ( "prefix must start with one of: " + Arrays . toString ( chars ) ) ; } for ( int pos = 1 ; pos < prefix . length ( ) ; ++ pos ) { char [ ] chars = new char [ nonFirstChars . length ] ; for ( int i = 0 ; i < chars . length ; i ++ ) { chars [ i ] = nonFirstChars [ i ] . name ; } if ( ! contains ( nonFirstChars , prefix . charAt ( pos ) ) ) { throw new IllegalArgumentException ( "prefix has invalid characters, must be one of: " + Arrays . toString ( chars ) ) ; } } } }
Validates a name prefix .
34,218
public String generateNextName ( ) { String name ; do { name = prefix ; int i = nameCount ; if ( name . isEmpty ( ) ) { int pos = i % firstChars . length ; name = String . valueOf ( firstChars [ pos ] . name ) ; i /= firstChars . length ; } while ( i > 0 ) { i -- ; int pos = i % nonFirstChars . length ; name += nonFirstChars [ pos ] . name ; i /= nonFirstChars . length ; } nameCount ++ ; } while ( TokenStream . isKeyword ( name ) || reservedNames . contains ( name ) ) ; return name ; }
Generates the next short name .
34,219
private boolean fastAllPathsReturnCheck ( ControlFlowGraph < Node > cfg ) { for ( DiGraphEdge < Node , Branch > s : cfg . getImplicitReturn ( ) . getInEdges ( ) ) { Node n = s . getSource ( ) . getValue ( ) ; if ( ! n . isReturn ( ) && ! convention . isFunctionCallThatAlwaysThrows ( n ) ) { return false ; } } return true ; }
Fast check to see if all execution paths contain a return statement . May spuriously report that a return statement is missing .
34,220
private JSType getExplicitReturnTypeIfExpected ( Node scopeRoot ) { if ( ! scopeRoot . isFunction ( ) ) { return null ; } FunctionType scopeType = JSType . toMaybeFunctionType ( scopeRoot . getJSType ( ) ) ; if ( scopeType == null ) { return null ; } if ( isEmptyFunction ( scopeRoot ) ) { return null ; } if ( scopeType . isConstructor ( ) ) { return null ; } JSType returnType = scopeType . getReturnType ( ) ; if ( returnType == null ) { return null ; } if ( scopeRoot . isAsyncFunction ( ) ) { returnType = Promises . getTemplateTypeOfThenable ( compiler . getTypeRegistry ( ) , returnType ) ; } if ( ! isVoidOrUnknown ( returnType ) ) { return returnType ; } return null ; }
Determines if the given scope should explicitly return . All functions with non - void or non - unknown return types must have explicit returns .
34,221
private void convertAsyncGenerator ( NodeTraversal t , Node originalFunction ) { checkNotNull ( originalFunction ) ; checkState ( originalFunction . isAsyncGeneratorFunction ( ) ) ; Node asyncGeneratorWrapperRef = astFactory . createAsyncGeneratorWrapperReference ( originalFunction . getJSType ( ) , t . getScope ( ) ) ; Node innerFunction = astFactory . createEmptyAsyncGeneratorWrapperArgument ( asyncGeneratorWrapperRef . getJSType ( ) ) ; Node innerBlock = originalFunction . getLastChild ( ) ; originalFunction . removeChild ( innerBlock ) ; innerFunction . replaceChild ( innerFunction . getLastChild ( ) , innerBlock ) ; Node outerBlock = astFactory . createBlock ( astFactory . createReturn ( astFactory . createNewNode ( asyncGeneratorWrapperRef , astFactory . createCall ( innerFunction ) ) ) ) ; originalFunction . addChildToBack ( outerBlock ) ; originalFunction . setIsAsyncFunction ( false ) ; originalFunction . setIsGeneratorFunction ( false ) ; originalFunction . useSourceInfoIfMissingFromForTree ( originalFunction ) ; compiler . reportChangeToChangeScope ( originalFunction ) ; compiler . reportChangeToChangeScope ( innerFunction ) ; }
Moves the body of an async generator function into a nested generator function and removes the async and generator props from the original function .
34,222
private void convertAwaitOfAsyncGenerator ( NodeTraversal t , LexicalContext ctx , Node awaitNode ) { checkNotNull ( awaitNode ) ; checkState ( awaitNode . isAwait ( ) ) ; checkState ( ctx != null && ctx . function != null ) ; checkState ( ctx . function . isAsyncGeneratorFunction ( ) ) ; Node expression = awaitNode . removeFirstChild ( ) ; checkNotNull ( expression , "await needs an expression" ) ; Node newActionRecord = astFactory . createNewNode ( astFactory . createQName ( t . getScope ( ) , ACTION_RECORD_NAME ) , astFactory . createQName ( t . getScope ( ) , ACTION_ENUM_AWAIT ) , expression ) ; newActionRecord . useSourceInfoIfMissingFromForTree ( awaitNode ) ; awaitNode . addChildToFront ( newActionRecord ) ; awaitNode . setToken ( Token . YIELD ) ; }
Converts an await into a yield of an ActionRecord to perform AWAIT .
34,223
private void convertYieldOfAsyncGenerator ( NodeTraversal t , LexicalContext ctx , Node yieldNode ) { checkNotNull ( yieldNode ) ; checkState ( yieldNode . isYield ( ) ) ; checkState ( ctx != null && ctx . function != null ) ; checkState ( ctx . function . isAsyncGeneratorFunction ( ) ) ; Node expression = yieldNode . removeFirstChild ( ) ; Node newActionRecord = astFactory . createNewNode ( astFactory . createQName ( t . getScope ( ) , ACTION_RECORD_NAME ) ) ; if ( yieldNode . isYieldAll ( ) ) { checkNotNull ( expression ) ; newActionRecord . addChildToBack ( astFactory . createQName ( t . getScope ( ) , ACTION_ENUM_YIELD_STAR ) ) ; newActionRecord . addChildToBack ( expression ) ; } else { if ( expression == null ) { expression = NodeUtil . newUndefinedNode ( null ) ; } newActionRecord . addChildToBack ( astFactory . createQName ( t . getScope ( ) , ACTION_ENUM_YIELD ) ) ; newActionRecord . addChildToBack ( expression ) ; } newActionRecord . useSourceInfoIfMissingFromForTree ( yieldNode ) ; yieldNode . addChildToFront ( newActionRecord ) ; yieldNode . removeProp ( Node . YIELD_ALL ) ; }
Converts a yield into a yield of an ActionRecord to perform YIELD or YIELD_STAR .
34,224
private int getIntForType ( JSType type ) { if ( type != null && type . isGenericObjectType ( ) ) { type = type . toMaybeObjectType ( ) . getRawType ( ) ; } if ( intForType . containsKey ( type ) ) { return intForType . get ( type ) . intValue ( ) ; } int newInt = intForType . size ( ) + 1 ; intForType . put ( type , newInt ) ; return newInt ; }
Returns an integer that uniquely identifies a JSType .
34,225
@ SuppressWarnings ( "ReferenceEquality" ) private void computeRelatedTypesForNonUnionType ( JSType type ) { checkState ( ! type . isUnionType ( ) , type ) ; if ( relatedBitsets . containsKey ( type ) ) { return ; } JSTypeBitSet related = new JSTypeBitSet ( intForType . size ( ) ) ; relatedBitsets . put ( type , related ) ; related . set ( getIntForType ( type ) ) ; if ( type . isFunctionPrototypeType ( ) ) { FunctionType maybeCtor = type . toMaybeObjectType ( ) . getOwnerFunction ( ) ; if ( maybeCtor . isConstructor ( ) || maybeCtor . isInterface ( ) ) { addRelatedInstance ( maybeCtor , related ) ; } return ; } FunctionType constructor = type . toMaybeObjectType ( ) . getConstructor ( ) ; if ( constructor != null ) { for ( FunctionType subType : constructor . getDirectSubTypes ( ) ) { addRelatedInstance ( subType , related ) ; } } FunctionType fnType = type . toMaybeFunctionType ( ) ; if ( fnType != null ) { for ( FunctionType subType : fnType . getDirectSubTypes ( ) ) { if ( fnType == subType . getImplicitPrototype ( ) ) { addRelatedType ( subType , related ) ; } } } }
Adds subtypes - and implementors in the case of interfaces - of the type to its JSTypeBitSet of related types .
34,226
private void addRelatedInstance ( FunctionType constructor , JSTypeBitSet related ) { checkArgument ( constructor . hasInstanceType ( ) , "Constructor %s without instance type." , constructor ) ; ObjectType instanceType = constructor . getInstanceType ( ) ; addRelatedType ( instanceType , related ) ; }
Adds the instance of the given constructor its implicit prototype and all its related types to the given bit set .
34,227
private void addRelatedType ( JSType type , JSTypeBitSet related ) { computeRelatedTypesForNonUnionType ( type ) ; related . or ( relatedBitsets . get ( type ) ) ; }
Adds the given type and all its related types to the given bit set .
34,228
private void checkDescendantNames ( Name name , boolean nameIsDefined ) { if ( name . props != null ) { for ( Name prop : name . props ) { boolean propIsDefined = false ; if ( nameIsDefined ) { propIsDefined = ( ! propertyMustBeInitializedByFullName ( prop ) || prop . getGlobalSets ( ) + prop . getLocalSets ( ) > 0 ) ; } validateName ( prop , propIsDefined ) ; checkDescendantNames ( prop , propIsDefined ) ; } } }
Checks to make sure all the descendants of a name are defined if they are referenced .
34,229
private boolean checkForBadModuleReference ( Name name , Ref ref ) { JSModuleGraph moduleGraph = compiler . getModuleGraph ( ) ; if ( name . getGlobalSets ( ) == 0 || ref . type == Ref . Type . SET_FROM_GLOBAL ) { return false ; } if ( name . getGlobalSets ( ) == 1 ) { Ref declaration = checkNotNull ( name . getDeclaration ( ) ) ; return ! isSetFromPrecedingModule ( ref , declaration , moduleGraph ) ; } for ( Ref set : name . getRefs ( ) ) { if ( isSetFromPrecedingModule ( ref , set , moduleGraph ) ) { return false ; } } return true ; }
Returns true if this name is potentially referenced before being defined in a different module
34,230
private static boolean isSetFromPrecedingModule ( Ref originalRef , Ref set , JSModuleGraph moduleGraph ) { return set . type == Ref . Type . SET_FROM_GLOBAL && ( originalRef . getModule ( ) == set . getModule ( ) || moduleGraph . dependsOn ( originalRef . getModule ( ) , set . getModule ( ) ) ) ; }
Whether the set is in the global scope and occurs in a module the original ref depends on
34,231
private boolean propertyMustBeInitializedByFullName ( Name name ) { if ( name . getParent ( ) == null ) { return false ; } if ( isNameUnsafelyAliased ( name . getParent ( ) ) ) { return false ; } if ( objectPrototypeProps . contains ( name . getBaseName ( ) ) ) { return false ; } if ( name . getParent ( ) . isObjectLiteral ( ) ) { return true ; } if ( name . getParent ( ) . isClass ( ) ) { return ! hasSuperclass ( name . getParent ( ) ) ; } return name . getParent ( ) . isFunction ( ) && name . getParent ( ) . isDeclaredType ( ) && ! functionPrototypeProps . contains ( name . getBaseName ( ) ) ; }
The input name is a property . Check whether this property must be initialized with its full qualified name .
34,232
private boolean hasSuperclass ( Name es6Class ) { Node decl = es6Class . getDeclaration ( ) . getNode ( ) ; Node classNode = NodeUtil . getRValueOfLValue ( decl ) ; checkState ( classNode . isClass ( ) , classNode ) ; Node superclass = classNode . getSecondChild ( ) ; return ! superclass . isEmpty ( ) ; }
Returns whether the given ES6 class extends something .
34,233
ScopedName getClosureNamespaceTypeFromCall ( Node googRequire ) { if ( moduleMap == null ) { return null ; } String moduleId = googRequire . getSecondChild ( ) . getString ( ) ; Module module = moduleMap . getClosureModule ( moduleId ) ; if ( module == null ) { return null ; } switch ( module . metadata ( ) . moduleType ( ) ) { case GOOG_PROVIDE : Node provide = module . metadata ( ) . rootNode ( ) ; if ( provide != null && provide . isScript ( ) ) { return ScopedName . of ( moduleId , provide . getGrandparent ( ) ) ; } else { return null ; } case GOOG_MODULE : case LEGACY_GOOG_MODULE : Node scopeRoot = getGoogModuleScopeRoot ( module ) ; return scopeRoot != null ? ScopedName . of ( "exports" , scopeRoot ) : null ; case ES6_MODULE : throw new IllegalStateException ( "Type checking ES modules not yet supported" ) ; case COMMON_JS : throw new IllegalStateException ( "Type checking CommonJs modules not yet supported" ) ; case SCRIPT : throw new IllegalStateException ( "Cannot import a name from a SCRIPT" ) ; } throw new AssertionError ( ) ; }
Attempts to look up the type of a Closure namespace from a require call
34,234
private Node initTemplate ( Node templateFunctionNode ) { Node prepped = templateFunctionNode . cloneTree ( ) ; prepTemplatePlaceholders ( prepped ) ; Node body = prepped . getLastChild ( ) ; Node startNode ; if ( body . hasOneChild ( ) && body . getFirstChild ( ) . isExprResult ( ) ) { startNode = body . getFirstFirstChild ( ) ; } else { startNode = body . getFirstChild ( ) ; } for ( int i = 0 ; i < templateLocals . size ( ) ; i ++ ) { this . localVarMatches . add ( null ) ; } for ( int i = 0 ; i < templateParams . size ( ) ; i ++ ) { this . paramNodeMatches . add ( null ) ; } return startNode ; }
Prepare an template AST to use when performing matches .
34,235
private void prepTemplatePlaceholders ( Node fn ) { final List < String > locals = templateLocals ; final List < String > params = templateParams ; final Map < String , JSType > paramTypes = new HashMap < > ( ) ; String fnName = fn . getFirstChild ( ) . getString ( ) ; fn . getFirstChild ( ) . setString ( "" ) ; Node templateParametersNode = fn . getSecondChild ( ) ; JSDocInfo info = NodeUtil . getBestJSDocInfo ( fn ) ; if ( templateParametersNode . hasChildren ( ) ) { Preconditions . checkNotNull ( info , "Missing JSDoc declaration for template function %s" , fnName ) ; } for ( Node paramNode : templateParametersNode . children ( ) ) { String name = paramNode . getString ( ) ; JSTypeExpression expression = info . getParameterType ( name ) ; Preconditions . checkNotNull ( expression , "Missing JSDoc for parameter %s of template function %s" , name , fnName ) ; JSType type = typeRegistry . evaluateTypeExpressionInGlobalScope ( expression ) ; checkNotNull ( type ) ; params . add ( name ) ; paramTypes . put ( name , type ) ; } traverse ( fn , new Visitor ( ) { public void visit ( Node n ) { if ( n . isName ( ) ) { Node parent = n . getParent ( ) ; String name = n . getString ( ) ; if ( ! name . isEmpty ( ) && parent . isVar ( ) && ! locals . contains ( name ) ) { locals . add ( n . getString ( ) ) ; } if ( params . contains ( name ) ) { JSType type = paramTypes . get ( name ) ; boolean isStringLiteral = type . isStringValueType ( ) && name . startsWith ( "string_literal" ) ; replaceNodeInPlace ( n , createTemplateParameterNode ( params . indexOf ( name ) , type , isStringLiteral ) ) ; } else if ( locals . contains ( name ) ) { replaceNodeInPlace ( n , createTemplateLocalNameNode ( locals . indexOf ( name ) ) ) ; } } } } ) ; }
Build parameter and local information for the template and replace the references in the template fn with placeholder nodes use to facility matching .
34,236
private Node createTemplateParameterNode ( int index , JSType type , boolean isStringLiteral ) { checkState ( index >= 0 ) ; checkNotNull ( type ) ; Node n = Node . newNumber ( index ) ; if ( isStringLiteral ) { n . setToken ( TEMPLATE_STRING_LITERAL ) ; } else { n . setToken ( TEMPLATE_TYPE_PARAM ) ; } n . setJSType ( type ) ; return n ; }
Creates a template parameter or string literal template node .
34,237
private boolean matchesTemplateShape ( Node template , Node ast ) { while ( template != null ) { if ( ast == null || ! matchesNodeShape ( template , ast ) ) { return false ; } template = template . getNext ( ) ; ast = ast . getNext ( ) ; } return true ; }
Returns whether the template matches an AST structure node starting with node taking into account the template parameters that were provided to this matcher . Here only the template shape is checked template local declarations and parameters are checked later .
34,238
private boolean matchesNode ( Node template , Node ast ) { if ( isTemplateParameterNode ( template ) ) { int paramIndex = ( int ) ( template . getDouble ( ) ) ; Node previousMatch = paramNodeMatches . get ( paramIndex ) ; if ( previousMatch != null ) { return ast . isEquivalentTo ( previousMatch ) ; } JSType templateType = template . getJSType ( ) ; checkNotNull ( templateType , "null template parameter type." ) ; if ( isUnresolvedType ( templateType ) ) { return false ; } MatchResult matchResult = typeMatchingStrategy . match ( templateType , ast . getJSType ( ) ) ; isLooseMatch = matchResult . isLooseMatch ( ) ; boolean isMatch = matchResult . isMatch ( ) ; if ( isMatch && previousMatch == null ) { paramNodeMatches . set ( paramIndex , ast ) ; } return isMatch ; } else if ( isTemplateLocalNameNode ( template ) ) { int paramIndex = ( int ) ( template . getDouble ( ) ) ; boolean previouslyMatched = this . localVarMatches . get ( paramIndex ) != null ; if ( previouslyMatched ) { return ast . getString ( ) . equals ( this . localVarMatches . get ( paramIndex ) ) ; } else { String originalName = ast . getOriginalName ( ) ; String name = ( originalName != null ) ? originalName : ast . getString ( ) ; this . localVarMatches . set ( paramIndex , name ) ; } } else if ( isTemplateParameterStringLiteralNode ( template ) ) { int paramIndex = ( int ) ( template . getDouble ( ) ) ; Node previousMatch = paramNodeMatches . get ( paramIndex ) ; if ( previousMatch != null ) { return ast . isEquivalentTo ( previousMatch ) ; } if ( NodeUtil . isSomeCompileTimeConstStringValue ( ast ) ) { paramNodeMatches . set ( paramIndex , ast ) ; return true ; } return false ; } Node templateChild = template . getFirstChild ( ) ; Node astChild = ast . getFirstChild ( ) ; while ( templateChild != null ) { if ( ! matchesNode ( templateChild , astChild ) ) { return false ; } templateChild = templateChild . getNext ( ) ; astChild = astChild . getNext ( ) ; } return true ; }
Returns whether two nodes are equivalent taking into account the template parameters that were provided to this matcher . If the template comparison node is a parameter node then only the types of the node must match . If the template node is a string literal only match string literals . Otherwise the node must be equal and the child nodes must be equivalent according to the same function . This differs from the built in Node equivalence function with the special comparison .
34,239
private boolean hasOverriddenNativeProperty ( String propertyName ) { if ( isNativeObjectType ( ) ) { return false ; } JSType propertyType = getPropertyType ( propertyName ) ; ObjectType nativeType = isFunctionType ( ) ? registry . getNativeObjectType ( JSTypeNative . FUNCTION_PROTOTYPE ) : registry . getNativeObjectType ( JSTypeNative . OBJECT_PROTOTYPE ) ; JSType nativePropertyType = nativeType . getPropertyType ( propertyName ) ; return propertyType != nativePropertyType ; }
Given the name of a native object property checks whether the property is present on the object and different from the native one .
34,240
private static boolean isSubtype ( ObjectType typeA , RecordType typeB , ImplCache implicitImplCache , SubtypingMode subtypingMode ) { MatchStatus cached = implicitImplCache . checkCache ( typeA , typeB ) ; if ( cached != null ) { return cached . subtypeValue ( ) ; } boolean result = isStructuralSubtypeHelper ( typeA , typeB , implicitImplCache , subtypingMode , ALL_PROPS_ARE_REQUIRED ) ; return implicitImplCache . updateCache ( typeA , typeB , MatchStatus . valueOf ( result ) ) ; }
Determines if typeA is a subtype of typeB
34,241
public synchronized SourceMapConsumerV3 getSourceMap ( ErrorManager errorManager ) { if ( ! cached ) { cached = true ; String sourceMapPath = sourceFile . getOriginalPath ( ) ; try { String sourceMapContents = sourceFile . getCode ( ) ; SourceMapConsumerV3 consumer = new SourceMapConsumerV3 ( ) ; consumer . parse ( sourceMapContents ) ; parsedSourceMap = consumer ; } catch ( IOException e ) { JSError error = JSError . make ( SourceMapInput . SOURCEMAP_RESOLVE_FAILED , sourceMapPath , e . getMessage ( ) ) ; errorManager . report ( error . getDefaultLevel ( ) , error ) ; } catch ( SourceMapParseException e ) { JSError error = JSError . make ( SourceMapInput . SOURCEMAP_PARSE_FAILED , sourceMapPath , e . getMessage ( ) ) ; errorManager . report ( error . getDefaultLevel ( ) , error ) ; } } return parsedSourceMap ; }
Gets the source map reading from disk and parsing if necessary . Returns null if the sourcemap cannot be resolved or is malformed .
34,242
private static String getLastPartOfQualifiedName ( Node n ) { if ( n . isName ( ) ) { return n . getString ( ) ; } else if ( n . isGetProp ( ) ) { return n . getLastChild ( ) . getString ( ) ; } return null ; }
or null for this and super .
34,243
private void moveGlobalSymbols ( Collection < GlobalSymbol > globalSymbols ) { for ( GlobalSymbolCycle globalSymbolCycle : new OrderAndCombineGlobalSymbols ( globalSymbols ) . orderAndCombine ( ) ) { globalSymbolCycle . moveDeclarationStatements ( ) ; } }
Moves all of the declaration statements that can move to their best possible chunk location .
34,244
public void loadRefasterJsTemplate ( String refasterjsTemplate ) throws IOException { checkState ( templateJs == null , "Can't load RefasterJs template since a template is already loaded." ) ; this . templateJs = Thread . currentThread ( ) . getContextClassLoader ( ) . getResource ( refasterjsTemplate ) != null ? Resources . toString ( Resources . getResource ( refasterjsTemplate ) , UTF_8 ) : Files . asCharSource ( new File ( refasterjsTemplate ) , UTF_8 ) . read ( ) ; }
Loads the RefasterJs template . This must be called before the scanner is used .
34,245
private Node transformNode ( Node templateNode , Map < String , Node > templateNodeToMatchMap , Map < String , String > shortNames ) { Node clone = templateNode . cloneNode ( ) ; if ( templateNode . isName ( ) ) { String name = templateNode . getString ( ) ; if ( templateNodeToMatchMap . containsKey ( name ) ) { Node templateMatch = templateNodeToMatchMap . get ( name ) ; Preconditions . checkNotNull ( templateMatch , "Match for %s is null" , name ) ; if ( templateNode . getParent ( ) . isVar ( ) ) { clone . setString ( templateMatch . getString ( ) ) ; } else { return templateMatch . cloneTree ( ) ; } } } else if ( templateNode . isCall ( ) && templateNode . getBooleanProp ( Node . FREE_CALL ) && templateNode . getFirstChild ( ) . isName ( ) ) { String name = templateNode . getFirstChild ( ) . getString ( ) ; if ( templateNodeToMatchMap . containsKey ( name ) ) { clone . putBooleanProp ( Node . FREE_CALL , false ) ; } } if ( templateNode . isQualifiedName ( ) ) { String name = templateNode . getQualifiedName ( ) ; if ( shortNames . containsKey ( name ) ) { String shortName = shortNames . get ( name ) ; if ( ! shortName . equals ( name ) ) { return IR . name ( shortNames . get ( name ) ) ; } } } for ( Node child : templateNode . children ( ) ) { clone . addChildToBack ( transformNode ( child , templateNodeToMatchMap , shortNames ) ) ; } return clone ; }
Transforms the template node to a replacement node by mapping the template names to the ones that were matched against in the JsSourceMatcher .
34,246
public JSType build ( ) { if ( isEmpty ) { return registry . getNativeObjectType ( JSTypeNative . OBJECT_TYPE ) ; } ImmutableSortedMap . Builder < String , RecordProperty > m = ImmutableSortedMap . naturalOrder ( ) ; m . putAll ( this . properties ) ; return new RecordType ( registry , m . build ( ) , isDeclared ) ; }
Creates a record . Fails if any duplicate property names were added .
34,247
private List < Node > createDependenciesList ( Node n ) { checkArgument ( n . isFunction ( ) ) ; Node params = NodeUtil . getFunctionParameters ( n ) ; if ( params != null ) { return createStringsFromParamList ( params ) ; } return new ArrayList < > ( ) ; }
Given a FUNCTION node returns array of STRING nodes representing function parameters .
34,248
private List < Node > createStringsFromParamList ( Node params ) { Node param = params . getFirstChild ( ) ; ArrayList < Node > names = new ArrayList < > ( ) ; while ( param != null ) { if ( param . isName ( ) ) { names . add ( IR . string ( param . getString ( ) ) . srcref ( param ) ) ; } else if ( param . isDestructuringPattern ( ) ) { compiler . report ( JSError . make ( param , INJECTED_FUNCTION_HAS_DESTRUCTURED_PARAM ) ) ; return new ArrayList < > ( ) ; } else if ( param . isDefaultValue ( ) ) { compiler . report ( JSError . make ( param , INJECTED_FUNCTION_HAS_DEFAULT_VALUE ) ) ; return new ArrayList < > ( ) ; } param = param . getNext ( ) ; } return names ; }
Given a PARAM_LIST node creates an array of corresponding STRING nodes .
34,249
private void addNode ( Node n ) { Node target = null ; Node fn = null ; String name = null ; switch ( n . getToken ( ) ) { case ASSIGN : if ( ! n . getFirstChild ( ) . isQualifiedName ( ) ) { compiler . report ( JSError . make ( n , INJECTED_FUNCTION_ON_NON_QNAME ) ) ; return ; } name = n . getFirstChild ( ) . getQualifiedName ( ) ; fn = n ; while ( fn . isAssign ( ) ) { fn = fn . getLastChild ( ) ; } target = n . getParent ( ) ; break ; case FUNCTION : name = NodeUtil . getName ( n ) ; fn = n ; target = n ; if ( n . getParent ( ) . isAssign ( ) && n . getParent ( ) . getJSDocInfo ( ) . isNgInject ( ) ) { return ; } break ; case VAR : case LET : case CONST : name = n . getFirstChild ( ) . getString ( ) ; fn = getDeclarationRValue ( n ) ; target = n ; break ; case MEMBER_FUNCTION_DEF : Node parent = n . getParent ( ) ; if ( parent . isClassMembers ( ) ) { Node classNode = parent . getParent ( ) ; String midPart = n . isStaticMember ( ) ? "." : ".prototype." ; name = NodeUtil . getName ( classNode ) + midPart + n . getString ( ) ; if ( NodeUtil . isEs6ConstructorMemberFunctionDef ( n ) ) { name = NodeUtil . getName ( classNode ) ; } fn = n . getFirstChild ( ) ; if ( classNode . getParent ( ) . isAssign ( ) || classNode . getParent ( ) . isName ( ) ) { target = classNode . getGrandparent ( ) ; } else { target = classNode ; } } break ; default : break ; } if ( fn == null || ! fn . isFunction ( ) ) { compiler . report ( JSError . make ( n , INJECT_NON_FUNCTION_ERROR ) ) ; return ; } if ( ! target . getParent ( ) . isScript ( ) && ! target . getParent ( ) . isBlock ( ) && ! target . getParent ( ) . isModuleBody ( ) ) { compiler . report ( JSError . make ( n , INJECT_IN_NON_GLOBAL_OR_BLOCK_ERROR ) ) ; return ; } checkNotNull ( name ) ; injectables . add ( new NodeContext ( name , n , fn , target ) ) ; }
Add node to the list of injectables .
34,250
@ GwtIncompatible ( "Unnecessary" ) private boolean isOutputInJson ( ) { return config . jsonStreamMode == JsonStreamMode . OUT || config . jsonStreamMode == JsonStreamMode . BOTH ; }
Returns whether output should be a JSON stream .
34,251
@ GwtIncompatible ( "Unnecessary" ) private List < SourceFile > createInputs ( List < FlagEntry < JsSourceType > > files , boolean allowStdIn , List < JsModuleSpec > jsModuleSpecs ) throws IOException { return createInputs ( files , null , allowStdIn , jsModuleSpecs ) ; }
Creates inputs from a list of files .
34,252
@ GwtIncompatible ( "Unnecessary" ) private List < SourceFile > createInputs ( List < FlagEntry < JsSourceType > > files , List < JsonFileSpec > jsonFiles , List < JsModuleSpec > jsModuleSpecs ) throws IOException { return createInputs ( files , jsonFiles , false , jsModuleSpecs ) ; }
Creates inputs from a list of source files and json files .
34,253
@ GwtIncompatible ( "Unnecessary" ) private List < SourceFile > createSourceInputs ( List < JsModuleSpec > jsModuleSpecs , List < FlagEntry < JsSourceType > > files , List < JsonFileSpec > jsonFiles , List < String > moduleRoots ) throws IOException { if ( isInTestMode ( ) ) { return inputsSupplierForTesting != null ? inputsSupplierForTesting . get ( ) : null ; } if ( files . isEmpty ( ) && jsonFiles == null ) { files = ImmutableList . of ( new FlagEntry < JsSourceType > ( JsSourceType . JS , "-" ) ) ; } for ( JSError error : deduplicateIjsFiles ( files , moduleRoots , ! jsModuleSpecs . isEmpty ( ) ) ) { compiler . report ( error ) ; } try { if ( jsonFiles != null ) { return createInputs ( files , jsonFiles , jsModuleSpecs ) ; } else { return createInputs ( files , true , jsModuleSpecs ) ; } } catch ( FlagUsageException e ) { throw new FlagUsageException ( "Bad --js flag. " + e . getMessage ( ) ) ; } }
Creates JS source code inputs from a list of files .
34,254
@ GwtIncompatible ( "Unnecessary" ) private List < SourceFile > createExternInputs ( List < String > files ) throws IOException { List < FlagEntry < JsSourceType > > externFiles = new ArrayList < > ( ) ; for ( String file : files ) { externFiles . add ( new FlagEntry < JsSourceType > ( JsSourceType . EXTERN , file ) ) ; } try { return createInputs ( externFiles , false , new ArrayList < JsModuleSpec > ( ) ) ; } catch ( FlagUsageException e ) { throw new FlagUsageException ( "Bad --externs flag. " + e . getMessage ( ) ) ; } }
Creates JS extern inputs from a list of files .
34,255
public static List < JSModule > createJsModules ( List < JsModuleSpec > specs , List < SourceFile > inputs ) throws IOException { checkState ( specs != null ) ; checkState ( ! specs . isEmpty ( ) ) ; checkState ( inputs != null ) ; List < String > moduleNames = new ArrayList < > ( specs . size ( ) ) ; Map < String , JSModule > modulesByName = new LinkedHashMap < > ( ) ; Map < String , Integer > modulesFileCountMap = new LinkedHashMap < > ( ) ; int numJsFilesExpected = 0 ; int minJsFilesRequired = 0 ; for ( JsModuleSpec spec : specs ) { if ( modulesByName . containsKey ( spec . name ) ) { throw new FlagUsageException ( "Duplicate module name: " + spec . name ) ; } JSModule module = new JSModule ( spec . name ) ; for ( String dep : spec . deps ) { JSModule other = modulesByName . get ( dep ) ; if ( other == null ) { throw new FlagUsageException ( "Module '" + spec . name + "' depends on unknown module '" + dep + "'. Be sure to list modules in dependency order." ) ; } module . addDependency ( other ) ; } if ( spec . numJsFiles < 0 ) { numJsFilesExpected = - 1 ; } else { minJsFilesRequired += spec . numJsFiles ; } if ( numJsFilesExpected >= 0 ) { numJsFilesExpected += spec . numJsFiles ; } moduleNames . add ( 0 , spec . name ) ; modulesFileCountMap . put ( spec . name , spec . numJsFiles ) ; modulesByName . put ( spec . name , module ) ; } final int totalNumJsFiles = inputs . size ( ) ; if ( numJsFilesExpected >= 0 || minJsFilesRequired > totalNumJsFiles ) { if ( minJsFilesRequired > totalNumJsFiles ) { numJsFilesExpected = minJsFilesRequired ; } if ( numJsFilesExpected > totalNumJsFiles ) { throw new FlagUsageException ( "Not enough JS files specified. Expected " + numJsFilesExpected + " but found " + totalNumJsFiles ) ; } else if ( numJsFilesExpected < totalNumJsFiles ) { throw new FlagUsageException ( "Too many JS files specified. Expected " + numJsFilesExpected + " but found " + totalNumJsFiles ) ; } } int numJsFilesLeft = totalNumJsFiles ; int moduleIndex = 0 ; for ( String moduleName : moduleNames ) { int numJsFiles = modulesFileCountMap . get ( moduleName ) ; JSModule module = modulesByName . get ( moduleName ) ; if ( moduleIndex == moduleNames . size ( ) - 1 && numJsFiles == - 1 ) { numJsFiles = numJsFilesLeft ; } List < SourceFile > moduleFiles = inputs . subList ( numJsFilesLeft - numJsFiles , numJsFilesLeft ) ; for ( SourceFile input : moduleFiles ) { module . add ( input ) ; } numJsFilesLeft -= numJsFiles ; moduleIndex ++ ; } return new ArrayList < > ( modulesByName . values ( ) ) ; }
Creates module objects from a list of js module specifications .
34,256
public static Map < String , String > parseModuleWrappers ( List < String > specs , Iterable < JSModule > chunks ) { checkState ( specs != null ) ; Map < String , String > wrappers = new HashMap < > ( ) ; for ( JSModule c : chunks ) { wrappers . put ( c . getName ( ) , "" ) ; } for ( String spec : specs ) { int pos = spec . indexOf ( ':' ) ; if ( pos == - 1 ) { throw new FlagUsageException ( "Expected module wrapper to have " + "<name>:<wrapper> format: " + spec ) ; } String name = spec . substring ( 0 , pos ) ; if ( ! wrappers . containsKey ( name ) ) { throw new FlagUsageException ( "Unknown module: '" + name + "'" ) ; } String wrapper = spec . substring ( pos + 1 ) ; wrapper = wrapper . replace ( "%output%" , "%s" ) . replace ( "%n%" , "\n" ) ; if ( ! wrapper . contains ( "%s" ) ) { throw new FlagUsageException ( "No %s placeholder in module wrapper: '" + wrapper + "'" ) ; } wrappers . put ( name , wrapper ) ; } return wrappers ; }
Parses module wrapper specifications .
34,257
@ GwtIncompatible ( "Unnecessary" ) private static void maybeCreateDirsForPath ( String pathPrefix ) { if ( ! Strings . isNullOrEmpty ( pathPrefix ) ) { String dirName = pathPrefix . charAt ( pathPrefix . length ( ) - 1 ) == File . separatorChar ? pathPrefix . substring ( 0 , pathPrefix . length ( ) - 1 ) : new File ( pathPrefix ) . getParent ( ) ; if ( dirName != null ) { new File ( dirName ) . mkdirs ( ) ; } } }
Creates any directories necessary to write a file that will have a given path prefix .
34,258
@ GwtIncompatible ( "Unnecessary" ) int processResults ( Result result , List < JSModule > modules , B options ) throws IOException { if ( config . printPassGraph ) { if ( compiler . getRoot ( ) == null ) { return 1 ; } else { Appendable jsOutput = createDefaultOutput ( ) ; jsOutput . append ( DotFormatter . toDot ( compiler . getPassConfig ( ) . getPassGraph ( ) ) ) ; jsOutput . append ( '\n' ) ; closeAppendable ( jsOutput ) ; return 0 ; } } if ( config . printAst ) { if ( compiler . getRoot ( ) == null ) { return 1 ; } else { Appendable jsOutput = createDefaultOutput ( ) ; ControlFlowGraph < Node > cfg = compiler . computeCFG ( ) ; DotFormatter . appendDot ( compiler . getRoot ( ) . getLastChild ( ) , cfg , jsOutput ) ; jsOutput . append ( '\n' ) ; closeAppendable ( jsOutput ) ; return 0 ; } } if ( config . printTree ) { if ( compiler . getRoot ( ) == null ) { compiler . report ( JSError . make ( NO_TREE_GENERATED_ERROR ) ) ; return 1 ; } else { Appendable jsOutput = createDefaultOutput ( ) ; compiler . getRoot ( ) . appendStringTree ( jsOutput ) ; jsOutput . append ( "\n" ) ; closeAppendable ( jsOutput ) ; return 0 ; } } if ( config . skipNormalOutputs ) { outputManifest ( ) ; outputBundle ( ) ; outputModuleGraphJson ( ) ; return 0 ; } else if ( options . outputJs != OutputJs . NONE && result . success ) { outputModuleGraphJson ( ) ; if ( modules == null ) { outputSingleBinary ( options ) ; if ( ! isOutputInJson ( ) ) { outputSourceMap ( options , config . jsOutputFile ) ; } } else { DiagnosticType error = outputModuleBinaryAndSourceMaps ( compiler . getModules ( ) , options ) ; if ( error != null ) { compiler . report ( JSError . make ( error ) ) ; return 1 ; } } if ( options . externExportsPath != null ) { try ( Writer eeOut = openExternExportsStream ( options , config . jsOutputFile ) ) { eeOut . append ( result . externExport ) ; } } outputNameMaps ( ) ; outputStringMap ( ) ; outputManifest ( ) ; outputBundle ( ) ; if ( isOutputInJson ( ) ) { outputJsonStream ( ) ; } } return Math . min ( result . errors . size ( ) , 0x7f ) ; }
Processes the results of the compile job and returns an error code .
34,259
@ GwtIncompatible ( "Unnecessary" ) JsonFileSpec createJsonFile ( B options , String outputMarker , Function < String , String > escaper ) throws IOException { Appendable jsOutput = new StringBuilder ( ) ; writeOutput ( jsOutput , compiler , ( JSModule ) null , config . outputWrapper , outputMarker , escaper ) ; JsonFileSpec jsonOutput = new JsonFileSpec ( jsOutput . toString ( ) , Strings . isNullOrEmpty ( config . jsOutputFile ) ? "compiled.js" : config . jsOutputFile ) ; if ( ! Strings . isNullOrEmpty ( options . sourceMapOutputPath ) ) { StringBuilder sourcemap = new StringBuilder ( ) ; compiler . getSourceMap ( ) . appendTo ( sourcemap , jsonOutput . getPath ( ) ) ; jsonOutput . setSourceMap ( sourcemap . toString ( ) ) ; } return jsonOutput ; }
Save the compiler output to a JsonFileSpec to be later written to stdout
34,260
@ GwtIncompatible ( "Unnecessary" ) private JsonFileSpec createJsonFileFromModule ( JSModule module ) throws IOException { compiler . resetAndIntitializeSourceMap ( ) ; StringBuilder output = new StringBuilder ( ) ; writeModuleOutput ( output , module ) ; JsonFileSpec jsonFile = new JsonFileSpec ( output . toString ( ) , getModuleOutputFileName ( module ) ) ; StringBuilder moduleSourceMap = new StringBuilder ( ) ; compiler . getSourceMap ( ) . appendTo ( moduleSourceMap , getModuleOutputFileName ( module ) ) ; jsonFile . setSourceMap ( moduleSourceMap . toString ( ) ) ; return jsonFile ; }
Given an output module convert it to a JSONFileSpec with associated sourcemap
34,261
@ GwtIncompatible ( "Unnecessary" ) private Charset getInputCharset ( ) { if ( ! config . charset . isEmpty ( ) ) { if ( ! Charset . isSupported ( config . charset ) ) { throw new FlagUsageException ( config . charset + " is not a valid charset name." ) ; } return Charset . forName ( config . charset ) ; } return UTF_8 ; }
Query the flag for the input charset and return a Charset object representing the selection .
34,262
@ GwtIncompatible ( "Unnecessary" ) private Charset getLegacyOutputCharset ( ) { if ( ! config . charset . isEmpty ( ) ) { if ( ! Charset . isSupported ( config . charset ) ) { throw new FlagUsageException ( config . charset + " is not a valid charset name." ) ; } return Charset . forName ( config . charset ) ; } return US_ASCII ; }
Query the flag for the output charset .
34,263
@ GwtIncompatible ( "Unnecessary" ) private boolean shouldGenerateMapPerModule ( B options ) { return options . sourceMapOutputPath != null && options . sourceMapOutputPath . contains ( "%outname%" ) ; }
Returns true if and only if a source map file should be generated for each module as opposed to one unified map . This is specified by having the source map pattern include the %outname% variable .
34,264
@ GwtIncompatible ( "Unnecessary" ) private Writer openExternExportsStream ( B options , String path ) throws IOException { if ( options . externExportsPath == null ) { return null ; } String exPath = options . externExportsPath ; if ( ! exPath . contains ( File . separator ) ) { File outputFile = new File ( path ) ; exPath = outputFile . getParent ( ) + File . separatorChar + exPath ; } return fileNameToOutputWriter2 ( exPath ) ; }
Returns a stream for outputting the generated externs file .
34,265
@ GwtIncompatible ( "Unnecessary" ) private String expandCommandLinePath ( String path , JSModule forModule ) { String sub ; if ( forModule != null ) { sub = config . moduleOutputPathPrefix + forModule . getName ( ) + ".js" ; } else if ( ! config . module . isEmpty ( ) ) { sub = config . moduleOutputPathPrefix ; } else { sub = config . jsOutputFile ; } return path . replace ( "%outname%" , sub ) ; }
Expand a file path specified on the command - line .
34,266
@ GwtIncompatible ( "Unnecessary" ) String expandSourceMapPath ( B options , JSModule forModule ) { if ( Strings . isNullOrEmpty ( options . sourceMapOutputPath ) ) { return null ; } return expandCommandLinePath ( options . sourceMapOutputPath , forModule ) ; }
Expansion function for source map .
34,267
@ GwtIncompatible ( "Unnecessary" ) protected OutputStream filenameToOutputStream ( String fileName ) throws IOException { if ( fileName == null ) { return null ; } return new FileOutputStream ( fileName ) ; }
Converts a file name into a Outputstream . Returns null if the file name is null .
34,268
@ GwtIncompatible ( "Unnecessary" ) private Writer streamToLegacyOutputWriter ( OutputStream stream ) throws IOException { if ( legacyOutputCharset == null ) { return new BufferedWriter ( new OutputStreamWriter ( stream , UTF_8 ) ) ; } else { return new BufferedWriter ( new OutputStreamWriter ( stream , legacyOutputCharset ) ) ; } }
Create a writer with the legacy output charset .
34,269
@ GwtIncompatible ( "Unnecessary" ) private Writer streamToOutputWriter2 ( OutputStream stream ) { if ( outputCharset2 == null ) { return new BufferedWriter ( new OutputStreamWriter ( stream , UTF_8 ) ) ; } else { return new BufferedWriter ( new OutputStreamWriter ( stream , outputCharset2 ) ) ; } }
Create a writer with the newer output charset .
34,270
@ GwtIncompatible ( "Unnecessary" ) private void outputSourceMap ( B options , String associatedName ) throws IOException { if ( Strings . isNullOrEmpty ( options . sourceMapOutputPath ) || options . sourceMapOutputPath . equals ( "/dev/null" ) ) { return ; } String outName = expandSourceMapPath ( options , null ) ; maybeCreateDirsForPath ( outName ) ; try ( Writer out = fileNameToOutputWriter2 ( outName ) ) { compiler . getSourceMap ( ) . appendTo ( out , associatedName ) ; } }
Outputs the source map found in the compiler to the proper path if one exists .
34,271
@ GwtIncompatible ( "Unnecessary" ) private void outputNameMaps ( ) throws IOException { String propertyMapOutputPath = null ; String variableMapOutputPath = null ; if ( config . createNameMapFiles ) { String basePath = getMapPath ( config . jsOutputFile ) ; propertyMapOutputPath = basePath + "_props_map.out" ; variableMapOutputPath = basePath + "_vars_map.out" ; } if ( ! config . variableMapOutputFile . isEmpty ( ) ) { if ( variableMapOutputPath != null ) { throw new FlagUsageException ( "The flags variable_map_output_file and " + "create_name_map_files cannot both be used simultaneously." ) ; } variableMapOutputPath = config . variableMapOutputFile ; } if ( ! config . propertyMapOutputFile . isEmpty ( ) ) { if ( propertyMapOutputPath != null ) { throw new FlagUsageException ( "The flags property_map_output_file and " + "create_name_map_files cannot both be used simultaneously." ) ; } propertyMapOutputPath = config . propertyMapOutputFile ; } if ( variableMapOutputPath != null && compiler . getVariableMap ( ) != null ) { compiler . getVariableMap ( ) . save ( variableMapOutputPath ) ; } if ( propertyMapOutputPath != null && compiler . getPropertyMap ( ) != null ) { compiler . getPropertyMap ( ) . save ( propertyMapOutputPath ) ; } }
Outputs the variable and property name maps for the specified compiler if the proper FLAGS are set .
34,272
public static void createDefineOrTweakReplacements ( List < String > definitions , CompilerOptions options , boolean tweaks ) { for ( String override : definitions ) { String [ ] assignment = override . split ( "=" , 2 ) ; String defName = assignment [ 0 ] ; if ( defName . length ( ) > 0 ) { String defValue = assignment . length == 1 ? "true" : assignment [ 1 ] ; boolean isTrue = defValue . equals ( "true" ) ; boolean isFalse = defValue . equals ( "false" ) ; if ( isTrue || isFalse ) { if ( tweaks ) { options . setTweakToBooleanLiteral ( defName , isTrue ) ; } else { options . setDefineToBooleanLiteral ( defName , isTrue ) ; } continue ; } else if ( defValue . length ( ) > 1 && ( ( defValue . charAt ( 0 ) == '\'' && defValue . charAt ( defValue . length ( ) - 1 ) == '\'' ) || ( defValue . charAt ( 0 ) == '\"' && defValue . charAt ( defValue . length ( ) - 1 ) == '\"' ) ) ) { String maybeStringVal = defValue . substring ( 1 , defValue . length ( ) - 1 ) ; if ( maybeStringVal . indexOf ( defValue . charAt ( 0 ) ) == - 1 ) { if ( tweaks ) { options . setTweakToStringLiteral ( defName , maybeStringVal ) ; } else { options . setDefineToStringLiteral ( defName , maybeStringVal ) ; } continue ; } } else { try { double value = Double . parseDouble ( defValue ) ; if ( tweaks ) { options . setTweakToDoubleLiteral ( defName , value ) ; } else { options . setDefineToDoubleLiteral ( defName , value ) ; } continue ; } catch ( NumberFormatException e ) { } if ( defValue . length ( ) > 0 ) { if ( tweaks ) { options . setTweakToStringLiteral ( defName , defValue ) ; } else { options . setDefineToStringLiteral ( defName , defValue ) ; } continue ; } } } if ( tweaks ) { throw new RuntimeException ( "--tweak flag syntax invalid: " + override ) ; } throw new RuntimeException ( "--define flag syntax invalid: " + override ) ; } }
Create a map of constant names to constant values from a textual description of the map .
34,273
@ GwtIncompatible ( "Unnecessary" ) private boolean shouldGenerateOutputPerModule ( String output ) { return ! config . module . isEmpty ( ) && output != null && output . contains ( "%outname%" ) ; }
Returns true if and only if a manifest or bundle should be generated for each module as opposed to one unified manifest .
34,274
@ GwtIncompatible ( "Unnecessary" ) private void outputModuleGraphJson ( ) throws IOException { if ( config . outputModuleDependencies != null && config . outputModuleDependencies . length ( ) != 0 ) { try ( Writer out = fileNameToOutputWriter2 ( config . outputModuleDependencies ) ) { printModuleGraphJsonTo ( out ) ; } } }
Creates a file containing the current module graph in JSON serialization .
34,275
@ GwtIncompatible ( "Unnecessary" ) void printModuleGraphJsonTo ( Appendable out ) throws IOException { out . append ( compiler . getModuleGraph ( ) . toJson ( ) . toString ( ) ) ; }
Prints the current module graph as JSON .
34,276
@ GwtIncompatible ( "Unnecessary" ) void printModuleGraphManifestOrBundleTo ( JSModuleGraph graph , Appendable out , boolean isManifest ) throws IOException { Joiner commas = Joiner . on ( "," ) ; boolean requiresNewline = false ; for ( JSModule module : graph . getAllModules ( ) ) { if ( requiresNewline ) { out . append ( "\n" ) ; } if ( isManifest ) { String dependencies = commas . join ( module . getSortedDependencyNames ( ) ) ; out . append ( String . format ( "{%s%s}\n" , module . getName ( ) , dependencies . isEmpty ( ) ? "" : ":" + dependencies ) ) ; printManifestTo ( module . getInputs ( ) , out ) ; } else { printBundleTo ( module . getInputs ( ) , out ) ; } requiresNewline = true ; } }
Prints a set of modules to the manifest or bundle file .
34,277
@ GwtIncompatible ( "Unnecessary" ) private Map < String , String > constructRootRelativePathsMap ( ) { Map < String , String > rootRelativePathsMap = new LinkedHashMap < > ( ) ; for ( String mapString : config . manifestMaps ) { int colonIndex = mapString . indexOf ( ':' ) ; checkState ( colonIndex > 0 ) ; String execPath = mapString . substring ( 0 , colonIndex ) ; String rootRelativePath = mapString . substring ( colonIndex + 1 ) ; checkState ( rootRelativePath . indexOf ( ':' ) == - 1 ) ; rootRelativePathsMap . put ( execPath , rootRelativePath ) ; } return rootRelativePathsMap ; }
Construct and return the input root path map . The key is the exec path of each input file and the value is the corresponding root relative path .
34,278
void expectValidTypeofName ( Node n , String found ) { report ( JSError . make ( n , UNKNOWN_TYPEOF_VALUE , found ) ) ; }
a warning and attempt to correct the mismatch when possible .
34,279
boolean expectObject ( Node n , JSType type , String msg ) { if ( ! type . matchesObjectContext ( ) ) { mismatch ( n , msg , type , OBJECT_TYPE ) ; return false ; } return true ; }
Expect the type to be an object or a type convertible to object . If the expectation is not met issue a warning at the provided node s source code position .
34,280
void expectActualObject ( Node n , JSType type , String msg ) { if ( ! type . isObject ( ) ) { mismatch ( n , msg , type , OBJECT_TYPE ) ; } }
Expect the type to be an object . Unlike expectObject a type convertible to object is not acceptable .
34,281
void expectAnyObject ( Node n , JSType type , String msg ) { JSType anyObjectType = getNativeType ( NO_OBJECT_TYPE ) ; if ( ! anyObjectType . isSubtypeOf ( type ) && ! type . isEmptyType ( ) ) { mismatch ( n , msg , type , anyObjectType ) ; } }
Expect the type to contain an object sometimes . If the expectation is not met issue a warning at the provided node s source code position .
34,282
boolean expectAutoboxesToIterable ( Node n , JSType type , String msg ) { if ( type . isUnionType ( ) ) { for ( JSType alt : type . toMaybeUnionType ( ) . getAlternates ( ) ) { alt = alt . isBoxableScalar ( ) ? alt . autoboxesTo ( ) : alt ; if ( ! alt . isSubtypeOf ( getNativeType ( ITERABLE_TYPE ) ) ) { mismatch ( n , msg , type , ITERABLE_TYPE ) ; return false ; } } } else { JSType autoboxedType = type . isBoxableScalar ( ) ? type . autoboxesTo ( ) : type ; if ( ! autoboxedType . isSubtypeOf ( getNativeType ( ITERABLE_TYPE ) ) ) { mismatch ( n , msg , type , ITERABLE_TYPE ) ; return false ; } } return true ; }
Expect the type to autobox to be an Iterable .
34,283
Optional < JSType > expectAutoboxesToIterableOrAsyncIterable ( Node n , JSType type , String msg ) { MaybeBoxedIterableOrAsyncIterable maybeBoxed = JsIterables . maybeBoxIterableOrAsyncIterable ( type , typeRegistry ) ; if ( maybeBoxed . isMatch ( ) ) { return Optional . of ( maybeBoxed . getTemplatedType ( ) ) ; } mismatch ( n , msg , type , iterableOrAsyncIterable ) ; return Optional . empty ( ) ; }
Expect the type to autobox to be an Iterable or AsyncIterable .
34,284
void expectGeneratorSupertype ( Node n , JSType type , String msg ) { if ( ! getNativeType ( GENERATOR_TYPE ) . isSubtypeOf ( type ) ) { mismatch ( n , msg , type , GENERATOR_TYPE ) ; } }
Expect the type to be a Generator or supertype of Generator .
34,285
void expectAsyncGeneratorSupertype ( Node n , JSType type , String msg ) { if ( ! getNativeType ( ASYNC_GENERATOR_TYPE ) . isSubtypeOf ( type ) ) { mismatch ( n , msg , type , ASYNC_GENERATOR_TYPE ) ; } }
Expect the type to be a AsyncGenerator or supertype of AsyncGenerator .
34,286
void expectValidAsyncReturnType ( Node n , JSType type ) { if ( promiseOfUnknownType . isSubtypeOf ( type ) ) { return ; } JSError err = JSError . make ( n , INVALID_ASYNC_RETURN_TYPE , type . toString ( ) ) ; registerMismatch ( type , promiseOfUnknownType , err ) ; report ( err ) ; }
Expect the type to be a supertype of Promise .
34,287
void expectITemplateArraySupertype ( Node n , JSType type , String msg ) { if ( ! getNativeType ( I_TEMPLATE_ARRAY_TYPE ) . isSubtypeOf ( type ) ) { mismatch ( n , msg , type , I_TEMPLATE_ARRAY_TYPE ) ; } }
Expect the type to be an ITemplateArray or supertype of ITemplateArray .
34,288
void expectString ( Node n , JSType type , String msg ) { if ( ! type . matchesStringContext ( ) ) { mismatch ( n , msg , type , STRING_TYPE ) ; } }
Expect the type to be a string or a type convertible to string . If the expectation is not met issue a warning at the provided node s source code position .
34,289
void expectNumber ( Node n , JSType type , String msg ) { if ( ! type . matchesNumberContext ( ) ) { mismatch ( n , msg , type , NUMBER_TYPE ) ; } else { expectNumberStrict ( n , type , msg ) ; } }
Expect the type to be a number or a type convertible to number . If the expectation is not met issue a warning at the provided node s source code position .
34,290
void expectNumberStrict ( Node n , JSType type , String msg ) { if ( ! type . isSubtypeOf ( getNativeType ( NUMBER_TYPE ) ) ) { registerMismatchAndReport ( n , INVALID_OPERAND_TYPE , msg , type , getNativeType ( NUMBER_TYPE ) , null , null ) ; } }
Expect the type to be a number or a subtype .
34,291
void expectNumberOrSymbol ( Node n , JSType type , String msg ) { if ( ! type . matchesNumberContext ( ) && ! type . matchesSymbolContext ( ) ) { mismatch ( n , msg , type , NUMBER_SYMBOL ) ; } }
Expect the type to be a number or string or a type convertible to a number or symbol . If the expectation is not met issue a warning at the provided node s source code position .
34,292
void expectStringOrSymbol ( Node n , JSType type , String msg ) { if ( ! type . matchesStringContext ( ) && ! type . matchesSymbolContext ( ) ) { mismatch ( n , msg , type , STRING_SYMBOL ) ; } }
Expect the type to be a string or symbol or a type convertible to a string . If the expectation is not met issue a warning at the provided node s source code position .
34,293
boolean expectNotNullOrUndefined ( NodeTraversal t , Node n , JSType type , String msg , JSType expectedType ) { if ( ! type . isNoType ( ) && ! type . isUnknownType ( ) && type . isSubtypeOf ( nullOrUndefined ) && ! containsForwardDeclaredUnresolvedName ( type ) ) { if ( n . isGetProp ( ) && ! t . inGlobalScope ( ) && type . isNullType ( ) ) { return true ; } mismatch ( n , msg , type , expectedType ) ; return false ; } return true ; }
Expect the type to be anything but the null or void type . If the expectation is not met issue a warning at the provided node s source code position . Note that a union type that includes the void type and at least one other type meets the expectation .
34,294
void expectSwitchMatchesCase ( Node n , JSType switchType , JSType caseType ) { if ( ! switchType . canTestForShallowEqualityWith ( caseType ) && ( caseType . autoboxesTo ( ) == null || ! caseType . autoboxesTo ( ) . isSubtypeOf ( switchType ) ) ) { mismatch ( n . getFirstChild ( ) , "case expression doesn't match switch" , caseType , switchType ) ; } else if ( ! switchType . canTestForShallowEqualityWith ( caseType ) && ( caseType . autoboxesTo ( ) == null || ! caseType . autoboxesTo ( ) . isSubtypeWithoutStructuralTyping ( switchType ) ) ) { TypeMismatch . recordImplicitInterfaceUses ( this . implicitInterfaceUses , n , caseType , switchType ) ; TypeMismatch . recordImplicitUseOfNativeObject ( this . mismatches , n , caseType , switchType ) ; } }
Expect that the type of a switch condition matches the type of its case condition .
34,295
void expectIndexMatch ( Node n , JSType objType , JSType indexType ) { checkState ( n . isGetElem ( ) || n . isComputedProp ( ) , n ) ; Node indexNode = n . isGetElem ( ) ? n . getLastChild ( ) : n . getFirstChild ( ) ; if ( indexType . isSymbolValueType ( ) ) { return ; } if ( objType . isStruct ( ) ) { report ( JSError . make ( indexNode , ILLEGAL_PROPERTY_ACCESS , "'[]'" , "struct" ) ) ; } if ( objType . isUnknownType ( ) ) { expectStringOrNumberOrSymbol ( indexNode , indexType , "property access" ) ; } else { ObjectType dereferenced = objType . dereference ( ) ; if ( dereferenced != null && dereferenced . getTemplateTypeMap ( ) . hasTemplateKey ( typeRegistry . getObjectIndexKey ( ) ) ) { expectCanAssignTo ( indexNode , indexType , dereferenced . getTemplateTypeMap ( ) . getResolvedTemplateType ( typeRegistry . getObjectIndexKey ( ) ) , "restricted index type" ) ; } else if ( dereferenced != null && dereferenced . isArrayType ( ) ) { expectNumberOrSymbol ( indexNode , indexType , "array access" ) ; } else if ( objType . matchesObjectContext ( ) ) { expectStringOrSymbol ( indexNode , indexType , "property access" ) ; } else { mismatch ( n , "only arrays or objects can be accessed" , objType , typeRegistry . createUnionType ( ARRAY_TYPE , OBJECT_TYPE ) ) ; } } }
Expect that the first type can be addressed with GETELEM syntax and that the second type is the right type for an index into the first type .
34,296
void expectArgumentMatchesParameter ( Node n , JSType argType , JSType paramType , Node callNode , int ordinal ) { if ( ! argType . isSubtypeOf ( paramType ) ) { mismatch ( n , SimpleFormat . format ( "actual parameter %d of %s does not match formal parameter" , ordinal , typeRegistry . getReadableTypeNameNoDeref ( callNode . getFirstChild ( ) ) ) , argType , paramType ) ; } else if ( ! argType . isSubtypeWithoutStructuralTyping ( paramType ) ) { TypeMismatch . recordImplicitInterfaceUses ( this . implicitInterfaceUses , n , argType , paramType ) ; TypeMismatch . recordImplicitUseOfNativeObject ( this . mismatches , n , argType , paramType ) ; } }
Expect that the type of an argument matches the type of the parameter that it s fulfilling .
34,297
void expectSuperType ( Node n , ObjectType superObject , ObjectType subObject ) { FunctionType subCtor = subObject . getConstructor ( ) ; ObjectType implicitProto = subObject . getImplicitPrototype ( ) ; ObjectType declaredSuper = implicitProto == null ? null : implicitProto . getImplicitPrototype ( ) ; if ( declaredSuper != null && declaredSuper . isTemplatizedType ( ) ) { declaredSuper = declaredSuper . toMaybeTemplatizedType ( ) . getReferencedType ( ) ; } if ( declaredSuper != null && ! ( superObject instanceof UnknownType ) && ! declaredSuper . isEquivalentTo ( superObject ) ) { if ( declaredSuper . isEquivalentTo ( getNativeType ( OBJECT_TYPE ) ) ) { registerMismatch ( superObject , declaredSuper , report ( JSError . make ( n , MISSING_EXTENDS_TAG_WARNING , subObject . toString ( ) ) ) ) ; } else { mismatch ( n , "mismatch in declaration of superclass type" , superObject , declaredSuper ) ; } if ( ! subCtor . hasCachedValues ( ) ) { subCtor . setPrototypeBasedOn ( superObject ) ; } } }
Expect that the first type is the direct superclass of the second type .
34,298
void expectExtends ( Node n , FunctionType subCtor , FunctionType astSuperCtor ) { if ( astSuperCtor == null || ( ! astSuperCtor . isConstructor ( ) && ! astSuperCtor . isInterface ( ) ) ) { return ; } if ( astSuperCtor . isConstructor ( ) != subCtor . isConstructor ( ) ) { return ; } ObjectType astSuperInstance = astSuperCtor . getInstanceType ( ) ; if ( subCtor . isConstructor ( ) ) { FunctionType registeredSuperCtor = subCtor . getSuperClassConstructor ( ) ; if ( registeredSuperCtor != null ) { ObjectType registeredSuperInstance = registeredSuperCtor . getInstanceType ( ) ; if ( ! astSuperInstance . isEquivalentTo ( registeredSuperInstance ) ) { mismatch ( n , "mismatch in declaration of superclass type" , astSuperInstance , registeredSuperInstance ) ; } } } else if ( subCtor . isInterface ( ) ) { } }
Expect that an ES6 class s extends clause is actually a supertype of the given class . Compares the registered supertype which is taken from the JSDoc if present otherwise from the AST with the type in the extends node of the AST .
34,299
void expectCanAssignToPrototype ( JSType ownerType , Node node , JSType rightType ) { if ( ownerType . isFunctionType ( ) ) { FunctionType functionType = ownerType . toMaybeFunctionType ( ) ; if ( functionType . isConstructor ( ) ) { expectObject ( node , rightType , "cannot override prototype with non-object" ) ; } } }
Expect that it s valid to assign something to a given type s prototype .