Skip to content

[kotlin] Follow-ups from XPath functions/type attributes PR (#6893) #7091

Open

Description

@stokpop

Follow-up ideas noted during review of #6893 ([kotlin] Add XPath functions and type attributes),
intentionally left out of that PR to keep it focused. Tracking issue for #4339.

See discussion: #6893 (comment)

Open points:

  • Suppress empty-list attribute values (e.g. @AnnotationFqNames) in tree dumps

  • Suggestion: KotlinInnerNode / AttributeView - override AttributeView#getXPathAttributesIterator() to return an empty list/filter already there to avoid KotlinInnerNode#STANDARD_ATTRIBUTE_NAMES

  • Expose unresolved reference names (e.g. pmd-kotlin:unresolvedReferenceNames())

  • Fix @TypeName leaking from first destructured component onto whole declaration node

  • Deprecate type info on PropertyDeclaration in favour of VariableDeclaration: with the destructuring fix, VariableDeclaration carries @TypeName for every variable (including destructured components and for-loop variables), so the type on PropertyDeclaration is redundant for single variables and absent for destructuring. Keep it working for one release with a migration note, then remove @TypeName and typeIs/isNullable support there.

  • Bump kotlin-type-mapper once fix: property declaration position and inferred lambda parameters stokpop/kotlin-type-mapper#36 is released (0.7.2, done in [kotlin] Add @TypeName to VariableDeclaration, fix destructuring type leak #7168): it fixes property declaration positions (Property declaration position starts at initializer instead of val keyword stokpop/kotlin-type-mapper#34) and emits lambda parameters with an inferred type (Lambda parameters with inferred type are not emitted stokpop/kotlin-type-mapper#35). Then { x -> ... } lambda parameters get @TypeName on their VariableDeclaration; add a test and update the note in kotlin.md that only explicitly typed lambda parameters are covered.

  • Type of the implicit lambda parameter it: there is no declaration node for it, so it has no @TypeName. Options: a lambda-level attribute (e.g. @ItTypeName on LambdaLiteral) as a stopgap, or typing of expressions/references in general, which would also cover other uses of variables.

  • Support nullable type arguments in generics (e.g. isNullable(0))

  • Merge into draft PR [kotlin] Kotlin types support #6645 once it lands, port @TypeInfoAvailable boxed-Boolean fix

  • For discussion: typeIs/typeIsExactly treat kotlin.collections.Map and
    kotlin.collections.MutableMap (and List/MutableList, Set/MutableSet) as equivalent,
    since kotlin-type-mapper's typeNamesEquivalent maps both to the same JVM java.util.* type.
    Correct for reflection/classpath purposes, but a footgun for rules that need to distinguish
    Kotlin's read-only vs. mutable collection interfaces (e.g. [kotlin] New Rule: LooseCoupling #7092 LooseCoupling, which needs to
    suggest Map vs. MutableMap based on actual usage). Needs discussion: keep current
    alias-based equivalence and add a separate strict/exact-FQN check for these cases, or change
    typeIsExactly semantics (broader impact, would break existing java.util.* <-> kotlin.* matching
    convenience).

  • For discussion: LooseCoupling ([kotlin] New Rule: LooseCoupling #7092) currently checks against a fixed list of common
    JDK concrete collection/map types via pmd-kotlin:typeIs(), unlike the Java equivalent
    (LooseCouplingRule.java), which generically flags any concrete Collection/Map
    implementation (isA(Collection) || isA(Map)) && !isInterface()). A generic Kotlin version
    wouldn't need a new "isA"-style function — typeIs(fqn) already fills that role (it's backed
    by ReflectionTypeHierarchy.kt's reflection-based typeHierarchy, built from real
    java.lang.Class supertype/interface info across the classpath, not just source — that's
    already why typeIs() correctly matches user-defined subclasses of JDK types today). The
    missing piece is isInterface(). Feasibility correction: this is a small ktm addition, not
    a big one — ReflectionTypeHierarchy.kt already loads a java.lang.Class for every reflected
    type; clazz.isInterface is a one-line addition there (e.g. record it alongside
    typeHierarchy, or expose a new isInterface(fqn): Boolean? query). Once available, expose
    it as pmd-kotlin:isInterface(); then LooseCoupling could become
    (typeIs('java.util.Collection') or typeIs('java.util.Map')) and not(isInterface()). Also
    worth considering functional-interface/SAM types so they aren't accidentally swept in when
    this lands.

    Deliberately NOT growing the fixed type list piecemeal with popular library types (Guava
    ArrayListMultimap/HashMultimap/HashBiMap, Guava Immutable*, Apache Commons
    Collections4 TreeList, Kotlin's own kotlinx.collections.immutable
    PersistentList/PersistentMap, etc.) in the meantime — several of these (Guava
    Immutable*, kotlinx.collections.immutable persistent types) are often intentionally
    exposed as concrete return types precisely to guarantee immutability, so a naive addition
    would create debatable false positives. Prefer waiting for the isInterface()-based generic
    check above and letting it decide "concrete vs. interface" for any library, rather than
    hand-picking more types now.

  • Designer integration: the modifiers are currently only displayed on PropertyDeclaration nodes, and not on ClassDeclaration or FunctionDeclaration. There is only one MainAttribute per node, which is then displayed in the AST tree on the right in the Designer. ClassDeclaration and FunctionDeclaration have both an identifier, so that is displayed instead.
    Improvement: add the modifiers (and maybe other info like pmd-kotlin:isNullable and pmd-kotlin:hasUnresolvedReference) to the "AdditionalInfo" section (override method "getAdditionalInfo").

  • Consider UncheckedIOException catching in KotlinTypeAnalysisContext
    See test net.sourceforge.pmd.lang.kotlin.rule.internal.KotlinTypeAnalysisContextTest#fromSkipsFileWhoseAbsolutePathCannotBeCanonicalized. In theory, if there is an I/O error, something is really bad and it is questionable, whether to continue at all.

  • Improve test setup to leverage compiled auxclasspath sources

  • For discussion: Why does ForStatement has a @TypeName attribute? Is this correct? Brought up in #7168.

