Class OptionalImplVisitor
- All Implemented Interfaces:
TreeVisitor<Void,Void>
- See the Checker Framework Manual:
- Optional Checker
-
Nested Class Summary
Nested classes/interfaces inherited from class org.checkerframework.common.basetype.BaseTypeVisitor
BaseTypeVisitor.FoundRequired, BaseTypeVisitor.OverrideChecker -
Field Summary
Fields inherited from class org.checkerframework.common.basetype.BaseTypeVisitor
assumePureGetters, atypeFactory, checker, DETERMINISTIC, ignoreTargetLocations, IMPURE, methodTree, positions, PURE, qualAllowedLocations, qualHierarchy, showchecks, SIDE_EFFECT_FREE, TARGET, targetValueElement, typeHierarchy, typeValidator, unusedWhenElement, warnRedundantAnnotationsFields inherited from class org.checkerframework.framework.source.SourceVisitor
elements, root, trees, treesWithSuppressWarnings, types -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected 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 BaseTypeValidatorReturns the set of methods that should be verified using theNonEmptyChecker.voidPart of rule #3.voidRule #4.voidPartial support for Rule #5 and Rule #7.voidPart of rule #3.voidprocessMethodTree(String className, MethodTree methodDecl) Type-check methodTree.static StatementTreeskipBlocks(StatementTree tree) If the given tree is a block tree with a single element, return the enclosed non-block statement.visitBinary(BinaryTree tree, Void p) visitMemberReference(MemberReferenceTree tree, Void p) Performs a method invocation check.visitVariable(VariableTree tree, Void p) Rule #6 (partial).Methods inherited from class org.checkerframework.common.basetype.BaseTypeVisitor
checkAccess, checkAccessAllowed, checkArguments, checkArrayInitialization, checkConditionalPostcondition, checkConstructorInvocation, checkConstructorResult, checkContract, checkDefaultConstructor, checkEnclosingExpr, checkExceptionParameter, checkExplicitAnnotationsOnIntersectionBounds, checkExtendsAndImplements, checkExtendsOrImplements, checkFieldInvariantDeclarations, checkMethodInvocability, checkMethodReferenceAsOverride, checkOverride, checkOverride, checkPostcondition, checkPreconditions, checkPurityAnnotations, checkQualifierParameter, checkSuperConstructorCall, checkThisConstructorCall, checkThisOrSuperConstructorCall, checkThrownExpression, checkTypeArguments, checkTypecastRedundancy, checkTypecastSafety, checkVarargs, commonAssignmentCheck, commonAssignmentCheck, commonAssignmentCheckEndDiagnostic, commonAssignmentCheckEndDiagnostic, commonAssignmentCheckStartDiagnostic, contractExpressionAndType, createOverrideChecker, createQualAllowedLocations, createTypeFactory, createTypeFactoryPublic, enclosingMemberSelect, enclosingStatement, getExceptionParameterLowerBoundAnnotations, getThrowUpperBoundAnnotations, getTypeFactory, isTypeCastSafe, isValidUse, isValidUse, isValidUse, processClassTree, reportCommonAssignmentError, reportMethodInvocabilityError, reportPurityErrors, scan, setRoot, shouldSkipUses, shouldWarnAboutIrrelevantJavaTypes, skipReceiverSubtypeCheck, testAnnotationInsertion, testJointJavacJavaParserVisitor, testTypevarContainment, typeCheckVectorCopyIntoArgument, validateTargetLocation, validateType, validateTypeOf, validateVariablesTargetLocation, visitAnnotatedType, visitAnnotatedType, visitAnnotation, visitAssignment, visitCatch, visitClass, visitCompilationUnit, visitCompoundAssignment, visitEnhancedForLoop, visitIdentifier, visitInstanceOf, visitLambdaExpression, visitMethod, visitNewArray, visitNewClass, visitReturn, visitSwitchExpression17, visitThrow, visitTypeCast, visitTypeParameter, visitUnary, warnAboutIrrelevantJavaTypes, warnInvalidPolymorphicQualifier, warnInvalidPolymorphicQualifier, warnRedundantAnnotationsMethods 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, visitBindingPattern, visitBlock, visitBreak, visitCase, visitConstantCaseLabel, visitContinue, visitDeconstructionPattern, visitDefaultCaseLabel, visitDoWhileLoop, visitEmptyStatement, visitErroneous, visitExports, visitExpressionStatement, visitForLoop, visitImport, visitIntersectionType, visitLabeledStatement, visitLiteral, visitMemberSelect, visitModifiers, visitModule, visitOpens, visitOther, visitPackage, visitParameterizedType, visitParenthesized, visitPatternCaseLabel, visitPrimitiveType, visitProvides, visitRequires, visitStringTemplate, visitSwitch, visitSwitchExpression, visitSynchronized, visitTry, visitUnionType, visitUses, visitWhileLoop, visitWildcard, visitYield
-
Constructor Details
-
OptionalImplVisitor
Create an OptionalImplVisitor.- Parameters:
checker- the associated instance ofOptionalImplChecker
-
-
Method Details
-
createTypeValidator
- Overrides:
createTypeValidatorin classBaseTypeVisitor<BaseAnnotatedTypeFactory>
-
getNamesOfMethodsToVerifyWithNonEmptyChecker
Returns the set of methods that should be verified using theNonEmptyChecker.This should only be called by the Non-Empty Checker.
- Returns:
- the set of methods that should be verified using the
NonEmptyChecker
-
visitConditionalExpression
- Specified by:
visitConditionalExpressionin interfaceTreeVisitor<Void,Void> - Overrides:
visitConditionalExpressionin classBaseTypeVisitor<BaseAnnotatedTypeFactory>
-
handleTernaryIsPresentGet
Part of rule #3.Pattern match for:
VAR.isPresent() ? VAR.get().METHOD() : VALUEPrefer:
VAR.map(METHOD).orElse(VALUE);- Parameters:
tree- a conditional expression that can perhaps be simplified
-
visitIf
- Specified by:
visitIfin interfaceTreeVisitor<Void,Void> - Overrides:
visitIfin classTreeScanner<Void,Void>
-
handleConditionalStatementIsPresentGet
Part of rule #3.Pattern match for:
if (VAR.isPresent()) { METHOD(VAR.get()); }Prefer:
VAR.ifPresent(METHOD);Also matches:
if (VAR.isPresent()) { x = METHOD(VAR.get()); } else { x = OTHER; }Wherexis some variable (e.g., a field, a local variable).Prefer:
x = VAR.map(METHOD).orElse(OTHER);- Parameters:
tree- an if statement that can perhaps be simplified
-
visitMethodInvocation
Description copied from class:BaseTypeVisitorPerforms 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 classBaseTypeVisitor<BaseAnnotatedTypeFactory>
-
processMethodTree
Description copied from class:BaseTypeVisitorType-check methodTree. Subclasses should override this method instead ofBaseTypeVisitor.visitMethod(MethodTree, Void).- Overrides:
processMethodTreein classBaseTypeVisitor<BaseAnnotatedTypeFactory>- Parameters:
className- the class that contains the method, for diagnostics onlymethodDecl- the method to type-check
-
visitBinary
- Specified by:
visitBinaryin interfaceTreeVisitor<Void,Void> - Overrides:
visitBinaryin classTreeScanner<Void,Void>
-
commonAssignmentCheck
protected boolean commonAssignmentCheck(AnnotatedTypeMirror varType, ExpressionTree valueExpTree, @CompilerMessageKey String errorKey, Object... extraArgs) Description copied from class:BaseTypeVisitorChecks 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.- Overrides:
commonAssignmentCheckin classBaseTypeVisitor<BaseAnnotatedTypeFactory>- 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
-
handleCreationElimination
Rule #4.Pattern match for:
CREATION().PROPAGATION()*.ELIMINATION()CREATION()wraps a value in an instance ofOptional, andPROPAGATION()is a method (or a sequence of methods) that operate on and returnOptional.ELIMINATION()is the terminal operation that unwraps theOptionalvalue (i.e.,Optional.get()).This creation-propagation-elimination pattern can be eliminated by directly checking whether a value is null before invoking methods on it.
- Parameters:
tree- a method invocation that can perhaps be simplified
-
handleNestedOptionalCreation
Partial support for Rule #5 and Rule #7.Rule #5: Avoid nested Optional chains, or operations that have an intermediate Optional value.
Rule #7: Don't use Optional to wrap any collection type.
Certain types are illegal, such as
Optional<Optional>. The type validator may see a supertype of the most precise run-time type; for example, it may see the type asOptional<? extends Object>, and it would not flag any problem with such a type. This method checks atOptionalcreation sites.TODO: This finds only some
Optional<Optional>: those that consist ofOptional.of(optionalExpr)orOptional.ofNullable(optionalExpr), whereoptionalExprhas typeOptional. There are other ways thatOptional<Optional>can be created, such asoptionalExpr.map(Optional::of).TODO: Also check at collection creation sites, but there are so many of them, and there often are not values of the element type at the collection creation site.
- Parameters:
tree- a method invocation that might createOptional<X>where X is impermissable: Optional or Collection
-
visitVariable
Rule #6 (partial).Don't use Optional in fields and method parameters.
- Specified by:
visitVariablein interfaceTreeVisitor<Void,Void> - Overrides:
visitVariablein classBaseTypeVisitor<BaseAnnotatedTypeFactory>
-
skipBlocks
If the given tree is a block tree with a single element, return the enclosed non-block statement. Otherwise, return the same tree.- Parameters:
tree- a statement tree- Returns:
- the single enclosed statement, if it exists; otherwise, the same tree
-
visitMemberReference
- Specified by:
visitMemberReferencein interfaceTreeVisitor<Void,Void> - Overrides:
visitMemberReferencein classBaseTypeVisitor<BaseAnnotatedTypeFactory>
-