Repository navigation
Description
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
@TypeNameleaking from first destructured component onto whole declaration node -
Deprecate type info on
PropertyDeclarationin favour ofVariableDeclaration: with the destructuring fix,VariableDeclarationcarries@TypeNamefor every variable (including destructured components and for-loop variables), so the type onPropertyDeclarationis redundant for single variables and absent for destructuring. Keep it working for one release with a migration note, then remove@TypeNameandtypeIs/isNullablesupport 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@TypeNameon theirVariableDeclaration; add a test and update the note inkotlin.mdthat only explicitly typed lambda parameters are covered. -
Type of the implicit lambda parameter
it: there is no declaration node forit, so it has no@TypeName. Options: a lambda-level attribute (e.g.@ItTypeNameonLambdaLiteral) 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
@TypeInfoAvailableboxed-Booleanfix -
For discussion:
typeIs/typeIsExactlytreatkotlin.collections.Mapand
kotlin.collections.MutableMap(andList/MutableList,Set/MutableSet) as equivalent,
since kotlin-type-mapper'stypeNamesEquivalentmaps both to the same JVMjava.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
suggestMapvs.MutableMapbased on actual usage). Needs discussion: keep current
alias-based equivalence and add a separate strict/exact-FQN check for these cases, or change
typeIsExactlysemantics (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 viapmd-kotlin:typeIs(), unlike the Java equivalent
(LooseCouplingRule.java), which generically flags any concreteCollection/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
byReflectionTypeHierarchy.kt's reflection-basedtypeHierarchy, built from real
java.lang.Classsupertype/interface info across the classpath, not just source — that's
already whytypeIs()correctly matches user-defined subclasses of JDK types today). The
missing piece isisInterface(). Feasibility correction: this is a small ktm addition, not
a big one —ReflectionTypeHierarchy.ktalready loads ajava.lang.Classfor every reflected
type;clazz.isInterfaceis a one-line addition there (e.g. record it alongside
typeHierarchy, or expose a newisInterface(fqn): Boolean?query). Once available, expose
it aspmd-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, GuavaImmutable*, Apache Commons
Collections4TreeList, Kotlin's ownkotlinx.collections.immutable
PersistentList/PersistentMap, etc.) in the meantime — several of these (Guava
Immutable*,kotlinx.collections.immutablepersistent 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 theisInterface()-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
@TypeNameattribute? 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 plainBlock, not a
FunctionBody— onlyfunctionDeclaration/getter/setter/anonymous-function bodies use
FunctionBody. Any future rule doing this kind of "is this local?" check needs to also exclude
ancestor::AnonymousInitializerandancestor::SecondaryConstructorexplicitly (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 (
FunctionValueParameterunderSecondaryConstructor) are
not visited/annotated by the type-annotation visitor the wayFunctionDeclarationparameters
are. Because of that,pmd-kotlin:typeIs()/typeIsExactly()on such a parameter falls through
to the line-tolerant (±1line, no column check)declarationsAt()/callSitesAt()lookup,
which can misattribute the type of an unrelated adjacent-line declaration to the parameter.
Reproduced: a secondary constructor'sIntparameter 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
FunctionParameterAnnotatorforFunctionDeclaration), removing the need for rules to work
around this withancestor::FunctionDeclarationguards. - More generally: any XPath rule combining multiple declaration-site node types
(PropertyDeclaration,ClassParameter,FunctionValueParameter,FunctionDeclaration, ...)
into one selector should have explicit regression tests forinitblocks 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):
- Absent attributes in XPath: I've just tested in in the designer. The following works as well
//PropertyDeclaration[data(@Mutable)]or//PropertyDeclaration[not(data(@Mutable))]. We probably should add some hints in the general XPath rule doc, on how to test attributes (probably here: https://docs.pmd-code.org/latest/pmd_userdocs_extending_writing_xpath_rules.html). There are some subtleties for testing sequences and booleans...
Part of #4339
Activity
[-][kotlin] Suppress empty-list attribute values (e.g. @AnnotationFqNames) in tree dumps[/-][+][kotlin] Follow-ups from XPath functions/type attributes PR (#6893)[/+][kotlin] LooseCoupling: refine message/description per review
[kotlin] LooseCoupling: refine message/description per review
[kotlin] Fix #7092: Add LooseCoupling rule (#7094)
adangel commentedon Oct 27, 2026
Thanks for creating the issue. I've just now added my notes to the description.
stokpop commentedon Nov 7, 2026
Re the
ForStatement@TypeNamequestion from the #7168 review: forfor ((number, text) in pairs)it reports the loop element type (kotlin.Pair<kotlin.Int, kotlin.String>), which differs from the component types on theVariableDeclarationnodes. It's what makes//ForStatement[pmd-kotlin:typeIs('kotlin.Pair')]possible, so I'd rather not lose it.The asymmetry with
val (a, b) = pairexists 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 onMultiVariableDeclarationforval,forand lambda destructuring, and then revisitForStatement/PropertyDeclarationconsistently.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
forloops that destructure aPairwould be written as:and the same type is reachable for
val (a, b) = pairand lambda destructuring via//MultiVariableDeclaration[pmd-kotlin:typeIs('kotlin.Pair')]. Today only theForStatementvariant works, as//ForStatement[pmd-kotlin:typeIs('kotlin.Pair')].