idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
34,700
private static boolean inForcedStringContext ( Node n ) { if ( n . getParent ( ) . isGetElem ( ) && n . getParent ( ) . getLastChild ( ) == n ) { return true ; } return n . getParent ( ) . isAdd ( ) ; }
Returns whether this node must be coerced to a string .
34,701
private Node tryFlattenArrayOrObjectLit ( Node parentLit ) { for ( Node child = parentLit . getFirstChild ( ) ; child != null ; ) { Node spread = child ; child = child . getNext ( ) ; if ( ! spread . isSpread ( ) ) { continue ; } Node innerLit = spread . getOnlyChild ( ) ; if ( ! parentLit . getToken ( ) . equals ( innerLit . getToken ( ) ) ) { continue ; } parentLit . addChildrenAfter ( innerLit . removeChildren ( ) , spread ) ; spread . detach ( ) ; reportChangeToEnclosingScope ( parentLit ) ; } return parentLit ; }
Flattens array - or object - literals that contain spreads of other literals .
34,702
public void setWrapperPrefix ( String prefix ) { int prefixLine = 0 ; int prefixIndex = 0 ; for ( int i = 0 ; i < prefix . length ( ) ; ++ i ) { if ( prefix . charAt ( i ) == '\n' ) { prefixLine ++ ; prefixIndex = 0 ; } else { prefixIndex ++ ; } } prefixPosition = new FilePosition ( prefixLine , prefixIndex ) ; }
Sets the prefix used for wrapping the generated source file before it is written . This ensures that the source map is adjusted for the change in character offsets .
34,703
public void setStartingPosition ( int offsetLine , int offsetIndex ) { checkState ( offsetLine >= 0 ) ; checkState ( offsetIndex >= 0 ) ; offsetPosition = new FilePosition ( offsetLine , offsetIndex ) ; }
Sets the source code that exists in the buffer for which the generated code is being generated . This ensures that the source map accurately reflects the fact that the source is being appended to an existing buffer and as such does not start at line 0 position 0 but rather some other line and position .
34,704
public void addExtension ( String name , Object object ) throws SourceMapParseException { if ( ! name . startsWith ( "x_" ) ) { throw new SourceMapParseException ( "Extension '" + name + "' must start with 'x_'" ) ; } this . extensions . put ( name , object ) ; }
Adds field extensions to the json source map . The value is allowed to be any value accepted by json eg . string JsonObject JsonArray etc .
34,705
private static void appendFirstField ( Appendable out , String name , CharSequence value ) throws IOException { appendFieldStart ( out , name , true ) ; out . append ( value ) ; }
Source map field helpers .
34,706
private int prepMappings ( ) throws IOException { ( new MappingTraversal ( ) ) . traverse ( new UsedMappingCheck ( ) ) ; int id = 0 ; int maxLine = 0 ; for ( Mapping m : mappings ) { if ( m . used ) { m . id = id ++ ; int endPositionLine = m . endPosition . getLine ( ) ; maxLine = Math . max ( maxLine , endPositionLine ) ; } } return maxLine + prefixPosition . getLine ( ) ; }
Assigns sequential ids to used mappings and returns the last line mapped .
34,707
public void appendIndexMapTo ( Appendable out , String name , List < SourceMapSection > sections ) throws IOException { out . append ( "{\n" ) ; appendFirstField ( out , "version" , "3" ) ; appendField ( out , "file" , escapeString ( name ) ) ; appendFieldStart ( out , "sections" ) ; out . append ( "[\n" ) ; boolean first = true ; for ( SourceMapSection section : sections ) { if ( first ) { first = false ; } else { out . append ( ",\n" ) ; } out . append ( "{\n" ) ; appendFieldStart ( out , "offset" , true ) ; appendOffsetValue ( out , section . getLine ( ) , section . getColumn ( ) ) ; if ( section . getSectionType ( ) == SourceMapSection . SectionType . URL ) { appendField ( out , "url" , escapeString ( section . getSectionValue ( ) ) ) ; } else if ( section . getSectionType ( ) == SourceMapSection . SectionType . MAP ) { appendField ( out , "map" , section . getSectionValue ( ) ) ; } else { throw new IOException ( "Unexpected section type" ) ; } out . append ( "\n}" ) ; } out . append ( "\n]" ) ; appendFieldEnd ( out ) ; out . append ( "\n}\n" ) ; }
Appends the index source map to the given buffer .
34,708
public static final void resetMaximumInputSize ( ) { String maxInputSizeStr = System . getProperty ( Protocol . MAX_INPUT_SIZE_KEY ) ; if ( maxInputSizeStr == null ) { maxInputSize = Protocol . FALLBACK_MAX_INPUT_SIZE ; } else { maxInputSize = Integer . parseInt ( maxInputSizeStr ) ; } }
Reset the maximum input size so that the property key is rechecked . This is needed for testing code because we are caching the maximum input size value .
34,709
public boolean isConnectedInDirection ( DiGraphNode < N , E > dNode1 , Predicate < E > edgeMatcher , DiGraphNode < N , E > dNode2 ) { List < DiGraphEdge < N , E > > outEdges = dNode1 . getOutEdges ( ) ; int outEdgesLen = outEdges . size ( ) ; List < DiGraphEdge < N , E > > inEdges = dNode2 . getInEdges ( ) ; int inEdgesLen = inEdges . size ( ) ; if ( outEdgesLen < inEdgesLen ) { for ( int i = 0 ; i < outEdgesLen ; i ++ ) { DiGraphEdge < N , E > outEdge = outEdges . get ( i ) ; if ( outEdge . getDestination ( ) == dNode2 && edgeMatcher . apply ( outEdge . getValue ( ) ) ) { return true ; } } } else { for ( int i = 0 ; i < inEdgesLen ; i ++ ) { DiGraphEdge < N , E > inEdge = inEdges . get ( i ) ; if ( inEdge . getSource ( ) == dNode1 && edgeMatcher . apply ( inEdge . getValue ( ) ) ) { return true ; } } } return false ; }
DiGraphNode look ups can be expensive for a large graph operation prefer this method if you have the DiGraphNodes available .
34,710
private static boolean insideGetCssNameCall ( Node n ) { Node parent = n . getParent ( ) ; return parent . isCall ( ) && parent . getFirstChild ( ) . matchesQualifiedName ( GET_CSS_NAME_FUNCTION ) ; }
Returns whether the node is an argument of a goog . getCssName call .
34,711
protected boolean isWellDefined ( ) { int size = references . size ( ) ; if ( size == 0 ) { return false ; } Reference init = getInitializingReference ( ) ; if ( init == null ) { return false ; } checkState ( references . get ( 0 ) . isDeclaration ( ) ) ; BasicBlock initBlock = init . getBasicBlock ( ) ; for ( int i = 1 ; i < size ; i ++ ) { if ( ! initBlock . provablyExecutesBefore ( references . get ( i ) . getBasicBlock ( ) ) ) { return false ; } } return true ; }
Determines if the variable for this reference collection is well - defined . A variable is well - defined if we can prove at compile - time that it s assigned a value before it s used .
34,712
boolean isEscaped ( ) { Scope hoistScope = null ; for ( Reference ref : references ) { if ( hoistScope == null ) { hoistScope = ref . getScope ( ) . getClosestHoistScope ( ) ; } else if ( hoistScope != ref . getScope ( ) . getClosestHoistScope ( ) ) { return true ; } } return false ; }
Whether the variable is escaped into an inner function .
34,713
Reference getInitializingReferenceForConstants ( ) { int size = references . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( isInitializingDeclarationAt ( i ) || isInitializingAssignmentAt ( i ) ) { return references . get ( i ) ; } } return null ; }
Constants are allowed to be defined after their first use .
34,714
private void protectSideEffects ( ) { if ( ! problemNodes . isEmpty ( ) ) { if ( ! preserveFunctionInjected ) { addExtern ( compiler ) ; } for ( Node n : problemNodes ) { Node name = IR . name ( PROTECTOR_FN ) . srcref ( n ) ; name . putBooleanProp ( Node . IS_CONSTANT_NAME , true ) ; Node replacement = IR . call ( name ) . srcref ( n ) ; replacement . putBooleanProp ( Node . FREE_CALL , true ) ; n . replaceWith ( replacement ) ; replacement . addChildToBack ( n ) ; compiler . reportChangeToEnclosingScope ( replacement ) ; } } }
Protect side - effect free nodes by making them parameters to a extern function call . This call will be removed after all the optimizations passes have run .
34,715
static void addExtern ( AbstractCompiler compiler ) { Node name = IR . name ( PROTECTOR_FN ) ; name . putBooleanProp ( Node . IS_CONSTANT_NAME , true ) ; Node var = IR . var ( name ) ; JSDocInfoBuilder builder = new JSDocInfoBuilder ( false ) ; var . setJSDocInfo ( builder . build ( ) ) ; CompilerInput input = compiler . getSynthesizedExternsInput ( ) ; Node root = input . getAstRoot ( compiler ) ; name . setStaticSourceFileFrom ( root ) ; var . setStaticSourceFileFrom ( root ) ; root . addChildToBack ( var ) ; compiler . reportChangeToEnclosingScope ( var ) ; }
Injects JSCOMPILER_PRESEVE into the synthetic externs
34,716
private void unrollBinaryOperator ( Node n , Token op , String opStr , Context context , Context rhsContext , int leftPrecedence , int rightPrecedence ) { Node firstNonOperator = n . getFirstChild ( ) ; while ( firstNonOperator . getToken ( ) == op ) { firstNonOperator = firstNonOperator . getFirstChild ( ) ; } addExpr ( firstNonOperator , leftPrecedence , context ) ; Node current = firstNonOperator ; do { current = current . getParent ( ) ; cc . addOp ( opStr , true ) ; addExpr ( current . getSecondChild ( ) , rightPrecedence , rhsContext ) ; } while ( current != n ) ; }
We could use addList recursively here but sometimes we produce very deeply nested operators and run out of stack space so we just unroll the recursion when possible .
34,717
void addArrayList ( Node firstInList ) { boolean lastWasEmpty = false ; for ( Node n = firstInList ; n != null ; n = n . getNext ( ) ) { if ( n != firstInList ) { cc . listSeparator ( ) ; } addExpr ( n , 1 , Context . OTHER ) ; lastWasEmpty = n . isEmpty ( ) ; } if ( lastWasEmpty ) { cc . listSeparator ( ) ; } }
This function adds a comma - separated list as is specified by an ARRAYLIT node with the associated skipIndexes array . This is a space optimization since we avoid creating a whole Node object for each empty array literal slot .
34,718
private String escapeUnrecognizedCharacters ( String s ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; switch ( c ) { case '\b' : case '\f' : case '\n' : case '\r' : case '\t' : case '\\' : case '\"' : case '\'' : case '$' : case '`' : case '\u2028' : case '\u2029' : sb . append ( c ) ; break ; default : if ( ( outputCharsetEncoder != null && outputCharsetEncoder . canEncode ( c ) ) || ( c > 0x1f && c < 0x7f ) ) { sb . append ( c ) ; } else { Util . appendHexJavaScriptRepresentation ( sb , c ) ; } } } return sb . toString ( ) ; }
Helper to escape the characters that might be misinterpreted
34,719
private static Node getFirstNonEmptyChild ( Node n ) { for ( Node c = n . getFirstChild ( ) ; c != null ; c = c . getNext ( ) ) { if ( c . isBlock ( ) ) { Node result = getFirstNonEmptyChild ( c ) ; if ( result != null ) { return result ; } } else if ( ! c . isEmpty ( ) ) { return c ; } } return null ; }
Gets the first non - empty child of the given node .
34,720
private static Context getContextForArrowFunctionBody ( Context context ) { return context . inForInInitClause ( ) ? Context . START_OF_ARROW_FN_IN_FOR_INIT : Context . START_OF_ARROW_FN_BODY ; }
If we re at the start of an arrow function body we need parentheses around object literals and object patterns . We also must also pass the IN_FOR_INIT_CLAUSE flag into subexpressions .
34,721
private boolean isValidDefineType ( JSTypeExpression expression ) { JSTypeRegistry registry = compiler . getTypeRegistry ( ) ; JSType type = registry . evaluateTypeExpressionInGlobalScope ( expression ) ; return ! type . isUnknownType ( ) && type . isSubtypeOf ( registry . getNativeType ( NUMBER_STRING_BOOLEAN ) ) ; }
Only defines of literal number string or boolean are supported .
34,722
private static Node getConstantDeclValue ( Node name ) { Node parent = name . getParent ( ) ; if ( parent == null ) { return null ; } if ( name . isName ( ) ) { if ( parent . isConst ( ) ) { return name . getFirstChild ( ) ; } else if ( ! parent . isVar ( ) ) { return null ; } JSDocInfo jsdoc = NodeUtil . getBestJSDocInfo ( name ) ; return jsdoc != null && jsdoc . isConstant ( ) ? name . getFirstChild ( ) : null ; } else if ( name . isGetProp ( ) && parent . isAssign ( ) ) { JSDocInfo jsdoc = NodeUtil . getBestJSDocInfo ( name ) ; return jsdoc != null && jsdoc . isConstant ( ) ? name . getNext ( ) : null ; } return null ; }
Checks whether the NAME node is inside either a CONST or a
34,723
private static void setDefineInfoNotAssignable ( DefineInfo info , NodeTraversal t ) { info . setNotAssignable ( format ( REASON_DEFINE_NOT_ASSIGNABLE , t . getLineNumber ( ) , t . getSourceName ( ) ) ) ; }
Records the fact that because of the current node in the node traversal the define can t ever be assigned again .
34,724
private static ImmutableList < String > computePathPrefixes ( String path ) { List < String > pieces = Q_NAME_SPLITTER . splitToList ( path ) ; ImmutableList . Builder < String > pathPrefixes = ImmutableList . builder ( ) ; String partial = pieces . get ( 0 ) ; pathPrefixes . add ( partial ) ; for ( int i = 1 ; i < pieces . size ( ) ; i ++ ) { partial = Q_NAME_JOINER . join ( partial , pieces . get ( i ) ) ; pathPrefixes . add ( partial ) ; } return pathPrefixes . build ( ) ; }
Computes a list of the path prefixes constructed from the components of the path .
34,725
private boolean isExportLhs ( Node lhs ) { if ( ! lhs . isQualifiedName ( ) ) { return false ; } return lhs . matchesQualifiedName ( "exports" ) || ( lhs . isGetProp ( ) && lhs . getFirstChild ( ) . matchesQualifiedName ( "exports" ) ) ; }
Is this the LHS of a goog . module export? i . e . Either exports or exports . name
34,726
public List < String > getDependencies ( String code ) throws ServiceException { return getDependencies ( parseRequires ( code , true ) ) ; }
Gets a list of dependencies for the provided code .
34,727
public List < String > getDependencies ( Collection < String > symbols ) throws ServiceException { return getDependencies ( symbols , new HashSet < String > ( ) ) ; }
Gets a list of dependencies for the provided list of symbols .
34,728
private static Collection < String > parseRequires ( String code , boolean addClosureBase ) { ErrorManager errorManager = new LoggerErrorManager ( logger ) ; JsFileParser parser = new JsFileParser ( errorManager ) ; DependencyInfo deps = parser . parseFile ( "<unknown path>" , "<unknown path>" , code ) ; List < String > requires = new ArrayList < > ( ) ; if ( addClosureBase ) { requires . add ( CLOSURE_BASE_PROVIDE ) ; } requires . addAll ( deps . getRequiredSymbols ( ) ) ; errorManager . generateReport ( ) ; return requires ; }
Parses a block of code for goog . require statements and extracts the required symbols .
34,729
private DependencyInfo getDependencyInfo ( String symbol ) { for ( DependencyFile depsFile : depsFiles ) { DependencyInfo di = depsFile . getDependencyInfo ( symbol ) ; if ( di != null ) { return di ; } } return null ; }
Looks at each of the dependency files for dependency information .
34,730
private boolean resolveViaRegistry ( ErrorReporter reporter ) { JSType type = registry . getType ( resolutionScope , reference ) ; if ( type != null ) { setReferencedAndResolvedType ( type , reporter ) ; return true ; } return false ; }
Resolves a named type by looking it up in the registry .
34,731
private void resolveViaProperties ( ErrorReporter reporter ) { String [ ] componentNames = reference . split ( "\\." , - 1 ) ; if ( componentNames [ 0 ] . length ( ) == 0 ) { handleUnresolvedType ( reporter , true ) ; return ; } StaticTypedSlot slot = resolutionScope . getSlot ( componentNames [ 0 ] ) ; if ( slot == null ) { handleUnresolvedType ( reporter , true ) ; return ; } JSType slotType = slot . getType ( ) ; if ( slotType == null || slotType . isAllType ( ) || slotType . isNoType ( ) ) { handleUnresolvedType ( reporter , true ) ; return ; } for ( int i = 1 ; i < componentNames . length ; i ++ ) { ObjectType parentObj = ObjectType . cast ( slotType ) ; if ( parentObj == null || componentNames [ i ] . length ( ) == 0 ) { handleUnresolvedType ( reporter , true ) ; return ; } if ( i == componentNames . length - 1 ) { Node def = parentObj . getPropertyDefSite ( componentNames [ i ] ) ; JSType typedefType = def != null ? def . getTypedefTypeProp ( ) : null ; if ( typedefType != null ) { setReferencedAndResolvedType ( typedefType , reporter ) ; return ; } } slotType = parentObj . getPropertyType ( componentNames [ i ] ) ; } if ( slotType == null ) { handleUnresolvedType ( reporter , true ) ; } else if ( slotType . isFunctionType ( ) && ( slotType . isConstructor ( ) || slotType . isInterface ( ) ) ) { setReferencedAndResolvedType ( slotType . toMaybeFunctionType ( ) . getInstanceType ( ) , reporter ) ; } else if ( slotType . isNoObjectType ( ) ) { setReferencedAndResolvedType ( registry . getNativeObjectType ( JSTypeNative . NO_OBJECT_TYPE ) , reporter ) ; } else if ( slotType instanceof EnumType ) { setReferencedAndResolvedType ( ( ( EnumType ) slotType ) . getElementsType ( ) , reporter ) ; } else { handleUnresolvedType ( reporter , slotType . isUnknownType ( ) ) ; } }
Resolves a named type by looking up its first component in the scope and subsequent components as properties . The scope must have been fully parsed and a symbol table constructed .
34,732
private void handleUnresolvedType ( ErrorReporter reporter , boolean ignoreForwardReferencedTypes ) { boolean isForwardDeclared = ignoreForwardReferencedTypes && registry . isForwardDeclaredType ( reference ) ; if ( ! isForwardDeclared ) { String msg = "Bad type annotation. Unknown type " + reference ; warning ( reporter , msg ) ; } else { setReferencedType ( new NoResolvedType ( registry , getReferenceName ( ) , getTemplateTypes ( ) ) ) ; if ( validator != null ) { validator . apply ( getReferencedType ( ) ) ; } } setResolvedTypeInternal ( getReferencedType ( ) ) ; }
type name .
34,733
private UndiGraph < Var , Void > computeVariableNamesInterferenceGraph ( ControlFlowGraph < Node > cfg , Set < ? extends Var > escaped ) { UndiGraph < Var , Void > interferenceGraph = LinkedUndirectedGraph . create ( ) ; List < Var > orderedVariables = liveness . getAllVariablesInOrder ( ) ; for ( Var v : orderedVariables ) { if ( escaped . contains ( v ) ) { continue ; } if ( v . getParentNode ( ) . isFunction ( ) ) { continue ; } if ( v . getParentNode ( ) . isClass ( ) ) { continue ; } if ( isInMultipleLvalueDecl ( v ) ) { continue ; } interferenceGraph . createNode ( v ) ; } int v1Index = - 1 ; for ( Var v1 : orderedVariables ) { v1Index ++ ; int v2Index = - 1 ; NEXT_VAR_PAIR : for ( Var v2 : orderedVariables ) { v2Index ++ ; if ( v1Index > v2Index ) { continue ; } if ( ! interferenceGraph . hasNode ( v1 ) || ! interferenceGraph . hasNode ( v2 ) ) { continue NEXT_VAR_PAIR ; } if ( v1 . isParam ( ) && v2 . isParam ( ) ) { interferenceGraph . connectIfNotFound ( v1 , null , v2 ) ; continue NEXT_VAR_PAIR ; } NEXT_CROSS_CFG_NODE : for ( DiGraphNode < Node , Branch > cfgNode : cfg . getDirectedGraphNodes ( ) ) { if ( cfg . isImplicitReturn ( cfgNode ) ) { continue NEXT_CROSS_CFG_NODE ; } FlowState < LiveVariableLattice > state = cfgNode . getAnnotation ( ) ; if ( ( state . getIn ( ) . isLive ( v1Index ) && state . getIn ( ) . isLive ( v2Index ) ) || ( state . getOut ( ) . isLive ( v1Index ) && state . getOut ( ) . isLive ( v2Index ) ) ) { interferenceGraph . connectIfNotFound ( v1 , null , v2 ) ; continue NEXT_VAR_PAIR ; } } NEXT_INTRA_CFG_NODE : for ( DiGraphNode < Node , Branch > cfgNode : cfg . getDirectedGraphNodes ( ) ) { if ( cfg . isImplicitReturn ( cfgNode ) ) { continue NEXT_INTRA_CFG_NODE ; } FlowState < LiveVariableLattice > state = cfgNode . getAnnotation ( ) ; boolean v1OutLive = state . getOut ( ) . isLive ( v1Index ) ; boolean v2OutLive = state . getOut ( ) . isLive ( v2Index ) ; CombinedLiveRangeChecker checker = new CombinedLiveRangeChecker ( cfgNode . getValue ( ) , new LiveRangeChecker ( v1 , v2OutLive ? null : v2 ) , new LiveRangeChecker ( v2 , v1OutLive ? null : v1 ) ) ; checker . check ( cfgNode . getValue ( ) ) ; if ( checker . connectIfCrossed ( interferenceGraph ) ) { continue NEXT_VAR_PAIR ; } } } } return interferenceGraph ; }
In order to determine when it is appropriate to coalesce two variables we use a live variables analysis to make sure they are not alive at the same time . We take every pairing of variables and for every CFG node determine whether the two variables are alive at the same time . If two variables are alive at the same time we create an edge between them in the interference graph . The interference graph is the input to a graph coloring algorithm that ensures any interfering variables are marked in different color groups while variables that can safely be coalesced are assigned the same color group .
34,734
private boolean isInMultipleLvalueDecl ( Var v ) { Token declarationType = v . declarationType ( ) ; switch ( declarationType ) { case LET : case CONST : case VAR : Node nameDecl = NodeUtil . getEnclosingNode ( v . getNode ( ) , NodeUtil :: isNameDeclaration ) ; return NodeUtil . findLhsNodesInNode ( nameDecl ) . size ( ) > 1 ; default : return false ; } }
Returns whether this variable s declaration also declares other names .
34,735
private static void removeVarDeclaration ( Node name ) { Node var = NodeUtil . getEnclosingNode ( name , NodeUtil :: isNameDeclaration ) ; Node parent = var . getParent ( ) ; if ( var . getFirstChild ( ) . isDestructuringLhs ( ) ) { Node destructuringLhs = var . getFirstChild ( ) ; Node pattern = destructuringLhs . getFirstChild ( ) . detach ( ) ; if ( NodeUtil . isEnhancedFor ( parent ) ) { var . replaceWith ( pattern ) ; } else { Node rvalue = var . getFirstFirstChild ( ) . detach ( ) ; var . replaceWith ( NodeUtil . newExpr ( IR . assign ( pattern , rvalue ) . srcref ( var ) ) ) ; } } else if ( NodeUtil . isEnhancedFor ( parent ) ) { parent . replaceChild ( var , name . detach ( ) ) ; } else { checkState ( var . hasOneChild ( ) && var . getFirstChild ( ) == name , var ) ; if ( name . hasChildren ( ) ) { Node value = name . removeFirstChild ( ) ; var . removeChild ( name ) ; Node assign = IR . assign ( name , value ) . srcref ( name ) ; if ( ! parent . isVanillaFor ( ) ) { assign = NodeUtil . newExpr ( assign ) ; } parent . replaceChild ( var , assign ) ; } else { NodeUtil . removeChild ( parent , var ) ; } } }
Remove variable declaration if the variable has been coalesced with another variable that has already been declared .
34,736
private static void makeDeclarationVar ( Var coalescedName ) { if ( coalescedName . isLet ( ) || coalescedName . isConst ( ) ) { Node declNode = NodeUtil . getEnclosingNode ( coalescedName . getParentNode ( ) , NodeUtil :: isNameDeclaration ) ; declNode . setToken ( Token . VAR ) ; } }
Because the code has already been normalized by the time this pass runs we can safely redeclare any let and const coalesced variables as vars
34,737
private void visitMethod ( Node member , ClassDeclarationMetadata metadata ) { Node qualifiedMemberAccess = getQualifiedMemberAccess ( member , metadata ) ; Node method = member . getLastChild ( ) . detach ( ) ; Node assign = astFactory . createAssign ( qualifiedMemberAccess , method ) . useSourceInfoIfMissingFrom ( method ) ; JSDocInfo info = member . getJSDocInfo ( ) ; if ( member . isStaticMember ( ) && NodeUtil . referencesThis ( assign . getLastChild ( ) ) ) { JSDocInfoBuilder memberDoc = JSDocInfoBuilder . maybeCopyFrom ( info ) ; memberDoc . recordThisType ( new JSTypeExpression ( new Node ( Token . BANG , new Node ( Token . QMARK ) ) , member . getSourceFileName ( ) ) ) ; info = memberDoc . build ( ) ; } if ( info != null ) { assign . setJSDocInfo ( info ) ; } Node newNode = NodeUtil . newExpr ( assign ) ; metadata . insertNodeAndAdvance ( newNode ) ; }
Handles transpilation of a standard class member function . Getters setters and the constructor are not handled here .
34,738
ResolveExportResult copy ( Node sourceNode , Binding . CreatedBy createdBy ) { checkNotNull ( sourceNode ) ; if ( binding == null ) { return this ; } return new ResolveExportResult ( binding . copy ( sourceNode , createdBy ) , state ) ; }
Creates a new result that has the given node for the source of the binding and given type of binding .
34,739
private static void appendHexJavaScriptRepresentation ( int codePoint , Appendable out ) throws IOException { if ( Character . isSupplementaryCodePoint ( codePoint ) ) { char [ ] surrogates = Character . toChars ( codePoint ) ; appendHexJavaScriptRepresentation ( surrogates [ 0 ] , out ) ; appendHexJavaScriptRepresentation ( surrogates [ 1 ] , out ) ; return ; } out . append ( "\\u" ) . append ( HEX_CHARS [ ( codePoint >>> 12 ) & 0xf ] ) . append ( HEX_CHARS [ ( codePoint >>> 8 ) & 0xf ] ) . append ( HEX_CHARS [ ( codePoint >>> 4 ) & 0xf ] ) . append ( HEX_CHARS [ codePoint & 0xf ] ) ; }
Returns a JavaScript representation of the character in a hex escaped format .
34,740
protected Property getProperty ( String name ) { if ( ! properties . containsKey ( name ) ) { properties . put ( name , new Property ( name ) ) ; } return properties . get ( name ) ; }
Returns the property for the given name creating it if necessary .
34,741
void renameProperties ( ) { int propsRenamed = 0 ; int propsSkipped = 0 ; int instancesRenamed = 0 ; int instancesSkipped = 0 ; int singleTypeProps = 0 ; Set < String > reported = new HashSet < > ( ) ; for ( Property prop : properties . values ( ) ) { if ( prop . shouldRename ( ) ) { UnionFind < JSType > pTypes = prop . getTypes ( ) ; Map < JSType , String > propNames = buildPropNames ( prop ) ; ++ propsRenamed ; prop . expandTypesToSkip ( ) ; for ( Map . Entry < Node , JSType > entry : prop . rootTypesByNode . entrySet ( ) ) { Node node = entry . getKey ( ) ; JSType rootType = entry . getValue ( ) ; if ( prop . shouldRename ( rootType ) ) { String newName = propNames . get ( pTypes . find ( rootType ) ) ; node . setString ( newName ) ; compiler . reportChangeToEnclosingScope ( node ) ; ++ instancesRenamed ; } else { ++ instancesSkipped ; CheckLevel checkLevelForProp = propertiesToErrorFor . get ( prop . name ) ; if ( checkLevelForProp != null && checkLevelForProp != CheckLevel . OFF && ! reported . contains ( prop . name ) ) { reported . add ( prop . name ) ; compiler . report ( JSError . make ( node , checkLevelForProp , Warnings . INVALIDATION_ON_TYPE , prop . name , rootType . toString ( ) , "" ) ) ; } } } } else { if ( prop . skipRenaming ) { ++ propsSkipped ; } else { ++ singleTypeProps ; } } } if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Renamed " + instancesRenamed + " instances of " + propsRenamed + " properties." ) ; logger . fine ( "Skipped renaming " + instancesSkipped + " invalidated " + "properties, " + propsSkipped + " instances of properties " + "that were skipped for specific types and " + singleTypeProps + " properties that were referenced from only one type." ) ; } }
Renames all properties with references on more than one type .
34,742
private Map < JSType , String > buildPropNames ( Property prop ) { UnionFind < JSType > pTypes = prop . getTypes ( ) ; String pname = prop . name ; Map < JSType , String > names = new HashMap < > ( ) ; for ( Set < JSType > set : pTypes . allEquivalenceClasses ( ) ) { checkState ( ! set . isEmpty ( ) ) ; JSType representative = pTypes . find ( set . iterator ( ) . next ( ) ) ; String typeName = null ; for ( JSType type : set ) { String typeString = type . toString ( ) ; if ( typeName == null || typeString . compareTo ( typeName ) < 0 ) { typeName = typeString ; } } String newName ; if ( "{...}" . equals ( typeName ) ) { newName = pname ; } else { newName = NONWORD_PATTERN . matcher ( typeName ) . replaceAll ( "_" ) + '$' + pname ; } names . put ( representative , newName ) ; } return names ; }
Chooses a name to use for renaming in each equivalence class and maps the representative type of that class to that name .
34,743
private ImmutableSet < JSType > getTypesToSkipForType ( JSType type ) { type = type . restrictByNotNullOrUndefined ( ) ; if ( type . isUnionType ( ) ) { ImmutableSet . Builder < JSType > types = ImmutableSet . builder ( ) ; types . add ( type ) ; for ( JSType alt : type . getUnionMembers ( ) ) { types . addAll ( getTypesToSkipForTypeNonUnion ( alt ) ) ; } return types . build ( ) ; } else if ( type . isEnumElementType ( ) ) { return getTypesToSkipForType ( type . getEnumeratedTypeOfEnumElement ( ) ) ; } return ImmutableSet . copyOf ( getTypesToSkipForTypeNonUnion ( type ) ) ; }
Returns a set of types that should be skipped given the given type . This is necessary for interfaces as all super interfaces must also be skipped .
34,744
private Iterable < ? extends JSType > getTypeAlternatives ( JSType type ) { if ( type . isUnionType ( ) ) { return type . getUnionMembers ( ) ; } else { ObjectType objType = type . toMaybeObjectType ( ) ; FunctionType constructor = objType != null ? objType . getConstructor ( ) : null ; if ( constructor != null && constructor . isInterface ( ) ) { List < JSType > list = new ArrayList < > ( ) ; for ( FunctionType impl : constructor . getDirectSubTypes ( ) ) { list . add ( impl . getInstanceType ( ) ) ; } return list . isEmpty ( ) ? null : list ; } else { return null ; } } }
Returns the alternatives if this is a type that represents multiple types and null if not . Union and interface types can correspond to multiple other types .
34,745
private ObjectType getTypeWithProperty ( String field , JSType type ) { if ( type == null ) { return null ; } ObjectType foundType = gtwpCacheGet ( field , type ) ; if ( foundType != null ) { return foundType . equals ( bottomObjectType ) ? null : foundType ; } if ( type . isEnumElementType ( ) ) { foundType = getTypeWithProperty ( field , type . getEnumeratedTypeOfEnumElement ( ) ) ; gtwpCachePut ( field , type , foundType == null ? bottomObjectType : foundType ) ; return foundType ; } if ( ! type . isObjectType ( ) ) { if ( type . isBoxableScalar ( ) ) { foundType = getTypeWithProperty ( field , type . autobox ( ) ) ; gtwpCachePut ( field , type , foundType == null ? bottomObjectType : foundType ) ; return foundType ; } else { gtwpCachePut ( field , type , bottomObjectType ) ; return null ; } } if ( "prototype" . equals ( field ) ) { gtwpCachePut ( field , type , bottomObjectType ) ; return null ; } ObjectType objType = type . toMaybeObjectType ( ) ; if ( objType != null && objType . getConstructor ( ) != null && objType . getConstructor ( ) . isInterface ( ) ) { ObjectType topInterface = objType . getTopDefiningInterface ( field ) ; if ( topInterface != null && topInterface . getConstructor ( ) != null ) { foundType = topInterface . getImplicitPrototype ( ) ; } } else { while ( objType != null && ! Objects . equals ( objType . getImplicitPrototype ( ) , objType ) ) { if ( objType . hasOwnProperty ( field ) ) { foundType = objType ; } objType = objType . getImplicitPrototype ( ) ; } } if ( foundType == null ) { JSType subtypeWithProp = type . getGreatestSubtypeWithProperty ( field ) ; ObjectType maybeType = subtypeWithProp == null ? null : subtypeWithProp . toMaybeObjectType ( ) ; if ( maybeType != null && maybeType . hasOwnProperty ( field ) ) { foundType = maybeType ; } } if ( foundType != null && foundType . isGenericObjectType ( ) ) { foundType = foundType . getRawType ( ) ; } if ( foundType != null && foundType . isNamedType ( ) ) { foundType = foundType . toMaybeNamedType ( ) . getReferencedType ( ) . toMaybeObjectType ( ) ; } gtwpCachePut ( field , type , foundType == null ? bottomObjectType : foundType ) ; return foundType ; }
Returns the type in the chain from the given type that contains the given field or null if it is not found anywhere . Can return a subtype of the input type .
34,746
private static JSType getInstanceIfPrototype ( JSType maybePrototype ) { if ( maybePrototype . isFunctionPrototypeType ( ) ) { FunctionType constructor = maybePrototype . toObjectType ( ) . getOwnerFunction ( ) ; if ( constructor != null ) { if ( ! constructor . hasInstanceType ( ) ) { return null ; } return constructor . getInstanceType ( ) ; } } return null ; }
Returns the corresponding instance if maybePrototype is a prototype of a constructor otherwise null
34,747
private void recordInterfaces ( FunctionType constructor , JSType relatedType , Property p ) { Iterable < ObjectType > interfaces = ancestorInterfaces . get ( constructor ) ; if ( interfaces == null ) { interfaces = constructor . getAncestorInterfaces ( ) ; ancestorInterfaces . put ( constructor , interfaces ) ; } for ( ObjectType itype : interfaces ) { JSType top = getTypeWithProperty ( p . name , itype ) ; if ( top != null ) { p . addType ( itype , relatedType ) ; } if ( p . skipRenaming ) { return ; } } }
Records that this property could be referenced from any interface that this type inherits from .
34,748
private void populateFunctionDefinitions ( String name , List < Node > references ) { AmbiguatedFunctionSummary summaryForName = checkNotNull ( summariesByName . get ( name ) ) ; List < ImmutableList < Node > > rvaluesAssignedToName = references . stream ( ) . filter ( ( n ) -> ! isDefinitelyRValue ( n ) ) . map ( NodeUtil :: getRValueOfLValue ) . map ( ( n ) -> ( n == null ) ? null : collectCallableLeaves ( n ) ) . collect ( toList ( ) ) ; if ( rvaluesAssignedToName . isEmpty ( ) || rvaluesAssignedToName . contains ( null ) ) { summaryForName . setAllFlags ( ) ; } else { rvaluesAssignedToName . stream ( ) . flatMap ( List :: stream ) . forEach ( ( rvalue ) -> { if ( rvalue . isFunction ( ) ) { summariesForAllNamesOfFunctionByNode . put ( rvalue , summaryForName ) ; } else { String rvalueName = nameForReference ( rvalue ) ; AmbiguatedFunctionSummary rvalueSummary = summariesByName . getOrDefault ( rvalueName , unknownFunctionSummary ) ; reverseCallGraph . connect ( rvalueSummary . graphNode , SideEffectPropagation . forAlias ( ) , summaryForName . graphNode ) ; } } ) ; } }
For a name and its set of references record the set of functions that may define that name or blacklist the name if there are unclear definitions .
34,749
private void updateSideEffectsForExternFunction ( Node externFunction , AmbiguatedFunctionSummary summary ) { checkArgument ( externFunction . isFunction ( ) ) ; checkArgument ( externFunction . isFromExterns ( ) ) ; JSDocInfo info = NodeUtil . getBestJSDocInfo ( externFunction ) ; JSType typei = externFunction . getJSType ( ) ; FunctionType functionType = typei == null ? null : typei . toMaybeFunctionType ( ) ; if ( functionType == null ) { summary . setEscapedReturn ( ) ; } else { JSType retType = functionType . getReturnType ( ) ; if ( ! isLocalValueType ( retType , compiler ) ) { summary . setEscapedReturn ( ) ; } } if ( info == null ) { summary . setMutatesGlobalState ( ) ; summary . setFunctionThrows ( ) ; } else { if ( info . modifiesThis ( ) ) { summary . setMutatesThis ( ) ; } else if ( info . hasSideEffectsArgumentsAnnotation ( ) ) { summary . setMutatesArguments ( ) ; } else if ( ! info . getThrownTypes ( ) . isEmpty ( ) ) { summary . setFunctionThrows ( ) ; } else if ( info . isNoSideEffects ( ) ) { } else { summary . setMutatesGlobalState ( ) ; } } }
Update function for
34,750
private void visitLhsNodes ( AmbiguatedFunctionSummary sideEffectInfo , Scope scope , Node enclosingFunction , List < Node > lhsNodes , Predicate < Node > hasLocalRhs ) { for ( Node lhs : lhsNodes ) { if ( NodeUtil . isGet ( lhs ) ) { if ( lhs . getFirstChild ( ) . isThis ( ) ) { sideEffectInfo . setMutatesThis ( ) ; } else { Node objectNode = lhs . getFirstChild ( ) ; if ( objectNode . isName ( ) ) { Var var = scope . getVar ( objectNode . getString ( ) ) ; if ( isVarDeclaredInSameContainerScope ( var , scope ) ) { taintedVarsByFunction . put ( enclosingFunction , var ) ; } else { sideEffectInfo . setMutatesGlobalState ( ) ; } } else { sideEffectInfo . setMutatesGlobalState ( ) ; } } } else { checkState ( lhs . isName ( ) , lhs ) ; Var var = scope . getVar ( lhs . getString ( ) ) ; if ( isVarDeclaredInSameContainerScope ( var , scope ) ) { if ( ! hasLocalRhs . test ( lhs ) ) { blacklistedVarsByFunction . put ( enclosingFunction , var ) ; } } else { sideEffectInfo . setMutatesGlobalState ( ) ; } } } }
Record information about the side effects caused by assigning a value to a given LHS .
34,751
private void visitCall ( AmbiguatedFunctionSummary callerInfo , Node invocation ) { if ( invocation . isCall ( ) && ! NodeUtil . functionCallHasSideEffects ( invocation , compiler ) ) { return ; } if ( invocation . isNew ( ) && ! NodeUtil . constructorCallHasSideEffects ( invocation ) ) { return ; } List < AmbiguatedFunctionSummary > calleeSummaries = getSummariesForCallee ( invocation ) ; if ( calleeSummaries . isEmpty ( ) ) { callerInfo . setAllFlags ( ) ; return ; } for ( AmbiguatedFunctionSummary calleeInfo : calleeSummaries ) { SideEffectPropagation edge = SideEffectPropagation . forInvocation ( invocation ) ; reverseCallGraph . connect ( calleeInfo . graphNode , edge , callerInfo . graphNode ) ; } }
Record information about a call site .
34,752
boolean propagate ( AmbiguatedFunctionSummary callee , AmbiguatedFunctionSummary caller ) { int initialCallerFlags = caller . bitmask ; if ( callerIsAlias ) { caller . setMask ( callee . bitmask ) ; return caller . bitmask != initialCallerFlags ; } if ( callee . mutatesGlobalState ( ) ) { caller . setMutatesGlobalState ( ) ; } if ( callee . functionThrows ( ) ) { caller . setFunctionThrows ( ) ; } if ( callee . mutatesArguments ( ) && ! allArgsUnescapedLocal ) { caller . setMutatesGlobalState ( ) ; } if ( callee . mutatesThis ( ) ) { if ( invocation . isNew ( ) ) { } else if ( calleeThisEqualsCallerThis ) { caller . setMutatesThis ( ) ; } else { caller . setMutatesGlobalState ( ) ; } } return caller . bitmask != initialCallerFlags ; }
Propagate the side effects from the callee to the caller .
34,753
@ SuppressWarnings ( "ReferenceEquality" ) private boolean hasVisitedType ( TemplateType type ) { for ( TemplateType visitedType : visitedTypes ) { if ( visitedType == type ) { return true ; } } return false ; }
Checks if the specified type has already been visited during the Visitor s traversal of a JSType .
34,754
protected Set < String > normalizeWhitelist ( Set < String > whitelist ) { Set < String > result = new HashSet < > ( ) ; for ( String line : whitelist ) { String trimmed = line . trim ( ) ; if ( trimmed . isEmpty ( ) || trimmed . charAt ( 0 ) == '#' ) { continue ; } result . add ( LINE_NUMBER . matcher ( trimmed ) . replaceFirst ( ":" ) ) ; } return ImmutableSet . copyOf ( result ) ; }
Loads legacy warnings list from the set of strings . During development line numbers are changed very often - we just cut them and compare without ones .
34,755
public void removeType ( StaticScope scope , String name ) { scopedNameTable . remove ( getRootNodeForScope ( getLookupScope ( scope , name ) ) , name ) ; }
Removes a type by name .
34,756
private static boolean isObjectLiteralThatCanBeSkipped ( JSType t ) { t = t . restrictByNotNullOrUndefined ( ) ; return t . isRecordType ( ) || t . isLiteralObject ( ) ; }
we don t need to store these properties in the propertyIndex separately .
34,757
public PropDefinitionKind canPropertyBeDefined ( JSType type , String propertyName ) { if ( type . isStruct ( ) ) { switch ( type . getPropertyKind ( propertyName ) ) { case KNOWN_PRESENT : return PropDefinitionKind . KNOWN ; case MAYBE_PRESENT : return PropDefinitionKind . KNOWN ; case ABSENT : return PropDefinitionKind . UNKNOWN ; } } else { if ( ! type . isEmptyType ( ) && ! type . isUnknownType ( ) ) { switch ( type . getPropertyKind ( propertyName ) ) { case KNOWN_PRESENT : return PropDefinitionKind . KNOWN ; case MAYBE_PRESENT : return PropDefinitionKind . KNOWN ; case ABSENT : break ; } } if ( typesIndexedByProperty . containsKey ( propertyName ) ) { for ( JSType alternative : typesIndexedByProperty . get ( propertyName ) ) { JSType greatestSubtype = alternative . getGreatestSubtype ( type ) ; if ( ! greatestSubtype . isEmptyType ( ) ) { RecordType maybeRecordType = greatestSubtype . toMaybeRecordType ( ) ; if ( maybeRecordType != null && maybeRecordType . isSynthetic ( ) ) { continue ; } return PropDefinitionKind . LOOSE ; } } } if ( type . toMaybeRecordType ( ) != null ) { RecordType rec = type . toMaybeRecordType ( ) ; boolean mayBeInUnion = false ; for ( String pname : rec . getPropertyMap ( ) . getOwnPropertyNames ( ) ) { if ( this . propertiesOfSupertypesInUnions . contains ( pname ) ) { mayBeInUnion = true ; break ; } } if ( mayBeInUnion && this . droppedPropertiesOfUnions . contains ( propertyName ) ) { return PropDefinitionKind . LOOSE ; } } } return PropDefinitionKind . UNKNOWN ; }
Returns whether the given property can possibly be set on the given type .
34,758
ObjectType findCommonSuperObject ( ObjectType a , ObjectType b ) { List < ObjectType > stackA = getSuperStack ( a ) ; List < ObjectType > stackB = getSuperStack ( b ) ; ObjectType result = getNativeObjectType ( JSTypeNative . OBJECT_TYPE ) ; while ( ! stackA . isEmpty ( ) && ! stackB . isEmpty ( ) ) { ObjectType currentA = stackA . remove ( stackA . size ( ) - 1 ) ; ObjectType currentB = stackB . remove ( stackB . size ( ) - 1 ) ; if ( currentA . isEquivalentTo ( currentB ) ) { result = currentA ; } else { return result ; } } return result ; }
Finds the common supertype of the two given object types .
34,759
public void overwriteDeclaredType ( StaticScope scope , String name , JSType type ) { checkState ( isDeclaredForScope ( scope , name ) , "missing name %s" , name ) ; reregister ( scope , type , name ) ; }
Overrides a declared global type name . Throws an exception if this type name hasn t been declared yet .
34,760
public JSType getType ( StaticTypedScope scope , String jsTypeName , String sourceName , int lineno , int charno ) { return getType ( scope , jsTypeName , sourceName , lineno , charno , true ) ; }
Looks up a type by name . To allow for forward references to types an unrecognized string has to be bound to a NamedType object that will be resolved later .
34,761
public void resolveTypes ( ) { for ( NamedType type : unresolvedNamedTypes ) { type . resolve ( reporter ) ; } unresolvedNamedTypes . clear ( ) ; PrototypeObjectType globalThis = ( PrototypeObjectType ) getNativeType ( JSTypeNative . GLOBAL_THIS ) ; JSType windowType = getTypeInternal ( null , "Window" ) ; if ( globalThis . isUnknownType ( ) ) { ObjectType windowObjType = ObjectType . cast ( windowType ) ; if ( windowObjType != null ) { globalThis . setImplicitPrototype ( windowObjType ) ; } else { globalThis . setImplicitPrototype ( getNativeObjectType ( JSTypeNative . OBJECT_TYPE ) ) ; } } }
Resolve all the unresolved types in the given scope .
34,762
public JSType createOptionalType ( JSType type ) { if ( type instanceof UnknownType || type . isAllType ( ) ) { return type ; } else { return createUnionType ( type , getNativeType ( JSTypeNative . VOID_TYPE ) ) ; } }
Creates a type representing optional values of the given type .
34,763
public JSType createOptionalNullableType ( JSType type ) { return createUnionType ( type , getNativeType ( JSTypeNative . VOID_TYPE ) , getNativeType ( JSTypeNative . NULL_TYPE ) ) ; }
Creates a nullable and undefine - able value of the given type .
34,764
public JSType createUnionType ( JSType ... variants ) { UnionTypeBuilder builder = UnionTypeBuilder . create ( this ) ; for ( JSType type : variants ) { builder . addAlternate ( type ) ; } return builder . build ( ) ; }
Creates a union type whose variants are the arguments .
34,765
public JSType createUnionType ( JSTypeNative ... variants ) { UnionTypeBuilder builder = UnionTypeBuilder . create ( this ) ; for ( JSTypeNative typeId : variants ) { builder . addAlternate ( getNativeType ( typeId ) ) ; } return builder . build ( ) ; }
Creates a union type whose variants are the built - in types specified by the arguments .
34,766
public EnumType createEnumType ( String name , Node source , JSType elementsType ) { return new EnumType ( this , name , source , elementsType ) ; }
Creates an enum type .
34,767
public FunctionType createFunctionType ( JSType returnType , JSType ... parameterTypes ) { return createFunctionType ( returnType , createParameters ( parameterTypes ) ) ; }
Creates a function type .
34,768
private Node createParameters ( boolean lastVarArgs , JSType ... parameterTypes ) { FunctionParamBuilder builder = new FunctionParamBuilder ( this ) ; int max = parameterTypes . length - 1 ; for ( int i = 0 ; i <= max ; i ++ ) { if ( lastVarArgs && i == max ) { builder . addVarArgs ( parameterTypes [ i ] ) ; } else { builder . addRequiredParams ( parameterTypes [ i ] ) ; } } return builder . build ( ) ; }
Creates a tree hierarchy representing a typed argument list .
34,769
public Node createOptionalParameters ( JSType ... parameterTypes ) { FunctionParamBuilder builder = new FunctionParamBuilder ( this ) ; builder . addOptionalParams ( parameterTypes ) ; return builder . build ( ) ; }
Creates a tree hierarchy representing a typed parameter list in which every parameter is optional .
34,770
public FunctionType createFunctionTypeWithNewReturnType ( FunctionType existingFunctionType , JSType returnType ) { return FunctionType . builder ( this ) . copyFromOtherFunction ( existingFunctionType ) . withReturnType ( returnType ) . build ( ) ; }
Creates a new function type based on an existing function type but with a new return type .
34,771
public ObjectType createAnonymousObjectType ( JSDocInfo info ) { PrototypeObjectType type = new PrototypeObjectType ( this , null , null , true ) ; type . setPrettyPrint ( true ) ; type . setJSDocInfo ( info ) ; return type ; }
Create an anonymous object type .
34,772
public FunctionType createConstructorType ( String name , Node source , Node parameters , JSType returnType , ImmutableList < TemplateType > templateKeys , boolean isAbstract ) { checkArgument ( source == null || source . isFunction ( ) || source . isClass ( ) ) ; return FunctionType . builder ( this ) . forConstructor ( ) . withName ( name ) . withSourceNode ( source ) . withParamsNode ( parameters ) . withReturnType ( returnType ) . withTemplateKeys ( templateKeys ) . withIsAbstract ( isAbstract ) . build ( ) ; }
Creates a constructor function type .
34,773
public FunctionType createInterfaceType ( String name , Node source , ImmutableList < TemplateType > templateKeys , boolean struct ) { FunctionType fn = FunctionType . builder ( this ) . forInterface ( ) . withName ( name ) . withSourceNode ( source ) . withEmptyParams ( ) . withTemplateKeys ( templateKeys ) . build ( ) ; if ( struct ) { fn . setStruct ( ) ; } return fn ; }
Creates an interface function type .
34,774
public TemplateTypeMap createTemplateTypeMap ( ImmutableList < TemplateType > templateKeys , ImmutableList < JSType > templateValues ) { if ( templateKeys == null ) { templateKeys = ImmutableList . of ( ) ; } if ( templateValues == null ) { templateValues = ImmutableList . of ( ) ; } return ( templateKeys . isEmpty ( ) && templateValues . isEmpty ( ) ) ? emptyTemplateTypeMap : new TemplateTypeMap ( this , templateKeys , templateValues ) ; }
Creates a template type map from the specified list of template keys and template value types .
34,775
public NamedType createNamedType ( StaticTypedScope scope , String reference , String sourceName , int lineno , int charno ) { return new NamedType ( scope , this , reference , sourceName , lineno , charno ) ; }
Creates a named type .
34,776
@ SuppressWarnings ( "unchecked" ) public JSType createTypeFromCommentNode ( Node n , String sourceName , StaticTypedScope scope ) { return createFromTypeNodesInternal ( n , sourceName , scope , true ) ; }
Creates a JSType from the nodes representing a type .
34,777
private JSType createRecordTypeFromNodes ( Node n , String sourceName , StaticTypedScope scope ) { RecordTypeBuilder builder = new RecordTypeBuilder ( this ) ; for ( Node fieldTypeNode = n . getFirstChild ( ) ; fieldTypeNode != null ; fieldTypeNode = fieldTypeNode . getNext ( ) ) { Node fieldNameNode = fieldTypeNode ; boolean hasType = false ; if ( fieldTypeNode . getToken ( ) == Token . COLON ) { fieldNameNode = fieldTypeNode . getFirstChild ( ) ; hasType = true ; } String fieldName = fieldNameNode . getString ( ) ; if ( fieldName . startsWith ( "'" ) || fieldName . startsWith ( "\"" ) ) { fieldName = fieldName . substring ( 1 , fieldName . length ( ) - 1 ) ; } JSType fieldType = null ; if ( hasType ) { fieldType = createFromTypeNodesInternal ( fieldTypeNode . getLastChild ( ) , sourceName , scope , true ) ; } else { fieldType = getNativeType ( JSTypeNative . UNKNOWN_TYPE ) ; } builder . addProperty ( fieldName , fieldType , fieldNameNode ) ; } return builder . build ( ) ; }
Creates a RecordType from the nodes representing said record type .
34,778
public void registerTemplateTypeNamesInScope ( Iterable < TemplateType > keys , Node scopeRoot ) { for ( TemplateType key : keys ) { scopedNameTable . put ( scopeRoot , key . getReferenceName ( ) , key ) ; } }
Registers template types on the given scope root . This takes a Node rather than a StaticScope because at the time it is called the scope has not yet been created .
34,779
public StaticTypedScope createScopeWithTemplates ( StaticTypedScope scope , Iterable < TemplateType > templates ) { return new SyntheticTemplateScope ( scope , templates ) ; }
Returns a new scope that includes the given template names for type resolution purposes .
34,780
@ SuppressWarnings ( "unchecked" ) @ GwtIncompatible ( "ObjectOutputStream" ) public void saveContents ( ObjectOutputStream out ) throws IOException { out . writeObject ( eachRefTypeIndexedByProperty ) ; out . writeObject ( interfaceToImplementors ) ; out . writeObject ( typesIndexedByProperty ) ; }
Saves the derived state .
34,781
@ SuppressWarnings ( "unchecked" ) @ GwtIncompatible ( "ObjectInputStream" ) public void restoreContents ( ObjectInputStream in ) throws IOException , ClassNotFoundException { eachRefTypeIndexedByProperty = ( Map < String , Map < String , ObjectType > > ) in . readObject ( ) ; interfaceToImplementors = ( Multimap < String , FunctionType > ) in . readObject ( ) ; typesIndexedByProperty = ( Multimap < String , JSType > ) in . readObject ( ) ; }
Restores the derived state .
34,782
private void suppressBehavior ( Node behaviorValue , Node reportNode ) { if ( behaviorValue == null ) { compiler . report ( JSError . make ( reportNode , PolymerPassErrors . POLYMER_UNQUALIFIED_BEHAVIOR ) ) ; return ; } if ( behaviorValue . isArrayLit ( ) ) { for ( Node child : behaviorValue . children ( ) ) { suppressBehavior ( child , behaviorValue ) ; } } else if ( behaviorValue . isObjectLit ( ) ) { stripPropertyTypes ( behaviorValue ) ; addBehaviorSuppressions ( behaviorValue ) ; } }
Strip property type annotations and add suppressions on functions .
34,783
public static void encode ( Appendable out , int value ) throws IOException { value = toVLQSigned ( value ) ; do { int digit = value & VLQ_BASE_MASK ; value >>>= VLQ_BASE_SHIFT ; if ( value > 0 ) { digit |= VLQ_CONTINUATION_BIT ; } out . append ( Base64 . toBase64 ( digit ) ) ; } while ( value > 0 ) ; }
Writes a VLQ encoded value to the provide appendable .
34,784
public static int decode ( CharIterator in ) { int result = 0 ; boolean continuation ; int shift = 0 ; do { char c = in . next ( ) ; int digit = Base64 . fromBase64 ( c ) ; continuation = ( digit & VLQ_CONTINUATION_BIT ) != 0 ; digit &= VLQ_BASE_MASK ; result = result + ( digit << shift ) ; shift = shift + VLQ_BASE_SHIFT ; } while ( continuation ) ; return fromVLQSigned ( result ) ; }
Decodes the next VLQValue from the provided CharIterator .
34,785
public List < Symbol > getAllSymbolsSorted ( ) { List < Symbol > sortedSymbols = getNaturalSymbolOrdering ( ) . sortedCopy ( symbols . values ( ) ) ; return sortedSymbols ; }
Get the symbols in their natural ordering . Always returns a mutable list .
34,786
public Symbol getSymbolForScope ( SymbolScope scope ) { if ( scope . getSymbolForScope ( ) == null ) { scope . setSymbolForScope ( findSymbolForScope ( scope ) ) ; } return scope . getSymbolForScope ( ) ; }
All local scopes are associated with a function and some functions are associated with a symbol . Returns the symbol associated with the given scope .
34,787
private Symbol findSymbolForScope ( SymbolScope scope ) { Node rootNode = scope . getRootNode ( ) ; if ( rootNode . getParent ( ) == null ) { return globalScope . getSlot ( GLOBAL_THIS ) ; } if ( ! rootNode . isFunction ( ) ) { return null ; } String name = NodeUtil . getBestLValueName ( NodeUtil . getBestLValue ( rootNode ) ) ; return name == null ? null : scope . getParentScope ( ) . getQualifiedSlot ( name ) ; }
Find the symbol associated with the given scope . Notice that we won t always be able to figure out this association dynamically so sometimes we ll just create the association when we create the scope .
34,788
public Symbol getSymbolDeclaredBy ( FunctionType fn ) { checkState ( fn . isConstructor ( ) || fn . isInterface ( ) ) ; ObjectType instanceType = fn . getInstanceType ( ) ; return getSymbolForName ( fn . getSource ( ) , instanceType . getReferenceName ( ) ) ; }
Gets the symbol for the given constructor or interface .
34,789
public Symbol getSymbolForInstancesOf ( Symbol sym ) { FunctionType fn = sym . getFunctionType ( ) ; if ( fn != null && fn . isNominalConstructor ( ) ) { return getSymbolForInstancesOf ( fn ) ; } return null ; }
Gets the symbol for the prototype if this is the symbol for a constructor or interface .
34,790
public Symbol getSymbolForInstancesOf ( FunctionType fn ) { checkState ( fn . isConstructor ( ) || fn . isInterface ( ) ) ; ObjectType pType = fn . getPrototype ( ) ; return getSymbolForName ( fn . getSource ( ) , pType . getReferenceName ( ) ) ; }
Gets the symbol for the prototype of the given constructor or interface .
34,791
public List < Symbol > getAllSymbolsForType ( JSType type ) { if ( type == null ) { return ImmutableList . of ( ) ; } UnionType unionType = type . toMaybeUnionType ( ) ; if ( unionType != null ) { List < Symbol > result = new ArrayList < > ( 2 ) ; for ( JSType alt : unionType . getAlternates ( ) ) { Symbol altSym = getSymbolForTypeHelper ( alt , true ) ; if ( altSym != null ) { result . add ( altSym ) ; } } return result ; } Symbol result = getSymbolForTypeHelper ( type , true ) ; return result == null ? ImmutableList . of ( ) : ImmutableList . of ( result ) ; }
Gets all symbols associated with the given type . For union types this may be multiple symbols . For instance types this will return the constructor of that instance .
34,792
private Symbol getSymbolForTypeHelper ( JSType type , boolean linkToCtor ) { if ( type == null ) { return null ; } if ( type . isGlobalThisType ( ) ) { return globalScope . getSlot ( GLOBAL_THIS ) ; } else if ( type . isNominalConstructor ( ) ) { return linkToCtor ? globalScope . getSlot ( "Function" ) : getSymbolDeclaredBy ( type . toMaybeFunctionType ( ) ) ; } else if ( type . isFunctionPrototypeType ( ) ) { FunctionType ownerFn = ( ( ObjectType ) type ) . getOwnerFunction ( ) ; if ( ! ownerFn . isConstructor ( ) && ! ownerFn . isInterface ( ) ) { return null ; } return linkToCtor ? getSymbolDeclaredBy ( ownerFn ) : getSymbolForInstancesOf ( ownerFn ) ; } else if ( type . isInstanceType ( ) ) { FunctionType ownerFn = ( ( ObjectType ) type ) . getConstructor ( ) ; return linkToCtor ? getSymbolDeclaredBy ( ownerFn ) : getSymbolForInstancesOf ( ownerFn ) ; } else if ( type . isFunctionType ( ) ) { return linkToCtor ? globalScope . getSlot ( "Function" ) : globalScope . getQualifiedSlot ( "Function.prototype" ) ; } else if ( type . autoboxesTo ( ) != null ) { return getSymbolForTypeHelper ( type . autoboxesTo ( ) , linkToCtor ) ; } else { return null ; } }
Gets all symbols associated with the given type . If there is more that one symbol associated with the given type return null .
34,793
void findScopes ( Node externs , Node root ) { NodeTraversal . traverseRoots ( compiler , new NodeTraversal . AbstractScopedCallback ( ) { public void enterScope ( NodeTraversal t ) { createScopeFrom ( t . getScope ( ) ) ; } public void visit ( NodeTraversal t , Node n , Node p ) { } } , externs , root ) ; }
Finds all the scopes and adds them to this symbol table .
34,794
public void addAnonymousFunctions ( ) { TreeSet < SymbolScope > scopes = new TreeSet < > ( lexicalScopeOrdering ) ; for ( SymbolScope scope : getAllScopes ( ) ) { if ( scope . isLexicalScope ( ) ) { scopes . add ( scope ) ; } } for ( SymbolScope scope : scopes ) { addAnonymousFunctionsInScope ( scope ) ; } }
Finds anonymous functions in local scopes and gives them names and symbols . They will show up as local variables with names function%0 function%1 etc .
34,795
private Symbol isAnySymbolDeclared ( String name , Node declNode , SymbolScope scope ) { Symbol sym = symbols . get ( declNode , name ) ; if ( sym == null ) { return scope . ownSymbols . get ( name ) ; } return sym ; }
Checks if any symbol is already declared at the given node and scope for the given name . If so returns it .
34,796
private < S extends StaticSlot , R extends StaticRef > StaticRef findBestDeclToAdd ( StaticSymbolTable < S , R > otherSymbolTable , S slot ) { StaticRef decl = slot . getDeclaration ( ) ; if ( isGoodRefToAdd ( decl ) ) { return decl ; } for ( R ref : otherSymbolTable . getReferences ( slot ) ) { if ( isGoodRefToAdd ( ref ) ) { return ref ; } } return null ; }
Helper for addSymbolsFrom to determine the best declaration spot .
34,797
private void mergeSymbol ( Symbol from , Symbol to ) { for ( Node nodeToMove : from . references . keySet ( ) ) { if ( ! nodeToMove . equals ( from . getDeclarationNode ( ) ) ) { to . defineReferenceAt ( nodeToMove ) ; } } removeSymbol ( from ) ; }
Merges from symbol to to symbol by moving all references to point to the to symbol and removing from symbol .
34,798
void pruneOrphanedNames ( ) { nextSymbol : for ( Symbol s : getAllSymbols ( ) ) { if ( s . isProperty ( ) ) { continue ; } String currentName = s . getName ( ) ; int dot = - 1 ; while ( - 1 != ( dot = currentName . lastIndexOf ( '.' ) ) ) { currentName = currentName . substring ( 0 , dot ) ; Symbol owner = s . scope . getQualifiedSlot ( currentName ) ; if ( owner != null && getType ( owner ) != null && ( getType ( owner ) . isNominalConstructor ( ) || getType ( owner ) . isFunctionPrototypeType ( ) || getType ( owner ) . isEnumType ( ) ) ) { removeSymbol ( s ) ; continue nextSymbol ; } } } }
Removes symbols where the namespace they re on has been removed .
34,799
void fillJSDocInfo ( Node externs , Node root ) { NodeTraversal . traverseRoots ( compiler , new JSDocInfoCollector ( compiler . getTypeRegistry ( ) ) , externs , root ) ; for ( Symbol sym : getAllSymbols ( ) ) { JSDocInfo info = sym . getJSDocInfo ( ) ; if ( info == null ) { continue ; } for ( Marker marker : info . getMarkers ( ) ) { SourcePosition < Node > pos = marker . getNameNode ( ) ; if ( pos == null ) { continue ; } Node paramNode = pos . getItem ( ) ; String name = paramNode . getString ( ) ; Symbol param = getParameterInFunction ( sym , name ) ; if ( param == null ) { SourcePosition < Node > typePos = marker . getType ( ) ; JSType type = null ; if ( typePos != null ) { type = typePos . getItem ( ) . getJSType ( ) ; } if ( sym . docScope == null ) { sym . docScope = new SymbolScope ( null , null , null , sym ) ; } Symbol existingSymbol = isAnySymbolDeclared ( name , paramNode , sym . docScope ) ; if ( existingSymbol == null ) { declareSymbol ( name , type , type == null , sym . docScope , paramNode , null ) ; } } else { param . defineReferenceAt ( paramNode ) ; } } } }
Index JSDocInfo .