Skip to content

PatternVariableAssignment check false negative when pattern variable extends beyond the statement of introduction #17203

@SteLeo1602

Description

@SteLeo1602

I have downloaded the latest checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run
I have executed the cli and showed it below, as cli describes the problem better than 1,000 words

/var/tmp $ javac Test.java
/var/tmp $ cat config.xml
<?xml version="1.0" encoding="UTF-8"?> 
<!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="severity" value="warning"/>
  <property name="charset" value="UTF-8"/>
  <property name="fileExtensions" value="java, properties, xml"/>
  <module name="Checker">
    <module name="TreeWalker">
      <module name="PatternVariableAssignment"/>
    </module>
  </module>
</module>
/var/tmp $ cat Test.java
public class Test {                             
                                                
    public static boolean testMethod(Object s) {
        if (!(s instanceof String r)) {         
            return false;                       
        }                                       
        r = null;    
        return true;
   }

}
/var/tmp $ RUN_LOCALE="-Duser.language=en -Duser.country=US"
/var/tmp $ java $RUN_LOCALE -jar checkstyle-10.25.1-SNAPSHOT.jar -c config.xml Test.java
Starting audit...
Audit done.

Expected: PatternVariableAssignment mark r=null line as violation since pattern variable r is being assigned


The scope of a pattern variable can extend beyond the statement that introduced it:
From https://docs.oracle.com/en/java/javase/18/language/pattern-matching-instanceof-operator.html
.

Metadata

Metadata

Assignees

No one assigned

    Labels

    approvedbugfalse negativeissues where check should place violations on code, but does not

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions