blob: fd142c62e8e3b7941e03e9b46cbf2bb68d12e78e [file] [log] [blame]
Ashley Rosede080eb2018-12-07 17:20:25 -05001/*
Ashley Rosec1a4dec2018-12-13 18:06:30 -05002 * Copyright 2019 The Android Open Source Project
Ashley Rosede080eb2018-12-07 17:20:25 -05003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.processor.view.inspector;
18
19import static javax.tools.Diagnostic.Kind.ERROR;
20
21import com.squareup.javapoet.ClassName;
22
23import java.io.IOException;
24import java.util.HashMap;
25import java.util.Map;
26import java.util.Optional;
27import java.util.Set;
28
29import javax.annotation.processing.AbstractProcessor;
30import javax.annotation.processing.RoundEnvironment;
31import javax.annotation.processing.SupportedAnnotationTypes;
32import javax.lang.model.SourceVersion;
33import javax.lang.model.element.Element;
34import javax.lang.model.element.ElementKind;
Ashley Rose0b671da2019-01-25 15:41:29 -050035import javax.lang.model.element.Modifier;
Ashley Rosede080eb2018-12-07 17:20:25 -050036import javax.lang.model.element.TypeElement;
Ashley Rosefdb5af22019-03-08 17:23:38 -050037import javax.lang.model.util.ElementFilter;
Ashley Rosede080eb2018-12-07 17:20:25 -050038
39
40/**
41 * An annotation processor for the platform inspectable annotations.
42 *
43 * It mostly delegates to {@link ModelProcessor} and {@link InspectionCompanionGenerator}. This
44 * modular architecture allows the core generation code to be reused for comparable annotations
45 * outside the platform, such as in AndroidX.
46 *
47 * @see android.view.inspector.InspectableNodeName
48 * @see android.view.inspector.InspectableProperty
49 */
50@SupportedAnnotationTypes({
Ashley Rosec1a4dec2018-12-13 18:06:30 -050051 PlatformInspectableProcessor.NODE_NAME_QUALIFIED_NAME,
52 PlatformInspectableProcessor.PROPERTY_QUALIFIED_NAME
Ashley Rosede080eb2018-12-07 17:20:25 -050053})
54public final class PlatformInspectableProcessor extends AbstractProcessor {
55 static final String NODE_NAME_QUALIFIED_NAME =
56 "android.view.inspector.InspectableNodeName";
Ashley Rosec1a4dec2018-12-13 18:06:30 -050057 static final String PROPERTY_QUALIFIED_NAME =
58 "android.view.inspector.InspectableProperty";
Ashley Rosede080eb2018-12-07 17:20:25 -050059
60 @Override
61 public SourceVersion getSupportedSourceVersion() {
62 return SourceVersion.latest();
63 }
64
65 @Override
66 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
67 final Map<String, InspectableClassModel> modelMap = new HashMap<>();
68
69 for (TypeElement annotation : annotations) {
70 if (annotation.getQualifiedName().contentEquals(NODE_NAME_QUALIFIED_NAME)) {
71 runModelProcessor(
72 roundEnv.getElementsAnnotatedWith(annotation),
73 new InspectableNodeNameProcessor(NODE_NAME_QUALIFIED_NAME, processingEnv),
74 modelMap);
75
Ashley Rosec1a4dec2018-12-13 18:06:30 -050076 } else if (annotation.getQualifiedName().contentEquals(PROPERTY_QUALIFIED_NAME)) {
77 runModelProcessor(
78 roundEnv.getElementsAnnotatedWith(annotation),
79 new InspectablePropertyProcessor(PROPERTY_QUALIFIED_NAME, processingEnv),
80 modelMap);
Ashley Rosede080eb2018-12-07 17:20:25 -050081
82 } else {
83 fail("Unexpected annotation type", annotation);
84 }
85 }
86
87 final InspectionCompanionGenerator generator =
88 new InspectionCompanionGenerator(processingEnv.getFiler(), getClass());
89
90 for (InspectableClassModel model : modelMap.values()) {
91 try {
92 generator.generate(model);
93 } catch (IOException ioException) {
94 fail(String.format(
95 "Unable to generate inspection companion for %s due to %s",
96 model.getClassName().toString(),
97 ioException.getMessage()));
98 }
99 }
100
101 return true;
102 }
103
104 /**
105 * Run a {@link ModelProcessor} for a set of elements
106 *
107 * @param elements Elements to process, should be annotated correctly
108 * @param processor The processor to use
109 * @param modelMap A map of qualified class names to models
110 */
111 private void runModelProcessor(
112 Set<? extends Element> elements,
113 ModelProcessor processor,
114 Map<String, InspectableClassModel> modelMap) {
115 for (Element element : elements) {
116 final Optional<TypeElement> classElement = enclosingClassElement(element);
117
118 if (!classElement.isPresent()) {
119 fail("Element not contained in a class", element);
120 break;
121 }
122
Ashley Rose0b671da2019-01-25 15:41:29 -0500123 final Set<Modifier> classModifiers = classElement.get().getModifiers();
124
125 if (classModifiers.contains(Modifier.PRIVATE)) {
126 fail("Enclosing class cannot be private", element);
127 }
128
Ashley Rosede080eb2018-12-07 17:20:25 -0500129 final InspectableClassModel model = modelMap.computeIfAbsent(
130 classElement.get().getQualifiedName().toString(),
Ashley Rosefdb5af22019-03-08 17:23:38 -0500131 k -> {
132 if (hasNestedInspectionCompanion(classElement.get())) {
133 fail(
134 String.format(
135 "Class %s already has an inspection companion.",
136 classElement.get().getQualifiedName().toString()),
137 element);
138 }
139 return new InspectableClassModel(ClassName.get(classElement.get()));
140 });
Ashley Rosede080eb2018-12-07 17:20:25 -0500141
142 processor.process(element, model);
143 }
144 }
145
146 /**
Ashley Rosefdb5af22019-03-08 17:23:38 -0500147 * Determine if a class has a nested class named {@code InspectionCompanion}.
148 *
149 * @param typeElement A type element representing the class to check
150 * @return f the class contains a class named {@code InspectionCompanion}
151 */
152 private static boolean hasNestedInspectionCompanion(TypeElement typeElement) {
153 for (TypeElement nestedClass : ElementFilter.typesIn(typeElement.getEnclosedElements())) {
154 if (nestedClass.getSimpleName().toString().equals("InspectionCompanion")) {
155 return true;
156 }
157 }
158
159 return false;
160 }
161
162 /**
Ashley Rosede080eb2018-12-07 17:20:25 -0500163 * Get the nearest enclosing class if there is one.
164 *
165 * If {@param element} represents a class, it will be returned wrapped in an optional.
166 *
167 * @param element An element to search from
168 * @return A TypeElement of the nearest enclosing class or an empty optional
169 */
170 private static Optional<TypeElement> enclosingClassElement(Element element) {
171 Element cursor = element;
172
173 while (cursor != null) {
174 if (cursor.getKind() == ElementKind.CLASS) {
175 return Optional.of((TypeElement) cursor);
176 }
177
178 cursor = cursor.getEnclosingElement();
179 }
180
181 return Optional.empty();
182 }
183
184 /**
185 * Print message and fail the build.
186 *
187 * @param message Message to print
188 */
189 private void fail(String message) {
190 processingEnv.getMessager().printMessage(ERROR, message);
191 }
192
193 /**
194 * Print message and fail the build.
195 *
196 * @param message Message to print
197 * @param element The element that failed
198 */
199 private void fail(String message, Element element) {
200 processingEnv.getMessager().printMessage(ERROR, message, element);
201 }
202}