summaryrefslogtreecommitdiff
path: root/CLAUDE.md
blob: bdaa44c69f7ed1a366c1ecbdde2779cdf4489114 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## What this is

kotlin-proxy replaces the Kotlin compiler inside an AGP/Gradle build with an
ABI-identical **stub** of `org.jetbrains.kotlin.cli.jvm.K2JVMCompiler` that lives
on the **Kotlin daemon's** classpath. The stub logs every call (and the
compiler arguments it receives) and returns JVM defaults / reflectively-built
real return objects — it does **not** actually compile. This is **pure
replacement**: no passthrough, no fallback. With no overrides implemented
the build is *supposed* to go red; the point is to observe exactly what
AGP/KGP hands the compiler before implementing an alternative compile inside
the stub (the current `doExecutePhased` implementation does exactly that —
it drives a native-image kotlinc — so the test build is green; see Testing).

`README.md` is the deep reference (bytecode format, log format, full option
table). Read it before changing generation behavior.

## Layout

- `tools/gen_class.py` — self-contained Python stub generator (the core). Emits
  `.class` files **directly** (not Java source) by copying the real class's
  erased structure verbatim.
- `tools/gen_jar_lists.py` — regenerates the `jars/*.txt` lists from the local
  Gradle cache (see Building).
- `tools/gen_arg_table.py` + `tools/ArgProbe.java` — generate the CLI
  argument table (`stubs/gen/kotlin/proxy/GeneratedJvmArguments.java`):
  translates the daemon-populated `K2JVMCompilerArguments` into kotlinc CLI
  tokens for the alternative compile. The probe (reflection, no bytecode
  parsing) reads the `@Argument` annotations off the real class — flag
  names, delimiters, deprecated/removed markers, and the defaults the no-arg
  constructor leaves behind — because the flag names are *not* derivable
  from the descriptions (e.g. `-Xdebug` → `enableDebugMode`). The
  `kotlin-compiler-arguments.json` from the
  `kotlin-compiler-arguments-description` Maven artifact (fetched into
  `vendor/` by a curl make target, pinned to `KOTLIN_VERSION`) is only
  cross-checked for coverage.
- `docs/opcodes.html` — JVM bytecode opcode reference. **Consult it whenever
  hand-rolling bytecode in `gen_class.py`** — opcodes like `putstatic` (0xb3)
  and stack peaks are easy to get wrong, and the JVM only complains with an
  inscrutable `VerifyError`.
- `stubs/src/kotlin/proxy/KotlinProxyLog.java` — the logger every generated
  stub calls into.
- `stubs/src/kotlin/proxy/KotlinProxyOverrides.java` — per-method custom return
  values: the extension point for actually *implementing* stub methods.
- `stubs/gen/kotlin/proxy/GeneratedJvmArguments.java` — generated CLI
  argument table (gitignored, see `tools/gen_arg_table.py`).
- `vendor/kotlin-compiler-arguments-description-<v>.jar` — the Maven
  artifact the generator cross-checks against (gitignored, curl-fetched).
- `stubs/src/kotlin/proxy/ProxyPerformanceManager.java` — override support
  class (per-compiler-instance perf manager) returned by the overrides.
- `jars/defs.txt`, `jars/scan.txt`, `jars/fallback.txt`, `jars/.stamp` —
  auto-generated jar list files feeding the generator (one jar path per line,
  `#` = comment); `.stamp` records the versions the lists were generated for.
- `dist/kotlin-proxy-compiler-stubs.jar` — the build artifact (gitignored).
- `test_project/` — a minimal AGP app (AGP 9.4.1, Gradle 9.8.1, Kotlin 2.4.21,
  single file `Hello.kt`) that consumes the jar to prove the stub runs in the
  daemon.

## Building (from repo root; JDK 11+ and Python 3)

```bash
make
```

The Makefile runs the 5 real steps in order:

1. Fetch `vendor/kotlin-compiler-arguments-description-<v>.jar` from Maven
   Central via curl when missing (pinned to `KOTLIN_VERSION`; needs network).
2. Regenerate the CLI argument table
   `stubs/gen/kotlin/proxy/GeneratedJvmArguments.java` when the
   tool/probe/vendor-jar/defs list changed (`tools/gen_arg_table.py`; it
   prints a coverage report both directions — JSON args with no class field
   and vice versa — to stderr).
3. Regenerate `jars/*.txt` via `tools/gen_jar_lists.py` when the pinned
   versions (Makefile vars `KOTLIN_VERSION` / `AGP_VERSION`, kept in sync with
   `test_project/gradle/libs.versions.toml`) drift from `jars/.stamp`. The
   Gradle cache must already hold those versions — run the test_project once
   first (even a red build resolves everything).
4. Generate the stub classes (`tools/gen_class.py`, **wipes** `stubs/classes_min`
   first — put nothing you need there):
   `--seed-only --no-closure --seed '…K2JVMCompiler,…K2JVMCompiler$Companion,…K2JVMCompilerKt'`.
5. Compile the `kotlin.proxy.*` classes **and the generated argument table**
   into the same tree (the `-cp` lets `KotlinProxyOverrides` import real
   compiler types), then package the jar.

The result is 8 class files + manifest: the three seeded stubs plus
`kotlin/proxy/KotlinProxyLog`, `kotlin/proxy/KotlinProxyOverrides`
(+ inner `$Compiler`), `kotlin/proxy/ProxyPerformanceManager`, and
`kotlin/proxy/GeneratedJvmArguments`. The
seed trio are **the only** classes stubbed (the "trio" mode); their
superclasses/interfaces (`CLICompiler`, `K2JVMCompilerArguments`, …) are
*not* stubbed and resolve from the real jars on the daemon classpath.

## Testing / verifying (there is no unit-test suite)

The "test" is the test project. From `test_project/`:

```bash
./gradlew :app:compileDebugKotlin
```

Expected outcome depends on which overrides are implemented: with none, the
build is **red** (`compileDebugKotlin FAILED`, "Internal compiler error" —
the stub returns defaults, so the real compiler machinery fails after
calling into the stub). With the current `doExecutePhased` implementation
(it hands the generated CLI table to a native-image kotlinc), the build is
**green** and the compiled output lands in
`test_project/app/build/intermediates/built_in_kotlinc/…/classes` (e.g.
`…/org/the_jk/testproject/Hello.class`). To confirm the stub actually ran
*inside the out-of-process daemon*, read the marker file
`/tmp/kotlin-proxy-marker.txt` — a daemon run shows thread names
`RMI TCP Connection(N)` and `LOAD …/dist/kotlin-proxy-compiler-stubs.jar`
lines (the trio's `<clinit>`s also `LOAD` `…$Companion`). An
`OVERRIDE <owner>.<member> inst=0x… -> <dump>` line shows a
`KotlinProxyOverrides.invoke` implementation supplied the return value
(`inst` is the receiver instance the method was called on — omitted for
statics). The marker path is fixed regardless of the daemon's working dir,
so it is the reliable proof. The daemon's full argument dump ("Starting
compilation with args: …") lands in `/tmp/kotlin-daemon.*.log`.

Sanity-check generated bytecode with
`javap -c stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class`.
Verify every hand-rolled opcode number and the declared `max_stack` against
`docs/opcodes.html` — the JVM only complains with an inscrutable
`VerifyError`. A small `java -cp dist/…jar:<defs jars>` main that does
`Class.forName` on the trio and constructs it catches verification/linkage
failures in seconds, without a full Gradle build.

Stale daemons hold stale classpaths: `pkill -f 'KotlinCompile[D]aemon'`
(bracket trick so the pattern doesn't match your own shell) before
re-verifying, and `rm /tmp/kotlin-proxy-marker.txt` for a fresh marker.

## Architecture notes (why it works)

- **Bytecode, not source:** emitting Java and fighting `javac`'s generics checker
  is infeasible (erasure bridges the JVM needs for linkage but `javac` rejects).
  So `gen_class.py` copies the real class's erased structure — exact
  super/interfaces, every field, every method (incl. synthetic `$default` and
  erasure bridges) with its exact name + descriptor + access flags — and omits
  the `Signature` attribute entirely (no generics, no clashes). The JVM links by
  name + erased descriptor, both copied verbatim, so the stub is ABI-identical.
- **Straight-line bodies only:** method bodies have no branches, so no
  `StackMapTable` frames are needed. `<clinit>` calls `KotlinProxyLog.loaded`
  and — when the class has a Kotlin companion object — mirrors the real
  `<clinit>`'s `new Companion; dup; aconst_null; invokespecial; putstatic`
  (leaving the static null makes real code touching `<This>.Companion` NPE
  before any stub method is ever called). Constructors call `super()` (enums
  call `Enum.<init>("stub",0)`); concrete
  methods log and then return a default — but reference-class returns
  (except `String`) build an `Object[]` of the call's arguments (primitives
  boxed; `null` when param-less) and ask `KotlinProxyLog.returnValue`, which
  consults `KotlinProxyOverrides.invoke` first (per-method custom
  implementations — the hook for actually *implementing* a stub method with
  real arguments and the receiver — the stub instance the method was called
  on, `null` for statics — so overrides can keep per-instance state) and
  falls back to materializing a *real* instance of the
  declared return type so the daemon can proceed (e.g. `createArguments()`
  yields a real `K2JVMCompilerArguments`).
  Param-less erasure bridges forward to their concrete sibling instead of
  logging+null (the daemon dispatches through bridges).
- **Classpath shadowing (the subtle part):** KGP ≥ 2.3.20 runs JVM compilation
  through the **Build Tools API** by default, and the daemon's JVM classpath is
  the resolved **`kotlinBuildToolsApiClasspath`** configuration (KGP seeds it
  with *regular* deps `kotlin-build-tools-compat` + `kotlin-build-tools-impl`,
  whose transitive closure *is* the compiler — verified on KGP 2.4.21, where
  `config.dependencies` shows exactly those two plus our file dep; the old
  `defaultDependencies` story is stale, and Gradle 9 removed
  `defaultDependencies` from `Configuration` entirely).
  `test_project/app/build.gradle.kts` therefore adds **only** the stub jar as
  a `files(...)` dep (in `afterEvaluate`); Gradle resolves **file-collection
  deps before module deps**, so the stub lands FIRST in the resolved file
  order (observed on the daemon's `--daemon-compilerClasspath`) and the daemon
  loads `K2JVMCompiler` from the stub — no re-declaration of compat/impl.
  Do NOT resolve the configuration at configuration time (no
  `Configuration.files` / `.incoming` access in `afterEvaluate` or earlier):
  AGP's `DependencyResolutionChecks` raises "Configuration
  'kotlinBuildToolsApiClasspath' was resolved during configuration time".
  Declaring a dependency does not resolve — resolution happens at execution
  time when the compile task runs.
  The legacy `kotlinCompilerClasspath` (`runViaBuildToolsApi=false` path,
  removed in KGP 2.5) carries no deps in this setup and is left alone.
  The root `build.gradle.kts` also puts the stub first on the *buildscript*
  classpath, and pins KGP explicitly — AGP 9.x's built-in Kotlin would
  otherwise apply its own pinned KGP version (AGP 9.0 release notes, "Runtime
  dependency on Kotlin Gradle plugin"). All intentional.
- **Why not a `-javaagent` instead (explored, not adopted):** the daemon JVM
  args channel works in this flow — the Gradle property
  **`kotlin.daemon.jvmargs`** (NOT the legacy `kotlin.daemon.jvm.options`)
  reaches the daemon's command line, so a `-javaagent` jar is loaded in the
  daemon and its `ClassFileTransformer` successfully swaps the
  `K2JVMCompiler` trio's bytes. But a transformer is only consulted for class
  files the classloader can actually *find* — it replaces, it cannot ADD.
  The stubs reference `kotlin.proxy.*` support classes that exist nowhere on
  the daemon's classpath, so a swapped `K2JVMCompiler` dies with
  `ClassNotFoundException: kotlin.proxy.KotlinProxyLog`. The agent route
  would need fully self-contained stubs (the `kotlin.proxy.*` logic inlined
  into the trio by `gen_class.py`) before it becomes viable.

## Gotchas

- **Machine-specific absolute paths.** The `jars/*.txt` lists point into this
  machine's Gradle cache — regenerate them with `tools/gen_jar_lists.py`
  (or `make jars`) on another machine or fresh checkout, and fix the hardcoded
  `/home/the_jk/source/kotlin_proxy/dist/…` in `test_project/app/build.gradle.kts`.
- **Version coupling.** The Kotlin/AGP versions live in
  `test_project/gradle/libs.versions.toml` (what the build uses) and
  `KOTLIN_VERSION` / `AGP_VERSION` in the Makefile (what the jar lists are
  generated for) — keep them in sync. The lists themselves are generated, and
  `jars/.stamp` lets the Makefile detect drift and regenerate.
- **`--seed-only` + `--no-closure`** produces exactly the seed set (the daemon
  jar). The default mode is a full transitive closure from the AGP scan jars +
  KGP plugin entry points — a much larger jar; only use it when you actually
  want to stub a broader surface.
- **Build artifacts are gitignored:** `dist/` (whole dir),
  `stubs/classes_min/`, `stubs/gen/` (generated argument table) and
  `vendor/` (curl-fetched Maven artifact) are not tracked. If you need the
  jar and it's missing, run `make` (the arg table and vendor jar are
  regenerated/fetched as needed; the fetch needs network).