Skip to content

[kotlin] Kotlin types support - #6645

Draft
stokpop wants to merge 219 commits into
pmd:mainfrom
stokpop:feature/kotlin-type-mapper
Draft

stokpop wants to merge 219 commits into
pmd:mainfrom
stokpop:feature/kotlin-type-mapper

Conversation

@stokpop

@stokpop stokpop commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Kotlin Types support

As discussed before, being able to work with types in Kotlin would be very beneficial to writing new Kotlin rules.

This PR originated from a proof of concept with a kotlin-type-mapper library. This project uses the embedded Kotlin parser to generate a data structure with types for variables, parameters and call sites. This feature has a dependency on the kotlin-type-mapper jars (released in maven central).

This library is run as a post-processor to the Antlr parser, so the Antr structure is extended with type information.

Also custom pmd-kotlin functions are created, similar to the pmd-java functions like typeIs and matchesSig.

The PMD designer tool now contains extra type and other information running the Kotlin mode, which is very helpful to create new rules.

To check if the type mapping is working and useful, many existing Java rules have been migrated to Kotlin rules. Most in XPath style, but also some more complex ones as Java based rules. Rules have been adapted to Kotlin idiomatic usage where possible. See release notes addition for list of rules.

The consequence of adding the types processing is that a full classpath is needed. If classes are missing an UnresolvedType issue is reported, like in Java.

Testing this new feature against some code bases showed that for large files with certain Antrl prediction paths could end up running forever. A timeout guard with warnings has been implemented.

I realize this is a large amount of changes. These are totally contained in the pmd-kotlin sub project though. I am open to discuss if this is the proper approach and how to proceed forwards. Migrating the rules gave lots of insights and input for design decisions to be made: see DESIGN.md.

Disclaimer: this big PR has been co-authored with copilot-cli and multiple models. I have done my best to review all generated code as if it was my own, but artificial intelligence artifacts might still be present.

Documentation

To try out this Kotlin typed rules with gradle or maven projects, see:

  • docs/run-pmd-with-maven.md — classpath collection via dependency:build-classpath
  • docs/run-pmd-with-gradle.md — classpath collection via Gradle tasks (main + test variants)

Known limitation

// NOPMD and @Suppress are not yet supported for Kotlin (no comment or annotation suppressor implemented). Only violationSuppressRegex / violationSuppressXPath work. See DESIGN.md 12.2.

Related issues

Ready?

  • Added unit tests for fixed bug/feature
  • Passing all unit tests
  • Complete build ./mvnw clean verify passes (checked automatically by github actions)
  • Added (in-code) documentation (if needed)

stokpop and others added 30 commits April 3, 2026 07:54
…unctions

Integrate kotlin-type-mapper to enable type-aware XPath rules in pmd-kotlin.

New XPath functions:
- pmd-kotlin:typeIs(typeName): returns true when a PropertyDeclaration or
  FunctionDeclaration has the given resolved type/return type
- pmd-kotlin:matchesSig(sig): returns true when an expression node is a call
  site matching the given signature pattern

Both functions accept Java FQCNs and Kotlin FQNs interchangeably for well-known
mapped types (e.g. java.lang.String ↔ kotlin.String, java.util.List ↔
kotlin.collections.List).

New classes:
- KotlinTypeAnalysisContext: indexes TypedAst by (absFilePath, line)
- KotlinTypeAnalysisContextHolder: thread-local + global context holder
- KotlinTypeIsFunction: implements pmd-kotlin:typeIs
- KotlinMatchesSigFunction: implements pmd-kotlin:matchesSig

KotlinHandler updated with lazy-init (holder class) pattern to avoid circular
initialization during LanguageRegistry setup.

New rules added to demonstrate the functions:
- AvoidDecimalFormatAsField (errorprone): flags DecimalFormat/ChoiceFormat/NumberFormat
  stored as class-level fields using pmd-kotlin:typeIs
- AvoidRecompilingPatterns (bestpractices): flags Pattern.compile() calls inside
  function bodies using pmd-kotlin:matchesSig

