MapKeyValidator.java revision 5d3207ac2713386ed61c6ca8f0356e8f093a62e1
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 */
16package dagger.internal.codegen;
17
18import dagger.MapKey;
19import java.util.List;
20import javax.lang.model.element.Element;
21import javax.lang.model.element.ExecutableElement;
22import javax.lang.model.element.TypeElement;
23import javax.lang.model.type.TypeKind;
24
25import static dagger.internal.codegen.ErrorMessages.MAPKEY_WITHOUT_MEMBERS;
26import static dagger.internal.codegen.ErrorMessages.UNWRAPPED_MAP_KEY_WITH_ARRAY_MEMBER;
27import static dagger.internal.codegen.ErrorMessages.UNWRAPPED_MAP_KEY_WITH_TOO_MANY_MEMBERS;
28import static javax.lang.model.util.ElementFilter.methodsIn;
29
30/**
31 * A {@link 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"?
37final 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