Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions RELEASE_NOTES_1.2.2.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ Compile safety on Kotlin/Native and wasm/JS now sees your whole graph.
## 🐛 Fixed

- 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.
- 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).
- 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.

## 🔧 Changed

- **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.
- **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`.
- **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.
- **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`.
- **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.

## ✅ Compatibility
Expand Down
28 changes: 28 additions & 0 deletions docs/COMPILE_TIME_SAFETY.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,34 @@ or a module class off the classpath). Compile-time dependency checks are skipped

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.

### Which call sites are judged

Every call site is judged against this compilation's graph, except two cases:

| Call site | Judged here when |
|---|---|
| `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 |
| `KoinComponent.get()` / `by inject()`, `koinInject()`, `koinViewModel()`, Android `viewModel()`, Ktor | unless every entry point here is a plain `koinApplication { }` (a test fixture, a preview) |

Everything else is judged as before, including `get()` in a definition lambda, `koinApplication { }.koin`, a `val` initialized with `startKoin { }.koin`, `getKoin()` and `with(koin) { }`.

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.

```
[Koin][KOIN-W009] 3 call site(s) not validated at compile time (first: get<Clock>()): their type is
not defined in this compilation, and they resolve on a Koin instance whose modules it can't see.
They are only checked at runtime.
```

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`.

### `activityViewModel()` and `parametersOf`

`activityViewModel<T>()` returns the instance the activity created. When `T` has `@InjectedParam` and the call passes no `parametersOf(...)`:

- a call site in the same module creates `T` with `parametersOf(...)` → nothing reported;
- 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.

