idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
34,900
private void appendBehaviorMembersToBlock ( final PolymerClassDefinition cls , Node block ) { String qualifiedPath = cls . target . getQualifiedName ( ) + ".prototype." ; Map < String , Node > nameToExprResult = new HashMap < > ( ) ; for ( BehaviorDefinition behavior : cls . behaviors ) { for ( MemberDefinition behaviorFunction : behavior . functionsToCopy ) { String fnName = behaviorFunction . name . getString ( ) ; if ( NodeUtil . getFirstPropMatchingKey ( cls . descriptor , fnName ) != null ) { continue ; } if ( nameToExprResult . containsKey ( fnName ) ) { block . removeChild ( nameToExprResult . get ( fnName ) ) ; } Node fnValue = behaviorFunction . value . cloneTree ( ) ; NodeUtil . markNewScopesChanged ( fnValue , compiler ) ; Node exprResult = IR . exprResult ( IR . assign ( NodeUtil . newQName ( compiler , qualifiedPath + fnName ) , fnValue ) ) ; exprResult . useSourceInfoIfMissingFromForTree ( behaviorFunction . name ) ; JSDocInfoBuilder info = JSDocInfoBuilder . maybeCopyFrom ( behaviorFunction . info ) ; info . addSuppression ( "unusedPrivateMembers" ) ; if ( behaviorFunction . info != null && behaviorFunction . info . getVisibility ( ) == Visibility . PROTECTED ) { info . overwriteVisibility ( Visibility . PUBLIC ) ; } if ( ! behavior . isGlobalDeclaration ) { NodeUtil . getFunctionBody ( fnValue ) . removeChildren ( ) ; } exprResult . getFirstChild ( ) . setJSDocInfo ( info . build ( ) ) ; block . addChildToBack ( exprResult ) ; nameToExprResult . put ( fnName , exprResult ) ; } for ( MemberDefinition behaviorProp : behavior . nonPropertyMembersToCopy ) { String propName = behaviorProp . name . getString ( ) ; if ( nameToExprResult . containsKey ( propName ) ) { block . removeChild ( nameToExprResult . get ( propName ) ) ; } Node exprResult = IR . exprResult ( NodeUtil . newQName ( compiler , qualifiedPath + propName ) ) ; exprResult . useSourceInfoFromForTree ( behaviorProp . name ) ; JSDocInfoBuilder info = JSDocInfoBuilder . maybeCopyFrom ( behaviorProp . info ) ; if ( behaviorProp . name . isGetterDef ( ) ) { info = new JSDocInfoBuilder ( true ) ; if ( behaviorProp . info != null && behaviorProp . info . getReturnType ( ) != null ) { info . recordType ( behaviorProp . info . getReturnType ( ) ) ; } } exprResult . getFirstChild ( ) . setJSDocInfo ( info . build ( ) ) ; block . addChildToBack ( exprResult ) ; nameToExprResult . put ( propName , exprResult ) ; } } }
Appends all required behavior functions and non - property members to the given block .
34,901
private Node makeReadOnlySetter ( String propName , String qualifiedPath ) { String setterName = "_set" + propName . substring ( 0 , 1 ) . toUpperCase ( ) + propName . substring ( 1 ) ; Node fnNode = IR . function ( IR . name ( "" ) , IR . paramList ( IR . name ( propName ) ) , IR . block ( ) ) ; compiler . reportChangeToChangeScope ( fnNode ) ; Node exprResNode = IR . exprResult ( IR . assign ( NodeUtil . newQName ( compiler , qualifiedPath + setterName ) , fnNode ) ) ; JSDocInfoBuilder info = new JSDocInfoBuilder ( true ) ; info . recordOverride ( ) ; exprResNode . getFirstChild ( ) . setJSDocInfo ( info . build ( ) ) ; return exprResNode ; }
Adds the generated setter for a readonly property .
34,902
private void createExportsAndExterns ( final PolymerClassDefinition cls , List < MemberDefinition > readOnlyProps , List < MemberDefinition > attributeReflectedProps ) { Node block = IR . block ( ) ; String interfaceName = getInterfaceName ( cls ) ; Node fnNode = NodeUtil . emptyFunction ( ) ; compiler . reportChangeToChangeScope ( fnNode ) ; Node varNode = IR . var ( NodeUtil . newQName ( compiler , interfaceName ) , fnNode ) ; JSDocInfoBuilder info = new JSDocInfoBuilder ( true ) ; info . recordInterface ( ) ; varNode . setJSDocInfo ( info . build ( ) ) ; block . addChildToBack ( varNode ) ; String interfaceBasePath = interfaceName + ".prototype." ; if ( polymerExportPolicy == PolymerExportPolicy . EXPORT_ALL ) { appendPropertiesToBlock ( cls . props , block , interfaceBasePath ) ; LinkedHashMap < String , MemberDefinition > uniqueMethods = new LinkedHashMap < > ( ) ; if ( cls . behaviors != null ) { for ( BehaviorDefinition behavior : cls . behaviors ) { for ( MemberDefinition method : behavior . functionsToCopy ) { uniqueMethods . put ( method . name . getString ( ) , method ) ; } } } for ( MemberDefinition method : cls . methods ) { uniqueMethods . put ( method . name . getString ( ) , method ) ; } for ( MemberDefinition method : uniqueMethods . values ( ) ) { addMethodToObjectExternsUsingExportAnnotation ( cls , method ) ; } } else if ( polymerVersion == 1 ) { appendPropertiesToBlock ( cls . props , block , interfaceBasePath ) ; } else { List < MemberDefinition > interfaceProperties = new ArrayList < > ( ) ; interfaceProperties . addAll ( readOnlyProps ) ; if ( attributeReflectedProps != null ) { interfaceProperties . addAll ( attributeReflectedProps ) ; } appendPropertiesToBlock ( interfaceProperties , block , interfaceBasePath ) ; } for ( MemberDefinition prop : readOnlyProps ) { String propName = prop . name . getString ( ) ; String setterName = "_set" + propName . substring ( 0 , 1 ) . toUpperCase ( ) + propName . substring ( 1 ) ; Node setterExprNode = IR . exprResult ( NodeUtil . newQName ( compiler , interfaceBasePath + setterName ) ) ; JSDocInfoBuilder setterInfo = new JSDocInfoBuilder ( true ) ; JSTypeExpression propType = PolymerPassStaticUtils . getTypeFromProperty ( prop , compiler ) ; setterInfo . recordParameter ( propName , propType ) ; setterExprNode . getFirstChild ( ) . setJSDocInfo ( setterInfo . build ( ) ) ; block . addChildToBack ( setterExprNode ) ; } block . useSourceInfoIfMissingFromForTree ( polymerElementExterns ) ; Node scopeRoot = polymerElementExterns ; if ( ! scopeRoot . isScript ( ) ) { scopeRoot = scopeRoot . getParent ( ) ; } Node stmts = block . removeChildren ( ) ; scopeRoot . addChildrenToBack ( stmts ) ; compiler . reportChangeToEnclosingScope ( stmts ) ; }
Create exports and externs to protect element properties and methods from renaming and dead code removal .
34,903
private static Node varToAssign ( Node var ) { Node assign = IR . assign ( var . getFirstChild ( ) . cloneNode ( ) , var . getFirstChild ( ) . removeFirstChild ( ) ) ; return IR . exprResult ( assign ) . useSourceInfoIfMissingFromForTree ( var ) ; }
Returns an assign replacing the equivalent var or let declaration .
34,904
private void convertSimpleObserverStringsToReferences ( final PolymerClassDefinition cls ) { for ( MemberDefinition prop : cls . props ) { if ( prop . value . isObjectLit ( ) ) { Node observer = NodeUtil . getFirstPropMatchingKey ( prop . value , "observer" ) ; if ( observer != null && observer . isString ( ) ) { Node observerDirectReference = IR . getprop ( cls . target . cloneTree ( ) , "prototype" , observer . getString ( ) ) . useSourceInfoFrom ( observer ) ; observer . replaceWith ( observerDirectReference ) ; compiler . reportChangeToEnclosingScope ( observerDirectReference ) ; } } } }
Converts property observer strings to direct function references .
34,905
private List < Node > addComputedPropertiesReflectionCalls ( final PolymerClassDefinition cls ) { List < Node > propertySinkStatements = new ArrayList < > ( ) ; for ( MemberDefinition prop : cls . props ) { if ( prop . value . isObjectLit ( ) ) { Node computed = NodeUtil . getFirstPropMatchingKey ( prop . value , "computed" ) ; if ( computed != null && computed . isString ( ) ) { propertySinkStatements . addAll ( replaceMethodStringWithReflectedCalls ( cls . target , computed ) ) ; } } } return propertySinkStatements ; }
For any property in the Polymer property configuration object with a computed key parse the method call and path arguments and replace them with property reflection calls .
34,906
private List < Node > addComplexObserverReflectionCalls ( final PolymerClassDefinition cls ) { List < Node > propertySinkStatements = new ArrayList < > ( ) ; Node classMembers = NodeUtil . getClassMembers ( cls . definition ) ; Node getter = NodeUtil . getFirstGetterMatchingKey ( classMembers , "observers" ) ; if ( getter != null ) { Node complexObservers = null ; for ( Node child : NodeUtil . getFunctionBody ( getter . getFirstChild ( ) ) . children ( ) ) { if ( child . isReturn ( ) ) { if ( child . hasChildren ( ) && child . getFirstChild ( ) . isArrayLit ( ) ) { complexObservers = child . getFirstChild ( ) ; break ; } } } if ( complexObservers != null ) { for ( Node complexObserver : complexObservers . children ( ) ) { if ( complexObserver . isString ( ) ) { propertySinkStatements . addAll ( replaceMethodStringWithReflectedCalls ( cls . target , complexObserver ) ) ; } } } } return propertySinkStatements ; }
For any strings returned in the array from the Polymer static observers property parse the method call and path arguments and replace them with property reflection calls .
34,907
private List < String > parseMethodParams ( String methodParameters , Node methodSignature ) { List < String > parsedParameters = new ArrayList < > ( ) ; char nextDelimeter = ',' ; String currentTerm = "" ; for ( int i = 0 ; i < methodParameters . length ( ) ; i ++ ) { if ( methodParameters . charAt ( i ) == nextDelimeter ) { if ( nextDelimeter == ',' ) { parsedParameters . add ( currentTerm . trim ( ) ) ; currentTerm = "" ; } else { currentTerm += nextDelimeter ; nextDelimeter = ',' ; } } else { currentTerm += methodParameters . charAt ( i ) ; if ( methodParameters . charAt ( i ) == '"' || methodParameters . charAt ( i ) == '\'' ) { nextDelimeter = methodParameters . charAt ( i ) ; } } } if ( nextDelimeter != ',' ) { compiler . report ( JSError . make ( methodSignature , PolymerPassErrors . POLYMER_UNPARSABLE_STRING ) ) ; return parsedParameters ; } if ( currentTerm . length ( ) > 0 ) { parsedParameters . add ( currentTerm . trim ( ) ) ; } return parsedParameters ; }
Parses the parameters string from a complex observer or computed property into distinct parameters . Since a parameter can be a quoted string literal we can t just split on commas .
34,908
private static boolean isParamLiteral ( String param ) { try { Double . parseDouble ( param ) ; return true ; } catch ( NumberFormatException e ) { if ( param . length ( ) > 1 && ( param . charAt ( 0 ) == '"' || param . charAt ( 0 ) == '\'' ) && param . charAt ( 0 ) == param . charAt ( param . length ( ) - 1 ) ) { return true ; } } return false ; }
Determine if the method parameter a quoted string or numeric literal recognized by Polymer .
34,909
@ SuppressWarnings ( "ReferenceEquality" ) private FlowScope inferParameters ( FlowScope entryFlowScope ) { Node functionNode = containerScope . getRootNode ( ) ; if ( ! functionNode . isFunction ( ) ) { return entryFlowScope ; } else if ( NodeUtil . isBundledGoogModuleCall ( functionNode . getParent ( ) ) ) { return entryFlowScope ; } Node astParameters = functionNode . getSecondChild ( ) ; Node iifeArgumentNode = null ; if ( NodeUtil . isInvocationTarget ( functionNode ) ) { iifeArgumentNode = functionNode . getNext ( ) ; } FunctionType functionType = JSType . toMaybeFunctionType ( functionNode . getJSType ( ) ) ; Node parameterTypeNode = functionType . getParametersNode ( ) . getFirstChild ( ) ; for ( Node astParameter : astParameters . children ( ) ) { if ( iifeArgumentNode != null && iifeArgumentNode . isSpread ( ) ) { iifeArgumentNode = null ; } JSType inferredType = getJSType ( astParameter ) ; if ( iifeArgumentNode != null ) { if ( iifeArgumentNode . getJSType ( ) != null ) { inferredType = iifeArgumentNode . getJSType ( ) ; } } else if ( parameterTypeNode != null ) { if ( parameterTypeNode . getJSType ( ) != null ) { inferredType = parameterTypeNode . getJSType ( ) ; } } Node defaultValue = null ; if ( astParameter . isDefaultValue ( ) ) { defaultValue = astParameter . getSecondChild ( ) ; entryFlowScope = traverse ( defaultValue , entryFlowScope ) ; astParameter = astParameter . getFirstChild ( ) ; } else if ( astParameter . isRest ( ) ) { astParameter = astParameter . getOnlyChild ( ) ; inferredType = registry . createTemplatizedType ( registry . getNativeObjectType ( ARRAY_TYPE ) , inferredType ) ; } if ( defaultValue != null ) { inferredType = registry . createUnionType ( inferredType . restrictByNotUndefined ( ) , getJSType ( defaultValue ) ) ; } if ( astParameter . isDestructuringPattern ( ) ) { entryFlowScope = updateDestructuringParameter ( astParameter , inferredType , entryFlowScope ) ; } else { entryFlowScope = updateNamedParameter ( astParameter , defaultValue != null , inferredType , entryFlowScope ) ; } parameterTypeNode = parameterTypeNode != null ? parameterTypeNode . getNext ( ) : null ; iifeArgumentNode = iifeArgumentNode != null ? iifeArgumentNode . getNext ( ) : null ; } return entryFlowScope ; }
Infers all of a function s parameters if their types aren t declared .
34,910
private FlowScope traverseReturn ( Node n , FlowScope scope ) { scope = traverseChildren ( n , scope ) ; Node retValue = n . getFirstChild ( ) ; if ( retValue != null ) { JSType type = functionScope . getRootNode ( ) . getJSType ( ) ; if ( type != null ) { FunctionType fnType = type . toMaybeFunctionType ( ) ; if ( fnType != null ) { inferPropertyTypesToMatchConstraint ( retValue . getJSType ( ) , fnType . getReturnType ( ) ) ; } } } return scope ; }
Traverse a return value .
34,911
private FlowScope traverseCatch ( Node catchNode , FlowScope scope ) { Node catchTarget = catchNode . getFirstChild ( ) ; if ( catchTarget . isName ( ) ) { Node name = catchNode . getFirstChild ( ) ; JSType type ; JSDocInfo info = name . getJSDocInfo ( ) ; if ( info != null && info . hasType ( ) ) { type = info . getType ( ) . evaluate ( scope . getDeclarationScope ( ) , registry ) ; } else { type = getNativeType ( JSTypeNative . UNKNOWN_TYPE ) ; } name . setJSType ( type ) ; return redeclareSimpleVar ( scope , name , type ) ; } else if ( catchTarget . isDestructuringPattern ( ) ) { Node pattern = catchNode . getFirstChild ( ) ; return traverseDestructuringPattern ( pattern , scope , unknownType , AssignmentType . DECLARATION ) ; } else { checkState ( catchTarget . isEmpty ( ) , catchTarget ) ; return scope ; } }
Any value can be thrown so it s really impossible to determine the type of a CATCH param . Treat it as the UNKNOWN type .
34,912
private FlowScope updateScopeForAssignment ( FlowScope scope , Node target , JSType resultType , Node updateNode , AssignmentType type ) { checkNotNull ( resultType ) ; checkState ( updateNode == null || updateNode == target ) ; JSType targetType = target . getJSType ( ) ; Node right = NodeUtil . getRValueOfLValue ( target ) ; if ( isPossibleMixinApplication ( target , right ) ) { addMissingInterfaceProperties ( targetType ) ; } switch ( target . getToken ( ) ) { case NAME : String varName = target . getString ( ) ; TypedVar var = getDeclaredVar ( scope , varName ) ; JSType varType = var == null ? null : var . getType ( ) ; boolean isVarDeclaration = type == AssignmentType . DECLARATION && varType != null && ! var . isTypeInferred ( ) && var . getNameNode ( ) != null ; boolean isTypelessConstDecl = isVarDeclaration && NodeUtil . isConstantDeclaration ( compiler . getCodingConvention ( ) , var . getJSDocInfo ( ) , var . getNameNode ( ) ) && ! ( var . getJSDocInfo ( ) != null && var . getJSDocInfo ( ) . containsDeclarationExcludingTypelessConst ( ) ) ; boolean isVarTypeBetter = isVarDeclaration && ! resultType . isNullType ( ) && ! resultType . isVoidType ( ) && ! isTypelessConstDecl ; if ( isVarTypeBetter ) { scope = redeclareSimpleVar ( scope , target , varType ) ; } else { scope = redeclareSimpleVar ( scope , target , resultType ) ; } if ( updateNode != null ) { updateNode . setJSType ( resultType ) ; } if ( var != null && var . isTypeInferred ( ) && ! ( target . getParent ( ) . isLet ( ) && ! target . hasChildren ( ) ) ) { JSType oldType = var . getType ( ) ; var . setType ( oldType == null ? resultType : oldType . getLeastSupertype ( resultType ) ) ; } else if ( isTypelessConstDecl ) { var . setType ( resultType ) ; } break ; case GETPROP : if ( target . isQualifiedName ( ) ) { String qualifiedName = target . getQualifiedName ( ) ; boolean declaredSlotType = false ; JSType rawObjType = target . getFirstChild ( ) . getJSType ( ) ; if ( rawObjType != null ) { ObjectType objType = ObjectType . cast ( rawObjType . restrictByNotNullOrUndefined ( ) ) ; if ( objType != null ) { String propName = target . getLastChild ( ) . getString ( ) ; declaredSlotType = objType . isPropertyTypeDeclared ( propName ) ; } } JSType safeLeftType = targetType == null ? unknownType : targetType ; scope = scope . inferQualifiedSlot ( target , qualifiedName , safeLeftType , resultType , declaredSlotType ) ; } if ( updateNode != null ) { updateNode . setJSType ( resultType ) ; } ensurePropertyDefined ( target , resultType , scope ) ; break ; default : break ; } return scope ; }
Updates the scope according to the result of an assignment .
34,913
private void ensurePropertyDefined ( Node getprop , JSType rightType , FlowScope scope ) { String propName = getprop . getLastChild ( ) . getString ( ) ; Node obj = getprop . getFirstChild ( ) ; JSType nodeType = getJSType ( obj ) ; ObjectType objectType = ObjectType . cast ( nodeType . restrictByNotNullOrUndefined ( ) ) ; boolean propCreationInConstructor = obj . isThis ( ) && getJSType ( containerScope . getRootNode ( ) ) . isConstructor ( ) ; if ( objectType == null ) { registry . registerPropertyOnType ( propName , nodeType ) ; } else { if ( nodeType . isStruct ( ) && ! objectType . hasProperty ( propName ) ) { boolean staticPropCreation = false ; Node maybeAssignStm = getprop . getGrandparent ( ) ; if ( containerScope . isGlobal ( ) && NodeUtil . isPrototypePropertyDeclaration ( maybeAssignStm ) ) { String propCreationFilename = maybeAssignStm . getSourceFileName ( ) ; Node ctor = objectType . getOwnerFunction ( ) . getSource ( ) ; if ( ctor != null && ctor . getSourceFileName ( ) . equals ( propCreationFilename ) ) { staticPropCreation = true ; } } if ( ! propCreationInConstructor && ! staticPropCreation ) { return ; } } if ( ensurePropertyDeclaredHelper ( getprop , objectType , scope ) ) { return ; } if ( ! objectType . isPropertyTypeDeclared ( propName ) ) { if ( objectType . hasProperty ( propName ) || ! objectType . isInstanceType ( ) ) { if ( "prototype" . equals ( propName ) ) { objectType . defineDeclaredProperty ( propName , rightType , getprop ) ; } else { objectType . defineInferredProperty ( propName , rightType , getprop ) ; } } else if ( propCreationInConstructor ) { objectType . defineInferredProperty ( propName , rightType , getprop ) ; } else { registry . registerPropertyOnType ( propName , objectType ) ; } } } }
Defines a property if the property has not been defined yet .
34,914
private boolean ensurePropertyDeclaredHelper ( Node getprop , ObjectType objectType , FlowScope scope ) { if ( getprop . isQualifiedName ( ) ) { String propName = getprop . getLastChild ( ) . getString ( ) ; String qName = getprop . getQualifiedName ( ) ; TypedVar var = getDeclaredVar ( scope , qName ) ; if ( var != null && ! var . isTypeInferred ( ) ) { if ( propName . equals ( "prototype" ) || ( ! objectType . hasOwnProperty ( propName ) && ( ! objectType . isInstanceType ( ) || ( var . isExtern ( ) && ! objectType . isNativeObjectType ( ) ) ) ) ) { return objectType . defineDeclaredProperty ( propName , var . getType ( ) , getprop ) ; } } } return false ; }
Declares a property on its owner if necessary .
34,915
private FlowScope traverseDestructuringPattern ( Node pattern , FlowScope scope , JSType patternType , AssignmentType assignmentType ) { return traverseDestructuringPatternHelper ( pattern , scope , patternType , ( FlowScope flowScope , Node targetNode , JSType targetType ) -> { targetType = targetType != null ? targetType : getNativeType ( UNKNOWN_TYPE ) ; return updateScopeForAssignment ( flowScope , targetNode , targetType , assignmentType ) ; } ) ; }
Traverses a destructuring pattern in an assignment or declaration
34,916
private FlowScope traverseArrayLiteral ( Node n , FlowScope scope ) { scope = traverseChildren ( n , scope ) ; n . setJSType ( getNativeType ( ARRAY_TYPE ) ) ; return scope ; }
Traverse each element of the array .
34,917
private void backwardsInferenceFromCallSite ( Node n , FunctionType fnType , FlowScope scope ) { boolean updatedFnType = inferTemplatedTypesForCall ( n , fnType , scope ) ; if ( updatedFnType ) { fnType = n . getFirstChild ( ) . getJSType ( ) . toMaybeFunctionType ( ) ; } updateTypeOfArguments ( n , fnType ) ; updateBind ( n ) ; }
We only do forward type inference . We do not do full backwards type inference .
34,918
private void updateBind ( Node n ) { CodingConvention . Bind bind = compiler . getCodingConvention ( ) . describeFunctionBind ( n , false , true ) ; if ( bind == null ) { return ; } Node target = bind . target ; FunctionType callTargetFn = getJSType ( target ) . restrictByNotNullOrUndefined ( ) . toMaybeFunctionType ( ) ; if ( callTargetFn == null ) { return ; } if ( bind . thisValue != null && target . isFunction ( ) ) { JSType thisType = getJSType ( bind . thisValue ) ; if ( thisType . toObjectType ( ) != null && ! thisType . isUnknownType ( ) && callTargetFn . getTypeOfThis ( ) . isUnknownType ( ) ) { callTargetFn = FunctionType . builder ( registry ) . copyFromOtherFunction ( callTargetFn ) . withTypeOfThis ( thisType . toObjectType ( ) ) . build ( ) ; target . setJSType ( callTargetFn ) ; } } n . setJSType ( callTargetFn . getBindReturnType ( bind . getBoundParameterCount ( ) + 1 ) ) ; }
When bind is called on a function we infer the type of the returned bound function by looking at the number of parameters in the call site . We also infer the this type of the target if it s a function expression .
34,919
private void updateTypeOfArguments ( Node n , FunctionType fnType ) { checkState ( NodeUtil . isInvocation ( n ) , n ) ; Iterator < Node > parameters = fnType . getParameters ( ) . iterator ( ) ; if ( n . isTaggedTemplateLit ( ) ) { if ( ! parameters . hasNext ( ) ) { return ; } parameters . next ( ) ; } Iterator < Node > arguments = NodeUtil . getInvocationArgsAsIterable ( n ) . iterator ( ) ; Node iParameter ; Node iArgument ; while ( parameters . hasNext ( ) && arguments . hasNext ( ) ) { iArgument = arguments . next ( ) ; JSType iArgumentType = getJSType ( iArgument ) ; iParameter = parameters . next ( ) ; JSType iParameterType = getJSType ( iParameter ) ; inferPropertyTypesToMatchConstraint ( iArgumentType , iParameterType ) ; FunctionType restrictedParameter = null ; if ( iParameterType . isUnionType ( ) ) { UnionType union = iParameterType . toMaybeUnionType ( ) ; for ( JSType alternative : union . getAlternates ( ) ) { if ( alternative . isFunctionType ( ) ) { restrictedParameter = alternative . toMaybeFunctionType ( ) ; break ; } } } else { restrictedParameter = iParameterType . toMaybeFunctionType ( ) ; } if ( restrictedParameter != null && iArgument . isFunction ( ) && iArgumentType . isFunctionType ( ) ) { FunctionType argFnType = iArgumentType . toMaybeFunctionType ( ) ; JSDocInfo argJsdoc = iArgument . getJSDocInfo ( ) ; boolean declared = ( argJsdoc != null && argJsdoc . containsDeclaration ( ) ) || NodeUtil . functionHasInlineJsdocs ( iArgument ) ; iArgument . setJSType ( matchFunction ( restrictedParameter , argFnType , declared ) ) ; } } }
Performs a limited back - inference on function arguments based on the expected parameter types .
34,920
private FunctionType matchFunction ( FunctionType expectedType , FunctionType currentType , boolean declared ) { if ( declared ) { if ( currentType . getTypeOfThis ( ) . isUnknownType ( ) && ! expectedType . getTypeOfThis ( ) . isUnknownType ( ) ) { FunctionType replacement = FunctionType . builder ( registry ) . copyFromOtherFunction ( currentType ) . withTypeOfThis ( expectedType . getTypeOfThis ( ) ) . build ( ) ; return replacement ; } } else { if ( currentType . getMaxArity ( ) <= expectedType . getMaxArity ( ) ) { return expectedType ; } } return currentType ; }
Take the current function type and try to match the expected function type . This is a form of backwards - inference like record - type constraint matching .
34,921
private Map < String , JSType > buildTypeVariables ( Map < TemplateType , JSType > inferredTypes ) { Map < String , JSType > typeVars = new LinkedHashMap < > ( ) ; for ( Entry < TemplateType , JSType > e : inferredTypes . entrySet ( ) ) { if ( ! e . getKey ( ) . isTypeTransformation ( ) ) { typeVars . put ( e . getKey ( ) . getReferenceName ( ) , e . getValue ( ) ) ; } } return typeVars ; }
Build the type environment where type transformations will be evaluated . It only considers the template type variables that do not have a type transformation .
34,922
private Map < TemplateType , JSType > evaluateTypeTransformations ( ImmutableList < TemplateType > templateTypes , Map < TemplateType , JSType > inferredTypes , FlowScope scope ) { Map < String , JSType > typeVars = null ; Map < TemplateType , JSType > result = null ; TypeTransformation ttlObj = null ; for ( TemplateType type : templateTypes ) { if ( type . isTypeTransformation ( ) ) { if ( ttlObj == null ) { ttlObj = new TypeTransformation ( compiler , scope . getDeclarationScope ( ) ) ; typeVars = buildTypeVariables ( inferredTypes ) ; result = new LinkedHashMap < > ( ) ; } JSType transformedType = ttlObj . eval ( type . getTypeTransformation ( ) , ImmutableMap . copyOf ( typeVars ) ) ; result . put ( type , transformedType ) ; typeVars . put ( type . getReferenceName ( ) , transformedType ) ; } } return result ; }
This function will evaluate the type transformations associated to the template types
34,923
private boolean inferTemplatedTypesForCall ( Node n , FunctionType fnType , FlowScope scope ) { ImmutableList < TemplateType > keys = fnType . getTemplateTypeMap ( ) . getTemplateKeys ( ) ; if ( keys . isEmpty ( ) ) { return false ; } Map < TemplateType , JSType > rawInferrence = inferTemplateTypesFromParameters ( fnType , n , scope ) ; Map < TemplateType , JSType > inferred = Maps . newIdentityHashMap ( ) ; for ( TemplateType key : keys ) { JSType type = rawInferrence . get ( key ) ; if ( type == null ) { type = unknownType ; } inferred . put ( key , type ) ; } Map < TemplateType , JSType > typeTransformations = evaluateTypeTransformations ( keys , inferred , scope ) ; if ( typeTransformations != null ) { inferred . putAll ( typeTransformations ) ; } TemplateTypeReplacer replacer = new TemplateTypeReplacer ( registry , inferred ) ; Node callTarget = n . getFirstChild ( ) ; FunctionType replacementFnType = fnType . visit ( replacer ) . toMaybeFunctionType ( ) ; checkNotNull ( replacementFnType ) ; callTarget . setJSType ( replacementFnType ) ; n . setJSType ( replacementFnType . getReturnType ( ) ) ; return replacer . madeChanges ; }
For functions that use template types specialize the function type for the call target based on the call - site specific arguments . Specifically this enables inference to set the type of any function literal parameters based on these inferred types .
34,924
private static void inferPropertyTypesToMatchConstraint ( JSType type , JSType constraint ) { if ( type == null || constraint == null ) { return ; } type . matchConstraint ( constraint ) ; }
Suppose X is an object with inferred properties . Suppose also that X is used in a way where it would only type - check correctly if some of those properties are widened . Then we should be polite and automatically widen X s properties .
34,925
private FlowScope tightenTypeAfterDereference ( Node n , FlowScope scope ) { if ( n . isQualifiedName ( ) ) { JSType type = getJSType ( n ) ; JSType narrowed = type . restrictByNotNullOrUndefined ( ) ; if ( ! type . equals ( narrowed ) ) { scope = narrowScope ( scope , n , narrowed ) ; } } return scope ; }
If we access a property of a symbol then that symbol is not null or undefined .
34,926
private static String normalizePath ( String path ) { int indexOfProtocol = path . indexOf ( "://" ) ; if ( indexOfProtocol > - 1 ) { path = path . substring ( indexOfProtocol + 3 ) ; int indexOfSlash = path . indexOf ( '/' ) ; if ( indexOfSlash > - 1 ) { path = path . substring ( indexOfSlash + 1 ) ; } } else if ( path . startsWith ( "/" ) ) { path = path . substring ( 1 ) ; } return path ; }
Normalizes a registered or import path .
34,927
public static void applySuggestedFixesToFiles ( Iterable < SuggestedFix > fixes ) throws IOException { Set < String > filenames = new HashSet < > ( ) ; for ( SuggestedFix fix : fixes ) { filenames . addAll ( fix . getReplacements ( ) . keySet ( ) ) ; } Map < String , String > filenameToCodeMap = new HashMap < > ( ) ; for ( String filename : filenames ) { filenameToCodeMap . put ( filename , Files . asCharSource ( new File ( filename ) , UTF_8 ) . read ( ) ) ; } Map < String , String > newCode = applySuggestedFixesToCode ( fixes , filenameToCodeMap ) ; for ( Map . Entry < String , String > entry : newCode . entrySet ( ) ) { Files . asCharSink ( new File ( entry . getKey ( ) ) , UTF_8 ) . write ( entry . getValue ( ) ) ; } }
Applies the provided set of suggested fixes to the files listed in the suggested fixes . The fixes can be provided in any order but they may not have any overlapping modifications for the same file .
34,928
public static String applyCodeReplacements ( Iterable < CodeReplacement > replacements , String code ) { List < CodeReplacement > sortedReplacements = ORDER_CODE_REPLACEMENTS . sortedCopy ( replacements ) ; validateNoOverlaps ( sortedReplacements ) ; StringBuilder sb = new StringBuilder ( ) ; int lastIndex = 0 ; for ( CodeReplacement replacement : sortedReplacements ) { sb . append ( code , lastIndex , replacement . getStartPosition ( ) ) ; sb . append ( replacement . getNewContent ( ) ) ; lastIndex = replacement . getEndPosition ( ) ; } if ( lastIndex <= code . length ( ) ) { sb . append ( code , lastIndex , code . length ( ) ) ; } return sb . toString ( ) ; }
Applies the provided set of code replacements to the code and returns the transformed code . The code replacements may not have any overlap .
34,929
private static void validateNoOverlaps ( List < CodeReplacement > replacements ) { checkState ( ORDER_CODE_REPLACEMENTS . isOrdered ( replacements ) ) ; if ( containsOverlaps ( replacements ) ) { throw new IllegalArgumentException ( "Found overlap between code replacements!\n" + Joiner . on ( "\n\n" ) . join ( replacements ) ) ; } }
Validates that none of the CodeReplacements have any overlap since applying changes that have overlap will produce malformed results . The replacements must be provided in order sorted by start position as sorted by ORDER_CODE_REPLACEMENTS .
34,930
private static boolean containsOverlaps ( List < CodeReplacement > replacements ) { checkState ( ORDER_CODE_REPLACEMENTS . isOrdered ( replacements ) ) ; int start = - 1 ; for ( CodeReplacement replacement : replacements ) { if ( replacement . getStartPosition ( ) < start ) { return true ; } start = Math . max ( start , replacement . getEndPosition ( ) ) ; } return false ; }
Checks whether the CodeReplacements have any overlap . The replacements must be provided in order sorted by start position as sorted by ORDER_CODE_REPLACEMENTS .
34,931
private void rewriteJsdoc ( JSDocInfo info ) { for ( Node typeNode : info . getTypeNodes ( ) ) { NodeUtil . visitPreOrder ( typeNode , replaceJsDocRefs ) ; } }
Rewrites JsDoc type references to match AST changes resulting from imported alias inlining module content renaming of top level constructor functions and classes and module renaming from fully qualified legacy namespace to its binary name .
34,932
private void pushScript ( ScriptDescription newCurrentScript ) { currentScript = newCurrentScript ; if ( ! scriptStack . isEmpty ( ) ) { ScriptDescription parentScript = scriptStack . peek ( ) ; parentScript . addChildScript ( currentScript ) ; } scriptStack . addFirst ( currentScript ) ; }
Record the provided script as the current script at top of the script stack and add it as a child of the previous current script if there was one .
34,933
private void reportUnrecognizedRequires ( ) { for ( UnrecognizedRequire unrecognizedRequire : unrecognizedRequires ) { String legacyNamespace = unrecognizedRequire . legacyNamespace ; Node requireNode = unrecognizedRequire . requireNode ; boolean targetGoogModuleExists = rewriteState . containsModule ( legacyNamespace ) ; boolean targetLegacyScriptExists = rewriteState . legacyScriptNamespaces . contains ( legacyNamespace ) ; if ( ! targetGoogModuleExists && ! targetLegacyScriptExists ) { compiler . report ( JSError . make ( requireNode , MISSING_MODULE_OR_PROVIDE , legacyNamespace ) ) ; if ( ! preserveSugar ) { Node changeScope = NodeUtil . getEnclosingChangeScopeRoot ( requireNode ) ; if ( changeScope == null ) { } else { compiler . reportChangeToChangeScope ( changeScope ) ; NodeUtil . getEnclosingStatement ( requireNode ) . detach ( ) ; } } continue ; } if ( unrecognizedRequire . mustBeOrdered ) { compiler . report ( JSError . make ( requireNode , LATE_PROVIDE_ERROR , legacyNamespace ) ) ; } } unrecognizedRequires . clear ( ) ; }
Examines queue ed unrecognizedRequires to categorize and report them as either missing module missing namespace or late provide .
34,934
private void replaceStringNodeLocationForExportedTopLevelVariable ( Node n , int sourcePosition , int length ) { if ( n . hasOneChild ( ) ) { Node assign = n . getFirstChild ( ) ; if ( assign != null && assign . isAssign ( ) ) { Node getProp = assign . getFirstChild ( ) ; if ( getProp != null && getProp . isGetProp ( ) ) { for ( Node child : getProp . children ( ) ) { child . setSourceEncodedPosition ( sourcePosition ) ; child . setLength ( length ) ; } } } } }
If we had something like const FOO = text and we export FOO change the source location information for the rewritten FOO . The replacement should be something like MOD . FOO = text so we look for MOD . FOO and replace the source location for FOO to the original location of FOO .
34,935
public void declarePrototypeProperty ( String name , JSType type , Node defSite ) { prototype . defineDeclaredProperty ( name , type , defSite ) ; }
Declares a property on the nominal type s prototype .
34,936
public void declareInstanceProperty ( String name , JSType type , Node defSite ) { instance . defineDeclaredProperty ( name , type , defSite ) ; }
Declares an instance property on the nominal type .
34,937
public void declareConstructorProperty ( String name , JSType type , Node defSite ) { constructor . defineDeclaredProperty ( name , type , defSite ) ; }
Declares a static property on the nominal type s constructor .
34,938
public NominalTypeBuilder superClass ( ) { FunctionType ctor = instance . getSuperClassConstructor ( ) ; if ( ctor == null ) { return null ; } return new NominalTypeBuilder ( ctor , ctor . getInstanceType ( ) ) ; }
Returns a NominalTypeBuilder for this type s superclass .
34,939
@ SuppressWarnings ( "ReferenceEquality" ) public boolean hasTemplateKey ( TemplateType templateKey ) { for ( TemplateType entry : templateKeys ) { if ( entry == templateKey ) { return true ; } } return false ; }
Returns true if this map contains the specified template key false otherwise .
34,940
private int getTemplateTypeIndex ( TemplateType key ) { int maxIndex = Math . min ( templateKeys . size ( ) , templateValues . size ( ) ) ; for ( int i = maxIndex - 1 ; i >= 0 ; i -- ) { if ( isSameKey ( templateKeys . get ( i ) , key ) ) { return i ; } } return - 1 ; }
Returns the index of the JSType value associated with the specified template key . If no JSType value is associated returns - 1 .
34,941
public JSType getResolvedTemplateType ( TemplateType key ) { int index = getTemplateTypeIndex ( key ) ; return ( index == - 1 ) ? registry . getNativeType ( JSTypeNative . UNKNOWN_TYPE ) : resolvedTemplateValues [ index ] ; }
Returns the JSType value associated with the specified template key . If no JSType value is associated returns UNKNOWN_TYPE .
34,942
public boolean checkEquivalenceHelper ( TemplateTypeMap that , EquivalenceMethod eqMethod , SubtypingMode subtypingMode ) { return checkEquivalenceHelper ( that , eqMethod , EqCache . create ( ) , subtypingMode ) ; }
Determines if this map and the specified map have equivalent template types .
34,943
private static boolean failedEquivalenceCheck ( EquivalenceMatch eqMatch , EquivalenceMethod eqMethod ) { return eqMatch == EquivalenceMatch . VALUE_MISMATCH || ( eqMatch == EquivalenceMatch . NO_KEY_MATCH && eqMethod != EquivalenceMethod . INVARIANT ) ; }
Determines if the specified EquivalenceMatch is considered a failing condition for an equivalence check given the EquivalenceMethod used for the check .
34,944
TemplateTypeMap extend ( TemplateTypeMap other ) { ImmutableList < JSType > resizedOtherValues = other . resizedToMatchKeys ( other . templateValues ) ; return registry . createTemplateTypeMap ( concatImmutableLists ( other . templateKeys , templateKeys ) , concatImmutableLists ( resizedOtherValues , templateValues ) ) ; }
Extends this TemplateTypeMap with the contents of the specified map . UNKNOWN_TYPE will be used as the value for any missing values in the specified map .
34,945
TemplateTypeMap copyFilledWithValues ( ImmutableList < JSType > additionalValues ) { ImmutableList < JSType > finalValues = resizedToMatchKeys ( concatImmutableLists ( templateValues , additionalValues ) ) ; return registry . createTemplateTypeMap ( templateKeys , finalValues ) ; }
Returns a new TemplateTypeMap whose values have been extended with the specified list .
34,946
TemplateTypeMap remove ( Set < TemplateType > toRemove ) { ImmutableList . Builder < TemplateType > keys = ImmutableList . builder ( ) ; keys . addAll ( templateKeys . subList ( 0 , templateValues . size ( ) ) ) ; for ( int i = templateValues . size ( ) ; i < templateKeys . size ( ) ; i ++ ) { TemplateType key = templateKeys . get ( i ) ; if ( ! toRemove . contains ( key ) ) { keys . add ( key ) ; } } return registry . createTemplateTypeMap ( keys . build ( ) , templateValues ) ; }
Returns a new TemplateTypeMap with the given template types removed . Keys will only be removed if they are unmapped .
34,947
private static < T > ImmutableList < T > concatImmutableLists ( ImmutableList < T > first , ImmutableList < T > second ) { if ( first . isEmpty ( ) ) { return second ; } if ( second . isEmpty ( ) ) { return first ; } return ImmutableList . < T > builder ( ) . addAll ( first ) . addAll ( second ) . build ( ) ; }
Concatenates two ImmutableList instances . If either input is empty the other is returned ; otherwise a new ImmutableList instance is created that contains the contents of both arguments .
34,948
public static ModuleIdentifier forClosure ( String name ) { String normalizedName = name ; if ( normalizedName . startsWith ( "goog:" ) ) { normalizedName = normalizedName . substring ( "goog:" . length ( ) ) ; } String namespace = normalizedName ; String moduleName = normalizedName ; int splitPoint = normalizedName . indexOf ( ':' ) ; if ( splitPoint != - 1 ) { moduleName = normalizedName . substring ( 0 , splitPoint ) ; namespace = normalizedName . substring ( Math . min ( splitPoint + 1 , normalizedName . length ( ) - 1 ) ) ; } return new AutoValue_ModuleIdentifier ( normalizedName , namespace , moduleName ) ; }
Returns an identifier for a Closure namespace .
34,949
public static ModuleIdentifier forFile ( String filepath ) { String normalizedName = ModuleNames . fileToModuleName ( filepath ) ; return new AutoValue_ModuleIdentifier ( filepath , normalizedName , normalizedName ) ; }
Returns an identifier for an ES or CommonJS module .
34,950
private void checkAst ( Node externs , Node root ) { astValidator . validateCodeRoot ( externs ) ; astValidator . validateCodeRoot ( root ) ; }
Check that the AST is structurally accurate .
34,951
private void checkNormalization ( Node externs , Node root ) { CodeChangeHandler handler = new ForbiddenChange ( ) ; compiler . addChangeHandler ( handler ) ; new PrepareAst ( compiler , true ) . process ( null , root ) ; if ( compiler . getLifeCycleStage ( ) . isNormalized ( ) ) { ( new Normalize ( compiler , true ) ) . process ( externs , root ) ; if ( compiler . getLifeCycleStage ( ) . isNormalizedUnobfuscated ( ) ) { boolean checkUserDeclarations = true ; CompilerPass pass = new Normalize . VerifyConstants ( compiler , checkUserDeclarations ) ; pass . process ( externs , root ) ; } } compiler . removeChangeHandler ( handler ) ; }
Verifies that the normalization pass does nothing on an already - normalized tree .
34,952
private void moveMethods ( Collection < NameInfo > allNameInfo ) { boolean hasStubDeclaration = idGenerator . hasGeneratedAnyIds ( ) ; for ( NameInfo nameInfo : allNameInfo ) { if ( ! nameInfo . isReferenced ( ) ) { continue ; } if ( nameInfo . readsClosureVariables ( ) ) { continue ; } JSModule deepestCommonModuleRef = nameInfo . getDeepestCommonModuleRef ( ) ; if ( deepestCommonModuleRef == null ) { compiler . report ( JSError . make ( NULL_COMMON_MODULE_ERROR ) ) ; continue ; } Iterator < Symbol > declarations = nameInfo . getDeclarations ( ) . descendingIterator ( ) ; while ( declarations . hasNext ( ) ) { Symbol symbol = declarations . next ( ) ; if ( symbol instanceof PrototypeProperty ) { tryToMovePrototypeMethod ( nameInfo , deepestCommonModuleRef , ( PrototypeProperty ) symbol ) ; } else if ( symbol instanceof ClassMemberFunction ) { tryToMoveMemberFunction ( nameInfo , deepestCommonModuleRef , ( ClassMemberFunction ) symbol ) ; } } } if ( ! noStubFunctions && ! hasStubDeclaration && idGenerator . hasGeneratedAnyIds ( ) ) { Node declarations = compiler . parseSyntheticCode ( STUB_DECLARATIONS ) ; NodeUtil . markNewScopesChanged ( declarations , compiler ) ; Node firstScript = compiler . getNodeForCodeInsertion ( null ) ; firstScript . addChildrenToFront ( declarations . removeChildren ( ) ) ; compiler . reportChangeToEnclosingScope ( firstScript ) ; } }
Move methods deeper in the chunk graph when possible .
34,953
private void tryToMoveMemberFunction ( NameInfo nameInfo , JSModule deepestCommonModuleRef , ClassMemberFunction classMemberFunction ) { Var rootVar = classMemberFunction . getRootVar ( ) ; if ( rootVar == null || ! rootVar . isGlobal ( ) ) { return ; } Node definitionNode = classMemberFunction . getDefinitionNode ( ) ; if ( ! definitionNode . isMemberFunctionDef ( ) ) { return ; } if ( moduleGraph . dependsOn ( deepestCommonModuleRef , classMemberFunction . getModule ( ) ) ) { if ( hasUnmovableRedeclaration ( nameInfo , classMemberFunction ) ) { return ; } Node destinationParent = compiler . getNodeForCodeInsertion ( deepestCommonModuleRef ) ; String className = rootVar . getName ( ) ; if ( noStubFunctions ) { moveClassInstanceMethodWithoutStub ( className , definitionNode , destinationParent ) ; } else { moveClassInstanceMethodWithStub ( className , definitionNode , destinationParent ) ; } } }
If possible move a class instance member function definition to the deepest chunk common to all uses of the method .
34,954
static Visibility getOverriddenPropertyVisibility ( ObjectType objectType , String propertyName ) { return objectType != null ? objectType . getOwnPropertyJSDocInfo ( propertyName ) . getVisibility ( ) : Visibility . INHERITED ; }
Returns the original visibility of an overridden property .
34,955
public boolean defineElement ( String name , Node definingNode ) { elements . add ( name ) ; return defineDeclaredProperty ( name , elementsType , definingNode ) ; }
Defines a new element on this enum .
34,956
String parseJsString ( String jsStringLiteral ) throws ParseException { valueMatcher . reset ( jsStringLiteral ) ; if ( ! valueMatcher . matches ( ) ) { throw new ParseException ( "Syntax error in JS String literal" , true ) ; } return valueMatcher . group ( 1 ) != null ? valueMatcher . group ( 1 ) : valueMatcher . group ( 2 ) ; }
Parses a JS string literal .
34,957
PropertyMap getPrimaryParent ( ) { if ( parentSource == null ) { return null ; } ObjectType iProto = parentSource . getImplicitPrototype ( ) ; return iProto == null ? null : iProto . getPropertyMap ( ) ; }
Returns the direct parent of this property map .
34,958
private void collectPropertyNamesHelper ( Set < String > props , Set < PropertyMap > cache ) { if ( ! cache . add ( this ) ) { return ; } props . addAll ( properties . keySet ( ) ) ; PropertyMap primaryParent = getPrimaryParent ( ) ; if ( primaryParent != null ) { primaryParent . collectPropertyNamesHelper ( props , cache ) ; } for ( ObjectType o : getSecondaryParentObjects ( ) ) { PropertyMap p = o . getPropertyMap ( ) ; if ( p != null ) { p . collectPropertyNamesHelper ( props , cache ) ; } } }
Use cache to avoid stack overflow .
34,959
static void createSynthesizedExternVar ( AbstractCompiler compiler , String varName ) { Node nameNode = IR . name ( varName ) ; if ( compiler . getCodingConvention ( ) . isConstant ( varName ) ) { nameNode . putBooleanProp ( Node . IS_CONSTANT_NAME , true ) ; } Node syntheticExternVar = IR . var ( nameNode ) ; getSynthesizedExternsRoot ( compiler ) . addChildToBack ( syntheticExternVar ) ; compiler . reportChangeToEnclosingScope ( syntheticExternVar ) ; }
Create a new variable in a synthetic script . This will prevent subsequent compiler passes from crashing .
34,960
static boolean hasDuplicateDeclarationSuppression ( AbstractCompiler compiler , Node n , Node origVar ) { if ( isExternNamespace ( n ) ) { return true ; } return TypeValidator . hasDuplicateDeclarationSuppression ( compiler , origVar ) ; }
Returns true if duplication warnings are suppressed on either n or origVar .
34,961
static boolean isExternNamespace ( Node n ) { return n . getParent ( ) . isVar ( ) && n . isFromExterns ( ) && NodeUtil . isNamespaceDecl ( n ) ; }
Returns true if n is the name of a variable that declares a namespace in an externs file .
34,962
private boolean isFunctionThatShouldHaveJsDoc ( NodeTraversal t , Node function ) { if ( ! ( t . inGlobalHoistScope ( ) || t . inModuleScope ( ) ) ) { return false ; } if ( NodeUtil . isFunctionDeclaration ( function ) ) { return true ; } if ( NodeUtil . isNameDeclaration ( function . getGrandparent ( ) ) || function . getParent ( ) . isAssign ( ) ) { return true ; } if ( function . getParent ( ) . isExport ( ) ) { return true ; } if ( function . getGrandparent ( ) . isClassMembers ( ) ) { Node memberNode = function . getParent ( ) ; if ( memberNode . isMemberFunctionDef ( ) ) { return ! isConstructorWithoutParameters ( function ) ; } else if ( memberNode . isGetterDef ( ) || memberNode . isSetterDef ( ) ) { return true ; } } if ( function . getGrandparent ( ) . isObjectLit ( ) && NodeUtil . isCallTo ( function . getGrandparent ( ) . getParent ( ) , "Polymer" ) ) { return true ; } return false ; }
Whether the given function should have JSDoc . True if it s a function declared in the global scope or a method on a class which is declared in the global scope .
34,963
private void checkInlineParams ( NodeTraversal t , Node function ) { Node paramList = NodeUtil . getFunctionParameters ( function ) ; for ( Node param : paramList . children ( ) ) { JSDocInfo jsDoc = param . getJSDocInfo ( ) ; if ( jsDoc == null ) { t . report ( param , MISSING_PARAMETER_JSDOC ) ; return ; } else { JSTypeExpression paramType = jsDoc . getType ( ) ; checkNotNull ( paramType , "Inline JSDoc info should always have a type" ) ; checkParam ( t , param , null , paramType ) ; } } }
Checks that the inline type annotations are correct .
34,964
Node transformNodeWithInlineJsDoc ( ParseTree node ) { JSDocInfo info = handleInlineJsDoc ( node ) ; Node irNode = transformDispatcher . process ( node ) ; if ( info != null ) { irNode . setJSDocInfo ( info ) ; } setSourceInfo ( irNode , node ) ; return irNode ; }
Names and destructuring patterns in parameters or variable declarations are special because they can have inline type docs attached .
34,965
private JsDocInfoParser createJsDocInfoParser ( Comment node ) { String comment = node . value ; int lineno = lineno ( node . location . start ) ; int charno = charno ( node . location . start ) ; int position = node . location . start . offset ; int numOpeningChars = 3 ; JsDocInfoParser jsdocParser = new JsDocInfoParser ( new JsDocTokenStream ( comment . substring ( numOpeningChars ) , lineno , charno + numOpeningChars ) , comment , position , templateNode , config , errorReporter ) ; jsdocParser . setFileLevelJsDocBuilder ( fileLevelJsDocBuilder ) ; jsdocParser . setFileOverviewJSDocInfo ( fileOverviewInfo ) ; if ( node . type == Comment . Type . IMPORTANT && node . value . length ( ) > 0 ) { jsdocParser . parseImportantComment ( ) ; } else { jsdocParser . parse ( ) ; } return jsdocParser ; }
Creates a JsDocInfoParser and parses the JsDoc string .
34,966
private JSDocInfo parseInlineTypeDoc ( Comment node ) { String comment = node . value ; int lineno = lineno ( node . location . start ) ; int charno = charno ( node . location . start ) ; int numOpeningChars = 3 ; JsDocInfoParser parser = new JsDocInfoParser ( new JsDocTokenStream ( comment . substring ( numOpeningChars ) , lineno , charno + numOpeningChars ) , comment , node . location . start . offset , templateNode , config , errorReporter ) ; return parser . parseInlineTypeDoc ( ) ; }
Parses inline type info .
34,967
void setLength ( Node node , SourcePosition start , SourcePosition end ) { node . setLength ( end . offset - start . offset ) ; }
Set the length on the node if we re in IDE mode .
34,968
Node cloneProps ( Node n ) { if ( ! n . hasProps ( ) ) { n . clonePropsFrom ( templateNode ) ; } for ( Node child : n . children ( ) ) { cloneProps ( child ) ; } return n ; }
Clone the properties from the template node recursively skips nodes that have properties already .
34,969
private static Flags getDefaultFlags ( ) { if ( defaultFlags != null ) { return defaultFlags ; } defaultFlags = new Flags ( ) ; defaultFlags . angularPass = false ; defaultFlags . applyInputSourceMaps = true ; defaultFlags . assumeFunctionWrapper = false ; defaultFlags . checksOnly = false ; defaultFlags . chunk = null ; defaultFlags . chunkWrapper = null ; defaultFlags . chunkOutputPathPrefix = "./" ; defaultFlags . compilationLevel = "SIMPLE" ; defaultFlags . createSourceMap = true ; defaultFlags . dartPass = false ; defaultFlags . debug = false ; defaultFlags . define = null ; defaultFlags . defines = null ; defaultFlags . dependencyMode = null ; defaultFlags . entryPoint = null ; defaultFlags . env = "BROWSER" ; defaultFlags . exportLocalPropertyDefinitions = false ; defaultFlags . extraAnnotationName = null ; defaultFlags . externs = null ; defaultFlags . forceInjectLibraries = null ; defaultFlags . formatting = null ; defaultFlags . generateExports = false ; defaultFlags . hideWarningsFor = null ; defaultFlags . injectLibraries = true ; defaultFlags . js = null ; defaultFlags . jsCode = null ; defaultFlags . jscompError = null ; defaultFlags . jscompOff = null ; defaultFlags . jscompWarning = null ; defaultFlags . jsModuleRoot = null ; defaultFlags . jsOutputFile = "compiled.js" ; defaultFlags . languageIn = "ECMASCRIPT_2017" ; defaultFlags . languageOut = "ECMASCRIPT5" ; defaultFlags . moduleResolution = "BROWSER" ; defaultFlags . newTypeInf = false ; defaultFlags . isolationMode = "NONE" ; defaultFlags . outputWrapper = null ; defaultFlags . packageJsonEntryNames = null ; defaultFlags . parseInlineSourceMaps = true ; defaultFlags . polymerPass = false ; defaultFlags . polymerVersion = null ; defaultFlags . preserveTypeAnnotations = false ; defaultFlags . processClosurePrimitives = true ; defaultFlags . processCommonJsModules = false ; defaultFlags . renamePrefixNamespace = null ; defaultFlags . renameVariablePrefix = null ; defaultFlags . renaming = true ; defaultFlags . rewritePolyfills = true ; defaultFlags . sourceMapIncludeContent = false ; defaultFlags . strictModeInput = true ; defaultFlags . tracerMode = "OFF" ; defaultFlags . warningLevel = "DEFAULT" ; defaultFlags . useTypesForOptimization = true ; return defaultFlags ; }
Lazy initialize due to GWT . If things are exported then Object is not available when the static initialization runs .
34,970
public static PassFactory createEmptyPass ( String name ) { return new PassFactory ( name , true ) { protected CompilerPass create ( final AbstractCompiler compiler ) { return new CompilerPass ( ) { public void process ( Node externs , Node root ) { } } ; } protected FeatureSet featureSet ( ) { return FeatureSet . latest ( ) ; } } ; }
Create a no - op pass that can only run once . Used to break up loops .
34,971
private static boolean isClassOrConstantName ( String name ) { return name != null && name . length ( ) > 1 && Character . isUpperCase ( name . charAt ( 0 ) ) ; }
Return true if the name looks like a class name or a constant name .
34,972
private static ImmutableList < String > getClassNames ( String qualifiedName ) { ImmutableList . Builder < String > classNames = ImmutableList . builder ( ) ; List < String > parts = DOT_SPLITTER . splitToList ( qualifiedName ) ; for ( int i = 0 ; i < parts . size ( ) ; i ++ ) { String part = parts . get ( i ) ; if ( isClassOrConstantName ( part ) ) { classNames . add ( DOT_JOINER . join ( parts . subList ( 0 , i + 1 ) ) ) ; } } return classNames . build ( ) ; }
or null if no part refers to a class .
34,973
private void maybeAddGoogScopeUsage ( NodeTraversal t , Node n , Node parent ) { checkState ( NodeUtil . isNameDeclaration ( n ) ) ; if ( n . hasOneChild ( ) && parent == googScopeBlock ) { Node rhs = n . getFirstFirstChild ( ) ; if ( rhs != null && rhs . isQualifiedName ( ) ) { Node root = NodeUtil . getRootOfQualifiedName ( rhs ) ; if ( root . isName ( ) ) { Var var = t . getScope ( ) . getVar ( root . getString ( ) ) ; if ( var == null || ( var . isGlobal ( ) && ! var . isExtern ( ) ) ) { usages . put ( rhs . getQualifiedName ( ) , rhs ) ; } } } } }
var Dog = some . cute . Dog ; counts as a usage of some . cute . Dog if it s immediately inside a goog . scope function .
34,974
public static void addPostCheckTranspilationPasses ( List < PassFactory > passes , CompilerOptions options ) { if ( options . needsTranspilationFrom ( FeatureSet . ES_NEXT ) ) { passes . add ( rewriteCatchWithNoBinding ) ; } if ( options . needsTranspilationFrom ( ES2018 ) ) { passes . add ( rewriteAsyncIteration ) ; passes . add ( rewriteObjectSpread ) ; } if ( options . needsTranspilationFrom ( ES8 ) ) { passes . add ( createFeatureRemovalPass ( "markTrailingCommasInParameterListsRemoved" , Feature . TRAILING_COMMA_IN_PARAM_LIST ) ) ; passes . add ( rewriteAsyncFunctions ) ; } if ( options . needsTranspilationFrom ( ES7 ) ) { passes . add ( rewriteExponentialOperator ) ; } if ( options . needsTranspilationFrom ( ES6 ) ) { passes . add ( createFeatureRemovalPass ( "markEs6FeaturesNotRequiringTranspilationAsRemoved" , Feature . BINARY_LITERALS , Feature . OCTAL_LITERALS , Feature . REGEXP_FLAG_U , Feature . REGEXP_FLAG_Y ) ) ; passes . add ( es6NormalizeShorthandProperties ) ; passes . add ( es6RewriteClassExtends ) ; passes . add ( es6ConvertSuper ) ; passes . add ( es6RenameVariablesInParamLists ) ; passes . add ( es6SplitVariableDeclarations ) ; passes . add ( getEs6RewriteDestructuring ( ObjectDestructuringRewriteMode . REWRITE_ALL_OBJECT_PATTERNS ) ) ; passes . add ( es6RewriteArrowFunction ) ; passes . add ( es6ExtractClasses ) ; passes . add ( es6RewriteClass ) ; passes . add ( es6RewriteRestAndSpread ) ; passes . add ( lateConvertEs6ToEs3 ) ; passes . add ( es6ForOf ) ; passes . add ( rewriteBlockScopedFunctionDeclaration ) ; passes . add ( rewriteBlockScopedDeclaration ) ; passes . add ( rewriteGenerators ) ; passes . add ( es6ConvertSuperConstructorCalls ) ; } else if ( options . needsTranspilationOf ( Feature . OBJECT_PATTERN_REST ) ) { passes . add ( es6RenameVariablesInParamLists ) ; passes . add ( es6SplitVariableDeclarations ) ; passes . add ( getEs6RewriteDestructuring ( ObjectDestructuringRewriteMode . REWRITE_OBJECT_REST ) ) ; } }
Adds transpilation passes that should run after all checks are done .
34,975
static void processTranspile ( AbstractCompiler compiler , Node combinedRoot , FeatureSet featureSet , Callback ... callbacks ) { if ( compiler . getOptions ( ) . needsTranspilationFrom ( featureSet ) ) { FeatureSet languageOutFeatures = compiler . getOptions ( ) . getOutputFeatureSet ( ) ; for ( Node singleRoot : combinedRoot . children ( ) ) { if ( doesScriptHaveUnsupportedFeatures ( singleRoot , languageOutFeatures ) ) { for ( Callback callback : callbacks ) { singleRoot . putBooleanProp ( Node . TRANSPILED , true ) ; NodeTraversal . traverse ( compiler , singleRoot , callback ) ; } } } } }
Process transpilations if the input language needs transpilation from certain features on any JS file that has features not present in the compiler s output language mode .
34,976
static void hotSwapTranspile ( AbstractCompiler compiler , Node scriptRoot , FeatureSet featureSet , Callback ... callbacks ) { if ( compiler . getOptions ( ) . needsTranspilationFrom ( featureSet ) ) { FeatureSet languageOutFeatures = compiler . getOptions ( ) . getOutputFeatureSet ( ) ; if ( doesScriptHaveUnsupportedFeatures ( scriptRoot , languageOutFeatures ) ) { for ( Callback callback : callbacks ) { scriptRoot . putBooleanProp ( Node . TRANSPILED , true ) ; NodeTraversal . traverse ( compiler , scriptRoot , callback ) ; } } } }
Hot - swap ES6 + transpilations if the input language needs transpilation from certain features on any JS file that has features not present in the compiler s output language mode .
34,977
private static HotSwapPassFactory createFeatureRemovalPass ( String passName , final Feature featureToRemove , final Feature ... moreFeaturesToRemove ) { return new HotSwapPassFactory ( passName ) { protected HotSwapCompilerPass create ( final AbstractCompiler compiler ) { return new HotSwapCompilerPass ( ) { public void hotSwapScript ( Node scriptRoot , Node originalRoot ) { maybeMarkFeaturesAsTranspiledAway ( compiler , featureToRemove , moreFeaturesToRemove ) ; } public void process ( Node externs , Node root ) { maybeMarkFeaturesAsTranspiledAway ( compiler , featureToRemove , moreFeaturesToRemove ) ; } } ; } protected FeatureSet featureSet ( ) { return FeatureSet . latest ( ) ; } } ; }
Returns a pass that just removes features from the AST FeatureSet .
34,978
void scanNewNodes ( Set < AstChange > newNodes ) { BuildGlobalNamespace builder = new BuildGlobalNamespace ( ) ; for ( AstChange info : newNodes ) { if ( ! info . node . isQualifiedName ( ) && ! NodeUtil . mayBeObjectLitKey ( info . node ) ) { continue ; } scanFromNode ( builder , info . module , info . scope , info . node ) ; } }
If the client adds new nodes to the AST scan these new nodes to see if they ve added any references to the global namespace .
34,979
private void process ( ) { if ( hasExternsRoot ( ) ) { sourceKind = SourceKind . EXTERN ; NodeTraversal . traverse ( compiler , externsRoot , new BuildGlobalNamespace ( ) ) ; } sourceKind = SourceKind . CODE ; NodeTraversal . traverse ( compiler , root , new BuildGlobalNamespace ( ) ) ; generated = true ; externsScope = null ; }
Builds the namespace lazily .
34,980
private boolean isGlobalNameReference ( String name , Scope s ) { String topVarName = getTopVarName ( name ) ; return isGlobalVarReference ( topVarName , s ) ; }
Determines whether a name reference in a particular scope is a global name reference .
34,981
private static String getTopVarName ( String name ) { int firstDotIndex = name . indexOf ( '.' ) ; return firstDotIndex == - 1 ? name : name . substring ( 0 , firstDotIndex ) ; }
Gets the top variable name from a possibly namespaced name .
34,982
private boolean isGlobalVarReference ( String name , Scope s ) { Var v = s . getVar ( name ) ; if ( v == null && externsScope != null ) { v = externsScope . getVar ( name ) ; } return v != null && ! v . isLocal ( ) ; }
Determines whether a variable name reference in a particular scope is a global variable reference .
34,983
private static String toSource ( Node root , Format outputFormat , CompilerOptions options , SourceMap sourceMap , boolean tagAsTypeSummary , boolean tagAsStrict , boolean lineBreak , CodeGeneratorFactory codeGeneratorFactory ) { checkState ( options . sourceMapDetailLevel != null ) ; boolean createSourceMap = ( sourceMap != null ) ; MappedCodePrinter mcp = outputFormat == Format . COMPACT ? new CompactCodePrinter ( lineBreak , options . preferLineBreakAtEndOfFile , options . lineLengthThreshold , createSourceMap , options . sourceMapDetailLevel ) : new PrettyCodePrinter ( options . lineLengthThreshold , createSourceMap , options . sourceMapDetailLevel ) ; CodeGenerator cg = codeGeneratorFactory . getCodeGenerator ( outputFormat , mcp ) ; if ( tagAsTypeSummary ) { cg . tagAsTypeSummary ( ) ; } if ( tagAsStrict ) { cg . tagAsStrict ( ) ; } cg . add ( root ) ; mcp . endFile ( ) ; String code = mcp . getCode ( ) ; if ( createSourceMap ) { mcp . generateSourceMap ( code , sourceMap ) ; } return code ; }
Converts a tree to JS code
34,984
private void validateClassDeclaration ( Node n , boolean isAmbient ) { validateClassHelper ( n , isAmbient ) ; validateName ( n . getFirstChild ( ) ) ; }
In a class declaration unlike a class expression the class name is required .
34,985
public final void removeChild ( Node child ) { checkState ( child . parent == this , "%s is not the parent of %s" , this , child ) ; checkNotNull ( child . previous ) ; Node last = first . previous ; Node prevSibling = child . previous ; Node nextSibling = child . next ; if ( first == child ) { first = nextSibling ; if ( nextSibling != null ) { nextSibling . previous = last ; } } else if ( child == last ) { first . previous = prevSibling ; prevSibling . next = null ; } else { prevSibling . next = nextSibling ; nextSibling . previous = prevSibling ; } child . next = null ; child . previous = null ; child . parent = null ; }
Detach a child from its parent and siblings .
34,986
public final void replaceChild ( Node child , Node newChild ) { checkArgument ( newChild . next == null , "The new child node has next siblings." ) ; checkArgument ( newChild . previous == null , "The new child node has previous siblings." ) ; checkArgument ( newChild . parent == null , "The new child node already has a parent." ) ; checkState ( child . parent == this , "%s is not the parent of %s" , this , child ) ; newChild . useSourceInfoIfMissingFrom ( child ) ; newChild . parent = this ; Node nextSibling = child . next ; Node prevSibling = child . previous ; Node last = first . previous ; if ( child == prevSibling ) { first = newChild ; first . previous = newChild ; } else { if ( child == first ) { first = newChild ; } else { prevSibling . next = newChild ; } if ( child == last ) { first . previous = newChild ; } else { nextSibling . previous = newChild ; } newChild . previous = prevSibling ; } newChild . next = nextSibling ; child . next = null ; child . previous = null ; child . parent = null ; }
Detaches child from Node and replaces it with newChild .
34,987
public final Node clonePropsFrom ( Node other ) { checkState ( this . propListHead == null , "Node has existing properties." ) ; this . propListHead = other . propListHead ; return this ; }
Clone the properties from the provided node without copying the property object . The receiving node may not have any existing properties .
34,988
public final int getIntProp ( Prop propType ) { PropListItem item = lookupProperty ( propType ) ; if ( item == null ) { return 0 ; } return item . getIntValue ( ) ; }
Returns the integer value for the property or 0 if the property is not defined .
34,989
private byte [ ] getSortedPropTypes ( ) { int count = 0 ; for ( PropListItem x = propListHead ; x != null ; x = x . next ) { count ++ ; } byte [ ] keys = new byte [ count ] ; for ( PropListItem x = propListHead ; x != null ; x = x . next ) { count -- ; keys [ count ] = x . propType ; } Arrays . sort ( keys ) ; return keys ; }
Gets all the property types in sorted order .
34,990
public void setString ( String value ) { if ( this . token == Token . STRING || this . token == Token . NAME ) { throw new IllegalStateException ( "String node not created with Node.newString" ) ; } else { throw new UnsupportedOperationException ( this + " is not a string node" ) ; } }
Can only be called for a Token . STRING or Token . NAME .
34,991
public final void setStaticSourceFileFrom ( Node other ) { if ( other . propListHead != null && ( this . propListHead == null || ( this . propListHead . propType == Prop . SOURCE_FILE . ordinal ( ) && this . propListHead . next == null ) ) ) { PropListItem tail = other . propListHead ; while ( tail . next != null ) { tail = tail . next ; } if ( tail . propType == Prop . SOURCE_FILE . ordinal ( ) ) { propListHead = tail ; return ; } } setStaticSourceFile ( other . getStaticSourceFile ( ) ) ; }
Source position management
34,992
public final void setLengthForTree ( int length ) { this . length = length ; for ( Node child = first ; child != null ; child = child . next ) { child . setLengthForTree ( length ) ; } }
Useful to set length of a transpiled node tree to map back to the length of original node .
34,993
public final Node getAncestor ( int level ) { checkArgument ( level >= 0 ) ; Node node = this ; while ( node != null && level -- > 0 ) { node = node . getParent ( ) ; } return node ; }
Gets the ancestor node relative to this .
34,994
public final boolean hasXChildren ( int x ) { int c = 0 ; for ( Node n = first ; n != null && c <= x ; n = n . next ) { c ++ ; } return c == x ; }
Check for has exactly the number of specified children .
34,995
public final boolean hasChild ( Node child ) { for ( Node n = first ; n != null ; n = n . next ) { if ( child == n ) { return true ; } } return false ; }
Intended for testing and verification only .
34,996
public final String getQualifiedName ( ) { switch ( token ) { case NAME : String name = getString ( ) ; return name . isEmpty ( ) ? null : name ; case GETPROP : StringBuilder builder = getQualifiedNameForGetProp ( 0 ) ; return builder != null ? builder . toString ( ) : null ; case THIS : return "this" ; case SUPER : return "super" ; default : return null ; } }
This function takes a set of GETPROP nodes and produces a string that is each property separated by dots . If the node ultimately under the left sub - tree is not a simple name this is not a valid qualified name .
34,997
public final String getOriginalQualifiedName ( ) { if ( token == Token . NAME || getBooleanProp ( Prop . IS_MODULE_NAME ) ) { String name = getOriginalName ( ) ; if ( name == null ) { name = getString ( ) ; } return name . isEmpty ( ) ? null : name ; } else if ( token == Token . GETPROP ) { String left = getFirstChild ( ) . getOriginalQualifiedName ( ) ; if ( left == null ) { return null ; } String right = getLastChild ( ) . getOriginalName ( ) ; if ( right == null ) { right = getLastChild ( ) . getString ( ) ; } return left + "." + right ; } else if ( token == Token . THIS ) { return "this" ; } else if ( token == Token . SUPER ) { return "super" ; } else { return null ; } }
This function takes a set of GETPROP nodes and produces a string that is each property separated by dots . If the node ultimately under the left sub - tree is not a simple name this is not a valid qualified name . This method returns the original name of each segment rather than the renamed version .
34,998
public final void detachChildren ( ) { for ( Node child = first ; child != null ; ) { Node nextChild = child . next ; child . parent = null ; child . next = null ; child . previous = null ; child = nextChild ; } first = null ; }
Removes all children from this node and isolates the children from each other .
34,999
public final void setIsSyntheticBlock ( boolean val ) { checkState ( token == Token . BLOCK ) ; putBooleanProp ( Prop . SYNTHETIC , val ) ; }
Sets whether this is a synthetic block that should not be considered a real source block .