Class BaseTypeVisitor<Factory extends GenericAnnotatedTypeFactory<?,?,?,?>>
- All Implemented Interfaces:
TreeVisitor<Void,Void>
- Direct Known Subclasses:
AccumulationVisitor,AinferTestVisitor,AliasingVisitor,ClassValVisitor,DisbarUseVisitor,ElementSuppressionVisitor,FenumVisitor,FormatterVisitor,GrowOnlyVisitor,GuiEffectVisitor,H1H2Visitor,I18nFormatterVisitor,InitializationFieldAccessVisitor,InitializationVisitor,InterningVisitor,IntersectionGlbVisitor,LessThanVisitor,LockVisitor,LowerBoundVisitor,MethodValVisitor,MustCallVisitor,NTDVisitor,NullnessNoInitVisitor,OptionalImplVisitor,ReflectionTestVisitor,RegexVisitor,ReportVisitor,ReturnsReceiverVisitor,SameLenVisitor,SignednessVisitor,SkipDefsVisitor,SqlQuotesVisitor,StandaloneDiamondVisitor,TaintingVisitor,TypeDeclBoundsVisitor,TypeOutputtingChecker.Visitor,UnitsVisitor,UpperBoundVisitor,ValueVisitor,ViewpointTestVisitor
SourceVisitor that performs assignment and pseudo-assignment checking, method
invocation checking, and assignability checking. The visitor visits every construct in a program,
not just types.
This implementation uses the AnnotatedTypeFactory implementation provided by an
associated BaseTypeChecker; its visitor methods will invoke this factory on parts of the
AST to determine the "annotated type" of an expression. Then, the visitor methods will check the
types in assignments and pseudo-assignments using commonAssignmentCheck(com.sun.source.tree.Tree, com.sun.source.tree.ExpressionTree, java.lang.String, java.lang.Object...), which
ultimately calls the TypeHierarchy.isSubtype(org.checkerframework.framework.type.AnnotatedTypeMirror, org.checkerframework.framework.type.AnnotatedTypeMirror) method and reports errors that violate
Java's rules of assignment.
Note that since this implementation only performs assignment and pseudo-assignment checking,
other rules for custom type systems must be added in subclasses (e.g., dereference checking in
the NullnessChecker is implemented in the NullnessChecker's TreeScanner.visitMemberSelect(com.sun.source.tree.MemberSelectTree, P)
method).
This implementation does the following checks:
- Assignment and Pseudo-Assignment Check: It verifies that any assignment type-checks,
using the
TypeHierarchy.isSubtype(org.checkerframework.framework.type.AnnotatedTypeMirror, org.checkerframework.framework.type.AnnotatedTypeMirror)method. This includes method invocation and method overriding checks. - Type Validity Check: It verifies that any user-supplied type is a valid type, using
one of the
isValidUsemethods. - (Re-)Assignability Check: It verifies that any assignment is valid, using
Checker.isAssignablemethod.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static classClass that lazily creates string representations ofAnnotatedTypeMirrors which are only verbose if required to differentiate the two types.classClass to perform method override and method reference checks. -
Field Summary
FieldsModifier and TypeFieldDescriptionfinal booleanTrue if "-AassumePureGetters" was passed on the command line.protected final FactoryThe factory to use for obtaining "parsed" version of annotations.protected final BaseTypeCheckerTheBaseTypeCheckerfor error reporting.protected final AnnotationMirrorThe @Deterministicannotation.protected final AnnotationMirrorThe @Impureannotation.protected @Nullable MethodTreeThe tree of the enclosing method that is currently being visited, if any.protected final AnnotationMirrorThe @Pureannotation.protected final QualifierHierarchyThe qualifier hierarchy.protected final booleanTrue if "-Ashowchecks" was passed on the command line.protected final AnnotationMirrorThe @SideEffectFreeannotation.protected final longThe number of seconds that typechecking must take for a single tree, to issue a "slow typechecking" warning; default 45.The tree of the most recent "slow typechecking" warning.protected final AnnotationMirrorThe @java.lang.annotation.Target annotation.protected final ExecutableElementThevalueelement/field of the @java.lang.annotation.Target annotation.protected final TypeHierarchyThe Annotated Type Hierarchy.protected final TypeValidatorprotected final ExecutableElementThewhenelement/field of the @Unused annotation.protected final booleanTrue if "-AwarnRedundantAnnotations" was passed on the command line.Fields inherited from class org.checkerframework.framework.source.SourceVisitor
elements, root, trees, treesWithSuppressWarnings, types -
Constructor Summary
ConstructorsModifierConstructorDescriptionBaseTypeVisitor(BaseTypeChecker checker) Create a new BaseTypeChecker.protectedBaseTypeVisitor(BaseTypeChecker checker, @Nullable Factory typeFactory) Constructor for creating a BaseTypeVisitor. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidcheckAccess(IdentifierTree identifierTree, Void p) Issues an error if access is not allowed, based on an@Unusedannotation.protected voidcheckAccessAllowed(Element field, @Nullable AnnotatedTypeMirror receiverType, ExpressionTree accessTree) Issues an error if access not allowed, based on an @Unused annotation.protected voidcheckAnnotationOnSupertype(Tree boundClause) Reports anannotation.on.supertypeerror ifboundClausecarries a type qualifier in this checker's hierarchy, or an alias for one, directly on the supertype.protected voidcheckArguments(List<? extends AnnotatedTypeMirror> requiredTypes, List<? extends ExpressionTree> passedArgs, CharSequence executableName, List<?> paramNames) A helper method to check that each passed argument is a subtype of the corresponding required argument.protected booleancheckArrayInitialization(AnnotatedTypeMirror type, List<? extends ExpressionTree> initializers) Checks that the array initializers are consistent with the array type.protected voidcheckConditionalPostcondition(MethodTree methodTree, AnnotationMirror annotation, JavaExpression expression, boolean result) Check that the expression's type is annotated withannotationat every regular exit that returnsresult.protected voidcheckConstructorInvocation(AnnotatedTypeMirror.AnnotatedDeclaredType invocation, AnnotatedTypeMirror.AnnotatedExecutableType constructor, NewClassTree newClassTree) Check that the (explicit) annotations on a new class tree are comparable to the result type of the constructor.protected voidcheckConstructorResult(AnnotatedTypeMirror.AnnotatedExecutableType constructorType, MethodTree constructorTree) Issue a warning if the result type of the constructor declaration is not top.protected booleancheckContract(JavaExpression expr, AnnotationMirror necessaryAnnotation, AnnotationMirror inferredAnnotation, CFAbstractStore<?, ?> store) Returns true if and only ifinferredAnnotationis valid for a given expression to match thenecessaryAnnotation.protected voidCheck the default constructor.protected voidcheckEnclosingExpr(NewClassTree node, AnnotatedTypeMirror.AnnotatedExecutableType constructorType) Helper method to type check the enclosing expression of an inner class instantiation.protected voidIssue error if the exception parameter is not a supertype of the annotation specified bygetExceptionParameterLowerBoundAnnotations(), which is top by default.protected voidcheckExplicitAnnotationsOnIntersectionBounds(AnnotatedTypeMirror.AnnotatedIntersectionType intersection, List<? extends Tree> boundTrees) Issues "explicit.annotation.ignored" warning if any explicit annotation on an intersection bound -- or, if written as an alias, its canonical form -- is not the same as the primary annotation of the given intersection type.protected voidcheckExtendsAndImplements(ClassTree classTree) In@A class X extends @B Y implements @C Z {}, enforce that@Amust be a subtype of@Band@C.protected voidcheckExtendsOrImplements(Tree boundClause, AnnotationMirrorSet classBounds, TypeMirror classType, boolean isExtends) Helper forcheckExtendsAndImplements(com.sun.source.tree.ClassTree)that checks one extends or implements clause.protected final voidcheckExtendsOrImplementsEndDiagnostic(boolean success, Tree boundClause, AnnotationMirror classAnno, TypeMirror classType, AnnotationMirror boundAnno, TypeMirror boundTM, boolean isExtends) Prints a diagnostic after checking an extends or implements clause, if the-Ashowcheckscommand-line option is provided.protected final voidcheckExtendsOrImplementsStartDiagnostic(Tree boundClause, AnnotationMirror classAnno, TypeMirror classType, AnnotationMirror boundAnno, TypeMirror boundTM, boolean isExtends) Prints a diagnostic before checking an extends or implements clause, if the-Ashowcheckscommand-line option is provided.protected voidcheckFieldInvariantDeclarations(ClassTree classTree) Check that the field invariant declaration annotations meet the following requirements: If the superclass ofclassTreehas a field invariant, then the field invariant forclassTreemust include all the fields in the superclass invariant and those fields' annotations must be a subtype (or equal) to the annotations for those fields in the superclass.protected final voidcheckMethodInvocability(AnnotatedTypeMirror.AnnotatedExecutableType method, MethodInvocationTree tree) Tests whether the method can be invoked using the receiver of the 'tree' method invocation, and issues a "method.invocation.invalid" if the invocation is invalid.protected voidcheckMethodInvocability(AnnotatedTypeMirror.AnnotatedExecutableType method, MethodInvocationTree tree, @Nullable AnnotatedTypeMirror receiverType) LikecheckMethodInvocability(AnnotatedExecutableType, MethodInvocationTree), but usesreceiverTypeas the type of the receiver instead of asking the type factory for the type oftree's receiver.protected booleancheckMethodReferenceAsOverride(MemberReferenceTree memberReferenceTree, Void p) Check that a method reference is allowed.protected booleancheckOverride(MethodTree overriderTree, AnnotatedTypeMirror.AnnotatedDeclaredType overriderType, AnnotatedTypeMirror.AnnotatedExecutableType overriddenMethodType, AnnotatedTypeMirror.AnnotatedDeclaredType overriddenType) Type checks that a method may override another method.protected booleancheckOverride(MethodTree overriderTree, AnnotatedTypeMirror.AnnotatedExecutableType overriderMethodType, AnnotatedTypeMirror.AnnotatedDeclaredType overriderType, AnnotatedTypeMirror.AnnotatedExecutableType overriddenMethodType, AnnotatedTypeMirror.AnnotatedDeclaredType overriddenType) Type checks that a method may override another method.protected voidcheckPostcondition(MethodTree methodTree, AnnotationMirror annotation, JavaExpression expression) Check that the expression's type is annotated withannotationat the regular exit store.protected voidcheckPreconditions(MethodInvocationTree tree, Set<Contract.Precondition> preconditions) Checks that all the givenpreconditionshold true immediately prior to the method invocation or variable access attree.protected voidCheck method purity if needed.protected voidcheckQualifierParameter(ClassTree classTree) Issues an error ifclassTreehas polymorphic fields but is not annotated with@HasQualifierParameter.protected voidcheckSuperConstructorCall(MethodInvocationTree superCall) Checks that the following rule is satisfied: The type on a constructor declaration must be a supertype of the return type of "super()" invocation within that constructor.protected voidChecks that the receiver and the arguments of one synthetic method invocation satisfy the declared type of the method that the conversion calls.voidChecks the method invocations that the CFG synthesized for conversions written in the source, such as thevalueOfcall of a boxing conversion, theintValuecall of an unboxing conversion, and theiteratorcall of an enhanced for loop.protected voidcheckThisConstructorCall(MethodInvocationTree thisCall) Checks that the following rule is satisfied: The type on a constructor declaration must be a supertype of the return type of "this()" invocation within that constructor.protected voidcheckThisOrSuperConstructorCall(MethodInvocationTree call, @CompilerMessageKey String errorKey) Checks that the following rule is satisfied: The type on a constructor declaration must be a supertype of the return type of "this()" or "super()" invocation within that constructor.protected voidChecks the type of the thrown expression.protected voidcheckTypeArguments(Tree toptree, List<? extends AnnotatedTypeParameterBounds> paramBounds, List<? extends AnnotatedTypeMirror> typeargs, List<? extends Tree> typeargTrees, CharSequence typeOrMethodName, List<?> paramNames) Checks that the annotations on the type arguments supplied to a type or a method invocation are within the bounds of the type variables as declared, and issues the "type.argument.type.incompatible" error if they are not.protected voidcheckTypecastRedundancy(TypeCastTree typeCastTree) If the lint option "cast:redundant" is set, this method issues a warning if the cast is redundant.protected voidcheckTypecastSafety(TypeCastTree typeCastTree) Issues a warning if the given explicitly-written typecast is unsafe.protected voidcheckVarargs(AnnotatedTypeMirror.AnnotatedExecutableType invokedMethod, Tree tree) If the given invocation is a varargs invocation, check that the array type of actual varargs is a subtype of the corresponding formal parameter; issues "argument.invalid" error if not.protected booleancommonAssignmentCheck(Tree varTree, ExpressionTree valueExpTree, @CompilerMessageKey String errorKey, Object... extraArgs) Checks the validity of an assignment (or pseudo-assignment) from a value to a variable and emits an error message (through the compiler's messaging interface) if it is not valid.protected booleancommonAssignmentCheck(AnnotatedTypeMirror varType, ExpressionTree valueExpTree, @CompilerMessageKey String errorKey, Object... extraArgs) Checks the validity of an assignment (or pseudo-assignment) from a value to a variable and emits an error message (through the compiler's messaging interface) if it is not valid.protected booleancommonAssignmentCheck(AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueExpTree, @CompilerMessageKey String errorKey, Object... extraArgs) Checks the validity of an assignment (or pseudo-assignment) from a value to a variable and emits an error message (through the compiler's messaging interface) if it is not valid.protected final voidcommonAssignmentCheckEndDiagnostic(boolean success, @Nullable String extraMessage, AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueExpTree) Prints a diagnostic about exitingcommonAssignmentCheck(), if the showchecks option was set.protected final voidcommonAssignmentCheckEndDiagnostic(String message, AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueExpTree) Helper method for printing a diagnostic about exitingcommonAssignmentCheck(), if the showchecks option was set.protected final voidcommonAssignmentCheckStartDiagnostic(AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueExpTree) Prints a diagnostic about enteringcommonAssignmentCheck(), if the showchecks option was set.protected StringcontractExpressionAndType(String expression, @Nullable AnnotationMirror qualifier) Returns a string representation of an expression and type qualifier.protected BaseTypeVisitor<Factory>.OverrideCheckercreateOverrideChecker(Tree overriderTree, AnnotatedTypeMirror.AnnotatedExecutableType overriderMethodType, AnnotatedTypeMirror overriderType, AnnotatedTypeMirror overriderReturnType, AnnotatedTypeMirror.AnnotatedExecutableType overriddenMethodType, AnnotatedTypeMirror.AnnotatedDeclaredType overriddenType, AnnotatedTypeMirror overriddenReturnType) Create an OverrideChecker.protected FactoryConstructs an instance of the appropriate type factory for the implemented type system.A public variant ofcreateTypeFactory().protected TypeValidatorprotected @Nullable MemberSelectTreeCall this only when the current path is an identifier.enclosingStatement(Tree tree) Returns the statement that encloses the given one.protected AnnotationMirrorSetReturns a set of AnnotationMirrors that is a lower bound for exception parameters.protected AnnotationMirrorSetReturns a set of AnnotationMirrors that is an upper bound for thrown exceptions.final Factoryprotected booleanisInstanceOfPatternSafe(AnnotatedTypeMirror variableType, AnnotatedTypeMirror expType) Returns true if the instanceof binding pattern is safe.protected booleanisTypeCastSafe(AnnotatedTypeMirror castType, AnnotatedTypeMirror exprType) Returns true if the cast is safe.booleanisValidUse(AnnotatedTypeMirror.AnnotatedArrayType type, Tree tree) Tests that the qualifiers present on the array type are valid.booleanisValidUse(AnnotatedTypeMirror.AnnotatedDeclaredType declarationType, AnnotatedTypeMirror.AnnotatedDeclaredType useType, Tree tree) Tests that the qualifiers present onuseTypeare valid qualifiers, given the qualifiers on the declaration of the type,declarationType.booleanisValidUse(AnnotatedTypeMirror.AnnotatedPrimitiveType type, Tree tree) Tests that the qualifiers present on the primitive type are valid.voidprocessClassTree(ClassTree classTree) Type-check classTree.voidprocessMethodTree(String className, MethodTree tree) Type-check methodTree.voidprocessPackageTree(PackageTree tree, PackageElement elt) Type-checks a package declaration, that is, thepackageclause of apackage-info.java.protected voidreportCommonAssignmentError(AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueTree, @CompilerMessageKey String errorKey, Object... extraArgs) Report a common assignment error.protected voidreportMethodInvocabilityError(MethodInvocationTree tree, AnnotatedTypeMirror found, AnnotatedTypeMirror expected) Report a method invocability error.protected voidreportPurityErrors(PurityChecker.PurityResult result, MethodTree tree, EnumSet<Pure.Kind> expectedKinds) Reports errors found during purity checking.protected voidreportTypeArgumentInferenceFailure(ExpressionTree tree, AnnotatedTypeMirror.AnnotatedExecutableType methodType, InferenceResult inferenceResult) Reports that type argument inference failed because the annotation constraint system had no satisfying solution -- as opposed toInferenceResult.inferenceBudgetExceeded()orInferenceResult.inferenceCrashed(), which are reported separately bycheckTypeArgumentInference(com.sun.source.tree.ExpressionTree, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType)and never reach this method.voidsetRoot(CompilationUnitTree newRoot) Set the CompilationUnitTree to be used during any visits.protected booleanshouldCheckTypeArgument(Tree toptree, AnnotatedTypeParameterBounds bounds, AnnotatedTypeMirror typeArg, @Nullable Tree typeArgTree, CharSequence typeOrMethodName, Object paramName) Returns true if the given type argument should be checked against its type parameter's bounds.protected booleanshouldCheckVarargs(Tree tree) Returns true if the varargs array created for the given varargs invocation should be checked against the formal varargs parameter type.protected final booleanshouldSkipUses(ExpressionTree exprTree) Returns true if the expression should not be checked because of the tree referring to unannotated classes, as specified in thechecker.skipUsesproperty.protected booleanReturns true if the checker should issue warnings about irrelevant java types.protected booleanskipReceiverSubtypeCheck(MethodInvocationTree tree, AnnotatedTypeMirror methodDefinitionReceiver, AnnotatedTypeMirror methodCallReceiver) Returns true if to skip subtype checks on the receiver when checking method invocability.protected voidTestsInsertAjavaAnnotationsif the checker has the "ajavaChecks" option.protected voidTestJointJavacJavaParserVisitorif the checker has the "ajavaChecks" option.protected booleantestTypevarContainment(AnnotatedTypeMirror inner, AnnotatedTypeMirror outer) Returns true if both types are type variables and outer contains inner.protected voidtypeCheckVectorCopyIntoArgument(MethodInvocationTree tree, List<? extends AnnotatedTypeMirror> params) Type checks the method arguments ofVector.copyInto().protected booleanvalidateType(Tree tree, AnnotatedTypeMirror type) Returns true if the type and corresponding type tree is a valid type, and emits an error if that is not the case (e.g.booleanvalidateTypeOf(Tree tree) Returns true if the tree expressed by the passed type tree is a valid type, and emits an error if that is not the case (e.g.visitAnnotatedType(AnnotatedTypeTree tree, Void p) Rather than overriding this method, clients should often overridevisitAnnotatedType(List,Tree).voidvisitAnnotatedType(@Nullable List<? extends AnnotationTree> annoTrees, Tree typeTree) Checks an annotated type.visitAnnotation(AnnotationTree tree, Void p) Ensure that the annotation arguments comply to their declarations.visitAssignment(AssignmentTree tree, Void p) Performs two checks: subtyping and assignability checks, usingcommonAssignmentCheck(Tree, ExpressionTree, String, Object[]).visitCatch(CatchTree tree, Void p) Checks the type of the exception parameter.final VoidvisitClass(ClassTree tree, Void p) Type-check tree and skips classes specified by the skipDef option.visitCompilationUnit(CompilationUnitTree identifierTree, Void p) Override Compilation Unit so we won't visit package names or imports.Performs assignability check.visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) Performs a subtype check, to test whether the tree expression iterable type is a subtype of the variable type in the enhanced for loop.visitIdentifier(IdentifierTree tree, Void p) If "-AignoreDeadCode" was passed on the command line andtree's condition is a compile-time constant, skips checking the branch that can never execute.visitInstanceOf(InstanceOfTree tree, Void p) visitMemberReference(MemberReferenceTree tree, Void p) final VoidvisitMethod(MethodTree tree, Void p) Checks that the method obeys override and subtype rules to all overridden methods.Performs a method invocation check.visitNewArray(NewArrayTree tree, Void p) visitNewClass(NewClassTree tree, Void p) Performs a new class invocation check.visitPackage(PackageTree tree, Void p) visitReturn(ReturnTree tree, Void p) Checks that the type of the return expression is a subtype of the enclosing method required return type.voidvisitSwitchExpression17(Tree switchExpressionTree) This method validates the type of the switch expression.visitThrow(ThrowTree tree, Void p) Checks the type of a thrown exception.visitTypeCast(TypeCastTree tree, Void p) visitTypeParameter(TypeParameterTree tree, Void p) visitUnary(UnaryTree tree, Void p) Performs assignability check.visitVariable(VariableTree tree, Void p) voidwarnAboutIrrelevantJavaTypes(@Nullable List<? extends AnnotationTree> annoTrees, Tree typeTree) Warns if a type annotation is written on a Java type that is not listed in the @RelevantJavaTypes annotation.protected voidwarnInvalidPolymorphicQualifier(ClassTree classTree) Issues an "invalid.polymorphic.qualifier" error for all polymorphic annotations written on the class declaration.protected voidwarnInvalidPolymorphicQualifier(List<? extends TypeParameterTree> typeParameterTrees) Issues an "invalid.polymorphic.qualifier" error for all polymorphic annotations written on the type parameters declaration.protected voidwarnRedundantAnnotations(Tree tree, AnnotatedTypeMirror type) Issues a "redundant.anno" warning if the annotation written on the type is the same as the default annotation for this type and location.Methods inherited from class org.checkerframework.framework.source.SourceVisitor
visitMethods inherited from class com.sun.source.util.TreePathScanner
getCurrentPath, scanMethods inherited from class com.sun.source.util.TreeScanner
reduce, scan, visitAnyPattern, visitArrayAccess, visitArrayType, visitAssert, visitBinary, visitBindingPattern, visitBlock, visitBreak, visitCase, visitConstantCaseLabel, visitContinue, visitDeconstructionPattern, visitDefaultCaseLabel, visitDoWhileLoop, visitEmptyStatement, visitErroneous, visitExports, visitExpressionStatement, visitForLoop, visitImport, visitIntersectionType, visitLabeledStatement, visitLiteral, visitMemberSelect, visitModifiers, visitModule, visitOpens, visitOther, visitParameterizedType, visitParenthesized, visitPatternCaseLabel, visitPrimitiveType, visitProvides, visitRequires, visitStringTemplate, visitSwitch, visitSwitchExpression, visitSynchronized, visitTry, visitUnionType, visitUses, visitWhileLoop, visitWildcard, visitYield
-
Field Details
-
checker
TheBaseTypeCheckerfor error reporting. -
atypeFactory
The factory to use for obtaining "parsed" version of annotations. -
qualHierarchy
The qualifier hierarchy. -
typeHierarchy
The Annotated Type Hierarchy. -
TARGET
The @java.lang.annotation.Target annotation. -
DETERMINISTIC
The @Deterministicannotation. -
SIDE_EFFECT_FREE
The @SideEffectFreeannotation. -
PURE
The @Pureannotation. -
IMPURE
The @Impureannotation. -
targetValueElement
Thevalueelement/field of the @java.lang.annotation.Target annotation. -
unusedWhenElement
Thewhenelement/field of the @Unused annotation. -
showchecks
protected final boolean showchecksTrue if "-Ashowchecks" was passed on the command line. -
assumePureGetters
public final boolean assumePureGettersTrue if "-AassumePureGetters" was passed on the command line. -
warnRedundantAnnotations
protected final boolean warnRedundantAnnotationsTrue if "-AwarnRedundantAnnotations" was passed on the command line. -
methodTree
The tree of the enclosing method that is currently being visited, if any. -
slowTypecheckingSeconds
protected final long slowTypecheckingSecondsThe number of seconds that typechecking must take for a single tree, to issue a "slow typechecking" warning; default 45. -
slowTypecheckingTree
The tree of the most recent "slow typechecking" warning. This is used to avoid warning about both a subtree and a supertree. -
typeValidator
-
-
Constructor Details
-
BaseTypeVisitor
Create a new BaseTypeChecker.- Parameters:
checker- the type-checker associated with this visitor (for callbacks toTypeHierarchy.isSubtype(org.checkerframework.framework.type.AnnotatedTypeMirror, org.checkerframework.framework.type.AnnotatedTypeMirror))
-
BaseTypeVisitor
Constructor for creating a BaseTypeVisitor.- Parameters:
checker- the type-checker associated with this visitortypeFactory- the type factory, or null. If null, this callscreateTypeFactory().
-
-
Method Details
-
createTypeFactory
Constructs an instance of the appropriate type factory for the implemented type system.The default implementation uses the checker naming convention to create the appropriate type factory. If no factory is found, it returns
BaseAnnotatedTypeFactory. It reflectively invokes the constructor that accepts this checker and compilation unit tree (in that order) as arguments.Subclasses have to override this method to create the appropriate visitor if they do not follow the checker naming convention.
- Returns:
- the appropriate type factory
-
getTypeFactory
-
createTypeFactoryPublic
A public variant ofcreateTypeFactory(). Only use this if you know what you are doing.- Returns:
- the appropriate type factory
-
setRoot
Description copied from class:SourceVisitorSet the CompilationUnitTree to be used during any visits. For any later calls ofcom.sun.source.util.TreePathScanner.scan(TreePath, P), the CompilationUnitTree of the TreePath has to be equal toroot.- Overrides:
setRootin classSourceVisitor<Void,Void> - Parameters:
newRoot- the new compilation unit
-
scan
- Overrides:
scanin classSourceVisitor<Void,Void>
-
testJointJavacJavaParserVisitor
protected void testJointJavacJavaParserVisitor()TestJointJavacJavaParserVisitorif the checker has the "ajavaChecks" option.Parse the current source file with JavaParser and check that the AST can be matched with the Tree produced by javac. Crash if not.
Subclasses may override this method to disable the test even if the "ajavaChecks" option is provided.
-
testAnnotationInsertion
protected void testAnnotationInsertion()TestsInsertAjavaAnnotationsif the checker has the "ajavaChecks" option.- Parses the current file with JavaParser.
- Removes all annotations.
- Reinserts the annotations.
- Throws an exception if the ASTs are not the same.
Subclasses may override this method to disable the test even if the option is provided.
-
visitClass
Type-check tree and skips classes specified by the skipDef option. Subclasses should overrideprocessClassTree(ClassTree)instead of this method.- Specified by:
visitClassin interfaceTreeVisitor<Void,Void> - Overrides:
visitClassin classSourceVisitor<Void,Void> - Parameters:
tree- class to checkp- null- Returns:
- null
-
visitPackage
- Specified by:
visitPackagein interfaceTreeVisitor<Void,Void> - Overrides:
visitPackagein classTreeScanner<Void,Void>
-
processPackageTree
Type-checks a package declaration, that is, thepackageclause of apackage-info.java.A package declaration contains no code, so unlike
processClassTree(com.sun.source.tree.ClassTree)this sees only the declaration annotations written on the package. It is the hook for checking those: an annotation whose@TargetincludesPACKAGEcan be written on a package and can contradict another one there exactly as it can on a class.- Parameters:
tree- the package declarationelt- the package declared bytree
-
processClassTree
Type-check classTree. Subclasses should override this method instead ofvisitClass(ClassTree, Void).- Parameters:
classTree- class to check
-
warnInvalidPolymorphicQualifier
Issues an "invalid.polymorphic.qualifier" error for all polymorphic annotations written on the class declaration.- Parameters:
classTree- the class to check
-
warnInvalidPolymorphicQualifier
protected void warnInvalidPolymorphicQualifier(List<? extends TypeParameterTree> typeParameterTrees) Issues an "invalid.polymorphic.qualifier" error for all polymorphic annotations written on the type parameters declaration.- Parameters:
typeParameterTrees- the type parameters to check
-
checkQualifierParameter
Issues an error ifclassTreehas polymorphic fields but is not annotated with@HasQualifierParameter. Always issue a warning if the type of a static field is annotated with a polymorphic qualifier.Issues an error if
classTreeextends or implements a class/interface that has a qualifier parameter, but this class does not.- Parameters:
classTree- the ClassTree to check for polymorphic fields
-
checkExtendsAndImplements
In@A class X extends @B Y implements @C Z {}, enforce that@Amust be a subtype of@Band@C.Also validate the types of the extends and implements clauses.
- Parameters:
classTree- class tree to check
-
checkExtendsOrImplements
protected void checkExtendsOrImplements(Tree boundClause, AnnotationMirrorSet classBounds, TypeMirror classType, boolean isExtends) Helper forcheckExtendsAndImplements(com.sun.source.tree.ClassTree)that checks one extends or implements clause.This method performs two checks for the given extends or implements clause.
First, it invokes
checkAnnotationOnSupertype(com.sun.source.tree.Tree). Its default implementation reports an error for an explicitly written main annotation on the supertype. A checker that permits such annotations, such as theTainting Checker, may override that method to suppress the error.Second, it checks that the type-declaration bounds of the class being declared are subtypes of the bounds specified by this extends or implements clause. For each qualifier hierarchy without an explicitly written annotation,
AnnotatedTypeFactory.getTypeOfExtendsImplements(com.sun.source.tree.Tree)uses the type-declaration bound of the class or interface named by the clause. Those bounds are first viewpoint-adapted to the bounds of the class being declared, so that a supertype declared with a receiver-dependent bound can be extended or implemented. This check is necessary even ifcheckAnnotationOnSupertype(com.sun.source.tree.Tree)rejects explicitly written annotations, and it is performed for every clause because each clause can have different annotations.- Parameters:
boundClause- an extends or implements clauseclassBounds- the type declarations bounds to check for consistency withboundClauseclassType- the type being declaredisExtends- true for an extends clause, false for an implements clause
-
checkExtendsOrImplementsStartDiagnostic
protected final void checkExtendsOrImplementsStartDiagnostic(Tree boundClause, AnnotationMirror classAnno, TypeMirror classType, AnnotationMirror boundAnno, TypeMirror boundTM, boolean isExtends) Prints a diagnostic before checking an extends or implements clause, if the-Ashowcheckscommand-line option is provided.- Parameters:
boundClause- an extends or implements clauseclassAnno- the annotation on the class declarationclassType- the type being declaredboundAnno- the annotation on the extends or implements clauseboundTM- the type of the extends or implements clauseisExtends- true for an extends clause, false for an implements clause
-
checkExtendsOrImplementsEndDiagnostic
protected final void checkExtendsOrImplementsEndDiagnostic(boolean success, Tree boundClause, AnnotationMirror classAnno, TypeMirror classType, AnnotationMirror boundAnno, TypeMirror boundTM, boolean isExtends) Prints a diagnostic after checking an extends or implements clause, if the-Ashowcheckscommand-line option is provided.- Parameters:
success- whether the check succeeded or failedboundClause- an extends or implements clauseclassAnno- the annotation on the class declarationclassType- the type being declaredboundAnno- the annotation on the extends or implements clauseboundTM- the type of the extends or implements clauseisExtends- true for an extends clause, false for an implements clause
-
checkAnnotationOnSupertype
Reports anannotation.on.supertypeerror ifboundClausecarries a type qualifier in this checker's hierarchy, or an alias for one, directly on the supertype. A checker that allows annotations directly on supertypes (e.g.,TaintingVisitor) should override this method to do nothing.This method is called from
checkExtendsOrImplements(Tree, AnnotationMirrorSet, TypeMirror, boolean)for each extends and implements clause in a class declaration.- Parameters:
boundClause- an extends or implements clause- See Also:
-
checkFieldInvariantDeclarations
Check that the field invariant declaration annotations meet the following requirements:- If the superclass of
classTreehas a field invariant, then the field invariant forclassTreemust include all the fields in the superclass invariant and those fields' annotations must be a subtype (or equal) to the annotations for those fields in the superclass. - The fields in the invariant must be a.) final and b.) declared in a
superclass of
classTree. - The qualifier for each field must be a subtype of the annotation on the declaration of that field.
- The field invariant has an equal number of fields and qualifiers, or it has one qualifier and at least one field.
- Parameters:
classTree- class that might have a field invariant- See the Checker Framework Manual:
- Field invariants
- If the superclass of
-
checkDefaultConstructor
Check the default constructor.- Parameters:
tree- a class declaration
-
visitMethod
Checks that the method obeys override and subtype rules to all overridden methods. (Uses the pseudo-assignment logic to do so.)The override rule specifies that a method, m1, may override a method m2 only if:
- m1 return type is a subtype of m2
- m1 receiver type is a supertype of m2
- m1 parameters are supertypes of corresponding m2 parameters
- Specified by:
visitMethodin interfaceTreeVisitor<Void,Void> - Overrides:
visitMethodin classSourceVisitor<Void,Void>
-
processMethodTree
Type-check methodTree. Subclasses should override this method instead ofvisitMethod(MethodTree, Void).- Parameters:
className- the class that contains the method, for diagnostics onlytree- the method to type-check
-
checkPurityAnnotations
Check method purity if needed. Note that overriding rules are checked as part ofcheckOverride(MethodTree, AnnotatedTypeMirror.AnnotatedExecutableType, AnnotatedTypeMirror.AnnotatedDeclaredType, AnnotatedTypeMirror.AnnotatedExecutableType, AnnotatedTypeMirror.AnnotatedDeclaredType).- Parameters:
tree- the method tree to check
-
checkConstructorResult
protected void checkConstructorResult(AnnotatedTypeMirror.AnnotatedExecutableType constructorType, MethodTree constructorTree) Issue a warning if the result type of the constructor declaration is not top. If it is a supertype of the class, then a type.invalid.conflicting.annos error will also be issued byisValidUse(AnnotatedTypeMirror.AnnotatedDeclaredType,AnnotatedTypeMirror.AnnotatedDeclaredType,Tree).- Parameters:
constructorType- the AnnotatedExecutableType for the constructorconstructorTree- the declaration of the constructor
-
reportPurityErrors
protected void reportPurityErrors(PurityChecker.PurityResult result, MethodTree tree, EnumSet<Pure.Kind> expectedKinds) Reports errors found during purity checking.- Parameters:
result- true if the method is deterministic and/or side-effect-freetree- the methodexpectedKinds- the expected purity for the method
-
checkPostcondition
protected void checkPostcondition(MethodTree methodTree, AnnotationMirror annotation, JavaExpression expression) Check that the expression's type is annotated withannotationat the regular exit store.- Parameters:
methodTree- declaration of the methodannotation- expression's type must have this annotationexpression- the expression that must have an annotation
-
contractExpressionAndType
Returns a string representation of an expression and type qualifier.- Parameters:
expression- a Java expressionqualifier- the expression's type, or null if no information is available- Returns:
- a string representation of the expression and type qualifier
-
checkConditionalPostcondition
protected void checkConditionalPostcondition(MethodTree methodTree, AnnotationMirror annotation, JavaExpression expression, boolean result) Check that the expression's type is annotated withannotationat every regular exit that returnsresult.- Parameters:
methodTree- tree of method with the postconditionannotation- expression's type must have this annotationexpression- the expression that the postcondition concernsresult- result for which the postcondition is valid
-
visitTypeParameter
- Specified by:
visitTypeParameterin interfaceTreeVisitor<Void,Void> - Overrides:
visitTypeParameterin classTreeScanner<Void,Void>
-
checkExplicitAnnotationsOnIntersectionBounds
protected void checkExplicitAnnotationsOnIntersectionBounds(AnnotatedTypeMirror.AnnotatedIntersectionType intersection, List<? extends Tree> boundTrees) Issues "explicit.annotation.ignored" warning if any explicit annotation on an intersection bound -- or, if written as an alias, its canonical form -- is not the same as the primary annotation of the given intersection type. A checker that overridesAnnotatedTypeFactory.combineIntersectionBoundAnnotationsInHierarchy(javax.lang.model.element.AnnotationMirror, javax.lang.model.element.AnnotationMirror, org.checkerframework.framework.type.QualifierHierarchy)so that every bound counts can override this method to issue no warning.- Parameters:
intersection- type to useboundTrees- trees ofintersectionbounds
-
visitVariable
- Specified by:
visitVariablein interfaceTreeVisitor<Void,Void> - Overrides:
visitVariablein classSourceVisitor<Void,Void>
-
warnRedundantAnnotations
Issues a "redundant.anno" warning if the annotation written on the type is the same as the default annotation for this type and location.- Parameters:
tree- an AST nodetype- get the explicit annotation on this type and compare it with the default one for this type and location
-
visitAssignment
Performs two checks: subtyping and assignability checks, usingcommonAssignmentCheck(Tree, ExpressionTree, String, Object[]).If the subtype check fails, it issues an "assignment.type.incompatible" error.
- Specified by:
visitAssignmentin interfaceTreeVisitor<Void,Void> - Overrides:
visitAssignmentin classTreeScanner<Void,Void>
-
visitEnhancedForLoop
Performs a subtype check, to test whether the tree expression iterable type is a subtype of the variable type in the enhanced for loop.If the subtype check fails, it issues a "enhancedfor.type.incompatible" error.
An enhanced for loop also calls
iterator()on anIterableor reads the length and the elements of an array, which no tree represents. A type system with a rule for method calls or array accesses, such as a dereference rule, must override this method to apply it totree.getExpression(), asNullnessNoInitVisitorandLockVisitordo.- Specified by:
visitEnhancedForLoopin interfaceTreeVisitor<Void,Void> - Overrides:
visitEnhancedForLoopin classTreeScanner<Void,Void>
-
checkSyntheticMethodInvocations
Checks the method invocations that the CFG synthesized for conversions written in the source, such as thevalueOfcall of a boxing conversion, theintValuecall of an unboxing conversion, and theiteratorcall of an enhanced for loop.These trees are built by
TreeBuilderinside the CFG builder, so they are not part of the AST that this visitor scans andvisitMethodInvocation(com.sun.source.tree.MethodInvocationTree, java.lang.Void)never sees them. Without this, a type system's declaration of the called method is enforced for an explicit call and silently ignored for the conversion that desugars to the same call.- Parameters:
cfg- the CFG whose synthetic method invocations to check
-
checkSyntheticMethodInvocation
Checks that the receiver and the arguments of one synthetic method invocation satisfy the declared type of the method that the conversion calls.The types come from the dataflow store at the invocation rather than from
AnnotatedTypeFactory.getAnnotatedType(Tree). A conversion usually applies to a local or a resource variable, whose declared type is the top qualifier under CLIMB-to-top and whose real type is whatever dataflow refined it to, so the declared type would report an error on almost every conversion.As for an explicit call, nothing is checked if
shouldSkipUses(ExpressionTree)holds for the invocation.- Parameters:
node- the synthetic invocationtree- the tree ofnode
-
visitMethodInvocation
Performs a method invocation check.An invocation of a method, m, on the receiver, r is valid only if:
- passed arguments are subtypes of corresponding m parameters
- r is a subtype of m receiver type
- if m is generic, passed type arguments are subtypes of m type variables
- Specified by:
visitMethodInvocationin interfaceTreeVisitor<Void,Void> - Overrides:
visitMethodInvocationin classTreeScanner<Void,Void>
-
reportTypeArgumentInferenceFailure
protected void reportTypeArgumentInferenceFailure(ExpressionTree tree, AnnotatedTypeMirror.AnnotatedExecutableType methodType, InferenceResult inferenceResult) Reports that type argument inference failed because the annotation constraint system had no satisfying solution -- as opposed toInferenceResult.inferenceBudgetExceeded()orInferenceResult.inferenceCrashed(), which are reported separately bycheckTypeArgumentInference(com.sun.source.tree.ExpressionTree, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType)and never reach this method. This can happen even when javac's own (unannotated) type argument inference succeeds for the same invocation, for example when a type system's qualifier encoding makes some constraint sets unsatisfiable that are not actually errors.Regardless of how this method reports the failure (or whether it reports anything at all), the caller treats type argument inference as failed for
tree: it skips this invocation's structural checks (argument and type-argument-bound compatibility), exactly as it does for the budget-exceeded and crashed cases. This does not change the type computed for the invocation expression itself, whichAnnotatedTypes.findTypeArguments(org.checkerframework.framework.type.AnnotatedTypeFactory, com.sun.source.tree.ExpressionTree, javax.lang.model.element.ExecutableElement, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType, boolean)produces independently of this method, using the same best-effort type arguments thatinferenceResultalready carries.The default implementation reports a hard error. A checker whose qualifier encoding makes this failure mode common and usually spurious (for example, one with a nonstandard qualifier order) may override this method to report a warning instead, via
SourceChecker.reportWarning(java.lang.Object, java.lang.String, java.lang.Object...)with the same"type.arguments.not.inferred"message key, or to suppress the diagnostic entirely.- Parameters:
tree- a tree that requires type argument inferencemethodType- the type of the method before type argument substitutioninferenceResult- the failed result of type argument inference; never null at this call site, becausecheckTypeArgumentInference(com.sun.source.tree.ExpressionTree, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType)already dereferences it (viaInferenceResult.inferenceBudgetExceeded()andInferenceResult.inferenceCrashed()) before reaching this method, so a null value there would already have thrown aNullPointerException
-
checkThisConstructorCall
Checks that the following rule is satisfied: The type on a constructor declaration must be a supertype of the return type of "this()" invocation within that constructor.Subclasses can override this method to change the behavior for just "this" constructor class. Or override
checkThisOrSuperConstructorCall(MethodInvocationTree, String)to change the behavior for "this" and "super" constructor calls.- Parameters:
thisCall- the AST node for the constructor call
-
checkSuperConstructorCall
Checks that the following rule is satisfied: The type on a constructor declaration must be a supertype of the return type of "super()" invocation within that constructor.Subclasses can override this method to change the behavior for just "super" constructor class. Or override
checkThisOrSuperConstructorCall(MethodInvocationTree, String)to change the behavior for "this" and "super" constructor calls.- Parameters:
superCall- the AST node for the super constructor call
-
checkThisOrSuperConstructorCall
protected void checkThisOrSuperConstructorCall(MethodInvocationTree call, @CompilerMessageKey String errorKey) Checks that the following rule is satisfied: The type on a constructor declaration must be a supertype of the return type of "this()" or "super()" invocation within that constructor.- Parameters:
call- the AST node for the constructor callerrorKey- the error message key to use if the check fails
-
checkVarargs
If the given invocation is a varargs invocation, check that the array type of actual varargs is a subtype of the corresponding formal parameter; issues "argument.invalid" error if not.The caller must type-check for each element in varargs before or after calling this method.
- Parameters:
invokedMethod- the method type to be invokedtree- method or constructor invocation tree- See Also:
-
shouldCheckVarargs
Returns true if the varargs array created for the given varargs invocation should be checked against the formal varargs parameter type.The default implementation returns false if zero varargs actual arguments were passed at the call site, because no user arguments were passed to populate the varargs array. Checkers that enforce container array annotations on implicit empty arrays (such as the Value Checker enforcing
@MinLen) may override this method to return true even when zero varargs actual arguments were passed.- Parameters:
tree- the invocation tree- Returns:
- true if the varargs array should be checked
-
checkPreconditions
protected void checkPreconditions(MethodInvocationTree tree, Set<Contract.Precondition> preconditions) Checks that all the givenpreconditionshold true immediately prior to the method invocation or variable access attree.- Parameters:
tree- the method invocation; immediately prior to it, the preconditions must hold truepreconditions- the preconditions to be checked
-
checkContract
protected boolean checkContract(JavaExpression expr, AnnotationMirror necessaryAnnotation, AnnotationMirror inferredAnnotation, CFAbstractStore<?, ?> store) Returns true if and only ifinferredAnnotationis valid for a given expression to match thenecessaryAnnotation.By default,
inferredAnnotationmust be a subtype of (or equal to)necessaryAnnotation, but subclasses might override this behavior.- Parameters:
expr- an expressionnecessaryAnnotation- the annotation that is required for the expressioninferredAnnotation- the annotation that is inferred for the expressionstore- the store- Returns:
- true if
inferredAnnotationis a subtype ofnecessaryAnnotation
-
typeCheckVectorCopyIntoArgument
protected void typeCheckVectorCopyIntoArgument(MethodInvocationTree tree, List<? extends AnnotatedTypeMirror> params) Type checks the method arguments ofVector.copyInto().The Checker Framework special-cases the method invocation, as its type safety cannot be expressed by Java's type system.
For a Vector
vof typeVector<E>, the method invocationv.copyInto(arr)is type-safe iffarris an array of typeT[], whereTis a subtype ofE.In other words, this method checks that the type argument of the receiver method is a subtype of the component type of the passed array argument.
- Parameters:
tree- a method invocation ofVector.copyInto()params- the types of the parameters ofVectory.copyInto()
-
visitNewClass
Performs a new class invocation check.An invocation of a constructor, c, is valid only if:
- passed arguments are subtypes of corresponding c parameters
- if c is generic, passed type arguments are subtypes of c type variables
- Specified by:
visitNewClassin interfaceTreeVisitor<Void,Void> - Overrides:
visitNewClassin classTreeScanner<Void,Void>
-
visitLambdaExpression
- Specified by:
visitLambdaExpressionin interfaceTreeVisitor<Void,Void> - Overrides:
visitLambdaExpressionin classTreeScanner<Void,Void>
-
visitMemberReference
- Specified by:
visitMemberReferencein interfaceTreeVisitor<Void,Void> - Overrides:
visitMemberReferencein classTreeScanner<Void,Void>
-
visitReturn
Checks that the type of the return expression is a subtype of the enclosing method required return type. If not, it issues a "return.type.incompatible" error.- Specified by:
visitReturnin interfaceTreeVisitor<Void,Void> - Overrides:
visitReturnin classTreeScanner<Void,Void>
-
visitAnnotation
Ensure that the annotation arguments comply to their declarations. This needs some special casing, as annotation arguments form special trees.- Specified by:
visitAnnotationin interfaceTreeVisitor<Void,Void> - Overrides:
visitAnnotationin classTreeScanner<Void,Void>
-
visitConditionalExpression
- Specified by:
visitConditionalExpressionin interfaceTreeVisitor<Void,Void> - Overrides:
visitConditionalExpressionin classTreeScanner<Void,Void>
-
visitIf
If "-AignoreDeadCode" was passed on the command line andtree's condition is a compile-time constant, skips checking the branch that can never execute.Only
ifneeds this treatment: awhile/forloop whose condition is a compile-time constantfalseis already a compile-time error (an unreachable statement), so such a loop body cannot appear in valid Java source.- Specified by:
visitIfin interfaceTreeVisitor<Void,Void> - Overrides:
visitIfin classTreeScanner<Void,Void>
-
visitSwitchExpression17
This method validates the type of the switch expression. It issues an error if the type of a value that the switch expression can result is not a subtype of the switch type.If a subclass overrides this method, it must call
super.scan(switchExpressionTree, null)so that the blocks and statements in the cases are checked.- Parameters:
switchExpressionTree- aSwitchExpressionTree
-
visitUnary
Performs assignability check.- Specified by:
visitUnaryin interfaceTreeVisitor<Void,Void> - Overrides:
visitUnaryin classTreeScanner<Void,Void>
-
visitCompoundAssignment
Performs assignability check.- Specified by:
visitCompoundAssignmentin interfaceTreeVisitor<Void,Void> - Overrides:
visitCompoundAssignmentin classTreeScanner<Void,Void>
-
visitNewArray
- Specified by:
visitNewArrayin interfaceTreeVisitor<Void,Void> - Overrides:
visitNewArrayin classTreeScanner<Void,Void>
-
checkTypecastRedundancy
If the lint option "cast:redundant" is set, this method issues a warning if the cast is redundant.- Parameters:
typeCastTree- the TypeCastTree to check
-
checkTypecastSafety
Issues a warning if the given explicitly-written typecast is unsafe. Does nothing if the lint option "-cast:unsafe" is set. Only primary qualifiers are checked unless the command line option "checkCastElementType" is supplied.- Parameters:
typeCastTree- an explicitly-written typecast
-
isTypeCastSafe
Returns true if the cast is safe.Only primary qualifiers are checked unless the command line option "checkCastElementType" is supplied.
- Parameters:
castType- annotated type of the castexprType- annotated type of the casted expression- Returns:
- true if the type cast is safe, false otherwise
-
visitTypeCast
- Specified by:
visitTypeCastin interfaceTreeVisitor<Void,Void> - Overrides:
visitTypeCastin classTreeScanner<Void,Void>
-
visitInstanceOf
- Specified by:
visitInstanceOfin interfaceTreeVisitor<Void,Void> - Overrides:
visitInstanceOfin classTreeScanner<Void,Void>
-
isInstanceOfPatternSafe
protected boolean isInstanceOfPatternSafe(AnnotatedTypeMirror variableType, AnnotatedTypeMirror expType) Returns true if the instanceof binding pattern is safe.- Parameters:
variableType- annotated type of the pattern variableexpType- annotated type of the expression being tested- Returns:
- true if the pattern is safe, false otherwise
-
visitCatch
Checks the type of the exception parameter. Subclasses should overridecheckExceptionParameter(com.sun.source.tree.CatchTree)rather than this method to change the behavior of this check.- Specified by:
visitCatchin interfaceTreeVisitor<Void,Void> - Overrides:
visitCatchin classTreeScanner<Void,Void>
-
visitThrow
Checks the type of a thrown exception. Subclasses should override checkThrownExpression(ThrowTree tree) rather than this method to change the behavior of this check.- Specified by:
visitThrowin interfaceTreeVisitor<Void,Void> - Overrides:
visitThrowin classTreeScanner<Void,Void>
-
visitAnnotatedType
Rather than overriding this method, clients should often overridevisitAnnotatedType(List,Tree). That method also handles the case of annotations at the beginning of a variable or method declaration. javac parses all those annotations as being on the variable or method declaration, even though the ones that are type annotations logically belong to the variable type or method return type.- Specified by:
visitAnnotatedTypein interfaceTreeVisitor<Void,Void> - Overrides:
visitAnnotatedTypein classTreeScanner<Void,Void>
-
visitAnnotatedType
Checks an annotated type. Invoked byvisitAnnotatedType(AnnotatedTypeTree, Void),visitVariable(com.sun.source.tree.VariableTree, java.lang.Void), andvisitMethod(com.sun.source.tree.MethodTree, java.lang.Void). Exists to prevent code duplication among the three. Checking invisitVariableandvisitMethodis needed because there isn't an AnnotatedTypeTree within a variable declaration or for a method return type -- all the annotations are attached to the VariableTree or MethodTree, respectively.- Parameters:
annoTrees- annotations written before a variable/method declaration, if this type is from one; null otherwise. This might contain type annotations that the Java parser attached to the declaration rather than to the type.typeTree- the type that any type annotations in annoTrees apply to
-
warnAboutIrrelevantJavaTypes
public void warnAboutIrrelevantJavaTypes(@Nullable List<? extends AnnotationTree> annoTrees, Tree typeTree) Warns if a type annotation is written on a Java type that is not listed in the @RelevantJavaTypes annotation.- Parameters:
annoTrees- annotations written before a variable/method declaration, if this type is from one; null otherwise. This might contain type annotations that the Java parser attached to the declaration rather than to the type.typeTree- the type that any type annotations in annoTrees apply to
-
shouldWarnAboutIrrelevantJavaTypes
protected boolean shouldWarnAboutIrrelevantJavaTypes()Returns true if the checker should issue warnings about irrelevant java types.- Returns:
- true if the checker should issue warnings about irrelevant java types
-
checkExceptionParameter
Issue error if the exception parameter is not a supertype of the annotation specified bygetExceptionParameterLowerBoundAnnotations(), which is top by default.Subclasses may override this method to change the behavior of this check. Subclasses wishing to enforce that exception parameter be annotated with other annotations can just override
getExceptionParameterLowerBoundAnnotations().- Parameters:
tree- a CatchTree to check
-
getExceptionParameterLowerBoundAnnotations
Returns a set of AnnotationMirrors that is a lower bound for exception parameters. If a user writes a more specific (lower) annotation than this on an exception parameter, the Checker Framework issues a warning indicating that the written annotation cannot be verified.This implementation returns top; subclasses can change this behavior.
- Returns:
- set of annotation mirrors, one per hierarchy, that form a lower bound of annotations that can be written on an exception parameter
-
checkThrownExpression
Checks the type of the thrown expression.By default, this method checks that the thrown expression is a subtype of top.
Issue error if the thrown expression is not a sub type of the annotation given by
getThrowUpperBoundAnnotations(), the same asgetExceptionParameterLowerBoundAnnotations()by default.Subclasses may override this method to change the behavior of this check. Subclasses wishing to enforce that the thrown expression be a subtype of a type besides
getExceptionParameterLowerBoundAnnotations(), should overridegetThrowUpperBoundAnnotations().- Parameters:
tree- a ThrowTree to check
-
getThrowUpperBoundAnnotations
Returns a set of AnnotationMirrors that is an upper bound for thrown exceptions.Note: by default this method returns
getExceptionParameterLowerBoundAnnotations(), so that the same bound is enforced.(Default is top.)
- Returns:
- set of annotation mirrors, one per hierarchy, that form an upper bound of thrown expressions
-
commonAssignmentCheck
protected boolean commonAssignmentCheck(Tree varTree, ExpressionTree valueExpTree, @CompilerMessageKey String errorKey, Object... extraArgs) Checks the validity of an assignment (or pseudo-assignment) from a value to a variable and emits an error message (through the compiler's messaging interface) if it is not valid.- Parameters:
varTree- the AST node for the lvalue (usually a variable)valueExpTree- the AST node for the rvalue (the new value)errorKey- the error message key to use if the check failsextraArgs- arguments to the error message key, before "found" and "expected" types- Returns:
- true if the check succeeds, false if an error message was issued
-
commonAssignmentCheck
protected boolean commonAssignmentCheck(AnnotatedTypeMirror varType, ExpressionTree valueExpTree, @CompilerMessageKey String errorKey, Object... extraArgs) Checks the validity of an assignment (or pseudo-assignment) from a value to a variable and emits an error message (through the compiler's messaging interface) if it is not valid.- Parameters:
varType- the annotated type for the lvalue (usually a variable)valueExpTree- the AST node for the rvalue (the new value)errorKey- the error message key to use if the check failsextraArgs- arguments to the error message key, before "found" and "expected" types- Returns:
- true if the check succeeds, false if an error message was issued
-
commonAssignmentCheck
protected boolean commonAssignmentCheck(AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueExpTree, @CompilerMessageKey String errorKey, Object... extraArgs) Checks the validity of an assignment (or pseudo-assignment) from a value to a variable and emits an error message (through the compiler's messaging interface) if it is not valid.- Parameters:
varType- the annotated type of the variablevalueType- the annotated type of the valuevalueExpTree- the location to use when reporting the error messageerrorKey- the error message key to use if the check failsextraArgs- arguments to the error message key, before "found" and "expected" types- Returns:
- true if the check succeeds, false if an error message was issued
-
reportCommonAssignmentError
protected void reportCommonAssignmentError(AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueTree, @CompilerMessageKey String errorKey, Object... extraArgs) Report a common assignment error. Allows checkers to change how the message is output.- Parameters:
varType- the annotated type of the variablevalueType- the annotated type of the valuevalueTree- the location to use when reporting the error messageerrorKey- the error message key to use if the check failsextraArgs- arguments to the error message key, before "found" and "expected" types
-
commonAssignmentCheckStartDiagnostic
protected final void commonAssignmentCheckStartDiagnostic(AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueExpTree) Prints a diagnostic about enteringcommonAssignmentCheck(), if the showchecks option was set.- Parameters:
varType- the annotated type of the variablevalueType- the annotated type of the valuevalueExpTree- the location to use when reporting the error message
-
commonAssignmentCheckEndDiagnostic
protected final void commonAssignmentCheckEndDiagnostic(boolean success, @Nullable String extraMessage, AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueExpTree) Prints a diagnostic about exitingcommonAssignmentCheck(), if the showchecks option was set.- Parameters:
success- true if the check succeededextraMessage- information about why the result is what it is; may be nullvarType- the annotated type of the variablevalueType- the annotated type of the valuevalueExpTree- the location to use when reporting the error message
-
commonAssignmentCheckEndDiagnostic
protected final void commonAssignmentCheckEndDiagnostic(String message, AnnotatedTypeMirror varType, AnnotatedTypeMirror valueType, Tree valueExpTree) Helper method for printing a diagnostic about exitingcommonAssignmentCheck(), if the showchecks option was set.Most clients should call
commonAssignmentCheckEndDiagnostic(boolean, String, AnnotatedTypeMirror, AnnotatedTypeMirror, Tree). The purpose of this method is to permit customizing the message that is printed.- Parameters:
message- the result, plus information about why the result is what it isvarType- the annotated type of the variablevalueType- the annotated type of the valuevalueExpTree- the location to use when reporting the error message
-
checkArrayInitialization
protected boolean checkArrayInitialization(AnnotatedTypeMirror type, List<? extends ExpressionTree> initializers) Checks that the array initializers are consistent with the array type.- Parameters:
type- the array elemen typeinitializers- the initializers- Returns:
- true if the check succeeds, false if an error message was issued
-
checkTypeArguments
protected void checkTypeArguments(Tree toptree, List<? extends AnnotatedTypeParameterBounds> paramBounds, List<? extends AnnotatedTypeMirror> typeargs, List<? extends Tree> typeargTrees, CharSequence typeOrMethodName, List<?> paramNames) Checks that the annotations on the type arguments supplied to a type or a method invocation are within the bounds of the type variables as declared, and issues the "type.argument.type.incompatible" error if they are not.- Parameters:
toptree- the tree for error reporting, only used for inferred type argumentsparamBounds- the bounds of the type parameters from a class or method declarationtypeargs- the type arguments from the type or method invocationtypeargTrees- the type arguments as trees, used for error reporting
-
shouldCheckTypeArgument
protected boolean shouldCheckTypeArgument(Tree toptree, AnnotatedTypeParameterBounds bounds, AnnotatedTypeMirror typeArg, @Nullable Tree typeArgTree, CharSequence typeOrMethodName, Object paramName) Returns true if the given type argument should be checked against its type parameter's bounds. The default implementation always returns true.A checker may override this method to skip both the upper-bound and the lower-bound check for a given type argument, for example when its bound conformance is guaranteed by construction under the checker's type system (for example, captures of source-written wildcards under nonstandard subtyping). This method does not affect
checkHasQualifierParameterAsTypeArgument(org.checkerframework.framework.type.AnnotatedTypeMirror, org.checkerframework.framework.type.AnnotatedTypeMirror, com.sun.source.tree.Tree), which always runs regardless of the result of this method.- Parameters:
toptree- the tree for error reporting, only used for inferred type argumentsbounds- the bounds of the type parameter corresponding totypeArgtypeArg- the type argument from the type or method invocationtypeArgTree- the type argument as a tree, used for error reporting; null if the type argument was inferred (that is, if the enclosing call's type argument trees were null or empty)typeOrMethodName- the name of the type or method being invokedparamName- the name of the type parameter corresponding totypeArg- Returns:
- true if
typeArgshould be checked againstbounds
-
skipReceiverSubtypeCheck
protected boolean skipReceiverSubtypeCheck(MethodInvocationTree tree, AnnotatedTypeMirror methodDefinitionReceiver, AnnotatedTypeMirror methodCallReceiver) Returns true if to skip subtype checks on the receiver when checking method invocability. A visitor may, for example, allow a method to be invoked even if the receivers are siblings in a hierarchy, provided that some other condition (implemented by the visitor) is satisfied.- Parameters:
tree- the method invocation treemethodDefinitionReceiver- the ATM of the receiver of the method definitionmethodCallReceiver- the ATM of the receiver of the method call- Returns:
- true if to skip subtype checks on the receiver
-
checkMethodInvocability
protected final void checkMethodInvocability(AnnotatedTypeMirror.AnnotatedExecutableType method, MethodInvocationTree tree) Tests whether the method can be invoked using the receiver of the 'tree' method invocation, and issues a "method.invocation.invalid" if the invocation is invalid.This implementation tests whether the receiver in the method invocation is a subtype of the method receiver type. This behavior can be specialized by overriding skipReceiverSubtypeCheck.
- Parameters:
method- the type of the invoked methodtree- the method invocation tree
-
checkMethodInvocability
protected void checkMethodInvocability(AnnotatedTypeMirror.AnnotatedExecutableType method, MethodInvocationTree tree, @Nullable AnnotatedTypeMirror receiverType) LikecheckMethodInvocability(AnnotatedExecutableType, MethodInvocationTree), but usesreceiverTypeas the type of the receiver instead of asking the type factory for the type oftree's receiver. A synthetic invocation, whose receiver is often a local or a resource variable whose declared type is the top qualifier under CLIMB-to-top, passes the type that dataflow refined it to.This is the method to override: it is the one both callers reach, whereas the two-argument version is final and only delegates here. Overriding only the two-argument version would leave a synthetic invocation unaffected by the override.
- Parameters:
method- the type of the invoked methodtree- the method invocation treereceiverType- the type of the receiver, or null to use the type oftree's receiver
-
reportMethodInvocabilityError
protected void reportMethodInvocabilityError(MethodInvocationTree tree, AnnotatedTypeMirror found, AnnotatedTypeMirror expected) Report a method invocability error. Allows checkers to change how the message is output.- Parameters:
tree- the method invocationfound- the receiver typeexpected- the expected receiver type
-
checkConstructorInvocation
protected void checkConstructorInvocation(AnnotatedTypeMirror.AnnotatedDeclaredType invocation, AnnotatedTypeMirror.AnnotatedExecutableType constructor, NewClassTree newClassTree) Check that the (explicit) annotations on a new class tree are comparable to the result type of the constructor. Issue an error if not.Issue a warning if the annotations on the constructor invocation is a subtype of the constructor result type. This is equivalent to down-casting.
For type checking of the enclosing expression of inner type instantiations, see
checkEnclosingExpr(NewClassTree, AnnotatedTypeMirror.AnnotatedExecutableType)- Parameters:
invocation- the AnnotatedDeclaredType of the constructor invocationconstructor- the AnnotatedExecutableType of the constructor declarationnewClassTree- the NewClassTree
-
checkEnclosingExpr
protected void checkEnclosingExpr(NewClassTree node, AnnotatedTypeMirror.AnnotatedExecutableType constructorType) Helper method to type check the enclosing expression of an inner class instantiation.- Parameters:
node- the NewClassTreeconstructorType- the annotatedExecutableType of the constructor declaration
-
checkArguments
protected void checkArguments(List<? extends AnnotatedTypeMirror> requiredTypes, List<? extends ExpressionTree> passedArgs, CharSequence executableName, List<?> paramNames) A helper method to check that each passed argument is a subtype of the corresponding required argument. Issues an "argument.invalid" error for each passed argument that not a subtype of the required one.Note this method requires the lists to have the same length, as it does not handle cases like var args.
- Parameters:
requiredTypes- the required types. This may differ from the formal parameter types, because it replaces a varargs parameter by multiple parameters with the vararg's element type.passedArgs- the expressions passed to the corresponding typesexecutableName- the name of the method or constructor being calledparamNames- the names of the callee's formal parameters- See Also:
-
testTypevarContainment
Returns true if both types are type variables and outer contains inner. Outer contains inner implies: inner.upperBound <: outer.upperBound outer.lowerBound <: inner.lowerBound.- Returns:
- true if both types are type variables and outer contains inner
-
createOverrideChecker
protected BaseTypeVisitor<Factory>.OverrideChecker createOverrideChecker(Tree overriderTree, AnnotatedTypeMirror.AnnotatedExecutableType overriderMethodType, AnnotatedTypeMirror overriderType, AnnotatedTypeMirror overriderReturnType, AnnotatedTypeMirror.AnnotatedExecutableType overriddenMethodType, AnnotatedTypeMirror.AnnotatedDeclaredType overriddenType, AnnotatedTypeMirror overriddenReturnType) Create an OverrideChecker.This exists so that subclasses can subclass OverrideChecker and use their subclass instead of using OverrideChecker itself.
- Parameters:
overriderTree- the AST node of the overriding method or method referenceoverriderMethodType- the type of the overriding methodoverriderType- the type enclosing the overrider method, usually an AnnotatedDeclaredType; for Method References may be something elseoverriderReturnType- the return type of the overriding methodoverriddenMethodType- the type of the overridden methodoverriddenType- the declared type enclosing the overridden methodoverriddenReturnType- the return type of the overridden method- Returns:
- an OverrideChecker
-
checkOverride
protected boolean checkOverride(MethodTree overriderTree, AnnotatedTypeMirror.AnnotatedDeclaredType overriderType, AnnotatedTypeMirror.AnnotatedExecutableType overriddenMethodType, AnnotatedTypeMirror.AnnotatedDeclaredType overriddenType) Type checks that a method may override another method. Uses an OverrideChecker subclass as created bycreateOverrideChecker(com.sun.source.tree.Tree, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType, org.checkerframework.framework.type.AnnotatedTypeMirror, org.checkerframework.framework.type.AnnotatedTypeMirror, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType, org.checkerframework.framework.type.AnnotatedTypeMirror). This version of the method uses the annotated type factory to get the annotated type of the overriding method, and does NOT expose that type.- Parameters:
overriderTree- declaration tree of overriding methodoverriderType- type of overriding classoverriddenMethodType- type of overridden methodoverriddenType- type of overridden class- Returns:
- true if the override is allowed
- See Also:
-
checkOverride
protected boolean checkOverride(MethodTree overriderTree, AnnotatedTypeMirror.AnnotatedExecutableType overriderMethodType, AnnotatedTypeMirror.AnnotatedDeclaredType overriderType, AnnotatedTypeMirror.AnnotatedExecutableType overriddenMethodType, AnnotatedTypeMirror.AnnotatedDeclaredType overriddenType) Type checks that a method may override another method. Uses an OverrideChecker subclass as created bycreateOverrideChecker(com.sun.source.tree.Tree, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType, org.checkerframework.framework.type.AnnotatedTypeMirror, org.checkerframework.framework.type.AnnotatedTypeMirror, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType, org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType, org.checkerframework.framework.type.AnnotatedTypeMirror). This version of the method exposes the AnnotatedExecutableType of the overriding method. Override this version of the method if you need to access that type.- Parameters:
overriderTree- declaration tree of overriding methodoverriderMethodType- type of the overriding methodoverriderType- type of overriding classoverriddenMethodType- type of overridden methodoverriddenType- type of overridden class- Returns:
- true if the override is allowed
- See Also:
-
checkMethodReferenceAsOverride
Check that a method reference is allowed. Uses the OverrideChecker class.- Parameters:
memberReferenceTree- the tree for the method reference- Returns:
- true if the method reference is allowed
-
enclosingMemberSelect
Call this only when the current path is an identifier.- Returns:
- the enclosing member select, or null if the identifier is not the field in a member selection
-
enclosingStatement
Returns the statement that encloses the given one.- Parameters:
tree- an AST node that is on the current path- Returns:
- the statement that encloses the given one
-
visitIdentifier
- Specified by:
visitIdentifierin interfaceTreeVisitor<Void,Void> - Overrides:
visitIdentifierin classTreeScanner<Void,Void>
-
checkAccess
Issues an error if access is not allowed, based on an@Unusedannotation.- Parameters:
identifierTree- the identifier being accessed; the method does nothing if it is not a fieldp- ignored
-
checkAccessAllowed
protected void checkAccessAllowed(Element field, @Nullable AnnotatedTypeMirror receiverType, @FindDistinct ExpressionTree accessTree) Issues an error if access not allowed, based on an @Unused annotation.- Parameters:
field- the field to be accessed, whose declaration might be annotated by @Unused. It can also be (for example)this, in which casereceiverTypeis null.receiverType- the type of the expression whose field is accessed; null if the field is staticaccessTree- the access expression
-
isValidUse
public boolean isValidUse(AnnotatedTypeMirror.AnnotatedDeclaredType declarationType, AnnotatedTypeMirror.AnnotatedDeclaredType useType, Tree tree) Tests that the qualifiers present onuseTypeare valid qualifiers, given the qualifiers on the declaration of the type,declarationType.The check is shallow, as it does not descend into generic or array types (i.e. only performing the validity check on the raw type or outermost array dimension).
validateTypeOf(Tree)would call this for each type argument or array dimension separately.In most cases,
useTypesimply needs to be a subtype ofdeclarationType. If a type system makes exceptions to this rule, its implementation should override this method.This method is not called if
BaseTypeValidator.shouldCheckTopLevelDeclaredOrPrimitiveType(AnnotatedTypeMirror, Tree)returns false -- by default, it is not called on the top level for locals and expressions. To enforce a type validity property everywhere, override methods such asBaseTypeValidator.visitDeclared(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType, com.sun.source.tree.Tree)rather than this method.- Parameters:
declarationType- the type of the class (TypeElement)useType- the use of the class (instance type)tree- the tree where the type is used- Returns:
- true if the useType is a valid use of elemType
-
isValidUse
Tests that the qualifiers present on the primitive type are valid.- Parameters:
type- the use of the primitive typetree- the tree where the type is used- Returns:
- true if the type is a valid use of the primitive type
-
isValidUse
Tests that the qualifiers present on the array type are valid. This method will be invoked for each array level independently, i.e. this method only needs to check the top-level qualifiers of an array.- Parameters:
type- the array type usetree- the tree where the type is used- Returns:
- true if the type is a valid array type
-
validateTypeOf
Returns true if the tree expressed by the passed type tree is a valid type, and emits an error if that is not the case (e.g. '@Mutable String'). If the tree is a method or constructor, check the return type.- Parameters:
tree- the AST type supplied by the user- Returns:
- true if the tree is a valid type
-
validateType
Returns true if the type and corresponding type tree is a valid type, and emits an error if that is not the case (e.g. '@Mutable String'). If the tree is a method or constructor, tests the return type.A type is invalid if it is ill-formed, for example if it has two qualifiers of one hierarchy or a qualifier that the type system forbids at that location. The checks that compare such a type with another, such as the assignment,
return, enhancedfor,new, and cast checks, are skipped: comparing an ill-formed type is not meaningful, and some comparisons assume one qualifier per hierarchy. An override that returns false must therefore have reported an error. A type argument that is outside the bounds of its type parameter is reported, but leaves the type valid: the type is well-formed, so the other checks still apply to it.- Parameters:
tree- the type tree supplied by the usertype- the type corresponding to tree- Returns:
- true if the type is valid
-
createTypeValidator
-
shouldSkipUses
Returns true if the expression should not be checked because of the tree referring to unannotated classes, as specified in thechecker.skipUsesproperty.It returns true if exprTree is a method invocation or a field access to a class whose qualified name matches the
checker.skipUsesproperty.- Parameters:
exprTree- any expression tree- Returns:
- true if checker should not test exprTree
-
visitCompilationUnit
Override Compilation Unit so we won't visit package names or imports.- Specified by:
visitCompilationUnitin interfaceTreeVisitor<Void,Void> - Overrides:
visitCompilationUnitin classTreeScanner<Void,Void>
-