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 androidx.room.compiler.processing.XAnnotationKt; 20 import androidx.room.compiler.processing.XMethodElement; 21 import androidx.room.compiler.processing.XTypeElement; 22 import androidx.room.compiler.processing.XTypeKt; 23 import dagger.MapKey; 24 import dagger.internal.codegen.javapoet.TypeNames; 25 import dagger.internal.codegen.langmodel.DaggerElements; 26 import java.util.List; 27 import javax.inject.Inject; 28 29 /** A validator for {@link MapKey} annotations. */ 30 // TODO(dpb,gak): Should unwrapped MapKeys be required to have their single member be named "value"? 31 public final class MapKeyValidator { 32 private final DaggerElements elements; 33 34 @Inject MapKeyValidator(DaggerElements elements)35 MapKeyValidator(DaggerElements elements) { 36 this.elements = elements; 37 } 38 validate(XTypeElement element)39 public ValidationReport validate(XTypeElement element) { 40 ValidationReport.Builder builder = ValidationReport.about(element); 41 List<XMethodElement> members = element.getDeclaredMethods(); 42 if (members.isEmpty()) { 43 builder.addError("Map key annotations must have members", element); 44 } else if (XAnnotationKt.get( 45 element.getAnnotation(TypeNames.MAP_KEY), "unwrapValue", Boolean.class)) { 46 if (members.size() > 1) { 47 builder.addError( 48 "Map key annotations with unwrapped values must have exactly one member", element); 49 } else if (XTypeKt.isArray(members.get(0).getReturnType())) { 50 builder.addError("Map key annotations with unwrapped values cannot use arrays", element); 51 } 52 } else if (autoAnnotationIsMissing()) { 53 builder.addError( 54 "@AutoAnnotation is a necessary dependency if @MapKey(unwrapValue = false). Add a " 55 + "dependency for the annotation, " 56 + "\"com.google.auto.value:auto-value-annotations:<current version>\", " 57 + "and the annotation processor, " 58 + "\"com.google.auto.value:auto-value:<current version>\""); 59 } 60 return builder.build(); 61 } 62 autoAnnotationIsMissing()63 private boolean autoAnnotationIsMissing() { 64 return elements.getTypeElement("com.google.auto.value.AutoAnnotation") == null; 65 } 66 } 67