Skip to content

[core] BaseAntlrTerminalNode should return type instead of index for getTokenKind() #6471

@stokpop

Description

@stokpop

Affects PMD Version: 7.21.0

Description:

Creating a custom Kotlin rule using Java we found that BaseAntlrInnerNode#getToken(s) would always return null.

This filter fails:

.filter(it -> it.getTokenKind() == kind)

due to BaseAntlrInnerNode

    protected int getTokenKind() {
        return antlrNode.symbol.getTokenIndex();
    }

Fix is to change that to getType() assuming that type is also kind.

This can fail in antlr4 base Kotlin parser and perhaps also in the Swift parser.

Code Sample demonstrating the issue:

        String code = "class Foo { fun foo() { var a = 42; a += 1 } }";

        // Parse using KotlinParsingHelper
        KtKotlinFile root = KotlinParsingHelper.DEFAULT.parse(code);

        assertNotNull(root);

        // Traverse to the first function declaration in the file
        KtFunctionDeclaration fn = root.descendants(KtFunctionDeclaration.class).first();
        assertNotNull(fn, "Expected a function declaration in the parsed Kotlin file");

        // Find the first KtAssignmentAndOperator node within the function body
        KtAssignmentAndOperator idNode = fn.descendants(KtAssignmentAndOperator.class).first();
        assertNotNull(idNode, "Expected a assignmentAndOperator within the function node");
        // Call the generated accessor that returns the ADD_ASSIGNMENT terminal node.
        // This calls getToken/getTokens under the hood and will exercise
        // BaseAntlrInnerNode#getToken(s).
        TerminalNode tn = idNode.ADD_ASSIGNMENT();
        assertNotNull(tn, "Expected an ADD_ASSIGNMENT terminal node");
        assertEquals("+=", tn.getText());
        assertEquals(ADD_ASSIGNMENT, tn.getSymbol().getType());

Steps to reproduce:

Run the unit test above, will submit this in a PR.

Running PMD through: [custom Kotlin Java rule]

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:bugPMD crashes or fails to analyse a file.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions