Home | History | Annotate | Download | only in codegen
      1 /*
      2  * Copyright (C) 2014 Google, Inc.
      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 package dagger.internal.codegen;
     17 
     18 import dagger.MapKey;
     19 import java.util.List;
     20 import javax.lang.model.element.Element;
     21 import javax.lang.model.element.ExecutableElement;
     22 import javax.lang.model.element.TypeElement;
     23 import javax.lang.model.type.TypeKind;
     24 
     25 import static dagger.internal.codegen.ErrorMessages.MAPKEY_WITHOUT_MEMBERS;
     26 import static dagger.internal.codegen.ErrorMessages.UNWRAPPED_MAP_KEY_WITH_ARRAY_MEMBER;
     27 import static dagger.internal.codegen.ErrorMessages.UNWRAPPED_MAP_KEY_WITH_TOO_MANY_MEMBERS;
     28 import static javax.lang.model.util.ElementFilter.methodsIn;
     29 
     30 /**
     31  * A validator for {@link MapKey} annotations.
     32  *
     33  * @author Chenying Hou
     34  * @since 2.0
     35  */
     36 // TODO(dpb,gak): Should unwrapped MapKeys be required to have their single member be named "value"?
     37 final class MapKeyValidator {
     38   ValidationReport<Element> validate(Element element) {
     39     ValidationReport.Builder<Element> builder = ValidationReport.about(element);
     40     List<ExecutableElement> members = methodsIn(((TypeElement) element).getEnclosedElements());
     41     if (members.isEmpty()) {
     42       builder.addError(MAPKEY_WITHOUT_MEMBERS, element);
     43     } else if (element.getAnnotation(MapKey.class).unwrapValue()) {
     44       if (members.size() > 1) {
     45         builder.addError(UNWRAPPED_MAP_KEY_WITH_TOO_MANY_MEMBERS, element);
     46       } else if (members.get(0).getReturnType().getKind() == TypeKind.ARRAY) {
     47         builder.addError(UNWRAPPED_MAP_KEY_WITH_ARRAY_MEMBER, element);
     48       }
     49     }
     50     return builder.build();
     51   }
     52 }
     53