Skip to content

Commit c4e54be

Browse files
fix: no false KOIN-D002 on a Koin built elsewhere (#58), no false KOIN-D006 on activityViewModel (#121) (#136)
* fix: judge a call site only when its Koin isn't provably foreign (#58) A `get<T>()` was judged against whatever koinApplication/startKoin the compilation declared, even on a Koin built elsewhere: a shared test fixture's instance, a parameter, a stored property. That gave false KOIN-D002, mostly in test source sets (#58). Every call site is still judged exactly as before, except: - Koin.get/inject/Scope.get on a Koin that is provably foreign: a function parameter, a lateinit var, a property with a custom getter or by lazy, or a non-Koin function's result (an overridden getKoin(), a fixture's koin). Seen through val, casts and !!; a plain val is followed to its initializer, so `val appKoin = startKoin { }.koin` stays judged. - global resolvers (KoinComponent, Compose, Android, Ktor), when every entry point is a plain koinApplication { } (a test fixture or a preview). Such a call site that would have been KOIN-D002 is neither an error nor a hint; one KOIN-W009 per compilation counts them. An unrecognised shape keeps the old behavior: at worst an old false D002, never a lost error. Behavior change: `fun f(koin: Koin) = koin.get<X>()` in an app module, with X defined nowhere, now gives KOIN-W009 instead of KOIN-D002. Known limit: a judged call site is still checked against every graph of the compilation, merged (documented). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: no false KOIN-D006 on activityViewModel, which reuses the activity's instance (#121) activityViewModel / getActivityViewModel / koinActivityViewModel return the ViewModel the activity created with its own parametersOf, so a missing parametersOf there is not an error: - a call site in the same compilation creates that ViewModel with parametersOf → nothing reported; - none does → new KOIN-W010 warning. The creator is often in another Gradle module (activity in :app, fragment in :feature), so this can't be D006; if nothing creates it first, this call creates it without parameters and fails at runtime. KOIN-D005 (wrong parametersOf) and the missing-type check are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 50f4d3e commit c4e54be

61 files changed

Lines changed: 1721 additions & 5 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎RELEASE_NOTES_1.2.2.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@ Compile safety on Kotlin/Native and wasm/JS now sees your whole graph.
33
## 🐛 Fixed
44

55
- On Kotlin/Native, wasm and JS, definitions from another Gradle module were invisible to compile safety: `@ComponentScan` classes, DSL definitions, `@InjectedParam` shapes and deferred call sites. You got a false `KOIN-D002` on valid code, or a real missing dependency passed the build. Always the case on Kotlin 2.4.20, and on earlier versions for modules without `@Configuration` (#105, #106, #113). If you turned `compileSafety` off for your Native or wasm targets, turn it back on. JVM and Android were not affected.
6+
- False `KOIN-D002` on `koin.get<T>()` when that `Koin` was built elsewhere: by a test helper, received as a parameter, or held in a property. It was checked against the graph of an unrelated `koinApplication { }` in the same compilation, which mostly hit test source sets (#58).
7+
- False `KOIN-D006` on `activityViewModel<T>()` for a ViewModel with `@InjectedParam`: it reuses the instance the activity created with `parametersOf()` (#121). When nothing in the module creates it that way, you get the new `KOIN-W010` warning instead.
68

79
## 🔧 Changed
810

911
- **Real errors now reported on Native and wasm/JS.** Missing dependencies, missing `parametersOf()` and deferred call sites are now checked the same way as on JVM. A build that was green on these targets can now fail on a real problem.
1012
- **New `KOIN-W008` warning.** When the plugin can't see a module's definitions, it now says so and names the module instead of skipping the check silently. Typical causes: the module was built with an older plugin version, its `@ComponentScan` matches nothing, or it is not a direct dependency. This applies to every target, JVM included, and fails builds that use `allWarningsAsErrors`.
13+
- **New `KOIN-W009` warning, and one fewer error.** A call on a `Koin` that comes from your own code (a function parameter, a property of your class, a helper's instance) is no longer checked against this compilation's graph. When its type is defined nowhere in the compilation, one warning per compilation counts these calls instead of failing the build. So `fun f(koin: Koin) = koin.get<X>()` in your app module, with `X` undefined, now gives `KOIN-W009` instead of `KOIN-D002`. Calls through `KoinComponent`, `getKoin()`, `koinInject` or `by inject()` are still checked where `startKoin` is called.
14+
- **New `KOIN-W010` warning** on `activityViewModel<T>()` without `parametersOf()` when nothing in the module creates `T` with `parametersOf()` (see Fixed). Both new warnings fail builds that use `allWarningsAsErrors`.
1115
- **KMP libraries checking their KLIB ABI** (`apiCheck`) will see new `org.koin.plugin.hints` entries once. Run `apiDump`. These hints were always meant to be published; on JVM they already were.
1216

1317
## ✅ Compatibility

‎docs/COMPILE_TIME_SAFETY.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,34 @@ or a module class off the classpath). Compile-time dependency checks are skipped
133133

134134
Usual causes: the dependency was built by an older plugin version, its `@ComponentScan` matches nothing, or the module sits more than one `implementation` hop away. Rebuild it with the same plugin version, or add it as a direct dependency.
135135

136+
### Which call sites are judged
137+
138+
Every call site is judged against this compilation's graph, except two cases:
139+
140+
| Call site | Judged here when |
141+
|---|---|
142+
| `koin.get()` / `koin.getScope(..).get()` on a `Koin` that comes from outside Koin's API: a function parameter, a `lateinit var`, a property with a custom getter or `by lazy`, a function of your own (`TestFixture().koin`, an overridden `getKoin()`) | never — the same shape holds your app's Koin or a test helper's, so its graph is unknown here |
143+
| `KoinComponent.get()` / `by inject()`, `koinInject()`, `koinViewModel()`, Android `viewModel()`, Ktor | unless every entry point here is a plain `koinApplication { }` (a test fixture, a preview) |
144+
145+
Everything else is judged as before, including `get()` in a definition lambda, `koinApplication { }.koin`, a `val` initialized with `startKoin { }.koin`, `getKoin()` and `with(koin) { }`.
146+
147+
A call site that isn't judged here and whose type nothing in this compilation defines is not an error. It is never dropped silently: one `KOIN-W009` per compilation counts them.
148+
149+
```
150+
[Koin][KOIN-W009] 3 call site(s) not validated at compile time (first: get<Clock>()): their type is
151+
not defined in this compilation, and they resolve on a Koin instance whose modules it can't see.
152+
They are only checked at runtime.
153+
```
154+
155+
Known limit: a judged call site is checked against every graph the compilation builds, merged. With two `koinApplication { }` blocks in one compilation, `a.koin.get<T>()` passes when only the other one provides `T`.
156+
157+
### `activityViewModel()` and `parametersOf`
158+
159+
`activityViewModel<T>()` returns the instance the activity created. When `T` has `@InjectedParam` and the call passes no `parametersOf(...)`:
160+
161+
- a call site in the same module creates `T` with `parametersOf(...)` → nothing reported;
162+
- none does → `KOIN-W010`. The creator may be in another module; if nothing creates `T` first, this call creates it without parameters and fails at runtime.
163+
136164
## External Types: `@Provided` and Whitelist
137165

138166
Some types are provided by the platform or framework at runtime (e.g., Android's `Context`, `SavedStateHandle`) and are never declared as Koin definitions. Without special handling, these would trigger false "missing dependency" errors.

‎koin-compiler-plugin/src/org/koin/compiler/plugin/KoinAnnotationFqNames.kt‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,9 @@ object KoinAnnotationFqNames {
220220
// the gap) — found via the app-dsl playground's own AnalyticsModule.kt.
221221
val SCOPE_GET = FqName("org.koin.core.scope.Scope.get")
222222

223+
// Receiver type of `koin.getScope(..)` — a scope opened on a foreign Koin is foreign (#58).
224+
val KOIN_CLASS = FqName("org.koin.core.Koin")
225+
223226
// --- android ---
224227
val ANDROID_COMPONENT_GET = FqName("org.koin.android.ext.android.get")
225228
val ANDROID_COMPONENT_INJECT = FqName("org.koin.android.ext.android.inject")
@@ -234,6 +237,11 @@ object KoinAnnotationFqNames {
234237
val KTOR_GET = FqName("org.koin.ktor.ext.get")
235238
val KTOR_INJECT = FqName("org.koin.ktor.ext.inject")
236239

240+
/** Return a ViewModel the activity already created with its own parameters (#121). */
241+
val REUSED_INSTANCE_RESOLUTION_FUNCTIONS = setOf(
242+
ANDROID_ACTIVITY_VIEW_MODEL, ANDROID_GET_ACTIVITY_VIEW_MODEL, KOIN_ACTIVITY_VIEW_MODEL_COMPOSE,
243+
)
244+
237245
/** All call-site resolution functions for A4 validation. */
238246
val CALL_SITE_RESOLUTION_FUNCTIONS = listOf(
239247
// compose

‎koin-compiler-plugin/src/org/koin/compiler/plugin/KoinDiagnostic.kt‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,41 @@ sealed class KoinDiagnostic(
423423
"or add it as a direct dependency.",
424424
)
425425

426+
/**
427+
* KOIN-W009 — Call sites this compilation can't judge (#58): a `Koin` it can't trace to its
428+
* entry point (a parameter, a property, a helper's instance), or the global context while only
429+
* an isolated `koinApplication { }` / `koinConfiguration { }` is declared here. Only those that
430+
* would otherwise be KOIN-D002 are counted: judging them against this compilation's graph gave
431+
* false errors, and skipping them must never be silent. One per compilation, at the first one.
432+
*/
433+
class UntracedCallSites(
434+
count: Int,
435+
first: String,
436+
) : KoinDiagnostic(
437+
code = "KOIN-W009",
438+
severity = Severity.WARNING,
439+
message = "$count call site(s) not validated at compile time (first: $first): their type is " +
440+
"not defined in this compilation, and they resolve on a Koin instance whose modules it " +
441+
"can't see. They are only checked at runtime.",
442+
)
443+
444+
/**
445+
* KOIN-W010 — `activityViewModel<T>()` without `parametersOf`, for a T with `@InjectedParam`, and
446+
* no call site in this compilation creates T with `parametersOf` (#121). Reuse of the activity's
447+
* instance is fine; creating T here would crash. The creator may sit in another module, so this
448+
* can't be KOIN-D006.
449+
*/
450+
class UnverifiedReusedInstanceParams(
451+
target: String,
452+
callFn: String,
453+
) : KoinDiagnostic(
454+
code = "KOIN-W010",
455+
severity = Severity.WARNING,
456+
message = "$callFn<${target.substringAfterLast('.')}>() has no parametersOf(...) and no call site " +
457+
"in this module creates $target with parametersOf(...). Fine if the activity creates it first; " +
458+
"otherwise it is created here without its @InjectedParam values and fails at runtime.",
459+
)
460+
426461
/** KOIN-A001 — `@KoinViewModel` used without `io.insert-koin:koin-core-viewmodel`. */
427462
class MissingViewModelArtifact(
428463
def: String,

‎koin-compiler-plugin/src/org/koin/compiler/plugin/ir/CallSiteValidator.kt‎

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,22 @@ class CallSiteValidator(private val context: IrPluginContext) {
8585
// CompileSafetyValidator's class doc). Defaults to true so existing callers/tests that
8686
// don't pass it keep today's behavior.
8787
hasKoinEntryPoint: Boolean = true,
88+
globalContextBuiltHere: Boolean = true,
8889
) {
8990
val hasFullGraph = assembledGraphTypes.isNotEmpty()
9091

92+
// #58: a call site whose Koin doesn't come from a graph this compilation builds is never
93+
// judged here. Those that would have been KOIN-D002 are disclosed by one KOIN-W009 instead.
94+
// Known limit: a judged call site is still checked against every graph of the compilation.
95+
fun judgedHere(callSite: PendingCallSiteValidation) = !hasKoinEntryPoint || when (callSite.receiver) {
96+
CallSiteReceiver.GRAPH_BOUND -> true
97+
CallSiteReceiver.GLOBAL -> globalContextBuiltHere
98+
CallSiteReceiver.FOREIGN -> false
99+
}
100+
val notValidatedHere = mutableListOf<PendingCallSiteValidation>()
101+
// #121: an activity-scoped ViewModel is only reused if some call site created it with parametersOf.
102+
val createdWithParameters = callSites.filter { it.hasParametersLambda }.mapTo(mutableSetOf()) { it.targetFqName }
103+
91104
// Discover DSL definitions from dependency hints (cross-module DSL discovery).
92105
// Always merge: A3's assembled graph only contains @Module classes' definitions, not
93106
// DSL definitions loaded via `modules(dslModule)` from upstream modules. The hints
@@ -136,10 +149,12 @@ class CallSiteValidator(private val context: IrPluginContext) {
136149
continue
137150
}
138151

152+
val judged = judgedHere(callSite)
153+
139154
// Check assembled graph + DSL definitions + DSL hints
140155
if (callSite.targetFqName in allKnownTypes) {
141156
KoinPluginLogger.debug { "A4: OK ${callSite.callFunctionName}<${callSite.targetFqName}>() — found in graph" }
142-
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints)
157+
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints, createdWithParameters)
143158
continue
144159
}
145160

@@ -151,13 +166,13 @@ class CallSiteValidator(private val context: IrPluginContext) {
151166
}
152167
if (hasAnnotation) {
153168
KoinPluginLogger.debug { "A4: OK ${callSite.callFunctionName}<${callSite.targetFqName}>() — has definition annotation" }
154-
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints)
169+
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints, createdWithParameters)
155170
continue
156171
}
157172
}
158173

159174
// Not resolved locally
160-
if (!hasFullGraph || topologyUnverifiable) {
175+
if (!hasFullGraph || topologyUnverifiable || !judged) {
161176
// Defer external types (from dependency JARs) — they may be defined in a downstream
162177
// module. Also defer when this compilation has no Koin entry point at all: a leaf
163178
// has no assembled graph to judge a local type against either, so treat it the same
@@ -167,14 +182,21 @@ class CallSiteValidator(private val context: IrPluginContext) {
167182
// A local class / anonymous object is never deferred: no other module can provide it,
168183
// and it can't be written into a hint (#101) — KOIN-D002 right here instead.
169184
val isExternalType = callSite.targetClass.origin == IrDeclarationOrigin.IR_EXTERNAL_DECLARATION_STUB
170-
val isDeferrable = callSite.targetClass.isNameableCrossModule() &&
185+
val isNameable = callSite.targetClass.isNameableCrossModule()
186+
val isDeferrable = isNameable && (!hasFullGraph || topologyUnverifiable) &&
171187
(isExternalType || dslDefinitions.isEmpty() || !hasKoinEntryPoint || topologyUnverifiable)
172188
if (isDeferrable) {
173189
unresolvedCallSites.add(callSite)
174-
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints)
190+
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints, createdWithParameters)
175191
KoinPluginLogger.debug { "A4: Deferred ${callSite.callFunctionName}<${callSite.targetFqName}>() — will generate call-site hint (external=$isExternalType, hasEntryPoint=$hasKoinEntryPoint, topologyUnverifiable=$topologyUnverifiable)" }
176192
continue
177193
}
194+
if (isNameable && !judged) {
195+
notValidatedHere.add(callSite)
196+
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints, createdWithParameters)
197+
KoinPluginLogger.debug { "A4: Not validated ${callSite.callFunctionName}<${callSite.targetFqName}>() — receiver ${callSite.receiver}, graph not visible here" }
198+
continue
199+
}
178200
}
179201

180202
// Report error — full graph available (or local type with local definitions), and this
@@ -189,6 +211,17 @@ class CallSiteValidator(private val context: IrPluginContext) {
189211
)
190212
}
191213

214+
val untraced = notValidatedHere.distinctBy { Triple(it.filePath, it.line, it.column) }
215+
untraced.firstOrNull()?.let { first ->
216+
KoinPluginLogger.report(
217+
KoinDiagnostic.UntracedCallSites(
218+
count = untraced.size,
219+
first = "${first.callFunctionName}<${first.targetFqName.substringAfterLast('.')}>()",
220+
),
221+
first.filePath, first.line, first.column
222+
)
223+
}
224+
192225
// Generate call-site hints for unresolved types (deferred validation)
193226
if (unresolvedCallSites.isNotEmpty()) {
194227
KoinPluginLogger.debug { "Phase 3.5: Generating ${unresolvedCallSites.size} call-site hints for deferred validation" }
@@ -607,16 +640,28 @@ class CallSiteValidator(private val context: IrPluginContext) {
607640
* Decision matrix:
608641
* slots == null → def doesn't need params (or unknown) → no report
609642
* !hasParametersLambda → user forgot `parametersOf` entirely → KOIN-D006
643+
* (`activityViewModel` reuses an instance, #121: nothing if a call
644+
* site creates it with parametersOf, else KOIN-W010)
610645
* parametersOfArgs == null → trailing lambda was non-trivial → ambiguous, no report
611646
* shape != Ok → KOIN-D005 with reason ARITY or TYPE
612647
*/
613648
private fun validateInjectedParamShapeAtCallSite(
614649
callSite: PendingCallSiteValidation,
615650
hints: InjectedParamHintGenerator,
651+
createdWithParameters: Set<String>,
616652
) {
617653
val slots = hints.getSlots(callSite.targetFqName) ?: return
618654

619655
if (!callSite.hasParametersLambda) {
656+
if (callSite.reusesInstance) {
657+
if (callSite.targetFqName !in createdWithParameters) {
658+
KoinPluginLogger.report(
659+
KoinDiagnostic.UnverifiedReusedInstanceParams(callSite.targetFqName, callSite.callFunctionName),
660+
callSite.filePath, callSite.line, callSite.column,
661+
)
662+
}
663+
return
664+
}
620665
KoinPluginLogger.report(
621666
KoinDiagnostic.MissingInjectedParams(
622667
target = callSite.targetFqName,

0 commit comments

Comments
 (0)