aboutsummaryrefslogtreecommitdiff
path: root/examples/playground/test-processor/src/main/kotlin/TestProcessor.kt
blob: d78587035990edf8101f5e7fa13a7a80e416f517 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.validate
import java.io.File
import java.io.OutputStream


class TestProcessor(
    val codeGenerator: CodeGenerator,
    val options: Map<String, String>
) : SymbolProcessor {
    lateinit var file: OutputStream
    var invoked = false

    fun emit(s: String, indent: String) {
        file.appendText("$indent$s\n")
    }

    override fun process(resolver: Resolver): List<KSAnnotated> {
        if (invoked) {
            return emptyList()
        }
        file = codeGenerator.createNewFile(Dependencies(false), "", "TestProcessor", "log")
        emit("TestProcessor: init($options)", "")

        val javaFile = codeGenerator.createNewFile(Dependencies(false), "", "Generated", "java")
        javaFile.appendText("class Generated {}")

        val fileKt = codeGenerator.createNewFile(Dependencies(false), "", "HELLO", "java")
        fileKt.appendText("public class HELLO{\n")
        fileKt.appendText("public int foo() { return 1234; }\n")
        fileKt.appendText("}")

        val files = resolver.getAllFiles()
        emit("TestProcessor: process()", "")
        val visitor = TestVisitor()
        for (file in files) {
            emit("TestProcessor: processing ${file.fileName}", "")
            file.accept(visitor, "")
        }
        invoked = true
        return emptyList()
    }

    inner class TestVisitor : KSVisitor<String, Unit> {

        override fun visitReferenceElement(element: KSReferenceElement, data: String) {
        }

        override fun visitModifierListOwner(modifierListOwner: KSModifierListOwner, data: String) {
            TODO("Not yet implemented")
        }

        override fun visitNode(node: KSNode, data: String) {
            TODO("Not yet implemented")
        }

        override fun visitPropertyAccessor(accessor: KSPropertyAccessor, data: String) {
            TODO("Not yet implemented")
        }

        override fun visitDynamicReference(reference: KSDynamicReference, data: String) {
            TODO("Not yet implemented")
        }
        val visited = HashSet<Any>()

        private fun checkVisited(symbol: Any): Boolean {
            return if (visited.contains(symbol)) {
                true
            } else {
                visited.add(symbol)
                false
            }
        }

        private fun invokeCommonDeclarationApis(declaration: KSDeclaration, indent: String) {
            emit(
              "${declaration.modifiers.joinToString(" ")} ${declaration.simpleName.asString()}", indent
            )
            declaration.annotations.forEach{ it.accept(this, "$indent  ") }
            if (declaration.parentDeclaration != null)
                emit("  enclosing: ${declaration.parentDeclaration!!.qualifiedName?.asString()}", indent)
            declaration.containingFile?.let { emit("${it.packageName.asString()}.${it.fileName}", indent) }
            declaration.typeParameters.forEach { it.accept(this, "$indent  ") }
        }

        override fun visitFile(file: KSFile, data: String) {
            if (checkVisited(file)) return
            file.annotations.forEach{ it.accept(this, "$data  ") }
            emit(file.packageName.asString(), data)
            for (declaration in file.declarations) {
                declaration.accept(this, data)
            }
        }

        override fun visitAnnotation(annotation: KSAnnotation, data: String) {
            if (checkVisited(annotation)) return
            emit("annotation", data)
            annotation.annotationType.accept(this, "$data  ")
            annotation.arguments.forEach { it.accept(this, "$data  ") }
        }

        override fun visitCallableReference(reference: KSCallableReference, data: String) {
            if (checkVisited(reference)) return
            emit("element: ", data)
            reference.functionParameters.forEach { it.accept(this, "$data  ") }
            reference.receiverType?.accept(this, "$data receiver")
            reference.returnType.accept(this, "$data  ")
        }

        override fun visitPropertyGetter(getter: KSPropertyGetter, data: String) {
            if (checkVisited(getter)) return
            emit("propertyGetter: ", data)
            getter.annotations.forEach { it.accept(this, "$data  ") }
            emit(getter.modifiers.joinToString(" "), data)
            getter.returnType?.accept(this, "$data  ")
        }

        override fun visitPropertySetter(setter: KSPropertySetter, data: String) {
            if (checkVisited(setter)) return
            emit("propertySetter: ", data)
            setter.annotations.forEach { it.accept(this, "$data  ") }
            emit(setter.modifiers.joinToString(" "), data)
        }

        override fun visitTypeArgument(typeArgument: KSTypeArgument, data: String) {
            if (checkVisited(typeArgument)) return
            typeArgument.annotations.forEach{ it.accept(this, "$data  ") }
            emit(
              when (typeArgument.variance) {
                  Variance.STAR -> "*"
                  Variance.COVARIANT -> "out"
                  Variance.CONTRAVARIANT -> "in"
                  else -> ""
              }, data
            )
            typeArgument.type?.accept(this, "$data  ")
        }

        override fun visitTypeParameter(typeParameter: KSTypeParameter, data: String) {
            if (checkVisited(typeParameter)) return
            typeParameter.annotations.forEach{ it.accept(this, "$data  ") }
            if (typeParameter.isReified) {
                emit("reified ", data)
            }
            emit(
              when (typeParameter.variance) {
                  Variance.COVARIANT -> "out "
                  Variance.CONTRAVARIANT -> "in "
                  else -> ""
              } + typeParameter.name.asString(), data
            )
            if (typeParameter.bounds.toList().isNotEmpty()) {
                typeParameter.bounds.forEach { it.accept(this, "$data  ") }
            }
        }

        override fun visitValueParameter(valueParameter: KSValueParameter, data: String) {
            if (checkVisited(valueParameter)) return
            valueParameter.annotations.forEach { it.accept(this, "$data  ") }
            if (valueParameter.isVararg) {
                emit("vararg", "$data  ")
            }
            if (valueParameter.isNoInline) {
                emit("noinline", "$data  ")
            }
            if (valueParameter.isCrossInline) {
                emit("crossinline ", "$data  ")
            }
            emit(valueParameter.name?.asString() ?: "_", "$data  ")
            valueParameter.type.accept(this, "$data  ")
        }

        override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: String) {
            if (checkVisited(function)) return
            invokeCommonDeclarationApis(function, data)
            for (declaration in function.declarations) {
                declaration.accept(this, "$data  ")
            }
            function.parameters.forEach { it.accept(this, "$data  ") }
            function.typeParameters.forEach { it.accept(this, "$data  ") }
            function.extensionReceiver?.accept(this, "$data extension:")
            emit("returnType:", data)
            function.returnType?.accept(this, "$data  ")
        }

        override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: String) {
            if (checkVisited(classDeclaration)) return
            invokeCommonDeclarationApis(classDeclaration, data)
            emit(classDeclaration.classKind.type, data)
            for (declaration in classDeclaration.declarations) {
                declaration.accept(this, "$data ")
            }
            classDeclaration.superTypes.forEach { it.accept(this, "$data  ") }
            classDeclaration.primaryConstructor?.accept(this, "$data  ")
        }

        override fun visitPropertyDeclaration(property: KSPropertyDeclaration, data: String) {
            if (checkVisited(property)) return
            invokeCommonDeclarationApis(property, data)
            property.type.accept(this, "$data  ")
            property.extensionReceiver?.accept(this, "$data extension:")
            property.setter?.accept(this, "$data  ")
            property.getter?.accept(this, "$data  ")
        }

        override fun visitTypeReference(typeReference: KSTypeReference, data: String) {
            if (checkVisited(typeReference)) return
            typeReference.annotations.forEach{ it.accept(this, "$data  ") }
            val type = typeReference.resolve()
            type.let {
                emit("resolved to: ${it.declaration.qualifiedName?.asString()}", data)
            }
            try {
                typeReference.element?.accept(this, "$data  ")
            } catch (e: IllegalStateException) {
                emit("TestProcessor: exception: $e", data)
            }
        }

        override fun visitAnnotated(annotated: KSAnnotated, data: String) {
        }

        override fun visitDeclaration(declaration: KSDeclaration, data: String) {
        }

        override fun visitDeclarationContainer(declarationContainer: KSDeclarationContainer, data: String) {
        }

        override fun visitParenthesizedReference(reference: KSParenthesizedReference, data: String) {
        }

        override fun visitClassifierReference(reference: KSClassifierReference, data: String) {
            if (checkVisited(reference)) return
            if (reference.typeArguments.isNotEmpty()) {
                reference.typeArguments.forEach { it.accept(this, "$data  ") }
            }
        }

        override fun visitTypeAlias(typeAlias: KSTypeAlias, data: String) {
        }

        override fun visitValueArgument(valueArgument: KSValueArgument, data: String) {
            if (checkVisited(valueArgument)) return
            val name = valueArgument.name?.asString() ?: "<no name>"
            emit("$name: ${valueArgument.value}", data)
            valueArgument.annotations.forEach { it.accept(this, "$data  ") }
        }
    }

}

class TestProcessorProvider : SymbolProcessorProvider {
    override fun create(
        environment: SymbolProcessorEnvironment
    ): SymbolProcessor {
        return TestProcessor(environment.codeGenerator, environment.options)
    }
}