Tests: 7 tests for typeIs, 7 tests for matchesSig covering Java and Kotlin names,
wildcards, negative cases, and static method call matching.

Docs: pmd-kotlin/README-type-analysis.md

Co-authored-by: Copilot <[email protected]>
Local variables inside function bodies ARE supported: they use the same
propertyDeclaration grammar rule as class-level properties, and
kotlin-type-mapper's visitProperty captures all KtProperty nodes
regardless of scope. Remove the false limitation.

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

When KotlinLanguageProcessor writes .kt files to a temp dir for analysis,
the resulting KotlinTypeAnalysisContext is indexed by temp-dir paths.
PMD's FileId.getAbsolutePath() returns the original source path.

Fix: if the full-path lookup misses, fall back to indexing by filename
only (new File(path).getName()), enabling path-agnostic call-site and
declaration lookup.

Co-authored-by: Copilot <[email protected]>
When the PMD Designer parses Kotlin code it calls services().getParser()
directly; launchAnalysis() is never invoked, so annotationVisitor was
always null and @TypeName/@ReturnTypeName were never set.

Fix: in AnnotatingKotlinHandler.getParser(), pass the source text to
annotateIfPossible(). When annotationVisitor is null (Designer mode),
a new runSingleFileAnalysis() method writes the single file to a temp
dir, runs KotlinTypeMapper, builds the context, and returns a fresh
KotlinTypeAnnotationVisitor — exactly the same flow as batch mode but
scoped to one file.

In batch mode the pre-computed annotationVisitor is still used (fast path).

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

- KotlinNode: add TYPE_NAME_KEY, RETURN_TYPE_KEY DataMap keys and
  getTypeName()/getReturnTypeName() default methods, exposing
  @typename and @ReturnTypeName as XPath attributes on all nodes
- KotlinTypeAnnotationVisitor (NEW): walks parsed AST and sets type
  attributes from TypedAst data, matching by filename
- KotlinLanguageModule: override createProcessor() to return
  KotlinLanguageProcessor so type analysis runs automatically
- KotlinTypeIsFunction: fast path via node attributes before fallback
  to KotlinTypeAnalysisContext lookup
- pom.xml: promote kotlin-type-mapper-analyzer from test to compile scope

Co-authored-by: Copilot <[email protected]>
Picks up the fix that recompiles kotlin-type-mapper targeting Java 17
class files, resolving UnsupportedClassVersionError on Java 17 runtimes.

Co-authored-by: Copilot <[email protected]>
…n Designer

In the PMD Designer, TextDocument is created with FileId.UNKNOWN whose
getAbsolutePath() returns '(unknown)'. The previous code used that as
the temp filename, which has no .kt extension. KotlinTypeMapper filters
for .kt files, so it silently skipped the file — the annotation visitor
was never populated, leaving @TypeName/@ReturnTypeName always null.

Fix in annotateIfPossible():
- sanitizeKtFilename(absPath): if the basename ends in .kt use it,
  otherwise fall back to 'snippet.kt'
- runSingleFileAnalysis() now receives the sanitized name and writes
  the temp file with that name
- annotate() is called with the same sanitized name so the filename
  index lookup succeeds

Result: @typename and @ReturnTypeName are now populated on
propertyDeclaration / functionDeclaration nodes in the Designer.

Co-authored-by: Copilot <[email protected]>
pmd-kotlin:matchesSig() previously returned true for any PostfixUnaryExpression
on the same line as a matching call site.  For code like:

    val pattern = Pattern.compile("[a-z]+")

both Pattern.compile("[a-z]+") AND the string literal "[a-z]+" are
PostfixUnaryExpression nodes on the same line, causing the rule to report
both nodes.

Root cause: callSitesAt() returns all call sites near a line; matchesSig()
checked only line, never column.

Fix: when the call site's line matches the context node's begin line exactly,
additionally require that call.getColumn() falls within
[contextNode.getBeginColumn(), contextNode.getEndColumn()].  The string
literal argument starts AFTER the callee column so it is correctly excluded.
The ±1 line fallback is unaffected (different line → no column restriction).

