aboutsummaryrefslogtreecommitdiff
path: root/java/com/google/turbine/binder/ConstBinder.java
blob: 96c03db7c942b1eed81b308414cf52bf12029b37 (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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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 com.google.turbine.binder;

import static java.util.Objects.requireNonNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.turbine.binder.bound.AnnotationMetadata;
import com.google.turbine.binder.bound.EnumConstantValue;
import com.google.turbine.binder.bound.SourceTypeBoundClass;
import com.google.turbine.binder.bound.TurbineClassValue;
import com.google.turbine.binder.bound.TypeBoundClass;
import com.google.turbine.binder.bound.TypeBoundClass.FieldInfo;
import com.google.turbine.binder.bound.TypeBoundClass.MethodInfo;
import com.google.turbine.binder.bound.TypeBoundClass.ParamInfo;
import com.google.turbine.binder.bound.TypeBoundClass.TyVarInfo;
import com.google.turbine.binder.env.CompoundEnv;
import com.google.turbine.binder.env.Env;
import com.google.turbine.binder.sym.ClassSymbol;
import com.google.turbine.binder.sym.FieldSymbol;
import com.google.turbine.binder.sym.TyVarSymbol;
import com.google.turbine.diag.TurbineLog.TurbineLogWithSource;
import com.google.turbine.model.Const;
import com.google.turbine.model.Const.ArrayInitValue;
import com.google.turbine.model.Const.Kind;
import com.google.turbine.model.Const.Value;
import com.google.turbine.model.TurbineElementType;
import com.google.turbine.model.TurbineFlag;
import com.google.turbine.model.TurbineTyKind;
import com.google.turbine.type.AnnoInfo;
import com.google.turbine.type.Type;
import com.google.turbine.type.Type.ArrayTy;
import com.google.turbine.type.Type.ClassTy;
import com.google.turbine.type.Type.ClassTy.SimpleClassTy;
import com.google.turbine.type.Type.IntersectionTy;
import com.google.turbine.type.Type.TyKind;
import com.google.turbine.type.Type.TyVar;
import com.google.turbine.type.Type.WildLowerBoundedTy;
import com.google.turbine.type.Type.WildTy;
import com.google.turbine.type.Type.WildUnboundedTy;
import com.google.turbine.type.Type.WildUpperBoundedTy;
import java.lang.annotation.RetentionPolicy;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;

/** Binding pass to evaluate constant expressions. */
public class ConstBinder {

  private final Env<FieldSymbol, Value> constantEnv;
  private final ClassSymbol origin;
  private final SourceTypeBoundClass base;
  private final CompoundEnv<ClassSymbol, TypeBoundClass> env;
  private final ConstEvaluator constEvaluator;
  private final TurbineLogWithSource log;

  public ConstBinder(
      Env<FieldSymbol, Value> constantEnv,
      ClassSymbol origin,
      CompoundEnv<ClassSymbol, TypeBoundClass> env,
      SourceTypeBoundClass base,
      TurbineLogWithSource log) {
    this.constantEnv = constantEnv;
    this.origin = origin;
    this.base = base;
    this.env = env;
    this.log = log;
    this.constEvaluator =
        new ConstEvaluator(
            origin,
            origin,
            base.memberImports(),
            base.source(),
            base.scope(),
            constantEnv,
            env,
            log);
  }

  public SourceTypeBoundClass bind() {
    ImmutableList<AnnoInfo> annos =
        new ConstEvaluator(
                origin,
                base.owner(),
                base.memberImports(),
                base.source(),
                base.enclosingScope(),
                constantEnv,
                env,
                log)
            .evaluateAnnotations(base.annotations());
    ImmutableList<TypeBoundClass.FieldInfo> fields = fields(base.fields());
    ImmutableList<MethodInfo> methods = bindMethods(base.methods());
    return new SourceTypeBoundClass(
        bindTypes(base.interfaceTypes()),
        base.superClassType() != null ? bindType(base.superClassType()) : null,
        bindTypeParameters(base.typeParameterTypes()),
        base.access(),
        methods,
        fields,
        base.owner(),
        base.kind(),
        base.children(),
        base.typeParameters(),
        base.enclosingScope(),
        base.scope(),
        base.memberImports(),
        bindAnnotationMetadata(base.kind(), annos),
        annos,
        base.source(),
        base.decl());
  }

  private ImmutableList<MethodInfo> bindMethods(ImmutableList<MethodInfo> methods) {
    ImmutableList.Builder<MethodInfo> result = ImmutableList.builder();
    for (MethodInfo f : methods) {
      result.add(bindMethod(f));
    }
    return result.build();
  }

  private MethodInfo bindMethod(MethodInfo base) {
    Const value = null;
    if (base.decl() != null && base.decl().defaultValue().isPresent()) {
      value =
          constEvaluator.evalAnnotationValue(base.decl().defaultValue().get(), base.returnType());
    }

    return new MethodInfo(
        base.sym(),
        bindTypeParameters(base.tyParams()),
        bindType(base.returnType()),
        bindParameters(base.parameters()),
        bindTypes(base.exceptions()),
        base.access(),
        value,
        base.decl(),
        constEvaluator.evaluateAnnotations(base.annotations()),
        base.receiver() != null ? bindParameter(base.receiver()) : null);
  }

  private ImmutableList<ParamInfo> bindParameters(ImmutableList<ParamInfo> formals) {
    ImmutableList.Builder<ParamInfo> result = ImmutableList.builder();
    for (ParamInfo base : formals) {
      result.add(bindParameter(base));
    }
    return result.build();
  }

  private ParamInfo bindParameter(ParamInfo base) {
    ImmutableList<AnnoInfo> annos = constEvaluator.evaluateAnnotations(base.annotations());
    return new ParamInfo(base.sym(), bindType(base.type()), annos, base.access());
  }

  static @Nullable AnnotationMetadata bindAnnotationMetadata(
      TurbineTyKind kind, Iterable<AnnoInfo> annotations) {
    if (kind != TurbineTyKind.ANNOTATION) {
      return null;
    }
    RetentionPolicy retention = null;
    ImmutableSet<TurbineElementType> target = null;
    ClassSymbol repeatable = null;
    for (AnnoInfo annotation : annotations) {
      ClassSymbol sym = annotation.sym();
      if (sym == null) {
        continue;
      }
      switch (sym.binaryName()) {
        case "java/lang/annotation/Retention":
          retention = bindRetention(annotation);
          break;
        case "java/lang/annotation/Target":
          target = bindTarget(annotation);
          break;
        case "java/lang/annotation/Repeatable":
          repeatable = bindRepeatable(annotation);
          break;
        default:
          break;
      }
    }
    return new AnnotationMetadata(retention, target, repeatable);
  }

  private static @Nullable RetentionPolicy bindRetention(AnnoInfo annotation) {
    Const value = annotation.values().get("value");
    if (value == null) {
      return null;
    }
    if (value.kind() != Kind.ENUM_CONSTANT) {
      return null;
    }
    EnumConstantValue enumValue = (EnumConstantValue) value;
    if (!enumValue.sym().owner().binaryName().equals("java/lang/annotation/RetentionPolicy")) {
      return null;
    }
    return RetentionPolicy.valueOf(enumValue.sym().name());
  }

  private static ImmutableSet<TurbineElementType> bindTarget(AnnoInfo annotation) {
    ImmutableSet.Builder<TurbineElementType> result = ImmutableSet.builder();
    // requireNonNull is safe because java.lang.annotation.Target declares `value`.
    Const val = requireNonNull(annotation.values().get("value"));
    switch (val.kind()) {
      case ARRAY:
        for (Const element : ((ArrayInitValue) val).elements()) {
          if (element.kind() == Kind.ENUM_CONSTANT) {
            bindTargetElement(result, (EnumConstantValue) element);
          }
        }
        break;
      case ENUM_CONSTANT:
        bindTargetElement(result, (EnumConstantValue) val);
        break;
      default:
        break;
    }
    return result.build();
  }

  private static @Nullable ClassSymbol bindRepeatable(AnnoInfo annotation) {
    // requireNonNull is safe because java.lang.annotation.Repeatable declares `value`.
    Const value = requireNonNull(annotation.values().get("value"));
    if (value.kind() != Kind.CLASS_LITERAL) {
      return null;
    }
    Type type = ((TurbineClassValue) value).type();
    if (type.tyKind() != TyKind.CLASS_TY) {
      return null;
    }
    return ((ClassTy) type).sym();
  }

  private static void bindTargetElement(
      ImmutableSet.Builder<TurbineElementType> target, EnumConstantValue enumVal) {
    if (enumVal.sym().owner().binaryName().equals("java/lang/annotation/ElementType")) {
      target.add(TurbineElementType.valueOf(enumVal.sym().name()));
    }
  }

  private ImmutableList<TypeBoundClass.FieldInfo> fields(ImmutableList<FieldInfo> fields) {
    ImmutableList.Builder<TypeBoundClass.FieldInfo> result = ImmutableList.builder();
    for (TypeBoundClass.FieldInfo base : fields) {
      Value value = fieldValue(base);
      result.add(
          new TypeBoundClass.FieldInfo(
              base.sym(),
              bindType(base.type()),
              base.access(),
              constEvaluator.evaluateAnnotations(base.annotations()),
              base.decl(),
              value));
    }
    return result.build();
  }

  private @Nullable Value fieldValue(TypeBoundClass.FieldInfo base) {
    if (base.decl() == null || !base.decl().init().isPresent()) {
      return null;
    }
    if ((base.access() & TurbineFlag.ACC_FINAL) == 0) {
      return null;
    }
    Type type = base.type();
    switch (type.tyKind()) {
      case PRIM_TY:
        break;
      case CLASS_TY:
        if (((Type.ClassTy) type).sym().equals(ClassSymbol.STRING)) {
          break;
        }
        // falls through
      default:
        return null;
    }
    Value value = constantEnv.get(base.sym());
    if (value == null) {
      return null;
    }
    if (type.tyKind().equals(TyKind.PRIM_TY)) {
      value =
          constEvaluator.coerce(
              base.decl().init().get().position(), value, ((Type.PrimTy) type).primkind());
    }
    return value;
  }

  private ImmutableList<Type> bindTypes(ImmutableList<Type> types) {
    ImmutableList.Builder<Type> result = ImmutableList.builder();
    for (Type t : types) {
      result.add(bindType(t));
    }
    return result.build();
  }

  private ImmutableMap<TyVarSymbol, TyVarInfo> bindTypeParameters(
      ImmutableMap<TyVarSymbol, TyVarInfo> typarams) {
    ImmutableMap.Builder<TyVarSymbol, TyVarInfo> result = ImmutableMap.builder();
    for (Map.Entry<TyVarSymbol, TyVarInfo> entry : typarams.entrySet()) {
      TyVarInfo info = entry.getValue();
      result.put(
          entry.getKey(),
          new TyVarInfo(
              (IntersectionTy) bindType(info.upperBound()),
              /* lowerBound= */ null,
              constEvaluator.evaluateAnnotations(info.annotations())));
    }
    return result.build();
  }

  private Type bindType(Type type) {
    switch (type.tyKind()) {
      case TY_VAR:
        TyVar tyVar = (TyVar) type;
        return TyVar.create(tyVar.sym(), constEvaluator.evaluateAnnotations(tyVar.annos()));
      case CLASS_TY:
        return bindClassType((ClassTy) type);
      case ARRAY_TY:
        ArrayTy arrayTy = (ArrayTy) type;
        return ArrayTy.create(
            bindType(arrayTy.elementType()), constEvaluator.evaluateAnnotations(arrayTy.annos()));
      case WILD_TY:
        {
          WildTy wildTy = (WildTy) type;
          switch (wildTy.boundKind()) {
            case NONE:
              return WildUnboundedTy.create(
                  constEvaluator.evaluateAnnotations(wildTy.annotations()));
            case UPPER:
              return WildUpperBoundedTy.create(
                  bindType(wildTy.bound()),
                  constEvaluator.evaluateAnnotations(wildTy.annotations()));
            case LOWER:
              return WildLowerBoundedTy.create(
                  bindType(wildTy.bound()),
                  constEvaluator.evaluateAnnotations(wildTy.annotations()));
          }
          throw new AssertionError(wildTy.boundKind());
        }
      case PRIM_TY:
      case VOID_TY:
      case ERROR_TY:
        return type;
      case INTERSECTION_TY:
        return IntersectionTy.create(bindTypes(((IntersectionTy) type).bounds()));
      default:
        throw new AssertionError(type.tyKind());
    }
  }

  private ClassTy bindClassType(ClassTy type) {
    ClassTy classTy = type;
    ImmutableList.Builder<SimpleClassTy> classes = ImmutableList.builder();
    for (SimpleClassTy c : classTy.classes()) {
      classes.add(
          SimpleClassTy.create(
              c.sym(), bindTypes(c.targs()), constEvaluator.evaluateAnnotations(c.annos())));
    }
    return ClassTy.create(classes.build());
  }
}