Repository navigation
[kotlin] Add kotlin-type-mapper infrastructure - #6795
Conversation
|
Compared to main: (comment created at 2026-07-18 16:14:25+00:00 for 7657a3a) |
7fbd9f2 to
065f02b
Compare
… 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).
…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.
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.
…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.
- 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
065f02b to
4de1583
Compare
…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.
runTypeAnalysis() and runSingleFileAnalysis() shared identical core logic: fromSources, context creation, setGlobal/clearGlobal. Extract to private analyzeAndBuildVisitor(); callers add context-specific debug logging.
…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.
…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.
… 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.
…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.
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
…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
…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).
|
Pushed additional commits addressing the remaining non-trivial review items: Items 1–4 (previous session):
Items 5+6 (this session):
The kotlin-type-mapper 0.6.1 lib has been released and is referenced. |
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.
…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).
…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.
…n-memory fallback is for test framework only
|
Update — additional commits addressing remaining review items: Annotation FQNs as
Removed basename fallback from
Removed
Designer fallback clarification
ktm 0.6.1 released
|
|
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. |
…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.
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.
…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.
|
Again thanks for the patience @adangel — additional fixes were made after rechecking today:
The remaining designer bypass (no |
|
Correction: fields ended up as plain fields (not volatile) — |
…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.
That's correct.
This is already done, so the designer should now also call the prepare(). |
- moving KotlinTypeAnnotationVisitor into internal package - simplifying implementations of AnnotationFqnAnnotator, DelegationSpecifierAnnotator and FunctionParameterAnnotator - Correcting `@since` javadoc tags - add all internal packages to japicmp
adangel
left a comment
There was a problem hiding this comment.
Thanks, looks good.
I'll push a few more commits to this branch and merge it afterwards for 7.27.0.
Address review comment from PR pmd#6795: if getCanonicalPath() fails, the file is inaccessible and analysis will fail later anyway. Fail fast with UncheckedIOException.
|
@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. |
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 asList<String>.KotlinTypeAnnotationVisitor— pre-analysis pass driven byKotlinLanguageProcessorthat annotates nodes: property types, function return types, function parameters, catch-block types, for-loop variables, delegation specifiers (extends/implements), annotation FQNs, and class declaration FQNsKotlinTypeAwarenessSupport— encapsulates the lifecycle of the pre-analysis pass. When all source files are on disk, usesKotlinTypeMapper.fromPaths()so KTM reads files itself (no duplication of source strings between PMD and the analyser). Falls back tofromSourcesfor 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 (inrule.internalpackage). Indexed by canonical abs path (disk) or relativePath (in-memory); includes a fail-fast clash detector. DelegatesisSubtypeOftoTypedAstHierarchyQueriesKt.isSubtypeOfUpward(ktm) — O(ancestors) walk upward, short-circuits onjava.lang.Object/kotlin.Any.AnnotationFqnAnnotator/FunctionParameterAnnotator/DelegationSpecifierAnnotator— helpers for annotation, function-parameter, and supertype annotationType data currently exposed on AST nodes (via
KotlinNodeTypeData)PropertyDeclarationgetTypeNameFunctionDeclarationgetReturnTypeName,getAnnotationFqNamesFunctionValueParametergetTypeNameClassParametergetTypeNameClassDeclarationgetTypeName(FQN when package declared),getAnnotationFqNamesCatchBlockgetTypeNameForStatementgetTypeName(loop variable)DelegationSpecifiergetTypeName(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:
A Java-based rule can read the resolved type via
KotlinNodeTypeData:KotlinNodeTypeData.isTypeInfoAvailable(rootNode)returnstrueonly whenauxClasspathis configured and the pre-analysis pass succeeded; guard on it to avoid false negatives when running without a classpath.Intentionally out of scope
typeIs(),matchesSig(),hasAnnotation(), etc.) — follow-up PR@TypeName,@ReturnTypeName) — type data stored inKotlinNodeTypeDatais accessible from Java-based rules but not yet from XPath rules or the PMD Rule Designer. Requires addinggetTypeName()/getReturnTypeName()methods toAttributeViewsubclasses (follow-up).callsOnReceiver,callsReturning) and type alias support — deferred to theadd-kotlin-typealias-supportfollow-up PR.Design note: why plain
Stringtypes are currently sufficientKotlinNodeTypeDatastores only resolved type names asString— that covers display and exact-match.Richer queries are handled by
KotlinTypeAnalysisContext, built from kotlin-type-mapper'sTypedAstin the same pre-analysis pass:isSubtypeOfdelegates toTypedAstHierarchyQueriesKt.isSubtypeOfUpward(ktm): walks supertypes ofactualTypeupward 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 plainStringtype names. All coupling to ktm model types (TypedAst,CallSiteAst,DeclarationAst) is confined to therule.internalpackage.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)
KotlinTypeAnalysisContextHolderstatic state — context is now stored per-file on the rootKtKotlinFilenode viaKotlinNodeTypeData, eliminating cross-run leakage when PMD is invoked in parallel.prepare()usesKotlinTypeMapper.fromPaths()for disk-backed files — KTM reads files itself, source strings not duplicated between PMD'sTextFileand the analyser.annotateIfPossible()single-file branch now usesvisitor.getContext()instead of re-readinganalysisContext.get(), eliminating the window where a concurrent analysis could overwrite theAtomicReferencebetween set and read.List<String>—ANNOTATION_NAMES_KEYchanged fromSimpleDataKey<String>(comma-joined) toSimpleDataKey<List<String>>.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 throwIllegalStateExceptionimmediately.sanitizeKtFilenameworkaround — root cause fixed:buildSourceMapnow keys bygetAbsolutePath()(wasgetFileName()); single-file path usesabsPathdirectly on both sides. AddedvalidateKotlinPath()with fail-fast throw for null/empty absPath.Tests
KotlinTypeAnnotationVisitorTest— covers all annotated node types including delegation specifiersKotlinNodeTypeDataTest— unit tests for DataMap storage/retrievalKotlinAuxClasspathResolverTest— path filtering and property wiringKotlinAuxClasspathIntegrationTest— end-to-end: without auxClasspathorg.junit.jupiter.api.Testis unresolved; with junit-jupiter-api JAR on classpath it resolves correctlyKotlinTypeAnalysisContextTest— subtype checks, type equivalence, call-site span fields, unknown path returns emptyKotlinLanguageProcessorTest— fail-fast validation for null/empty absPathmvn -pl pmd-kotlin verifypasses (130 tests + checkstyle)Related issues