Added tests:
- matchesSigPatternCompileOnlyMatchesCallNotArgument: exactly 1 violation on
  the compile line, not 2
- matchesSigPatternCompileDoesNotMatchUnrelatedCall: unrelated line not matched

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

New XPath function pmd-kotlin:hasAnnotation('ClassName') that returns true
when the context declaration node carries an annotation matching the given
simple or fully-qualified name. Useful on ClassDeclaration, FunctionDeclaration,
PropertyDeclaration, and ObjectDeclaration nodes.

Matching strategy (checked in order):
1. @typename on UnescapedAnnotation child nodes (FQN from kotlin-type-mapper)
2. ANNOTATION_NAMES_KEY comma list stored on the declaration node
3. Source-text fallback via text region (simple names only)

Also fixes aux classpath not being forwarded to kotlin-type-mapper:
- KotlinLanguageModule now overrides newPropertyBundle() to return
  JvmLanguagePropertyBundle, adding the standard 'auxClasspath' property
- KotlinLanguageProcessor reads that property and passes the JAR list to
  KotlinTypeMapper so FQNs can be resolved (e.g. Spring, JPA annotations)

Changes:
- KotlinHasAnnotationFunction.java: new XPath function (3-path matching)
- KotlinTypeAnnotationVisitor.java: extended to handle ClassDeclaration;
  sets @typename on UnescapedAnnotation nodes and ANNOTATION_NAMES_KEY on
  declaration nodes
- KotlinNode.java: adds ANNOTATION_NAMES_KEY, getAnnotationFqNames()
- KotlinHandler.java: registers KotlinHasAnnotationFunction
- KotlinLanguageModule.java: uses JvmLanguagePropertyBundle
- KotlinLanguageProcessor.java: forwards aux classpath to KotlinTypeMapper
- pom.xml: bump kotlin-type-mapper to 0.1.2
- KotlinHasAnnotationFunctionTest.java: 6 tests (simple name, FQN, negative cases)
- AnnotatedEntities.kt: test resource with @entity, @column, @deprecated

Co-authored-by: Copilot <[email protected]>
… is empty

PmdAnalysis propagates the auxiliary classpath via
JvmLanguagePropertyBundle.setClassLoader(), not the AUX_CLASSPATH string
property. The Designer and API use this path, so getAuxClasspathEntries()
was returning an empty list, preventing kotlin-type-mapper from resolving
FQNs for external annotations (e.g. @service → org.springframework...).

Fix: fall back to extracting file:// URLs from the analysis ClassLoader
(which is a URLClassLoader / ClasspathClassLoader) when the string
property is blank.

Co-authored-by: Copilot <[email protected]>
Returns the explicit modifiers of a declaration node as a string sequence,
matching pmd-java:modifiers() usage patterns.

Supported modifiers:
  visibility:   public, private, protected, internal
  inheritance:  abstract, final, open
  class:        data, sealed, enum, inner, value, annotation
  member:       override, lateinit
  function:     suspend, inline, infix, operator, tailrec, external
  property:     const
  parameter:    vararg, noinline, crossinline
  platform:     expect, actual

Implementation walks Modifiers → Modifier → specific sub-rule → terminal
token and returns getText() for each modifier keyword. Annotations in the
modifier list are excluded.

Example XPath:
  //FunctionDeclaration[pmd-kotlin:modifiers() = 'suspend']
  //ClassDeclaration[pmd-kotlin:modifiers() = ('internal', 'abstract')]

Co-authored-by: Copilot <[email protected]>
…fiers()

- Add hasAnnotation() section with matching strategy and classpath note
- Add modifiers() section with full modifier table and examples
- Add auxClasspath configuration instructions (XML + Designer)
- Simplify pre-analysis section (KotlinLanguageProcessor runs automatically)
- Add two new example rules: SpringServiceShouldBeOpen, TransactionalFunctionShouldBeSuspendable
- Update Known Limitations

