Skip to content

[kotlin] Add XPath functions and type attributes - #6893

Merged
adangel merged 54 commits into
pmd:mainfrom
stokpop:add-kotlin-xpath-type-functions
Sep 17, 2026
Merged

adangel merged 54 commits into
pmd:mainfrom
stokpop:add-kotlin-xpath-type-functions

Conversation

@stokpop

@stokpop stokpop commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Adds XPath function and attribute support to pmd-kotlin, enabling type-aware XPath rules.

What's included

7 XPath functions (pmd-kotlin: namespace):

  • typeIs(typeName) / typeIsExactly(typeName) — type checks (with/without subtypes)
  • matchesSig(signature) — match function/constructor call signatures
  • hasAnnotation(fqn) — check annotation presence
  • modifiers() — get modifier keywords
  • isNullable() — nullable type check
  • hasUnresolvedReference() — whether a node has an unresolved type reference

Type-info XPath attributes (need auxClasspath + resolved types; absent otherwise):

Attribute Nodes Meaning
@TypeName ClassDeclaration, PropertyDeclaration, ClassParameter, DelegationSpecifier, CatchBlock, ForStatement, SingleAnnotation, UnescapedAnnotation, FunctionValueParameter FQ type name (with generics + nullable marker)
@ReturnTypeName FunctionDeclaration FQ return type name
@AnnotationFqNames ClassDeclaration, FunctionDeclaration, PropertyDeclaration, ClassParameter FQNs of all annotations (always present, empty list if none)

General (structural) XPath attributes — always present, don't depend on type resolution:

Attribute Nodes Meaning
@Identifier ClassDeclaration, FunctionDeclaration, ClassParameter, CompanionObject, VariableDeclaration, ImportAlias Simple name of the declared identifier
@Mutable PropertyDeclaration true/false for var/val
@Name ImportHeader Fully-qualified imported name

Note: modifiers are not exposed as an @Modifiers XPath attribute — use pmd-kotlin:modifiers()
instead. HasModifiers.getModifiers() remains available for Java-based rules.

Also incorporates the #6891 fix (KtModifiers container in AnnotationFqnAnnotator).

