Remove obsolete kapt2 implementation

This commit is contained in:
Yan Zhulanow
2017-06-05 22:49:29 +03:00
parent 423a09e46a
commit 820f914d35
122 changed files with 1 additions and 5983 deletions
-2
View File
@@ -31,10 +31,8 @@
</library>
</orderEntry>
<orderEntry type="library" scope="TEST" name="gradle-and-groovy-plugin" level="project" />
<orderEntry type="module" module-name="java-model-wrappers" scope="TEST" />
<orderEntry type="module" module-name="light-classes" scope="TEST" />
<orderEntry type="library" scope="TEST" name="junit-plugin" level="project" />
<orderEntry type="module" module-name="annotation-processing" scope="TEST" />
<orderEntry type="module" module-name="build-common" scope="TEST" />
<orderEntry type="module" module-name="jps-tests" scope="TEST" />
<orderEntry type="module" module-name="kapt3" scope="TEST" />
@@ -1,178 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.annotation.processing.test.processor
import com.intellij.openapi.extensions.Extensions
import com.intellij.testFramework.registerServiceInstance
import org.jetbrains.kotlin.annotation.AbstractAnnotationProcessingExtension
import org.jetbrains.kotlin.annotation.processing.diagnostic.DefaultErrorMessagesAnnotationProcessing
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.codegen.AbstractBytecodeTextTest
import org.jetbrains.kotlin.codegen.CodegenTestUtil
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.java.model.elements.JeAnnotationMirror
import org.jetbrains.kotlin.java.model.elements.JeMethodExecutableElement
import org.jetbrains.kotlin.java.model.elements.JeTypeElement
import org.jetbrains.kotlin.java.model.elements.JeVariableElement
import org.jetbrains.kotlin.java.model.internal.JeElementRegistry
import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension
import org.jetbrains.kotlin.test.ConfigurationKind
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.test.TestJdkKind
import java.io.File
import java.nio.file.Files
import javax.annotation.processing.Completion
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.Processor
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
import javax.lang.model.element.*
class AnnotationProcessingExtensionForTests(
val processors: List<Processor>
) : AbstractAnnotationProcessingExtension(createTempDir(), createTempDir(), listOf(), true,
createIncrementalDataFile()) {
override fun loadAnnotationProcessors() = processors
override val options: Map<String, String>
get() = emptyMap()
private companion object {
fun createTempDir(): File = Files.createTempDirectory("ap-test").toFile().apply {
deleteOnExit()
}
fun createIncrementalDataFile(): File = File.createTempFile("incrementalData", "txt").apply {
deleteOnExit()
}
}
}
abstract class AbstractProcessorTest : AbstractBytecodeTextTest() {
abstract val testDataDir: String
private fun createTestEnvironment(processors: List<Processor>): KotlinCoreEnvironment {
val configuration = KotlinTestUtils.newConfiguration(ConfigurationKind.ALL, TestJdkKind.MOCK_JDK)
val environment = KotlinCoreEnvironment.createForTests(testRootDisposable, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES)
val project = environment.project
val apExtension = AnnotationProcessingExtensionForTests(processors)
AnalysisHandlerExtension.registerExtension(project, apExtension)
project.registerServiceInstance(JeElementRegistry::class.java, JeElementRegistry())
Extensions.getRootArea().getExtensionPoint(DefaultErrorMessages.Extension.EP_NAME)
.registerExtension(DefaultErrorMessagesAnnotationProcessing())
return environment
}
fun doTest(path: String, processors: List<Processor>) {
myEnvironment = createTestEnvironment(processors)
loadFileByFullPath(path)
CodegenTestUtil.generateFiles(myEnvironment, myFiles)
}
protected fun Element.assertHasAnnotation(fqName: String, vararg parameterValues: Any?) {
val annotation = annotationMirrors.first { it is JeAnnotationMirror && it.psi.qualifiedName == fqName }
val actualValues = annotation.elementValues.values
assertEquals(parameterValues.size, actualValues.size)
for ((expected, actual) in parameterValues.zip(actualValues)) {
assertEquals(expected, actual.value)
}
}
protected fun test(
name: String,
vararg supportedAnnotations: String,
process: (Set<TypeElement>, RoundEnvironment, ProcessingEnvironment) -> Unit
) = testAP(true, name, process, *supportedAnnotations)
protected fun testShouldNotRun(
name: String,
vararg supportedAnnotations: String
) = testAP(false, name, { _, _, _ -> fail("Should not run") }, *supportedAnnotations)
protected fun testAP(
shouldRun: Boolean,
name: String,
process: (Set<TypeElement>, RoundEnvironment, ProcessingEnvironment) -> Unit,
vararg supportedAnnotations: String
) {
val ktFileName = File(testDataDir, name + ".kt")
var started = false
val processor = object : Processor {
lateinit var processingEnv: ProcessingEnvironment
override fun getSupportedOptions() = setOf<String>()
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
if (!roundEnv.processingOver()) {
started = true
process(annotations, roundEnv, processingEnv)
}
return true
}
override fun init(env: ProcessingEnvironment) {
processingEnv = env
}
override fun getCompletions(
element: Element?,
annotation: AnnotationMirror?,
member: ExecutableElement?,
userText: String?
): Iterable<Completion>? {
return emptyList()
}
override fun getSupportedSourceVersion() = SourceVersion.RELEASE_6
override fun getSupportedAnnotationTypes() = supportedAnnotations.toSet()
}
doTest(ktFileName.canonicalPath, listOf(processor))
if (started != shouldRun) {
fail("Annotation processor " + (if (shouldRun) "was not started" else "was started"))
}
}
protected fun TypeElement.findMethods(name: String): List<JeMethodExecutableElement> {
return enclosedElements.filterIsInstance<JeMethodExecutableElement>().filter { it.simpleName.toString() == name }
}
protected fun TypeElement.findMethod(name: String, vararg parameterTypes: String): JeMethodExecutableElement {
return enclosedElements.first {
if (it !is JeMethodExecutableElement
|| it.simpleName.toString() != name
|| parameterTypes.size != it.parameters.size) return@first false
parameterTypes.zip(it.parameters).all { it.first == it.second.asType().toString() }
} as JeMethodExecutableElement
}
protected fun TypeElement.findField(name: String): JeVariableElement {
return enclosedElements.first { it is JeVariableElement && it.simpleName.toString() == name } as JeVariableElement
}
protected fun ProcessingEnvironment.findClass(fqName: String) = elementUtils.getTypeElement(fqName) as JeTypeElement
protected fun assertEquals(expected: String, actual: Name) = assertEquals(expected, actual.toString())
}
@@ -1,138 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.annotation.processing.test.processor
import org.jetbrains.kotlin.annotation.processing.impl.KotlinElements
import org.jetbrains.kotlin.java.model.elements.JeTypeElement
import org.jetbrains.kotlin.java.model.types.JeArrayType
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
class ElementsTests : AbstractProcessorTest() {
override val testDataDir = "plugins/annotation-processing/testData/elements"
fun testOverrides() = test("Overrides", "*") { _, _, env ->
val (parent, child, childChild) = Triple(env.findClass("Parent"), env.findClass("Child"), env.findClass("ChildOfChild"))
val parentA = parent.findMethod("a")
val childA = child.findMethod("a")
val childAString = child.findMethod("a", "java.lang.String")
val childB = child.findMethod("b")
val childChildA = childChild.findMethod("a")
val childChildACharSequence = childChild.findMethod("a", "java.lang.CharSequence")
val childChildB = childChild.findMethod("b")
fun ExecutableElement.assertOverrides(overridden: ExecutableElement, result: Boolean) {
assertEquals(result, env.elementUtils.overrides(this, overridden, enclosingElement as JeTypeElement))
}
parentA.assertOverrides(parentA, false)
childA.assertOverrides(parentA, true)
childAString.assertOverrides(childA, false)
childB.assertOverrides(parentA, false)
childChildA.assertOverrides(parentA, true)
childChildA.assertOverrides(childA, true)
childChildB.assertOverrides(childB, true)
childChildACharSequence.assertOverrides(childA, false)
}
fun testOverrides2() = test("Overrides2", "*") { _, _, env ->
val classes = listOf(env.findClass("Intf"), env.findClass("A"), env.findClass("B"))
val (intf, a, b) = classes.map { it.findMethod("a") }
fun ExecutableElement.assertOverrides(overridden: ExecutableElement, context: TypeElement, result: Boolean) {
assertEquals(result, env.elementUtils.overrides(this, overridden, context))
}
a.assertOverrides(intf, classes[1], false)
b.assertOverrides(a, classes[2], true)
b.assertOverrides(intf, classes[2], true)
a.assertOverrides(intf, classes[2], true)
}
fun testIsFunctionalInterface() = test("IsFunctionalInterface", "*") { _, _, env ->
with (env.elementUtils as KotlinElements) {
fun assertIsFunctionalInterface(fqName: String, isIntf: Boolean) {
assertEquals(isIntf, isFunctionalInterface(env.findClass(fqName)))
}
assertIsFunctionalInterface("A", false)
assertIsFunctionalInterface("A.AA", true)
assertIsFunctionalInterface("B", false)
assertIsFunctionalInterface("C", true)
assertIsFunctionalInterface("D", false)
assertIsFunctionalInterface("E", true)
assertIsFunctionalInterface("F", false)
}
}
fun testIsDeprecated() = test("IsDeprecated", "*") { _, _, env ->
with (env.elementUtils) {
assertEquals(true, isDeprecated(env.findClass("Depr")))
assertEquals(false, isDeprecated(env.findClass("NoDepr")))
assertEquals(true, isDeprecated(env.findClass("JavaDepr")))
}
}
fun testGetElementValuesWithDefaults() = test("GetElementValuesWithDefaults", "Anno") { _, _, env ->
val (a, b, c, d) = listOf(env.findClass("A"), env.findClass("B"), env.findClass("C"), env.findClass("D"))
fun getValues(e: JeTypeElement) = env.elementUtils
.getElementValuesWithDefaults(e.annotationMirrors.first { it.psi.qualifiedName == "Anno" })
.values.map { it.value }
assertEquals(listOf("Tom", 10), getValues(a))
assertEquals(listOf("Tom", 20), getValues(b))
assertEquals(listOf("Mary", 10), getValues(c))
assertEquals(listOf("Mary", 20), getValues(d))
}
fun testGetAllMembers() = test("GetAllMembers", "*") { _, _, env ->
val clazz = env.findClass("MyClass")
val members = clazz.enclosedElements
assertEquals(5, members.size) // constructor, field, getter/setter, arbitrary method
val allMembers = env.elementUtils.getAllMembers(clazz)
assertEquals(17, allMembers.size)
assertEquals("<init>, clone, equals, finalize, getClass, getMyProperty, hashCode, myFunction, myProperty, " +
"notify, notifyAll, registerNatives, setMyProperty, toString, wait, wait, wait",
allMembers.sortedBy { it.simpleName.toString() }.joinToString { it.simpleName })
}
fun testGetPackageOf() = test("GetPackageOf", "*") { _, _, env ->
val e = env.elementUtils
val myClass = env.findClass("test.MyClass")
val packageElement = e.getPackageOf(myClass)
assertEquals("test", packageElement.qualifiedName)
assertEquals(packageElement, e.getPackageOf(packageElement))
assertNull(e.getPackageElement("SomethingStrange"))
val testPackageElement = e.getPackageElement("test")
assertEquals(packageElement, testPackageElement)
assertFalse(packageElement.isUnnamed)
val classes = packageElement.enclosedElements.filterIsInstance<JeTypeElement>()
assertEquals(3, classes.size)
}
fun testGetArrayType() = test("GetPackageOf", "*") { _, _, env ->
val myClass = env.findClass("test.MyClass").asType()
val array = env.typeUtils.getArrayType(myClass)
assert(array is JeArrayType)
}
}
@@ -1,374 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.annotation.processing.test.processor
import org.intellij.lang.annotations.Language
import org.jetbrains.kotlin.annotation.processing.impl.KotlinProcessingEnvironment
import org.jetbrains.kotlin.java.model.elements.*
import org.jetbrains.kotlin.java.model.types.JeDeclaredType
import org.jetbrains.kotlin.java.model.types.JeMethodExecutableTypeMirror
import org.jetbrains.kotlin.java.model.util.DisposableRef
import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.AnnotationMirror
import javax.lang.model.element.Element
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeMirror
import javax.lang.model.type.TypeVariable
// See EnumArray.kt
enum class RGBColors { RED, GREEN, BLUE }
annotation class ColorsAnnotation(val colors: Array<RGBColors>)
class ProcessorTests : AbstractProcessorTest() {
override val testDataDir = "plugins/annotation-processing/testData/processors"
fun testSimple() = test("Simple", "Anno") { set, roundEnv, _ ->
assertEquals(1, set.size)
val annotated = roundEnv.getElementsAnnotatedWith(set.first())
assertEquals(3, annotated.size)
val clazz = annotated.firstIsInstance<JeTypeElement>()
val method = annotated.firstIsInstance<JeMethodExecutableElement>()
val field = annotated.firstIsInstance<JeVariableElement>()
listOf(clazz, method, field).forEach {
it.assertHasAnnotation("Anno", it.simpleName.toString() + "Anno")
}
}
fun testSeveralAnnotations() = test("SeveralAnnotations", "Name", "Age") { set, roundEnv, _ ->
val annos = set.toList()
assertEquals(2, annos.size)
val annotated1 = roundEnv.getElementsAnnotatedWith(annos[0]).sortedBy { it.simpleName.toString() }
val annotated2 = roundEnv.getElementsAnnotatedWith(annos[1]).sortedBy { it.simpleName.toString() }
assertEquals(2, annotated1.size)
assertEquals(annotated1, annotated2)
val (kate, mary) = Pair(annotated1[0] as JeTypeElement, annotated1[1] as JeTypeElement)
assertEquals("Mary", mary.simpleName)
with (kate) {
assertEquals("Kate", simpleName)
assertHasAnnotation("Name", "Kate")
assertHasAnnotation("Age", 22)
}
}
fun testStar() = test("Star", "*") { set, _, _ ->
assertEquals(true, set.any { it.qualifiedName.toString() == "Anno" })
}
fun testStar2() = test("Star", "Anno", "*") { set, _, _ ->
assertEquals(true, set.any { it.qualifiedName.toString() == "Anno" })
}
fun testStar3() = test("Star3", "Anno", "*") { set, _, _ ->
assertEquals(true, set.any { it.qualifiedName.toString() == "Anno2" })
}
fun testDoesNotRun() = testShouldNotRun("DoesNotRun", "Anno")
fun testDoesNotRun2() = testShouldNotRun("DoesNotRun2", "Anno")
fun testInheritedAnnotations() {
val handledClasses = mutableListOf<String>()
test("InheritedAnnotations", "Anno") { set, roundEnv, _ ->
assertEquals(1, set.size)
val annotatedElements = roundEnv.getElementsAnnotatedWith(set.first())
for (element in annotatedElements) {
handledClasses += element.simpleName.toString()
}
val implAnnotations = annotatedElements.first { it.simpleName.toString() == "Impl" }.annotationMirrors
// Should contain the inherited annotation
assertEquals(1, implAnnotations.size)
assertEquals("Anno", (implAnnotations.first() as JeAnnotationMirror).psi.qualifiedName)
}
// IntfImpl should not be here. Annotations can be inherited only from superclasses (not interfaces).
assertEquals(listOf("Base", "Impl", "Intf"), handledClasses.sorted())
}
fun testInheritedAnnotationsOverridden() = test("InheritedAnnotationsOverridden", "Anno") { set, roundEnv, _ ->
assertEquals(1, set.size)
val annotatedElements = roundEnv.getElementsAnnotatedWith(set.first())
assertEquals(2, annotatedElements.size)
val implAnnotations = annotatedElements.first { it.simpleName.toString() == "Impl" }.annotationMirrors
assertEquals(1, implAnnotations.size)
assertEquals("Tom", implAnnotations.first().elementValues.values.first().value)
}
fun testNested() = test("Nested", "Anno") { set, roundEnv, _ ->
assertEquals(1, set.size)
val annotatedElements = roundEnv.getElementsAnnotatedWith(set.first())
assertEquals(1, annotatedElements.size)
val test = annotatedElements.first()
val anno2 = test.annotationMirrors.first { it is JeAnnotationMirror && it.psi.qualifiedName == "Anno" }
fun AnnotationMirror.getParam(name: String) = elementValues.entries.first { it.key.simpleName.toString() == name }.value
assertTrue(anno2.getParam("a") is JeAnnotationAnnotationValue)
assertTrue((anno2.getParam("b") as JeArrayAnnotationValue).value.first() is JeAnnotationAnnotationValue)
assertTrue(anno2.getParam("c") is JePrimitiveAnnotationValue<*>)
assertTrue(anno2.getParam("d") is JeTypeAnnotationValue)
assertTrue((anno2.getParam("e") as JeArrayAnnotationValue).value.first() is JeTypeAnnotationValue)
}
fun testEnumArray() = test("EnumArray", "*") { _, _, env ->
val testClass = env.findClass("org.jetbrains.kotlin.annotation.processing.test.processor.Test")
val enumAnno = testClass.getAnnotation(ColorsAnnotation::class.java)
assertNotNull(enumAnno)
assertEquals(listOf("BLUE", "RED"), enumAnno!!.colors.map { it.name })
}
fun testStringArray() = test("StringArray", "*") { _, _, env ->
val testClass = env.findClass("Test")
val suppress = testClass.getAnnotation(Suppress::class.java)
assertNotNull(suppress)
assertEquals(listOf("Tom", "Mary"), suppress!!.names.toList())
}
fun testTypeArguments() = test("TypeArguments", "*") { _, _, env ->
val classA = env.findClass("A")
val superB = classA.superclass as JeDeclaredType
val interfaceC = classA.interfaces[0] as JeDeclaredType
assertTrue(superB.typeArguments.size == 1)
assertTrue(interfaceC.typeArguments.size == 1)
}
fun testTypeArguments2() = test("TypeArguments2", "*") { _, _, env ->
val b = env.findClass("B")
val bSuperTypes = env.typeUtils.directSupertypes(b.asType())
assertEquals(1, bSuperTypes.size)
val bASuperTypes = env.typeUtils.directSupertypes(bSuperTypes.first())
assertEquals(2, bASuperTypes.size) // Object and I
fun List<TypeMirror>.iInterface() = first { it.toString().matches("I(<.*>)?".toRegex()) } as DeclaredType
val bai = bASuperTypes.iInterface()
assertEquals(1, bai.typeArguments.size)
assertEquals("java.lang.String", bai.typeArguments.first().toString())
val c = env.findClass("C")
val cSuperTypes = env.typeUtils.directSupertypes(c.asType())
assertEquals(1, cSuperTypes.size)
val cai = env.typeUtils.directSupertypes(cSuperTypes.first()).iInterface()
assertEquals(1, cai.typeArguments.size)
val typeArg = cai.typeArguments.first()
assertTrue(typeArg is TypeVariable)
val a2 = env.findClass("A2")
val i2 = env.typeUtils.directSupertypes(a2.asType()).first { it.toString().matches("I2(<.*>)?".toRegex()) } as JeDeclaredType
assertEquals("I2<T>", i2.toString())
val stringType = env.elementUtils.getTypeElement("java.lang.String").asType()
val a3 = env.findClass("A3")
val resolvedA3 = env.typeUtils.getDeclaredType(a3, stringType)
val i3 = env.typeUtils.directSupertypes(resolvedA3).first { it.toString().matches("I3(<.*>)?".toRegex()) } as JeDeclaredType
assertEquals("I3<java.util.List<? extends java.lang.String>>", i3.toString())
}
fun testErasureSimple() = test("ErasureSimple", "*") { _, _, env ->
val test = env.findClass("Test")
val int = test.findMethod("a").returnType
val void = test.findMethod("b").returnType
assertEquals(int, env.typeUtils.erasure(int))
assertEquals(void, env.typeUtils.erasure(void))
}
fun testErasure2() = test("Erasure2", "*") { _, _, env ->
val erasure = fun (t: JeMethodExecutableTypeMirror) = env.typeUtils.erasure(t)
fun JeTypeElement.check(methodName: String, toString: String, transform: (JeMethodExecutableTypeMirror) -> TypeMirror = { it }) {
val method = enclosedElements.first { it is JeMethodExecutableElement && it.simpleName.toString() == methodName }
assertEquals(toString, transform((method as JeMethodExecutableElement).asType()).toString())
}
with (env.findClass("Test")) {
val classType = asType() as DeclaredType
assertEquals(1, classType.typeArguments.size)
assertEquals("Test<T>", classType.toString())
val erasedType = env.typeUtils.erasure(asType()) as DeclaredType
assertEquals(0, erasedType.typeArguments.size)
assertEquals("Test", erasedType.toString())
check("a", "()java.lang.String")
check("b", "(java.lang.String,java.lang.CharSequence)void")
check("c", "()int")
check("d", "()T")
check("e", "<D>(D)D")
check("e", "(java.lang.Object)java.lang.Object", erasure)
check("f", "(java.util.List<? extends java.util.Map<java.lang.String,java.lang.Integer>>,int)void")
check("f", "(java.util.List,int)void", erasure)
check("g", "<D>(D)void")
check("g", "(java.lang.String)void", erasure)
check("h", "()java.util.List<java.lang.String>[]")
check("h", "()java.util.List[]", erasure)
check("i", "<T>()T")
check("i", "()java.lang.CharSequence", erasure)
}
with (env.findClass("Test2")) {
assertEquals("Test2<A,B>", asType().toString())
assertEquals("Test2", env.typeUtils.erasure(asType()).toString())
check("a", "(A)void")
check("a", "(java.util.List)void", erasure)
check("b", "()B")
check("b", "()java.util.List", erasure)
}
}
fun testIncrementalDataSimple() = incrementalDataTest(
"IncrementalDataSimple",
"i Intf, i Test, i Test2, i Test3, i Test6, i Test7, i Test8")
fun testIncrementalDataKotlinAnnotations() = incrementalDataTest(
"KotlinAnnotations",
"i AnnoAnnotated")
private fun getKapt2Extension() = AnalysisHandlerExtension.getInstances(myEnvironment.project)
.firstIsInstance<AnnotationProcessingExtensionForTests>()
private fun incrementalDataTest(fileName: String, @Language("TEXT") expectedText: String) {
test(fileName, "Anno", "Anno2", "Anno3") { _, _, _ -> }
val ext = getKapt2Extension()
val incrementalDataFile = ext.incrementalDataFile
assertNotNull(incrementalDataFile)
val text = incrementalDataFile!!.readText().lines().sorted().joinToString(", ")
assertEquals(expectedText, text)
}
fun testKotlinAnnotationDefaultValueFromBinary() = test("DefaultValueFromBinary", "*") { _, _, env ->
fun check(expectedValue: Boolean, className: String) {
val clazz = env.findClass(className)
val anno = clazz.getAnnotation(JvmSuppressWildcards::class.java)!!
assertEquals(expectedValue, anno.suppress)
}
check(true, "Test")
check(true, "TestTrue")
check(false, "TestFalse")
}
fun testAsMemberOf() = test("AsMemberOf", "*") { _, _, env ->
val f = env.findClass("Test").findField("f")
val fType = f.asType() as JeDeclaredType
val base = env.findClass("Base")
val impl = env.findClass("Impl")
val baseF = base.findField("f")
val baseM = base.findMethod("m", "T")
val implM = impl.findMethod("implM", "T")
fun check(element: Element, expectedTypeSignature: String) {
assertEquals(expectedTypeSignature, env.typeUtils.asMemberOf(fType, element).toString())
}
assertEquals("(T)T", baseM.asType().toString())
check(baseM, "(java.lang.String)java.lang.String")
assertEquals("T", baseF.asType().toString())
check(baseF, "java.lang.String")
assertEquals("(T)T", implM.asType().toString())
check(implM, "(java.lang.String)java.lang.String")
}
fun testAsMemberOfTypeParameters() = test("AsMemberOfTypeParameters", "*") { _, _, env ->
val intf = env.findClass("Intf")
val intfT = intf.typeParameters[0]
val base = env.findClass("Base")
val baseFactory = base.findMethod("factory")
val impl = env.findClass("Impl")
assertEquals("T", intfT.asType().toString())
val implT = env.typeUtils.asMemberOf(impl.asType() as DeclaredType, intfT)
assertEquals("java.lang.String", implT.toString())
val baseT = env.typeUtils.asMemberOf(baseFactory.returnType as DeclaredType, intfT)
assertEquals("java.lang.CharSequence", baseT.toString())
}
fun testDispose() {
var savedEnv: ProcessingEnvironment? = null
test("AsMemberOf", "*") { _, _, env ->
savedEnv = env
}
fun <T> T.test(f: T.() -> Unit) {
var exceptionCaught = false
try {
f()
}
catch (e: IllegalStateException) {
exceptionCaught = true
}
assertEquals("Exception was not caught", true, exceptionCaught)
}
with (savedEnv as KotlinProcessingEnvironment) {
test { elementUtils }
test { typeUtils }
test { messager }
test { options }
test { filer }
fun testDisposable(name: String) {
test { (this::class.java.methods.first { it.name.startsWith("$name$") }.invoke(this) as DisposableRef<*>).invoke() }
}
testDisposable("getProject")
testDisposable("getJavaPsiFacade")
testDisposable("getBindingContext")
}
}
fun testMapMutableMap() = test("MapMutableMap", "*") { _, _, env ->
val test = env.findClass("Test")
fun test(name: String, expected: String) {
assertEquals(expected, test.findMethods(name).single().parameters.single().asType().toString())
}
test("a", "java.util.Map<java.lang.Integer,? extends Intf>")
test("b", "java.util.Map<java.lang.Integer,Intf>")
test("c", "java.util.Map<java.lang.Integer,Test>")
test("d", "java.util.Map<java.lang.Integer,Test>")
}
fun testExceptionDuringAp() {
class HiThere : RuntimeException()
var kotlinEnv: KotlinProcessingEnvironment? = null
try {
test("MapMutableMap", "*") { _, _, env ->
kotlinEnv = env as KotlinProcessingEnvironment
throw HiThere()
}
} catch (e: IllegalStateException) {
assertTrue(e.message!!.startsWith("ANNOTATION_PROCESSING_ERROR"))
}
val env = kotlinEnv!!
assertEquals(1, env.messager.errorCount)
assertEquals(0, env.messager.warningCount)
}
}
@@ -1,74 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.annotation.processing.test.processor
import java.io.File
import javax.lang.model.element.TypeElement
import javax.tools.JavaFileObject
class TestsWithFiler : AbstractProcessorTest() {
override val testDataDir = "plugins/annotation-processing/testData/withFiler"
fun testSimple() = filerTest("Simple", 1, "generated/Inject2Test.java")
fun testMethodsFields() = filerTest("MethodsFields", 1,
"generated/InjectmyField.java",
"generated/InjectmyFunc.java")
fun testTwoRounds() = filerTest("TwoRounds", 2,
"generated/Inject2InjectTest.java",
"generated/InjectTest.java",
"generated/InjectmyFunc.java")
fun testOneRound() = filerTest("OneRound", 1,
"generated/Inject2Test.java",
"generated/Inject2myFunc.java",
"generated/InjectmyFunc.java")
fun testZeroRounds() = filerTest("ZeroRounds", 0)
private fun filerTest(
fileName: String,
roundCount: Int,
vararg expectedFiles: String
) {
val filesCreated = mutableSetOf<JavaFileObject>()
var actualRoundCount = 0
testAP(roundCount > 0, fileName, { set, roundEnv, env ->
if (!roundEnv.processingOver()) actualRoundCount++
for (anno in set) {
val annotated = roundEnv.getElementsAnnotatedWith(anno)
annotated.forEach { el ->
val className = anno.simpleName.toString() + el.simpleName.toString()
env.filer.createSourceFile("generated.$className").apply {
filesCreated += this
val inject2 = if (el is TypeElement && anno.simpleName.toString() == "Inject") "@Inject2\n" else ""
openWriter().use {
it.write("package generated;\n" + inject2 +
"public class $className {}")
}
}
}
}
}, "Inject", "Inject2")
assertEquals(roundCount, actualRoundCount)
assertEquals(expectedFiles.map { it.replace('/', File.separatorChar) }, filesCreated.map { it.name }.sorted())
}
}
@@ -1,34 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.annotation.processing.test.sourceRetention
import org.jetbrains.kotlin.codegen.AbstractBytecodeListingTest
import org.jetbrains.kotlin.codegen.ClassBuilderFactories
import org.jetbrains.kotlin.codegen.ClassBuilderFactory
abstract class AbstractBytecodeListingTestForSourceRetention : AbstractBytecodeListingTest() {
override fun getClassBuilderFactory(): ClassBuilderFactory {
return if (getTestName(true).contains("withSource", ignoreCase = true))
ClassBuilderFactories.TEST_WITH_SOURCE_RETENTION_ANNOTATIONS
else
ClassBuilderFactories.TEST
}
override fun verifyWithDex(): Boolean {
return false
}
}
@@ -1,50 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.annotation.processing.test.sourceRetention;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TargetBackend;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("plugins/annotation-processing/testData/sourceRetention")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class BytecodeListingTestForSourceRetentionGenerated extends AbstractBytecodeListingTestForSourceRetention {
public void testAllFilesPresentInSourceRetention() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("plugins/annotation-processing/testData/sourceRetention"), Pattern.compile("^(.+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("withSource.kt")
public void testWithSource() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/sourceRetention/withSource.kt");
doTest(fileName);
}
@TestMetadata("withoutSource.kt")
public void testWithoutSource() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/sourceRetention/withoutSource.kt");
doTest(fileName);
}
}
@@ -1,60 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.annotation.processing.test.wrappers
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.testFramework.registerServiceInstance
import org.jetbrains.kotlin.codegen.AbstractBytecodeTextTest
import org.jetbrains.kotlin.codegen.CodegenTestCase
import org.jetbrains.kotlin.codegen.CodegenTestUtil
import org.jetbrains.kotlin.java.model.elements.DefaultJeElementRenderer
import org.jetbrains.kotlin.java.model.internal.JeElementRegistry
import org.jetbrains.kotlin.java.model.toJeElement
import org.jetbrains.kotlin.test.ConfigurationKind
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
import java.util.regex.Pattern
abstract class AbstractAnnotationProcessingTest : AbstractBytecodeTextTest() {
companion object {
private val SUBJECT_FQ_NAME_PATTERN = Pattern.compile("^// FQNAME: \\s*(.*)$", Pattern.MULTILINE)
private val RENDERER = DefaultJeElementRenderer()
}
override fun doMultiFileTest(wholeFile: File, files: List<CodegenTestCase.TestFile>, javaFilesDir: File?) {
createEnvironmentWithMockJdkAndIdeaAnnotations(ConfigurationKind.ALL, files, javaFilesDir)
myEnvironment.project.registerServiceInstance(JeElementRegistry::class.java, JeElementRegistry())
loadMultiFiles(files)
val text = FileUtil.loadFile(wholeFile, true)
val matcher = SUBJECT_FQ_NAME_PATTERN.matcher(text)
assertTrue("No FqName specified. First line of the form '// f.q.Name' expected", matcher.find())
val fqName = matcher.group(1)
CodegenTestUtil.generateFiles(myEnvironment, myFiles)
val project = myEnvironment.project
val psiClass = JavaPsiFacade.getInstance(project).findClass(fqName, GlobalSearchScope.projectScope(project))!!
val modelFile = File(wholeFile.parent, wholeFile.nameWithoutExtension + ".txt")
val jeElement = psiClass.toJeElement() ?: error("JeElement is null")
KotlinTestUtils.assertEqualsToFile(modelFile, RENDERER.render(jeElement))
}
}
@@ -1,122 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.annotation.processing.test.wrappers;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TargetBackend;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("plugins/annotation-processing/testData/wrappers")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class AnnotationProcessingTestGenerated extends AbstractAnnotationProcessingTest {
public void testAllFilesPresentInWrappers() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("plugins/annotation-processing/testData/wrappers"), Pattern.compile("^(.+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("plugins/annotation-processing/testData/wrappers/javaWrappers")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class JavaWrappers extends AbstractAnnotationProcessingTest {
public void testAllFilesPresentInJavaWrappers() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("plugins/annotation-processing/testData/wrappers/javaWrappers"), Pattern.compile("^(.+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("EnumClass.kt")
public void testEnumClass() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/javaWrappers/EnumClass.kt");
doTest(fileName);
}
@TestMetadata("MetaAnnotation.kt")
public void testMetaAnnotation() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/javaWrappers/MetaAnnotation.kt");
doTest(fileName);
}
@TestMetadata("Simple.kt")
public void testSimple() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/javaWrappers/Simple.kt");
doTest(fileName);
}
@TestMetadata("WithNested.kt")
public void testWithNested() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/javaWrappers/WithNested.kt");
doTest(fileName);
}
}
@TestMetadata("plugins/annotation-processing/testData/wrappers/kotlinWrappers")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class KotlinWrappers extends AbstractAnnotationProcessingTest {
public void testAllFilesPresentInKotlinWrappers() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("plugins/annotation-processing/testData/wrappers/kotlinWrappers"), Pattern.compile("^(.+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("annotations.kt")
public void testAnnotations() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/kotlinWrappers/annotations.kt");
doTest(fileName);
}
@TestMetadata("enum.kt")
public void testEnum() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/kotlinWrappers/enum.kt");
doTest(fileName);
}
@TestMetadata("kotlinAnnotations.kt")
public void testKotlinAnnotations() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/kotlinWrappers/kotlinAnnotations.kt");
doTest(fileName);
}
@TestMetadata("metaAnnotations.kt")
public void testMetaAnnotations() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/kotlinWrappers/metaAnnotations.kt");
doTest(fileName);
}
@TestMetadata("nestedClasses.kt")
public void testNestedClasses() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/kotlinWrappers/nestedClasses.kt");
doTest(fileName);
}
@TestMetadata("repeatableAnnotations.kt")
public void testRepeatableAnnotations() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/kotlinWrappers/repeatableAnnotations.kt");
doTest(fileName);
}
@TestMetadata("simple.kt")
public void testSimple() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/annotation-processing/testData/wrappers/kotlinWrappers/simple.kt");
doTest(fileName);
}
}
}