• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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.internal.codegen;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 
21 import com.google.auto.common.BasicAnnotationProcessor.ProcessingStep;
22 import com.google.common.collect.ImmutableSet;
23 import com.google.common.collect.ImmutableSetMultimap;
24 import com.google.common.collect.SetMultimap;
25 import java.lang.annotation.Annotation;
26 import java.util.function.Function;
27 import javax.lang.model.element.Element;
28 
29 /**
30  * A {@link ProcessingStep} that processes one element at a time and defers any for which {@link
31  * TypeNotPresentException} is thrown.
32  */
33 // TODO(dpb): Contribute to auto-common.
34 abstract class TypeCheckingProcessingStep<E extends Element> implements ProcessingStep {
35   private final Function<Element, E> downcaster;
36 
TypeCheckingProcessingStep(Function<Element, E> downcaster)37   TypeCheckingProcessingStep(Function<Element, E> downcaster) {
38     this.downcaster = checkNotNull(downcaster);
39   }
40 
41   @Override
process( SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation)42   public ImmutableSet<Element> process(
43       SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) {
44     ImmutableSet.Builder<Element> deferredElements = ImmutableSet.builder();
45     ImmutableSetMultimap.copyOf(elementsByAnnotation)
46         .inverse()
47         .asMap()
48         .forEach(
49             (element, annotations) -> {
50               try {
51                 process(downcaster.apply(element), ImmutableSet.copyOf(annotations));
52               } catch (TypeNotPresentException e) {
53                 deferredElements.add(element);
54               }
55             });
56     return deferredElements.build();
57   }
58 
59   /**
60    * Processes one element. If this method throws {@link TypeNotPresentException}, the element will
61    * be deferred until the next round of processing.
62    *
63    * @param annotations the subset of {@link ProcessingStep#annotations()} that annotate {@code
64    *     element}
65    */
process(E element, ImmutableSet<Class<? extends Annotation>> annotations)66   protected abstract void process(E element, ImmutableSet<Class<? extends Annotation>> annotations);
67 }
68