| 
 | 1 | +package software.amazon.app.platform.metro.processor  | 
 | 2 | + | 
 | 3 | +import com.google.devtools.ksp.KspExperimental  | 
 | 4 | +import com.google.devtools.ksp.getAllSuperTypes  | 
 | 5 | +import com.google.devtools.ksp.isAnnotationPresent  | 
 | 6 | +import com.google.devtools.ksp.processing.CodeGenerator  | 
 | 7 | +import com.google.devtools.ksp.processing.KSPLogger  | 
 | 8 | +import com.google.devtools.ksp.processing.Resolver  | 
 | 9 | +import com.google.devtools.ksp.processing.SymbolProcessor  | 
 | 10 | +import com.google.devtools.ksp.symbol.KSAnnotated  | 
 | 11 | +import com.google.devtools.ksp.symbol.KSClassDeclaration  | 
 | 12 | +import com.squareup.kotlinpoet.AnnotationSpec  | 
 | 13 | +import com.squareup.kotlinpoet.ClassName  | 
 | 14 | +import com.squareup.kotlinpoet.FileSpec  | 
 | 15 | +import com.squareup.kotlinpoet.FunSpec  | 
 | 16 | +import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy  | 
 | 17 | +import com.squareup.kotlinpoet.TypeSpec  | 
 | 18 | +import com.squareup.kotlinpoet.asClassName  | 
 | 19 | +import com.squareup.kotlinpoet.ksp.addOriginatingKSFile  | 
 | 20 | +import com.squareup.kotlinpoet.ksp.toClassName  | 
 | 21 | +import com.squareup.kotlinpoet.ksp.writeTo  | 
 | 22 | +import dev.zacsweers.metro.AppScope  | 
 | 23 | +import dev.zacsweers.metro.ContributesTo  | 
 | 24 | +import dev.zacsweers.metro.Inject  | 
 | 25 | +import dev.zacsweers.metro.IntoMap  | 
 | 26 | +import dev.zacsweers.metro.Provider  | 
 | 27 | +import dev.zacsweers.metro.Provides  | 
 | 28 | +import software.amazon.app.platform.inject.robot.ContributesRobot  | 
 | 29 | +import software.amazon.app.platform.ksp.decapitalize  | 
 | 30 | +import software.amazon.app.platform.metro.METRO_LOOKUP_PACKAGE  | 
 | 31 | +import software.amazon.app.platform.metro.MetroContextAware  | 
 | 32 | +import software.amazon.app.platform.renderer.metro.RobotKey  | 
 | 33 | + | 
 | 34 | +/**  | 
 | 35 | + * Generates the necessary code in order to support [ContributesRobot].  | 
 | 36 | + *  | 
 | 37 | + * If you use `@ContributesRobot(AbcScope::class)`, then this processor will generate a graph  | 
 | 38 | + * interface, which gets contributed to this scope.  | 
 | 39 | + *  | 
 | 40 | + * ```  | 
 | 41 | + * package app.platform.inject.metro.software.amazon.test  | 
 | 42 | + *  | 
 | 43 | + * @ContributesTo(scope = AbcScope::class)  | 
 | 44 | + * public interface AbcRobotGraph {  | 
 | 45 | + *     @Provide  | 
 | 46 | + *     fun provideAbcRobot(): AbcRobot = AbcRobot()  | 
 | 47 | + *  | 
 | 48 | + *     @Provides  | 
 | 49 | + *     @IntoMap  | 
 | 50 | + *     @RobotKey(AbcRobot::class)  | 
 | 51 | + *     fun provideAbcRobotIntoMap(  | 
 | 52 | + *         robot: Provider<AbcRobot>,  | 
 | 53 | + *     ): Robot = robot()  | 
 | 54 | + * }  | 
 | 55 | + * ```  | 
 | 56 | + */  | 
 | 57 | +@OptIn(KspExperimental::class)  | 
 | 58 | +internal class ContributesRobotProcessor(  | 
 | 59 | +  private val codeGenerator: CodeGenerator,  | 
 | 60 | +  override val logger: KSPLogger,  | 
 | 61 | +) : SymbolProcessor, MetroContextAware {  | 
 | 62 | + | 
 | 63 | +  private val robotClassName = ClassName("software.amazon.app.platform.robot", "Robot")  | 
 | 64 | +  private val robotFqName = robotClassName.canonicalName  | 
 | 65 | + | 
 | 66 | +  private val robotKey = RobotKey::class.asClassName()  | 
 | 67 | + | 
 | 68 | +  override fun process(resolver: Resolver): List<KSAnnotated> {  | 
 | 69 | +    resolver  | 
 | 70 | +      .getSymbolsWithAnnotation(ContributesRobot::class)  | 
 | 71 | +      .filterIsInstance<KSClassDeclaration>()  | 
 | 72 | +      .onEach {  | 
 | 73 | +        checkIsPublic(it)  | 
 | 74 | +        checkHasInjectAnnotation(it)  | 
 | 75 | +        checkNotSingleton(it)  | 
 | 76 | +        checkSuperType(it)  | 
 | 77 | +        checkAppScope(it)  | 
 | 78 | +      }  | 
 | 79 | +      .forEach { generateGraph(it) }  | 
 | 80 | + | 
 | 81 | +    return emptyList()  | 
 | 82 | +  }  | 
 | 83 | + | 
 | 84 | +  private fun generateGraph(clazz: KSClassDeclaration) {  | 
 | 85 | +    val packageName = "${METRO_LOOKUP_PACKAGE}.${clazz.packageName.asString()}"  | 
 | 86 | +    val graphClassName = ClassName(packageName, "${clazz.innerClassNames()}Graph")  | 
 | 87 | + | 
 | 88 | +    val fileSpec =  | 
 | 89 | +      FileSpec.builder(graphClassName)  | 
 | 90 | +        .addType(  | 
 | 91 | +          TypeSpec.interfaceBuilder(graphClassName)  | 
 | 92 | +            .addOriginatingKSFile(clazz.requireContainingFile())  | 
 | 93 | +            .addAnnotation(  | 
 | 94 | +              AnnotationSpec.builder(ContributesTo::class)  | 
 | 95 | +                .addMember("%T::class", clazz.scope().type.toClassName())  | 
 | 96 | +                .build()  | 
 | 97 | +            )  | 
 | 98 | +            .apply {  | 
 | 99 | +              if (!clazz.isAnnotationPresent(Inject::class)) {  | 
 | 100 | +                addFunction(  | 
 | 101 | +                  FunSpec.builder("provide${clazz.innerClassNames()}")  | 
 | 102 | +                    .addAnnotation(Provides::class)  | 
 | 103 | +                    .returns(clazz.toClassName())  | 
 | 104 | +                    .addStatement("return %T()", clazz.toClassName())  | 
 | 105 | +                    .build()  | 
 | 106 | +                )  | 
 | 107 | +              }  | 
 | 108 | +            }  | 
 | 109 | +            .addFunction(  | 
 | 110 | +              FunSpec.builder("provide${clazz.innerClassNames()}IntoMap")  | 
 | 111 | +                .addAnnotation(Provides::class)  | 
 | 112 | +                .addAnnotation(IntoMap::class)  | 
 | 113 | +                .addAnnotation(  | 
 | 114 | +                  AnnotationSpec.builder(robotKey)  | 
 | 115 | +                    .addMember("%T::class", clazz.toClassName())  | 
 | 116 | +                    .build()  | 
 | 117 | +                )  | 
 | 118 | +                .addParameter(  | 
 | 119 | +                  name = "robot",  | 
 | 120 | +                  type = Provider::class.asClassName().parameterizedBy(clazz.toClassName()),  | 
 | 121 | +                )  | 
 | 122 | +                .returns(robotClassName)  | 
 | 123 | +                .addStatement("return robot()")  | 
 | 124 | +                .build()  | 
 | 125 | +            )  | 
 | 126 | +            .addProperty(name = clazz.innerClassNames().decapitalize(), type = clazz.toClassName())  | 
 | 127 | +            .build()  | 
 | 128 | +        )  | 
 | 129 | +        .build()  | 
 | 130 | + | 
 | 131 | +    fileSpec.writeTo(codeGenerator, aggregating = false)  | 
 | 132 | +  }  | 
 | 133 | + | 
 | 134 | +  private fun checkHasInjectAnnotation(clazz: KSClassDeclaration) {  | 
 | 135 | +    if (clazz.primaryConstructor?.parameters?.isNotEmpty() == true) {  | 
 | 136 | +      check(clazz.annotations.any { it.isAnnotation(injectFqName) }, clazz) {  | 
 | 137 | +        "${clazz.simpleName.asString()} must be annotated with @Inject when " +  | 
 | 138 | +          "injecting arguments into a robot."  | 
 | 139 | +      }  | 
 | 140 | +    }  | 
 | 141 | +  }  | 
 | 142 | + | 
 | 143 | +  private fun checkNotSingleton(clazz: KSClassDeclaration) {  | 
 | 144 | +    check(clazz.annotations.none { it.isMetroScopeAnnotation() }, clazz) {  | 
 | 145 | +      "It's not allowed allowed for a robot to be a singleton, because the lifetime " +  | 
 | 146 | +        "of the robot is scoped to the robot() factory function. Remove the @" +  | 
 | 147 | +        clazz.annotations.first { it.isMetroScopeAnnotation() }.shortName.asString() +  | 
 | 148 | +        " annotation."  | 
 | 149 | +    }  | 
 | 150 | +  }  | 
 | 151 | + | 
 | 152 | +  private fun checkSuperType(clazz: KSClassDeclaration) {  | 
 | 153 | +    val extendsRobot =  | 
 | 154 | +      clazz.getAllSuperTypes().any { it.declaration.requireQualifiedName() == robotFqName }  | 
 | 155 | + | 
 | 156 | +    check(extendsRobot, clazz) {  | 
 | 157 | +      "In order to use @ContributesRobot, ${clazz.simpleName.asString()} must " +  | 
 | 158 | +        "implement $robotFqName."  | 
 | 159 | +    }  | 
 | 160 | +  }  | 
 | 161 | + | 
 | 162 | +  private fun checkAppScope(clazz: KSClassDeclaration) {  | 
 | 163 | +    val scope = clazz.scope().type.declaration.requireQualifiedName()  | 
 | 164 | +    check(scope == AppScope::class.requireQualifiedName(), clazz) {  | 
 | 165 | +      "Robots can only be contributed to the AppScope for now. Scope $scope is unsupported."  | 
 | 166 | +    }  | 
 | 167 | +  }  | 
 | 168 | +}  | 
0 commit comments