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 com.google.common.collect.ImmutableSet;
19import java.util.Set;
20import javax.inject.Inject;
21import javax.lang.model.element.AnnotationMirror;
22import javax.lang.model.element.Modifier;
23import javax.lang.model.element.VariableElement;
24import javax.tools.Diagnostic.Kind;
25
26import static dagger.internal.codegen.ErrorMessages.FINAL_INJECT_FIELD;
27import static dagger.internal.codegen.ErrorMessages.MULTIPLE_QUALIFIERS;
28import static dagger.internal.codegen.ErrorMessages.PRIVATE_INJECT_FIELD;
29import static dagger.internal.codegen.ErrorMessages.STATIC_INJECT_FIELD;
30import static dagger.internal.codegen.InjectionAnnotations.getQualifiers;
31import static javax.lang.model.element.Modifier.FINAL;
32import static javax.lang.model.element.Modifier.PRIVATE;
33import static javax.lang.model.element.Modifier.STATIC;
34
35/**
36 * A {@linkplain ValidationReport validator} for {@link Inject} fields.
37 *
38 * @author Gregory Kick
39 * @since 2.0
40 */
41final class InjectFieldValidator {
42  private Kind privateMemberValidationKind;
43  private Kind staticMemberValidationKind;
44
45  public InjectFieldValidator(
46      Kind privateMemberValidationKind, Kind staticMemberValidationKind) {
47    this.privateMemberValidationKind = privateMemberValidationKind;
48    this.staticMemberValidationKind = staticMemberValidationKind;
49  }
50
51  ValidationReport<VariableElement> validate(VariableElement fieldElement) {
52    ValidationReport.Builder<VariableElement> builder = ValidationReport.about(fieldElement);
53    Set<Modifier> modifiers = fieldElement.getModifiers();
54    if (modifiers.contains(FINAL)) {
55      builder.addError(FINAL_INJECT_FIELD, fieldElement);
56    }
57
58    if (modifiers.contains(PRIVATE)) {
59      builder.addItem(PRIVATE_INJECT_FIELD, privateMemberValidationKind, fieldElement);
60    }
61
62    if (modifiers.contains(STATIC)) {
63      builder.addItem(STATIC_INJECT_FIELD, staticMemberValidationKind, fieldElement);
64    }
65
66    ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(fieldElement);
67    if (qualifiers.size() > 1) {
68      for (AnnotationMirror qualifier : qualifiers) {
69        builder.addError(MULTIPLE_QUALIFIERS, fieldElement, qualifier);
70      }
71    }
72
73    return builder.build();
74  }
75}
76