Class SourceChecker

All Implemented Interfaces:
Processor, OptionConfiguration
Direct Known Subclasses:
AggregateChecker, AnnotationStatistics, BaseTypeChecker, JavaCodeStatistics, RelevantJavaTypesTest.BaseRelevantChecker, RelevantJavaTypesTest.PlainUnannotatedChecker, StubFilesTest.BaseStubChecker, StubFilesTest.ChildStubChecker, StubFilesTest.ExtraStubChecker, StubFilesTest.GrandparentStubChecker, StubFilesTest.ParentStubChecker, SuppressWarningsPrefixTest.BasePrefixChecker, SuppressWarningsPrefixTest.EnclosedChildChecker, SuppressWarningsPrefixTest.EnclosingParentChecker, SuppressWarningsPrefixTest.GrandparentPrefixChecker, SuppressWarningsPrefixTest.PlainUnannotatedChecker

@SupportedOptions({"suppressWarnings","skipUses","onlyUses","skipDefs","onlyDefs","skipFiles","onlyFiles","onlyAnnotatedFor","assumeSideEffectFree","assumeDeterministic","assumePure","assumePureGetters","assumeAssertions","assumeAssertionsAreEnabled","assumeAssertionsAreDisabled","ignoreRawTypeArguments","ignoreTargetLocations","ignoreDeadCode","warns","checkPurityAnnotations","invariantArrays","checkCastElementType","warnBytecodeConflicts","checkEnclosingExpr","useConservativeDefaultsForUncheckedCode","usePermissiveDefaultsForUncheckedCode","concurrentSemantics","warnRedundantAnnotations","mode","lint","suggestPureMethods","resolveReflection","infer","inferOutputDirectory","inferOutputOriginal","showSuppressWarningsStrings","warnUnneededSuppressions","warnUnneededSuppressionsExceptions","requirePrefixInWarningSuppressions","showPrefixInWarningMessages","ignoreInvalidAnnotationLocations","aliasedTypeAnnos","aliasedDeclAnnos","stubs","ajava","stubWarnIfNotFound","stubNoWarnIfNotFound","stubWarnIfNotFoundIgnoresClasses","stubWarnIfOverwritesBytecode","stubWarnIfRedundantWithBytecode","stubWarnNote","mergeStubsWithSource","storeInBytecode","slowTypecheckingSeconds","version","printGitProperties","printAllQualifiers","printVerboseGenerics","noPrintErrorStack","noWarnMemoryConstraints","nomsgtext","onelinemsg","noJreVersionCheck","exceptionLineSeparator","detailedmsgtext","ignorejdkastub","permitMissingJdk","parseAllJdk","stubDebug","binaryStubDiffCheck","filenames","showchecks","dumpOnErrors","cfgviz","flowdotdir","verbosecfg","atfCacheSize","atfDoNotCache","lspTypeInfo","resourceStats","ajavaChecks","convertTypeArgInferenceCrashToWarning","inferenceWorkBudget"}) 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 to 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.

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 extend AbstractProcessor (or even this class).

  • Field Details

    • SUPPRESS_ALL_MESSAGE_KEY

      public static final String SUPPRESS_ALL_MESSAGE_KEY
      The message key that will suppress all warnings (it matches any message key).
      See Also:
    • SUPPRESS_ALL_PREFIX

      public static final String SUPPRESS_ALL_PREFIX
      The SuppressWarnings prefix that will suppress warnings for all checkers.
      See Also:
    • UNNEEDED_SUPPRESSION_KEY

      public static final @CompilerMessageKey String UNNEEDED_SUPPRESSION_KEY
      The message key emitted when an unused warning suppression is found.
      See Also:
    • MSGS_FILE

      protected static final String MSGS_FILE
      File name of the localized messages.
      See Also:
    • messager

      protected Messager messager
      Used to report error messages and warnings via the compiler. Is set in typeProcessingStart().
    • elements

      protected Elements elements
      Element utilities.
    • trees

      protected Trees trees
      Tree utilities; used as a helper for the SourceVisitor.
    • types

      protected Types types
      Type utilities.
    • currentRoot

      The source tree that is being scanned. Is set in setRoot(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 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:
    • 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 List<@FullyQualifiedName String> upstreamCheckerNames
      List of upstream checker names. Includes the current checker.
    • DETAILS_SEPARATOR

      public static final String DETAILS_SEPARATOR
      Separates parts of a "detailed message", to permit easier parsing.
      See Also:
  • Constructor Details

    • SourceChecker

      protected SourceChecker()
      Creates a source checker.
  • Method Details

    • setDiagnosticSink

      public final void setDiagnosticSink(@Nullable DiagnosticSink sink)
      Installs a DiagnosticSink to receive this checker's findings, instead of printing them through javac's Trees. Pass null to restore the default (print to javac).

      Intended for hosts that embed the Checker Framework (such as the Error Prone plugin) and want to translate findings into their own diagnostic representation. When several checkers run together under one parent (e.g. an AggregateChecker or subcheckers), all findings are flushed through the parent checker, so installing the sink on the checker that the host drives is sufficient.

      The sink receives only tree-positioned findings; findings positioned at an Element or with no source position still go through javac's Messager (see DiagnosticSink).

      Parameters:
      sink - the diagnostic sink, or null to print to javac
    • setHostOptions

      public final void setHostOptions(Map<String,String> options)
      Supplies the options of a host that embeds the Checker Framework, which this checker and its subcheckers then read in place of the -A options of the compilation. Each entry is an option as it would be written after -A (so stubs or NullnessChecker_stubs) mapped to its value, or to null for an option without a value; the host's options are read exactly as the -A options are. Must be called before init(ProcessingEnvironment), which reads the options.
      Parameters:
      options - the host's options, as unprefixed -A option names mapped to values
    • init

      public final void init(ProcessingEnvironment env)
      Description copied from class: AbstractTypeProcessor

      In the default (self-driven) mode, registers a TaskListener that will get called after FLOW. In externally-driven mode (see AbstractTypeProcessor.externallyDriven), no TaskListener is registered; the host drives the type-processing lifecycle instead.

      The shouldStopPolicy is bumped to at least FLOW in both modes. The bump is idempotent, so it is harmless if a host has already requested the same or a later stop policy.

      Specified by:
      init in interface Processor
      Overrides:
      init in class AbstractTypeProcessor
    • getProcessingEnvironment

      public ProcessingEnvironment getProcessingEnvironment()
      Returns the ProcessingEnvironment that was supplied to this checker.
      Returns:
      the ProcessingEnvironment that was supplied to this checker
    • setParentChecker

      protected void setParentChecker(SourceChecker parentChecker)
      Set the parent checker of the current checker.
      Parameters:
      parentChecker - the parent 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(CompilationUnitTree newRoot)
      Invoked when the current compilation unit root changes.
      Parameters:
      newRoot - the new compilation unit root
    • getUpstreamCheckerNames

      public List<@FullyQualifiedName String> getUpstreamCheckerNames()
      Returns a list containing this checker name and all checkers it is a part of (that is, checkers that called it).

      This list has two uses:

      • It determines which @AnnotatedFor annotations are recognized as covering this checker.
      • By default, getSuppressWarningsPrefixes() includes lower-case prefixes derived from all checker names returned by this method. For example, if an override adds the name of an abstract parent class that this checker extends, the parent class's lower-case checker name is also accepted as a @SuppressWarnings prefix.
      Returns:
      a list containing this checker name and all checkers it is a part of (that is, checkers that called it)
      See Also:
    • getOptionConfiguration

      public OptionConfiguration getOptionConfiguration()
      Returns the OptionConfiguration associated with this.
      Returns:
      the OptionConfiguration associated with this
    • getElementUtils

      public Elements getElementUtils()
      Returns the element utilities associated with this.
      Returns:
      the element utilities associated with this
    • getTypeUtils

      public Types getTypeUtils()
      Returns the type utilities associated with this.
      Returns:
      the type utilities associated with this
    • getTreeUtils

      public 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
    • getOptionsNoSubcheckers

      public Map<String,String> getOptionsNoSubcheckers()
      Like getOptions(), but only includes options passed to this checker. Does not include those passed only to subcheckers.
      Returns:
      the active options for this checker, not including those passed only to subcheckers
    • hasOptionNoSubcheckers

      public final boolean hasOptionNoSubcheckers(String name)
      Like hasOption(java.lang.String), but checks whether the given option is passed to this checker. Does not consider options only passed to subcheckers.
      Parameters:
      name - the name of the option to check
      Returns:
      true if the option name was passed to this checker, false otherwise
    • getExtraStubFiles

      public List<String> getExtraStubFiles()
      Returns a list of stub files to be treated as if they had been written in a @StubFiles annotation.
      Returns:
      stub files to be treated as if they had been written in a @StubFiles annotation
    • getStubFiles

      public final List<String> getStubFiles()
      Returns the list of stub files to be parsed for this checker, including those declared via StubFiles, getExtraStubFiles(), and those from parent checkers and subcheckers.
      Returns:
      the list of stub files for this checker
    • createSourceVisitor

      protected abstract SourceVisitor<?,?> createSourceVisitor()
      Provides the SourceVisitor 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
    • createMessagesProperties

      protected Properties createMessagesProperties()
      Creates the mapping of error keys to custom error messages.

      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.

      initChecker() calls this method once and uses the result for every diagnostic.

      Returns:
      a Properties that maps error keys to error message text
    • 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 class AbstractTypeProcessor
      See Also:
    • typeProcessingOver

      public void typeProcessingOver()
      Description copied from class: AbstractTypeProcessor
      A method to be called once all the classes are processed.

      Subclasses may override this method to do any aggregate analysis (e.g. generate report, persistence) or resource deallocation.

      Method AbstractTypeProcessor.getCompilerLog() can be used to access the number of compiler errors.

      Overrides:
      typeProcessingOver in class AbstractTypeProcessor
    • initChecker

      public void initChecker()
      Initialize the checker.
      See Also:
    • getSubchecker

      public <T extends SourceChecker> @Nullable T getSubchecker(Class<T> checkerClass)
      Returns the requested (immediate) subchecker. A checker of a given class can only be run once, so this returns the only such checker, or null if none was found. The caller must know the exact checker class to request.
      Type Parameters:
      T - the class of the subchecker to return
      Parameters:
      checkerClass - the class of the subchecker to return
      Returns:
      the requested (immediate) subchecker or null if not found
    • instantiateSubcheckers

      protected List<SourceChecker> instantiateSubcheckers(Map<Class<? extends SourceChecker>,SourceChecker> alreadyInitializedSubcheckerMap)
      Computes the unmodifiable list of immediate subcheckers of this checker, in the order the checkers need to be run.

      Modifies the alreadyInitializedSubcheckerMap parameter by adding all recursively newly instantiated subcheckers' class objects and instances. It is necessary to use a map that preserves the order in which entries were inserted, such as LinkedHashMap or ArrayMap.

      Parameters:
      alreadyInitializedSubcheckerMap - subcheckers that have already been instantiated. Is modified by this method. Its point is to ensure that if two checkers A and B both depend on checker C, then checker C is instantiated and run only once, not twice.
      Returns:
      the unmodifiable list of immediate subcheckers of this checker
    • getSubcheckers

      public List<SourceChecker> getSubcheckers()
      Returns the list of all subcheckers (if any). This list is only non-empty for the one checker that runs all other subcheckers. These are recursively instantiated via instantiateSubcheckers() the first time this method is called if field subcheckers is null. Assumes all checkers run on the same thread.
      Returns:
      the list of all subcheckers (if any)
    • getTreePathCacher

      public TreePathCacher getTreePathCacher()
      Returns the shared TreePathCacher instance.
      Returns:
      the shared TreePathCacher instance
    • typeProcess

      public void typeProcess(TypeElement e, TreePath p)
      Type-check the code using this checker's visitor.
      Specified by:
      typeProcess in class AbstractTypeProcessor
      Parameters:
      e - element of the analyzed class
      p - the tree path to the element, with the leaf being a ClassTree
      See Also:
    • packageProcess

      public void packageProcess(PackageElement e, TreePath p)
      Type-checks a package declaration: the package clause of a package-info.java.

      The counterpart of typeProcess(javax.lang.model.element.TypeElement, com.sun.source.util.TreePath) for a compilation unit that declares no type, and which AbstractTypeProcessor therefore never dispatches to typeProcess. It mirrors that method: subcheckers run first and in order, the message store and error bookkeeping behave the same, and the visitor is driven the same way. A package declaration contains no code, so the visitor reaches only the declaration annotations written on it.

      Overrides:
      packageProcess in class AbstractTypeProcessor
      Parameters:
      e - the package being processed
      p - the path to the package declaration
    • reportError

      public void reportError(@Nullable Object source, @CompilerMessageKey String messageKey, Object... args)
      Reports an error. By default, prints it to the screen via the compiler's internal messager.

      Prefer a Tree: pass an Element only for a declaration that has none, such as one read from bytecode. Under a host that collects diagnostics, such as the Error Prone plugin, an Element declared in the current compilation unit is reported on its declaration; any other Element is reported directly to javac, bypassing the host's severity and suppression.

      Parameters:
      source - the source position information; may be an Element or a Tree. Null means the error has no source position -- for example, it is issued while the checker is initializing, before any source file is processed -- and is reported against the compilation as a whole.
      messageKey - the message key
      args - arguments for interpolation in the string corresponding to the given message key
    • reportWarning

      public void reportWarning(@Nullable Object source, @CompilerMessageKey String messageKey, Object... args)
      Reports a warning. By default, prints it to the screen via the compiler's internal messager.

      Prefer a Tree: pass an Element only for a declaration that has none, such as one read from bytecode. Under a host that collects diagnostics, such as the Error Prone plugin, an Element declared in the current compilation unit is reported on its declaration; any other Element is reported directly to javac, bypassing the host's severity and suppression.

      Parameters:
      source - the source position information; may be an Element or a Tree. Null means the warning has no source position -- for example, it is issued while the checker is initializing, before any source file is processed. Such a warning cannot be suppressed by a @SuppressWarnings annotation, because there is no declaration to write one on; only the -AsuppressWarnings command-line option suppresses it.
      messageKey - the message key
      args - arguments for interpolation in the string corresponding to the given message key
    • getErrorCount

      public int getErrorCount()
      Returns the number of errors that this checker has reported so far in this compilation, through reportError(java.lang.Object, java.lang.String, java.lang.Object...) or report(Object, DiagMessage). Suppressed errors are not counted. An error that -Awarns reports as a warning is counted.

      The count does not include the errors of this checker's subcheckers; see getSubcheckers(). Unlike javac's error count, it does not include errors from javac or from other annotation processors, and it is also correct when a host, such as the Error Prone plugin, rather than javac receives the checker's diagnostics. For example, an override of typeProcessingOver() can use it to print a note if the checker reported an error.

      Returns:
      the number of errors that this checker has reported
    • report

      public void report(@Nullable 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...) or reportWarning(java.lang.Object, java.lang.String, java.lang.Object...).

      Parameters:
      source - the source position information; may be an Element or a Tree. Null means the message has no source position -- for example, it is issued while the checker is initializing, before any source file is processed -- and is reported against the compilation as a whole.
      d - the diagnostic message
    • message

      @FormatMethod public void message(Diagnostic.Kind kind, String msg, 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 using reportError(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 print
      msg - the message text
      args - optional arguments to substitute in the message
      See Also:
    • message

      public void message(Diagnostic.Kind kind, 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 using reportError(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 print
      msg - the message text
      See Also:
    • getSuppressWarningsPrefixesOfSubcheckers

      public Collection<String> getSuppressWarningsPrefixesOfSubcheckers()
      Like getSuppressWarningsPrefixes(), but includes all prefixes supported by this checker or any of its subcheckers. Does not guarantee that the result is in any particular order. The result is immutable.
      Returns:
      the suppress warnings prefixes supported by this checker or any of its subcheckers
    • fullMessageOf

      protected String fullMessageOf(String messageKey, 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, returns defaultValue.
      Parameters:
      messageKey - a message key
      defaultValue - a default value to use if messageKey is not a message key
      Returns:
      the localized long message corresponding to this key or a suffix, or defaultValue
    • processErrorMessageArg

      protected Object processErrorMessageArg(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
    • suppressWarningsString

      protected String suppressWarningsString(String messageKey)
      Returns the most specific warning suppression string for the warning/error being printed.
      • If -AshowSuppressWarningsStrings was supplied on the command line, this is [checkername1, checkername2]:msg, where each checkername is a checker name or "allcheckers".
      • If -ArequirePrefixInWarningSuppressions or -AshowPrefixInWarningMessages was supplied on the command line, this is checkername:msg (where checkername may be "allcheckers").
      • Otherwise, it is just msg.
      Parameters:
      messageKey - the simple, checker-specific error message key
      Returns:
      the most specific SuppressWarnings string for the warning/error being printed
    • getLintOption

      public final boolean getLintOption(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:
      IllegalArgumentException - if the option name is not recognized via the SupportedLintOptions annotation or the getSupportedLintOptions() method
      See Also:
    • getLintOption

      public final boolean getLintOption(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 for
      def - 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:
      IllegalArgumentException - if the option name is not recognized via the SupportedLintOptions annotation or the getSupportedLintOptions() method
      See Also:
    • setLintOption

      protected final void setLintOption(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 set
      val - the option value
      Throws:
      IllegalArgumentException - if the option name is not recognized via the SupportedLintOptions annotation or the getSupportedLintOptions() method
      See Also:
    • getImmediateSubcheckerClasses

      protected Set<Class<? extends SourceChecker>> getImmediateSubcheckerClasses()
      Returns the set of subchecker classes on which this checker depends. ("Depends" means the checkers that are subcheckers of the current checker rather than a subchecker of some other checker.) Returns an empty set if this checker does not depend on any others.

      If this checker should run multiple independent checkers and not contain a type system, then subclass AggregateChecker.

      Subclasses should override this method to specify subcheckers. If they do so, they should call the super implementation of this method and add dependencies to the returned set so that checkers required for reflection resolution are included if reflection resolution is requested.

      If a checker should be added or not based on a command line option, use getOptionsNoSubcheckers() or hasOptionNoSubcheckers(String) to avoid recursively calling this method.

      Each subchecker of this checker may also depend on other checkers. If this checker and one of its subcheckers both depend on a third checker, that checker will only be instantiated once.

      Though each checker is run on a whole compilation unit before the next checker is run, error and warning messages are collected and sorted based on the location in the source file before being printed (see printOrStoreMessage).

      WARNING: Circular dependencies are not supported. (In other words, if checker A depends on checker B, checker B cannot depend on checker A.) The Checker Framework does not check for circularity. Make sure no circular dependencies are created when overriding this method.

      This method is protected so it can be overridden, but it should only be called internally by SourceChecker.

      Returns:
      the subchecker classes on which this checker depends; will be modified by callees
    • shouldResolveReflection

      public boolean shouldResolveReflection()
      Returns true if reflection should be resolved.
      Returns:
      true if reflection should be resolved
    • getRelatedClassName

      public static @ClassGetName String getRelatedClassName(Class<?> checkerClass, String replacement)
      Returns the name of a class related to a given one, by replacing "Checker" or "Subchecker" by replacement.
      Parameters:
      checkerClass - the checker class
      replacement - the string that replaces "Checker" or "Subchecker"
      Returns:
      the name of the related class
    • getSupportedLintOptions

      public Set<String> getSupportedLintOptions()
      Returns the lint options recognized by this checker. Lint options are those which can be checked for via getLintOption(java.lang.String).
      Returns:
      an unmodifiable Set of the lint options recognized by this checker
    • createSupportedLintOptions

      protected Set<String> createSupportedLintOptions()
      Compute the set of supported lint options for this checker and its subcheckers.
      Returns:
      the set of supported lint options for this checker and its subcheckers
    • getSupportedModes

      public final Set<String> getSupportedModes()
      Returns the values of -Amode that this checker and its subcheckers recognize. Each names a group of options; see addOptionsForMode(java.lang.String, java.util.Map<java.lang.String, java.lang.String>).
      Returns:
      an unmodifiable set of supported mode names
    • createSupportedModes

      protected Set<String> createSupportedModes()
      Computes the result of getSupportedModes(), from the SupportedModes annotations on this checker's class hierarchy, its parent checkers, and from its subcheckers.
      Returns:
      the supported mode names
    • addOptionsForMode

      protected void addOptionsForMode(String mode, Map<String,String> activeOptions)
      Adds to activeOptions the options that mode enables for this checker. The default implementation adds none; a checker that declares modes with SupportedModes overrides this, calls super, and ignores a mode it does not recognize (another checker in the same run may define it).

      Use Map.putIfAbsent(K, V): activeOptions already holds the options written on the command line, which take precedence over the mode.

      Parameters:
      mode - the value of the -Amode option
      activeOptions - the active options, to which mode options are added
    • getAssumeAssertions

      public final AssumeAssertions getAssumeAssertions()
      Returns what to assume about whether assertions are enabled at run time, as selected by the -AassumeAssertions command-line option.
      Returns:
      what to assume about whether assertions are enabled at run time
    • getOptions

      public Map<String,String> getOptions()
      Description copied from interface: OptionConfiguration
      Returns all active options for this checker.
      Specified by:
      getOptions in interface OptionConfiguration
      Returns:
      all active options for this checker
    • hasOption

      public final boolean hasOption(String name)
      Description copied from interface: OptionConfiguration
      Returns true if the given option is provided.

      Note that OptionConfiguration.getOption(java.lang.String) can still return null even if hasOption returns true: this happens e.g. for -Amyopt

      Specified by:
      hasOption in interface OptionConfiguration
      Parameters:
      name - the name of the option to check
      Returns:
      true if the option name was provided, false otherwise
    • getOption

      public final String getOption(String name)
      Determines the value of the option with the given name.

      Note that getOption can still return null even if OptionConfiguration.hasOption(java.lang.String) returns true: this happens e.g. for -Amyopt

      Specified by:
      getOption in interface OptionConfiguration
      Parameters:
      name - the name of the option to check
      Returns:
      the value of the option with the given name
      See Also:
    • getOption

      public final String getOption(String name, String defaultValue)
      Determines the boolean value of the option with the given name. Returns defaultValue if the option is not set.
      Specified by:
      getOption in interface OptionConfiguration
      Parameters:
      name - the name of the option to check
      defaultValue - 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:
    • getBooleanOption

      public final boolean getBooleanOption(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 interface OptionConfiguration
      Parameters:
      name - the name of the option to check
      Returns:
      the boolean value of the option
      See Also:
    • getBooleanOption

      public final boolean getBooleanOption(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 interface OptionConfiguration
      Parameters:
      name - the name of the option to check
      defaultValue - the default value to use if the option is not set
      Returns:
      the boolean value of the option
      See Also:
    • getStringsOption

      public final List<String> getStringsOption(String name, char separator, List<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 interface OptionConfiguration
      Parameters:
      name - the name of the option to check
      separator - the separator for list elements
      defaultValue - the default value to use if the option is not set
      Returns:
      the list of options
      See Also:
    • getStringsOption

      public final List<String> getStringsOption(String name, String separator, List<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 interface OptionConfiguration
      Parameters:
      name - the name of the option to check
      separator - the separator for list elements
      defaultValue - the default value to use if the option is not set
      Returns:
      the list of options
      See Also:
    • printStoredMessages

      protected void printStoredMessages(CompilationUnitTree unit)
      Prints error messages for this checker and all subcheckers such that the errors are ordered by line and column number and then by checker. (See SourceChecker.CheckerMessage.compareTo(CheckerMessage) for more precise order.)
      Parameters:
      unit - current compilation unit
    • getSupportedOptions

      public Set<String> getSupportedOptions()
      Description copied from interface: OptionConfiguration
      Map the Checker Framework version of SupportedOptions to the standard annotation provided version SupportedOptions.
      Specified by:
      getSupportedOptions in interface OptionConfiguration
      Specified by:
      getSupportedOptions in interface Processor
      Overrides:
      getSupportedOptions in class AbstractProcessor
      Returns:
      the supported options
    • getClassHierarchy

      public final List<Class<?>> getClassHierarchy()
      Returns the class hierarchy of this checker, starting from its runtime class up to (but not including) AbstractTypeProcessor.
      Returns:
      the class hierarchy of this checker
    • getRelevantJavaTypes

      public final @Nullable Set<Class<?>> getRelevantJavaTypes()
      Returns the set of Java classes specified by RelevantJavaTypes on this checker's class hierarchy, or null if no RelevantJavaTypes annotation is present.
      Returns:
      the set of relevant Java classes, or null if unrestricted
    • createRelevantJavaTypes

      protected @Nullable Set<Class<?>> createRelevantJavaTypes()
      Computes the set of Java classes specified by RelevantJavaTypes on this checker's class hierarchy. Subclasses can override this method to customize or extend the relevant Java types programmatically.
      Returns:
      the set of relevant Java classes, or null if unrestricted
    • expandCFOptions

      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.
      Parameters:
      clazzPrefixes - the classes to prefix
      options - the option names
      Returns:
      the possible combinations that should be supported
    • expandCFOptions

      protected Collection<String> expandCFOptions(List<? extends Class<?>> clazzPrefixes, Collection<String> options)
      Generate the possible command-line option names by prefixing each class name from classPrefixes to options, separated by OPTION_SEPARATOR.
      Parameters:
      clazzPrefixes - the classes to prefix
      options - the option names
      Returns:
      the possible combinations that should be supported
    • getSupportedAnnotationTypes

      public final Set<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 a SupportedAnnotationTypes annotation.

      To specify the annotations that a checker recognizes as type qualifiers, see AnnotatedTypeFactory.createSupportedTypeQualifiers().

      Specified by:
      getSupportedAnnotationTypes in interface Processor
      Overrides:
      getSupportedAnnotationTypes in class AbstractProcessor
      Throws:
      Error - if a subclass is annotated with SupportedAnnotationTypes
    • 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(Set<Element> elementsSuppress, Set<String> prefixes, Set<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 warning
      prefixes - the SuppressWarnings prefixes that suppress all warnings from this checker
      allErrorKeys - all error keys that can be issued by this checker
    • shouldSuppressWarnings

      public boolean shouldSuppressWarnings(Tree tree, 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 the errKey matches a string in -AsuppressWarnings.
      Parameters:
      tree - the tree that might be a source of a warning
      errKey - 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(TreePath path, 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.

      This overload also accounts for source-position-based suppression from unchecked code: if no matching @SuppressWarnings is found, then warnings outside a relevant AnnotatedFor scope are suppressed when -AuseConservativeDefaultsForUncheckedCode=source, -AusePermissiveDefaultsForUncheckedCode=source, or -AonlyAnnotatedFor is in effect.

      Parameters:
      path - the TreePath that might be a source of, or related to, a warning
      errKey - the error key the checker is emitting
      Returns:
      true if no warning should be emitted for the given path, either because it is contained by a declaration with an appropriately-valued @SuppressWarnings annotation, because it is suppressed by command-line arguments, or because it is outside an AnnotatedFor scope when source-based unchecked defaults are enabled; false otherwise
    • useConservativeDefault

      public boolean useConservativeDefault(String kindOfCode)
      Determine whether conservative defaults should be used for the kind of unchecked code indicated by the command line arguments.
      Parameters:
      kindOfCode - source or bytecode
      Returns:
      true if conservative defaults should be used
    • usePermissiveDefault

      public boolean usePermissiveDefault(String kindOfCode)
      Determine whether permissive defaults should be used for the kind of unchecked code indicated by the command line arguments.
      Parameters:
      kindOfCode - source or bytecode
      Returns:
      whether permissive defaults should be used
    • shouldSuppressWarnings

      public boolean shouldSuppressWarnings(Element elt, 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.

      This overload also accounts for source-position-based suppression from unchecked code: if no matching @SuppressWarnings is found, then warnings outside a relevant AnnotatedFor scope are suppressed when -AuseConservativeDefaultsForUncheckedCode=source, -AusePermissiveDefaultsForUncheckedCode=source, or -AonlyAnnotatedFor is in effect.

      shouldSuppressWarnings(TreePath, String) also calls this method, with the innermost declaration enclosing the tree, so an override applies to a diagnostic reported on a tree as well as to one reported on an element.

      Parameters:
      elt - the Element that might be a source of, or related to, a warning
      errKey - the error key the checker is emitting
      Returns:
      true if no warning should be emitted for the given Element, either because it is contained by a declaration with an appropriately-valued @SuppressWarnings annotation, because it is suppressed by command-line arguments, or because it is outside an AnnotatedFor scope when source-based unchecked defaults are enabled; false otherwise
    • messageKeyMatches

      protected boolean messageKeyMatches(String messageKey, 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 key of the error that is being emitted, without any "checker:" prefix
      messageKeyInSuppressWarningsString - the message key in a @SuppressWarnings annotation
      Returns:
      true if the arguments match
    • isElementAnnotatedForThisCheckerOrUpstreamChecker

      public boolean isElementAnnotatedForThisCheckerOrUpstreamChecker(@Nullable Element elt)
      Returns true if the element is in the scope of an @AnnotatedFor annotation for this checker or an upstream checker that called this one. The annotation may be on the element itself or on an enclosing element; an @UnannotatedFor that applies to this checker subtracts the element from an enclosing @AnnotatedFor scope, so this method returns false for such an element even though an enclosing element is annotated.

      This implementation always returns false, which is correct for a checker that does not type-check, such as an aggregate checker or one of the counting checkers. BaseTypeChecker overrides it.

      Parameters:
      elt - the source code element to check, or null
      Returns:
      true if the element is in the scope of an @AnnotatedFor for this checker or an upstream checker
    • getSuppressWarningsPrefixes

      public NavigableSet<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.

      This method is related to getUpstreamCheckerNames(). By default, the returned set includes lower-case prefixes derived from all checker names returned by getUpstreamCheckerNames(), unless this checker class has a SuppressWarningsPrefix meta-annotation.

      Returns:
      non-empty modifiable set of lower-case prefixes for SuppressWarnings strings
      See Also:
    • getStandardSuppressWarningsPrefixes

      protected final NavigableSet<String> getStandardSuppressWarningsPrefixes()
      Returns a sorted set of SuppressWarnings prefixes read from the SuppressWarningsPrefix meta-annotation on the checker class. Or if no SuppressWarningsPrefix is used, prefixes are inferred from the upstream checker names. SUPPRESS_ALL_PREFIX is also added, at the end, unless useAllcheckersPrefix is false.
      Returns:
      a sorted set of SuppressWarnings prefixes
    • getWarningMessagePrefix

      protected 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 of getSuppressWarningsPrefixes().

      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 Element element)
      Tests whether the class owner of the passed element matches the pattern specified in the checker.skipUses property.
      Parameters:
      element - the element
      Returns:
      true iff the enclosing class of element should be skipped
    • shouldSkipUses

      public boolean shouldSkipUses(@FullyQualifiedName String typeName)
      Returns true if the class owner of the passed type matches the pattern specified in the checker.skipUses property. In contrast to shouldSkipUses(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(ClassTree tree)
      Returns true if the class definition should not be checked because it matches the checker.skipDefs property, or does not match the checker.onlyDefs property. An anonymous or local class, which has no fully-qualified name, is checked if and only if its innermost enclosing class with a fully-qualified name is.
      Parameters:
      tree - class to potentially skip
      Returns:
      true if checker should not type-check tree
    • shouldSkipDefs

      public boolean shouldSkipDefs(MethodTree tree)
      Returns true if the method definition should not be checked. The default implementation returns false; subclasses may override it.
      Parameters:
      tree - method to potentially skip
      Returns:
      true if checker should not type-check tree
    • shouldSkipDefs

      public boolean shouldSkipDefs(VariableTree tree)
      Returns true if the variable declaration should not be checked: neither the declaration nor its initializer, including any lambda or class in the initializer. Code that uses the variable is still checked against its type. The default implementation returns false; subclasses may override it.
      Parameters:
      tree - variable declaration to potentially skip
      Returns:
      true if checker should not type-check tree
    • shouldSkipDefs

      public final boolean shouldSkipDefs(ClassTree cls, MethodTree meth)
      Returns true if the method definition should not be checked, because shouldSkipDefs(ClassTree) is true for its class or shouldSkipDefs(MethodTree) is true for the method.
      Parameters:
      cls - class to potentially skip
      meth - method to potentially skip
      Returns:
      true if checker should not type-check cls or meth
    • shouldSkipFiles

      public final boolean shouldSkipFiles(ClassTree tree)
      Returns true if the enclosing file path of the passed tree matches the pattern specified in the checker.skipFiles property.
      Parameters:
      tree - a tree
      Returns:
      true iff the enclosing directory of the tree should be skipped
    • handleProcessingError

      protected void handleProcessingError(String methodName, Throwable t)
      Handles a throwable thrown by AbstractTypeProcessor.typeProcessingOver(). The default implementation rethrows it, so that it is reported as an uncaught annotation processor exception. A subclass that reports a throwable as a compiler diagnostic overrides this.

      Reports the throwable as a compiler diagnostic. typeProcessingOver() is overridable, and five checkers override it, so AbstractTypeProcessor wrapping the call is what puts their work under this handler.

      Overrides:
      handleProcessingError in class AbstractTypeProcessor
      Parameters:
      methodName - the name of the method that threw t
      t - the throwable that methodName threw
    • shouldAddShutdownHook

      protected boolean shouldAddShutdownHook()
      Returns true to indicate that method shutdownHook() 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 Properties getProperties(Class<?> cls, String filePath, boolean permitNonExisting)
      A helper function to parse a Properties file.
      Parameters:
      cls - the class whose location is the base of the file path
      filePath - the name/path of the file to be read
      permitNonExisting - 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 SourceVersion getSupportedSourceVersion()
      Specified by:
      getSupportedSourceVersion in interface Processor
      Overrides:
      getSupportedSourceVersion in class AbstractProcessor
    • getPathToCompilationUnit

      public TreePath getPathToCompilationUnit()
      Returns the path to the current compilation unit.
      Returns:
      path to the current compilation unit
    • getSubCheckerIndex

      protected int getSubCheckerIndex()
      Index of this checker in getSubcheckers() (when getSubcheckers() is called on the ultimate ancestor), or the size of getSubcheckers() if this is the ancestor checker.
      Returns:
      index of this checker in the ultimate ancestor's getSubcheckers(), or the size of getSubcheckers() if this is the ancestor checker