| package com.google.autofactory; |
| |
| import static com.google.common.base.Preconditions.checkArgument; |
| import static javax.tools.Diagnostic.Kind.ERROR; |
| |
| import javax.annotation.processing.Messager; |
| import javax.inject.Inject; |
| import javax.lang.model.element.Element; |
| import javax.lang.model.element.ExecutableElement; |
| import javax.lang.model.element.VariableElement; |
| import javax.lang.model.util.ElementKindVisitor6; |
| |
| final class ProvidedChecker { |
| private final Messager messager; |
| |
| @Inject ProvidedChecker(Messager messager) { |
| this.messager = messager; |
| } |
| |
| void checkProvidedParameter(Element element) { |
| checkArgument(element.getAnnotation(Provided.class) != null); |
| element.accept(new ElementKindVisitor6<Void, Void>() { |
| @Override |
| protected Void defaultAction(Element e, Void p) { |
| throw new AssertionError("Provided can only be applied to parameters"); |
| } |
| |
| @Override |
| public Void visitVariableAsParameter(final VariableElement providedParameter, Void p) { |
| providedParameter.getEnclosingElement().accept(new ElementKindVisitor6<Void, Void>() { |
| @Override |
| protected Void defaultAction(Element e, Void p) { |
| raiseError(providedParameter, "@%s may only be applied to constructor parameters"); |
| return null; |
| } |
| |
| @Override |
| public Void visitExecutableAsConstructor(ExecutableElement constructor, Void p) { |
| if (!(annotatedWithAutoFactory(constructor) |
| || annotatedWithAutoFactory(constructor.getEnclosingElement()))) { |
| raiseError(providedParameter, |
| "@%s may only be applied to classes requesting an auto-factory"); |
| } |
| return null; |
| } |
| }, p); |
| return null; |
| } |
| }, null); |
| } |
| |
| private void raiseError(VariableElement providedParameter, String messageFormat) { |
| messager.printMessage(ERROR, String.format(messageFormat, Provided.class.getSimpleName()), |
| providedParameter); |
| } |
| |
| private static boolean annotatedWithAutoFactory(Element e) { |
| return e.getAnnotation(AutoFactory.class) != null; |
| } |
| } |