Skip to content

Always generate provider factories for binding modules #951

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 9, 2024
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.squareup.anvil.annotations

import com.squareup.anvil.annotations.ContributesBinding.Companion.PRIORITY_NORMAL
import kotlin.annotation.AnnotationRetention.RUNTIME
import kotlin.annotation.AnnotationTarget.CLASS
import kotlin.reflect.KClass
Expand Down
1 change: 1 addition & 0 deletions compiler-api/api/compiler-api.api
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public abstract interface class com/squareup/anvil/compiler/api/AnvilContext {
public abstract fun getGenerateFactoriesOnly ()Z
public abstract fun getModule ()Lorg/jetbrains/kotlin/descriptors/ModuleDescriptor;
public abstract fun getTrackSourceFiles ()Z
public abstract fun getWillHaveDaggerFactories ()Z
}

public abstract interface class com/squareup/anvil/compiler/api/CodeGenerator : com/squareup/anvil/compiler/api/AnvilApplicabilityChecker {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ public interface AnvilContext {
*/
public val trackSourceFiles: Boolean

/**
* True if there will be Dagger factory models for this target after compilation has finished.
*
* These models could be generated by any of:
* - Anvil via the [generateFactories] option
* - Dagger via KAPT
* - Dagger via KSP
*/
public val willHaveDaggerFactories: Boolean

/**
* The module of the current compilation.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ public class AnvilCompilation internal constructor(
optionName = "generate-dagger-factories-only",
optionValue = generateDaggerFactoriesOnly.toString(),
),
PluginOption(
pluginId = anvilCommandLineProcessor.pluginId,
optionName = "will-have-dagger-factories",
optionValue = (generateDaggerFactories || enableDaggerAnnotationProcessor).toString(),
),
PluginOption(
pluginId = anvilCommandLineProcessor.pluginId,
optionName = "track-source-files",
Expand All @@ -134,6 +139,7 @@ public class AnvilCompilation internal constructor(
}
// Run KSP embedded directly within this kotlinc invocation
kspWithCompilation = true
kspArgs["will-have-dagger-factories"] = generateDaggerFactories.toString()
kspArgs["generate-dagger-factories"] = generateDaggerFactories.toString()
kspArgs["generate-dagger-factories-only"] = generateDaggerFactoriesOnly.toString()
kspArgs["disable-component-merging"] = disableComponentMerging.toString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,56 @@
package com.squareup.anvil.compiler.internal.testing

import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import com.squareup.anvil.annotations.ExperimentalAnvilApi
import com.squareup.anvil.annotations.internal.InternalBindingMarker
import com.squareup.anvil.compiler.internal.capitalize
import dagger.Component
import dagger.Module
import dagger.Provides
import dagger.Subcomponent
import org.jetbrains.kotlin.analysis.utils.collections.mapToSet
import kotlin.reflect.KClass

@ExperimentalAnvilApi
public fun Class<*>.moduleFactoryClass(
providerMethodName: String,
providerMethodName: String? = null,
companion: Boolean = false,
): Class<*> {
val companionString = if (companion) "_Companion" else ""

val methodsOrCompanionMethods = if (companion) {
fields.single { it.name == "Companion" }.type.methods
} else {
methods
}

val providesMethods = methodsOrCompanionMethods
.filter { it.isAnnotationPresent(Provides::class.java) }
.mapToSet { it.name }

assertWithMessage("No @Provides methods found in $this")
.that(providesMethods)
.isNotEmpty()

if (providerMethodName != null) {
assertWithMessage(
"The name '$providerMethodName' must match a function annotated with @Provides",
)
.that(providesMethods)
.contains(providerMethodName)
} else {
assertWithMessage(
"You must specify a providerMethodName value when there is more than one @Provides function",
)
.that(providesMethods)
.hasSize(1)
}

val methodName = providerMethodName ?: providesMethods.single()

return classLoader.loadClass(
"${generatedClassesString()}${companionString}_${providerMethodName.capitalize()}Factory",
"${generatedClassesString()}${companionString}_${methodName.capitalize()}Factory",
)
}

Expand Down Expand Up @@ -106,7 +140,9 @@ public fun Array<KClass<*>>.withoutAnvilModules(): List<KClass<*>> = toList().wi
@ExperimentalAnvilApi
public fun Collection<KClass<*>>.withoutAnvilModules(): List<KClass<*>> =
filterNot {
it.qualifiedName!!.startsWith("anvil.module") || it.java.isAnnotationPresent(InternalBindingMarker::class.java)
it.qualifiedName!!.startsWith("anvil.module") || it.java.isAnnotationPresent(
InternalBindingMarker::class.java,
)
}

@ExperimentalAnvilApi
Expand Down
3 changes: 2 additions & 1 deletion compiler/api/compiler.api
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ public final class com/squareup/anvil/compiler/AnvilComponentRegistrar : org/jet

public final class com/squareup/anvil/compiler/CommandLineOptions {
public static final field Companion Lcom/squareup/anvil/compiler/CommandLineOptions$Companion;
public synthetic fun <init> (ZZZZLcom/squareup/anvil/compiler/api/AnalysisBackend;Lcom/squareup/anvil/compiler/api/ComponentMergingBackend;Lkotlin/jvm/internal/DefaultConstructorMarker;)V
public synthetic fun <init> (ZZZZZLcom/squareup/anvil/compiler/api/AnalysisBackend;Lcom/squareup/anvil/compiler/api/ComponentMergingBackend;Lkotlin/jvm/internal/DefaultConstructorMarker;)V
public final fun getBackend ()Lcom/squareup/anvil/compiler/api/AnalysisBackend;
public final fun getComponentMergingBackend ()Lcom/squareup/anvil/compiler/api/ComponentMergingBackend;
public final fun getDisableComponentMerging ()Z
public final fun getGenerateFactories ()Z
public final fun getGenerateFactoriesOnly ()Z
public final fun getTrackSourceFiles ()Z
public final fun getWillHaveDaggerFactories ()Z
}

public final class com/squareup/anvil/compiler/CommandLineOptions$Companion {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ internal const val trackSourceFilesName = "track-source-files"
internal val trackSourceFilesKey =
CompilerConfigurationKey.create<Boolean>("anvil $trackSourceFilesName")

internal const val willHaveDaggerFactoriesName = "will-have-dagger-factories"
internal val willHaveDaggerFactoriesKey =
CompilerConfigurationKey.create<Boolean>("anvil $willHaveDaggerFactoriesName")

internal const val analysisBackendName = "analysis-backend"
internal val analysisBackendKey =
CompilerConfigurationKey.create<String>("anvil $analysisBackendName")
Expand Down Expand Up @@ -107,6 +111,14 @@ public class AnvilCommandLineProcessor : CommandLineProcessor {
required = false,
allowMultipleOccurrences = false,
),
CliOption(
optionName = willHaveDaggerFactoriesName,
valueDescription = "<true|false>",
description = "Whether Anvil should expect that Dagger's Factory models will be generated " +
"by the end of compilation, from Anvil itself or from Dagger's generators.",
required = false,
allowMultipleOccurrences = false,
),
CliOption(
optionName = analysisBackendName,
valueDescription = AnalysisBackend.entries.joinToString("|", "<", ">"),
Expand Down Expand Up @@ -142,6 +154,9 @@ public class AnvilCommandLineProcessor : CommandLineProcessor {
disableComponentMergingName ->
configuration.put(disableComponentMergingKey, value.toBoolean())

willHaveDaggerFactoriesName ->
configuration.put(willHaveDaggerFactoriesKey, value.toBoolean())

trackSourceFilesName ->
configuration.put(trackSourceFilesKey, value.toBoolean())

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class CommandLineOptions private constructor(
public val generateFactoriesOnly: Boolean,
public val disableComponentMerging: Boolean,
public val trackSourceFiles: Boolean,
public val willHaveDaggerFactories: Boolean,
public val backend: AnalysisBackend,
public val componentMergingBackend: ComponentMergingBackend,
) {
Expand All @@ -20,6 +21,7 @@ public class CommandLineOptions private constructor(
generateFactoriesOnly = get(generateDaggerFactoriesOnlyKey, false),
disableComponentMerging = get(disableComponentMergingKey, false),
trackSourceFiles = get(trackSourceFilesKey, false),
willHaveDaggerFactories = get(willHaveDaggerFactoriesKey, false),
backend = parseBackend(),
componentMergingBackend = parseComponentMergingBackend(),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import com.squareup.kotlinpoet.ksp.writeTo
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.psi.KtFile
import java.io.File
import kotlin.properties.Delegates

/**
* Generates binding modules for every [ContributesBinding]-annotated class. If a class has repeated
Expand All @@ -52,7 +53,15 @@ import java.io.File
*/
internal object ContributesBindingCodeGen : AnvilApplicabilityChecker {

override fun isApplicable(context: AnvilContext) = !context.generateFactoriesOnly
// Used to determine if this generator needs to take responsibility
// for generating a factory for `@Provides` functions.
// https://github.com/square/anvil/issues/948
private var willHaveDaggerFactories: Boolean by Delegates.notNull()

override fun isApplicable(context: AnvilContext): Boolean {
willHaveDaggerFactories = context.willHaveDaggerFactories
return !context.generateFactoriesOnly
}

internal class KspGenerator(
override val env: SymbolProcessorEnvironment,
Expand Down Expand Up @@ -114,13 +123,15 @@ internal object ContributesBindingCodeGen : AnvilApplicabilityChecker {
)
}

for (spec in contributions.generateFileSpecs()) {
spec.writeTo(
env.codeGenerator,
aggregating = false,
originatingKSFiles = listOf(clazz.containingFile!!),
)
}
contributions
.generateFileSpecs(generateProviderFactories = !willHaveDaggerFactories)
.forEach { spec ->
spec.writeTo(
env.codeGenerator,
aggregating = false,
originatingKSFiles = listOf(clazz.containingFile!!),
)
}
}

return emptyList()
Expand Down Expand Up @@ -186,15 +197,16 @@ internal object ContributesBindingCodeGen : AnvilApplicabilityChecker {
)
}

contributions.generateFileSpecs().map { spec ->
createGeneratedFile(
codeGenDir = codeGenDir,
packageName = spec.packageName,
fileName = spec.name,
content = spec.toString(),
sourceFile = clazz.containingFileAsJavaFile,
)
}
contributions.generateFileSpecs(generateProviderFactories = !willHaveDaggerFactories)
.map { spec ->
createGeneratedFile(
codeGenDir = codeGenDir,
packageName = spec.packageName,
fileName = spec.name,
content = spec.toString(),
sourceFile = clazz.containingFileAsJavaFile,
)
}
}
.toList()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import com.squareup.kotlinpoet.ksp.writeTo
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.psi.KtFile
import java.io.File
import kotlin.properties.Delegates

/**
* Generates binding modules for every [ContributesMultibinding]-annotated class. If a class has repeated
Expand All @@ -49,7 +50,15 @@ import java.io.File
*/
internal object ContributesMultibindingCodeGen : AnvilApplicabilityChecker {

override fun isApplicable(context: AnvilContext) = !context.generateFactoriesOnly
// Used to determine if this generator needs to take responsibility
// for generating a factory for `@Provides` functions.
// https://github.com/square/anvil/issues/948
private var willHaveDaggerFactories: Boolean by Delegates.notNull()

override fun isApplicable(context: AnvilContext): Boolean {
willHaveDaggerFactories = context.willHaveDaggerFactories
return !context.generateFactoriesOnly
}

internal class KspGenerator(
override val env: SymbolProcessorEnvironment,
Expand Down Expand Up @@ -109,13 +118,15 @@ internal object ContributesMultibindingCodeGen : AnvilApplicabilityChecker {
)
}

for (spec in contributions.generateFileSpecs()) {
spec.writeTo(
codeGenerator = env.codeGenerator,
aggregating = false,
originatingKSFiles = listOf(clazz.containingFile!!),
)
}
contributions
.generateFileSpecs(generateProviderFactories = !willHaveDaggerFactories)
.forEach { spec ->
spec.writeTo(
codeGenerator = env.codeGenerator,
aggregating = false,
originatingKSFiles = listOf(clazz.containingFile!!),
)
}
}

return emptyList()
Expand Down Expand Up @@ -184,15 +195,16 @@ internal object ContributesMultibindingCodeGen : AnvilApplicabilityChecker {
)
}

contributions.generateFileSpecs().map { spec ->
createGeneratedFile(
codeGenDir = codeGenDir,
packageName = spec.packageName,
fileName = spec.name,
content = spec.toString(),
sourceFile = clazz.containingFileAsJavaFile,
)
}
contributions.generateFileSpecs(generateProviderFactories = !willHaveDaggerFactories)
.map { spec ->
createGeneratedFile(
codeGenDir = codeGenDir,
packageName = spec.packageName,
fileName = spec.name,
content = spec.toString(),
sourceFile = clazz.containingFileAsJavaFile,
)
}
}
.toList()
}
Expand Down
Loading