-
Notifications
You must be signed in to change notification settings - Fork 7
/
Processor.kt
75 lines (61 loc) · 3 KB
/
Processor.kt
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
package com.hitanshudhawan.ksingleton_compiler
import com.hitanshudhawan.ksingleton_annotations.KSingleton
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
import javax.lang.model.element.Modifier
import javax.lang.model.element.TypeElement
import javax.lang.model.util.ElementFilter
import javax.tools.Diagnostic
class Processor : AbstractProcessor() {
private var mProcessingEnvironment: ProcessingEnvironment? = null
override fun init(processingEnvironment: ProcessingEnvironment) {
super.init(processingEnvironment)
mProcessingEnvironment = processingEnvironment
}
override fun process(annotations: Set<TypeElement>, roundEnvironment: RoundEnvironment): Boolean {
for (typeElement in ElementFilter.typesIn(roundEnvironment.getElementsAnnotatedWith(KSingleton::class.java))) {
if (!checkForPrivateConstructors(typeElement)) return false
if (!checkForGetInstanceMethod(typeElement)) return false
}
return true
}
private fun checkForPrivateConstructors(typeElement: TypeElement): Boolean {
val constructors = ElementFilter.constructorsIn(typeElement.enclosedElements)
for (constructor in constructors) {
if (constructor.modifiers.isEmpty() || !constructor.modifiers.contains(Modifier.PRIVATE)) {
mProcessingEnvironment!!.messager.printMessage(Diagnostic.Kind.ERROR, "constructor of a singleton class must be private", constructor)
return false
}
}
return true
}
private fun checkForGetInstanceMethod(typeElement: TypeElement): Boolean {
val methods = ElementFilter.methodsIn(typeElement.enclosedElements)
for (method in methods) {
// check for name
if (method.simpleName.contentEquals("getInstance")) {
// check for return type
if (mProcessingEnvironment!!.typeUtils.isSameType(method.returnType, typeElement.asType())) {
// check for modifiers
if (method.modifiers.contains(Modifier.PRIVATE)) {
mProcessingEnvironment!!.messager.printMessage(Diagnostic.Kind.ERROR, "getInstance method can't have a private modifier", method)
return false
}
if (!method.modifiers.contains(Modifier.STATIC)) {
mProcessingEnvironment!!.messager.printMessage(Diagnostic.Kind.ERROR, "getInstance method should have a static modifier", method)
return false
}
}
}
}
return true
}
override fun getSupportedAnnotationTypes(): Set<String> {
return setOf(KSingleton::class.java.canonicalName)
}
override fun getSupportedSourceVersion(): SourceVersion {
return SourceVersion.latestSupported()
}
}