## External Types: `@Provided` and Whitelist

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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,9 @@ object KoinAnnotationFqNames {
// the gap) — found via the app-dsl playground's own AnalyticsModule.kt.
val SCOPE_GET = FqName("org.koin.core.scope.Scope.get")

// Receiver type of `koin.getScope(..)` — a scope opened on a foreign Koin is foreign (#58).
val KOIN_CLASS = FqName("org.koin.core.Koin")

// --- android ---
val ANDROID_COMPONENT_GET = FqName("org.koin.android.ext.android.get")
val ANDROID_COMPONENT_INJECT = FqName("org.koin.android.ext.android.inject")
Expand All @@ -234,6 +237,11 @@ object KoinAnnotationFqNames {
val KTOR_GET = FqName("org.koin.ktor.ext.get")
val KTOR_INJECT = FqName("org.koin.ktor.ext.inject")

/** Return a ViewModel the activity already created with its own parameters (#121). */
val REUSED_INSTANCE_RESOLUTION_FUNCTIONS = setOf(
ANDROID_ACTIVITY_VIEW_MODEL, ANDROID_GET_ACTIVITY_VIEW_MODEL, KOIN_ACTIVITY_VIEW_MODEL_COMPOSE,
)

/** All call-site resolution functions for A4 validation. */
val CALL_SITE_RESOLUTION_FUNCTIONS = listOf(
// compose
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,41 @@ sealed class KoinDiagnostic(
"or add it as a direct dependency.",
)

/**
* KOIN-W009 — Call sites this compilation can't judge (#58): a `Koin` it can't trace to its
* entry point (a parameter, a property, a helper's instance), or the global context while only
* an isolated `koinApplication { }` / `koinConfiguration { }` is declared here. Only those that
* would otherwise be KOIN-D002 are counted: judging them against this compilation's graph gave
* false errors, and skipping them must never be silent. One per compilation, at the first one.
*/
class UntracedCallSites(
count: Int,
first: String,
) : KoinDiagnostic(
code = "KOIN-W009",
severity = Severity.WARNING,
message = "$count call site(s) not validated at compile time (first: $first): their type is " +
"not defined in this compilation, and they resolve on a Koin instance whose modules it " +
"can't see. They are only checked at runtime.",
)

/**
* KOIN-W010 — `activityViewModel<T>()` without `parametersOf`, for a T with `@InjectedParam`, and
* no call site in this compilation creates T with `parametersOf` (#121). Reuse of the activity's
* instance is fine; creating T here would crash. The creator may sit in another module, so this
* can't be KOIN-D006.
*/
class UnverifiedReusedInstanceParams(
target: String,
callFn: String,
) : KoinDiagnostic(
code = "KOIN-W010",
severity = Severity.WARNING,
message = "$callFn<${target.substringAfterLast('.')}>() has no parametersOf(...) and no call site " +
"in this module creates $target with parametersOf(...). Fine if the activity creates it first; " +
"otherwise it is created here without its @InjectedParam values and fails at runtime.",
)

/** KOIN-A001 — `@KoinViewModel` used without `io.insert-koin:koin-core-viewmodel`. */
class MissingViewModelArtifact(
def: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,22 @@ class CallSiteValidator(private val context: IrPluginContext) {
// CompileSafetyValidator's class doc). Defaults to true so existing callers/tests that
// don't pass it keep today's behavior.
hasKoinEntryPoint: Boolean = true,
globalContextBuiltHere: Boolean = true,
) {
val hasFullGraph = assembledGraphTypes.isNotEmpty()

// #58: a call site whose Koin doesn't come from a graph this compilation builds is never
// judged here. Those that would have been KOIN-D002 are disclosed by one KOIN-W009 instead.
// Known limit: a judged call site is still checked against every graph of the compilation.
fun judgedHere(callSite: PendingCallSiteValidation) = !hasKoinEntryPoint || when (callSite.receiver) {
CallSiteReceiver.GRAPH_BOUND -> true
CallSiteReceiver.GLOBAL -> globalContextBuiltHere
CallSiteReceiver.FOREIGN -> false
}
val notValidatedHere = mutableListOf<PendingCallSiteValidation>()
// #121: an activity-scoped ViewModel is only reused if some call site created it with parametersOf.
val createdWithParameters = callSites.filter { it.hasParametersLambda }.mapTo(mutableSetOf()) { it.targetFqName }

// Discover DSL definitions from dependency hints (cross-module DSL discovery).
// Always merge: A3's assembled graph only contains @Module classes' definitions, not
// DSL definitions loaded via `modules(dslModule)` from upstream modules. The hints
Expand Down Expand Up @@ -136,10 +149,12 @@ class CallSiteValidator(private val context: IrPluginContext) {
continue
}

val judged = judgedHere(callSite)

// Check assembled graph + DSL definitions + DSL hints
if (callSite.targetFqName in allKnownTypes) {
KoinPluginLogger.debug { "A4: OK ${callSite.callFunctionName}<${callSite.targetFqName}>() — found in graph" }
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints)
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints, createdWithParameters)
continue
}

Expand All @@ -151,13 +166,13 @@ class CallSiteValidator(private val context: IrPluginContext) {
}
if (hasAnnotation) {
KoinPluginLogger.debug { "A4: OK ${callSite.callFunctionName}<${callSite.targetFqName}>() — has definition annotation" }
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints)
if (injectedParamHints != null) validateInjectedParamShapeAtCallSite(callSite, injectedParamHints, createdWithParameters)
continue
}
}

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

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

val untraced = notValidatedHere.distinctBy { Triple(it.filePath, it.line, it.column) }
untraced.firstOrNull()?.let { first ->
KoinPluginLogger.report(
KoinDiagnostic.UntracedCallSites(
count = untraced.size,
first = "${first.callFunctionName}<${first.targetFqName.substringAfterLast('.')}>()",
),
first.filePath, first.line, first.column
)
}

// Generate call-site hints for unresolved types (deferred validation)
if (unresolvedCallSites.isNotEmpty()) {
KoinPluginLogger.debug { "Phase 3.5: Generating ${unresolvedCallSites.size} call-site hints for deferred validation" }
Expand Down Expand Up @@ -607,16 +640,28 @@ class CallSiteValidator(private val context: IrPluginContext) {
* Decision matrix:
* slots == null → def doesn't need params (or unknown) → no report
* !hasParametersLambda → user forgot `parametersOf` entirely → KOIN-D006
* (`activityViewModel` reuses an instance, #121: nothing if a call
* site creates it with parametersOf, else KOIN-W010)
* parametersOfArgs == null → trailing lambda was non-trivial → ambiguous, no report
* shape != Ok → KOIN-D005 with reason ARITY or TYPE
*/
private fun validateInjectedParamShapeAtCallSite(
callSite: PendingCallSiteValidation,
hints: InjectedParamHintGenerator,
createdWithParameters: Set<String>,
) {
val slots = hints.getSlots(callSite.targetFqName) ?: return

if (!callSite.hasParametersLambda) {
if (callSite.reusesInstance) {
if (callSite.targetFqName !in createdWithParameters) {
KoinPluginLogger.report(
KoinDiagnostic.UnverifiedReusedInstanceParams(callSite.targetFqName, callSite.callFunctionName),
callSite.filePath, callSite.line, callSite.column,
)
}
return
}
KoinPluginLogger.report(
KoinDiagnostic.MissingInjectedParams(
target = callSite.targetFqName,
Expand Down
Loading
Loading