summaryrefslogtreecommitdiffstats
path: root/jack/src/com/android/jack/ir/ast/JPackage.java
blob: 9b181d041418211dafc94772d3358c3b153baf73 (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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * 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.android.jack.ir.ast;

import com.android.jack.ir.JNodeInternalError;
import com.android.jack.ir.StringInterner;
import com.android.jack.ir.sourceinfo.SourceInfo;
import com.android.jack.load.PackageLoader;
import com.android.jack.lookup.JLookupException;
import com.android.sched.item.Component;
import com.android.sched.item.Description;
import com.android.sched.scheduler.ScheduleInstance;
import com.android.sched.transform.TransformRequest;
import com.android.sched.util.location.Location;
import com.android.sched.util.log.Tracer;
import com.android.sched.util.log.TracerFactory;
import com.android.sched.util.log.stats.Counter;
import com.android.sched.util.log.stats.CounterImpl;
import com.android.sched.util.log.stats.StatisticId;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;

/**
 * Represents a Java package
 */
@Description("Represents a Java package")
public class JPackage extends JNode implements HasName, CanBeRenamed, HasEnclosingPackage {

  private static enum OnPath {
    NOT_YET_AVAILABLE,
    TRUE,
    FALSE;
  }

  @Nonnull
  public static final StatisticId<Counter> PACKAGE_CREATION = new StatisticId<Counter>(
      "jack.package.create", "Created JPackage",
      CounterImpl.class, Counter.class);

  @Nonnull
  public static final StatisticId<Counter> PHANTOM_CREATION = new StatisticId<Counter>(
      "jack.phantom.create", "Created phantom class or interface",
      CounterImpl.class, Counter.class);

  @CheckForNull
  private JPackage enclosingPackage;

  @Nonnull
  private final ArrayList<JPackage> subPackages = new ArrayList<JPackage>();

  @Nonnull
  private final ArrayList<JDefinedClassOrInterface> declaredTypes =
    new ArrayList<JDefinedClassOrInterface>();

  @Nonnull
  private final List<JPhantomClassOrInterface> phantomTypes =
    new ArrayList<JPhantomClassOrInterface>();

  @Nonnull
  private final List<JPhantomClass> phantomClasses = new ArrayList<JPhantomClass>();

  @Nonnull
  private final List<JPhantomEnum> phantomEnums = new ArrayList<JPhantomEnum>();

  @Nonnull
  private final List<JPhantomInterface> phantomInterfaces = new ArrayList<JPhantomInterface>();

  @Nonnull
  private final List<JPhantomAnnotationType> phantomAnnotations =
      new ArrayList<JPhantomAnnotationType>();

  @Nonnull
  private final Set<String> deletedItems = new HashSet<String>();

  @Nonnull
  private String name;

  @Nonnull
  private final JSession session;

  @Nonnull
  private static final Tracer tracer = TracerFactory.getTracer();

  @Nonnull
  private final List<PackageLoader> loaders =
      new LinkedList<PackageLoader>();

  private OnPath isOnPath = OnPath.NOT_YET_AVAILABLE;

  public JPackage(
      @Nonnull String name, @Nonnull JSession session, @CheckForNull JPackage enclosingPackage) {
    this(name, session, enclosingPackage, Collections.<PackageLoader>emptyList());
  }

  public JPackage(@Nonnull String name, @Nonnull JSession session,
      @CheckForNull JPackage enclosingPackage,
      @Nonnull List<PackageLoader> loaders) {
    super(SourceInfo.UNKNOWN);
    this.session = session;
    this.name = StringInterner.get().intern(name);
    this.loaders.addAll(loaders);
    if (enclosingPackage != null) {
      assert !name.isEmpty();
      this.enclosingPackage = enclosingPackage;
      this.enclosingPackage.addPackage(this);
    }
    tracer.getStatistic(PACKAGE_CREATION).incValue();
  }

  public void addType(@Nonnull JDefinedClassOrInterface type) {
    addItemWithName(type);
    declaredTypes.add(type);
  }

  public void addPackage(@Nonnull JPackage newPackage) {
    addItemWithName(newPackage);
    subPackages.add(newPackage);
  }

  public void add(@Nonnull HasEnclosingPackage node) {
    if (node instanceof JDefinedClassOrInterface) {
      addType((JDefinedClassOrInterface) node);
    } else if (node instanceof JPackage) {
      addPackage((JPackage) node);
    } else {
      throw new AssertionError("Not supported");
    }
  }

  @Nonnull
  public List<JPackage> getSubPackages() {
    loadSubPackages();
    return subPackages;
  }

  @Nonnull
  public List<JDefinedClassOrInterface> getTypes() {
    loadClassesAndInterfaces();
    return declaredTypes;
  }

  @Override
  @CheckForNull
  public JPackage getEnclosingPackage() {
    return enclosingPackage;
  }

  @Override
  public void setEnclosingPackage(@CheckForNull JPackage enclosingPackage) {
    this.enclosingPackage = enclosingPackage;
  }

  public boolean isTopLevelPackage() {
    return enclosingPackage == null;
  }

  @Nonnull
  public synchronized JPackage getSubPackage(@Nonnull String packageName)
      throws JPackageLookupException {
    for (JPackage f : subPackages) {
      if (f.name.equals(packageName)) {
        return f;
      }
    }

    return loadSubPackage(packageName);
  }

  @Nonnull
  public synchronized JPackage getOrCreateSubPackage(@Nonnull String packageName) {
    try {
      return getSubPackage(packageName);
    } catch (JPackageLookupException e) {
      assert !packageName.isEmpty();
      JPackage newPackage = new JPackage(packageName, session, this);
      newPackage.updateParents(this);
      return newPackage;
    }
  }

  @Nonnull
  public synchronized JDefinedClassOrInterface getType(@Nonnull String typeName)
      throws JTypeLookupException {
    for (JDefinedClassOrInterface type : declaredTypes) {
      if (type.getName().equals(typeName)) {
        return type;
      }
    }

    return loadClassOrInterface(typeName);
  }

  public void setOnPath() {
    this.isOnPath = OnPath.TRUE;
  }

  /**
   * Return true if this JPackage is defined in bootclasspath, classpath or a sourcepath.
   */
  public boolean isOnPath() {
    if (isOnPath == OnPath.NOT_YET_AVAILABLE) {
      isOnPath = OnPath.FALSE;
      for (PackageLoader loader : loaders) {
        if (loader.isOnPath(this)) {
          isOnPath = OnPath.TRUE;
          break;
        }
      }
    }
    return isOnPath == OnPath.TRUE;
  }

  @Nonnull
  public synchronized JClassOrInterface getPhantomClassOrInterface(@Nonnull String typeName) {
    try {
      return getType(typeName);
    } catch (JLookupException e) {
      for (JPhantomClassOrInterface f : phantomTypes) {
        if (f.name.equals(typeName)) {
          return f;
        }
      }
      JPhantomClassOrInterface phantom = new JPhantomClassOrInterface(typeName, this);
      phantomTypes.add(phantom);
      tracer.getStatistic(PHANTOM_CREATION).incValue();
      return phantom;
    }
  }

  @Nonnull
  public synchronized JClass getPhantomClass(@Nonnull String typeName) {
    try {
      JDefinedClassOrInterface defined = getType(typeName);
      if (defined instanceof JClass) {
        return (JClass) defined;
      }
    } catch (JLookupException e) {
      // ignore
    }
    for (JPhantomClass f : phantomClasses) {
      if (f.name.equals(typeName)) {
        return f;
      }
    }
    JPhantomClass phantom = new JPhantomClass(typeName, this);
    phantomClasses.add(phantom);
    tracer.getStatistic(PHANTOM_CREATION).incValue();
    return phantom;
  }

  @Nonnull
  public synchronized JEnum getPhantomEnum(@Nonnull String typeName) {
    try {
      JDefinedClassOrInterface defined = getType(typeName);
      if (defined instanceof JEnum) {
        return (JEnum) defined;
      }
    } catch (JLookupException e) {
      // ignore
    }
    for (JPhantomEnum f : phantomEnums) {
      if (f.name.equals(typeName)) {
        return f;
      }
    }
    JPhantomEnum phantom = new JPhantomEnum(typeName, this);
    phantomEnums.add(phantom);
    tracer.getStatistic(PHANTOM_CREATION).incValue();
    return phantom;
  }

  @Nonnull
  public synchronized JInterface getPhantomInterface(@Nonnull String typeName) {
    try {
      JDefinedClassOrInterface defined = getType(typeName);
      if (defined instanceof JInterface) {
        return (JInterface) defined;
      }
    } catch (JLookupException e) {
      // ignore
    }
    for (JPhantomInterface f : phantomInterfaces) {
      if (f.name.equals(typeName)) {
        return f;
      }
    }
    JPhantomInterface phantom = new JPhantomInterface(typeName, this);
    phantomInterfaces.add(phantom);
    tracer.getStatistic(PHANTOM_CREATION).incValue();
    return phantom;
  }

  @Nonnull
  public synchronized JAnnotationType getPhantomAnnotationType(@Nonnull String typeName) {
    try {
      JDefinedClassOrInterface defined = getType(typeName);
      if (defined instanceof JAnnotationType) {
        return (JAnnotationType) defined;
      }
    } catch (JLookupException e) {
      // ignore
    }
    for (JPhantomAnnotationType f : phantomAnnotations) {
      if (f.name.equals(typeName)) {
        return f;
      }
    }
    JPhantomAnnotationType phantom = new JPhantomAnnotationType(typeName, this);
    phantomAnnotations.add(phantom);
    tracer.getStatistic(PHANTOM_CREATION).incValue();
    return phantom;
  }

  @Override
  public void setName(@Nonnull String name) {
    if (enclosingPackage != null) {
      enclosingPackage.removeItemWithName(this);
    }
    this.name = StringInterner.get().intern(name);
  }

  public boolean isDefaultPackage() {
    return name.equals("");
  }

  @Nonnull
  public JSession getSession() {
    return session;
  }

  @Override
  public void traverse(@Nonnull JVisitor visitor) {
    assert enclosingPackage == null || !enclosingPackage.deletedItems.contains(getName());

    if (visitor.visit(this)) {
      if (visitor.needLoading()) {
        loadSubPackages();
        loadClassesAndInterfaces();
      }
      visitor.accept(subPackages);
      visitor.accept(declaredTypes);
    }
    visitor.endVisit(this);
  }

  @Override
  protected void transform(@Nonnull JNode existingNode, @CheckForNull JNode newNode,
      @Nonnull Transformation transformation) throws UnsupportedOperationException {
    boolean found = false;
    if (existingNode instanceof JPackage) {
      found =
          transform(this.subPackages, existingNode, (JPackage) newNode, transformation);
    } else if (existingNode instanceof JDefinedClassOrInterface) {
      found =
          transform(this.declaredTypes, existingNode, (JDefinedClassOrInterface) newNode,
              transformation);
    } else if (existingNode instanceof JPhantomClassOrInterface) {
      found =
          transform(this.phantomTypes, existingNode, (JPhantomClassOrInterface) newNode,
              transformation);
      if (!found) {
        if (existingNode instanceof JPhantomInterface) {
          found =
              transform(this.phantomInterfaces, existingNode, (JPhantomInterface) newNode,
                  transformation);
          if (!found) {
            if (newNode instanceof JPhantomAnnotationType) {
              found =
                  transform(this.phantomAnnotations, existingNode, (JPhantomAnnotationType) newNode,
                      transformation);
            }
          }
        } else if (existingNode instanceof JPhantomClass) {
          found =
              transform(this.phantomClasses, existingNode, (JPhantomClass) newNode, transformation);
          if ((!found) && (existingNode instanceof JPhantomEnum)) {
            found =
                transform(this.phantomEnums, existingNode, (JPhantomEnum) newNode, transformation);
           }
        }
      }
    }

    if (!found) {
      super.transform(existingNode, newNode, transformation);
    } else {
      if (transformation == Transformation.REMOVE) {
        assert existingNode instanceof HasName;
        removeItemWithName((HasName) existingNode);
      }
    }
  }

  @Override
  public void traverse(@Nonnull ScheduleInstance<? super Component> schedule) throws Exception {
    schedule.process(this);
    for (JPackage child : subPackages) {
      child.traverse(schedule);
    }
  }

  @Override
  public void visit(@Nonnull JVisitor visitor, @Nonnull TransformRequest transformRequest)
      throws Exception {
    visitor.visit(this, transformRequest);
  }

  @Override
  public String getName() {
    return name;
  }

  public Collection<? extends JDefinedClassOrInterface> getLoadedTypes() {
    return declaredTypes;
  }

  @Nonnull
  public JPackage addLoader(@Nonnull PackageLoader loader) {
    loaders.add(loader);
    return this;
  }

  @Nonnull
  public List<Location> getLocations(@Nonnull JPackage loaded) {
    List<Location> locations = new ArrayList<Location>(loaders.size());
    for (PackageLoader loader : loaders) {
      locations.add(loader.getLocation(loaded));
    }
    return locations;
  }

  @Nonnull
  protected JPackage loadSubPackage(@Nonnull String simpleName)
      throws JPackageLookupException {
    assert !deletedItems.contains(simpleName);

    List<PackageLoader> subLoaders = null;
    for (PackageLoader loader : loaders) {
      try {
        PackageLoader subLoader =
            loader.getLoaderForSubPackage(this, simpleName);
        if (subLoaders == null) {
          subLoaders = new LinkedList<PackageLoader>();
        }
        subLoaders.add(subLoader);
      } catch (JPackageLookupException e) {
        // ignore
      }
    }
    if (subLoaders != null) {
      JPackage subPackage = new JPackage(simpleName, getSession(), this, subLoaders);
      subPackage.updateParents(this);
      return subPackage;
    } else {
      throw new JPackageLookupException(simpleName, this);
    }
  }

  protected void loadSubPackages() {
    HashSet<String> subNames = new HashSet<String>();
    for (PackageLoader loader : loaders) {
      subNames.addAll(loader.getSubPackageNames(this));
    }

    for (String name : subNames) {
      if (!deletedItems.contains(name)) {
        try {
          getSubPackage(name);
        } catch (JPackageLookupException e) {
          // We know the packages exist so this should not happen
          throw new AssertionError(e);
        }
      }
    }
  }

  @Nonnull
  protected JDefinedClassOrInterface loadClassOrInterface(
      @Nonnull String simpleName) throws JTypeLookupException {
    assert !deletedItems.contains(simpleName);
    for (PackageLoader loader : loaders) {
      try {
        return loader.loadClassOrInterface(this, simpleName);
      } catch (JLookupException e) {
        // ignore
      }
    }
    throw new MissingJTypeLookupException(this, simpleName);
  }

  protected void loadClassesAndInterfaces() {
    HashSet<String> subNames = new HashSet<String>();
    for (PackageLoader loader : loaders) {
      subNames.addAll(loader.getSubClassNames(this));
    }

    for (String name : subNames) {
      if (!deletedItems.contains(name)) {
        try {
          getType(name);
        } catch (JTypeLookupException e) {
          // We know the packages exist so this should not happen
          throw new AssertionError(e);
        }
      }
    }
  }

  @Override
  public void checkValidity() {
    if (parent instanceof JPackage) {
      if (parent != enclosingPackage) {
        throw new JNodeInternalError(this, "Invalid parent or enclosing package");
      }
    } else if (parent instanceof JSession) {
      if (enclosingPackage != null) {
        throw new JNodeInternalError(this, "Invalid parent or enclosing package");
      }
    } else  {
      throw new JNodeInternalError(this, "Invalid parent or enclosing package");
    }
  }

  void removeItemWithName(@Nonnull HasName itemWithName) {
    deletedItems.add(itemWithName.getName());
  }

  private void addItemWithName(@Nonnull HasName itemWithName) {
    assert itemWithName instanceof JPackage || itemWithName instanceof JClassOrInterface;
    deletedItems.remove(itemWithName.getName());
  }
}