Skip to content

[Bug]: Spoon resolves wrong variable declaration with negated instanceof pattern and local variable shadowing #6645

@Luro02

Description

@Luro02

Describe the bug

In the below code, in the last System.out.println(i); in the main, the variable reference i is resolved as a reference to the first if (o instanceof String i) {.

This is wrong, because String i is only valid inside the if block, and not outside of it.
The code worked on version 11.2.2-beta-10, and started failing with 11.2.2-beta-11.

I think the cause for this issue is a change introduced by #6444

Source code you are trying to analyze/transform

public class Main {
    public static void main(String[] args) {
        Object o = "Hello";
        if (o instanceof String i) {
            System.out.println(i);
        }
                            
        // negated if
        if (!(o instanceof String i)) {
        } else {
            System.out.println(i);
        }
                            
        // then branch cannot complete
        if (!(o instanceof String i)) {
            throw new IllegalArgumentException();
        }
        System.out.println(i);
    }
}

Source code for your Spoon processing

Actual output

Expected output

Spoon Version

11.3.1-beta-8

JVM Version

openjdk version "21.0.2" 2024-01-16 LTS OpenJDK Runtime Environment Zulu21.32+17-CA (build 21.0.2+13-LTS) OpenJDK 64-Bit Server VM Zulu21.32+17-CA (build 21.0.2+13-LTS, mixed mode, sharing)

What operating system are you using?

Windows 11

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions