GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [kotlin] Add kotlin-type-mapper infrastructure by stokpop · Pull Request #6795 · pmd/pmd

Conversation

@stokpop

@stokpop stokpop commented Jun 19, 2026 •
edited by adangel
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Summary

Adds infrastructure for Kotlin type resolution via kotlin-type-mapper (v0.6.1). This PR wires up the type-mapper as a pre-analysis pass that annotates AST nodes with resolved type names and annotation FQNs. It is intentionally self-contained — no new XPath-visible functions are added here; those come in a follow-up PR.

What this PR adds

  • KotlinNodeTypeData — public API for reading type names from AST nodes (getTypeName, getReturnTypeName, getAnnotationFqNames, isTypeInfoAvailable). Annotation FQNs stored as List<String>.
  • KotlinTypeAnnotationVisitor — pre-analysis pass driven by KotlinLanguageProcessor that annotates nodes: property types, function return types, function parameters, catch-block types, for-loop variables, delegation specifiers (extends/implements), annotation FQNs, and class declaration FQNs
  • KotlinTypeAwarenessSupport — encapsulates the lifecycle of the pre-analysis pass. When all source files are on disk, uses KotlinTypeMapper.fromPaths() so KTM reads files itself (no duplication of source strings between PMD and the analyser). Falls back to fromSources for the PMD rule test framework (virtual in-memory files). Warn-once logging when auxClasspath is not configured.
  • KotlinTypeAnalysisContext — context object for subtype checks, usable by both XPath functions and Java-based rules (in rule.internal package). Indexed by canonical abs path (disk) or relativePath (in-memory); includes a fail-fast clash detector. Delegates isSubtypeOf to TypedAstHierarchyQueriesKt.isSubtypeOfUpward (ktm) — O(ancestors) walk upward, short-circuits on java.lang.Object/kotlin.Any.
  • AnnotationFqnAnnotator / FunctionParameterAnnotator / DelegationSpecifierAnnotator — helpers for annotation, function-parameter, and supertype annotation

Type data currently exposed on AST nodes (via KotlinNodeTypeData)

Node type Data available
PropertyDeclaration getTypeName
FunctionDeclaration getReturnTypeName, getAnnotationFqNames
FunctionValueParameter getTypeName
ClassParameter getTypeName
ClassDeclaration getTypeName (FQN when package declared), getAnnotationFqNames
CatchBlock getTypeName
ForStatement getTypeName (loop variable)
DelegationSpecifier getTypeName (supertype FQN)

Using type data in a Java-based rule

The power of type resolution is visible when the type is inferred — not written explicitly in the source:

val foo = "hello"   // no `: String` — type only known after compiler inference

A Java-based rule can read the resolved type via KotlinNodeTypeData:

// Example: flag any val/var whose resolved type is kotlin.String
@Override
public Object visit(KotlinParser.KtPropertyDeclaration node, Object data) {
    String typeName = KotlinNodeTypeData.getTypeName(node);
    if ("kotlin.String".equals(typeName)) {
        asCtx(data).addViolation(node);
    }
    return data;
}

KotlinNodeTypeData.isTypeInfoAvailable(rootNode) returns true only when auxClasspath is configured and the pre-analysis pass succeeded; guard on it to avoid false negatives when running without a classpath.

Intentionally out of scope

  • XPath functions (typeIs(), matchesSig(), hasAnnotation(), etc.) — follow-up PR
  • XPath attribute exposure on AST nodes (e.g. @TypeName, @ReturnTypeName) — type data stored in KotlinNodeTypeData is accessible from Java-based rules but not yet from XPath rules or the PMD Rule Designer. Requires adding getTypeName() / getReturnTypeName() methods to AttributeView subclasses (follow-up).
  • Call-site receiver/return queries (callsOnReceiver, callsReturning) and type alias support — deferred to the add-kotlin-typealias-support follow-up PR.

Design note: why plain String types are currently sufficient

From review of #6678: "At some point, rules probably want to query something like 'what are the methods of this type', or 'is this type a subtype of this other type'. Strings are maybe too simple."

KotlinNodeTypeData stores only resolved type names as String — that covers display and exact-match.
Richer queries are handled by KotlinTypeAnalysisContext, built from kotlin-type-mapper's TypedAst in the same pre-analysis pass:

// Subtype check (implements OR extends, transitively) — drives typeIs() in follow-up PR:
ctx.isSubtypeOf("java.util.List", "java.util.ArrayList")   // -> true

// Java <-> Kotlin name equivalence (transparent to rule authors):
ctx.isTypeEquivalent("java.lang.String", "kotlin.String")  // -> true

// Call-site lookup — drives matchesSig() in follow-up PR:
List<CallSiteAst> calls = ctx.callSitesAt(absFile, line);

// Declaration lookup — drives typeIs() on variables/params:
List<DeclarationAst> decls = ctx.declarationsAt(absFile, line);

isSubtypeOf delegates to TypedAstHierarchyQueriesKt.isSubtypeOfUpward (ktm): walks supertypes of actualType upward through the hierarchy graph — O(ancestors) vs downward BFS O(all subtypes).

Engine replaceability: KotlinNodeTypeData (public API) has zero dependencies on kotlin-type-mapper — it stores plain String type names. All coupling to ktm model types (TypedAst, CallSiteAst, DeclarationAst) is confined to the rule.internal package.

K1 vs K2: kotlin-type-mapper 0.6.1 uses the K1 PSI compiler frontend. K2/FIR support is a future concern tracked upstream.

Additional improvements from review (adangel)

  • Removed KotlinTypeAnalysisContextHolder static state — context is now stored per-file on the root KtKotlinFile node via KotlinNodeTypeData, eliminating cross-run leakage when PMD is invoked in parallel.
  • Memory (item 5): prepare() uses KotlinTypeMapper.fromPaths() for disk-backed files — KTM reads files itself, source strings not duplicated between PMD's TextFile and the analyser.
  • Race fix (item 6): annotateIfPossible() single-file branch now uses visitor.getContext() instead of re-reading analysisContext.get(), eliminating the window where a concurrent analysis could overwrite the AtomicReference between set and read.
  • Annotation FQNs as List<String> — ANNOTATION_NAMES_KEY changed from SimpleDataKey<String> (comma-joined) to SimpleDataKey<List<String>>.
  • Removed basename fallback from KotlinTypeAnalysisContext — was never needed (disk paths match exactly; in-memory key equals lookup key). Replaced with a fail-fast clash detector: two files resolving to the same index key throw IllegalStateException immediately.
  • Removed sanitizeKtFilename workaround — root cause fixed: buildSourceMap now keys by getAbsolutePath() (was getFileName()); single-file path uses absPath directly on both sides. Added validateKotlinPath() with fail-fast throw for null/empty absPath.

Tests

  • KotlinTypeAnnotationVisitorTest — covers all annotated node types including delegation specifiers
  • KotlinNodeTypeDataTest — unit tests for DataMap storage/retrieval
  • KotlinAuxClasspathResolverTest — path filtering and property wiring
  • KotlinAuxClasspathIntegrationTest — end-to-end: without auxClasspath org.junit.jupiter.api.Test is unresolved; with junit-jupiter-api JAR on classpath it resolves correctly
  • KotlinTypeAnalysisContextTest — subtype checks, type equivalence, call-site span fields, unknown path returns empty
  • KotlinLanguageProcessorTest — fail-fast validation for null/empty absPath
  • mvn -pl pmd-kotlin verify passes (130 tests + checkstyle)

Related issues

  • See [kotlin] Support symbol table and type resolution #4339

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@pmd-actions-helper

pmd-actions-helper Bot commented Jun 19, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

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-07-18 16:14:25+00:00 for 7657a3a)

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@stokpop stokpop changed the title feat(kotlin): add kotlin-type-mapper standalone infrastructure feat(kotlin): add kotlin-type-mapper infrastructure Jun 20, 2026
@stokpop stokpop changed the title feat(kotlin): add kotlin-type-mapper infrastructure [kotlin] add kotlin-type-mapper infrastructure Jun 20, 2026
@stokpop
stokpop force-pushed the add-kotlin-type-mapper-standalone branch from 7fbd9f2 to 065f02b Compare June 20, 2026 11:26
stokpop added 5 commits June 20, 2026 11:31
@stokpop
feat(kotlin): add KotlinNodeTypeData with package-private setters and…
7ffa75f
… InternalApiBridge

KotlinNodeTypeData stores type-mapper results on AST nodes via DataMap.
Setters are package-private; InternalApiBridge exposes them to callers
outside the types package (e.g. KotlinLanguageProcessor).
@stokpop
feat(kotlin): add KotlinTypeAnalysisContext and holder with kotlin-ty…
286f73b
…pe-mapper deps

Add KotlinTypeAnalysisContext (indexes call sites, declarations, type
hierarchy from TypedAst) and KotlinTypeAnalysisContextHolder (global +
thread-local slots). Add kotlin-type-mapper-model and -analyzer deps.
@stokpop
feat(kotlin): integrate kotlin-type-mapper AST annotation phase
716219c
Add KotlinTypeAnnotationVisitor, AnnotationAttributeAnnotator, and
DelegationSpecifierAnnotator to walk parsed ASTs and set @typename /
@ReturnTypeName attributes on declaration nodes. KotlinLanguageProcessor
now runs kotlin-type-mapper before parsing and annotates each file via
InternalApiBridge; falls back gracefully when no auxClasspath is set.
@stokpop
test(kotlin): expand KotlinTypeAnnotationVisitorTest to full visitor …
b0b2d60
…coverage

9 tests covering all node types with specific type assertions:
PropertyDeclaration, FunctionDeclaration, CatchBlock, ForStatement (loop var
+ collection param), ClassParameter, ClassDeclaration (simple name without
package; FQN with package declaration), annotation FQN. Uses
KotlinParsingHelper for production-like parsing.
@stokpop
fix(kotlin): upgrade ktm to 0.5.1, fix NPE, add missing tests
4de1583
- Upgrade kotlin-type-mapper deps from 0.5.1-SNAPSHOT to 0.5.1
- Add delegation specifier tests (superclass + interface) to KotlinTypeAnnotationVisitorTest
- Add KotlinAuxClasspathIntegrationTest: end-to-end auxClasspath flow
- Remove KotlinNodeTypeDataTest.typeInfoAvailableFalseWhenNotSet (always failed)
- Add KotlinTypeAnalysisContextHolder.clear() to test teardown
- Add kotlin-type-mapper attribution to kotlin.md docs
- Fix NPE in KotlinAuxClasspathResolver when path has no filename component
@stokpop
stokpop force-pushed the add-kotlin-type-mapper-standalone branch from 065f02b to 4de1583 Compare June 20, 2026 11:31
stokpop added 2 commits June 20, 2026 17:38
@stokpop
refactor(kotlin): move KotlinTypeAnalysisContext to rule.internal pac…
c08286f
…kage