Lessons learned while building #7092 (LooseCoupling rule) — relevant for future Kotlin rules
and possible function/attribute improvements:

  • not(ancestor::FunctionBody) is not sufficient to detect "this declaration is local, not
    part of the API surface". init { } blocks (AnonymousInitializer) and secondary constructor
    bodies (SecondaryConstructor) both wrap their statements in a plain Block, not a
    FunctionBody — only functionDeclaration/getter/setter/anonymous-function bodies use
    FunctionBody. Any future rule doing this kind of "is this local?" check needs to also exclude
    ancestor::AnonymousInitializer and ancestor::SecondaryConstructor explicitly (or a more
    general "innermost enclosing block is not a class body" check). Worth documenting this gotcha in
    docs/pages/pmd/languages/kotlin.md, since it's non-obvious from the attribute docs alone.
  • Secondary-constructor parameters (FunctionValueParameter under SecondaryConstructor) are
    not visited/annotated by the type-annotation visitor the way FunctionDeclaration parameters
    are. Because of that, pmd-kotlin:typeIs()/typeIsExactly() on such a parameter falls through
    to the line-tolerant (±1 line, no column check) declarationsAt()/callSitesAt() lookup,
    which can misattribute the type of an unrelated adjacent-line declaration to the parameter.
    Reproduced: a secondary constructor's Int parameter got falsely matched against a concrete
    collection type declared on the very next line inside the constructor body. Consider extending
    the type-annotation visitor to cover secondary-constructor parameters directly (mirroring
    FunctionParameterAnnotator for FunctionDeclaration), removing the need for rules to work
    around this with ancestor::FunctionDeclaration guards.
  • More generally: any XPath rule combining multiple declaration-site node types
    (PropertyDeclaration, ClassParameter, FunctionValueParameter, FunctionDeclaration, ...)
    into one selector should have explicit regression tests for init blocks and secondary
    constructors, since these are easy to miss (they're absent from the kotlin.md attribute table
    entirely) and both interact with the "is this local / not part of API surface" and "is this
    node type-annotated at all" assumptions in surprising ways.

Miscellaneous points (not strictly related to kotlin only):

Part of #4339

Activity

  1. changed the title [-][kotlin] Suppress empty-list attribute values (e.g. @AnnotationFqNames) in tree dumps[/-] [+][kotlin] Follow-ups from XPath functions/type attributes PR (#6893)[/+] on Sep 21, 2026
  2. added a commit that references this issue on Oct 23, 2026
  3. adangel commented on Oct 27, 2026

    @adangel
    Member

    Thanks for creating the issue. I've just now added my notes to the description.

  4. stokpop commented on Nov 7, 2026

    @stokpop
    ContributorAuthor

    Re the ForStatement @TypeName question from the #7168 review: for for ((number, text) in pairs) it reports the loop element type (kotlin.Pair<kotlin.Int, kotlin.String>), which differs from the component types on the VariableDeclaration nodes. It's what makes //ForStatement[pmd-kotlin:typeIs('kotlin.Pair')] possible, so I'd rather not lose it.

    The asymmetry with val (a, b) = pair exists because kotlin-type-mapper emits no entry for the destructured value as a whole, only its components. I opened stokpop/kotlin-type-mapper#37 for that. The plan is to expose that type on MultiVariableDeclaration for val, for and lambda destructuring, and then revisit ForStatement/PropertyDeclaration consistently.

    If you are open to it, we could also get this in as a follow-up PR in the current release cycle, once the ktm change is released. No problem at all if it ends up in a later release.

    With that in place, finding all for loops that destructure a Pair would be written as:

    //ForStatement/MultiVariableDeclaration[pmd-kotlin:typeIs('kotlin.Pair')]
    

    and the same type is reachable for val (a, b) = pair and lambda destructuring via //MultiVariableDeclaration[pmd-kotlin:typeIs('kotlin.Pair')]. Today only the ForStatement variant works, as //ForStatement[pmd-kotlin:typeIs('kotlin.Pair')].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions