aboutsummaryrefslogtreecommitdiff
path: root/java/dagger/internal/codegen/base/SourceFileHjarGenerator.java
blob: 6857c366fa56553cbc91a1872d384e97dae122ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
 * Copyright (C) 2017 The Dagger Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package dagger.internal.codegen.base;

import static com.squareup.javapoet.MethodSpec.constructorBuilder;
import static com.squareup.javapoet.MethodSpec.methodBuilder;
import static com.squareup.javapoet.TypeSpec.classBuilder;
import static dagger.internal.codegen.extension.DaggerStreams.toImmutableList;
import static dagger.internal.codegen.extension.DaggerStreams.toImmutableSet;
import static dagger.internal.codegen.langmodel.Accessibility.isElementAccessibleFrom;
import static dagger.internal.codegen.xprocessing.XElements.closestEnclosingTypeElement;
import static javax.lang.model.element.Modifier.PRIVATE;

import androidx.room.compiler.processing.XConstructorElement;
import androidx.room.compiler.processing.XElement;
import androidx.room.compiler.processing.XExecutableParameterElement;
import androidx.room.compiler.processing.XProcessingEnv;
import androidx.room.compiler.processing.XType;
import androidx.room.compiler.processing.XTypeElement;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import dagger.internal.codegen.javapoet.CodeBlocks;
import dagger.internal.codegen.javapoet.TypeNames;
import java.util.Optional;
import javax.lang.model.element.Modifier;

/**
 * A source file generator that only writes the relevant code necessary for Bazel to create a
 * correct header (ABI) jar.
 */
public final class SourceFileHjarGenerator<T> extends SourceFileGenerator<T> {
  public static <T> SourceFileGenerator<T> wrap(
      SourceFileGenerator<T> delegate, XProcessingEnv processingEnv) {
    return new SourceFileHjarGenerator<>(delegate, processingEnv);
  }

  private final SourceFileGenerator<T> delegate;
  private final XProcessingEnv processingEnv;

  private SourceFileHjarGenerator(SourceFileGenerator<T> delegate, XProcessingEnv processingEnv) {
    super(delegate);
    this.delegate = delegate;
    this.processingEnv = processingEnv;
  }

  @Override
  public XElement originatingElement(T input) {
    return delegate.originatingElement(input);
  }

  @Override
  public ImmutableList<TypeSpec.Builder> topLevelTypes(T input) {
    String packageName = closestEnclosingTypeElement(originatingElement(input)).getPackageName();
    return delegate.topLevelTypes(input).stream()
        .map(completeType -> skeletonType(packageName, completeType.build()))
        .collect(toImmutableList());
  }

  private TypeSpec.Builder skeletonType(String packageName, TypeSpec completeType) {
    TypeSpec.Builder skeleton =
        classBuilder(completeType.name)
            .addSuperinterfaces(completeType.superinterfaces)
            .addTypeVariables(completeType.typeVariables)
            .addModifiers(completeType.modifiers.toArray(new Modifier[0]))
            .addAnnotations(completeType.annotations);

    if (!completeType.superclass.equals(ClassName.OBJECT)) {
      skeleton.superclass(completeType.superclass);
    }

    completeType.methodSpecs.stream()
        .filter(method -> !method.modifiers.contains(PRIVATE) || method.isConstructor())
        .map(completeMethod -> skeletonMethod(packageName, completeType, completeMethod))
        .forEach(skeleton::addMethod);

    completeType.fieldSpecs.stream()
        .filter(field -> !field.modifiers.contains(PRIVATE))
        .map(this::skeletonField)
        .forEach(skeleton::addField);

    completeType.typeSpecs.stream()
        .map(type -> skeletonType(packageName, type).build())
        .forEach(skeleton::addType);

    completeType.alwaysQualifiedNames
        .forEach(skeleton::alwaysQualify);

    return skeleton;
  }

  private MethodSpec skeletonMethod(
      String packageName, TypeSpec completeType, MethodSpec completeMethod) {
    MethodSpec.Builder skeleton =
        completeMethod.isConstructor()
            ? constructorBuilder()
            : methodBuilder(completeMethod.name).returns(completeMethod.returnType);

    if (completeMethod.isConstructor()) {
      getRequiredSuperCall(packageName, completeType)
          .ifPresent(superCall -> skeleton.addStatement("$L", superCall));
    } else if (!completeMethod.returnType.equals(TypeName.VOID)) {
      skeleton.addStatement("return $L", getDefaultValueCodeBlock(completeMethod.returnType));
    }

    return skeleton
        .addModifiers(completeMethod.modifiers)
        .addTypeVariables(completeMethod.typeVariables)
        .addParameters(completeMethod.parameters)
        .addExceptions(completeMethod.exceptions)
        .varargs(completeMethod.varargs)
        .addAnnotations(completeMethod.annotations)
        .build();
  }

  private Optional<CodeBlock> getRequiredSuperCall(String packageName, TypeSpec completeType) {
    if (completeType.superclass.equals(TypeName.OBJECT)) {
      return Optional.empty();
    }

    ClassName rawSuperClass = (ClassName) TypeNames.rawTypeName(completeType.superclass);
    XTypeElement superTypeElement =
        processingEnv.requireTypeElement(rawSuperClass.canonicalName());

    ImmutableSet<XConstructorElement> accessibleConstructors =
        superTypeElement.getConstructors().stream()
            .filter(
                constructor ->
                    // isElementAccessibleFrom doesn't take protected into account so check manually
                    constructor.isProtected()
                        || isElementAccessibleFrom(constructor, packageName))
            .collect(toImmutableSet());

    // If there's an accessible default constructor we don't need to call super() manually.
    if (accessibleConstructors.isEmpty()
            || accessibleConstructors.stream()
                .anyMatch(constructor -> constructor.getParameters().isEmpty())) {
      return Optional.empty();
    }

    return Optional.of(
        CodeBlock.of(
            "super($L)",
            CodeBlocks.makeParametersCodeBlock(
                // We just choose the first constructor (it doesn't really matter since we're just
                // trying to ensure the constructor body compiles).
                accessibleConstructors.stream().findFirst().get().getParameters().stream()
                    .map(XExecutableParameterElement::getType)
                    .map(XType::getTypeName)
                    .map(SourceFileHjarGenerator::getDefaultValueCodeBlock)
                    .collect(toImmutableList()))));
  }

  /**
   * Returns a {@link CodeBlock} containing the default value for the given {@code typeName}.
   *
   * <p>See https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html.
   */
  private static CodeBlock getDefaultValueCodeBlock(TypeName typeName) {
    if (typeName.isPrimitive()) {
      if (typeName.equals(TypeName.BOOLEAN)) {
        return CodeBlock.of("false");
      } else if (typeName.equals(TypeName.CHAR)) {
        return CodeBlock.of("'\u0000'");
      } else if (typeName.equals(TypeName.BYTE)) {
        return CodeBlock.of("0");
      } else if (typeName.equals(TypeName.SHORT)) {
        return CodeBlock.of("0");
      } else if (typeName.equals(TypeName.INT)) {
        return CodeBlock.of("0");
      } else if (typeName.equals(TypeName.LONG)) {
        return CodeBlock.of("0L");
      } else if (typeName.equals(TypeName.FLOAT)) {
        return CodeBlock.of("0.0f");
      } else if (typeName.equals(TypeName.DOUBLE)) {
        return CodeBlock.of("0.0d");
      } else {
        throw new AssertionError("Unexpected type: " + typeName);
      }
    }
    return CodeBlock.of("null");
  }

  private FieldSpec skeletonField(FieldSpec completeField) {
    return FieldSpec.builder(
            completeField.type,
            completeField.name,
            completeField.modifiers.toArray(new Modifier[0]))
        .addAnnotations(completeField.annotations)
        .build();
  }
}