GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||
GeezerVison is showing github.com — [kotlin] Add kotlin-type-mapper infrastructure by stokpop · Pull Request #6795 · pmd/pmd Conversation
|
| 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) |
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.
typeIs(), matchesSig(), hasAnnotation(), etc.) — follow-up PR@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).callsOnReceiver, callsReturning) and type alias support — deferred to the add-kotlin-typealias-support follow-up PR.String types are currently sufficientFrom 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.
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.prepare() uses KotlinTypeMapper.fromPaths() for disk-backed files — KTM reads files itself, source strings not duplicated between PMD's TextFile and the analyser.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.List<String> — ANNOTATION_NAMES_KEY changed from SimpleDataKey<String> (comma-joined) to SimpleDataKey<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 throw IllegalStateException immediately.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.KotlinTypeAnnotationVisitorTest — covers all annotated node types including delegation specifiersKotlinNodeTypeDataTest — unit tests for DataMap storage/retrievalKotlinAuxClasspathResolverTest — path filtering and property wiringKotlinAuxClasspathIntegrationTest — end-to-end: without auxClasspath org.junit.jupiter.api.Test is 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 verify passes (130 tests + checkstyle)
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
Compared to main: (comment created at 2026-07-18 16:14:25+00:00 for 7657a3a) |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
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).
There was an error while loading. Please reload this page.
|
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. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
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
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
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. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…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 |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Correction: fields ended up as plain fields (not volatile) — |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…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(). |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
- moving KotlinTypeAnnotationVisitor into internal package - simplifying implementations of AnnotationFqnAnnotator, DelegationSpecifierAnnotator and FunctionParameterAnnotator - Correcting `@since` javadoc tags - add all internal packages to japicmp
There was a problem 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.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
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. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.