@SupportedOptions(value={"skipUses","onlyUses","skipDefs","onlyDefs","suppressWarnings","showSuppressWarningKeys","assumeSideEffectFree","ignoreRawTypeArguments","checkPurityAnnotations","invariantArrays","checkCastElementType","warns","lint","suggestPureMethods","assumeAssertionsAreEnabled","assumeAssertionsAreDisabled","concurrentSemantics","useDefaultsForUncheckedCode","resolveReflection","stubs","stubWarnIfNotFound","stubWarnIfOverwritesBytecode","printAllQualifiers","printQualifierParametersAsAnnotations","printVerboseGenerics","detailedmsgtext","printErrorStack","nomsgtext","ignorejdkastub","nocheckjdk","stubDebug","filenames","showchecks","flowdotdir","verbosecfg","resourceStats","atfCacheSize","atfDoNotReadCache","atfDoNotCache"}) public abstract class SourceChecker extends AbstractTypeProcessor implements ErrorHandler, CFContext, OptionConfiguration
javac's annotation processing API, routines for error
reporting via the JSR 199 compiler API, and an implementation for using a
SourceVisitor to perform the type-checking.
Subclasses must implement the following methods: (TODO: update the list)
getMessages() (for type-qualifier specific error messages)
createSourceVisitor() (for a custom SourceVisitor)
getSuppressWarningsKeys() (for honoring
@{link SuppressWarnings} annotations)
BaseTypeChecker,
instead of this class. Only checkers that require annotated types but not
subtype checking (e.g. for testing purposes) should extend this.
Non-type checkers (e.g. for enforcing coding styles) should extend
AbstractProcessor (or even this class) as the Checker Framework is
not designed for such checkers.| Modifier and Type | Class and Description |
|---|---|
static class |
SourceChecker.CheckerError
Exception type used only internally to abort
processing.
|
| Modifier and Type | Field and Description |
|---|---|
protected CompilationUnitTree |
currentRoot
The source tree that is being scanned.
|
static String |
DETAILS_SEPARATOR |
protected int |
errsOnLastExit
The number of errors at the last exit of the type processor.
|
protected Messager |
messager
Used to report error messages and warnings via the compiler.
|
protected Properties |
messages
Maps error keys to localized/custom error messages.
|
protected static String |
MSGS_FILE
File name of the localized messages.
|
protected SourceChecker |
parentChecker
The checker that called this one, whether that be a BaseTypeChecker (used
as a compound checker) or an AggregateChecker.
|
protected static String |
SUPPRESS_ALL_KEY
The @SuppressWarnings key that will suppress warnings for all checkers.
|
protected Trees |
trees
Used as a helper for the
SourceVisitor. |
protected List<String> |
upstreamCheckerNames
List of upstream checker names.
|
protected SourceVisitor<?,?> |
visitor
The visitor to use.
|
processingEnv| Constructor and Description |
|---|
SourceChecker() |
| Modifier and Type | Method and Description |
|---|---|
protected void |
addOptions(Map<String,String> moreopts)
Add additional active options.
|
protected abstract SourceVisitor<?,?> |
createSourceVisitor()
Provides the
SourceVisitor that the checker should use to scan
input source trees. |
protected Set<String> |
createSupportedLintOptions()
Compute the set of supported lint options.
|
void |
errorAbort(String msg)
Log an error message and abort processing.
|
void |
errorAbort(String msg,
Throwable cause)
Log an error message and abort processing.
|
protected Collection<String> |
expandCFOptions(List<? extends Class<?>> clazzPrefixes,
String[] options)
Generate the possible command-line option names by prefixing
each class name from
classPrefixes to options,
separated by OPTION_SEPARATOR. |
protected String |
formatStackTrace(StackTraceElement[] stackTrace)
Format a list of
StackTraceElements to be printed out as an error
message. |
protected String |
fullMessageOf(String messageKey,
String defValue)
Returns the localized long message corresponding for this key, and
returns the defValue if no localized message is found.
|
AnnotationProvider |
getAnnotationProvider() |
SourceChecker |
getChecker() |
CFContext |
getContext() |
Elements |
getElementUtils() |
boolean |
getLintOption(String name)
Determines the value of the lint option with the given name.
|
boolean |
getLintOption(String name,
boolean def)
Determines the value of the lint option with the given name.
|
Properties |
getMessages()
Provides a mapping of error keys to custom error messages.
|
String |
getOption(String name)
Determines the value of the option with the given name.
|
String |
getOption(String name,
String def)
Determines the value of the lint option with the given name and
returns the default value if nothing is specified.
|
OptionConfiguration |
getOptionConfiguration() |
Map<String,String> |
getOptions()
Return all active options for this checker.
|
ProcessingEnvironment |
getProcessingEnvironment() |
protected Properties |
getProperties(Class<?> cls,
String filePath)
A helper function to parse a Properties file
|
protected Collection<String> |
getStandardSuppressWarningsKeys()
Determine the standard set of suppress warning keys usable for any checker.
|
Set<String> |
getSupportedAnnotationTypes()
Overrides the default implementation to always
return a singleton set containing only "*".
|
Set<String> |
getSupportedLintOptions()
Returns the lint options recognized by this checker.
|
Set<String> |
getSupportedOptions()
Map the Checker Framework version of
SupportedOptions to
the standard annotation provided version
SupportedOptions. |
SourceVersion |
getSupportedSourceVersion() |
Collection<String> |
getSuppressWarningsKeys() |
Trees |
getTreeUtils() |
Types |
getTypeUtils() |
List<String> |
getUpstreamCheckerNames() |
SourceVisitor<?,?> |
getVisitor() |
boolean |
hasOption(String name)
Check whether the given option is provided.
|
void |
init(ProcessingEnvironment env)
Register a TaskListener that will get called after FLOW.
|
void |
initChecker()
Initialize the checker.
|
void |
message(Diagnostic.Kind kind,
Object source,
@CompilerMessageKey String msgKey,
Object... args)
Prints a message (error, warning, note, etc.) via JSR-269.
|
void |
message(Diagnostic.Kind kind,
String msg,
Object... args)
Print a non-localized message using the javac messager.
|
protected void |
printStats()
Print resource usage statistics
|
protected Object |
processArg(Object arg)
Process an argument to an error message before it is passed to String.format.
|
void |
report(Result r,
Object src)
Reports a result.
|
protected void |
setLintOption(String name,
boolean val)
Set the value of the lint option with the given name.
|
protected void |
setParentChecker(SourceChecker parentChecker) |
protected void |
setProcessingEnvironment(ProcessingEnvironment env) |
protected void |
setSupportedLintOptions(Set<String> newlints)
Set the supported lint options.
|
protected boolean |
shouldAddShutdownHook()
Return true to indicate that method
shutdownHook() should be
added as a shutdownHook of the JVM. |
boolean |
shouldSkipDefs(ClassTree node)
Tests whether the class definition should not be checked because it
matches the
checker.skipDefs property. |
boolean |
shouldSkipDefs(ClassTree cls,
MethodTree meth)
Tests whether the method definition should not be checked because it
matches the
checker.skipDefs property. |
boolean |
shouldSkipUses(Element element)
Tests whether the class owner of the passed element is an unannotated
class and matches the pattern specified in the
checker.skipUses property. |
boolean |
shouldSkipUses(String typeName)
Tests whether the class owner of the passed type matches
the pattern specified in the
checker.skipUses property. |
boolean |
shouldSuppressWarnings(@Nullable Element elt,
String errKey)
Determines whether all the warnings pertaining to a given tree
should be suppressed.
|
protected void |
shutdownHook()
Method that gets called exactly once at shutdown time of the JVM.
|
String |
treeToFilePositionString(Tree tree,
CompilationUnitTree currentRoot,
ProcessingEnvironment processingEnv)
For the given tree, compute the source positions for that tree.
|
void |
typeProcess(TypeElement e,
TreePath p)
Type-check the code with Java specifications and then runs the Checker
Rule Checking visitor on the processed source.
|
void |
typeProcessingStart()
A method to be called once before the first call to typeProcess.
|
void |
userErrorAbort(String msg)
Log a user error message and abort processing.
|
boolean |
useUncheckedCodeDefault(String kindOfCode)
Should unchecked code defaults be used for the kind of code indicated by the parameter
|
process, typeProcessingOvergetCompletions, isInitializedprotected static final String SUPPRESS_ALL_KEY
protected static final String MSGS_FILE
protected Properties messages
protected Messager messager
protected Trees trees
SourceVisitor.protected CompilationUnitTree currentRoot
protected SourceVisitor<?,?> visitor
protected SourceChecker parentChecker
protected List<String> upstreamCheckerNames
protected int errsOnLastExit
public static final String DETAILS_SEPARATOR
public final void init(ProcessingEnvironment env)
AbstractTypeProcessorinit in interface Processorinit in class AbstractTypeProcessorpublic ProcessingEnvironment getProcessingEnvironment()
getProcessingEnvironment in interface BaseContextProcessingEnvironment that was supplied to this
checkerprotected void setProcessingEnvironment(ProcessingEnvironment env)
protected void setParentChecker(SourceChecker parentChecker)
public SourceChecker getChecker()
getChecker in interface CFContextpublic OptionConfiguration getOptionConfiguration()
getOptionConfiguration in interface BaseContextpublic Elements getElementUtils()
getElementUtils in interface BaseContextpublic Types getTypeUtils()
getTypeUtils in interface BaseContextpublic Trees getTreeUtils()
getTreeUtils in interface BaseContextpublic SourceVisitor<?,?> getVisitor()
getVisitor in interface CFContextprotected abstract SourceVisitor<?,?> createSourceVisitor()
SourceVisitor that the checker should use to scan
input source trees.SourceVisitor to use to scan source treespublic AnnotationProvider getAnnotationProvider()
getAnnotationProvider in interface BaseContextpublic Properties getMessages()
As a default, this implementation builds a Properties out of
file messages.properties. It accumulates all the properties files
in the Java class hierarchy from the checker up to SourceChecker.
This permits subclasses to inherit default messages while being able to
override them.
Properties that maps error keys to error message textpublic void errorAbort(String msg)
errorAbort in interface ErrorHandlermsg - The error message to log.public void errorAbort(String msg, Throwable cause)
errorAbort in interface ErrorHandlermsg - The error message to log.cause - The original error cause.public void userErrorAbort(String msg)
errorAbort(String) this method
presents a more user-friendly output.msg - The error message to log.public void typeProcessingStart()
Subclasses may override this method to do any initialization work. Type-checkers are not supposed to override this. Instead use initChecker. This allows us to handle CheckerError only here and doesn't require all overriding implementations to be aware of CheckerError.
typeProcessingStart in class AbstractTypeProcessorAbstractProcessor.init(ProcessingEnvironment),
initChecker()public void initChecker()
protected boolean shouldAddShutdownHook()
shutdownHook() should be
added as a shutdownHook of the JVM.protected void shutdownHook()
protected void printStats()
public void typeProcess(TypeElement e, TreePath p)
typeProcess in class AbstractTypeProcessore - element of the analyzed classp - the tree path to the element, with the leaf being a
ClassTreeProcessor.process(Set, RoundEnvironment)protected String formatStackTrace(StackTraceElement[] stackTrace)
StackTraceElements to be printed out as an error
message.protected String fullMessageOf(String messageKey, String defValue)
public void message(Diagnostic.Kind kind, Object source, @CompilerMessageKey String msgKey, Object... args)
kind - the type of message to printsource - the object from which to obtain source position informationmsgKey - the message key to printargs - arguments for interpolation in the string corresponding to the
given message keyIllegalArgumentException - if source is neither a Tree nor an
ElementDiagnosticprotected Object processArg(Object arg)
arg - the argumentpublic void message(Diagnostic.Kind kind, String msg, Object... args)
message(Diagnostic.Kind, Object, String, Object...).kind - The kind of message to print.msg - The message text.args - Optional arguments to substitute in the message.message(Diagnostic.Kind, Object, String, Object...)public String treeToFilePositionString(Tree tree, CompilationUnitTree currentRoot, ProcessingEnvironment processingEnv)
tree - Tree to locate within the current compilation unitcurrentRoot - The current compilation unitprocessingEnv - The current processing environmentpublic boolean useUncheckedCodeDefault(String kindOfCode)
kindOfCode - source or bytecodepublic boolean shouldSuppressWarnings(@Nullable Element elt, String errKey)
getSuppressWarningsKeys() method.elt - the Element that might be a source of, or related to, a warningerrKey - the error key the checker is emitting@SuppressWarnings annotation; false otherwisepublic void report(Result r, Object src)
r - the result to reportsrc - the position object associated with the resultpublic final boolean getLintOption(String name)
name - the name of the lint option to check forIllegalArgumentException - if the option name is not recognized
via the SupportedLintOptions annotation or the getSupportedLintOptions() methodgetLintOption(String, boolean)public final boolean getLintOption(String name, boolean def)
name - the name of the lint option to check fordef - the default option value, returned if the option was not givendef if it was not given at allIllegalArgumentException - if the option name is not recognized
via the SupportedLintOptions annotation or the getSupportedLintOptions() methodgetLintOption(String),
getOption(String)protected final void setLintOption(String name, boolean val)
name - the name of the lint option to setval - the option valueIllegalArgumentException - if the option name is not recognized
via the SupportedLintOptions annotation or the getSupportedLintOptions() methodgetLintOption(String),
getLintOption(String,boolean)public Set<String> getSupportedLintOptions()
getLintOption(java.lang.String).Set of the lint options recognized by
this checkerprotected Set<String> createSupportedLintOptions()
protected void setSupportedLintOptions(Set<String> newlints)
protected void addOptions(Map<String,String> moreopts)
public final String getOption(String name)
getOption in interface OptionConfigurationgetLintOption(String,boolean)public Map<String,String> getOptions()
getOptions in interface OptionConfigurationpublic final boolean hasOption(String name)
getOption(String) can still return null even
if hasOption is true: this happens e.g. for -AmyopthasOption in interface OptionConfigurationname - The option name to checkpublic final String getOption(String name, String def)
getOption in interface OptionConfigurationgetOption(String),
getLintOption(String)public Set<String> getSupportedOptions()
SupportedOptions to
the standard annotation provided version
SupportedOptions.getSupportedOptions in interface ProcessorgetSupportedOptions in interface OptionConfigurationgetSupportedOptions in class AbstractProcessorprotected Collection<String> expandCFOptions(List<? extends Class<?>> clazzPrefixes, String[] options)
classPrefixes to options,
separated by OPTION_SEPARATOR.clazzPrefixes - The classes to prefixoptions - The option namespublic final Set<String> getSupportedAnnotationTypes()
javac uses this list to determine which classes process; javac only
runs an annotation processor on classes that contain at least one of
the mentioned annotations.
Thus, the effect of returning "*"
is as if the checker were annotated by
@SupportedAnnotationTypes("*"):
javac runs the checker on every
class mentioned on the javac command line. This method also checks
that subclasses do not contain a SupportedAnnotationTypes
annotation.
To specify the annotations that a checker recognizes as type qualifiers,
see AnnotatedTypeFactory.createSupportedTypeQualifiers().
getSupportedAnnotationTypes in interface ProcessorgetSupportedAnnotationTypes in class AbstractProcessorError - if a subclass is annotated with
SupportedAnnotationTypespublic Collection<String> getSuppressWarningsKeys()
SuppressWarningsKeysprotected final Collection<String> getStandardSuppressWarningsKeys()
getSuppressWarningsKeys()public final boolean shouldSkipUses(Element element)
checker.skipUses property.element - an elementpublic final boolean shouldSkipUses(String typeName)
checker.skipUses property.
In contrast to shouldSkipUses(Element) this version
can also be used from primitive types, which don't have an element.typeName - the fully-qualified name of a typepublic final boolean shouldSkipDefs(ClassTree node)
checker.skipDefs property.node - class to potentially skippublic final boolean shouldSkipDefs(ClassTree cls, MethodTree meth)
checker.skipDefs property.
TODO: currently only uses the class definition. Refine pattern. Same for skipUses.cls - class to potentially skipmeth - method to potentially skipprotected Properties getProperties(Class<?> cls, String filePath)
cls - the class whose location is the base of the file pathfilePath - the name/path of the file to be readpublic final SourceVersion getSupportedSourceVersion()
getSupportedSourceVersion in interface ProcessorgetSupportedSourceVersion in class AbstractProcessor