javalombokcheckstyle

Suppress checkstyle for lombok's val using SuppressionXpathFilter


I am using lombok's val to specify the final variables in my code. The checkstyle rule for FinalLocalVariable reports any val variable as non-final. I am trying to write a custom suppress.xml to suppress this check for any val field. Currently, my suppression.xml looks like this

<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
    "-//Checkstyle//DTD SuppressionXpathFilter Experimental Configuration 1.2//EN"
    "https://checkstyle.org/dtds/suppressions_1_2_xpath_experimental.dtd">
 <suppressions>
<suppress-xpath 
        checks="FinalLocalVariable" query="//VARIABLE_DEF[./TYPE/IDENT[@text='val']]"/
</suppressions>

I have generated the AST tree for the class that has the val fields, here is the part where val is declared

`--SLIST -> { [32:96]
    |       |--VARIABLE_DEF -> VARIABLE_DEF [33:4]
    |       |   |--MODIFIERS -> MODIFIERS [33:4]
    |       |   |--TYPE -> TYPE [33:4]
    |       |   |   `--IDENT -> val [33:4]

My idea was to specify that any variable definition of identity val should be ignored for this exact check. I have read the checkstyle's documentation for SuppressionXpathFilter and I cannot find what my issue is as the checkstyle keeps reporting that the variable should be declared final. Any help would be much appreciated.


Solution

  • You need to address the IDENT child node of the VARIABLE_DEF with the suppression query:

    query="//VARIABLE_DEF[./TYPE/IDENT[@text='val']]/IDENT"
    

    For the following source code:

    class C {
        void m() {
            val a = 3;
        }
    }
    

    with the following checkstyle config:

    <?xml version="1.0"?>
    <!DOCTYPE module PUBLIC
            "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
            "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
    <module name="Checker">
        <property name="fileExtensions" value="java"/>
        <module name="TreeWalker">
            <module name="SuppressionXpathFilter">
                <property name="file" value="suppressions-check.xml"/>
            </module>
            <module name="FinalLocalVariable"/>
        </module>
    </module>
    

    using this suppression filter file:

    <?xml version="1.0"?>
    <!DOCTYPE suppressions PUBLIC
            "-//Checkstyle//DTD SuppressionXpathFilter Experimental Configuration 1.2//EN"
            "https://checkstyle.org/dtds/suppressions_1_2_xpath_experimental.dtd">
    <suppressions>
        <suppress-xpath checks="FinalLocalVariable" query="//VARIABLE_DEF[./TYPE/IDENT[@text='val']]/IDENT"/>
    </suppressions>
    

    Checkstyle won't report any error.