Skip to content

Commit dc19054

Browse files
authored
Merge pull request #328 from square/ralf/private-code-generators
Only call private code generators once after all other code generators are done
2 parents 6747ebe + 6ac18f4 commit dc19054

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

compiler/src/main/java/com/squareup/anvil/compiler/codegen/CodeGenerationExtension.kt

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ internal class CodeGenerationExtension(
6969
val anvilModule = RealAnvilModuleDescriptor(module)
7070
anvilModule.addFiles(files)
7171

72+
val (privateCodeGenerators, nonPrivateCodeGenerators) =
73+
codeGenerators.partition { it is PrivateCodeGenerator }
74+
7275
fun Collection<GeneratedFile>.toKtFile(): Collection<KtFile> {
7376
return this
7477
.mapNotNull { (file, content) ->
@@ -95,19 +98,19 @@ internal class CodeGenerationExtension(
9598
codeGenerator.flush(codeGenDir, anvilModule).toKtFile()
9699
}
97100

98-
var newFiles = codeGenerators.generateCode(files)
101+
var newFiles = nonPrivateCodeGenerators.generateCode(files)
102+
99103
while (newFiles.isNotEmpty()) {
100104
// Parse the KtFile for each generated file. Then feed the code generators with the new
101105
// parsed files until no new files are generated.
102-
newFiles = codeGenerators.generateCode(newFiles)
106+
newFiles = nonPrivateCodeGenerators.generateCode(newFiles)
103107
}
104108

105-
val flushedFiles = codeGenerators.flush()
109+
nonPrivateCodeGenerators.flush()
106110

107-
// The contract is that PrivateCodeGenerators are called one last time after flush().
108-
codeGenerators
109-
.filterIsInstance<PrivateCodeGenerator>()
110-
.generateCode(flushedFiles)
111+
// PrivateCodeGenerators don't impact other code generators. Therefore, they can be called a
112+
// single time at the end.
113+
privateCodeGenerators.generateCode(anvilModule.allFiles)
111114

112115
// This restarts the analysis phase and will include our files.
113116
return RetryWithAdditionalRoots(

compiler/src/main/java/com/squareup/anvil/compiler/codegen/RealAnvilModuleDescriptor.kt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,15 @@ class RealAnvilModuleDescriptor(
1515
delegate: ModuleDescriptor
1616
) : AnvilModuleDescriptor, ModuleDescriptor by delegate {
1717

18+
internal val allFiles = mutableListOf<KtFile>()
19+
1820
private val classesMap = mutableMapOf<String, List<KtClassOrObject>>()
1921
private val allClasses: Sequence<KtClassOrObject>
2022
get() = classesMap.values.asSequence().flatMap { it }
2123

2224
fun addFiles(files: Collection<KtFile>) {
25+
allFiles += files
26+
2327
files.forEach { ktFile ->
2428
classesMap[ktFile.identifier] = ktFile.classesAndInnerClasses()
2529
}

0 commit comments

Comments
 (0)