KotlinTypeName type abstraction.
Type info is stored as KotlinTypeName objects (PMD-owned, immutable), decoupling the public API
from kotlin-type-mapper, which stays an internal implementation detail. Key members:
getFqName(), isNullable(), isUnresolved(), toDisplayString() (includes generics, e.g.
kotlin.collections.List<kotlin.String>?, powered by kotlin-type-mapper 0.7.1's TypeAst).

Java rules use HasTypeName.getType() / KotlinNodeTypeData.getType(); XPath rules use
@TypeName / @ReturnTypeName directly.

Design notes

  • Null attributes are filtered (KotlinInnerNode.getXPathAttributesIterator): type-info
    attributes return null when they don't apply, so they're absent from XPath rather than
    present-with-null. @AnnotationFqNames, @Identifier, @Mutable, @Name are always present.
  • Unresolved vs. genuinely-none, mirroring pmd-java's isUnresolved(): an absent @TypeName/
    @ReturnTypeName is ambiguous on its own, since a configured auxClasspath doesn't guarantee
    every type resolves. pmd-kotlin:hasUnresolvedReference() disambiguates: true → analysis ran
    but the type couldn't be resolved; false → analysis ran and there's genuinely no such value.
    Doesn't apply to @AnnotationFqNames (always present) or modifiers (absence just means none).
  • Unresolved types still get best-effort names (KotlinTypeName.isUnresolved()), via
    kotlin-type-mapper 0.7.1's TypeAst.isUnresolved() support (Surface best-effort type name for unresolved references stokpop/kotlin-type-mapper#29).

Related issues

Adds 7 XPath functions and type-info attributes to make kotlin-type-mapper
data accessible in XPath rules and the PMD Rule Designer:

XPath functions (pmd-kotlin namespace):
- typeIs(typeName): subtype-aware type match on declaration/parameter/catch/for nodes
- typeIsExactly(typeName): exact declared type match (no subtype widening)
- matchesSig(signature): call-site signature match with _ and .. wildcards
- hasAnnotation(name): simple-name or FQN annotation match on declaration nodes
- isNullable(): true if declared type is nullable (Kotlin ? suffix)
- hasUnresolvedReference(): true if node contains an unresolved reference
- modifiers(): sequence of modifier keywords (suspend, data, override, ...)

New XPath attributes on declaration nodes:
- @typename: FQN of the declared/caught/loop-variable type
- @ReturnTypeName: FQN of the function return type
- @AnnotationFqNames: sequence of annotation FQNs on the declaration
- @modifiers: space-separated modifier keywords
- @Identifier: simple name of the declared identifier

Also fixes AnnotationFqnAnnotator using KtModifier (singular keyword)
instead of KtModifiers (plural container), which prevented @typename
from being set on UnescapedAnnotation/SingleAnnotation nodes (pmd#6891).
@stokpop
stokpop force-pushed the add-kotlin-xpath-type-functions branch from 6c13ed6 to 48f95c9 Compare July 20, 2026 10:13
@pmd-actions-helper

pmd-actions-helper Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Documentation Preview

Compared to main:
This changeset changes 0 violations,
introduces 0 new violations, 0 new errors and 0 new configuration errors,
removes 0 violations, 0 errors and 0 configuration errors.
There are 0 changed duplications, 0 new duplications and 0 removed duplications.
There are 0 changed CPD errors, 0 new CPD errors and 0 removed CPD errors.

Regression Tester Report

(comment created at 2026-09-17 12:04:38+00:00 for ebddae8)

Move shared runXPath(), buildXPathRule(), getResource() and assertion
helpers into a base class, matching pmd-java's BaseXPathFunctionTest
pattern. Also simplify getImage() to return null unconditionally
(deprecated, should not be used).
Add a "Java-based rules" section to kotlin.md showing HasTypeName,
HasModifiers, and KotlinNodeTypeData usage. Note the difference from
pmd-java's richer TypeNode/JTypeMirror approach.
@stokpop
stokpop marked this pull request as ready for review July 20, 2026 12:54
Address review comment from PR pmd#6795: if getCanonicalPath() fails,
the file is inaccessible and analysis will fail later anyway.
Fail fast with UncheckedIOException.
stokpop added 12 commits July 26, 2026 21:26
…f null. Add tests for annotation fully-qualified names in function declarations
- Add HasModifiers to KtClassParameterAttributes (grammar has modifiers?)
- Add HasSimpleIdentifier to KtCompanionObjectAttributes (grammar has simpleIdentifier?)
- Add getAnnotationFqNames() to KtPropertyDeclarationAttributes and
  KtClassParameterAttributes (data was stored by KotlinTypeAnnotationVisitor
  but not exposed as XPath attribute)
- Remove VariableDeclaration and ImportAlias from @modifiers docs table
  (neither has modifiers in the Kotlin grammar)
- Add tests for the new interfaces
The actual signature format (from kotlin-type-mapper's SignatureMatcher)
uses * for any-parameter-list matching, not .. as previously documented.
Also clarify the _ wildcard for receiver and add a (*) example.
These node types are supported by the implementation and listed in the
function's Javadoc but were missing from the user-facing documentation.
The method returns null when type analysis has not run, matching
the pattern used by other nullable-returning methods in this PR.
…eter

- Add HasModifiers to KtPropertyDeclarationAttributes (standard modifiers)
- Add custom getModifiers() to KtFunctionValueParameterAttributes
  (uses parameterModifiers grammar rule: vararg, noinline, crossinline)
- Update @modifiers docs table to list all nodes that now expose it
- Update Simple.txt tree dump reference (private property now shows @modifiers)
- Add tests for both new modifier attributes
…difiers

Help users find the right node: modifiers (private, lateinit, const)
are on PropertyDeclaration, not the child VariableDeclaration.
@stokpop
stokpop force-pushed the add-kotlin-xpath-type-functions branch from ca39fde to 95c5e8d Compare August 20, 2026 15:55
Replace nl.stokpop.kotlin and nl.stokpop.test packages with
net.sourceforge.pmd.lang.kotlin.rule.xpath.typeis (all lowercase)
in test resource .kt files. Rename directory accordingly and update
all references in KotlinTypeIsFunctionTest and KotlinParserTests.
Adapt to TypeAst API: getType(), getReturnType(), and
getArgumentTypes() now return TypeAst objects instead of plain
strings. Use TypeAst.toFqString() for string representation and
TypeAst.isNullable() for direct nullable checks.

New 0.7.0 capabilities available for future use:
- TypeAst.isUnresolved for per-type unresolved detection
- TypeAst.typeArguments for generic type argument queries
- constructorCallsOf/constructorCallsOfSubtype queries
- callsOnReceiverSubtype/callsReturningSubtype polymorphic queries
Adapt to TypeAst API: getType(), getReturnType(), and
getArgumentTypes() now return TypeAst objects instead of plain
strings. Use TypeAst.toFqString() for string representation and
TypeAst.isNullable() for direct nullable checks.

New 0.7.0 capabilities available for future use:
- TypeAst.isUnresolved for per-type unresolved detection
- TypeAst.typeArguments for generic type argument queries
- constructorCallsOf/constructorCallsOfSubtype queries
- callsOnReceiverSubtype/callsReturningSubtype polymorphic queries
Add PMD-owned KotlinTypeName as the internal type representation,
replacing raw String storage in KotlinNodeTypeData. This keeps the
kotlin-type-mapper library as a replaceable implementation detail:

- KotlinTypeName holds fqName, nullable, unresolved, displayString
- Single conversion point in KotlinTypeAnnotationVisitor.toKotlinTypeName()
- XPath functions use KotlinTypeName.isNullable() directly (no string hacks)
- All ktm imports remain confined to internal packages
- Public API (HasTypeName, XPath attributes) still exposes String
- Remove getTypeName()/getReturnTypeName() string wrappers from KotlinNodeTypeData
- HasTypeName now exposes getType() returning KotlinTypeName directly
- KtFunctionDeclarationAttributes adds getReturnType() returning KotlinTypeName
- Add KotlinTypeName.displayStringOf() null-safe helper for XPath string attributes
- KotlinHasAnnotationFunction uses getFqName() directly
- Update docs: KotlinTypeName API examples, generic type argument behavior,
  @typename uses FQNs for generics, typeIs()/typeIsExactly() ignore generics
@stokpop

stokpop commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@adangel when time permits, can you go through the conversations and mark them "resolved" if you agree with the fix and/or approach. Thanks!

@stokpop
stokpop requested a review from adangel September 14, 2026 14:44
Comment thread docs/pages/pmd/languages/kotlin.md Resolved
Comment thread docs/pages/pmd/languages/kotlin.md Resolved
Comment thread docs/pages/pmd/languages/kotlin.md Resolved
Comment thread docs/pages/pmd/languages/kotlin.md Resolved
Comment thread docs/pages/release_notes.md Resolved
Comment thread docs/pages/release_notes.md Resolved
Use xpath code fence and XPath comment syntax for the example; remove
release notes content duplicated from 7.27.0 (Java 27, Apex, Kotlin
type-aware analysis sections, pmd#6747).
stokpop and others added 2 commits September 17, 2026 10:53
Per review (adangel, PR pmd#6893): IndexOutOfBoundsException from
sliceOriginalText() here would only occur if PMD/antlr parsing itself
is buggy (broken text region <-> AST mapping). Swallowing it and
returning null would silently hide such a bug instead of surfacing it.
Confirmed it doesn't occur with the existing test files.

Removed the catch, made the method's return type non-null, updated
Javadoc and the caller (no longer needs a null check).

Co-authored-by: Copilot <[email protected]>
…pe-functions

# Conflicts:
#	docs/pages/release_notes.md
@stokpop

stokpop commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

@adangel I fixed all outstanding issues I am aware of. Please let me know if there are any open issues for this PR that need to be addressed here.

@adangel adangel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good now. Thanks for your patience!
I've also tested the changes together with #6645 and it looks good (once you add back the Identifier attribute).

Note: I'm going to squash-merge this - be aware when updating #6645 ...

What should we do with the deferred items in #6893 (comment)? Should we create an umbrella issue where we collect improvements?

@adangel
adangel merged commit 5bc929e into pmd:main Sep 17, 2026
13 checks passed
@stokpop

stokpop commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

No worries, thanks for the valuable reviews!
Yes, umbrella issue is good I think, we can reference it from PRs or create separate issues to be solved one-by-one later?

@stokpop

stokpop commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

Filed #7091 to track these follow-up points (part of #4339), so they don't get lost.

stokpop added a commit to stokpop/pmd that referenced this pull request Sep 22, 2026
Ports pmd-java's LooseCoupling rule to Kotlin as an XPath rule, flagging
concrete collection/map implementation types (ArrayList, HashMap,
LinkedHashMap, HashSet, LinkedHashSet, TreeMap, TreeSet, Vector, Stack,
Hashtable, LinkedList) used for properties, class/function parameters,
and function return types, in favor of the corresponding interface.

Demonstrates the new pmd-kotlin:typeIs() / typeIsExactly() / modifiers()
XPath functions and @typename / @ReturnTypeName attributes added in pmd#6893.

- Uses typeIs() (subtype-aware) so user-defined subclasses of a concrete
  collection type are also caught.
- Skips local variables (not part of the API surface), including those
  declared inside init {} blocks and secondary constructors, which use a
  plain Block rather than a FunctionBody.
- Skips override-annotated members, matching the Java rule's behavior.
- Skips secondary-constructor parameters, since they aren't currently
  visited by the type-annotation visitor and would otherwise fall back to
  a line-tolerant type lookup that can misattribute an adjacent
  declaration's type.
- Supports an allowedTypes property (default java.util.Properties),
  mirroring the Java rule's property of the same name.

Fixes pmd#7092
stokpop added a commit to stokpop/pmd that referenced this pull request Sep 22, 2026
Ports pmd-java's LooseCoupling rule to Kotlin as an XPath rule, flagging
concrete collection/map implementation types (ArrayList, HashMap,
LinkedHashMap, HashSet, LinkedHashSet, TreeMap, TreeSet, Vector, Stack,
Hashtable, LinkedList) used for properties, class/function parameters,
and function return types, in favor of the corresponding interface.

Demonstrates the new pmd-kotlin:typeIs() / typeIsExactly() / modifiers()
XPath functions and @typename / @ReturnTypeName attributes added in pmd#6893.

- Uses typeIs() (subtype-aware) so user-defined subclasses of a concrete
  collection type are also caught.
- Skips local variables (not part of the API surface), including those
  declared inside init {} blocks and secondary constructors, which use a
  plain Block rather than a FunctionBody.
- Skips override-annotated members, matching the Java rule's behavior.
- Skips secondary-constructor parameters, since they aren't currently
  visited by the type-annotation visitor and would otherwise fall back to
  a line-tolerant type lookup that can misattribute an adjacent
  declaration's type.
- Supports an allowedTypes property (default java.util.Properties),
  mirroring the Java rule's property of the same name.

Fixes pmd#7092
adangel pushed a commit that referenced this pull request Oct 23, 2026
Ports pmd-java's LooseCoupling rule to Kotlin as an XPath rule, flagging
concrete collection/map implementation types (ArrayList, HashMap,
LinkedHashMap, HashSet, LinkedHashSet, TreeMap, TreeSet, Vector, Stack,
Hashtable, LinkedList) used for properties, class/function parameters,
and function return types, in favor of the corresponding interface.

Demonstrates the new pmd-kotlin:typeIs() / typeIsExactly() / modifiers()
XPath functions and @typename / @ReturnTypeName attributes added in #6893.

- Uses typeIs() (subtype-aware) so user-defined subclasses of a concrete
  collection type are also caught.
- Skips local variables (not part of the API surface), including those
  declared inside init {} blocks and secondary constructors, which use a
  plain Block rather than a FunctionBody.
- Skips override-annotated members, matching the Java rule's behavior.
- Skips secondary-constructor parameters, since they aren't currently
  visited by the type-annotation visitor and would otherwise fall back to
  a line-tolerant type lookup that can misattribute an adjacent
  declaration's type.
- Supports an allowedTypes property (default java.util.Properties),
  mirroring the Java rule's property of the same name.

Fixes #7092

* [kotlin] LooseCoupling: refine message/description per review

- Message no longer suggests Mutable* as an equal alternative to the
  read-only interface; that nuance now lives only in the description,
  worded to prefer the read-only interface by default and fall back to
  Mutable* only when mutation is actually needed.
- Description now documents that this rule checks a fixed list of
  common JDK concrete types, unlike pmd-java's LooseCouplingRule, which
  generically flags any concrete Collection/Map implementation. Doing
  the same generically in Kotlin isn't currently possible: ktm only
  exposes interface-vs-class info for declarations found in the
  analyzed Kotlin source, not for external/JDK types resolved via
  classpath. Tracked as a follow-up in #7091.

Deliberately not growing the fixed type list piecemeal with popular
library collection types (Guava Multimap/BiMap/Immutable*, Apache
Commons Collections4, kotlinx.collections.immutable Persistent*,
etc.): several of those are often intentionally exposed as concrete
types to guarantee immutability, so hand-picking more now would create
debatable false positives. Prefer waiting for the generic
isInterface-based check (#7091) to decide "concrete vs. interface" for
any library, rather than expanding this list ad hoc. (Note for PR
description once opened.)

* [kotlin] Document {0} message limitation, add release notes entry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

an:enhancement An improvement on existing features / rules in:xpath Relating to xpath support at large, eg Jaxen / Saxon, custom functions, attribute resolution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants