Skip to content

About

Generate a structured file with type information from the kotlin source code.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Kotlin TypeMapper

Scans Kotlin source files in a Gradle or Maven project and extracts a semantic AST — all declarations (functions, classes, properties, etc.), resolved call sites with full type information, and unresolved references (names the compiler could not bind, typically due to missing classpath dependencies) — serialised to JSON.

Analysis uses the Kotlin K1 analysis API (embedded compiler internals: KotlinCoreEnvironment, TopDownAnalyzerFacadeForJVM) so types are fully resolved, including generics and nullability. A reflection-based type hierarchy is built at analysis time so polymorphic queries work correctly.

K1 vs K2 note: The project compiles with Kotlin 2.x (K2 compiler) but the analysis pipeline used internally is the K1 API, which is deprecated in 2.x in favour of the K2 Analysis API (KaSession/analyze{}). The K1 API still ships in kotlin-compiler-embeddable 2.x and is intentionally kept until a dedicated migration is done.

Subprojects

Module Artifact Purpose
:model kotlin-type-mapper-model Data model, JSON I/O, query extensions, signature matcher
:analyzer kotlin-type-mapper-analyzer Compiler integration, PSI visitors, classpath resolution
:cli (shadow jar) Command-line tool (analyze, load, query)

Build

./gradlew build

The memory-check demo project is downloaded automatically into cli/build/memory-check/ from github.com/stokpop/memory-check on first run and cleaned by ./gradlew clean.

CLI usage

The shadow jar is built to cli/build/libs/kotlin-type-mapper-cli-<version>-all.jar, or download it from the GitHub releases page.

Set up ktm alias

Add an alias so you can type ktm instead of the full java -jar ... invocation.

bash / zsh — add to ~/.bashrc or ~/.zshrc:

alias ktm='java -jar /path/to/kotlin-type-mapper-cli-<version>-all.jar'

fish — add to ~/.config/fish/config.fish:

alias ktm='java -jar /path/to/kotlin-type-mapper-cli-<version>-all.jar'

Replace /path/to/ with the actual path, e.g.:

alias ktm='java -jar ~/tools/kotlin-type-mapper-cli-0.3.0-all.jar'

After adding, reload your shell (source ~/.bashrc) or open a new terminal.

Analyze a project

ktm analyze --output result.json /path/to/src/main/kotlin

Classpath jars are resolved automatically from the nearest Gradle or Maven build.

Step-by-step walkthrough

Step 1 — run analysis

Point the tool at your main Kotlin sources. Classpath is auto-resolved if a gradlew or mvn wrapper is found in an ancestor directory:

ktm analyze --output result.json /path/to/myproject/src/main/kotlin

Output shows how many files were found and how many declarations and call sites were extracted:

Analyzing 413 Kotlin file(s) across 1 source root(s)
Written 16538 declarations, 34793 call sites → result.json

Step 2 — check for unresolved references

ktm query result.json unresolved-references

If types from external libraries could not be resolved (missing from the auto-detected classpath), they appear here.

Step 3 — add missing jars

Re-run analysis with -cp for each missing jar. The flag is repeatable:

ktm analyze --output result.json \
  -cp ~/.m2/repository/javax/persistence/javax.persistence-api/2.2/javax.persistence-api-2.2.jar \
  -cp ~/.m2/repository/org/springframework/spring-context/6.2.10/spring-context-6.2.10.jar \
  /path/to/myproject/src/main/kotlin

Repeat until unresolved-references is empty (or only shows references that are intentionally absent).

Step 4 — run queries

ktm query result.json calls "kotlin.String#trim()"
ktm query result.json calls-polymorphic "kotlin.collections.Collection#size()"
ktm query result.json implementors "java.io.Closeable"
ktm query result.json annotated-with "org.springframework.stereotype.Service"
ktm query result.json calls "kotlin.String#trim()"
ktm query result.json calls-polymorphic "kotlin.collections.Collection#size()"
ktm query result.json implementors "java.io.Closeable"
ktm query result.json annotated-with "org.springframework.stereotype.Service"
ktm query result.json unresolved-references
ktm query result.json unresolved-types
ktm query result.json type-arg-uses "com.example.MyEntity"

All query commands accept --context/-C <N> to show ±N source lines around each match (default 3, pass 0 to suppress). unresolved-references, unresolved-types, and type-arg-uses default to 0.

Unresolved types

When a dependency jar is missing, K1 cannot resolve the type. The TypeAst still carries a best-effort name reconstructed from file imports:

# List declarations with unresolved types
ktm query result.json unresolved-types
# Client.kt:3:13  property  com.example.client  [HttpClient (fqName: org.apache.http.client.HttpClient)]

Type argument queries

Find all declarations and call sites where a specific type appears as a generic type argument:

# Find all uses of MyEntity in generics (List<MyEntity>, Map<String, MyEntity>, etc.)
ktm query result.json type-arg-uses "com.example.MyEntity"

Generic type matching in signatures

Signature patterns support generics with two modes:

  • Exact: include type arguments for exact matching
    calls "java.util.stream.Stream<com.example.Foo>#filter(*)" — only matches Stream<Foo>
  • Erasure: omit type arguments to match any generic instantiation
    calls "java.util.stream.Stream#filter(*)" — matches Stream<Foo>, Stream<Bar>, etc.

Nullable types

K1 preserves the nullable marker (?) in stored receiver and return types. The standard query functions strip it before comparison, so callsOnReceiver("com.example.Dog") matches both Dog and Dog? receivers.

Use --nullable-receiver / --non-null-receiver to distinguish them:

# only calls where the receiver was nullable (safe-call sites: dog?.bark())
ktm query result.json calls "com.example.Dog#bark()" --nullable-receiver

# only calls where the receiver was non-null
ktm query result.json calls "com.example.Dog#bark()" --non-null-receiver

Both flags are also available on calls-polymorphic.

Type aliases

K1 always expands type aliases when recording call site receiver and return types. If your codebase defines typealias MyDog = Dog, call sites with a MyDog receiver are stored with dispatchReceiverType = "com.example.Dog" — not "com.example.MyDog".

Use resolve-alias to find the concrete type, then query by it:

ktm query result.json resolve-alias com.example.MyDog
# com.example.MyDog -> com.example.Dog
# Expanded: com.example.Dog

ktm query result.json calls "com.example.Dog#bark()"

unresolved-references lists all names the Kotlin compiler could not resolve, including wildcard imports from packages absent on the classpath (e.g. import com.example.* when com.example is not on the classpath).

nl/stokpop/memory/HistoReader.kt:86:21  kotlin.collections.List<kotlin.String> → kotlin.collections.List.size(): kotlin.Int
      83:         // 5 elements can be found in java 9+ dumps, example:
      84:         //    4:         88508        2124192  java.lang.String
      85:         // the module is ignored
  >   86:         if (!(split.size == 4 || split.size == 5)) {
      87:             throw InvalidHistoLineException("Cannot read histo line ...")
      88:         }
      89:         val lineNumber = skipLastCharacter(split[0])

Or run analysis via Gradle (uses memory-check as demo target)

./gradlew run

Signature patterns

Queries use PMD-style patterns:

receiverType#methodName(paramType, ...)
Wildcard Meaning
_ any single type or name
* any parameter list
kotlin.String#trim()       exact match
_#trim()                   any receiver
kotlin.String#_()          any method on String
kotlin.String#_(*)         any method, any params

Extension functions are matched by their extension receiver type, not by a type-prefixed name. For fun Dog.fetch() called as dog.fetch():

  • calleeFqName = "com.example.fetch" (package + function name, no Dog in it)
  • extensionReceiverType = "com.example.Dog"

Use the receiver-prefixed signature form — it matches against the extension receiver:

com.example.Dog#fetch()    ✓ matches extension fn via extensionReceiverType
com.example.Dog.fetch()    ✗ no match — calleeFqName is com.example.fetch

callsOnReceiver("com.example.Dog") also finds extension calls since it checks both dispatch and extension receiver fields.

Library usage

Publish to local Maven and add :model + :analyzer as dependencies:

./gradlew publishToMavenLocal
// build.gradle.kts
implementation("nl.stokpop.typemapper:kotlin-type-mapper-analyzer:0.1.0")
import nl.stokpop.typemapper.analyzer.analyzeKotlinProject
import nl.stokpop.typemapper.model.*

// Run analysis (simple: discovers all .kt files under sourceRoot automatically)
val ast: TypedAst = analyzeKotlinProject(
    sourceRoot = File("/path/to/src/main/kotlin"),
    extraClasspath = listOf(File("mylib.jar"), File("build/classes/kotlin/main"))
)

// Or load from JSON
val ast: TypedAst = TypedAstJson.load(File("result.json"))

// Query
ast.callsMatching("_#size()").forEach { println(it) }
ast.callsMatchingPolymorphic("kotlin.collections.Collection#size()").forEach { println(it) }
ast.implementorsOf("java.io.Closeable").forEach { println(it) }
ast.declarationsAnnotatedWith("kotlin.Deprecated").forEach { println(it) }

// Receiver types explained:
//   dispatchReceiverType  — the object a *member* method is called on (TypeAst?)
//                           dog.bark()        → dispatchReceiverType.fqName = "com.example.Dog"
//                           dog?.bark()       → dispatchReceiverType.isNullable = true
//   extensionReceiverType — the object an *extension* function is called on (TypeAst?)
//                           dog.ext()         → extensionReceiverType.fqName = "com.example.Dog"
//                                               dispatchReceiverType  = null
//   returnType            — what the callee declares as its return type (TypeAst)
//                           fun bark(): Dog?  → returnType.fqName = "com.example.Dog", isNullable = true
//
// TypeAst fields: fqName, simpleName, isNullable, isUnresolved, typeArguments
// TypeAst.toFqString() renders back to the legacy string format (e.g. "kotlin.collections.List<kotlin.String>?")
//
// Standard queries strip ? before comparison (match both nullable and non-null).
// Use predicates to filter by nullability:
ast.callsOnReceiver("com.example.Dog")
    .filter { it.dispatchReceiverIsNullable() }   // only dog?.bark() safe-call sites
    .filter { it.returnTypeIsNullable() }          // only calls that may return null

// Type-argument queries: find all uses of a type as a generic argument
ast.declarationsWithTypeArgument("com.example.MyEntity")  // properties like List<MyEntity>
ast.callsWithTypeArgument("com.example.MyEntity")         // calls returning/receiving List<MyEntity>

// Unresolved types: access best-effort name for types the compiler couldn't resolve
val unresolved = ast.declarations().filter { it.type?.isUnresolved == true }
unresolved.forEach { println("${it.fqName}: ${it.type?.simpleName} (fqn: ${it.type?.fqName})") }

// Type aliases — K1 expands aliases in call site types; use alias-aware variants or expandAlias()
// typealias MyDog = Dog  →  dispatchReceiverType is "com.example.Dog", not "com.example.MyDog"
ast.callsOnReceiverAlias("com.example.MyDog")          // expands alias, then matches receiver
ast.callsReturningAlias("com.example.MyDog")           // expands alias, then matches return type
ast.constructorCallsOfAlias("com.example.MyDog")       // expands alias, then matches constructor
ast.callsOnReceiverSubtype(ast.expandAlias("com.example.MyDog"))  // compose for subtype variant
ast.resolveTypeAlias("com.example.MyDog")              // -> "com.example.Dog" (or null if not an alias)
ast.typeAliasChainOf("com.example.A")                  // -> ["com.example.A", "com.example.B", "kotlin.String"]

Output format

{
  "schemaVersion": "2.0",
  "generatedBy": "kotlin-type-mapper",
  "sourceRoot": "/absolute/path/to/src/main/kotlin",
  "typeHierarchy": { "kotlin.collections.List": ["kotlin.collections.Collection", "kotlin.Any"] },
  "files": [
    {
      "relativePath": "Example.kt",
      "packageFqName": "com.example",
      "declarations": [
        {
          "kind": "function",
          "name": "greet",
          "fqName": "com.example.greet",
          "returnType": {
            "fqName": "kotlin.String",
            "simpleName": "String",
            "isNullable": false,
            "isUnresolved": false,
            "typeArguments": []
          },
          "annotations": [],
          "line": 5, "column": 1
        },
        {
          "kind": "property",
          "name": "items",
          "fqName": "com.example.items",
          "type": {
            "fqName": "kotlin.collections.List",
            "simpleName": "List",
            "isNullable": false,
            "isUnresolved": false,
            "typeArguments": [
              { "variance": "invariant", "type": { "fqName": "kotlin.String", "simpleName": "String", "isNullable": false, "isUnresolved": false, "typeArguments": [] } }
            ]
          },
          "line": 7, "column": 1
        }
      ],
      "calls": [
        {
          "calleeFqName": "kotlin.text.trim",
          "dispatchReceiverType": null,
          "extensionReceiverType": { "fqName": "kotlin.String", "simpleName": "String", "isNullable": false, "isUnresolved": false, "typeArguments": [] },
          "returnType": { "fqName": "kotlin.String", "simpleName": "String", "isNullable": false, "isUnresolved": false, "typeArguments": [] },
          "argumentTypes": [],
          "line": 8, "column": 12
        }
      ],
      "unresolvedReferences": [
        {
          "name": "MissingType",
          "line": 3, "column": 8
        }
      ]
    }
  ]
}

TypeAst structure

All type fields (returnType, type, dispatchReceiverType, extensionReceiverType, argumentTypes, parameter types) use the structured TypeAst format:

Field Type Description
fqName String Fully-qualified name; best-effort from imports when unresolved
simpleName String Short class name as written in source
isNullable Boolean True when marked with ?
isUnresolved Boolean True when the type could not be resolved (missing jar)
typeArguments List Generic type arguments with variance

Each type argument has:

Field Type Description
variance Enum invariant, out, in, or star
type TypeAst? The projected type (null for star projections)

Architecture

File Module Role
AstModel.kt :model Data model (TypedAst, FileAst, DeclarationAst, CallSiteAst, …)
TypedAstJson.kt :model JSON serialisation / deserialisation
TypedAstQuery.kt :model Query extensions (callsMatching, implementorsOf, …)
SignatureMatcher.kt :model Pattern-based call-site matching
KotlinAnalyzer.kt :analyzer Compiler setup, semantic analysis, entry point
DeclarationExtractor.kt :analyzer PSI visitor for declarations and annotations
CallSiteExtractor.kt :analyzer PSI visitor for call sites and property reads
ReflectionTypeHierarchy.kt :analyzer Reflection-based type hierarchy builder
ClasspathResolver.kt :analyzer Resolves Gradle/Maven runtime classpath
TypeMapper.kt :cli Clikt 5 CLI (analyze, load, query)

Tests

./gradlew test

Releasing

See RELEASE.md for full release instructions.

License

Apache 2.0 — see LICENSE.

About

Generate a structured file with type information from the kotlin source code.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages