Class GenericAnnotatedTypeFactory<Value extends CFAbstractValue<Value>,Store extends CFAbstractStore<Value,Store>,TransferFunction extends CFAbstractTransfer<Value,Store,TransferFunction>,FlowAnalysis extends CFAbstractAnalysis<Value,Store,TransferFunction>>
- Type Parameters:
Value- the value typeStore- the store typeTransferFunction- the transfer function typeFlowAnalysis- the flow analysis type
- All Implemented Interfaces:
AnnotationProvider
- Direct Known Subclasses:
AccumulationAnnotatedTypeFactory,BaseAnnotatedTypeFactory,InitializationParentAnnotatedTypeFactory,KeyForAnnotatedTypeFactory,LockAnnotatedTypeFactory,NullnessNoInitAnnotatedTypeFactory
AnnotatedTypeFactory to optionally use flow-sensitive qualifier
inference.
It also adds other features: qualifier polymorphism, default annotations via DefaultFor, user-specified defaults via DefaultQualifier, standardization via DependentTypesHelper, etc. Those features, and addComputedTypeAnnotations(com.sun.source.tree.Tree, org.checkerframework.framework.type.AnnotatedTypeMirror) (other than
the part related to flow-sensitivity), could and should be in the superclass AnnotatedTypeFactory; it is not clear why they are defined in this class.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static enumTrack the state of org.checkerframework.dataflow analysis scanning for each class tree in the compilation unit.Nested classes/interfaces inherited from class org.checkerframework.framework.type.AnnotatedTypeFactory
AnnotatedTypeFactory.CapturedTypeVarSubstitutor, AnnotatedTypeFactory.ParameterizedExecutableType -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected FlowAnalysisanalysis.getResult()is the result of the most recent analysis.protected final booleanTrue if users may write type annotations on arrays.protected final CFGVisualizer<Value, Store, TransferFunction> The CFGVisualizer to be used by all CFAbstractAnalysis instances.protected final ContractsFromMethodTo handle method pre- and postconditions.protected QualifierDefaultsto handle defaults specified by the userprotected DependentTypesHelperTo handle dependent type annotations and contract expressions.protected StoreAn empty store.protected IdentityHashMap<Tree, Store> A mapping from methods (or other code blocks) to their exceptional exit store.protected static booleanShould flow be used by default?protected @MonotonicNonNull AnalysisResult<Value, Store> The merged result of all the analyses performed in the current compilation unit.protected final Map<TransferInput<Value, Store>, IdentityHashMap<Node, TransferResult<Value, Store>>> protected static final PatternMatches parameter expressions as they appear inEnsuresQualifierandRequiresQualifierannotations, e.g.final booleanTrue if this checker either has one or more subcheckers, or if this checker is a subchecker.protected Storeprotected Storeprotected final IdentityHashMap<Element, AnnotationMirrorSet> Cache used exclusively during stub parsing to memoize the primary defaults of parameter-less declared types (likejava.lang.Object).protected QualifierPolymorphismto handle any polymorphic typesprotected IdentityHashMap<Tree, Store> A mapping from methods (or other code blocks) to their regular exit store (used to check postconditions).final @Nullable Set<TypeMirror> The Java types on which users may write this type system's type annotations.protected IdentityHashMap<MethodTree, List<Pair<ReturnNode, TransferResult<Value, Store>>>> A mapping from methods to a list with all return statements and the corresponding store.Map from ClassTree to their dataflow analysis state.protected booleanIf true,setRoot(CompilationUnitTree)should clear thesubcheckerSharedCFGmap, freeing memory.booleanShould the analysis assume that side effects to a value can change the type of aliased references?protected @MonotonicNonNull IdentityHashMap<Tree, ControlFlowGraph> Subcheckers share the same ControlFlowGraph for each analyzed code statement.protected TransferFunctionprotected TreeAnnotatorUsed to annotate types based on a given tree.protected TypeAnnotatorUsed to annotate types based on the given un-annotated types.Fields inherited from class org.checkerframework.framework.type.AnnotatedTypeFactory
ajavaTypes, annotatedForApplyToSubpackagesElement, annotatedForListValueElement, annotatedForValueElement, capturedTypeVarSubstitutor, checker, currentFileAjavaTypes, defaultQualifierListValueElement, elements, ensuresQualifierExpressionElement, ensuresQualifierIfExpressionElement, ensuresQualifierIfListTM, ensuresQualifierIfListValueElement, ensuresQualifierIfResultElement, ensuresQualifierIfTM, ensuresQualifierListTM, ensuresQualifierListValueElement, ensuresQualifierTM, fieldInvariantFieldElement, fieldInvariantQualifierElement, fromExpressionTreeCache, fromMemberTreeCache, fromTypeTreeCache, hasQualifierParameterApplyToSubpackagesElement, hasQualifierParameterValueElement, ignoreRawTypeArguments, inferenceResultCache, loader, methodValClassNameElement, methodValMethodNameElement, methodValParamsElement, nodeValueInferenceResultCache, noQualifierParameterValueElement, objectGetClass, processingEnv, qualHierarchy, qualifierUpperBounds, reflectionResolver, requiresQualifierExpressionElement, requiresQualifierListTM, requiresQualifierListValueElement, requiresQualifierTM, shouldCache, stubTypes, trees, typeArgumentInference, typeFormatter, typeHierarchy, typeInformationPresenter, types, typeVarSubstitutor, uid, UNANNOTATED_FOR_NAME, unannotatedForApplyToSubpackagesElement, unannotatedForListValueElement, unannotatedForValueElement, viewpointAdapter -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedCreates a type factory.protectedGenericAnnotatedTypeFactory(BaseTypeChecker checker, boolean useFlow) Creates a type factory. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddAnnotationsFromDefaultForType(@Nullable Element element, AnnotatedTypeMirror type) Adds default qualifiers based on the underlying type oftypetotype.protected voidAdds default qualifiers for type-checked code by readingDefaultForandDefaultQualifierInHierarchymeta-annotations.protected voidAdds the standard CLIMB defaults that do not conflict with previously added defaults.protected voidaddComputedTypeAnnotations(Tree tree, AnnotatedTypeMirror type) Changes annotations on a type obtained from aTree.voidaddComputedTypeAnnotations(Element elt, AnnotatedTypeMirror type) To add annotations to the type of method or constructor parameters, add aTypeAnnotatorusingcreateTypeAnnotator()and see the comment inTypeAnnotator.visitExecutable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType, Void).protected final voidA helper method to add computed type annotations to a type without using flow information.voidAdds default annotations totype.booleanaddSharedCFGForTree(Tree tree, ControlFlowGraph cfg) Add a new entry to the shared CFG.protected voidAdds the defaults for unchecked code of each mode the command-line options enable.protected ControlFlowGraphanalyze(Queue<Pair<ClassTree, @Nullable Store>> classQueue, Queue<Pair<LambdaExpressionTree, @Nullable Store>> lambdaQueue, UnderlyingAST ast, List<CFAbstractAnalysis.FieldInitialValue<Value>> fieldValues, @Nullable ControlFlowGraph cfg, boolean isInitializationCode, boolean updateInitializationStore, boolean isStatic, @Nullable Store capturedStore) Analyze the ASTastand store the result.Returns the annotations that should appear on the given irrelevant Java type.protected voidapplyInferredAnnotations(AnnotatedTypeMirror type, Value inferred) Applies the annotations inferred by the org.checkerframework.dataflow analysis to the typetype.protected voidapplyQualifierParameterDefaults(Tree tree, AnnotatedTypeMirror type) Applies defaults for types in a class with an qualifier parameter.protected voidApplies defaults for types in a class with an qualifier parameter.protected booleanReturns true if the type of the flow-dependent expressiontree(seeAnnotatedTypeFactory.isFlowDependent(ExpressionTree)) can be cached, i.e., it is computed from refined types that remain correct as long asAnnotatedTypeFactory.canUseCachedFlowDependentType(ExpressionTree)holds.protected booleanReturns true if a cached type of the flow-dependent expressiontree(seeAnnotatedTypeFactory.isFlowDependent(ExpressionTree)) is still correct, i.e., the refined types of the expressions it was computed from have not changed since it was cached.protected voidCheck that a default qualifier (in at least one hierarchy) has been set and issue an error if not.voidClears any caches used exclusively during the parse phase.constructorFromUse(NewClassTree tree, boolean inferTypeArgs) protected voidconstructorFromUsePreSubstitution(NewClassTree tree, AnnotatedTypeMirror.AnnotatedExecutableType type, boolean resolvePolyQuals) A callback method for the AnnotatedTypeFactory subtypes to customize the handling of the declared constructor type before type variable substitution.protected final QualifierDefaultsCreateQualifierDefaultswhich handles checker specified defaults, and initialize the createdQualifierDefaults.protected @Nullable CFGVisualizer<Value, Store, TransferFunction> Create a new CFGVisualizer.protected ContractsFromMethodCreates anDefaultContractsFromMethodand returns it.protected DefaultForTypeAnnotatorCreates anDefaultForTypeAnnotator.protected DefaultQualifierForUseTypeAnnotatorCreates anDefaultQualifierForUseTypeAnnotator.protected DependentTypesHelperCreates aDependentTypesHelperand returns it.protected FlowAnalysisReturns the appropriate flow analysis class that is used for the org.checkerframework.dataflow analysis.Returns the appropriate transfer function that is used for the given org.checkerframework.dataflow analysis.protected QualifierDefaultsCreateQualifierDefaultswhich handles checker specified defaults.protected QualifierPolymorphismCreates theQualifierPolymorphisminstance which supports the QualifierPolymorphism mechanism.protected @Nullable AnnotationMirrorcreateRequiresOrEnsuresQualifier(String expression, AnnotationMirror qualifier, AnnotatedTypeMirror declaredType, Analysis.BeforeOrAfter preOrPost, @Nullable List<AnnotationMirror> preconds) Creates aRequiresQualifier("...")orEnsuresQualifier("...")annotation for the given expression.protected TreeAnnotatorReturns aTreeAnnotatorthat adds annotations to a type based on the contents of a tree.protected TypeAnnotatorReturns aDefaultForTypeAnnotatorthat adds annotations to a type based on the content of the type itself.getAnnotatedTypeBefore(JavaExpression expr, ExpressionTree tree) Returns the type of a JavaExpressionexprif it were evaluated before a treetree.getAnnotatedTypeLhs(Tree lhsTree) Returns the type of a left-hand side of an assignment.getAnnotatedTypeLhsNoTypeVarDefault(Tree lhsTree) Returns the type of the left-hand side of an assignment without applying local variable defaults to type variables.Returns the type ofv + 1orv - 1wherevis the expression in the postfixed increment or decrement expression.Returns the type of a varargs array of a method invocation or a constructor invocation.getAnnotationFromJavaExpression(JavaExpression expr, Tree tree, Class<? extends Annotation> clazz) Returns the primary annotation withclazzonexpr's type, at a particular location.getAnnotationFromJavaExpressionString(String expression, Tree tree, TreePath path, Class<? extends Annotation> clazz) Returns the primary annotation withclazzonexpression's type, at a particular location.getAnnotationMirrorFromJavaExpressionString(String expression, Tree tree, TreePath currentPath) Returns the annotation mirror from dataflow forexpression.getAnnotationsFromJavaExpression(JavaExpression expr, Tree tree) Returns the primary annotations on an expression, at a particular location.The CFGVisualizer to be used by all CFAbstractAnalysis instances.getContractExpressions(Contract.Kind kind, AnnotationMirror contractAnnotation) IfcontractAnnotationis a framework annotation, return itsexpressionelement.Returns the helper for method pre- and postconditions.protected AnnotationMirrorSetgetDefaultAnnosForUses(Element element) Returns the set of qualifiers that should be applied to unannotated uses of the given element, as specified byDefaultQualifierForUse.getDefaultAnnotations(Tree tree, AnnotatedTypeMirror type) Removes all primary annotations on a copy of the type and calculates the default annotations that apply to the copied type, without type refinements.Returns theDefaultForTypeAnnotator.getDefaultValueAnnotatedType(TypeMirror typeMirror) Returns the type of the default value of the given type.Returns the DependentTypesHelper.Returns the empty store.getEnsuresQualifierIfResult(Contract.Kind kind, AnnotationMirror contractAnnotation) If kind = CONDITIONALPOSTCONDITION, return the result element, e.g.getExceptionalExitStore(Tree tree) Returns the exceptional exit store for a method or another code block (such as static initializers).getExplicitNewClassAnnos(NewClassTree newClassTree) Returns the annotations explicitly written on a NewClassTree.protected List<AnnotatedTypeMirror> getExplicitNewClassClassTypeArgs(NewClassTree newClassTree) Returns the partially-annotated explicit class type arguments of the new class tree.getExpressionAndOffsetFromJavaExpressionString(String expression, TreePath currentPath) Produces the JavaExpression and offset associated with an expression.Returns the value of effectively final local variables.getFinalLocalValues(Element declarer) Returns the values of the effectively-final local variables whose declaration is directly enclosed by the given element.getFirstNodeOfKindForTree(Tree tree, Class<T> kind) getInferredValueFor(Tree tree) Returns the inferred value (by the org.checkerframework.dataflow analysis) for a given tree.Returns the return type of the methodm.getNodesForTree(Tree tree) Returns theQualifierDefaultsthis factory applies, or null if it applies no defaults.Gives the currentQualifierPolymorphisminstance which supports the QualifierPolymorphism mechanism.getRegularExitStore(Tree tree) Returns the regular exit store for a method or another code block (such as static initializers).getReturnStatementStores(MethodTree methodTree) Returns a list of all return statements ofmethodpaired with their correspondingTransferResult.getSharedCFGForTree(Tree tree) Returns the shared control flow graph used fortreeby this checker's topmost superchecker.booleanShould the local variable default annotation be applied to type variables?protected final StringCreates and returns a string containing the number of qualifiers and the canonical class names of each qualifier that has been added to this checker's supported qualifier set.Returns the type oftreefor the dataflow value of its node, computed as iftreewere not nested in another expression, or null if the value is computed fromAnnotatedTypeFactory.getAnnotatedType(Tree)as usual.getStoreAfter(Tree tree) Returns the store immediately after a given tree.getStoreAfter(Node node) Returns the store immediately after a givenNode.getStoreBefore(Tree tree) Returns the store immediately before a givenTree.getStoreBefore(Node node) Returns the store immediately before a given node.final Set<Class<? extends Annotation>> Returns an immutable set of the monotonic type qualifiers supported by this checker.final <T extends GenericAnnotatedTypeFactory<?,?, ?, ?>>
TgetTypeFactoryOfSubchecker(Class<? extends SourceChecker> subCheckerClass) Returns the type factory used by a subchecker.<T extends GenericAnnotatedTypeFactory<?,?, ?, ?>>
@Nullable TgetTypeFactoryOfSubcheckerOrNull(Class<? extends SourceChecker> subCheckerClass) Returns the type factory used by a subchecker.protected booleanDetermines whether flow-sensitive type refinement should be used or not.protected voidHandle the visualization of the CFG, if necessary.Returns a string that can be passed to the "anno.on.irrelevant" error, giving information about which types are relevant.booleanisAnonymousDiamondSupertypeFinal(NewClassTree creation) Returns true if the supertype inferred for the anonymous class created bycreation, a diamond such asnew C<>(args) {...}, can no longer change.booleanReturns whethergetAnnotatedTypeLhs(Tree)is running right now.protected booleanReturns true if a dataflow analysis is computing the value of a node, which it does from the type of the node's tree.booleanisIgnoredExceptionType(TypeMirror typeMirror) Returns true iftypeMirroris an exception type that should be ignored.booleanisNotFullyInitializedReceiver(MethodTree methodDeclTree) Returns true if the receiver of a method or constructor might not be fully initialized.final booleanisRelevant(TypeMirror tm) Returns true if users can write type annotations from this type system directly on the given Java type.final booleanReturns true if users can write type annotations from this type system directly on the given Java type.protected booleanReturns true if users can write type annotations from this type system on the given Java type.booleanisUnreachable(ExpressionTree exprTree) Returns true if theexprTreeis unreachable.methodFromUse(MethodInvocationTree tree, boolean inferTypeArg) voidmethodFromUsePreSubstitution(ExpressionTree tree, AnnotatedTypeMirror.AnnotatedExecutableType type, boolean resolvePolyQuals) A callback method for the AnnotatedTypeFactory subtypes to customize the handling of the declared method type before type variable substitution.parseJavaExpressionString(String expression, TreePath currentPath) Produces the JavaExpression as ifexpressionwere written atcurrentPath.protected final voidperformFlowAnalysisForClass(ClassTree classTree) Perform a org.checkerframework.dataflow analysis over a single class tree and its nested classes.protected voidperformFlowAnalysisForClassImpl(ClassTree classTree) Performs the dataflow analysis forperformFlowAnalysisForClass(com.sun.source.tree.ClassTree), which calls this method between its bookkeeping.protected voidperformFlowAnalysisForClassOnce(ClassTree classTree) Flow analysis will be performed if all of the following are true.protected voidPerform any additional operations on a CFG.voidpostAsMemberOf(AnnotatedTypeMirror type, AnnotatedTypeMirror owner, Element element) A callback method for the AnnotatedTypeFactory subtypes to customize AnnotatedTypes.asMemberOf().protected voidpostInit()Actions that logically belong in the constructor, but need to run after the subclass constructor has completed.voidpreProcessClassTree(ClassTree classTree) Performs flow-sensitive type refinement onclassTreeif this type factory is configured to do so.protected final voidrunWithBodyVisitorPath(ControlFlowGraph cfg, Runnable action) Runsactionwith the visitor tree path set to the code ofcfg, asanalyze(java.util.Queue<org.checkerframework.javacutil.Pair<com.sun.source.tree.ClassTree, Store>>, java.util.Queue<org.checkerframework.javacutil.Pair<com.sun.source.tree.LambdaExpressionTree, Store>>, org.checkerframework.dataflow.cfg.UnderlyingAST, java.util.List<org.checkerframework.framework.flow.CFAbstractAnalysis.FieldInitialValue<Value>>, org.checkerframework.dataflow.cfg.ControlFlowGraph, boolean, boolean, boolean, Store)does for the analysis itself.voidSet the CompilationUnitTree that should be used.Adapt the upper bounds of the type variables of a class relative to the type instantiation.Methods inherited from class org.checkerframework.framework.type.AnnotatedTypeFactory
adaptGetClassReturnTypeToReceiver, addAliasedDeclAnnotation, addAliasedDeclAnnotation, addAliasedTypeAnnotation, addAliasedTypeAnnotation, addAliasedTypeAnnotation, addAliasedTypeAnnotation, addAnnotationFromFieldInvariant, addInheritedAnnotation, annotatedForPrecedesUnannotatedFor, applyCaptureConversion, applyCaptureConversion, applyUnboxing, areSameByClass, asSupportedQualifier, binaryTreeArgTypes, binaryTreeArgTypes, canonicalAnnotation, clearNodeValueInferenceResults, combineIntersectionBoundAnnotationsInHierarchy, compoundAssignmentTreeArgTypes, constructorFromUse, constructorFromUseWithoutTypeArgInference, containsCapturedTypes, containsSameByClass, containsSameOrAlias, createAnnotatedTypeFormatter, createAnnotationClassLoader, createAnnotationFormatter, createQualifierHierarchy, createQualifierUpperBounds, createSupportedTypeQualifiers, createTypeArgumentInference, createTypeHierarchy, createTypeInformationPresenter, createTypeVariableSubstitutor, createViewpointAdapter, declarationFromElement, doesAnnotatedForApplyToSubpackages, doesAnnotatedForApplyToThisChecker, doesUnannotatedForApplyToSubpackages, doesUnannotatedForApplyToThisChecker, fromElement, fromElement, fromElement, getAnnotatedForAnnotations, getAnnotatedNullType, getAnnotatedType, getAnnotatedType, getAnnotatedType, getAnnotatedType, getAnnotatedType, getAnnotatedType, getAnnotatedType, getAnnotatedType, getAnnotatedType, getAnnotatedTypeFormatter, getAnnotatedTypeFromTypeTree, getAnnotationByClass, getAnnotationFormatter, getAnnotationMirror, getAnnotationOrTypeDeclarationBound, getAnnotationWithMetaAnnotation, getAnonymousDiamondCreation, getAnonymousDiamondSuperConstructor, getAnonymousDiamondSupertype, getBoxedType, getBundledTypeQualifiers, getCacheSize, getChecker, getCheckerNames, getConstructorReceiverType, getContractExpressions, getContractListValues, getDeclAnnotation, getDeclAnnotationNoAliases, getDeclAnnotations, getDeclAnnotationWithMetaAnnotation, getDefaultQualifierAnnotations, getDefaultTypeDeclarationBounds, getDirectSupertypes, getDummyAssignedTo, getElementAnnotations, getElementUtils, getEnclosingClassOrMethod, getEnclosingSubType, getEnclosingType, getEnumConstructorQualifiers, getExpressionAndOffset, getFieldInvariantAnnotationTree, getFieldInvariantDeclarationAnnotations, getFieldInvariants, getFnInterfaceFromTree, getFunctionTypeFromTree, getFunctionTypeFromTree, getImplicitReceiverType, getInferenceWorkBudget, getInitializerTargetType, getIterableElementType, getIterableElementType, getMethodReceiverType, getMethodReturnType, getNarrowedAnnotations, getNarrowedPrimitive, getPath, getProcessingEnv, getQualifierHierarchy, getQualifierParameterHierarchies, getQualifierParameterHierarchies, getQualifierUpperBounds, getReceiverType, getResultingTypeOfConstructorMemberReference, getRoot, getSelfType, getSelfType, getStringType, getSupportedTypeQualifierNames, getSupportedTypeQualifiers, getTreeUtils, getTypeArgumentInference, getTypeDeclarationBounds, getTypeDeclarationBoundsFromUse, getTypeHierarchy, getTypeOfExtendsImplements, getTypeVarSubstitutor, getUnannotatedForAnnotations, getUnboxedType, getViewpointAdaptedTypeDeclarationBounds, getVisitorTreePath, getWidenedAnnotations, getWidenedType, getWidenedType, hasExplicitNoQualifierParameterInHierarchy, hasExplicitQualifierParameterInHierarchy, hasQualifierParameterInHierarchy, hasQualifierParameterInHierarchy, inferTypeArguments, initializeAtm, initializeReflectionResolution, isAliasedTypeAnnotation, isComputingInitializerTargetType, isDeterministic, isFromByteCode, isFromStubFile, isImmutable, isInferringStandalone, isParsingAnnotationFile, isSideEffectFree, isSupportedQualifier, isSupportedQualifier, isSupportedQualifier, isSupportedQualifierOrAlias, isWithinConstructor, mergeAnnotationFileAnnosIntoType, methodFromUse, methodFromUse, methodFromUse, methodFromUseWithoutTypeArgInference, methodFromUseWithoutTypeArgInference, negateConstant, order, overriddenMethodType, parseAnnotationFiles, permissiveOverriddenType, postDirectSuperTypes, postProcessClassTree, replaceAnnotations, replaceAnnotations, setPathForArtificialTree, setVisitorTreePath, shouldCacheElementType, shouldCacheMethodAsMemberOf, shouldStoreInBytecode, shouldWarnIfStubRedundantWithBytecode, toAnnotatedType, toString, type
-
Field Details
-
typeAnnotator
Used to annotate types based on the given un-annotated types. The type may be for source code or bytecode. -
treeAnnotator
Used to annotate types based on a given tree. -
poly
to handle any polymorphic types -
defaults
to handle defaults specified by the user -
dependentTypesHelper
To handle dependent type annotations and contract expressions. -
contractsUtils
To handle method pre- and postconditions. -
relevantJavaTypes
The Java types on which users may write this type system's type annotations. null means no restrictions. Arrays are handled by separate field#arraysAreRelevant.If the relevant type is generic, this contains its erasure.
Although a
Class<?>object exists for every element, this does not contain thoseClass<?>objects because the elements will be compared to TypeMirrors for which Class objects may not exist (they might not be on the classpath). -
arraysAreRelevant
protected final boolean arraysAreRelevantTrue if users may write type annotations on arrays. Ignored unlessrelevantJavaTypesis non-null. -
flowByDefault
protected static boolean flowByDefaultShould flow be used by default? -
sideEffectsUnrefineAliases
public boolean sideEffectsUnrefineAliasesShould the analysis assume that side effects to a value can change the type of aliased references?For many type systems, once a local variable's type is refined, side effects to the variable's value do not change the variable's type annotations. For some type systems, a side effect to the value could change them; set this field to true.
-
hasOrIsSubchecker
public final boolean hasOrIsSubcheckerTrue if this checker either has one or more subcheckers, or if this checker is a subchecker. False otherwise. All uses of the methodsaddSharedCFGForTree(Tree, ControlFlowGraph)andgetSharedCFGForTree(Tree)should be guarded by a check that this is true. -
emptyStore
An empty store. -
analysis
analysis.getResult()is the result of the most recent analysis. Compare toflowResult. -
transfer
-
initializationStore
-
initializationStaticStore
-
flowResultAnalysisCaches
protected final Map<TransferInput<Value extends CFAbstractValue<Value>,Store extends CFAbstractStore<Value, flowResultAnalysisCachesStore>>, IdentityHashMap<Node, TransferResult<Value extends CFAbstractValue<Value>, Store extends CFAbstractStore<Value, Store>>>> Caches forAnalysisResult.runAnalysisFor(Node, Analysis.BeforeOrAfter, TransferInput, IdentityHashMap, Map). This cache is enabled ifAnnotatedTypeFactory.shouldCacheis true. The cache size is derived fromAnnotatedTypeFactory.getCacheSize().- See Also:
-
scannedClasses
Map from ClassTree to their dataflow analysis state.This field is intentionally not final; it should only be re-assigned by
performFlowAnalysisForClass(com.sun.source.tree.ClassTree). -
flowResult
protected @MonotonicNonNull AnalysisResult<Value extends CFAbstractValue<Value>,Store extends CFAbstractStore<Value, flowResultStore>> The merged result of all the analyses performed in the current compilation unit. Invariant:scannedClasses.get(c) == FINISHED for some class c ⇒ flowResult != null
Note that flowResult contains analysis results for Trees from multiple classes which are produced by multiple calls to performFlowAnalysisForClass. -
regularExitStores
A mapping from methods (or other code blocks) to their regular exit store (used to check postconditions).This field is intentionally not final; it should only be re-assigned by
performFlowAnalysisForClass(com.sun.source.tree.ClassTree). -
exceptionalExitStores
A mapping from methods (or other code blocks) to their exceptional exit store.This field is intentionally not final; it should only be re-assigned by
performFlowAnalysisForClass(com.sun.source.tree.ClassTree). -
returnStatementStores
protected IdentityHashMap<MethodTree,List<Pair<ReturnNode, returnStatementStoresTransferResult<Value extends CFAbstractValue<Value>, Store extends CFAbstractStore<Value, Store>>>>> A mapping from methods to a list with all return statements and the corresponding store.This field is intentionally not final; it should only be re-assigned by
performFlowAnalysisForClass(com.sun.source.tree.ClassTree). -
parsePhasePrimaryDefaultsCache
Cache used exclusively during stub parsing to memoize the primary defaults of parameter-less declared types (likejava.lang.Object).Standard factory caches are disabled during parsing to prevent caching partially loaded stub annotations. This targeted cache bridges the performance gap by preventing heavy redundant processing, and is explicitly cleared when parsing completes to ensure no incomplete state leaks into the main type-checking phase.
-
cfgVisualizer
protected final CFGVisualizer<Value extends CFAbstractValue<Value>,Store extends CFAbstractStore<Value, cfgVisualizerStore>, TransferFunction extends CFAbstractTransfer<Value, Store, TransferFunction>> The CFGVisualizer to be used by all CFAbstractAnalysis instances. -
formalParameterPattern
Matches parameter expressions as they appear inEnsuresQualifierandRequiresQualifierannotations, e.g. "#1", "#2", etc.
-
-
Constructor Details
-
GenericAnnotatedTypeFactory
Creates a type factory. Its compilation unit is not yet set.- Parameters:
checker- the checker to which this type factory belongsuseFlow- true if flow analysis should be performed
-
GenericAnnotatedTypeFactory
Creates a type factory. Its compilation unit is not yet set. This constructor might get reflectively called by BaseTypeVisitor.createTypeFactory and uses flowByDefault to determine whether flow refinement should be enabled. Subclasses should instead use the two-parameter constructor and explicitly set whether to use flow refinement.- Parameters:
checker- the checker to which this type factory belongs
-
-
Method Details
-
getUseFlow
protected boolean getUseFlow()Determines whether flow-sensitive type refinement should be used or not.- Returns:
- whether flow-sensitive type refinement should be used or not
- See Also:
-
postInit
protected void postInit(@UnderInitialization(GenericAnnotatedTypeFactory.class) GenericAnnotatedTypeFactory<Value extends CFAbstractValue<Value>, Store extends CFAbstractStore<Value, Store>, TransferFunction extends CFAbstractTransfer<Value, Store, TransferFunction>, FlowAnalysis extends CFAbstractAnalysis<Value, Store, TransferFunction>> this) Description copied from class:AnnotatedTypeFactoryActions that logically belong in the constructor, but need to run after the subclass constructor has completed. In particular,AnnotationFileElementTypes.parseStubFiles()may try to do type resolution with this AnnotatedTypeFactory.- Overrides:
postInitin classAnnotatedTypeFactory
-
getQualifierDefaults
Description copied from class:AnnotatedTypeFactoryReturns theQualifierDefaultsthis factory applies, or null if it applies no defaults.- Overrides:
getQualifierDefaultsin classAnnotatedTypeFactory- Returns:
- the
QualifierDefaultsthis factory applies, or null
-
preProcessClassTree
Performs flow-sensitive type refinement onclassTreeif this type factory is configured to do so.- Overrides:
preProcessClassTreein classAnnotatedTypeFactory- Parameters:
classTree- tree on which to perform flow-sensitive type refinement
-
setRoot
Description copied from class:AnnotatedTypeFactorySet the CompilationUnitTree that should be used.- Overrides:
setRootin classAnnotatedTypeFactory- Parameters:
root- the new compilation unit to use
-
getSupportedMonotonicTypeQualifiers
Returns an immutable set of the monotonic type qualifiers supported by this checker.- Returns:
- the monotonic type qualifiers supported this processor, or an empty set if none
- See Also:
-
createTreeAnnotator
Returns aTreeAnnotatorthat adds annotations to a type based on the contents of a tree.The default tree annotator is a
ListTreeAnnotatorof the following:PropagationTreeAnnotator: Propagates annotations from subtreesLiteralTreeAnnotator: Adds annotations based onQualifierForLiteralsmeta-annotationsDependentTypesTreeAnnotator: Adapts dependent annotations based on context
Subclasses may override this method to specify additional tree annotators, for example:
new ListTreeAnnotator(super.createTreeAnnotator(), new KeyLookupTreeAnnotator(this));
- Returns:
- a tree annotator
-
createTypeAnnotator
Returns aDefaultForTypeAnnotatorthat adds annotations to a type based on the content of the type itself.Subclass may override this method. The default type annotator is a
ListTypeAnnotatorof the following:IrrelevantTypeAnnotator: Adds top to types not listed in the@RelevantJavaTypesannotation on the checker.PropagationTypeAnnotator: Propagates annotation onto wildcards.
- Returns:
- a type annotator
-
annotationsForIrrelevantJavaType
Returns the annotations that should appear on the given irrelevant Java type. If the type is relevant, this method's behavior is undefined.- Parameters:
tm- an irrelevant Java type- Returns:
- the annotations that should appear on the given irrelevant Java type
-
createDefaultForUseTypeAnnotator
Creates anDefaultQualifierForUseTypeAnnotator.- Returns:
- a new
DefaultQualifierForUseTypeAnnotator
-
getDefaultAnnosForUses
Description copied from class:AnnotatedTypeFactoryReturns the set of qualifiers that should be applied to unannotated uses of the given element, as specified byDefaultQualifierForUse.This implementation always returns an empty set, because
@DefaultQualifierForUseis implemented byDefaultQualifierForUseTypeAnnotator, which only aGenericAnnotatedTypeFactorycreates.GenericAnnotatedTypeFactoryoverrides this to consult that annotator.- Overrides:
getDefaultAnnosForUsesin classAnnotatedTypeFactory- Parameters:
element- the element- Returns:
- the set of default-for-use qualifiers; empty in this implementation
-
createDefaultForTypeAnnotator
Creates anDefaultForTypeAnnotator.- Returns:
- a new
DefaultForTypeAnnotator
-
getDefaultForTypeAnnotator
Returns theDefaultForTypeAnnotator.- Returns:
- the
DefaultForTypeAnnotator
-
createFlowAnalysis
Returns the appropriate flow analysis class that is used for the org.checkerframework.dataflow analysis.This implementation uses the checker naming convention to create the appropriate analysis. If no transfer function is found, it returns an instance of
CFAnalysis.Subclasses have to override this method to create the appropriate analysis if they do not follow the checker naming convention.
- Returns:
- the appropriate flow analysis class that is used for the org.checkerframework.dataflow analysis
-
createFlowTransferFunction
public TransferFunction createFlowTransferFunction(CFAbstractAnalysis<Value, Store, TransferFunction> analysis) Returns the appropriate transfer function that is used for the given org.checkerframework.dataflow analysis.This implementation uses the checker naming convention to create the appropriate transfer function. If no transfer function is found, it returns an instance of
CFTransfer.Subclasses have to override this method to create the appropriate transfer function if they do not follow the checker naming convention.
- Parameters:
analysis- a dataflow analysis- Returns:
- a new transfer function
-
createDependentTypesHelper
Creates aDependentTypesHelperand returns it. UsegetDependentTypesHelper()to access the value.- Returns:
- a new
DependentTypesHelper
-
getDependentTypesHelper
Returns the DependentTypesHelper.- Returns:
- the DependentTypesHelper
-
createContractsFromMethod
Creates anDefaultContractsFromMethodand returns it. If contract annotations are not used for a type system, override this method and return aNoContractsFromMethod.- Returns:
- a new
ContractsFromMethod
-
getContractsFromMethod
Returns the helper for method pre- and postconditions.- Returns:
- the helper for method pre- and postconditions
-
getExplicitNewClassClassTypeArgs
Description copied from class:AnnotatedTypeFactoryReturns the partially-annotated explicit class type arguments of the new class tree. TheAnnotatedTypeMirroronly include the annotations explicitly written on the explict type arguments. (IfnewClassuse a diamond operator, this method returns the empty list.) For example, when called withnew MyClass<@HERE String>()this method would return a list containing@HERE String.- Overrides:
getExplicitNewClassClassTypeArgsin classAnnotatedTypeFactory- Parameters:
newClassTree- a new class tree- Returns:
- the partially annotated
AnnotatedTypeMirrors for the (explicit) class type arguments of the new class tree
-
getExplicitNewClassAnnos
Description copied from class:AnnotatedTypeFactoryReturns the annotations explicitly written on a NewClassTree.new @HERE Class()- Overrides:
getExplicitNewClassAnnosin classAnnotatedTypeFactory- Parameters:
newClassTree- a constructor invocation- Returns:
- the annotations explicitly written on a NewClassTree
-
createAndInitQualifierDefaults
CreateQualifierDefaultswhich handles checker specified defaults, and initialize the createdQualifierDefaults. Subclasses should overrideaddCheckedCodeDefaults(QualifierDefaults defs)to add more defaults or use different defaults.- Returns:
- the QualifierDefaults object
-
createQualifierDefaults
CreateQualifierDefaultswhich handles checker specified defaults. Sub-classes override this method to provide a differentQualifierDefaultimplementation. -
getSortedQualifierNames
Creates and returns a string containing the number of qualifiers and the canonical class names of each qualifier that has been added to this checker's supported qualifier set. The names are alphabetically sorted.- Returns:
- a string containing the number of qualifiers and canonical names of each qualifier
-
addCheckedCodeDefaults
Adds default qualifiers for type-checked code by readingDefaultForandDefaultQualifierInHierarchymeta-annotations. Subclasses may override this method to add defaults that cannot be specified with aDefaultFororDefaultQualifierInHierarchymeta-annotations.- Parameters:
defs- the QualifierDefault object to which defaults are added
-
addCheckedStandardDefaults
Adds the standard CLIMB defaults that do not conflict with previously added defaults.- Parameters:
defs-QualifierDefaultsobject to which defaults are added
-
addUncheckedStandardDefaults
Adds the defaults for unchecked code of each mode the command-line options enable. Subclasses may override this method to customize unchecked-code defaults.- Parameters:
defs-QualifierDefaultsobject to which defaults are added
-
checkForDefaultQualifierInHierarchy
Check that a default qualifier (in at least one hierarchy) has been set and issue an error if not.- Parameters:
defs-QualifierDefaultsobject to which defaults are added
-
createQualifierPolymorphism
Creates theQualifierPolymorphisminstance which supports the QualifierPolymorphism mechanism.- Returns:
- the QualifierPolymorphism instance to use
-
getQualifierPolymorphism
Gives the currentQualifierPolymorphisminstance which supports the QualifierPolymorphism mechanism.- Returns:
- the QualifierPolymorphism instance to use
-
getAnnotationFromJavaExpressionString
public @Nullable AnnotationMirror getAnnotationFromJavaExpressionString(String expression, Tree tree, TreePath path, Class<? extends Annotation> clazz) throws JavaExpressionParseException Returns the primary annotation withclazzonexpression's type, at a particular location. The returned annotation may be null even if the expression should have a primary annotation ofclazz. This is becauseJavaExpressions do not always have enough information to get an annotated type.This method should only be used if a tree, element, or node is not available for
expression. UseAnnotatedTypeFactory.getAnnotatedType(Tree)orAnnotatedTypeFactory.getAnnotatedType(Element)instead.- Parameters:
expression- the expression for which the annotation is returnedtree- current treepath- location at which expression is evaluatedclazz- the annotation class for which to look- Returns:
- the annotation of
clazzonexpression's type, or null if one does not exist or ifexpressiondoes not have enough information to get the annotated type - Throws:
JavaExpressionParseException- thrown if the expression cannot be parsed
-
getAnnotationFromJavaExpression
public @Nullable AnnotationMirror getAnnotationFromJavaExpression(JavaExpression expr, Tree tree, Class<? extends Annotation> clazz) Returns the primary annotation withclazzonexpr's type, at a particular location. The returned annotation may be null even if the expression should have a primary annotation ofclazz. This is becauseJavaExpressions do not always have enough information to get an annotated type.This method should only be used if a tree, element, or node is not available for
expr. UseAnnotatedTypeFactory.getAnnotatedType(Tree)orAnnotatedTypeFactory.getAnnotatedType(Element)instead.- Parameters:
expr- the expression for which the annotation is returnedtree- current treeclazz- the annotation class for which to look- Returns:
- the annotation of
clazzonexpr's type, or null if one does not exist or ifexprdoes not have enough information to get the annotated type
-
getAnnotationsFromJavaExpression
Returns the primary annotations on an expression, at a particular location. The returned set of annotations may be empty even if the expression should have primary annotations. This is becauseJavaExpressiondo not always have enough information to get an annotated type.This method should only be used if a tree, element, or node is not available for
expr. UseAnnotatedTypeFactory.getAnnotatedType(Tree)orAnnotatedTypeFactory.getAnnotatedType(Element)instead.- Parameters:
expr- the expression for which the annotation is returnedtree- current tree- Returns:
- the annotations on the expression. May be empty if
exprdoes not have enough information to get the annotated type.
-
parseJavaExpressionString
public JavaExpression parseJavaExpressionString(String expression, TreePath currentPath) throws JavaExpressionParseException Produces the JavaExpression as ifexpressionwere written atcurrentPath.- Parameters:
expression- a Java expressioncurrentPath- the current path- Returns:
- the JavaExpression associated with expression on currentPath
- Throws:
JavaExpressionParseException- thrown if the expression cannot be parsed
-
getExpressionAndOffsetFromJavaExpressionString
public Pair<JavaExpression,String> getExpressionAndOffsetFromJavaExpressionString(String expression, TreePath currentPath) throws JavaExpressionParseException Produces the JavaExpression and offset associated with an expression. For instance, "n+1" has no associated JavaExpression, but this method produces a pair of a JavaExpression (for "n") and an offset ("1").- Parameters:
expression- a Java expression, possibly with a constant offsetcurrentPath- location at which expression is evaluated- Returns:
- the JavaExpression and offset for the given expression
- Throws:
JavaExpressionParseException- thrown if the expression cannot be parsed
-
getAnnotationMirrorFromJavaExpressionString
public @Nullable AnnotationMirror getAnnotationMirrorFromJavaExpressionString(String expression, Tree tree, TreePath currentPath) throws JavaExpressionParseException Returns the annotation mirror from dataflow forexpression.This will output a different annotation than
getAnnotationFromJavaExpressionString(String, Tree, TreePath, Class), because if the specified annotation isn't found in the store, the type from the factory is used.- Parameters:
expression- a Java expressiontree- the tree at the location to parse the expressioncurrentPath- location at which expression is evaluated- Returns:
- an AnnotationMirror representing the type in the store at the given location from this type factory's type system, or null if one is not available
- Throws:
JavaExpressionParseException- thrown if the expression cannot be parsed
-
isUnreachable
Returns true if theexprTreeis unreachable. This is a conservative estimate and may returnfalseeven though theexprTreeis unreachable. Only meaningful when "-AignoreDeadCode" was passed on the command line; otherwise always returnsfalse.- Parameters:
exprTree- an expression tree- Returns:
- true if the
exprTreeis unreachable
-
isAnonymousDiamondSupertypeFinal
Description copied from class:AnnotatedTypeFactoryReturns true if the supertype inferred for the anonymous class created bycreation, a diamond such asnew C<>(args) {...}, can no longer change. It is inferred from the types of the arguments and of the context, which change during dataflow analysis of the enclosing method.This implementation, which performs no dataflow analysis, returns true, like
AnnotatedTypeFactory.canUseCachedFlowDependentType(ExpressionTree).GenericAnnotatedTypeFactoryreturns true once dataflow analysis of the anonymous class has started, which is after that of the enclosing method. A factory that does not keep track of the analyzed classes itself must forward to the factory that does.- Overrides:
isAnonymousDiamondSupertypeFinalin classAnnotatedTypeFactory- Parameters:
creation- an anonymous class creation with a diamond- Returns:
- true if the inferred supertype of the anonymous class can no longer change
-
getRegularExitStore
Returns the regular exit store for a method or another code block (such as static initializers). Returnsnullif there is no such store. This can happen because the method cannot exit through the regular exit block, or it is abstract or in an interface.- Parameters:
tree- a MethodTree or other code block, such as a static initializer- Returns:
- the regular exit store, or
null
-
getExceptionalExitStore
Returns the exceptional exit store for a method or another code block (such as static initializers).- Parameters:
tree- a MethodTree or other code block, such as a static initializer- Returns:
- the exceptional exit store, or
null, if there is no such store
-
getReturnStatementStores
public List<Pair<ReturnNode,TransferResult<Value, getReturnStatementStoresStore>>> (MethodTree methodTree) Returns a list of all return statements ofmethodpaired with their correspondingTransferResult. Ifmethodhas no return statement, then the empty list is returned.- Parameters:
methodTree- method whose return statements should be returned- Returns:
- a list of all return statements of
methodpaired with their correspondingTransferResultor an empty list ifmethodhas no return statements
-
getStoreBefore
Returns the store immediately before a givenTree.- Parameters:
tree- the tree- Returns:
- the store immediately before a given
Tree
-
getStoreBefore
Returns the store immediately before a given node.- Parameters:
node- a node whose pre-store to return- Returns:
- the store immediately before
node
-
getStoreAfter
Returns the store immediately after a given tree.May return null; for example, after a
returnstatement.- Parameters:
tree- the tree whose post-store to return- Returns:
- the store immediately after a given tree
-
getStoreAfter
Returns the store immediately after a givenNode.- Parameters:
node- node after which the store is returned- Returns:
- the store immediately after a given
Node
-
getNodesForTree
-
getFirstNodeOfKindForTree
Returns the firstNodefor a givenTreethat has classkind.You probably don't want to use this function: iterate over the result of
getNodesForTree(Tree)yourself or ask for a conservative approximation of the store usinggetStoreBefore(Tree)orgetStoreAfter(Tree). This method is for code that uses aNodein a rather unusual way. Callers should probably be rewritten to not use aNodeat all. -
getFinalLocalValues
Returns the value of effectively final local variables.- Returns:
- the value of effectively final local variables
-
getFinalLocalValues
Returns the values of the effectively-final local variables whose declaration is directly enclosed by the given element.- Parameters:
declarer- an element, typically a method, lambda, or initializer- Returns:
- the values of the effectively-final local variables declared directly in
declarer; the empty map if there are none
-
isNotFullyInitializedReceiver
Returns true if the receiver of a method or constructor might not be fully initialized.- Parameters:
methodDeclTree- the declaration of the method or constructor- Returns:
- true if the receiver of a method or constructor might not be fully initialized
-
performFlowAnalysisForClass
Perform a org.checkerframework.dataflow analysis over a single class tree and its nested classes.This method does the bookkeeping that
canUseCachedFlowDependentType(ExpressionTree)relies on: it counts the active analyses and discards the cached types of expressions that the analysis may refine. It is final so that no subclass can skip it; a subclass customizes the analysis by overridingperformFlowAnalysisForClassImpl(ClassTree).- Parameters:
classTree- the class to analyze
-
canUseCachedFlowDependentType
Returns true if a cached type of the flow-dependent expressiontree(seeAnnotatedTypeFactory.isFlowDependent(ExpressionTree)) is still correct, i.e., the refined types of the expressions it was computed from have not changed since it was cached. This implementation, which performs no dataflow analysis, returns true.A factory that computes the types of expressions from another factory's dataflow results, such as the Initialization Checker's from the
InitializationFieldAccessSubchecker's, relies on the order of the checkers: the subchecker finishes the compilation unit before the parent checker's visitor runs. It may keep this default only as long as it is not queried earlier. A factory that can be queried earlier must override this method andAnnotatedTypeFactory.canCacheFlowDependentType(ExpressionTree).AnnotatedTypeFactory.isAnonymousDiamondSupertypeFinal(com.sun.source.tree.NewClassTree)has the same default for the same reason.When no dataflow analysis is running, the refined types of the trees of all classes that have been analyzed are final, and a class is analyzed before any of its trees are type-checked; the cached types of the trees of a class that has not been analyzed yet are discarded when its analysis starts.
While a class is analyzed, a cached type is used only for a tree that is evaluated before the tree whose node the analysis is computing: a proper subexpression of that tree, or part of the receiver or of an earlier argument of an enclosing invocation. The node of such a tree was visited before the current node in the current pass, so its cached type was computed in the current pass and not in an earlier one (see
canCacheFlowDependentType(ExpressionTree)). The cached type of any other tree may be from an earlier pass over a loop: for example, inferring the type arguments ofbar()infoo(bar(), id(x))also types the later argumentid(x), whose node has not been visited yet. A backward analysis would need another rule.- Overrides:
canUseCachedFlowDependentTypein classAnnotatedTypeFactory- Parameters:
tree- a flow-dependent expression- Returns:
- true if a cached type of
treecan be used
-
canCacheFlowDependentType
Returns true if the type of the flow-dependent expressiontree(seeAnnotatedTypeFactory.isFlowDependent(ExpressionTree)) can be cached, i.e., it is computed from refined types that remain correct as long asAnnotatedTypeFactory.canUseCachedFlowDependentType(ExpressionTree)holds. The type of a poly expression whose type arguments are inferred together with an enclosing invocation also depends on the other arguments of that invocation, not only on its own subexpressions. This implementation, which performs no dataflow analysis, returns true.While a class is analyzed, the type of a tree is cached only when the analysis computes the value of the tree's own node and the tree is its own type argument inference problem, that is, not a poly expression whose type arguments are inferred together with an enclosing invocation. Then its type depends only on its subexpressions, whose nodes have been visited in the current pass, and the tree's own node recomputes its type at each visit. The type of
bar()infoo(bar(), id(x))depends on the type ofid(x), whose node is visited after that ofbar().- Overrides:
canCacheFlowDependentTypein classAnnotatedTypeFactory- Parameters:
tree- a flow-dependent expression- Returns:
- true if the type of
treecan be cached
-
isComputingNodeValue
protected boolean isComputingNodeValue()Returns true if a dataflow analysis is computing the value of a node, which it does from the type of the node's tree. The analysis state that the types of expressions depend on does not change during that computation, so the results of type argument inference during it are reused within it (seeAnnotatedTypeFactory.nodeValueInferenceResultCache). This implementation, which performs no dataflow analysis, returns false.The analysis computes the value of a node in
CFAbstractTransfer.getValueFromFactory(com.sun.source.tree.Tree, org.checkerframework.dataflow.cfg.node.Node), which sets the analysis's current tree for the duration of the computation and clears the reused results before and after it.- Overrides:
isComputingNodeValuein classAnnotatedTypeFactory- Returns:
- true if a dataflow analysis is computing the value of a node
-
getStandaloneTypeForNodeValue
Returns the type oftreefor the dataflow value of its node, computed as iftreewere not nested in another expression, or null if the value is computed fromAnnotatedTypeFactory.getAnnotatedType(Tree)as usual.This applies to a diamond that does not create an anonymous class, has no poly expression argument, and is inferred together with an enclosing invocation, such as
new Pair<>(a, b)inArrays.asList(new Pair<>(a, b), ...). Its type arguments come from that invocation, but its primary annotations, which are all that a dataflow value keeps of its type, do not; inferring the enclosing invocation for each such argument would take time quadratic in the number of arguments. The underlying type of the result is not the one javac infers, so the caller uses only its primary annotations.The primary annotations of such a diamond are the same with and without the enclosing inference: a test that compared them for every nested diamond in the Checker Framework's tests and in a large project found no difference (see performance-notes.md and framework/tests/standalone-diamond). That is not so for a generic method invocation, whose return type can be a type variable that only the enclosing inference determines, nor for a lambda, which has no type without its target, so neither may be a direct argument.
- Parameters:
tree- a tree whose node's value is being computed- Returns:
- the type of
treeinferred without its enclosing invocation, or null
-
performFlowAnalysisForClassImpl
Performs the dataflow analysis forperformFlowAnalysisForClass(com.sun.source.tree.ClassTree), which calls this method between its bookkeeping. A subclass that does not run its own analysis, or runs it only under some condition, overrides this method and notperformFlowAnalysisForClass, which it cannot override.- Parameters:
classTree- the class to analyze
-
analyze
protected ControlFlowGraph analyze(Queue<Pair<ClassTree, @Nullable Store>> classQueue, Queue<Pair<LambdaExpressionTree, @Nullable Store>> lambdaQueue, UnderlyingAST ast, List<CFAbstractAnalysis.FieldInitialValue<Value>> fieldValues, @Nullable ControlFlowGraph cfg, boolean isInitializationCode, boolean updateInitializationStore, boolean isStatic, @Nullable Store capturedStore) Analyze the ASTastand store the result. Additional operations that should be performed after analysis should be implemented inpostAnalyze(ControlFlowGraph).- Parameters:
classQueue- the queue for encountered class trees and their initial storeslambdaQueue- the queue for encountered lambda expression trees and their initial storesast- the AST to analyzefieldValues- the abstract values for all fields of the same classcfg- control flow graph to use; if null, one will be created and returnedisInitializationCode- are we analyzing a (static/non-static) initializer block of a classupdateInitializationStore- should the initialization store be updatedisStatic- are we analyzing a static constructcapturedStore- the input Store to use for captured variables, e.g. in a lambda- Returns:
- the control flow graph for
ast, which iscfgifcfgis non-null - See Also:
-
runWithBodyVisitorPath
Runsactionwith the visitor tree path set to the code ofcfg, asanalyze(java.util.Queue<org.checkerframework.javacutil.Pair<com.sun.source.tree.ClassTree, Store>>, java.util.Queue<org.checkerframework.javacutil.Pair<com.sun.source.tree.LambdaExpressionTree, Store>>, org.checkerframework.dataflow.cfg.UnderlyingAST, java.util.List<org.checkerframework.framework.flow.CFAbstractAnalysis.FieldInitialValue<Value>>, org.checkerframework.dataflow.cfg.ControlFlowGraph, boolean, boolean, boolean, Store)does for the analysis itself. Without it, a path lookup made byactionresolves against whatever path the visitor last set, fails, andAnnotatedTypeFactory.getPath(com.sun.source.tree.Tree)caches that failure for the rest of the compilation unit.- Parameters:
cfg- a CFG that has been analyzedaction- the action to run
-
isIgnoredExceptionType
Returns true iftypeMirroris an exception type that should be ignored.- Parameters:
typeMirror- an exception type- Returns:
- true if
typeMirroris an exception type that should be ignored
-
postAnalyze
Perform any additional operations on a CFG. Called once per CFG, after the CFG has been analyzed byanalyze(Queue, Queue, UnderlyingAST, List, ControlFlowGraph, boolean, boolean, boolean, CFAbstractStore). If the CFG is analyzed more than once, this method is still only called one time after the last time the CFG is analyzed. This method can be used to initialize additional state or to perform any analyzes that are easier to perform on the CFG instead of the AST.This implementation type-checks the method invocations that the CFG synthesized for conversions, see
BaseTypeVisitor.checkSyntheticMethodInvocations(org.checkerframework.dataflow.cfg.ControlFlowGraph), and visualizes the CFG if requested.- Parameters:
cfg- the CFG- See Also:
-
handleCFGViz
Handle the visualization of the CFG, if necessary.- Parameters:
cfg- the CFG
-
getAnnotatedTypeLhsNoTypeVarDefault
Returns the type of the left-hand side of an assignment without applying local variable defaults to type variables.The type variables that are types of local variables are defaulted to top so that they can be refined by dataflow. When these types are used as context during type argument inference, this default is too conservative. So this method is used instead of
getAnnotatedTypeLhs(Tree).InferenceFactory.assignedToVariable(AnnotatedTypeFactory, Tree)explains why a different type is used.- Parameters:
lhsTree- left-hand side of an assignment- Returns:
- AnnotatedTypeMirror of
lhsTree
-
isComputingAnnotatedTypeMirrorOfLhs
public boolean isComputingAnnotatedTypeMirrorOfLhs()Returns whethergetAnnotatedTypeLhs(Tree)is running right now. This controls which hierarchies' qualifiers are changed based on the receiver type and the declared annotations for a field.- Returns:
- whether
getAnnotatedTypeLhs(Tree)is running right now - See Also:
-
getAnnotatedTypeBefore
Returns the type of a JavaExpressionexprif it were evaluated before a treetree.This is used by
BaseTypeVisitor.visitMethodInvocation(MethodInvocationTree, Void)to check the preconditions of method calls.- Parameters:
expr- the expression to typetree- a tree- Returns:
- the type of
exprif it were evaluated before treetree
-
getAnnotatedTypeLhs
Returns the type of a left-hand side of an assignment.The default implementation returns the type without considering dataflow type refinement. Subclass can override this method and add additional logic for computing the type of a LHS.
- Parameters:
lhsTree- left-hand side of an assignment- Returns:
- AnnotatedTypeMirror of
lhsTree
-
getAnnotatedTypeVarargsArray
Returns the type of a varargs array of a method invocation or a constructor invocation. Returns null only if private fielduseFlowis false.- Parameters:
tree- a method invocation or a constructor invocation- Returns:
- AnnotatedTypeMirror of varargs array for a method or constructor invocation
tree; returns null if private fielduseFlowis false
-
getAnnotatedTypeRhsUnaryAssign
Returns the type ofv + 1orv - 1wherevis the expression in the postfixed increment or decrement expression.- Parameters:
tree- a postfixed increment or decrement tree- Returns:
- AnnotatedTypeMirror of a right-hand side of an assignment for unary operation
-
constructorFromUse
protected AnnotatedTypeFactory.ParameterizedExecutableType constructorFromUse(NewClassTree tree, boolean inferTypeArgs) Description copied from class:AnnotatedTypeFactoryThe implementation ofAnnotatedTypeFactory.constructorFromUse(NewClassTree)andAnnotatedTypeFactory.constructorFromUseWithoutTypeArgInference(NewClassTree).- Overrides:
constructorFromUsein classAnnotatedTypeFactory- Parameters:
tree- the constructor invocation treeinferTypeArgs- true if the type arguments should be inferred- Returns:
- the annotated type of the invoked constructor (as an executable type) and the type arguments
-
constructorFromUsePreSubstitution
protected void constructorFromUsePreSubstitution(NewClassTree tree, AnnotatedTypeMirror.AnnotatedExecutableType type, boolean resolvePolyQuals) Description copied from class:AnnotatedTypeFactoryA callback method for the AnnotatedTypeFactory subtypes to customize the handling of the declared constructor type before type variable substitution.- Overrides:
constructorFromUsePreSubstitutionin classAnnotatedTypeFactory- Parameters:
tree- a NewClassTree from constructorFromUse()type- declared method type before type variable substitutionresolvePolyQuals- if true, resolve polymorphic qualifiers
-
getMethodReturnType
Description copied from class:AnnotatedTypeFactoryReturns the return type of the methodm.- Overrides:
getMethodReturnTypein classAnnotatedTypeFactory- Parameters:
m- tree of a method declaration- Returns:
- the return type of the method
-
addDefaultAnnotations
Description copied from class:AnnotatedTypeFactoryAdds default annotations totype. This method should only be used in places where the correct annotations cannot be computed because of type argument of raw types. (SeeAnnotatedTypeMirror.AnnotatedWildcardType.isTypeArgOfRawType().)- Overrides:
addDefaultAnnotationsin classAnnotatedTypeFactory- Parameters:
type- annotated type to which default annotations are added
-
getDefaultAnnotations
Removes all primary annotations on a copy of the type and calculates the default annotations that apply to the copied type, without type refinements.- Parameters:
tree- tree where the type is usedtype- type to determine the defaulted version for- Returns:
- the annotated type mirror with default annotations
-
addComputedTypeAnnotationsWithoutFlow
A helper method to add computed type annotations to a type without using flow information.This method is final; override
addComputedTypeAnnotations(Tree, AnnotatedTypeMirror)instead.- Parameters:
tree- an AST nodetype- the type obtained from tree- See Also:
-
addComputedTypeAnnotations
Changes annotations on a type obtained from aTree. By default, this method does nothing. GenericAnnotatedTypeFactory uses this method to implement defaulting and inference (flow-sensitive type refinement). Its subclasses usually override it only to customize default annotations.Subclasses that override this method should also override
AnnotatedTypeFactory.addComputedTypeAnnotations(Element, AnnotatedTypeMirror).This method adds defaults and flow-sensitive type refinements.
- Overrides:
addComputedTypeAnnotationsin classAnnotatedTypeFactory- Parameters:
tree- an AST nodetype- the type obtained fromtree- See Also:
-
performFlowAnalysisForClassOnce
Flow analysis will be performed if all of the following are true.treeis aClassTree- Flow analysis has not already been performed on
tree
- Parameters:
classTree- the tree to check and possibly perform flow analysis on
-
getInferredValueFor
Returns the inferred value (by the org.checkerframework.dataflow analysis) for a given tree.- Parameters:
tree- the tree- Returns:
- the value for the tree, if one has been computed by dataflow. If no value has been computed, null is returned (this does not mean that no value will ever be computed for the given tree).
-
applyInferredAnnotations
Applies the annotations inferred by the org.checkerframework.dataflow analysis to the typetype.- Parameters:
type- the type to modifyinferred- the inferred annotations to apply
-
applyQualifierParameterDefaults
Applies defaults for types in a class with an qualifier parameter.Within a class with
@HasQualifierParameter, types with that class default to the polymorphic qualifier rather than the typical default. Local variables with a type that has a qualifier parameter are initialized to the type of their initializer, rather than the default for local variables.- Parameters:
tree- a Tree whose type istypetype- where the defaults are applied
-
applyQualifierParameterDefaults
Applies defaults for types in a class with an qualifier parameter.Within a class with
@HasQualifierParameter, types with that class default to the polymorphic qualifier rather than the typical default. Local variables with a type that has a qualifier parameter are initialized to the type of their initializer, rather than the default for local variables.- Parameters:
elt- an Element whose type istypetype- where the defaults are applied
-
clearParsePhaseCache
public void clearParsePhaseCache()Description copied from class:AnnotatedTypeFactoryClears any caches used exclusively during the parse phase. Subclasses may override this to clear their own caches.- Overrides:
clearParsePhaseCachein classAnnotatedTypeFactory
-
addComputedTypeAnnotations
To add annotations to the type of method or constructor parameters, add aTypeAnnotatorusingcreateTypeAnnotator()and see the comment inTypeAnnotator.visitExecutable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType, Void).- Overrides:
addComputedTypeAnnotationsin classAnnotatedTypeFactory- Parameters:
elt- an elementtype- the type obtained fromelt
-
methodFromUse
protected AnnotatedTypeFactory.ParameterizedExecutableType methodFromUse(MethodInvocationTree tree, boolean inferTypeArg) Description copied from class:AnnotatedTypeFactoryThe implementation ofAnnotatedTypeFactory.methodFromUse(MethodInvocationTree)andAnnotatedTypeFactory.methodFromUseWithoutTypeArgInference(MethodInvocationTree).- Overrides:
methodFromUsein classAnnotatedTypeFactory- Parameters:
tree- a method invocation treeinferTypeArg- true if type arguments should be inferred- Returns:
- the type of the invoked method, any explicit type arguments, and if
inferTypeArgsis true, any inferred type arguments
-
methodFromUsePreSubstitution
public void methodFromUsePreSubstitution(ExpressionTree tree, AnnotatedTypeMirror.AnnotatedExecutableType type, boolean resolvePolyQuals) Description copied from class:AnnotatedTypeFactoryA callback method for the AnnotatedTypeFactory subtypes to customize the handling of the declared method type before type variable substitution.- Overrides:
methodFromUsePreSubstitutionin classAnnotatedTypeFactory- Parameters:
tree- either a method invocation or a member reference treetype- declared method type before type variable substitutionresolvePolyQuals- if true, resolve polymorphic qualifiers
-
typeVariablesFromUse
public List<AnnotatedTypeParameterBounds> typeVariablesFromUse(AnnotatedTypeMirror.AnnotatedDeclaredType type, TypeElement element) Description copied from class:AnnotatedTypeFactoryAdapt the upper bounds of the type variables of a class relative to the type instantiation. In some type systems, the upper bounds depend on the instantiation of the class. For example, in the Generic Universe Type system, consider a class declaration
then the instantiationclass C<X extends @Peer Object>
is legal. The upper bounds of class C have to be adapted by the main modifier.@Rep C<@Rep Object>An example of an adaptation follows. Suppose, I have a declaration:
And an instantiation:class MyClass<E extends List<E>>new MyClass<@NonNull String>()The upper bound of E adapted to the argument String, would be
List<@NonNull String>and the lower bound would be an AnnotatedNullType.TODO: ensure that this method is consistently used instead of directly querying the type variables.
- Overrides:
typeVariablesFromUsein classAnnotatedTypeFactory- Parameters:
type- the use of the typeelement- the corresponding element- Returns:
- the adapted bounds of the type parameters
-
getEmptyStore
Returns the empty store.- Returns:
- the empty store
-
getTypeFactoryOfSubchecker
public final <T extends GenericAnnotatedTypeFactory<?,?, T getTypeFactoryOfSubchecker?, ?>> (Class<? extends SourceChecker> subCheckerClass) Returns the type factory used by a subchecker. Throws an exception if no matching subchecker was found or if the type factory is null. The caller must know the exact checker class to request.Because the visitor path is copied, call this method each time a subfactory is needed rather than store the returned subfactory in a field.
- Type Parameters:
T- the type ofsubCheckerClass'sAnnotatedTypeFactory- Parameters:
subCheckerClass- the exact class of the subchecker- Returns:
- the AnnotatedTypeFactory of the subchecker; never null
- See Also:
-
getTypeFactoryOfSubcheckerOrNull
public <T extends GenericAnnotatedTypeFactory<?,?, @Nullable T getTypeFactoryOfSubcheckerOrNull?, ?>> (Class<? extends SourceChecker> subCheckerClass) Returns the type factory used by a subchecker. Returns null if no matching subchecker was found or if the type factory is null. The caller must know the exact checker class to request.Because the visitor path is copied, call this method each time a subfactory is needed rather than store the returned subfactory in a field.
- Type Parameters:
T- the type ofsubCheckerClass'sAnnotatedTypeFactory- Parameters:
subCheckerClass- the exact class of the subchecker- Returns:
- the AnnotatedTypeFactory of the subchecker or null if no subchecker exists
- See Also:
-
getShouldDefaultTypeVarLocals
public boolean getShouldDefaultTypeVarLocals()Should the local variable default annotation be applied to type variables?It is initialized to true if data flow is used by the checker. It is set to false when getting the assignment context for type argument inference.
- Returns:
- shouldDefaultTypeVarLocals
- See Also:
-
createCFGVisualizer
Create a new CFGVisualizer.- Returns:
- a new CFGVisualizer, or null if none will be used on this run
-
getCFGVisualizer
The CFGVisualizer to be used by all CFAbstractAnalysis instances. -
postAsMemberOf
Description copied from class:AnnotatedTypeFactoryA callback method for the AnnotatedTypeFactory subtypes to customize AnnotatedTypes.asMemberOf(). Overriding methods should merely change the annotations on the subtypes, without changing the types.- Overrides:
postAsMemberOfin classAnnotatedTypeFactory- Parameters:
type- the annotated type of the elementowner- the annotated type of the receiver of the accessing treeelement- the element of the field or method
-
addAnnotationsFromDefaultForType
protected void addAnnotationsFromDefaultForType(@Nullable Element element, AnnotatedTypeMirror type) Adds default qualifiers based on the underlying type oftypetotype. Ifelementis a local variable, or if the type already has an annotation from the relevant type hierarchy, then the defaults are not added.(This uses both the
DefaultQualifierForUseTypeAnnotatorandDefaultForTypeAnnotator.)- Parameters:
element- possibly null element whose type istypetype- the type to which defaults are added
-
isRelevant
Returns true if users can write type annotations from this type system directly on the given Java type.For a compound type, returns true only if a programmer may write a type qualifier on the top level of the compound type. That is, this method may return false, when it is possible to write type qualifiers on elements of the type.
Subclasses should override
#isRelevantImplinstead of this method.- Parameters:
tm- a type- Returns:
- true if users can write type annotations from this type system directly on the given Java type
-
isRelevant
Returns true if users can write type annotations from this type system directly on the given Java type.For a compound type, returns true only if it a programmer may write a type qualifier on the top level of the compound type. That is, this method may return false, when it is possible to write type qualifiers on elements of the type.
Subclasses should override
#isRelevantImplinstead of this method.- Parameters:
tm- a type- Returns:
- true if users can write type annotations from this type system directly on the given Java type
-
isRelevantImpl
Returns true if users can write type annotations from this type system on the given Java type. Does not use a cache.Clients should never call this. Call
isRelevant(javax.lang.model.type.TypeMirror)instead. This is a helper method forisRelevant(javax.lang.model.type.TypeMirror).- Parameters:
tm- a type- Returns:
- true if users can write type annotations from this type system on the given Java type
-
irrelevantExtraMessage
Returns a string that can be passed to the "anno.on.irrelevant" error, giving information about which types are relevant.- Returns:
- a string that can be passed to the "anno.on.irrelevant" error, possibly the empty string
-
getDefaultValueAnnotatedType
Returns the type of the default value of the given type. The default value is 0, false, or null.- Parameters:
typeMirror- a type- Returns:
- the annotated type of
type's default value
-
createRequiresOrEnsuresQualifier
protected @Nullable AnnotationMirror createRequiresOrEnsuresQualifier(String expression, AnnotationMirror qualifier, AnnotatedTypeMirror declaredType, Analysis.BeforeOrAfter preOrPost, @Nullable List<AnnotationMirror> preconds) Creates aRequiresQualifier("...")orEnsuresQualifier("...")annotation for the given expression.This is of the form
@RequiresQualifier(expression="expression", qualifier=MyQual.class)or@EnsuresQualifier(expression="expression", qualifier=MyQual.class), where "expression" is exactly the stringexpressionand MyQual is the annotation represented byqualifier.Returns null if the expression is invalid when combined with the kind of annotation: for example, precondition annotations on "this" and parameters ("#1", etc.) are not supported, because receiver/parameter annotations should be inferred instead.
This implementation returns null if no annotation can be created, because the qualifier has elements/arguments, which
@RequiresQualifierand@EnsuresQualifierdo not support. Subclasses may override this method to return qualifiers that do have arguments instead of returning null.- Parameters:
expression- the expression to which the qualifier appliesqualifier- the qualifier that must be presentdeclaredType- the declared type of the expression, which is used to avoid inferring redundant pre- or postcondition annotationspreOrPost- what to return: a precondition or postcondition annotationpreconds- the list of precondition annotations; used to suppress redundant postconditions; non-null exactly whenpreOrPostisBeforeOrAfter.BEFORE- Returns:
- a
RequiresQualifier("...")orEnsuresQualifier("...")annotation for the given expression, or null
-
getEnsuresQualifierIfResult
public @Nullable Boolean getEnsuresQualifierIfResult(Contract.Kind kind, AnnotationMirror contractAnnotation) If kind = CONDITIONALPOSTCONDITION, return the result element, e.g.EnsuresQualifierIf.result(). Otherwise, return null.- Parameters:
kind- the kind ofcontractAnnotationcontractAnnotation- aRequiresQualifier,EnsuresQualifier, orEnsuresQualifierIf- Returns:
- the
resultelement ofcontractAnnotation, or null if it doesn't have aresultelement
-
getContractExpressions
public @Nullable List<String> getContractExpressions(Contract.Kind kind, AnnotationMirror contractAnnotation) IfcontractAnnotationis a framework annotation, return itsexpressionelement. Otherwise,contractAnnotationis defined in a checker. If kind = CONDITIONALPOSTCONDITION, return itsexpressionelement, else return itsvalueelement.- Parameters:
kind- the kind ofcontractAnnotationcontractAnnotation- aRequiresQualifier,EnsuresQualifier, orEnsuresQualifierIf- Returns:
- the
resultelement ofcontractAnnotation, or null if it doesn't have aresultelement
-