Co-authored-by: Copilot <[email protected]>
Override getXPathAttributesIterator() in KotlinInnerNode to skip
attributes whose getter returns null. This prevents @typename and
@ReturnTypeName from appearing as empty attributes on every Kotlin
node — they now only appear on nodes that actually have a resolved
type, consistent with how @text only shows on T-prefixed terminal nodes.

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

When a FQN is resolved, also propagate TYPE_NAME_KEY to the parent
KtSingleAnnotation node. This lets users query at the more natural
level: //SingleAnnotation[@typename='org.example.Service'] as well
as //UnescapedAnnotation[@typename='org.example.Service'].

Multi-annotations (@[Ann1 Ann2]) are unchanged: each UnescapedAnnotation
gets its own @typename but the MultiAnnotation wrapper does not.

Co-authored-by: Copilot <[email protected]>
…o panel

- Add getModifiers() to KotlinNode (null default) implemented in KotlinInnerNode;
  returns space-separated keyword modifiers (e.g. 'override suspend') or null
- KotlinInnerNode.getXPathAttributesIterator() skips null-valued attributes so
  @Modifiers/@TypeName/@ReturnTypeName only appear when set (like @text on T- nodes)
- Add KotlinDesignerBindings extending DefaultDesignerBindings:
    pmd-kotlin:modifiers(): (override, suspend)   -- on declaration nodes
    TypeName: org.example.Service                  -- on UnescapedAnnotation / decls
    ReturnTypeName: kotlin.String                  -- on FunctionDeclaration
- Wire KotlinDesignerBindings into AnnotatingKotlinHandler.getDesignerBindings()

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

- Add getXPathAttributesIterator() null-filter to KotlinTerminalNode so T- nodes
  only show @text (the one non-null attribute) in the Designer
- Annotate getAnnotationFqNames() with @NoAttribute so the internal comma-list
  never appears as a node attribute in the Designer or XPath

Co-authored-by: Copilot <[email protected]>
- KotlinTypeAnalysisContext now stores typeHierarchy from TypedAst and exposes
  isSubtypeOf(expected, actual): BFS over transitive supertypes, with Java/Kotlin
  name equivalence at each level. Falls back to exact match when hierarchy is empty.
- pmd-kotlin:typeIs() now uses isSubtypeOf() — matches the declared type or any
  transitive subtype (requires compiled classes on auxClasspath for hierarchy resolution)
- pmd-kotlin:typeIsExactly() is a new function using isTypeEquivalent() — exact match
  only, no hierarchy walk, mirrors pmd-java:typeIsExactly()
- Register typeIsExactly in KotlinHandler
- Add 3 new tests: subtype hierarchy test (skipped when no classpath),
  typeIsExactly positive match, typeIsExactly negative (subtype not matched)
- Add SerializableSubtype.kt test resource

Co-authored-by: Copilot <[email protected]>
…s typeIsExactly

- Explain that all @typename values are K1-compiler-resolved FQNs, not import guesses
- Document why import-based fallback was not implemented (consistency: display must
  match function behaviour; K1 already handles imports correctly)
- Document the * prefix convention difference vs Java (absent attribute vs *marker)
- Add typeIs vs typeIsExactly comparison table

Co-authored-by: Copilot <[email protected]>
Override getMainAttribute() in KotlinDesignerBindings so terminal nodes
display their token text (via getText()) inline next to the node name in
the PMD Designer tree, matching the behaviour users see for Java terminal
nodes. Falls back to DefaultDesignerBindings behaviour for inner nodes.

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

Extend typeIs (and typeIsExactly) to work on three new node types,
matching Java's FormalParameter / catch / enhanced-for parity:

* FunctionValueParameter -- parameter types (e.g. fun foo(map: Map<*,*>))
* CatchBlock             -- caught exception type (catch (e: IOException))
* ForStatement           -- loop variable type (for (item in list))

Implementation:
- KotlinTypeAnnotationVisitor: added visitCatchBlock and visitForStatement
  handlers; extended visitFunctionDeclaration to also walk its
  FunctionValueParameters children and set @typename per position from the
  DeclarationAst.parameters list (no kotlin-type-mapper changes needed).