Was in rule.xpath.internal, implying XPath-only use. Both classes are
general infrastructure usable by Java-based rules too. Move to rule.internal,
add @experimental @SInCE 7.27.0, add japicmp exclusion for new package.
@stokpop
refactor(kotlin): extract analyzeAndBuildVisitor to remove duplication
59f11df
runTypeAnalysis() and runSingleFileAnalysis() shared identical core logic:
fromSources, context creation, setGlobal/clearGlobal. Extract to private
analyzeAndBuildVisitor(); callers add context-specific debug logging.
This was referenced Jun 20, 2026
Add null-safety annotations to public API; document getSourceRoot() contract stokpop/kotlin-type-mapper#7
Closed
Add built-in isSubtypeOf(String, String) to TypedAst stokpop/kotlin-type-mapper#8
Closed
Document line number semantics for DeclarationAst and CallSiteAst stokpop/kotlin-type-mapper#9
Closed
Expose receiver type and return type on CallSiteAst stokpop/kotlin-type-mapper#10
Closed
Expose typealias resolution chain, not just final resolved type stokpop/kotlin-type-mapper#11
Closed
Support batch/project-wide analysis for cross-file type resolution stokpop/kotlin-type-mapper#12
Closed
K2/FIR compiler frontend support stokpop/kotlin-type-mapper#13
Open
@stokpop
feat(kotlin): upgrade ktm to 0.6.0-SNAPSHOT, use resolveAbsolutePath (p…
260e701
…md#7)

Use TypedAstAccessorsKt.hasSourceRoot(ast) to explicitly distinguish
disk-based analysis (real abs path available) from in-memory analysis
(fromSources, sourceRoot is ""). For in-memory analysis, only the
basename is indexed — no bogus "/" + relativePath key is created.
For disk analysis, TypedAstAccessorsKt.resolveAbsolutePath(ast, file)
provides the canonical abs path.

Document that the basename index is an intentional fallback for cases
where PMD paths differ from ktm paths, and that it is inherently
ambiguous when multiple files share the same filename across packages.
@stokpop stokpop mentioned this pull request Jun 21, 2026
perf: cache reverse index + add upward-BFS isSubtypeOf variant stokpop/kotlin-type-mapper#20
Closed
stokpop added 9 commits June 21, 2026 07:22
@stokpop
refactor(kotlin): store TypedAst in context, delegate isSubtypeOf to …
2e9d409
…ktm (pmd#8)

Store TypedAst in KotlinTypeAnalysisContext and delegate isSubtypeOf() to
TypedAstHierarchyQueriesKt.isSubtypeOf(). Removes the separate typeHierarchy
field; getTypeHierarchy() now delegates to typedAst.getTypeHierarchy().
The empty context (null typedAst) falls back to name-equivalence only.

Note: ktm#20 filed to add a cached upward-BFS variant for better per-node
rule evaluation performance.
@stokpop
docs+test(kotlin): document endLine/endColumn span semantics from ktm…
4cc8a3e
… 0.6.0 (pmd#9)

- Document ktm 0.6.0 line semantics in callSitesAt/callSitesInRange javadoc:
  CallSiteAst.line = callee-name token; endLine/endColumn now available.
- Add compilation-check test asserting getEndLine() >= 0 is readable.
- Add 5 line-number-sensitive tests to KotlinTypeAnnotationVisitorTest covering
  multiline functions, multiple annotations on separate lines, leading blank lines,
  lambdas, and chained calls; each asserts the exact PMD beginLine.
- Document the +/-1 fallback in both lookupByLine and lookupWithFallback: needed
  when ktm reports the annotation line but PMD reports the keyword line.
@stokpop
feat(kotlin): expose callsOnReceiver/callsReturning delegation from k…
50ed3c2
…tm 0.6.0 (pmd#10)

Add callsOnReceiver, callsOnReceiverSubtype, callsReturning, callsReturningSubtype
to KotlinTypeAnalysisContext, delegating to TypedAstCallQueriesKt. These methods use
the dispatchReceiverType and extensionReceiverType fields introduced in CallSiteAst 0.6.0.
Add note to class Javadoc that ktm records concrete expanded types (not alias names).
Tests verify dispatchReceiverType is non-null for method calls and that both
callsOnReceiver and callsReturning find expected call sites.
@stokpop
perf(kotlin): use isSubtypeOfUpward for O(ancestors) hierarchy check …
2dcd241
…(ktm pmd#20)

Switch isSubtypeOf delegation from isSubtypeOf (downward BFS over all subtypes)
to isSubtypeOfUpward (upward walk of actual's supertypes, O(ancestors ~3-10)).
Also gains Object/Any short-circuit added in the same ktm PR pmd#21.
@stokpop
refactor(kotlin): defer call-site queries, use TypedAst direct API (ktm
477e818
pmd#22/pmd#23)

- Remove callsOnReceiver/callsOnReceiverSubtype/callsReturning/callsReturningSubtype
  from KotlinTypeAnalysisContext; deferred to add-kotlin-typealias-support branch
  alongside constructorCallsOf support (ktm pmd#22)
- Use TypedAst.hasSourceRoot() and TypedAst.resolveAbsolutePath(FileAst) directly
  instead of TypedAstAccessorsKt static dispatch (ktm pmd#23)
- Add missing @experimental + @experimental javadoc on KotlinTypeAnnotationVisitor
- Add missing @experimental javadoc on KotlinTypeAnalysisContext/Holder
@stokpop
chore(kotlin): upgrade kotlin-type-mapper to 0.6.0 release
09602dd
@stokpop
refactor(kotlin): simplify KotlinParser usage in annotators
60a1451
@stokpop
Refactor Kotlin type-awareness flow and tighten Kotlin checks
e95b495
@stokpop
Warn once for missing Kotlin aux classpath
cdad9dc
stokpop added 2 commits June 23, 2026 11:05
@stokpop
refactor(kotlin): KotlinTypeAnnotationVisitor: use KotlinTypeAnalysis…
9650c79
…Context instead of TypedAst

Eliminate the duplicate declaration index built inside the visitor.
KotlinTypeAnalysisContext already indexes by abs path, basename, .kt
extension fallback, and +/-1 line tolerance via declarationsAt().

- Constructor: TypedAst -> KotlinTypeAnalysisContext; drop byFilename field
- annotate(): remove filename extraction + byFilename lookup; delegate
  directly to AnnotatingVisitor(ctx, absPath)
- AnnotatingVisitor: take (ctx, absPath); call ctx.declarationsAt(absPath, line)
  instead of lookupWithFallback(byLine, line)
- Remove lookupWithFallback static method (superseded by ctx.declarationsAt)
- Remove now-unused imports: File, ArrayList, Collections, HashMap, Map,
  FileAst, TypedAst
- KotlinTypeAwarenessSupport: pass ctx (not ast) to visitor constructor
@stokpop
fix(kotlin): use ktm fromPaths for disk files; fix AtomicRef race (it…
a3cb36a
…ems 5+6)

Item 5 — memory: KotlinTypeAwarenessSupport.prepare() now passes List<Path> to
KotlinTypeMapper.fromPaths() when all source files are on disk. KTM reads the
files itself, so source strings are not duplicated between PMD's TextFile cache
and the analyser — halves peak memory for disk-backed analysis runs. Designer /
in-memory files fall back to the existing fromSources(Map<String,String>) path.

Item 6 — race: annotateIfPossible() single-file branch previously read back
analysisContext.get() after runSingleFileAnalysis() set it. A concurrent
Designer parse could race between the set and the re-read, stamping the wrong
context on the root node. Fixed by exposing getContext() on
KotlinTypeAnnotationVisitor and using the visitor's own ctx directly.

Also bumps kotlin-type-mapper dependency to 0.6.1-SNAPSHOT (adds fromPaths).
@stokpop

stokpop commented Jun 23, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor Author

Pushed additional commits addressing the remaining non-trivial review items:

Items 1–4 (previous session):

  • Remove KotlinTypeAnalysisContextHolder static state — context now stored on root KtKotlinFile node via KotlinNodeTypeData
  • Delete KotlinTypeXPathTestHelper (only user was the rewritten test)
  • Split AnnotationAttributeAnnotator → AnnotationFqnAnnotator + FunctionParameterAnnotator
  • KotlinTypeAnnotationVisitor constructor now takes KotlinTypeAnalysisContext instead of TypedAst

Items 5+6 (this session):

  • Memory (item 5): prepare() now calls KotlinTypeMapper.fromPaths(List<Path>, List<Path>) when all source files are on disk — KTM reads files itself, so source strings are not duplicated between PMD's TextFile cache and the analyser (peak memory halved for disk-backed runs). Falls back to fromSources for Designer / virtual files.
    • Requires ktm 0.6.1 (PR: feat(api): add fromPaths(List<Path>, List<Path>) companion method stokpop/kotlin-type-mapper#27)
  • Race (item 6): annotateIfPossible() single-file branch used analysisContext.get() after runSingleFileAnalysis() set it; a concurrent Designer parse could race between the set and the re-read. Fixed by exposing KotlinTypeAnnotationVisitor.getContext() and using the visitor's own ctx directly.

The kotlin-type-mapper 0.6.1 lib has been released and is referenced.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

stokpop added 5 commits June 25, 2026 13:58
@stokpop
chore(kotlin): bump kotlin-type-mapper to 0.6.1 (released)
ef2463c
@stokpop
refactor(kotlin): remove basename fallback from analysis context index
a24d1a6
Index by canonical abs path (disk) or relativePath (in-memory) only.
Basename fallback was never needed: disk paths always match (PMD passes
the same paths it got from FS), and in-memory uses the fromSources key
directly. Add fail-fast clash detection so two files mapping to the same
index key throw immediately instead of silently corrupting results.
@stokpop
refactor(kotlin): store annotation FQNs as List<String> instead of co…
1a4267d
…mma-joined String

Addresses adangel review suggestion. SimpleDataKey<List<String>> stores
the list directly; no join on set, no split on get. Remove stale
InternalApiBridge.setAnnotationFqNames bridge method (unused).
@stokpop
refactor(kotlin): remove sanitizeKtFilename workaround; use absPath d…
b62e7d4
…irectly

sanitizeKtFilename silently masked two bugs:
- buildSourceMap keyed by getFileName() (basename) while annotate()
  looked up by getAbsolutePath() — only worked via now-removed basename fallback
- single-file path used a sanitized name inconsistently

Fix: buildSourceMap keys by getAbsolutePath(), single-file path uses
absPath as-is on both sides. Keys always match without fallback.
Add validateKotlinPath() with fail-fast throw for null/empty absPath.
@stokpop
docs(kotlin): update comments — Designer fixed in pmd-designer#376, i…
fdb4404
…n-memory fallback is for test framework only
@stokpop

stokpop commented Jun 25, 2026

Copy link
Copy Markdown
Contributor Author

Update — additional commits addressing remaining review items:

Annotation FQNs as List<String> (adangel suggestion)

  • KotlinNodeTypeData: ANNOTATION_NAMES_KEY changed from SimpleDataKey<String> (comma-joined) to SimpleDataKey<List<String>> — no join on set, no split on get.

Removed basename fallback from KotlinTypeAnalysisContext

  • Files were previously indexed by both canonical abs path and basename, with a basename fallback on lookup. This was never actually needed:
    • Disk mode (fromPaths): PMD passes the same paths KTM canonicalises → abs path always matches
    • In-memory mode (fromSources): key is the relativePath from the sources map, which PMD also uses for lookup — exact match
  • Replaced with a fail-fast clash detector: if two files resolve to the same index key, IllegalStateException is thrown immediately instead of silently corrupting results.

Removed sanitizeKtFilename workaround

  • Root cause fixed: buildSourceMap was keying by getFileName() (basename) while annotate() looked up by getAbsolutePath() — the mismatch only worked via the now-removed basename fallback.
  • Fix: buildSourceMap now keys by getAbsolutePath(); single-file path uses absPath directly on both sides. Keys always match without any fallback.
  • Added validateKotlinPath() with fail-fast throw for null/empty absPath.

Designer fallback clarification

  • pmd-designer#376 is now merged. The !allOnDisk fallback to fromSources is no longer needed for Designer — it is only used by the PMD rule test framework, which supplies Kotlin snippets as virtual in-memory files via RuleTst.runTestFromString (TextFile.forCharSeq with a virtual FileId).

ktm 0.6.1 released

  • pmd-kotlin/pom.xml updated from 0.6.1-SNAPSHOT to 0.6.1.
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@stokpop
stokpop requested a review from adangel June 25, 2026 19:37
@stokpop
Merge remote-tracking branch 'origin/main' into add-kotlin-type-mappe…
fe74400
…r-standalone
@adangel adangel added this to the 7.27.0 milestone Jun 29, 2026
@stokpop

stokpop commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

Hi @adangel, what is best way to proceed?

Should I press resolve button for the fixed items, or will you do that after a re-check of the proposed changes?

All above issues should have been addressed.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

stokpop added 3 commits July 16, 2026 19:12
@stokpop
Merge upstream/main (7.27.0-SNAPSHOT) into add-kotlin-type-mapper-sta…
ede823b
…ndalone

Conflict in docs/pages/release_notes.md: kept Kotlin type-aware analysis entry
(PR pmd#6795 not yet merged), dropped 7.26.0-era entries already released upstream.
@stokpop
[test] use snippet.<ext> filename in RuleTst instead of bare "file"
6ede2b2
Gives the virtual in-memory file a proper language extension so that
kotlin-type-mapper (and other language processors) can identify the
language from the filename during the pre-analysis prepare() step.

Suggested by adangel in PR pmd#6795 review.
@stokpop
[kotlin] remove AtomicReference and single-file fallback from KotlinT…
d8b3f28
…ypeAwarenessSupport

Replace AtomicReference fields with volatile fields — lifecycle guarantees
happen-before between prepare() and annotateIfPossible(), volatile ensures
visibility across threads.

Remove the 'if (visitor == null)' single-file workaround from annotateIfPossible().
Fix the last bypass caller instead: KotlinParsingHelper now overrides doParse()
to call prepareForSingleDocument() before parsing, so KotlinTypeAnnotationVisitorTest
tests go through a proper prepare() step without needing a full PmdAnalysis run.

RuleTst.java was fixed in the previous commit. Designer bypass is addressed
by adangel's pmd-designer#376.

Suggested by adangel in PR pmd#6795 review.
@stokpop

stokpop commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author

Again thanks for the patience @adangel — additional fixes were made after rechecking today:

  • RuleTst.java: virtual snippet file now uses "snippet.<ext>" instead of bare "file", giving it the correct language extension
  • KotlinTypeAwarenessSupport: AtomicReference fields replaced with volatile fields; the if (visitor == null) single-file workaround removed — fixed the last bypass caller (KotlinParsingHelper.doParse()) instead, which now calls prepareForSingleDocument() before parsing so unit tests go through a proper prepare step

The remaining designer bypass (no prepare() call) is addressed by your pmd-designer#376 — this PR depends on that fix being released in the same PMD version.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@stokpop

stokpop commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author

Correction: fields ended up as plain fields (not volatile) — AvoidUsingVolatile dogfood rule fired. The calling order of the surrounding framework ensures no concurrency issues: prepare() completes before launchAnalysis() submits any file-processing tasks to threads, so all writes in prepare() are visible to those tasks. Correct?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@stokpop
[kotlin] use plain fields instead of volatile in KotlinTypeAwarenessS…
df30e32
…upport

Plain fields are sufficient: prepare() completes before launchAnalysis()
submits file-processing tasks to threads, so JMM executor task submission
guarantees visibility. Avoids AvoidUsingVolatile PMD dogfood violation.
@adangel

adangel commented Jul 18, 2026

Copy link
Copy Markdown
Member

The calling order of the surrounding framework ensures no concurrency issues: prepare() completes before launchAnalysis() submits any file-processing tasks to threads, so all writes in prepare() are visible to those tasks. Correct?

That's correct.

The remaining designer bypass (no prepare() call) is addressed by your pmd-designer#376 — this PR depends on that fix being released in the same PMD version.

This is already done, so the designer should now also call the prepare().
I'm not sure yet, whether the auxClasspath configuration fully works (e.g. the language property might not be set correctly even though PMDConfiguration/--aux-classpath is used), I think, the final fix is only in #6859.

stokpop reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

adangel added 2 commits July 18, 2026 17:49
@adangel
[kotlin] Simplifications and fixes from review
117a899
- moving KotlinTypeAnnotationVisitor into internal package
- simplifying implementations of AnnotationFqnAnnotator, DelegationSpecifierAnnotator and FunctionParameterAnnotator
- Correcting `@since` javadoc tags
- add all internal packages to japicmp
@adangel
Merge branch 'main' into pr-6795
b01ac93
adangel
adangel approved these changes Jul 18, 2026
View reviewed changes

@adangel adangel left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Thanks, looks good.

I'll push a few more commits to this branch and merge it afterwards for 7.27.0.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread docs/pages/release_notes.md Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread ...n/src/main/java/net/sourceforge/pmd/lang/kotlin/rule/internal/KotlinTypeAnalysisContext.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/types/FunctionParameterAnnotator.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/types/FunctionParameterAnnotator.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread ...c/main/java/net/sourceforge/pmd/lang/kotlin/types/internal/DelegationSpecifierAnnotator.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/types/KotlinNodeTypeData.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/types/KotlinTypeAnnotationVisitor.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread ...rc/main/java/net/sourceforge/pmd/lang/kotlin/types/internal/KotlinTypeAnnotationVisitor.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread ...rc/main/java/net/sourceforge/pmd/lang/kotlin/types/internal/KotlinTypeAnnotationVisitor.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/KotlinTypeAwarenessSupport.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

@adangel
[doc] Release notes (pmd#6795)
7657a3a
@adangel
adangel merged commit ca57d1e into pmd:main Jul 18, 2026
13 checks passed

Uh oh!

There was an error while loading. Please reload this page.

This was referenced Jul 19, 2026
Streaming per-file analysis API to cut peak memory (K2 follow-up for PMD) stokpop/kotlin-type-mapper#28
Open
[kotlin] AnnotationFqnAnnotator: @TypeName not set on UnescapedAnnotation nodes #6891
Closed
stokpop added a commit to stokpop/pmd that referenced this pull request Jul 20, 2026
@stokpop
[kotlin] Throw on canonicalization failure instead of silent fallback
80f4612
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

stokpop commented Jul 20, 2026

Copy link
Copy Markdown
Contributor Author

@adangel thanks for merging! Found a little bug by merging these changes into the draft "overall" PR, see new issue and PR...

Also, this merge now makes it possible to implement actual useful Kotlin XPath functions (and access in Java based rules): see follow-up PR.

Note I used your valuable comments and commits to extract preferred code and app architecture constructs as input for this new PR.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@adangel adangel mentioned this pull request Sep 17, 2026
[kotlin] Support symbol table and type resolution #4339
Open
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@adangel adangel adangel approved these changes

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

an:enhancement An improvement on existing features / rules

Projects

None yet

Milestone

7.27.0

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@stokpop @adangel
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.