1 /*
2 * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package com.sun.tools.javac.code;
27
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.EnumSet;
31 import java.util.HashMap;
32 import java.util.LinkedHashMap;
33 import java.util.Map;
34
35 import javax.lang.model.element.ElementVisitor;
36
37 import com.sun.tools.javac.code.Scope.WriteableScope;
38 import com.sun.tools.javac.code.Source.Feature;
39 import com.sun.tools.javac.code.Symbol.ClassSymbol;
40 import com.sun.tools.javac.code.Symbol.Completer;
41 import com.sun.tools.javac.code.Symbol.CompletionFailure;
42 import com.sun.tools.javac.code.Symbol.MethodSymbol;
43 import com.sun.tools.javac.code.Symbol.ModuleSymbol;
44 import com.sun.tools.javac.code.Symbol.PackageSymbol;
45 import com.sun.tools.javac.code.Symbol.RootPackageSymbol;
46 import com.sun.tools.javac.code.Symbol.TypeSymbol;
47 import com.sun.tools.javac.code.Symbol.VarSymbol;
48 import com.sun.tools.javac.code.Type.BottomType;
49 import com.sun.tools.javac.code.Type.ClassType;
50 import com.sun.tools.javac.code.Type.ErrorType;
51 import com.sun.tools.javac.code.Type.JCPrimitiveType;
52 import com.sun.tools.javac.code.Type.JCVoidType;
53 import com.sun.tools.javac.code.Type.MethodType;
54 import com.sun.tools.javac.code.Types.UniqueType;
55 import com.sun.tools.javac.comp.Modules;
56 import com.sun.tools.javac.jvm.Target;
57 import com.sun.tools.javac.util.Assert;
58 import com.sun.tools.javac.util.Context;
59 import com.sun.tools.javac.util.Convert;
60 import com.sun.tools.javac.util.DefinedBy;
61 import com.sun.tools.javac.util.DefinedBy.Api;
62 import com.sun.tools.javac.util.Iterators;
63 import com.sun.tools.javac.util.JavacMessages;
64 import com.sun.tools.javac.util.List;
65 import com.sun.tools.javac.util.Name;
66 import com.sun.tools.javac.util.Names;
67
68 import static com.sun.tools.javac.code.Flags.*;
69 import static com.sun.tools.javac.code.Kinds.Kind.*;
70 import static com.sun.tools.javac.code.TypeTag.*;
71
72 /** A class that defines all predefined constants and operators
73 * as well as special classes such as java.lang.Object, which need
74 * to be known to the compiler. All symbols are held in instance
75 * fields. This makes it possible to work in multiple concurrent
76 * projects, which might use different class files for library classes.
77 *
78 * <p><b>This is NOT part of any supported API.
79 * If you write code that depends on this, you do so at your own risk.
80 * This code and its internal interfaces are subject to change or
81 * deletion without notice.</b>
82 */
83 public class Symtab {
84 /** The context key for the symbol table. */
85 protected static final Context.Key<Symtab> symtabKey = new Context.Key<>();
86
87 /** Get the symbol table instance. */
88 public static Symtab instance(Context context) {
89 Symtab instance = context.get(symtabKey);
90 if (instance == null)
91 instance = new Symtab(context);
92 return instance;
93 }
94
95 /** Builtin types.
96 */
97 public final JCPrimitiveType byteType = new JCPrimitiveType(BYTE, null);
98 public final JCPrimitiveType charType = new JCPrimitiveType(CHAR, null);
99 public final JCPrimitiveType shortType = new JCPrimitiveType(SHORT, null);
100 public final JCPrimitiveType intType = new JCPrimitiveType(INT, null);
101 public final JCPrimitiveType longType = new JCPrimitiveType(LONG, null);
102 public final JCPrimitiveType floatType = new JCPrimitiveType(FLOAT, null);
103 public final JCPrimitiveType doubleType = new JCPrimitiveType(DOUBLE, null);
104 public final JCPrimitiveType booleanType = new JCPrimitiveType(BOOLEAN, null);
105 public final Type botType = new BottomType();
106 public final JCVoidType voidType = new JCVoidType();
107
108 private final Names names;
109 private final JavacMessages messages;
110 private final Completer initialCompleter;
111 private final Completer moduleCompleter;
112
113 /** A symbol for the unnamed module.
114 */
115 public final ModuleSymbol unnamedModule;
116
117 /** The error module.
118 */
119 public final ModuleSymbol errModule;
120
121 /** A symbol for no module, for use with -source 8 or less
122 */
123 public final ModuleSymbol noModule;
124
125 /** A symbol for the root package.
126 */
127 public final PackageSymbol rootPackage;
128
129 /** A symbol that stands for a missing symbol.
130 */
131 public final TypeSymbol noSymbol;
132
133 /** The error symbol.
134 */
135 public final ClassSymbol errSymbol;
136
137 /** The unknown symbol.
138 */
139 public final ClassSymbol unknownSymbol;
140
141 /** A value for the errType, with a originalType of noType */
142 public final Type errType;
143
144 /** A value for the unknown type. */
145 public final Type unknownType;
146
147 /** The builtin type of all arrays. */
148 public final ClassSymbol arrayClass;
149 public final MethodSymbol arrayCloneMethod;
150
151 /** VGJ: The (singleton) type of all bound types. */
152 public final ClassSymbol boundClass;
153
154 /** The builtin type of all methods. */
155 public final ClassSymbol methodClass;
156
157 /** A symbol for the java.base module.
158 */
159 public final ModuleSymbol java_base;
160
161 /** Predefined types.
162 */
163 public final Type objectType;
164 public final Type objectMethodsType;
165 public final Type exactConversionsSupportType;
166 public final Type objectsType;
167 public final Type classType;
168 public final Type classLoaderType;
169 public final Type stringType;
170 public final Type stringBufferType;
171 public final Type stringBuilderType;
172 public final Type cloneableType;
173 public final Type serializableType;
174 public final Type serializedLambdaType;
175 public final Type varHandleType;
176 public final Type methodHandleType;
177 public final Type methodHandlesType;
178 public final Type methodHandleLookupType;
179 public final Type methodTypeType;
180 public final Type nativeHeaderType;
181 public final Type throwableType;
182 public final Type errorType;
183 public final Type interruptedExceptionType;
184 public final Type illegalArgumentExceptionType;
185 public final Type exceptionType;
186 public final Type runtimeExceptionType;
187 public final Type classNotFoundExceptionType;
188 public final Type noClassDefFoundErrorType;
189 public final Type noSuchFieldErrorType;
190 public final Type assertionErrorType;
191 public final Type incompatibleClassChangeErrorType;
192 public final Type cloneNotSupportedExceptionType;
193 public final Type matchExceptionType;
194 public final Type annotationType;
195 public final TypeSymbol enumSym;
196 public final Type listType;
197 public final Type collectionsType;
198 public final Type comparableType;
199 public final Type comparatorType;
200 public final Type arraysType;
201 public final Type iterableType;
202 public final Type iteratorType;
203 public final Type annotationTargetType;
204 public final Type overrideType;
205 public final Type retentionType;
206 public final Type deprecatedType;
207 public final Type suppressWarningsType;
208 public final Type supplierType;
209 public final Type inheritedType;
210 public final Type profileType;
211 public final Type proprietaryType;
212 public final Type systemType;
213 public final Type autoCloseableType;
214 public final Type trustMeType;
215 public final Type lambdaMetafactory;
216 public final Type stringConcatFactory;
217 public final Type repeatableType;
218 public final Type documentedType;
219 public final Type elementTypeType;
220 public final Type functionalInterfaceType;
221 public final Type previewFeatureType;
222 public final Type previewFeatureInternalType;
223 public final Type restrictedType;
224 public final Type restrictedInternalType;
225 public final Type typeDescriptorType;
226 public final Type recordType;
227 public final Type switchBootstrapsType;
228 public final Type constantBootstrapsType;
229 public final Type requiresIdentityType;
230 public final Type requiresIdentityInternalType;
231 public final Type classDescType;
232 public final Type enumDescType;
233
234 // For serialization lint checking
235 public final Type objectStreamFieldType;
236 public final Type objectInputStreamType;
237 public final Type objectOutputStreamType;
238 public final Type ioExceptionType;
239 public final Type objectStreamExceptionType;
240 // For externalization lint checking
241 public final Type externalizableType;
242 public final Type objectInputType;
243 public final Type objectOutputType;
244
245 // valhalla
246 public final Type valueBasedType;
247 public final Type valueBasedInternalType;
248 public final Type migratedValueClassType;
249 public final Type migratedValueClassInternalType;
250 public final Type strictType;
251 /** The symbol representing the finalize method on Object */
252 public final MethodSymbol objectFinalize;
253 public final Type numberType;
254
255 /** The symbol representing the length field of an array.
256 */
257 public final VarSymbol lengthVar;
258
259 /** The symbol representing the final finalize method on enums */
260 public final MethodSymbol enumFinalFinalize;
261
262 /** The symbol representing the close method on TWR AutoCloseable type */
263 public final MethodSymbol autoCloseableClose;
264
265 /** The predefined type that belongs to a tag.
266 */
267 public final Type[] typeOfTag = new Type[TypeTag.getTypeTagCount()];
268
269 /** The name of the class that belongs to a basic type tag.
270 */
271 public final Name[] boxedName = new Name[TypeTag.getTypeTagCount()];
272
273 /** A hashtable containing the encountered top-level and member classes,
274 * indexed by flat names. The table does not contain local classes.
275 * It should be updated from the outside to reflect classes defined
276 * by compiled source files.
277 */
278 private final Map<Name, Map<ModuleSymbol,ClassSymbol>> classes = new HashMap<>();
279
280 /** A hashtable containing the encountered packages.
281 * the table should be updated from outside to reflect packages defined
282 * by compiled source files.
283 */
284 private final Map<Name, Map<ModuleSymbol,PackageSymbol>> packages = new HashMap<>();
285
286 /** A hashtable giving the encountered modules.
287 */
288 private final Map<Name, ModuleSymbol> modules = new LinkedHashMap<>();
289
290 private final Map<Types.UniqueType, VarSymbol> classFields = new HashMap<>();
291
292 public VarSymbol getClassField(Type type, Types types) {
293 return classFields.computeIfAbsent(
294 new UniqueType(type, types), k -> {
295 Type arg = null;
296 if (type.getTag() == ARRAY || type.getTag() == CLASS)
297 arg = types.erasure(type);
298 else if (type.isPrimitiveOrVoid())
299 arg = types.boxedClass(type).type;
300 else
301 throw new AssertionError(type);
302
303 Type t = new ClassType(
304 classType.getEnclosingType(), List.of(arg), classType.tsym);
305 return new VarSymbol(
306 STATIC | PUBLIC | FINAL, names._class, t, type.tsym);
307 });
308 }
309
310 public void initType(Type type, ClassSymbol c) {
311 type.tsym = c;
312 typeOfTag[type.getTag().ordinal()] = type;
313 }
314
315 public void initType(Type type, String name) {
316 initType(
317 type,
318 new ClassSymbol(
319 PUBLIC, names.fromString(name), type, rootPackage));
320 }
321
322 public void initType(Type type, String name, String bname) {
323 initType(type, name);
324 boxedName[type.getTag().ordinal()] = names.fromString("java.lang." + bname);
325 }
326
327 /** The class symbol that owns all predefined symbols.
328 */
329 public final ClassSymbol predefClass;
330
331 /** Enter a class into symbol table.
332 * @param s The name of the class.
333 */
334 private Type enterClass(String s) {
335 return enterClass(java_base, names.fromString(s)).type;
336 }
337
338 public void synthesizeEmptyInterfaceIfMissing(final Type type) {
339 final Completer completer = type.tsym.completer;
340 type.tsym.completer = new Completer() {
341 @Override
342 public void complete(Symbol sym) throws CompletionFailure {
343 try {
344 completer.complete(sym);
345 } catch (CompletionFailure e) {
346 sym.flags_field |= (PUBLIC | INTERFACE);
347 ((ClassType) sym.type).supertype_field = objectType;
348 }
349 }
350
351 @Override
352 public boolean isTerminal() {
353 return completer.isTerminal();
354 }
355 };
356 }
357
358 public void synthesizeBoxTypeIfMissing(final Type type) {
359 ClassSymbol sym = enterClass(java_base, boxedName[type.getTag().ordinal()]);
360 final Completer completer = sym.completer;
361 sym.completer = new Completer() {
362 @Override
363 public void complete(Symbol sym) throws CompletionFailure {
364 try {
365 completer.complete(sym);
366 } catch (CompletionFailure e) {
367 sym.flags_field |= PUBLIC;
368 ((ClassType) sym.type).supertype_field = objectType;
369 MethodSymbol boxMethod =
370 new MethodSymbol(PUBLIC | STATIC, names.valueOf,
371 new MethodType(List.of(type), sym.type,
372 List.nil(), methodClass),
373 sym);
374 sym.members().enter(boxMethod);
375 MethodSymbol unboxMethod =
376 new MethodSymbol(PUBLIC,
377 type.tsym.name.append(names.Value), // x.intValue()
378 new MethodType(List.nil(), type,
379 List.nil(), methodClass),
380 sym);
381 sym.members().enter(unboxMethod);
382 }
383 }
384
385 @Override
386 public boolean isTerminal() {
387 return completer.isTerminal();
388 }
389 };
390 }
391
392 // Enter a synthetic class that is used to mark classes in ct.sym.
393 // This class does not have a class file.
394 private Type enterSyntheticAnnotation(String name) {
395 return enterSyntheticAnnotation(names.fromString(name));
396 }
397
398 // Enter a synthetic class that is used to mark classes in ct.sym.
399 // This class does not have a class file.
400 private Type enterSyntheticAnnotation(Name name) {
401 // for now, leave the module null, to prevent problems from synthesizing the
402 // existence of a class in any specific module, including noModule
403 ClassType type = (ClassType)enterClass(java_base, name).type;
404 ClassSymbol sym = (ClassSymbol)type.tsym;
405 sym.completer = Completer.NULL_COMPLETER;
406 sym.flags_field = PUBLIC|ACYCLIC|ANNOTATION|INTERFACE;
407 sym.erasure_field = type;
408 sym.members_field = WriteableScope.create(sym);
409 type.typarams_field = List.nil();
410 type.allparams_field = List.nil();
411 type.supertype_field = annotationType;
412 type.interfaces_field = List.nil();
413 return type;
414 }
415
416 /** Constructor; enters all predefined identifiers and operators
417 * into symbol table.
418 */
419 @SuppressWarnings("this-escape")
420 protected Symtab(Context context) throws CompletionFailure {
421 context.put(symtabKey, this);
422
423 names = Names.instance(context);
424
425 messages = JavacMessages.instance(context);
426
427 MissingInfoHandler missingInfoHandler = MissingInfoHandler.instance(context);
428
429 Target target = Target.instance(context);
430 rootPackage = new RootPackageSymbol(names.empty, null,
431 missingInfoHandler,
432 target.runtimeUseNestAccess());
433
434 noModule = new ModuleSymbol(names.empty, null) {
435 @Override public boolean isNoModule() {
436 return true;
437 }
438 };
439 addRootPackageFor(noModule);
440
441 Source source = Source.instance(context);
442 if (Feature.MODULES.allowedInSource(source)) {
443 java_base = enterModule(names.java_base);
444 //avoid completing java.base during the Symtab initialization
445 java_base.completer = Completer.NULL_COMPLETER;
446 java_base.visiblePackages = Collections.emptyMap();
447 } else {
448 java_base = noModule;
449 }
450
451 // create the basic builtin symbols
452 unnamedModule = new ModuleSymbol(names.empty, null) {
453 {
454 directives = List.nil();
455 exports = List.nil();
456 provides = List.nil();
457 uses = List.nil();
458 com.sun.tools.javac.code.Directive.RequiresDirective d =
459 new com.sun.tools.javac.code.Directive.RequiresDirective(java_base,
460 EnumSet.of(com.sun.tools.javac.code.Directive.RequiresFlag.MANDATED));
461 requires = List.of(d);
462 }
463 @Override
464 public String toString() {
465 return messages.getLocalizedString("compiler.misc.unnamed.module");
466 }
467 };
468 addRootPackageFor(unnamedModule);
469 unnamedModule.enclosedPackages = unnamedModule.enclosedPackages.prepend(unnamedModule.unnamedPackage);
470
471 errModule = new ModuleSymbol(names.empty, null) {
472 {
473 directives = List.nil();
474 exports = List.nil();
475 provides = List.nil();
476 uses = List.nil();
477 com.sun.tools.javac.code.Directive.RequiresDirective d =
478 new com.sun.tools.javac.code.Directive.RequiresDirective(java_base,
479 EnumSet.of(com.sun.tools.javac.code.Directive.RequiresFlag.MANDATED));
480 requires = List.of(d);
481 }
482 };
483 addRootPackageFor(errModule);
484
485 noSymbol = new TypeSymbol(NIL, 0, names.empty, Type.noType, rootPackage) {
486 @Override @DefinedBy(Api.LANGUAGE_MODEL)
487 public <R, P> R accept(ElementVisitor<R, P> v, P p) {
488 return v.visitUnknown(this, p);
489 }
490 };
491
492 // create the error symbols
493 errSymbol = new ClassSymbol(PUBLIC|STATIC|ACYCLIC, names.any, null, rootPackage);
494 errType = new ErrorType(errSymbol, Type.noType);
495
496 unknownSymbol = new ClassSymbol(PUBLIC|STATIC|ACYCLIC, names.fromString("<any?>"), null, rootPackage);
497 // Create the unknown type
498 unknownType = new ErrorType(unknownSymbol, Type.noType);
499
500 // initialize builtin types
501 initType(byteType, "byte", "Byte");
502 initType(shortType, "short", "Short");
503 initType(charType, "char", "Character");
504 initType(intType, "int", "Integer");
505 initType(longType, "long", "Long");
506 initType(floatType, "float", "Float");
507 initType(doubleType, "double", "Double");
508 initType(booleanType, "boolean", "Boolean");
509 initType(voidType, "void", "Void");
510 initType(botType, "<nulltype>");
511 initType(errType, errSymbol);
512 initType(unknownType, unknownSymbol);
513
514 // the builtin class of all arrays
515 arrayClass = new ClassSymbol(PUBLIC|ACYCLIC, names.Array, noSymbol);
516
517 // VGJ
518 boundClass = new ClassSymbol(PUBLIC|ACYCLIC, names.Bound, noSymbol);
519 boundClass.members_field = new Scope.ErrorScope(boundClass);
520
521 // the builtin class of all methods
522 methodClass = new ClassSymbol(PUBLIC|ACYCLIC, names.Method, noSymbol);
523 methodClass.members_field = new Scope.ErrorScope(boundClass);
524
525 // Create class to hold all predefined constants and operations.
526 predefClass = new ClassSymbol(PUBLIC|ACYCLIC, names.empty, rootPackage);
527 WriteableScope scope = WriteableScope.create(predefClass);
528 predefClass.members_field = scope;
529
530 // Get the initial completer for Symbols from the ClassFinder
531 initialCompleter = ClassFinder.instance(context).getCompleter();
532 rootPackage.members_field = WriteableScope.create(rootPackage);
533
534 // Enter symbols for basic types.
535 scope.enter(byteType.tsym);
536 scope.enter(shortType.tsym);
537 scope.enter(charType.tsym);
538 scope.enter(intType.tsym);
539 scope.enter(longType.tsym);
540 scope.enter(floatType.tsym);
541 scope.enter(doubleType.tsym);
542 scope.enter(booleanType.tsym);
543 scope.enter(errType.tsym);
544
545 // Enter symbol for the errSymbol
546 scope.enter(errSymbol);
547
548 // Get the initial completer for ModuleSymbols from Modules
549 moduleCompleter = Modules.instance(context).getCompleter();
550
551 // Enter predefined classes. All are assumed to be in the java.base module.
552 objectType = enterClass("java.lang.Object");
553 throwableType = enterClass("java.lang.Throwable");
554 objectFinalize = new MethodSymbol(PROTECTED,
555 names.finalize,
556 new MethodType(List.nil(), voidType,
557 List.of(throwableType), methodClass),
558 objectType.tsym);
559 objectMethodsType = enterClass("java.lang.runtime.ObjectMethods");
560 exactConversionsSupportType = enterClass("java.lang.runtime.ExactConversionsSupport");
561 objectsType = enterClass("java.util.Objects");
562 classType = enterClass("java.lang.Class");
563 stringType = enterClass("java.lang.String");
564 stringBufferType = enterClass("java.lang.StringBuffer");
565 stringBuilderType = enterClass("java.lang.StringBuilder");
566 cloneableType = enterClass("java.lang.Cloneable");
567 serializableType = enterClass("java.io.Serializable");
568 serializedLambdaType = enterClass("java.lang.invoke.SerializedLambda");
569 varHandleType = enterClass("java.lang.invoke.VarHandle");
570 methodHandleType = enterClass("java.lang.invoke.MethodHandle");
571 methodHandlesType = enterClass("java.lang.invoke.MethodHandles");
572 methodHandleLookupType = enterClass("java.lang.invoke.MethodHandles$Lookup");
573 methodTypeType = enterClass("java.lang.invoke.MethodType");
574 errorType = enterClass("java.lang.Error");
575 illegalArgumentExceptionType = enterClass("java.lang.IllegalArgumentException");
576 interruptedExceptionType = enterClass("java.lang.InterruptedException");
577 exceptionType = enterClass("java.lang.Exception");
578 runtimeExceptionType = enterClass("java.lang.RuntimeException");
579 classNotFoundExceptionType = enterClass("java.lang.ClassNotFoundException");
580 noClassDefFoundErrorType = enterClass("java.lang.NoClassDefFoundError");
581 noSuchFieldErrorType = enterClass("java.lang.NoSuchFieldError");
582 assertionErrorType = enterClass("java.lang.AssertionError");
583 incompatibleClassChangeErrorType = enterClass("java.lang.IncompatibleClassChangeError");
584 cloneNotSupportedExceptionType = enterClass("java.lang.CloneNotSupportedException");
585 matchExceptionType = enterClass("java.lang.MatchException");
586 annotationType = enterClass("java.lang.annotation.Annotation");
587 classLoaderType = enterClass("java.lang.ClassLoader");
588 enumSym = enterClass(java_base, names.java_lang_Enum);
589 enumFinalFinalize =
590 new MethodSymbol(PROTECTED|FINAL|HYPOTHETICAL,
591 names.finalize,
592 new MethodType(List.nil(), voidType,
593 List.nil(), methodClass),
594 enumSym);
595 listType = enterClass("java.util.List");
596 collectionsType = enterClass("java.util.Collections");
597 comparableType = enterClass("java.lang.Comparable");
598 comparatorType = enterClass("java.util.Comparator");
599 arraysType = enterClass("java.util.Arrays");
600 iterableType = enterClass("java.lang.Iterable");
601 iteratorType = enterClass("java.util.Iterator");
602 annotationTargetType = enterClass("java.lang.annotation.Target");
603 overrideType = enterClass("java.lang.Override");
604 retentionType = enterClass("java.lang.annotation.Retention");
605 deprecatedType = enterClass("java.lang.Deprecated");
606 suppressWarningsType = enterClass("java.lang.SuppressWarnings");
607 supplierType = enterClass("java.util.function.Supplier");
608 inheritedType = enterClass("java.lang.annotation.Inherited");
609 repeatableType = enterClass("java.lang.annotation.Repeatable");
610 documentedType = enterClass("java.lang.annotation.Documented");
611 elementTypeType = enterClass("java.lang.annotation.ElementType");
612 systemType = enterClass("java.lang.System");
613 autoCloseableType = enterClass("java.lang.AutoCloseable");
614 autoCloseableClose = new MethodSymbol(PUBLIC,
615 names.close,
616 new MethodType(List.nil(), voidType,
617 List.of(exceptionType), methodClass),
618 autoCloseableType.tsym);
619 trustMeType = enterClass("java.lang.SafeVarargs");
620 nativeHeaderType = enterClass("java.lang.annotation.Native");
621 lambdaMetafactory = enterClass("java.lang.invoke.LambdaMetafactory");
622 stringConcatFactory = enterClass("java.lang.invoke.StringConcatFactory");
623 functionalInterfaceType = enterClass("java.lang.FunctionalInterface");
624 previewFeatureType = enterClass("jdk.internal.javac.PreviewFeature");
625 previewFeatureInternalType = enterSyntheticAnnotation("jdk.internal.PreviewFeature+Annotation");
626 restrictedType = enterClass("jdk.internal.javac.Restricted");
627 restrictedInternalType = enterSyntheticAnnotation("jdk.internal.javac.Restricted+Annotation");
628 typeDescriptorType = enterClass("java.lang.invoke.TypeDescriptor");
629 recordType = enterClass("java.lang.Record");
630 switchBootstrapsType = enterClass("java.lang.runtime.SwitchBootstraps");
631 constantBootstrapsType = enterClass("java.lang.invoke.ConstantBootstraps");
632 valueBasedType = enterClass("jdk.internal.ValueBased");
633 valueBasedInternalType = enterSyntheticAnnotation("jdk.internal.ValueBased+Annotation");
634 strictType = enterSyntheticAnnotation("jdk.internal.vm.annotation.Strict");
635 migratedValueClassType = enterClass("jdk.internal.MigratedValueClass");
636 migratedValueClassInternalType = enterSyntheticAnnotation("jdk.internal.MigratedValueClass+Annotation");
637 requiresIdentityType = enterClass("jdk.internal.RequiresIdentity");
638 requiresIdentityInternalType = enterSyntheticAnnotation(names.requiresIdentityInternal);
639 classDescType = enterClass("java.lang.constant.ClassDesc");
640 enumDescType = enterClass("java.lang.Enum$EnumDesc");
641 // For serialization lint checking
642 objectStreamFieldType = enterClass("java.io.ObjectStreamField");
643 objectInputStreamType = enterClass("java.io.ObjectInputStream");
644 objectOutputStreamType = enterClass("java.io.ObjectOutputStream");
645 ioExceptionType = enterClass("java.io.IOException");
646 objectStreamExceptionType = enterClass("java.io.ObjectStreamException");
647 externalizableType = enterClass("java.io.Externalizable");
648 objectInputType = enterClass("java.io.ObjectInput");
649 objectOutputType = enterClass("java.io.ObjectOutput");
650 synthesizeEmptyInterfaceIfMissing(autoCloseableType);
651 synthesizeEmptyInterfaceIfMissing(cloneableType);
652 synthesizeEmptyInterfaceIfMissing(serializableType);
653 synthesizeEmptyInterfaceIfMissing(lambdaMetafactory);
654 synthesizeEmptyInterfaceIfMissing(serializedLambdaType);
655 synthesizeEmptyInterfaceIfMissing(stringConcatFactory);
656 synthesizeBoxTypeIfMissing(doubleType);
657 synthesizeBoxTypeIfMissing(floatType);
658 synthesizeBoxTypeIfMissing(voidType);
659
660 numberType = enterClass("java.lang.Number");
661
662 // Enter a synthetic class that is used to mark internal
663 // proprietary classes in ct.sym. This class does not have a
664 // class file.
665 proprietaryType = enterSyntheticAnnotation("sun.Proprietary+Annotation");
666
667 // Enter a synthetic class that is used to provide profile info for
668 // classes in ct.sym. This class does not have a class file.
669 profileType = enterSyntheticAnnotation("jdk.Profile+Annotation");
670 MethodSymbol m = new MethodSymbol(PUBLIC | ABSTRACT, names.value, intType, profileType.tsym);
671 profileType.tsym.members().enter(m);
672
673 // Enter a class for arrays.
674 // The class implements java.lang.Cloneable and java.io.Serializable.
675 // It has a final length field and a clone method.
676 ClassType arrayClassType = (ClassType)arrayClass.type;
677 arrayClassType.supertype_field = objectType;
678 arrayClassType.interfaces_field = List.of(cloneableType, serializableType);
679 arrayClass.members_field = WriteableScope.create(arrayClass);
680 lengthVar = new VarSymbol(
681 PUBLIC | FINAL,
682 names.length,
683 intType,
684 arrayClass);
685 arrayClass.members().enter(lengthVar);
686 arrayCloneMethod = new MethodSymbol(
687 PUBLIC,
688 names.clone,
689 new MethodType(List.nil(), objectType,
690 List.nil(), methodClass),
691 arrayClass);
692 arrayClass.members().enter(arrayCloneMethod);
693
694 if (java_base != noModule)
695 java_base.completer = moduleCompleter::complete; //bootstrap issues
696
697 }
698
699 /** Define a new class given its name and owner.
700 */
701 public ClassSymbol defineClass(Name name, Symbol owner) {
702 ClassSymbol c = new ClassSymbol(0, name, owner);
703 c.completer = initialCompleter;
704 return c;
705 }
706
707 /** Create a new toplevel or member class symbol with given name
708 * and owner and enter in `classes' unless already there.
709 */
710 public ClassSymbol enterClass(ModuleSymbol msym, Name name, TypeSymbol owner) {
711 Assert.checkNonNull(msym);
712 Name flatname = TypeSymbol.formFlatName(name, owner);
713 ClassSymbol c = getClass(msym, flatname);
714 if (c == null) {
715 c = defineClass(name, owner);
716 doEnterClass(msym, c);
717 } else if ((c.name != name || c.owner != owner) && owner.kind == TYP &&
718 c.owner.kind == PCK && ((c.flags_field & FROM_SOURCE) == 0)) {
719 // reassign fields of classes that might have been loaded with
720 // their flat names.
721 c.owner.members().remove(c);
722 c.name = name;
723 c.owner = owner;
724 c.fullname = ClassSymbol.formFullName(name, owner);
725 }
726 return c;
727 }
728
729 public ClassSymbol getClass(ModuleSymbol msym, Name flatName) {
730 Assert.checkNonNull(msym, flatName::toString);
731 return classes.getOrDefault(flatName, Collections.emptyMap()).get(msym);
732 }
733
734 public PackageSymbol lookupPackage(ModuleSymbol msym, Name flatName) {
735 return lookupPackage(msym, flatName, false);
736 }
737
738 private PackageSymbol lookupPackage(ModuleSymbol msym, Name flatName, boolean onlyExisting) {
739 Assert.checkNonNull(msym);
740
741 if (flatName.isEmpty()) {
742 //unnamed packages only from the current module - visiblePackages contains *root* package, not unnamed package!
743 return msym.unnamedPackage;
744 }
745
746 if (msym == noModule) {
747 return enterPackage(msym, flatName);
748 }
749
750 msym.complete();
751
752 PackageSymbol pack;
753
754 pack = msym.visiblePackages.get(flatName);
755
756 if (pack != null)
757 return pack;
758
759 pack = getPackage(msym, flatName);
760
761 if ((pack != null && pack.exists()) || onlyExisting)
762 return pack;
763
764 boolean dependsOnUnnamed = msym.requires != null &&
765 msym.requires.stream()
766 .map(rd -> rd.module)
767 .anyMatch(mod -> mod == unnamedModule);
768
769 if (dependsOnUnnamed) {
770 //msyms depends on the unnamed module, for which we generally don't know
771 //the list of packages it "exports" ahead of time. So try to lookup the package in the
772 //current module, and in the unnamed module and see if it exists in one of them
773 PackageSymbol unnamedPack = getPackage(unnamedModule, flatName);
774
775 if (unnamedPack != null && unnamedPack.exists()) {
776 msym.visiblePackages.put(unnamedPack.fullname, unnamedPack);
777 return unnamedPack;
778 }
779
780 pack = enterPackage(msym, flatName);
781 pack.complete();
782 if (pack.exists())
783 return pack;
784
785 unnamedPack = enterPackage(unnamedModule, flatName);
786 unnamedPack.complete();
787 if (unnamedPack.exists()) {
788 msym.visiblePackages.put(unnamedPack.fullname, unnamedPack);
789 return unnamedPack;
790 }
791
792 return pack;
793 }
794
795 return enterPackage(msym, flatName);
796 }
797
798 private static final Map<ModuleSymbol, ClassSymbol> EMPTY = new HashMap<>();
799
800 public void removeClass(ModuleSymbol msym, Name flatName) {
801 classes.getOrDefault(flatName, EMPTY).remove(msym);
802 }
803
804 public Iterable<ClassSymbol> getAllClasses() {
805 return () -> Iterators.createCompoundIterator(classes.values(), v -> v.values().iterator());
806 }
807
808 private void doEnterClass(ModuleSymbol msym, ClassSymbol cs) {
809 classes.computeIfAbsent(cs.flatname, n -> new HashMap<>()).put(msym, cs);
810 }
811
812 /** Create a new member or toplevel class symbol with given flat name
813 * and enter in `classes' unless already there.
814 */
815 public ClassSymbol enterClass(ModuleSymbol msym, Name flatname) {
816 Assert.checkNonNull(msym);
817 PackageSymbol ps = lookupPackage(msym, Convert.packagePart(flatname));
818 Assert.checkNonNull(ps);
819 Assert.checkNonNull(ps.modle);
820 ClassSymbol c = getClass(ps.modle, flatname);
821 if (c == null) {
822 c = defineClass(Convert.shortName(flatname), ps);
823 doEnterClass(ps.modle, c);
824 return c;
825 } else
826 return c;
827 }
828
829 /** Check to see if a package exists, given its fully qualified name.
830 */
831 public boolean packageExists(ModuleSymbol msym, Name fullname) {
832 Assert.checkNonNull(msym);
833 PackageSymbol pack = lookupPackage(msym, fullname, true);
834 return pack != null && pack.exists();
835 }
836
837 /** Make a package, given its fully qualified name.
838 */
839 public PackageSymbol enterPackage(ModuleSymbol currModule, Name fullname) {
840 Assert.checkNonNull(currModule);
841 PackageSymbol p = getPackage(currModule, fullname);
842 if (p == null) {
843 Assert.check(!fullname.isEmpty(), () -> "rootPackage missing!; currModule: " + currModule);
844 p = new PackageSymbol(
845 Convert.shortName(fullname),
846 enterPackage(currModule, Convert.packagePart(fullname)));
847 p.completer = initialCompleter;
848 p.modle = currModule;
849 doEnterPackage(currModule, p);
850 }
851 return p;
852 }
853
854 private void doEnterPackage(ModuleSymbol msym, PackageSymbol pack) {
855 packages.computeIfAbsent(pack.fullname, n -> new HashMap<>()).put(msym, pack);
856 msym.enclosedPackages = msym.enclosedPackages.prepend(pack);
857 }
858
859 private void addRootPackageFor(ModuleSymbol module) {
860 doEnterPackage(module, rootPackage);
861 PackageSymbol unnamedPackage = new PackageSymbol(names.empty, rootPackage) {
862 @Override
863 public String toString() {
864 return messages.getLocalizedString("compiler.misc.unnamed.package");
865 }
866 };
867 unnamedPackage.modle = module;
868 //we cannot use a method reference below, as initialCompleter might be null now
869 unnamedPackage.completer = s -> initialCompleter.complete(s);
870 unnamedPackage.flags_field |= EXISTS;
871 module.unnamedPackage = unnamedPackage;
872 }
873
874 public PackageSymbol getPackage(ModuleSymbol module, Name fullname) {
875 return packages.getOrDefault(fullname, Collections.emptyMap()).get(module);
876 }
877
878 public ModuleSymbol enterModule(Name name) {
879 ModuleSymbol msym = modules.get(name);
880 if (msym == null) {
881 msym = ModuleSymbol.create(name, names.module_info);
882 addRootPackageFor(msym);
883 msym.completer = s -> moduleCompleter.complete(s); //bootstrap issues
884 modules.put(name, msym);
885 }
886 return msym;
887 }
888
889 public ModuleSymbol getModule(Name name) {
890 return modules.get(name);
891 }
892
893 //temporary:
894 public ModuleSymbol inferModule(Name packageName) {
895 if (packageName.isEmpty())
896 return java_base == noModule ? noModule : unnamedModule;//!
897
898 ModuleSymbol msym = null;
899 Map<ModuleSymbol,PackageSymbol> map = packages.get(packageName);
900 if (map == null)
901 return null;
902 for (Map.Entry<ModuleSymbol,PackageSymbol> e: map.entrySet()) {
903 if (!e.getValue().members().isEmpty()) {
904 if (msym == null) {
905 msym = e.getKey();
906 } else {
907 return null;
908 }
909 }
910 }
911 return msym;
912 }
913
914 public List<ModuleSymbol> listPackageModules(Name packageName) {
915 if (packageName.isEmpty())
916 return List.nil();
917
918 List<ModuleSymbol> result = List.nil();
919 Map<ModuleSymbol,PackageSymbol> map = packages.get(packageName);
920 if (map != null) {
921 for (Map.Entry<ModuleSymbol, PackageSymbol> e: map.entrySet()) {
922 if (!e.getValue().members().isEmpty()) {
923 result = result.prepend(e.getKey());
924 }
925 }
926 }
927 return result;
928 }
929
930 public Collection<ModuleSymbol> getAllModules() {
931 return modules.values();
932 }
933
934 public Iterable<ClassSymbol> getClassesForName(Name candidate) {
935 return classes.getOrDefault(candidate, Collections.emptyMap()).values();
936 }
937
938 public Iterable<PackageSymbol> getPackagesForName(Name candidate) {
939 return packages.getOrDefault(candidate, Collections.emptyMap()).values();
940 }
941 }