Class SuppressWarningsHolder

  • All Implemented Interfaces:
    Configurable, Contextualizable

    public class SuppressWarningsHolder
    extends AbstractCheck

    Maintains a set of check suppressions from @SuppressWarnings annotations. It allows to prevent Checkstyle from reporting violations from parts of code that were annotated with @SuppressWarnings and using name of the check to be excluded. It is possible to suppress all the checkstyle warnings with the argument "all". You can also use a checkstyle: prefix to prevent compiler from processing these annotations. You can also define aliases for check names that need to be suppressed.

    • Property aliasList - Specify aliases for check names that can be used in code within SuppressWarnings. Type is java.lang.String[]. Default value is null.

    To use default module configuration:

     <module name="TreeWalker">
       <module name="MemberName"/>
       <module name="ConstantName"/>
       <module name="ParameterNumber">
         <property name="id" value="ParamNumberId"/>
       </module>
       <module name="NoWhitespaceAfter"/>
    
       <module name="SuppressWarningsHolder"/>
     </module>
     <module name="SuppressWarningsFilter"/>
     
     class Test {
    
         private int K; // violation
         @SuppressWarnings({"membername"})
         private int J; // violation suppressed
    
         private static final int i = 0; // violation
         @SuppressWarnings("checkstyle:constantname")
         private static final int m = 0; // violation suppressed
    
         public void needsLotsOfParameters (int a, // violation
           int b, int c, int d, int e, int f, int g, int h) {
           // ...
         }
    
         @SuppressWarnings("ParamNumberId")
         public void needsLotsOfParameters1 (int a, // violation suppressed
           int b, int c, int d, int e, int f, int g, int h) {
           //  ...
         }
    
        private int [] ARR; // 2 violations
        @SuppressWarnings("all")
        private int [] ARRAY; // violations suppressed
     }
     

    The general rule is that the argument of the @SuppressWarnings will be matched against class name of the check in any letter case. Adding check suffix is also accepted.

    If aliasList property was provided you can use your own names e.g. below code will work if there was provided a ParameterNumberCheck=paramnum in the aliasList:

     <module name="TreeWalker">
       <module name="ParameterNumber"/>
    
       <module name="SuppressWarningsHolder">
         <property name="aliasList" value=
           "com.puppycrawl.tools.checkstyle.checks.sizes.ParameterNumberCheck=paramnum"/>
       </module>
     </module>
     <module name="SuppressWarningsFilter"/>
     
     class Test {
    
         public void needsLotsOfParameters (int a, // violation
           int b, int c, int d, int e, int f, int g, int h) {
           // ...
         }
    
         @SuppressWarnings("paramnum")
         public void needsLotsOfParameters1 (int a, // violation suppressed
           int b, int c, int d, int e, int f, int g, int h) {
           //  ...
         }
    
     }
     

    Parent is com.puppycrawl.tools.checkstyle.TreeWalker

    Since:
    5.7
    • Field Detail

      • CHECKSTYLE_PREFIX

        private static final java.lang.String CHECKSTYLE_PREFIX
        Optional prefix for warning suppressions that are only intended to be recognized by checkstyle. For instance, to suppress FallThroughCheck only in checkstyle (and not in javac), use the suppression "checkstyle:fallthrough" or "checkstyle:FallThrough". To suppress the warning in both tools, just use "fallthrough".
        See Also:
        Constant Field Values
      • CHECK_ALIAS_MAP

        private static final java.util.Map<java.lang.String,​java.lang.String> CHECK_ALIAS_MAP
        A map from check source names to suppression aliases.
      • ENTRIES

        private static final java.lang.ThreadLocal<java.util.List<SuppressWarningsHolder.Entry>> ENTRIES
        A thread-local holder for the list of suppression entries for the last file parsed.
      • WHITESPACE

        private static final java.util.regex.Pattern WHITESPACE
        Compiled pattern used to match whitespace in text block content.
      • NEWLINE

        private static final java.util.regex.Pattern NEWLINE
        Compiled pattern used to match preceding newline in text block content.
    • Method Detail

      • getDefaultAlias

        public static java.lang.String getDefaultAlias​(java.lang.String sourceName)
        Returns the default alias for the source name of a check, which is the source name in lower case with any dotted prefix or "Check"/"check" suffix removed.
        Parameters:
        sourceName - the source name of the check (generally the class name)
        Returns:
        the default alias for the given check
      • getAlias

        public static java.lang.String getAlias​(java.lang.String sourceName)
        Returns the alias for the source name of a check. If an alias has been explicitly registered via setAliasList(String...), that alias is returned; otherwise, the default alias is used.
        Parameters:
        sourceName - the source name of the check (generally the class name)
        Returns:
        the current alias for the given check
      • registerAlias

        private static void registerAlias​(java.lang.String sourceName,
                                          java.lang.String checkAlias)
        Registers an alias for the source name of a check.
        Parameters:
        sourceName - the source name of the check (generally the class name)
        checkAlias - the alias used in SuppressWarnings annotations
      • setAliasList

        public void setAliasList​(java.lang.String... aliasList)
        Setter to specify aliases for check names that can be used in code within SuppressWarnings.
        Parameters:
        aliasList - comma-separated alias assignments
        Throws:
        java.lang.IllegalArgumentException - when alias item does not have '='
      • isSuppressed

        public static boolean isSuppressed​(AuditEvent event)
        Checks for a suppression of a check with the given source name and location in the last file processed.
        Parameters:
        event - audit event.
        Returns:
        whether the check with the given name is suppressed at the given source location
      • isSuppressedAfterEventStart

        private static boolean isSuppressedAfterEventStart​(int line,
                                                           int column,
                                                           SuppressWarningsHolder.Entry entry)
        Checks whether suppression entry position is after the audit event occurrence position in the source file.
        Parameters:
        line - the line number in the source file where the event occurred.
        column - the column number in the source file where the event occurred.
        entry - suppression entry.
        Returns:
        true if suppression entry position is after the audit event occurrence position in the source file.
      • isSuppressedBeforeEventEnd

        private static boolean isSuppressedBeforeEventEnd​(int line,
                                                          int column,
                                                          SuppressWarningsHolder.Entry entry)
        Checks whether suppression entry position is before the audit event occurrence position in the source file.
        Parameters:
        line - the line number in the source file where the event occurred.
        column - the column number in the source file where the event occurred.
        entry - suppression entry.
        Returns:
        true if suppression entry position is before the audit event occurrence position in the source file.
      • getAcceptableTokens

        public int[] getAcceptableTokens()
        Description copied from class: AbstractCheck
        The configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.
        Specified by:
        getAcceptableTokens in class AbstractCheck
        Returns:
        the token set this check is designed for.
        See Also:
        TokenTypes
      • beginTree

        public void beginTree​(DetailAST rootAST)
        Description copied from class: AbstractCheck
        Called before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.
        Overrides:
        beginTree in class AbstractCheck
        Parameters:
        rootAST - the root of the tree
      • addSuppressions

        private static void addSuppressions​(java.util.List<java.lang.String> values,
                                            DetailAST targetAST)
        Method to populate list of suppression entries.
        Parameters:
        values - - list of check names
        targetAST - - annotation target
      • removeCheckstylePrefixIfExists

        private static java.lang.String removeCheckstylePrefixIfExists​(java.lang.String checkName)
        Method removes checkstyle prefix (checkstyle:) from check name if exists.
        Parameters:
        checkName - - name of the check
        Returns:
        check name without prefix
      • getAllAnnotationValues

        private static java.util.List<java.lang.String> getAllAnnotationValues​(DetailAST ast)
        Get all annotation values.
        Parameters:
        ast - annotation token
        Returns:
        list values
        Throws:
        java.lang.IllegalArgumentException - if there is an unknown annotation value type.
      • getAnnotationTarget

        private static java.util.Optional<DetailASTgetAnnotationTarget​(DetailAST ast)
        Get target of annotation.
        Parameters:
        ast - the AST node to get the child of
        Returns:
        get target of annotation
        Throws:
        java.lang.IllegalArgumentException - if there is an unexpected container type.
      • getNthChild

        private static DetailAST getNthChild​(DetailAST ast,
                                             int index)
        Returns the n'th child of an AST node.
        Parameters:
        ast - the AST node to get the child of
        index - the index of the child to get
        Returns:
        the n'th child of the given AST node, or null if none
      • getIdentifier

        private static java.lang.String getIdentifier​(DetailAST ast)
        Returns the Java identifier represented by an AST.
        Parameters:
        ast - an AST node for an IDENT or DOT
        Returns:
        the Java identifier represented by the given AST subtree
        Throws:
        java.lang.IllegalArgumentException - if the AST is invalid
      • getStringExpr

        private static java.lang.String getStringExpr​(DetailAST ast)
        Returns the literal string expression represented by an AST.
        Parameters:
        ast - an AST node for an EXPR
        Returns:
        the Java string represented by the given AST expression or empty string if expression is too complex
        Throws:
        java.lang.IllegalArgumentException - if the AST is invalid
      • getAnnotationValues

        private static java.util.List<java.lang.String> getAnnotationValues​(DetailAST ast)
        Returns the annotation values represented by an AST.
        Parameters:
        ast - an AST node for an EXPR or ANNOTATION_ARRAY_INIT
        Returns:
        the list of Java string represented by the given AST for an expression or annotation array initializer
        Throws:
        java.lang.IllegalArgumentException - if the AST is invalid
      • findAllExpressionsInChildren

        private static java.util.List<java.lang.String> findAllExpressionsInChildren​(DetailAST parent)
        Method looks at children and returns list of expressions in strings.
        Parameters:
        parent - ast, that contains children
        Returns:
        list of expressions in strings
      • getContentWithoutPrecedingWhitespace

        private static java.lang.String getContentWithoutPrecedingWhitespace​(java.lang.String textBlockContent)
        Remove preceding newline and whitespace from the content of a text block.
        Parameters:
        textBlockContent - the actual text in a text block.
        Returns:
        content of text block with preceding whitespace and newline removed.