1 /*
2  * Copyright (C) 2019 The Dagger Authors.
3  *
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 
17 package dagger.hilt.processor.internal;
18 
19 import com.google.auto.common.MoreElements;
20 import com.google.auto.value.AutoValue;
21 import com.google.common.base.Throwables;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Optional;
25 import javax.annotation.processing.Messager;
26 import javax.annotation.processing.ProcessingEnvironment;
27 import javax.lang.model.element.Element;
28 import javax.lang.model.util.Elements;
29 import javax.tools.Diagnostic.Kind;
30 
31 /** Utility class to handle keeping track of errors during processing. */
32 final class ProcessorErrorHandler {
33 
34   private static final String FAILURE_PREFIX = "[Hilt]\n";
35 
36   // Special characters to make the tag red and bold to draw attention since
37   // this error can get drowned out by other errors resulting from missing
38   // symbols when we can't generate code.
39   private static final String FAILURE_SUFFIX =
40       "\n\033[1;31m[Hilt] Processing did not complete. See error above for details.\033[0m";
41 
42   private final Messager messager;
43   private final Elements elements;
44   private final List<HiltError> hiltErrors;
45 
ProcessorErrorHandler(ProcessingEnvironment env)46   ProcessorErrorHandler(ProcessingEnvironment env) {
47     this.messager = env.getMessager();
48     this.elements = env.getElementUtils();
49     this.hiltErrors = new ArrayList<>();
50   }
51 
52   /**
53    * Records an error message for some exception to the messager. This can be used to handle
54    * exceptions gracefully that would otherwise be propagated out of the {@code process} method. The
55    * message is stored in order to allow the build to continue as far as it can. The build will be
56    * failed with a {@link Kind#ERROR} in {@link #checkErrors} if an error was recorded with this
57    * method.
58    */
recordError(Throwable t)59   void recordError(Throwable t) {
60     // Store messages to allow the build to continue as far as it can. The build will
61     // be failed in checkErrors when processing is over.
62 
63     if (t instanceof BadInputException) {
64       BadInputException badInput = (BadInputException) t;
65       for (Element element : badInput.getBadElements()) {
66         hiltErrors.add(HiltError.of(badInput.getMessage(), element));
67       }
68     } else if (t instanceof ErrorTypeException) {
69       ErrorTypeException badInput = (ErrorTypeException) t;
70       hiltErrors.add(HiltError.of(badInput.getMessage(), badInput.getBadElement()));
71     } else if (t.getMessage() != null) {
72       hiltErrors.add(HiltError.of(t.getMessage() + ": " + Throwables.getStackTraceAsString(t)));
73     } else {
74       hiltErrors.add(HiltError.of(t.getClass() + ": " + Throwables.getStackTraceAsString(t)));
75     }
76   }
77 
78   /** Checks for any recorded errors. This should be called at the end of process every round. */
checkErrors()79   void checkErrors() {
80     if (!hiltErrors.isEmpty()) {
81       hiltErrors.forEach(
82           hiltError -> {
83             if (hiltError.element().isPresent()) {
84               Element element = hiltError.element().get();
85               if (MoreElements.isType(element)) {
86                 // If the error type is a TypeElement, get a new one just in case it was thrown in a
87                 // previous round we can report the correct instance. Otherwise, this leads to
88                 // issues in AndroidStudio when linking an error to the proper element.
89                 // TODO(bcorso): Consider only allowing TypeElement errors when delaying errors,
90                 // or maybe even removing delayed errors altogether.
91                 element =
92                     elements.getTypeElement(
93                         MoreElements.asType(element).getQualifiedName().toString());
94               }
95               messager.printMessage(Kind.ERROR, hiltError.message(), element);
96             } else {
97               messager.printMessage(Kind.ERROR, hiltError.message());
98             }
99           });
100       hiltErrors.clear();
101     }
102   }
103 
104   @AutoValue
105   abstract static class HiltError {
of(String message)106     static HiltError of(String message) {
107       return of(message, Optional.empty());
108     }
109 
of(String message, Element element)110     static HiltError of(String message, Element element) {
111       return of(message, Optional.of(element));
112     }
113 
of(String message, Optional<Element> element)114     private static HiltError of(String message, Optional<Element> element) {
115       return new AutoValue_ProcessorErrorHandler_HiltError(
116           FAILURE_PREFIX + message + FAILURE_SUFFIX, element);
117     }
118 
message()119     abstract String message();
120 
element()121     abstract Optional<Element> element();
122   }
123 }
124