- KotlinTypeIsFunction: updated Javadoc to list all supported node types.
- KotlinTypeIsFunctionTest: 6 new tests (positive + negative for each node
  type); fixed subtype-hierarchy skip condition to check for the specific
  user-defined type rather than an empty hierarchy map.
- ParameterTypes.kt: new test resource covering all three new cases.
- README-type-analysis.md: updated typeIs table and examples.

Co-authored-by: Copilot <[email protected]>
Extend getMainAttribute() in KotlinDesignerBindings to return @typename
as the inline label for inner nodes that have it set (PropertyDeclaration,
FunctionValueParameter, CatchBlock, ForStatement, annotation nodes, etc.).
Terminal nodes still show @text; nodes without @typename fall back to the
default image-based behaviour.

Co-authored-by: Copilot <[email protected]>
…rs (ClassParameter)

Primary constructor val/var params (e.g. 'class Foo(val name: String)') are
KtClassParameter nodes in the ANTLR AST, not KtPropertyDeclaration. Wire
them up in KotlinTypeAnnotationVisitor so @typename is set and typeIs /
typeIsExactly work on them.

Changes:
- KotlinTypeAnnotationVisitor: new visitClassParameter handler that looks up
  kind='property' entries by line and sets TYPE_NAME_KEY on the node.
- KotlinTypeIsFunction: updated Javadoc to list ClassParameter.
- KotlinTypeIsFunctionTest: 2 new tests (positive + negative).
- PrimaryCtorParams.kt: new test resource.

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

Extend getMainAttribute() to fall through to @ReturnTypeName when @typename
is absent, so FunctionDeclaration nodes display their resolved return type
inline in the PMD Designer tree view.

Co-authored-by: Copilot <[email protected]>
…dentifier child

Add getIdentifier() to KotlinNode (null default) and implement in
KotlinInnerNode by scanning direct children for the first KtSimpleIdentifier
and returning its terminal token text.

This allows simpler XPath:
  //ClassDeclaration[@Identifier='Foo']
instead of:
  //ClassDeclaration/SimpleIdentifier/T-Identifier[@text='Foo']

The attribute is null-filtered (only appears when present) and is shown
inline in the Designer tree as the fallback label when @typename and
@ReturnTypeName are absent.

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

Add new section 'Using Type Data from Java-Based Rules' covering:
- Table mapping each XPath attribute/function to its KotlinNode Java method
- KotlinTypeAnalysisContext null-check guidance
- Three worked examples: parameter type check, annotation check, modifiers check

Also remove the pre-existing duplicate first half of README-type-analysis.md
(the file had two copies of the Functions/TypeNameFormats/SignatureFormat
sections; only the fuller second copy is kept).

Co-authored-by: Copilot <[email protected]>
…e resolution

Add design note explaining why a ContextHolder singleton is needed in Kotlin
PMD while Java PMD does not require one: the ANTLR-based Kotlin AST has no
built-in type resolver, so type data from kotlin-type-mapper is loaded once
and shared via a global/thread-local holder (like Spring SecurityContextHolder).
Also notes the deeper integration path that would require PMD core changes.

Co-authored-by: Copilot <[email protected]>
…eIs via source hierarchy

Fixes typeIs not matching properties with inferred types when the
declared class hierarchy is only in source (no compiled aux classpath).

Changes:
- KotlinTypeAnnotationVisitor.visitClassDeclaration now sets
  @typename = class FQN on ClassDeclaration nodes, and calls
  setDelegationSpecifierTypes() to annotate each supertype entry
- New helpers: setDelegationSpecifierTypes, annotateDelegationSpecifier,
  findUserTypeInDelegationSpecifier — walk the KtDelegationSpecifiers
  subtree and set @typename = supertype FQN on each KtDelegationSpecifier
- Designer tree now shows @typename on class and supertype nodes

Visible effects:
  //ClassDeclaration[@typename='nl.stokpop.kotlin.Simple']  -- matches
  //DelegationSpecifier[@typename='java.io.Serializable']   -- matches
  //PropertyDeclaration[pmd-kotlin:typeIs('java.io.Serializable')]
    matches val myValue = Simple("Hello") (inferred type)

