1 /* 2 * Copyright (C) 2014 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.validation; 18 19 import static javax.lang.model.util.ElementFilter.methodsIn; 20 21 import dagger.MapKey; 22 import dagger.internal.codegen.langmodel.DaggerElements; 23 import java.util.List; 24 import javax.inject.Inject; 25 import javax.lang.model.element.Element; 26 import javax.lang.model.element.ExecutableElement; 27 import javax.lang.model.element.TypeElement; 28 import javax.lang.model.type.TypeKind; 29 30 /** 31 * A validator for {@link MapKey} annotations. 32 */ 33 // TODO(dpb,gak): Should unwrapped MapKeys be required to have their single member be named "value"? 34 public final class MapKeyValidator { 35 private final DaggerElements elements; 36 37 @Inject MapKeyValidator(DaggerElements elements)38 MapKeyValidator(DaggerElements elements) { 39 this.elements = elements; 40 } 41 validate(Element element)42 public ValidationReport<Element> validate(Element element) { 43 ValidationReport.Builder<Element> builder = ValidationReport.about(element); 44 List<ExecutableElement> members = methodsIn(((TypeElement) element).getEnclosedElements()); 45 if (members.isEmpty()) { 46 builder.addError("Map key annotations must have members", element); 47 } else if (element.getAnnotation(MapKey.class).unwrapValue()) { 48 if (members.size() > 1) { 49 builder.addError( 50 "Map key annotations with unwrapped values must have exactly one member", element); 51 } else if (members.get(0).getReturnType().getKind() == TypeKind.ARRAY) { 52 builder.addError("Map key annotations with unwrapped values cannot use arrays", element); 53 } 54 } else if (autoAnnotationIsMissing()) { 55 builder.addError( 56 "@AutoAnnotation is a necessary dependency if @MapKey(unwrapValue = false). Add a " 57 + "dependency on com.google.auto.value:auto-value:<current version>"); 58 } 59 return builder.build(); 60 } 61 autoAnnotationIsMissing()62 private boolean autoAnnotationIsMissing() { 63 return elements.getTypeElement("com.google.auto.value.AutoAnnotation") == null; 64 } 65 } 66