Class SourceChecker
- java.lang.Object
-
- javax.annotation.processing.AbstractProcessor
-
- org.checkerframework.javacutil.AbstractTypeProcessor
-
- org.checkerframework.framework.source.SourceChecker
-
- All Implemented Interfaces:
javax.annotation.processing.Processor
,OptionConfiguration
- Direct Known Subclasses:
AggregateChecker
,AnnotationStatistics
,BaseTypeChecker
,JavaCodeStatistics
@SupportedOptions({"suppressWarnings","skipUses","onlyUses","skipDefs","onlyDefs","assumeSideEffectFree","assumeDeterministic","assumePure","assumeAssertionsAreEnabled","assumeAssertionsAreDisabled","warns","checkPurityAnnotations","invariantArrays","checkCastElementType","checkEnclosingExpr","useConservativeDefaultsForUncheckedCode","concurrentSemantics","conservativeUninferredTypeArguments","warnRedundantAnnotations","ignoreRawTypeArguments","lint","suggestPureMethods","resolveReflection","infer","inferOutputOriginal","showSuppressWarningsStrings","warnUnneededSuppressions","warnUnneededSuppressionsExceptions","requirePrefixInWarningSuppressions","showPrefixInWarningMessages","ignoreInvalidAnnotationLocations","aliasedTypeAnnos","aliasedDeclAnnos","stubs","ajava","stubWarnIfNotFound","stubNoWarnIfNotFound","stubWarnIfNotFoundIgnoresClasses","stubWarnIfOverwritesBytecode","stubWarnIfRedundantWithBytecode","stubWarnNote","mergeStubsWithSource","version","printGitProperties","printAllQualifiers","printVerboseGenerics","noPrintErrorStack","noWarnMemoryConstraints","nomsgtext","noJreVersionCheck","ignoreTargetLocations","detailedmsgtext","ignorejdkastub","permitMissingJdk","nocheckjdk","parseAllJdk","stubDebug","filenames","showchecks","showInferenceSteps","dumpOnErrors","cfgviz","flowdotdir","verbosecfg","atfCacheSize","atfDoNotCache","lspTypeInfo","resourceStats","ajavaChecks"}) public abstract class SourceChecker extends AbstractTypeProcessor implements OptionConfiguration
An abstract annotation processor designed for implementing a source-file checker as an annotation processor (a compiler plug-in). It provides an interface tojavac
's annotation processing API, routines for error reporting via the JSR 199 compiler API, and an implementation for using aSourceVisitor
to perform the type-checking.Most type-checker plug-ins should extend
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) may extendAbstractProcessor
(or even this class).
-
-
Field Summary
Fields Modifier and Type Field Description protected @MonotonicNonNull @InternedDistinct com.sun.source.tree.CompilationUnitTree
currentRoot
The source tree that is being scanned.static java.lang.String
DETAILS_SEPARATOR
Separates parts of a "detailed message", to permit easier parsing.protected javax.lang.model.util.Elements
elements
Element utilities.protected java.util.Set<javax.lang.model.element.Element>
elementsWithSuppressedWarnings
Elements with a@SuppressWarnings
that actually suppressed a warning for this checker.protected int
errsOnLastExit
The number of errors at the last exit of the type processor.protected boolean
javacErrored
If true, javac failed to compile the code or a previously-run annotation processor issued an error.protected javax.annotation.processing.Messager
messager
Used to report error messages and warnings via the compiler.protected java.util.Properties
messagesProperties
Maps error keys to localized/custom error messages.protected static java.lang.String
MSGS_FILE
File name of the localized messages.protected static java.lang.String
OPTION_SEPARATOR
The string that separates the checker name from the option name in a "-A" command-line argument.protected @Nullable SourceChecker
parentChecker
The checker that called this one, whether that be a BaseTypeChecker (used as a compound checker) or an AggregateChecker.static java.lang.String
SUPPRESS_ALL_MESSAGE_KEY
The message key that will suppress all warnings (it matches any message key).static java.lang.String
SUPPRESS_ALL_PREFIX
The SuppressWarnings prefix that will suppress warnings for all checkers.protected TreePathCacher
treePathCacher
TreePathCacher to share between instances.protected com.sun.source.util.Trees
trees
Tree utilities; used as a helper for theSourceVisitor
.protected javax.lang.model.util.Types
types
Type utilities.static @CompilerMessageKey java.lang.String
UNNEEDED_SUPPRESSION_KEY
The message key emitted when an unused warning suppression is found.protected @MonotonicNonNull java.util.List<@FullyQualifiedName java.lang.String>
upstreamCheckerNames
List of upstream checker names.protected boolean
useAllcheckersPrefix
If true, use the "allcheckers:" warning string prefix.protected SourceVisitor<?,?>
visitor
The visitor to use.
-
Constructor Summary
Constructors Modifier Constructor Description protected
SourceChecker()
Default constructor.
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description protected void
addOptions(java.util.Map<java.lang.String,java.lang.String> moreOpts)
Add additional active options.protected abstract SourceVisitor<?,?>
createSourceVisitor()
Provides theSourceVisitor
that the checker should use to scan input source trees.protected java.util.Set<java.lang.String>
createSupportedLintOptions()
Compute the set of supported lint options.protected java.util.Collection<java.lang.String>
expandCFOptions(java.util.List<? extends java.lang.Class<?>> clazzPrefixes, java.lang.String[] options)
Generate the possible command-line option names by prefixing each class name fromclassPrefixes
tooptions
, separated byOPTION_SEPARATOR
.protected java.lang.String
fullMessageOf(java.lang.String messageKey, java.lang.String defaultValue)
Returns the localized long message corresponding to this key.AnnotationProvider
getAnnotationProvider()
Returns the AnnotationProvider (the type factory) associated with this.boolean
getBooleanOption(java.lang.String name)
Determines the boolean value of the option with the given name.boolean
getBooleanOption(java.lang.String name, boolean defaultValue)
Determines the boolean value of the option with the given name.javax.lang.model.util.Elements
getElementUtils()
Returns the element utilities associated with this.boolean
getLintOption(java.lang.String name)
Determines the value of the lint option with the given name.boolean
getLintOption(java.lang.String name, boolean def)
Determines the value of the lint option with the given name.java.util.Properties
getMessagesProperties()
Provides a mapping of error keys to custom error messages.java.lang.String
getOption(java.lang.String name)
Determines the value of the option with the given name.java.lang.String
getOption(java.lang.String name, java.lang.String defaultValue)
Determines the boolean value of the option with the given name.OptionConfiguration
getOptionConfiguration()
Returns the OptionConfiguration associated with this.java.util.Map<java.lang.String,java.lang.String>
getOptions()
Return all active options for this checker.@Nullable SourceChecker
getParentChecker()
Returns the immediate parent checker of the current checker.com.sun.source.util.TreePath
getPathToCompilationUnit()
Return the path to the current compilation unit.javax.annotation.processing.ProcessingEnvironment
getProcessingEnvironment()
Returns theProcessingEnvironment
that was supplied to this checker.protected java.util.Properties
getProperties(java.lang.Class<?> cls, java.lang.String filePath, boolean permitNonExisting)
A helper function to parse a Properties file.protected java.util.NavigableSet<java.lang.String>
getStandardSuppressWarningsPrefixes()
Returns a sorted set of SuppressWarnings prefixes read from theSuppressWarningsPrefix
meta-annotation on the checker class.java.util.List<java.lang.String>
getStringsOption(java.lang.String name, char separator, java.util.List<java.lang.String> defaultValue)
Determines the string list value of the option with the given name.java.util.List<java.lang.String>
getStringsOption(java.lang.String name, java.lang.String separator, java.util.List<java.lang.String> defaultValue)
Determines the string list value of the option with the given name.java.util.Set<java.lang.String>
getSupportedAnnotationTypes()
Overrides the default implementation to always return a singleton set containing only "*".java.util.Set<java.lang.String>
getSupportedLintOptions()
Returns the lint options recognized by this checker.java.util.Set<java.lang.String>
getSupportedOptions()
Map the Checker Framework version ofSupportedOptions
to the standard annotation provided versionSupportedOptions
.javax.lang.model.SourceVersion
getSupportedSourceVersion()
java.util.NavigableSet<java.lang.String>
getSuppressWarningsPrefixes()
Returns a modifiable set of lower-case strings that are prefixes for SuppressWarnings strings.TreePathCacher
getTreePathCacher()
Get the shared TreePathCacher instance.com.sun.source.util.Trees
getTreeUtils()
Returns the tree utilities associated with this.javax.lang.model.util.Types
getTypeUtils()
Returns the type utilities associated with this.java.util.List<@FullyQualifiedName java.lang.String>
getUpstreamCheckerNames()
Returns a list containing this checker name and all checkers it is a part of (that is, checkers that called it).SourceVisitor<?,?>
getVisitor()
Returns the SourceVisitor associated with this.protected java.lang.String
getWarningMessagePrefix()
Returns the prefix that should be added when issuing an error or warning if the-AshowPrefixInWarningMessages
command-line option was passed.boolean
hasOption(java.lang.String name)
Check whether the given option is provided.void
init(javax.annotation.processing.ProcessingEnvironment env)
void
initChecker()
Initialize the checker.void
message(javax.tools.Diagnostic.Kind kind, java.lang.String msg)
Print a non-localized message using the javac messager.void
message(javax.tools.Diagnostic.Kind kind, java.lang.String msg, java.lang.Object... args)
Print a non-localized message using the javac messager.protected boolean
messageKeyMatches(java.lang.String messageKey, java.lang.String messageKeyInSuppressWarningsString)
Does the given messageKey match a messageKey that appears in a SuppressWarnings? Subclasses should override this method if they need additional logic to compare message keys.protected void
printOrStoreMessage(javax.tools.Diagnostic.Kind kind, java.lang.String message, com.sun.source.tree.Tree source, com.sun.source.tree.CompilationUnitTree root)
Do not call this method.protected void
printOrStoreMessage(javax.tools.Diagnostic.Kind kind, java.lang.String message, com.sun.source.tree.Tree source, com.sun.source.tree.CompilationUnitTree root, java.lang.StackTraceElement[] trace)
Do not call this method.protected void
printStats()
Print resource usage statistics.protected java.lang.Object
processErrorMessageArg(java.lang.Object arg)
Process an argument to an error message before it is passed to String.format.void
report(@Nullable java.lang.Object source, DiagMessage d)
Reports a diagnostic message.void
reportError(@Nullable java.lang.Object source, @CompilerMessageKey java.lang.String messageKey, java.lang.Object... args)
Reports an error.void
reportWarning(@Nullable java.lang.Object source, @CompilerMessageKey java.lang.String messageKey, java.lang.Object... args)
Reports a warning.protected void
setLintOption(java.lang.String name, boolean val)
Set the value of the lint option with the given name.protected void
setParentChecker(SourceChecker parentChecker)
Set the parent checker of the current checker.protected void
setProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment env)
Set the processing environment of the current checker.protected void
setRoot(com.sun.source.tree.CompilationUnitTree newRoot)
Invoked when the current compilation unit root changes.protected void
setSupportedLintOptions(java.util.Set<java.lang.String> newLints)
Set the supported lint options.protected boolean
shouldAddShutdownHook()
Return true to indicate that methodshutdownHook()
should be added as a shutdownHook of the JVM.boolean
shouldSkipDefs(com.sun.source.tree.ClassTree tree)
Tests whether the class definition should not be checked because it matches thechecker.skipDefs
property.boolean
shouldSkipDefs(com.sun.source.tree.ClassTree cls, com.sun.source.tree.MethodTree meth)
Tests whether the method definition should not be checked because it matches thechecker.skipDefs
property.boolean
shouldSkipUses(@Nullable javax.lang.model.element.Element element)
Tests whether the class owner of the passed element is an unannotated class and matches the pattern specified in thechecker.skipUses
property.boolean
shouldSkipUses(@FullyQualifiedName java.lang.String typeName)
Tests whether the class owner of the passed type matches the pattern specified in thechecker.skipUses
property.boolean
shouldSuppressWarnings(@Nullable com.sun.source.util.TreePath path, java.lang.String errKey)
Returns true if all the warnings pertaining to a given tree path should be suppressed.boolean
shouldSuppressWarnings(@Nullable javax.lang.model.element.Element elt, java.lang.String errKey)
Returns true if all the warnings pertaining to a given element should be suppressed.boolean
shouldSuppressWarnings(com.sun.source.tree.Tree tree, java.lang.String errKey)
Returns true if 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.void
typeProcess(javax.lang.model.element.TypeElement e, com.sun.source.util.TreePath p)
Type-check the code using this checker's visitor.void
typeProcessingStart()
A method to be called once before the first call to typeProcess.boolean
useConservativeDefault(java.lang.String kindOfCode)
Should conservative defaults be used for the kind of unchecked code indicated by the parameter?protected void
warnUnneededSuppressions()
Issues a warning about any@SuppressWarnings
that didn't suppress a warning, but starts with this checker name or "allcheckers".protected void
warnUnneededSuppressions(java.util.Set<javax.lang.model.element.Element> elementsSuppress, java.util.Set<java.lang.String> prefixes, java.util.Set<java.lang.String> allErrorKeys)
Issues a warning about any@SuppressWarnings
string that didn't suppress a warning, but starts with one of the given prefixes (checker names).-
Methods inherited from class org.checkerframework.javacutil.AbstractTypeProcessor
getCompilerLog, process, typeProcessingOver
-
Methods inherited from class javax.annotation.processing.AbstractProcessor
getCompletions, isInitialized
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface org.checkerframework.framework.util.OptionConfiguration
getStringsOption, getStringsOption
-
-
-
-
Field Detail
-
SUPPRESS_ALL_MESSAGE_KEY
public static final java.lang.String SUPPRESS_ALL_MESSAGE_KEY
The message key that will suppress all warnings (it matches any message key).- See Also:
- Constant Field Values
-
SUPPRESS_ALL_PREFIX
public static final java.lang.String SUPPRESS_ALL_PREFIX
The SuppressWarnings prefix that will suppress warnings for all checkers.- See Also:
- Constant Field Values
-
UNNEEDED_SUPPRESSION_KEY
public static final @CompilerMessageKey java.lang.String UNNEEDED_SUPPRESSION_KEY
The message key emitted when an unused warning suppression is found.- See Also:
- Constant Field Values
-
MSGS_FILE
protected static final java.lang.String MSGS_FILE
File name of the localized messages.- See Also:
- Constant Field Values
-
messagesProperties
protected java.util.Properties messagesProperties
Maps error keys to localized/custom error messages. Do not use directly; callfullMessageOf(java.lang.String, java.lang.String)
orprocessErrorMessageArg(java.lang.Object)
. Is set ininitChecker()
.
-
messager
protected javax.annotation.processing.Messager messager
Used to report error messages and warnings via the compiler. Is set intypeProcessingStart()
.
-
elements
protected javax.lang.model.util.Elements elements
Element utilities.
-
trees
protected com.sun.source.util.Trees trees
Tree utilities; used as a helper for theSourceVisitor
.
-
types
protected javax.lang.model.util.Types types
Type utilities.
-
currentRoot
protected @MonotonicNonNull @InternedDistinct com.sun.source.tree.CompilationUnitTree currentRoot
The source tree that is being scanned. Is set insetRoot(com.sun.source.tree.CompilationUnitTree)
.
-
visitor
protected SourceVisitor<?,?> visitor
The visitor to use.
-
useAllcheckersPrefix
protected boolean useAllcheckersPrefix
If true, use the "allcheckers:" warning string prefix.Checkers that never issue any error messages should set this to false. That prevents
-AwarnUnneededSuppressions
from issuing warnings about@SuppressWarnings("allcheckers:...")
.
-
OPTION_SEPARATOR
protected static final java.lang.String OPTION_SEPARATOR
The string that separates the checker name from the option name in a "-A" command-line argument. This string may only consist of valid Java identifier part characters, because it will be used within the key of an option.- See Also:
- Constant Field Values
-
parentChecker
protected @Nullable SourceChecker parentChecker
The checker that called this one, whether that be a BaseTypeChecker (used as a compound checker) or an AggregateChecker. Null if this is the checker that calls all others. Note that in the case of a compound checker, the compound checker is the parent, not the checker that was run prior to this one by the compound checker.
-
upstreamCheckerNames
protected @MonotonicNonNull java.util.List<@FullyQualifiedName java.lang.String> upstreamCheckerNames
List of upstream checker names. Includes the current checker.
-
treePathCacher
protected TreePathCacher treePathCacher
TreePathCacher to share between instances. Initialized in getTreePathCacher (which is also called fromBaseTypeChecker.instantiateSubcheckers(Map)
).
-
javacErrored
protected boolean javacErrored
If true, javac failed to compile the code or a previously-run annotation processor issued an error.
-
errsOnLastExit
protected int errsOnLastExit
The number of errors at the last exit of the type processor. At entry to the type processor we check whether the current error count is higher and then don't process the file, as it contains some Java errors. Needs to be protected to allow access from AggregateChecker and BaseTypeChecker.
-
DETAILS_SEPARATOR
public static final java.lang.String DETAILS_SEPARATOR
Separates parts of a "detailed message", to permit easier parsing.- See Also:
- Constant Field Values
-
elementsWithSuppressedWarnings
protected final java.util.Set<javax.lang.model.element.Element> elementsWithSuppressedWarnings
Elements with a@SuppressWarnings
that actually suppressed a warning for this checker.
-
-
Method Detail
-
init
public final void init(javax.annotation.processing.ProcessingEnvironment env)
Description copied from class:AbstractTypeProcessor
Register a TaskListener that will get called after FLOW.
- Specified by:
init
in interfacejavax.annotation.processing.Processor
- Overrides:
init
in classAbstractTypeProcessor
-
getProcessingEnvironment
public javax.annotation.processing.ProcessingEnvironment getProcessingEnvironment()
Returns theProcessingEnvironment
that was supplied to this checker.- Returns:
- the
ProcessingEnvironment
that was supplied to this checker
-
setProcessingEnvironment
protected void setProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment env)
Set the processing environment of the current checker.- Parameters:
env
- the new processing environment
-
setParentChecker
protected void setParentChecker(SourceChecker parentChecker)
Set the parent checker of the current checker.
-
getParentChecker
public @Nullable SourceChecker getParentChecker()
Returns the immediate parent checker of the current checker.- Returns:
- the immediate parent checker of the current checker, or null if there is none
-
setRoot
protected void setRoot(com.sun.source.tree.CompilationUnitTree newRoot)
Invoked when the current compilation unit root changes.- Parameters:
newRoot
- the new compilation unit root
-
getUpstreamCheckerNames
public java.util.List<@FullyQualifiedName java.lang.String> getUpstreamCheckerNames()
Returns a list containing this checker name and all checkers it is a part of (that is, checkers that called it).- Returns:
- a list containing this checker name and all checkers it is a part of (that is, checkers that called it)
-
getOptionConfiguration
public OptionConfiguration getOptionConfiguration()
Returns the OptionConfiguration associated with this.- Returns:
- the OptionConfiguration associated with this
-
getElementUtils
public javax.lang.model.util.Elements getElementUtils()
Returns the element utilities associated with this.- Returns:
- the element utilities associated with this
-
getTypeUtils
public javax.lang.model.util.Types getTypeUtils()
Returns the type utilities associated with this.- Returns:
- the type utilities associated with this
-
getTreeUtils
public com.sun.source.util.Trees getTreeUtils()
Returns the tree utilities associated with this.- Returns:
- the tree utilities associated with this
-
getVisitor
public SourceVisitor<?,?> getVisitor()
Returns the SourceVisitor associated with this.- Returns:
- the SourceVisitor associated with this
-
createSourceVisitor
protected abstract SourceVisitor<?,?> createSourceVisitor()
Provides theSourceVisitor
that the checker should use to scan input source trees.- Returns:
- a
SourceVisitor
to use to scan source trees
-
getAnnotationProvider
public AnnotationProvider getAnnotationProvider()
Returns the AnnotationProvider (the type factory) associated with this.- Returns:
- the AnnotationProvider (the type factory) associated with this
-
getMessagesProperties
public java.util.Properties getMessagesProperties()
Provides a mapping of error keys to custom error messages.As a default, this implementation builds a
Properties
out of filemessages.properties
. It accumulates all the properties files in the Java class hierarchy from the checker up toSourceChecker
. This permits subclasses to inherit default messages while being able to override them.- Returns:
- a
Properties
that maps error keys to error message text
-
getTreePathCacher
public TreePathCacher getTreePathCacher()
Get the shared TreePathCacher instance.- Returns:
- the shared TreePathCacher instance.
-
typeProcessingStart
public void typeProcessingStart()
A method to be called once before the first call to typeProcess.Subclasses may override this method to do any initialization work.
Type-checkers are not supposed to override this. Instead override initChecker. This allows us to handle BugInCF only here and doesn't require all overriding implementations to be aware of BugInCF.
- Overrides:
typeProcessingStart
in classAbstractTypeProcessor
- See Also:
AbstractProcessor.init(ProcessingEnvironment)
,initChecker()
-
initChecker
public void initChecker()
Initialize the checker.- See Also:
AbstractProcessor.init(ProcessingEnvironment)
-
typeProcess
public void typeProcess(javax.lang.model.element.TypeElement e, com.sun.source.util.TreePath p)
Type-check the code using this checker's visitor.- Specified by:
typeProcess
in classAbstractTypeProcessor
- Parameters:
e
- element of the analyzed classp
- the tree path to the element, with the leaf being aClassTree
- See Also:
Processor.process(Set, RoundEnvironment)
-
reportError
public void reportError(@Nullable java.lang.Object source, @CompilerMessageKey java.lang.String messageKey, java.lang.Object... args)
Reports an error. By default, prints it to the screen via the compiler's internal messager.- Parameters:
source
- the source position information; may be an Element, a Tree, or nullmessageKey
- the message keyargs
- arguments for interpolation in the string corresponding to the given message key
-
reportWarning
public void reportWarning(@Nullable java.lang.Object source, @CompilerMessageKey java.lang.String messageKey, java.lang.Object... args)
Reports a warning. By default, prints it to the screen via the compiler's internal messager.- Parameters:
source
- the source position information; may be an Element, a Tree, or nullmessageKey
- the message keyargs
- arguments for interpolation in the string corresponding to the given message key
-
report
public void report(@Nullable java.lang.Object source, DiagMessage d)
Reports a diagnostic message. By default, prints it to the screen via the compiler's internal messager.It is rare to use this method. Most clients should use
reportError(java.lang.Object, java.lang.String, java.lang.Object...)
orreportWarning(java.lang.Object, java.lang.String, java.lang.Object...)
.- Parameters:
source
- the source position information; may be an Element, a Tree, or nulld
- the diagnostic message
-
message
@FormatMethod public void message(javax.tools.Diagnostic.Kind kind, java.lang.String msg, java.lang.Object... args)
Print a non-localized message using the javac messager. This is preferable to using System.out or System.err, but should only be used for exceptional cases that don't happen in correct usage. Localized messages should be raised usingreportError(java.lang.Object, java.lang.String, java.lang.Object...)
,reportWarning(java.lang.Object, java.lang.String, java.lang.Object...)
, etc.- Parameters:
kind
- the kind of message to printmsg
- the message textargs
- optional arguments to substitute in the message- See Also:
report(Object, DiagMessage)
-
message
public void message(javax.tools.Diagnostic.Kind kind, java.lang.String msg)
Print a non-localized message using the javac messager. This is preferable to using System.out or System.err, but should only be used for exceptional cases that don't happen in correct usage. Localized messages should be raised usingreportError(java.lang.Object, java.lang.String, java.lang.Object...)
,reportWarning(java.lang.Object, java.lang.String, java.lang.Object...)
, etc.- Parameters:
kind
- the kind of message to printmsg
- the message text- See Also:
report(Object, DiagMessage)
-
printOrStoreMessage
protected void printOrStoreMessage(javax.tools.Diagnostic.Kind kind, java.lang.String message, com.sun.source.tree.Tree source, com.sun.source.tree.CompilationUnitTree root)
Do not call this method. CallreportError(java.lang.Object, java.lang.String, java.lang.Object...)
orreportWarning(java.lang.Object, java.lang.String, java.lang.Object...)
instead.This method exists so that the BaseTypeChecker can override it. For compound checkers, it stores all messages and sorts them by location before outputting them.
- Parameters:
kind
- the kind of message to printmessage
- the message textsource
- the source code position of the diagnostic messageroot
- the compilation unit
-
printOrStoreMessage
protected void printOrStoreMessage(javax.tools.Diagnostic.Kind kind, java.lang.String message, com.sun.source.tree.Tree source, com.sun.source.tree.CompilationUnitTree root, java.lang.StackTraceElement[] trace)
Do not call this method. CallreportError(java.lang.Object, java.lang.String, java.lang.Object...)
orreportWarning(java.lang.Object, java.lang.String, java.lang.Object...)
instead.This method exists so that the BaseTypeChecker can override it. For compound checkers, it stores all messages and sorts them by location before outputting them.
- Parameters:
kind
- the kind of message to printmessage
- the message textsource
- the source code position of the diagnostic messageroot
- the compilation unittrace
- the stack trace where the checker encountered an error. It is printed when the dumpOnErrors option is enabled.
-
fullMessageOf
protected java.lang.String fullMessageOf(java.lang.String messageKey, java.lang.String defaultValue)
Returns the localized long message corresponding to this key. If not found, tries suffixes of this key, stripping off dot-separated prefixes. If still not found, returnsdefaultValue
.- Parameters:
messageKey
- a message keydefaultValue
- a default value to use ifmessageKey
is not a message key- Returns:
- the localized long message corresponding to this key or a suffix, or
defaultValue
-
processErrorMessageArg
protected java.lang.Object processErrorMessageArg(java.lang.Object arg)
Process an argument to an error message before it is passed to String.format.This implementation expands the argument if it is exactly a message key.
By contrast,
fullMessageOf(java.lang.String, java.lang.String)
processes the message key itself but not the arguments, and tries suffixes.- Parameters:
arg
- the argument- Returns:
- the result after processing
-
getLintOption
public final boolean getLintOption(java.lang.String name)
Determines the value of the lint option with the given name. Just as javac uses "-Xlint:xxx" to enable and "-Xlint:-xxx" to disable option xxx, annotation-related lint options are enabled with "-Alint:xxx" and disabled with "-Alint:-xxx".- Parameters:
name
- the name of the lint option to check for- Returns:
- true if the lint option was given, false if it was not given or was given prepended with a "-"
- Throws:
java.lang.IllegalArgumentException
- if the option name is not recognized via theSupportedLintOptions
annotation or thegetSupportedLintOptions()
method- See Also:
getLintOption(String, boolean)
-
getLintOption
public final boolean getLintOption(java.lang.String name, boolean def)
Determines the value of the lint option with the given name. Just as javac uses "-Xlint:xxx" to enable and "-Xlint:-xxx" to disable option xxx, annotation-related lint options are enabled with "-Alint=xxx" and disabled with "-Alint=-xxx".- Parameters:
name
- the name of the lint option to check fordef
- the default option value, returned if the option was not given- Returns:
- true if the lint option was given, false if it was given prepended with a "-", or
def
if it was not given at all - Throws:
java.lang.IllegalArgumentException
- if the option name is not recognized via theSupportedLintOptions
annotation or thegetSupportedLintOptions()
method- See Also:
getLintOption(String)
,getOption(String)
-
setLintOption
protected final void setLintOption(java.lang.String name, boolean val)
Set the value of the lint option with the given name. Just as javac uses "-Xlint:xxx" to enable and "-Xlint:-xxx" to disable option xxx, annotation-related lint options are enabled with "-Alint=xxx" and disabled with "-Alint=-xxx". This method can be used by subclasses to enforce having certain lint options enabled/disabled.- Parameters:
name
- the name of the lint option to setval
- the option value- Throws:
java.lang.IllegalArgumentException
- if the option name is not recognized via theSupportedLintOptions
annotation or thegetSupportedLintOptions()
method- See Also:
getLintOption(String)
,getLintOption(String,boolean)
-
getSupportedLintOptions
public java.util.Set<java.lang.String> getSupportedLintOptions()
Returns the lint options recognized by this checker. Lint options are those which can be checked for viagetLintOption(java.lang.String)
.- Returns:
- an unmodifiable
Set
of the lint options recognized by this checker
-
createSupportedLintOptions
protected java.util.Set<java.lang.String> createSupportedLintOptions()
Compute the set of supported lint options.
-
setSupportedLintOptions
protected void setSupportedLintOptions(java.util.Set<java.lang.String> newLints)
Set the supported lint options. Use of this method should be limited to the AggregateChecker, who needs to set the lint options to the union of all subcheckers. Also, e.g. the NullnessSubchecker need to use this method, as one is created by the other.- Parameters:
newLints
- the new supported lint options, which replace any existing ones
-
addOptions
protected void addOptions(java.util.Map<java.lang.String,java.lang.String> moreOpts)
Add additional active options. Use of this method should be limited to the AggregateChecker, who needs to set the active options to the union of all subcheckers.- Parameters:
moreOpts
- the active options to add
-
getOptions
public java.util.Map<java.lang.String,java.lang.String> getOptions()
Description copied from interface:OptionConfiguration
Return all active options for this checker.- Specified by:
getOptions
in interfaceOptionConfiguration
- Returns:
- all active options for this checker
-
hasOption
public final boolean hasOption(java.lang.String name)
Description copied from interface:OptionConfiguration
Check whether the given option is provided.Note that
OptionConfiguration.getOption(java.lang.String)
can still return null even ifhasOption
returns true: this happens e.g. for-Amyopt
- Specified by:
hasOption
in interfaceOptionConfiguration
- Parameters:
name
- the name of the option to check- Returns:
- true if the option name was provided, false otherwise
-
getOption
public final java.lang.String getOption(java.lang.String name)
Determines the value of the option with the given name.Note that
getOption
can still return null even ifOptionConfiguration.hasOption(java.lang.String)
returns true: this happens e.g. for-Amyopt
- Specified by:
getOption
in interfaceOptionConfiguration
- Parameters:
name
- the name of the option to check- Returns:
- the value of the option with the given name
- See Also:
getLintOption(String,boolean)
-
getOption
public final java.lang.String getOption(java.lang.String name, java.lang.String defaultValue)
Determines the boolean value of the option with the given name. ReturnsdefaultValue
if the option is not set.- Specified by:
getOption
in interfaceOptionConfiguration
- Parameters:
name
- the name of the option to checkdefaultValue
- the default value to return if the option is not set- Returns:
- the value of the option with the given name, or
defaultValue
- See Also:
getLintOption(String,boolean)
-
getBooleanOption
public final boolean getBooleanOption(java.lang.String name)
Determines the boolean value of the option with the given name. Returns false if the option is not set.- Specified by:
getBooleanOption
in interfaceOptionConfiguration
- Parameters:
name
- the name of the option to check- Returns:
- the boolean value of the option
- See Also:
getLintOption(String,boolean)
-
getBooleanOption
public final boolean getBooleanOption(java.lang.String name, boolean defaultValue)
Determines the boolean value of the option with the given name. Returns the given default value if the option is not set.- Specified by:
getBooleanOption
in interfaceOptionConfiguration
- Parameters:
name
- the name of the option to checkdefaultValue
- the default value to use if the option is not set- Returns:
- the boolean value of the option
- See Also:
getLintOption(String,boolean)
-
getStringsOption
public final java.util.List<java.lang.String> getStringsOption(java.lang.String name, char separator, java.util.List<java.lang.String> defaultValue)
Determines the string list value of the option with the given name. The option's value is split on the given separator. Returns the given default value if the option is not set.- Specified by:
getStringsOption
in interfaceOptionConfiguration
- Parameters:
name
- the name of the option to checkseparator
- the separator for list elementsdefaultValue
- the default value to use if the option is not set- Returns:
- the list of options
- See Also:
getLintOption(String,boolean)
-
getStringsOption
public final java.util.List<java.lang.String> getStringsOption(java.lang.String name, java.lang.String separator, java.util.List<java.lang.String> defaultValue)
Determines the string list value of the option with the given name. The option's value is split on the given separator. Returns the given default value if the option is not set.- Specified by:
getStringsOption
in interfaceOptionConfiguration
- Parameters:
name
- the name of the option to checkseparator
- the separator for list elementsdefaultValue
- the default value to use if the option is not set- Returns:
- the list of options
- See Also:
getLintOption(String,boolean)
-
getSupportedOptions
public java.util.Set<java.lang.String> getSupportedOptions()
Map the Checker Framework version ofSupportedOptions
to the standard annotation provided versionSupportedOptions
.- Specified by:
getSupportedOptions
in interfaceOptionConfiguration
- Specified by:
getSupportedOptions
in interfacejavax.annotation.processing.Processor
- Overrides:
getSupportedOptions
in classjavax.annotation.processing.AbstractProcessor
- Returns:
- the supported options
-
expandCFOptions
protected java.util.Collection<java.lang.String> expandCFOptions(java.util.List<? extends java.lang.Class<?>> clazzPrefixes, java.lang.String[] options)
Generate the possible command-line option names by prefixing each class name fromclassPrefixes
tooptions
, separated byOPTION_SEPARATOR
.- Parameters:
clazzPrefixes
- the classes to prefixoptions
- the option names- Returns:
- the possible combinations that should be supported
-
getSupportedAnnotationTypes
public final java.util.Set<java.lang.String> getSupportedAnnotationTypes()
Overrides the default implementation to always return a singleton set containing only "*".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 aSupportedAnnotationTypes
annotation.To specify the annotations that a checker recognizes as type qualifiers, see
AnnotatedTypeFactory.createSupportedTypeQualifiers()
.- Specified by:
getSupportedAnnotationTypes
in interfacejavax.annotation.processing.Processor
- Overrides:
getSupportedAnnotationTypes
in classjavax.annotation.processing.AbstractProcessor
- Throws:
java.lang.Error
- if a subclass is annotated withSupportedAnnotationTypes
-
warnUnneededSuppressions
protected void warnUnneededSuppressions()
Issues a warning about any@SuppressWarnings
that didn't suppress a warning, but starts with this checker name or "allcheckers".
-
warnUnneededSuppressions
protected void warnUnneededSuppressions(java.util.Set<javax.lang.model.element.Element> elementsSuppress, java.util.Set<java.lang.String> prefixes, java.util.Set<java.lang.String> allErrorKeys)
Issues a warning about any@SuppressWarnings
string that didn't suppress a warning, but starts with one of the given prefixes (checker names). Does nothing if the string doesn't start with a checker name.- Parameters:
elementsSuppress
- elements with a@SuppressWarnings
that actually suppressed a warningprefixes
- the SuppressWarnings prefixes that suppress all warnings from this checkerallErrorKeys
- all error keys that can be issued by this checker
-
shouldSuppressWarnings
public boolean shouldSuppressWarnings(com.sun.source.tree.Tree tree, java.lang.String errKey)
Returns true if all the warnings pertaining to a given tree should be suppressed. Returns true if the tree is within the scope of a @SuppressWarnings annotation, one of whose values suppresses the checker's warning. Also, returns true if theerrKey
matches a string in-AsuppressWarnings
.- Parameters:
tree
- the tree that might be a source of a warningerrKey
- the error key the checker is emitting- Returns:
- true if no warning should be emitted for the given tree because it is contained by a declaration with an appropriately-valued @SuppressWarnings annotation; false otherwise
-
shouldSuppressWarnings
public boolean shouldSuppressWarnings(@Nullable com.sun.source.util.TreePath path, java.lang.String errKey)
Returns true if all the warnings pertaining to a given tree path should be suppressed. Returns true if the path is within the scope of a @SuppressWarnings annotation, one of whose values suppresses the checker's warning.- Parameters:
path
- the TreePath that might be a source of, or related to, a warningerrKey
- the error key the checker is emitting- Returns:
- true if no warning should be emitted for the given path because it is contained by a
declaration with an appropriately-valued
@SuppressWarnings
annotation; false otherwise
-
useConservativeDefault
public boolean useConservativeDefault(java.lang.String kindOfCode)
Should conservative defaults be used for the kind of unchecked code indicated by the parameter?- Parameters:
kindOfCode
- source or bytecode- Returns:
- whether conservative defaults should be used
-
shouldSuppressWarnings
public boolean shouldSuppressWarnings(@Nullable javax.lang.model.element.Element elt, java.lang.String errKey)
Returns true if all the warnings pertaining to a given element should be suppressed. Returns true if the element is within the scope of a @SuppressWarnings annotation, one of whose values suppresses all the checker's warnings.- Parameters:
elt
- the Element that might be a source of, or related to, a warningerrKey
- the error key the checker is emitting- Returns:
- true if no warning should be emitted for the given Element because it is contained by
a declaration with an appropriately-valued
@SuppressWarnings
annotation; false otherwise
-
messageKeyMatches
protected boolean messageKeyMatches(java.lang.String messageKey, java.lang.String messageKeyInSuppressWarningsString)
Does the given messageKey match a messageKey that appears in a SuppressWarnings? Subclasses should override this method if they need additional logic to compare message keys.- Parameters:
messageKey
- the message keymessageKeyInSuppressWarningsString
- the message key in a SuppressWarnings- Returns:
- true if the arguments match
-
getSuppressWarningsPrefixes
public java.util.NavigableSet<java.lang.String> getSuppressWarningsPrefixes()
Returns a modifiable set of lower-case strings that are prefixes for SuppressWarnings strings.The collection must not be empty and must not contain only
SUPPRESS_ALL_PREFIX
.- Returns:
- non-empty modifiable set of lower-case prefixes for SuppressWarnings strings
-
getStandardSuppressWarningsPrefixes
protected final java.util.NavigableSet<java.lang.String> getStandardSuppressWarningsPrefixes()
Returns a sorted set of SuppressWarnings prefixes read from theSuppressWarningsPrefix
meta-annotation on the checker class. Or if noSuppressWarningsPrefix
is used, the checker name is used.SUPPRESS_ALL_PREFIX
is also added, at the end, unlessuseAllcheckersPrefix
is false.- Returns:
- a sorted set of SuppressWarnings prefixes
-
getWarningMessagePrefix
protected java.lang.String getWarningMessagePrefix()
Returns the prefix that should be added when issuing an error or warning if the-AshowPrefixInWarningMessages
command-line option was passed.The default implementation uses the default prefix based on the class name if that default prefix is contained in
getSuppressWarningsPrefixes()
. Otherwise, it uses the first element ofgetSuppressWarningsPrefixes()
.- Returns:
- the prefix that should be added when issuing an error or warning if the *
-AshowPrefixInWarningMessages
command-line option was passed
-
shouldSkipUses
public final boolean shouldSkipUses(@Nullable javax.lang.model.element.Element element)
Tests whether the class owner of the passed element is an unannotated class and matches the pattern specified in thechecker.skipUses
property.- Parameters:
element
- an element- Returns:
- true iff the enclosing class of element should be skipped
-
shouldSkipUses
public boolean shouldSkipUses(@FullyQualifiedName java.lang.String typeName)
Tests whether the class owner of the passed type matches the pattern specified in thechecker.skipUses
property. In contrast toshouldSkipUses(Element)
this version can also be used from primitive types, which don't have an element.Checkers that require their annotations not to be checked on certain JDK classes may override this method to skip them. They shall call
super.shouldSkipUses(typeName)
to also skip the classes matching the pattern.- Parameters:
typeName
- the fully-qualified name of a type- Returns:
- true iff the enclosing class of element should be skipped
-
shouldSkipDefs
public boolean shouldSkipDefs(com.sun.source.tree.ClassTree tree)
Tests whether the class definition should not be checked because it matches thechecker.skipDefs
property.- Parameters:
tree
- class to potentially skip- Returns:
- true if checker should not test
tree
-
shouldSkipDefs
public boolean shouldSkipDefs(com.sun.source.tree.ClassTree cls, com.sun.source.tree.MethodTree meth)
Tests whether the method definition should not be checked because it matches thechecker.skipDefs
property.TODO: currently only uses the class definition. Refine pattern. Same for skipUses.
- Parameters:
cls
- class to potentially skipmeth
- method to potentially skip- Returns:
- true if checker should not test
meth
-
shouldAddShutdownHook
protected boolean shouldAddShutdownHook()
Return true to indicate that methodshutdownHook()
should be added as a shutdownHook of the JVM.- Returns:
- true to add
shutdownHook()
as a shutdown hook of the JVM
-
shutdownHook
protected void shutdownHook()
Method that gets called exactly once at shutdown time of the JVM. Checkers can override this method to customize the behavior.If you override this, you must also override
shouldAddShutdownHook()
to return true.
-
printStats
protected void printStats()
Print resource usage statistics.
-
getProperties
protected java.util.Properties getProperties(java.lang.Class<?> cls, java.lang.String filePath, boolean permitNonExisting)
A helper function to parse a Properties file.- Parameters:
cls
- the class whose location is the base of the file pathfilePath
- the name/path of the file to be readpermitNonExisting
- if true, return an empty Properties if the file does not exist or cannot be parsed; if false, issue an error- Returns:
- the properties
-
getSupportedSourceVersion
public final javax.lang.model.SourceVersion getSupportedSourceVersion()
- Specified by:
getSupportedSourceVersion
in interfacejavax.annotation.processing.Processor
- Overrides:
getSupportedSourceVersion
in classjavax.annotation.processing.AbstractProcessor
-
getPathToCompilationUnit
public com.sun.source.util.TreePath getPathToCompilationUnit()
Return the path to the current compilation unit.- Returns:
- path to the current compilation unit
-
-