Bump kotlin-type-mapper dependency 0.1.2 -> 0.2.0 (adds superTypes
field to DeclarationAst and source-hierarchy merging in KotlinAnalyzer)

Tests (22 total, +4):
- typeIsMatchesInferredTypeSubtypeViaSourceHierarchy
- typeIsDoesNotMatchUnrelatedInferredType
- classDeclarationHasTypeNameAttribute
- delegationSpecifierHasTypeNameAttribute
- New test resource: InferredTypeSubtype.kt (Foo2 + Simple : Serializable)

Co-authored-by: Copilot <[email protected]>
- Expanded typeIs() function table to list all 6 supported node types
- Expanded matchesSig() description to mention constructor calls (<init>)
- New section '@typename Coverage — which nodes get a type and when':
  * Table of nodes that receive @typename and their value
  * Table of nodes that do NOT (PostfixUnaryExpression, UserType, etc.)
    with 'how to query instead' column
  * Decision guide: typeIs vs matchesSig
  * Inferred-type example (val myValue = Simple("Hello")) with all
    four matching XPath patterns
  * Note on source-hierarchy vs aux-classpath for subtype checking

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

Add four rules to category/kotlin/bestpractices.xml and one to a new
category/kotlin/performance.xml, each ported from their Java equivalent
in the pmd-java module:

  bestpractices.xml:
    - AvoidMessageDigestField  (java/bestpractices.xml)
    - AvoidPrintStackTrace     (java/bestpractices.xml)
    - AvoidStringBufferField   (java/bestpractices.xml)
    - SystemPrintln            (java/bestpractices.xml)

  performance.xml (new file):
    - AvoidCalendarDateCreation (java/performance.xml)

Each rule carries a 'javaEquivalentRule' String property pointing to the
originating Java rule so future updates to the Java rule are easy to
track and propagate.

Rule engine changes:
- KotlinMatchesSigFunction now calls matchesSigPolymorphic (from
  kotlin-type-mapper 0.3.0) instead of matchesSigEquivalent, enabling
  subtype-aware receiver matching (e.g. Exception matches Throwable).
- kotlin-type-mapper bumped to 0.3.0 in pom.xml.

Test coverage:
- KotlinTypeIsFunctionTest: 5 new tests for StringBuffer/MessageDigest fields
- KotlinMatchesSigFunctionTest: 6 new tests for printStackTrace,
  System.out/err println, and Calendar.getInstance

Co-authored-by: Copilot <[email protected]>
…5 new rules

Fix the PmdRuleTst pipeline so rules using pmd-kotlin:typeIs/matchesSig can be
tested via the standard XML test infrastructure without @disabled.

Root cause: PmdRuleTst uses FileId.fromPathLikeString("file") with no .kt extension.
KotlinLanguageProcessor wrote the temp file as-is, so kotlin-type-mapper never
processed it. The annotation visitor and analysis context then could not find type
data for the synthetic "file" path.

Fixes:
- KotlinLanguageProcessor.writeToTempDir: sanitize filename to ensure .kt extension
- KotlinLanguageProcessor.sanitizeKtFilename: append .kt instead of falling back to
  generic "snippet.kt", keeping the name reversible for lookup
- KotlinTypeAnnotationVisitor.annotate: try filename + ".kt" when basename lookup
  fails (handles paths like "/cwd/file" -> looks up "file.kt")
- KotlinTypeAnalysisContext.callSitesAt/declarationsAt: same .kt suffix fallback

Also:
- Remove @disabled from AvoidDecimalFormatAsFieldTest
- Add PmdRuleTst XML test classes + data for: AvoidMessageDigestField,
  AvoidPrintStackTrace, AvoidStringBufferField, SystemPrintln (bestpractices),
  AvoidCalendarDateCreation (performance)
- Each rule has positive cases (violations), negative cases, and Kotlin-idiomatic
  good alternatives (kotlin-logging, runCatching{}, buildString{}, java.time API)
