idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
34,300
void expectCanCast ( Node n , JSType targetType , JSType sourceType ) { if ( ! sourceType . canCastTo ( targetType ) ) { registerMismatch ( sourceType , targetType , report ( JSError . make ( n , INVALID_CAST , sourceType . toString ( ) , targetType . toString ( ) ) ) ) ; } else if ( ! sourceType . isSubtypeWithoutStru...
Expect that the first type can be cast to the second type . The first type must have some relationship with the second .
34,301
TypedVar expectUndeclaredVariable ( String sourceName , CompilerInput input , Node n , Node parent , TypedVar var , String variableName , JSType newType ) { TypedVar newVar = var ; JSType varType = var . getType ( ) ; if ( varType != null && varType != typeRegistry . getNativeType ( UNKNOWN_TYPE ) && newType != null &&...
Expect that the given variable has not been declared with a type .
34,302
void expectAllInterfaceProperties ( Node n , FunctionType type ) { ObjectType instance = type . getInstanceType ( ) ; for ( ObjectType implemented : type . getAllImplementedInterfaces ( ) ) { if ( implemented . getImplicitPrototype ( ) != null ) { for ( String prop : implemented . getImplicitPrototype ( ) . getOwnPrope...
Expect that all properties on interfaces that this type implements are implemented and correctly typed .
34,303
private void expectInterfaceProperty ( Node n , ObjectType instance , ObjectType implementedInterface , String prop ) { StaticTypedSlot propSlot = instance . getSlot ( prop ) ; if ( propSlot == null ) { String sourceName = n . getSourceFileName ( ) ; sourceName = nullToEmpty ( sourceName ) ; registerMismatch ( instance...
Expect that the property in an interface that this type implements is implemented and correctly typed .
34,304
void expectAbstractMethodsImplemented ( Node n , FunctionType ctorType ) { checkArgument ( ctorType . isConstructor ( ) ) ; Map < String , ObjectType > abstractMethodSuperTypeMap = new LinkedHashMap < > ( ) ; FunctionType currSuperCtor = ctorType . getSuperClassConstructor ( ) ; if ( currSuperCtor == null || ! currSupe...
For a concrete class expect that all abstract methods that haven t been implemented by any of the super classes on the inheritance chain are implemented .
34,305
private void registerMismatchAndReport ( Node n , DiagnosticType diagnostic , String msg , JSType found , JSType required , Set < String > missing , Set < String > mismatch ) { String foundRequiredFormatted = formatFoundRequired ( msg , found , required , missing , mismatch ) ; JSError err = JSError . make ( n , diagno...
Used both for TYPE_MISMATCH_WARNING and INVALID_OPERAND_TYPE .
34,306
private void registerMismatch ( JSType found , JSType required , JSError error ) { TypeMismatch . registerMismatch ( this . mismatches , this . implicitInterfaceUses , found , required , error ) ; }
Registers a type mismatch into the universe of mismatches owned by this pass .
34,307
private void tryEliminateOptionalArgs ( ArrayList < Node > refs ) { int maxArgs = - 1 ; for ( Node n : refs ) { if ( ReferenceMap . isCallOrNewTarget ( n ) ) { int numArgs = 0 ; Node firstArg = ReferenceMap . getFirstArgumentForCallOrNewOrDotCall ( n ) ; for ( Node c = firstArg ; c != null ; c = c . getNext ( ) ) { num...
Removes any optional parameters if no callers specifies it as an argument .
34,308
private void tryEliminateConstantArgs ( ArrayList < Node > refs ) { List < Parameter > parameters = findFixedArguments ( refs ) ; if ( parameters == null ) { return ; } ImmutableListMultimap < Node , Node > fns = ReferenceMap . getFunctionNodes ( refs ) ; if ( fns . size ( ) > 1 ) { return ; } Node fn = Iterables . get...
Eliminate parameters if they are always constant .
34,309
private boolean findFixedParameters ( List < Parameter > parameters , Node cur ) { boolean anyMovable = false ; int index = 0 ; while ( cur != null ) { Parameter p ; if ( index >= parameters . size ( ) ) { p = new Parameter ( cur , false ) ; parameters . add ( p ) ; setParameterSideEffectInfo ( p , cur ) ; } else { p =...
Determine which parameters use the same expression .
34,310
private void eliminateParamsAfter ( Node fnNode , int argIndex ) { Node formalArgPtr = NodeUtil . getFunctionParameters ( fnNode ) . getFirstChild ( ) ; while ( argIndex != 0 && formalArgPtr != null ) { formalArgPtr = formalArgPtr . getNext ( ) ; argIndex -- ; } eliminateParamsAfter ( fnNode , formalArgPtr ) ; }
Removes all formal parameters starting at argIndex .
34,311
private void eliminateCallTargetArgAt ( Node ref , int argIndex ) { Node callArgNode = ReferenceMap . getArgumentForCallOrNewOrDotCall ( ref , argIndex ) ; if ( callArgNode != null ) { NodeUtil . deleteNode ( callArgNode , compiler ) ; } }
Eliminates the parameter from a function call .
34,312
private boolean maybeUseNativeClassTemplateNames ( JSDocInfo info ) { ImmutableList < TemplateType > nativeKeys = typeRegistry . maybeGetTemplateTypesOfBuiltin ( fnName ) ; if ( nativeKeys != null && info . getTemplateTypeNames ( ) . size ( ) == nativeKeys . size ( ) ) { this . templateTypeNames = nativeKeys ; return t...
Clobber the templateTypeNames from the JSDoc with builtin ones for native types .
34,313
FunctionTypeBuilder inferParameterTypes ( JSDocInfo info ) { Node lp = IR . paramList ( ) ; for ( String name : info . getParameterNames ( ) ) { lp . addChildToBack ( IR . name ( name ) ) ; } return inferParameterTypes ( lp , info ) ; }
Infer the parameter types from the doc info alone .
34,314
FunctionTypeBuilder inferConstructorParameters ( FunctionType superCtor ) { inferImplicitConstructorParameters ( superCtor . getParametersNode ( ) . cloneTree ( ) ) ; setConstructorTemplateTypeNames ( superCtor . getConstructorOnlyTemplateParameters ( ) , null ) ; return this ; }
Infer constructor parameters from the superclass constructor .
34,315
private boolean addParameter ( FunctionParamBuilder builder , JSType paramType , boolean warnedAboutArgList , boolean isOptional , boolean isVarArgs ) { boolean emittedWarning = false ; if ( isOptional ) { if ( ! builder . addOptionalParams ( paramType ) && ! warnedAboutArgList ) { reportWarning ( VAR_ARGS_MUST_BE_LAST...
Add a parameter to the param list .
34,316
private void provideDefaultReturnType ( ) { if ( contents . getSourceNode ( ) != null && contents . getSourceNode ( ) . isAsyncGeneratorFunction ( ) ) { ObjectType generatorType = typeRegistry . getNativeObjectType ( ASYNC_GENERATOR_TYPE ) ; returnType = typeRegistry . createTemplatizedType ( generatorType , typeRegist...
Sets the returnType for this function using very basic type inference .
34,317
FunctionType buildAndRegister ( ) { if ( returnType == null ) { provideDefaultReturnType ( ) ; checkNotNull ( returnType ) ; } if ( parametersNode == null ) { throw new IllegalStateException ( "All Function types must have params and a return type" ) ; } FunctionType fnType ; if ( isConstructor ) { fnType = getOrCreate...
Builds the function type and puts it in the registry .
34,318
static boolean isFunctionTypeDeclaration ( JSDocInfo info ) { return info . getParameterCount ( ) > 0 || info . hasReturnType ( ) || info . hasThisType ( ) || info . isConstructor ( ) || info . isInterface ( ) || info . isAbstract ( ) ; }
Determines whether the given JsDoc info declares a function type .
34,319
private TypedScope getScopeDeclaredIn ( ) { if ( declarationScope != null ) { return declarationScope ; } int dotIndex = fnName . indexOf ( '.' ) ; if ( dotIndex != - 1 ) { String rootVarName = fnName . substring ( 0 , dotIndex ) ; TypedVar rootVar = enclosingScope . getVar ( rootVarName ) ; if ( rootVar != null ) { re...
The scope that we should declare this function in if it needs to be declared in a scope . Notice that TypedScopeCreator takes care of most scope - declaring .
34,320
private static boolean hasMoreTagsToResolve ( ObjectType objectType ) { checkArgument ( objectType . isUnknownType ( ) ) ; FunctionType ctor = objectType . getConstructor ( ) ; if ( ctor != null ) { for ( ObjectType interfaceType : ctor . getExtendedInterfaces ( ) ) { if ( ! interfaceType . isResolved ( ) ) { return tr...
Check whether a type is resolvable in the future If this has a supertype that hasn t been resolved yet then we can assume this type will be OK once the super type resolves .
34,321
private void checkForUnusedLocalVar ( Var v , Reference unusedAssignment ) { if ( ! v . isLocal ( ) ) { return ; } JSDocInfo jsDoc = NodeUtil . getBestJSDocInfo ( unusedAssignment . getNode ( ) ) ; if ( jsDoc != null && jsDoc . hasTypedefType ( ) ) { return ; } boolean inGoogScope = false ; Scope s = v . getScope ( ) ;...
that we can run it after goog . scope processing and get rid of the inGoogScope check .
34,322
private void instrumentBranchCoverage ( NodeTraversal traversal , FileInstrumentationData data ) { int maxLine = data . maxBranchPresentLine ( ) ; int branchCoverageOffset = 0 ; for ( int lineIdx = 1 ; lineIdx <= maxLine ; ++ lineIdx ) { Integer numBranches = data . getNumBranches ( lineIdx ) ; if ( numBranches != null...
Add instrumentation code for branch coverage . For each block that correspond to a branch insert an assignment of the branch coverage data to the front of the block .
34,323
private Node newBranchInstrumentationNode ( NodeTraversal traversal , Node node , int idx ) { String arrayName = createArrayName ( traversal ) ; Node getElemNode = IR . getelem ( IR . name ( arrayName ) , IR . number ( idx ) ) ; Node exprNode = IR . exprResult ( IR . assign ( getElemNode , IR . trueNode ( ) ) ) ; Strin...
Create an assignment to the branch coverage data for the given index into the array .
34,324
private void processBranchInfo ( Node branchNode , FileInstrumentationData data , List < Node > blocks ) { int lineNumber = branchNode . getLineno ( ) ; data . setBranchPresent ( lineNumber ) ; int numBranches = 0 ; for ( Node child : blocks ) { data . putBranchNode ( lineNumber , numBranches + 1 , child ) ; numBranche...
Add branch instrumentation information for each block .
34,325
static ImmutableList < Require > getAllRequires ( Node nameDeclaration ) { Node rhs = nameDeclaration . getFirstChild ( ) . isDestructuringLhs ( ) ? nameDeclaration . getFirstChild ( ) . getSecondChild ( ) : nameDeclaration . getFirstFirstChild ( ) ; Binding . CreatedBy requireKind = getModuleDependencyTypeFromRhs ( rh...
Returns all Require built from the given statement or null if it is not a require
34,326
public void setWarningLevel ( CompilerOptions options , String name , CheckLevel level ) { DiagnosticGroup group = forName ( name ) ; Preconditions . checkNotNull ( group , "No warning class for name: %s" , name ) ; options . setWarningLevel ( group , level ) ; }
Adds warning levels by name .
34,327
public void process ( Node externs , Node root ) { checkState ( topLevelStatements . isEmpty ( ) , "process() called more than once" ) ; NodeTraversal t = new NodeTraversal ( compiler , this , scopeCreator ) ; t . traverseRoots ( externs , root ) ; }
Convenience method for running this pass over a tree with this class as a callback .
34,328
public static TernaryValue isStrWhiteSpaceChar ( int c ) { switch ( c ) { case '\u000B' : return TernaryValue . UNKNOWN ; case ' ' : case '\n' : case '\r' : case '\t' : case '\u00A0' : case '\u000C' : case '\u2028' : case '\u2029' : case '\uFEFF' : return TernaryValue . TRUE ; default : return ( Character . getType ( c...
Copied from Rhino s ScriptRuntime
34,329
boolean isRemovableAssign ( Node n ) { return ( NodeUtil . isAssignmentOp ( n ) && n . getFirstChild ( ) . isName ( ) ) || n . isInc ( ) || n . isDec ( ) ; }
will already remove variables that are initialized but unused .
34,330
private void tryRemoveDeadAssignments ( NodeTraversal t , ControlFlowGraph < Node > cfg , Map < String , Var > allVarsInFn ) { Iterable < DiGraphNode < Node , Branch > > nodes = cfg . getDirectedGraphNodes ( ) ; for ( DiGraphNode < Node , Branch > cfgNode : nodes ) { FlowState < LiveVariableLattice > state = cfgNode . ...
Try to remove useless assignments from a control flow graph that has been annotated with liveness information .
34,331
private boolean isVariableStillLiveWithinExpression ( Node n , Node exprRoot , String variable ) { while ( n != exprRoot ) { VariableLiveness state = VariableLiveness . MAYBE_LIVE ; switch ( n . getParent ( ) . getToken ( ) ) { case OR : case AND : if ( n . getNext ( ) != null ) { state = isVariableReadBeforeKill ( n ....
Given a variable node n in the tree and a sub - tree denoted by exprRoot as the root this function returns true if there exists a read of that variable before a write to that variable that is on the right side of n .
34,332
private VariableLiveness isVariableReadBeforeKill ( Node n , String variable ) { if ( ControlFlowGraph . isEnteringNewCfgNode ( n ) ) { return VariableLiveness . MAYBE_LIVE ; } if ( n . isName ( ) && variable . equals ( n . getString ( ) ) ) { if ( NodeUtil . isNameDeclOrSimpleAssignLhs ( n , n . getParent ( ) ) ) { ch...
Give an expression and a variable . It returns READ if the first reference of that variable is a read . It returns KILL if the first reference of that variable is an assignment . It returns MAY_LIVE otherwise .
34,333
public final String getNormalizedReferenceName ( ) { String name = getReferenceName ( ) ; if ( name != null ) { int start = name . indexOf ( '(' ) ; if ( start != - 1 ) { int end = name . lastIndexOf ( ')' ) ; String prefix = name . substring ( 0 , start ) ; return end + 1 % name . length ( ) == 0 ? prefix : prefix + n...
Due to the complexity of some of our internal type systems sometimes we have different types constructed by the same constructor . In other parts of the type system these are called delegates . We construct these types by appending suffixes to the constructor name .
34,334
public final boolean defineDeclaredProperty ( String propertyName , JSType type , Node propertyNode ) { boolean result = defineProperty ( propertyName , type , false , propertyNode ) ; registry . registerPropertyOnType ( propertyName , this ) ; return result ; }
Defines a property whose type is explicitly declared by the programmer .
34,335
public final boolean defineSynthesizedProperty ( String propertyName , JSType type , Node propertyNode ) { return defineProperty ( propertyName , type , false , propertyNode ) ; }
Defines a property whose type is on a synthesized object . These objects don t actually exist in the user s program . They re just used for bookkeeping in the type system .
34,336
public final boolean defineInferredProperty ( String propertyName , JSType type , Node propertyNode ) { if ( hasProperty ( propertyName ) ) { if ( isPropertyTypeDeclared ( propertyName ) ) { return true ; } JSType originalType = getPropertyType ( propertyName ) ; type = originalType == null ? type : originalType . getL...
Defines a property whose type is inferred .
34,337
public final JSDocInfo getOwnPropertyJSDocInfo ( String propertyName ) { Property p = getOwnSlot ( propertyName ) ; return p == null ? null : p . getJSDocInfo ( ) ; }
Gets the docInfo on the specified property on this type . This should not be implemented recursively as you generally need to know exactly on which type in the prototype chain the JSDocInfo exists .
34,338
public JSType getPropertyType ( String propertyName ) { StaticTypedSlot slot = getSlot ( propertyName ) ; if ( slot == null ) { if ( isNoResolvedType ( ) || isCheckedUnknownType ( ) ) { return getNativeType ( JSTypeNative . CHECKED_UNKNOWN_TYPE ) ; } else if ( isEmptyType ( ) ) { return getNativeType ( JSTypeNative . N...
Gets the property type of the property whose name is given . If the underlying object does not have this property the Unknown type is returned to indicate that no information is available on this property .
34,339
public final HasPropertyKind getOwnPropertyKind ( String propertyName ) { return getOwnSlot ( propertyName ) != null ? HasPropertyKind . KNOWN_PRESENT : HasPropertyKind . ABSENT ; }
Checks whether the property whose name is given is present directly on the object . Returns false even if it is declared on a supertype .
34,340
public final boolean isPropertyTypeDeclared ( String propertyName ) { StaticTypedSlot slot = getSlot ( propertyName ) ; return slot == null ? false : ! slot . isTypeInferred ( ) ; }
Checks whether the property s type is declared .
34,341
public final boolean isPropertyInExterns ( String propertyName ) { Property p = getSlot ( propertyName ) ; return p == null ? false : p . isFromExterns ( ) ; }
Checks whether the property was defined in the externs .
34,342
public final Set < String > getPropertyNames ( ) { Set < String > props = new TreeSet < > ( ) ; collectPropertyNames ( props ) ; return props ; }
Returns a list of properties defined or inferred on this type and any of its supertypes .
34,343
@ SuppressWarnings ( "ReferenceEquality" ) final boolean isImplicitPrototype ( ObjectType prototype ) { for ( ObjectType current = this ; current != null ; current = current . getImplicitPrototype ( ) ) { if ( current . isTemplatizedType ( ) ) { current = current . toMaybeTemplatizedType ( ) . getReferencedType ( ) ; }...
Checks that the prototype is an implicit prototype of this object . Since each object has an implicit prototype an implicit prototype s implicit prototype is also this implicit prototype s .
34,344
public boolean isUnknownType ( ) { if ( unknown ) { ObjectType implicitProto = getImplicitPrototype ( ) ; if ( implicitProto == null || implicitProto . isNativeObjectType ( ) ) { unknown = false ; for ( ObjectType interfaceType : getCtorExtendedInterfaces ( ) ) { if ( interfaceType . isUnknownType ( ) ) { unknown = tru...
We treat this as the unknown type if any of its implicit prototype properties is unknown .
34,345
public Map < String , JSType > getPropertyTypeMap ( ) { ImmutableMap . Builder < String , JSType > propTypeMap = ImmutableMap . builder ( ) ; for ( String name : this . getPropertyNames ( ) ) { propTypeMap . put ( name , this . getPropertyType ( name ) ) ; } return propTypeMap . build ( ) ; }
get the map of properties to types covered in an object type
34,346
private void reportMissingConst ( NodeTraversal t ) { for ( Node n : candidates ) { String propName = n . getLastChild ( ) . getString ( ) ; if ( ! modified . contains ( propName ) ) { t . report ( n , MISSING_CONST_PROPERTY , propName ) ; } } candidates . clear ( ) ; modified . clear ( ) ; }
Reports the property definitions that should use the
34,347
public void addAfter ( CompilerInput input , CompilerInput other ) { checkState ( inputs . contains ( other ) ) ; inputs . add ( inputs . indexOf ( other ) , input ) ; input . setModule ( this ) ; }
Adds a source code input to this module directly after other .
34,348
public void addDependency ( JSModule dep ) { checkNotNull ( dep ) ; Preconditions . checkState ( dep != this , "Cannot add dependency on self" , this ) ; deps . add ( dep ) ; }
Adds a dependency on another module .
34,349
List < String > getSortedDependencyNames ( ) { List < String > names = new ArrayList < > ( ) ; for ( JSModule module : getDependencies ( ) ) { names . add ( module . getName ( ) ) ; } Collections . sort ( names ) ; return names ; }
Gets the names of the modules that this module depends on sorted alphabetically .
34,350
public Set < JSModule > getAllDependencies ( ) { Set < JSModule > allDeps = Sets . newIdentityHashSet ( ) ; allDeps . addAll ( deps ) ; ArrayDeque < JSModule > stack = new ArrayDeque < > ( deps ) ; while ( ! stack . isEmpty ( ) ) { JSModule module = stack . pop ( ) ; List < JSModule > moduleDeps = module . deps ; for (...
Returns the transitive closure of dependencies starting from the dependencies of this module .
34,351
public Set < JSModule > getThisAndAllDependencies ( ) { Set < JSModule > deps = getAllDependencies ( ) ; deps . add ( this ) ; return deps ; }
Returns this module and all of its dependencies in one list .
34,352
public CompilerInput getByName ( String name ) { for ( CompilerInput input : inputs ) { if ( name . equals ( input . getName ( ) ) ) { return input ; } } return null ; }
Returns the input with the given name or null if none .
34,353
public boolean removeByName ( String name ) { boolean found = false ; Iterator < CompilerInput > iter = inputs . iterator ( ) ; while ( iter . hasNext ( ) ) { CompilerInput file = iter . next ( ) ; if ( name . equals ( file . getName ( ) ) ) { iter . remove ( ) ; file . setModule ( null ) ; found = true ; } } return fo...
Removes any input with the given name . Returns whether any were removed .
34,354
public void sortInputsByDeps ( AbstractCompiler compiler ) { for ( CompilerInput input : inputs ) { input . setCompiler ( compiler ) ; } List < CompilerInput > sortedList = new Es6SortedDependencies < > ( inputs ) . getSortedList ( ) ; inputs . clear ( ) ; inputs . addAll ( sortedList ) ; }
Puts the JS files into a topologically sorted order by their dependencies .
34,355
private void tryReplaceArguments ( Scope scope ) { Node parametersList = NodeUtil . getFunctionParameters ( scope . getRootNode ( ) ) ; checkState ( parametersList . isParamList ( ) , parametersList ) ; int numParameters = parametersList . getChildCount ( ) ; int highestIndex = getHighestIndex ( numParameters - 1 ) ; i...
Tries to optimize all the arguments array access in this scope by assigning a name to each element .
34,356
private int getHighestIndex ( int highestIndex ) { for ( Node ref : currentArgumentsAccesses ) { Node getElem = ref . getParent ( ) ; if ( ! getElem . isGetElem ( ) || ref != getElem . getFirstChild ( ) ) { return - 1 ; } Node index = ref . getNext ( ) ; if ( ! index . isNumber ( ) || index . getDouble ( ) < 0 ) { retu...
Iterate through all the references to arguments array in the function to determine the real highestIndex . Returns - 1 when we should not be replacing any arguments for this scope - we should exit tryReplaceArguments
34,357
private void changeMethodSignature ( ImmutableSortedMap < Integer , String > argNames , Node paramList ) { ImmutableSortedMap < Integer , String > newParams = argNames . tailMap ( paramList . getChildCount ( ) ) ; for ( String name : newParams . values ( ) ) { paramList . addChildToBack ( IR . name ( name ) . useSource...
Inserts new formal parameters into the method s signature based on the given set of names .
34,358
private boolean skipWhitespace ( ) { boolean foundLineTerminator = false ; while ( ! isAtEnd ( ) && peekWhitespace ( ) ) { if ( isLineTerminator ( nextChar ( ) ) ) { foundLineTerminator = true ; } } return foundLineTerminator ; }
Returns true if the whitespace that was skipped included any line terminators .
34,359
private static String processUnicodeEscapes ( String value ) { while ( value . contains ( "\\" ) ) { int escapeStart = value . indexOf ( '\\' ) ; try { if ( value . charAt ( escapeStart + 1 ) != 'u' ) { return null ; } String hexDigits ; int escapeEnd ; if ( value . charAt ( escapeStart + 2 ) != '{' ) { escapeEnd = esc...
Converts unicode escapes in the given string to the equivalent unicode character . If there are no escapes returns the input unchanged . If there is an invalid escape sequence returns null .
34,360
public static String caseCanonicalize ( String s ) { for ( int i = 0 , n = s . length ( ) ; i < n ; ++ i ) { char ch = s . charAt ( i ) ; char cu = caseCanonicalize ( ch ) ; if ( cu != ch ) { StringBuilder sb = new StringBuilder ( s ) ; sb . setCharAt ( i , cu ) ; while ( ++ i < n ) { sb . setCharAt ( i , caseCanonical...
Returns the case canonical version of the given string .
34,361
public static char caseCanonicalize ( char ch ) { if ( ch < 0x80 ) { return ( 'A' <= ch && ch <= 'Z' ) ? ( char ) ( ch | 32 ) : ch ; } if ( CASE_SENSITIVE . contains ( ch ) ) { for ( DeltaSet ds : CANON_DELTA_SETS ) { if ( ds . codeUnits . contains ( ch ) ) { return ( char ) ( ch - ds . delta ) ; } } } return ch ; }
Returns the case canonical version of the given code - unit . ECMAScript 5 explicitly says that code - units are to be treated as their code - point equivalent even surrogates .
34,362
public void process ( Node externsRoot , Node jsRoot ) { checkNotNull ( scopeCreator ) ; checkNotNull ( topScope ) ; Node externsAndJs = jsRoot . getParent ( ) ; checkState ( externsAndJs != null ) ; checkState ( externsRoot == null || externsAndJs . hasChild ( externsRoot ) ) ; if ( externsRoot != null ) { check ( ext...
Main entry point for this phase of processing . This follows the pattern for JSCompiler phases .
34,363
private void doPercentTypedAccounting ( Node n ) { JSType type = n . getJSType ( ) ; if ( type == null ) { nullCount ++ ; } else if ( type . isUnknownType ( ) ) { if ( reportUnknownTypes ) { compiler . report ( JSError . make ( n , UNKNOWN_EXPR_TYPE ) ) ; } unknownCount ++ ; } else { typedCount ++ ; } }
Counts the given node in the typed statistics .
34,364
private void checkCanAssignToWithScope ( NodeTraversal t , Node nodeToWarn , Node lvalue , JSType rightType , JSDocInfo info , String msg ) { if ( lvalue . isDestructuringPattern ( ) ) { checkDestructuringAssignment ( t , nodeToWarn , lvalue , rightType , msg ) ; } else { checkCanAssignToNameGetpropOrGetelem ( t , node...
Checks that we can assign the given right type to the given lvalue or destructuring pattern .
34,365
private void checkCanAssignToNameGetpropOrGetelem ( NodeTraversal t , Node nodeToWarn , Node lvalue , JSType rightType , JSDocInfo info , String msg ) { checkArgument ( lvalue . isName ( ) || lvalue . isGetProp ( ) || lvalue . isGetElem ( ) || lvalue . isCast ( ) , lvalue ) ; if ( lvalue . isGetProp ( ) ) { Node object...
Checks that we can assign the given right type to the given lvalue .
34,366
private void visitObjectPattern ( Node pattern ) { JSType patternType = getJSType ( pattern ) ; validator . expectObject ( pattern , patternType , "cannot destructure 'null' or 'undefined'" ) ; for ( Node child : pattern . children ( ) ) { DestructuredTarget target = DestructuredTarget . createTarget ( typeRegistry , p...
Validates all keys in an object pattern
34,367
private static boolean propertyIsImplicitCast ( ObjectType type , String prop ) { for ( ; type != null ; type = type . getImplicitPrototype ( ) ) { JSDocInfo docInfo = type . getOwnPropertyJSDocInfo ( prop ) ; if ( docInfo != null && docInfo . isImplicitCast ( ) ) { return true ; } } return false ; }
Returns true if any type in the chain has an implicitCast annotation for the given property .
34,368
private static boolean hasUnknownOrEmptySupertype ( FunctionType ctor ) { checkArgument ( ctor . isConstructor ( ) || ctor . isInterface ( ) ) ; checkArgument ( ! ctor . isUnknownType ( ) ) ; while ( true ) { ObjectType maybeSuperInstanceType = ctor . getPrototype ( ) . getImplicitPrototype ( ) ; if ( maybeSuperInstanc...
Given a constructor or an interface type find out whether the unknown type is a supertype of the current type .
34,369
private void visitInterfacePropertyAssignment ( Node object , Node lvalue ) { if ( ! lvalue . getParent ( ) . isAssign ( ) ) { reportInvalidInterfaceMemberDeclaration ( object ) ; return ; } Node assign = lvalue . getParent ( ) ; Node rvalue = assign . getSecondChild ( ) ; JSType rvalueType = getJSType ( rvalue ) ; if ...
Visits an lvalue node for cases such as
34,370
boolean visitName ( NodeTraversal t , Node n , Node parent ) { Token parentNodeType = parent . getToken ( ) ; if ( parentNodeType == Token . FUNCTION || parentNodeType == Token . CATCH || parentNodeType == Token . PARAM_LIST || NodeUtil . isNameDeclaration ( parent ) ) { return false ; } if ( NodeUtil . isEnhancedFor (...
Visits a NAME node .
34,371
private void checkForOfTypes ( NodeTraversal t , Node forOf ) { Node lhs = forOf . getFirstChild ( ) ; Node iterable = forOf . getSecondChild ( ) ; JSType iterableType = getJSType ( iterable ) ; JSType actualType ; if ( forOf . isForAwaitOf ( ) ) { Optional < JSType > maybeType = validator . expectAutoboxesToIterableOr...
Visits the loop variable of a FOR_OF and FOR_AWAIT_OF and verifies the type being assigned to it .
34,372
private void visitGetProp ( NodeTraversal t , Node n ) { Node property = n . getLastChild ( ) ; Node objNode = n . getFirstChild ( ) ; JSType childType = getJSType ( objNode ) ; if ( childType . isDict ( ) ) { report ( property , TypeValidator . ILLEGAL_PROPERTY_ACCESS , "'.'" , "dict" ) ; } else if ( validator . expec...
Visits a GETPROP node .
34,373
private void visitGetElem ( Node n ) { validator . expectIndexMatch ( n , getJSType ( n . getFirstChild ( ) ) , getJSType ( n . getLastChild ( ) ) ) ; ensureTyped ( n ) ; }
Visits a GETELEM node .
34,374
private void visitVar ( NodeTraversal t , Node n ) { if ( n . getParent ( ) . isForOf ( ) || n . getParent ( ) . isForIn ( ) ) { return ; } JSDocInfo varInfo = n . hasOneChild ( ) ? n . getJSDocInfo ( ) : null ; for ( Node child : n . children ( ) ) { if ( child . isName ( ) ) { Node value = child . getFirstChild ( ) ;...
Visits a VAR node .
34,375
private void visitNew ( Node n ) { Node constructor = n . getFirstChild ( ) ; JSType type = getJSType ( constructor ) . restrictByNotNullOrUndefined ( ) ; if ( ! couldBeAConstructor ( type ) || type . isEquivalentTo ( typeRegistry . getNativeType ( SYMBOL_OBJECT_FUNCTION_TYPE ) ) ) { report ( n , NOT_A_CONSTRUCTOR ) ; ...
Visits a NEW node .
34,376
private void checkInterfaceConflictProperties ( Node n , String functionName , Map < String , ObjectType > properties , Map < String , ObjectType > currentProperties , ObjectType interfaceType ) { ObjectType implicitProto = interfaceType . getImplicitPrototype ( ) ; Set < String > currentPropertyNames ; if ( implicitPr...
Check whether there s any property conflict for for a particular super interface
34,377
private void visitClass ( Node n ) { FunctionType functionType = JSType . toMaybeFunctionType ( n . getJSType ( ) ) ; Node extendsClause = n . getSecondChild ( ) ; if ( ! extendsClause . isEmpty ( ) ) { JSType superType = extendsClause . getJSType ( ) ; if ( superType . isConstructor ( ) || superType . isInterface ( ) ...
Visits a CLASS node .
34,378
private void checkConstructor ( Node n , FunctionType functionType ) { FunctionType baseConstructor = functionType . getSuperClassConstructor ( ) ; if ( ! Objects . equals ( baseConstructor , getNativeType ( OBJECT_FUNCTION_TYPE ) ) && baseConstructor != null && baseConstructor . isInterface ( ) ) { compiler . report (...
Checks a constructor which may be either an ES5 - style FUNCTION node or a CLASS node .
34,379
private void checkInterface ( Node n , FunctionType functionType ) { for ( ObjectType extInterface : functionType . getExtendedInterfaces ( ) ) { if ( extInterface . getConstructor ( ) != null && ! extInterface . getConstructor ( ) . isInterface ( ) ) { compiler . report ( JSError . make ( n , CONFLICTING_EXTENDED_TYPE...
Checks an interface which may be either an ES5 - style FUNCTION node or a CLASS node .
34,380
private void checkCallConventions ( NodeTraversal t , Node n ) { SubclassRelationship relationship = compiler . getCodingConvention ( ) . getClassesDefinedByCall ( n ) ; TypedScope scope = t . getTypedScope ( ) ; if ( relationship != null ) { ObjectType superClass = TypeValidator . getInstanceOfCtor ( scope . lookupQua...
Validate class - defining calls . Because JS has no native syntax for defining classes we need to do this manually .
34,381
private void visitCall ( NodeTraversal t , Node n ) { checkCallConventions ( t , n ) ; Node child = n . getFirstChild ( ) ; JSType childType = getJSType ( child ) . restrictByNotNullOrUndefined ( ) ; if ( ! childType . canBeCalled ( ) ) { report ( n , NOT_CALLABLE , childType . toString ( ) ) ; ensureTyped ( n ) ; retu...
Visits a CALL node .
34,382
private void visitArgumentList ( Node call , FunctionType functionType ) { Iterator < Node > parameters = functionType . getParameters ( ) . iterator ( ) ; Iterator < Node > arguments = NodeUtil . getInvocationArgsAsIterable ( call ) . iterator ( ) ; checkArgumentsMatchParameters ( call , functionType , arguments , par...
Visits the parameters of a CALL or a NEW node .
34,383
private void checkArgumentsMatchParameters ( Node call , FunctionType functionType , Iterator < Node > arguments , Iterator < Node > parameters , int firstParameterIndex ) { int spreadArgumentCount = 0 ; int normalArgumentCount = firstParameterIndex ; boolean checkArgumentTypeAgainstParameter = true ; Node parameter = ...
Checks that a list of arguments match a list of formal parameters
34,384
private void visitImplicitReturnExpression ( NodeTraversal t , Node exprNode ) { Node enclosingFunction = t . getEnclosingFunction ( ) ; JSType jsType = getJSType ( enclosingFunction ) ; if ( jsType . isFunctionType ( ) ) { FunctionType functionType = jsType . toMaybeFunctionType ( ) ; JSType expectedReturnType = funct...
Visits an arrow function expression body .
34,385
private void visitReturn ( NodeTraversal t , Node n ) { Node enclosingFunction = t . getEnclosingFunction ( ) ; if ( enclosingFunction . isGeneratorFunction ( ) && ! n . hasChildren ( ) ) { return ; } JSType jsType = getJSType ( enclosingFunction ) ; if ( jsType . isFunctionType ( ) ) { FunctionType functionType = jsTy...
Visits a RETURN node .
34,386
private void visitYield ( NodeTraversal t , Node n ) { JSType jsType = getJSType ( t . getEnclosingFunction ( ) ) ; JSType declaredYieldType = getNativeType ( UNKNOWN_TYPE ) ; if ( jsType . isFunctionType ( ) ) { FunctionType functionType = jsType . toMaybeFunctionType ( ) ; JSType returnType = functionType . getReturn...
Visits a YIELD node .
34,387
private void visitBinaryOperator ( Token op , Node n ) { Node left = n . getFirstChild ( ) ; JSType leftType = getJSType ( left ) ; Node right = n . getLastChild ( ) ; JSType rightType = getJSType ( right ) ; switch ( op ) { case ASSIGN_LSH : case ASSIGN_RSH : case LSH : case RSH : case ASSIGN_URSH : case URSH : String...
This function unifies the type checking involved in the core binary operators and the corresponding assignment operators . The representation used internally is such that common code can handle both kinds of operators easily .
34,388
private void checkEnumAlias ( NodeTraversal t , JSDocInfo declInfo , JSType valueType , Node nodeToWarn ) { if ( declInfo == null || ! declInfo . hasEnumParameterType ( ) ) { return ; } if ( ! valueType . isEnumType ( ) ) { return ; } EnumType valueEnumType = valueType . toMaybeEnumType ( ) ; JSType valueEnumPrimitiveT...
Checks enum aliases .
34,389
private void ensureTyped ( Node n , JSType type ) { checkState ( ! n . isFunction ( ) || type . isFunctionType ( ) || type . isUnknownType ( ) ) ; if ( n . getJSType ( ) == null ) { n . setJSType ( type ) ; } }
Ensures the node is typed .
34,390
private boolean isObjectTypeWithNonStringifiableKey ( JSType type ) { if ( ! type . isTemplatizedType ( ) ) { return false ; } TemplatizedType templatizedType = type . toMaybeTemplatizedType ( ) ; if ( templatizedType . getReferencedType ( ) . isNativeObjectType ( ) && templatizedType . getTemplateTypes ( ) . size ( ) ...
Checks whether current type is Object type with non - stringifable key .
34,391
public final void connectIfNotFound ( N n1 , E edge , N n2 ) { if ( ! isConnected ( n1 , edge , n2 ) ) { connect ( n1 , edge , n2 ) ; } }
Connects two nodes in the graph with an edge if such edge does not already exists between the nodes .
34,392
@ SuppressWarnings ( "unchecked" ) < T extends GraphNode < N , E > > T getNodeOrFail ( N val ) { T node = ( T ) getNode ( val ) ; if ( node == null ) { throw new IllegalArgumentException ( val + " does not exist in graph" ) ; } return node ; }
Gets the node of the specified type or throws an IllegalArgumentException .
34,393
private static void pushAnnotations ( Deque < GraphAnnotationState > stack , Collection < ? extends Annotatable > haveAnnotations ) { stack . push ( new GraphAnnotationState ( haveAnnotations . size ( ) ) ) ; for ( Annotatable h : haveAnnotations ) { stack . peek ( ) . add ( new AnnotationState ( h , h . getAnnotation ...
Pushes a new list on stack and stores nodes annotations in the new list . Clears objects annotations as well .
34,394
private static void popAnnotations ( Deque < GraphAnnotationState > stack ) { for ( AnnotationState as : stack . pop ( ) ) { as . first . setAnnotation ( as . second ) ; } }
Restores the node annotations on the top of stack and pops stack .
34,395
void regenerateGlobalTypedScope ( AbstractCompiler compiler , Node root ) { typedScopeCreator = new TypedScopeCreator ( compiler ) ; topScope = typedScopeCreator . createScope ( root , null ) ; }
Regenerates the top scope from scratch .
34,396
void patchGlobalTypedScope ( AbstractCompiler compiler , Node scriptRoot ) { checkNotNull ( typedScopeCreator ) ; typedScopeCreator . patchGlobalScope ( topScope , scriptRoot ) ; }
Regenerates the top scope potentially only for a sub - tree of AST and then copies information for the old global scope .
34,397
GraphvizGraph getPassGraph ( ) { LinkedDirectedGraph < String , String > graph = LinkedDirectedGraph . createWithoutAnnotations ( ) ; Iterable < PassFactory > allPasses = Iterables . concat ( getChecks ( ) , getOptimizations ( ) ) ; String lastPass = null ; String loopStart = null ; for ( PassFactory pass : allPasses )...
Gets a graph of the passes run . For debugging .
34,398
final TypeInferencePass makeTypeInference ( AbstractCompiler compiler ) { return new TypeInferencePass ( compiler , compiler . getReverseAbstractInterpreter ( ) , topScope , typedScopeCreator ) ; }
Create a type inference pass .
34,399
final TypeCheck makeTypeCheck ( AbstractCompiler compiler ) { return new TypeCheck ( compiler , compiler . getReverseAbstractInterpreter ( ) , compiler . getTypeRegistry ( ) , topScope , typedScopeCreator ) . reportUnknownTypes ( options . enables ( DiagnosticGroup . forType ( TypeCheck . UNKNOWN_EXPR_TYPE ) ) ) . repo...
Create a type - checking pass .