How kotlin-inject processes code
mainkotlin-inject operates like a compiler, transforming Kotlin Abstract Syntax Tree (AST) into generated Kotlin code through a multi-step pipeline. Understanding this pipeline helps in conceptualizing how dependencies are discovered and resolved.
The pipeline follows these steps:
- Kotlin AST: The source code is represented as an AST. The library uses a wrapper (defined in
kotlin-inject-compiler/core/Ast) to abstract over different backends like KSP. - Collect Types: The
TypeCollectorscans@Componentclasses and their superclasses/interfaces to find methods that provide types. During this phase, the library validates that scope annotations are correct and ensures no type is provided multiple times. - Resolve Types: The
TypeResultResolverdetermines how to construct each type, returning aTypeResult. This process builds a Directed Acyclic Graph (DAG) of dependencies.TypeResultinstances are cached to ensure shared instances are used wherever a type is required. - Optimize: The
TypeResultOptimizerrefines the dependency graph. Currently, it identifies types with multiple parents and extracts them into private getters to optimize the generated code. - Generate Code: The final Kotlin code is produced using [KotlinPoet].
Kotlin AST -> Collect Types -> Resolve Types -> Optimize -> Generate Code