- Escape MessageFormat braces in AvoidStringBufferField message (buildString{})
- Delete orphaned AvoidRecompilingPatterns.xml test data
- Update AvoidPrintStackTrace, AvoidStringBufferField, SystemPrintln descriptions
  and messages with Kotlin-idiomatic suggestions

Co-authored-by: Copilot <[email protected]>
stokpop added 25 commits August 20, 2026 14:28
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.
…pe-mapper

Resolves conflicts between the targeted AttributeView approach (xpath branch)
and the universal base-node attributes (feature branch rules). Restores
getIdentifier() and getModifiers() on KotlinInnerNode so that all 10 Kotlin
rules that reference @Identifier/@modifiers on arbitrary nodes continue to work.
The AttributeView dedup ensures no duplicate attributes.

Also restores: KotlinNodeTextFunction, KotlinIsWithinFunction,
KotlinIsWithinDirectFunction, KotlinInsideLoopFunction,
KotlinHasVariableArgumentFunction registrations in KotlinHandler,
missing type-alias/call-query methods in KotlinTypeAnalysisContext,
and removes duplicate dottedTextOf in KotlinAstUtil.
DoNotExtendJavaLangError: use typeIs() instead of string matching on class
names, reducing false positives from project-local classes with same names.

AddEmptyString: use structural AST matching (first child is StringLiteral
containing "") instead of nodeText() prefix matching, which was brittle
to whitespace variations.

UseLocaleWithCaseConversions: kept NavigationSuffix guard alongside
matchesSig() — it prevents false positives from parent PostfixUnaryExpression
nodes matching the same call site.
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.
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
Fix compilation errors from merging add-kotlin-xpath-type-functions into
feature/kotlin-type-mapper:
- KotlinDesignerBindings: use KotlinTypeName.displayStringOf() + getType()/getReturnType()
- KotlinTypeAnnotationVisitor: TypeAlias handler uses setType() with KotlinTypeName.ofFqName()
- KotlinTypeAnalysisContextTest: getDispatchReceiverType() returns TypeAst in ktm 0.7.0
- KotlinTypeAnnotationVisitorTest: TypeAlias tests use getType() + displayStringOf()
- Add @mutable to the attribute table in kotlin.md (was missing)
- Add note about XPath boolean comparison: use false()/true() functions
- Add @TypeInfoAvailable (KotlinFile root) to attribute table
- Add @name (ImportHeader) to attribute table
- Both were implemented but not listed in the docs table
@stokpop

stokpop commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Note for future reference (found while merging #6893 into this branch just now, commit dd9f3dcdb1):

This branch's KotlinInnerNode has its own base-level getIdentifier() (a generic @Identifier attribute available on any node), which the whole existing Kotlin XPath ruleset here relies on (AvoidRethrowingException, PreserveStackTrace, UseLocaleWithCaseConversions, UseCollectionIsEmpty, etc. all match on @Identifier against arbitrary node types like CatchBlock, NavigationSuffix, PrimaryExpression).

#6893 independently introduced a HasSimpleIdentifier interface (@AttributeView-based) that also exposes @Identifier, but only on specific declaration node types (KtVariableDeclarationAttributes, KtClassDeclarationAttributes, KtFunctionDeclarationAttributes, KtCompanionObjectAttributes, KtClassParameterAttributes, KtImportAliasAttributes).

On node types that have both sources, this throws IllegalStateException: Duplicate XPath attribute name @Identifier ... (the duplicate-attribute-name guard added in #6893 to catch exactly this class of bug). It doesn't show up in #6893 alone since that branch has no base-level getIdentifier().

Fix applied in the merge commit: add "Identifier" to the STANDARD_ATTRIBUTE_NAMES agreeing-value exemption set in KotlinInnerNode.java (same mechanism already used for BeginLine/BeginColumn/EndLine/EndColumn), since both sources compute the same value for these node types.

If this branch is rebased onto a future version of #6893 (e.g. after it lands on main), the same collision will likely reappear and need the same one-line fix — leaving this note so it's not a mystery next time.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[kotlin] Request for an XPath function as simple partial replacement of missing typeIs function [kotlin] Support symbol table and type resolution

2 participants