1 /*
  2  * Copyright (c) 1999, 2026, 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     /** The symbol representing the finalize method on Object */
251     public final MethodSymbol objectFinalize;
252     public final Type numberType;
253 
254     /** The symbol representing the length field of an array.
255      */
256     public final VarSymbol lengthVar;
257 
258     /** The symbol representing the final finalize method on enums */
259     public final MethodSymbol enumFinalFinalize;
260 
261     /** The symbol representing the close method on TWR AutoCloseable type */
262     public final MethodSymbol autoCloseableClose;
263 
264     /** The predefined type that belongs to a tag.
265      */
266     public final Type[] typeOfTag = new Type[TypeTag.getTypeTagCount()];
267 
268     /** The name of the class that belongs to a basic type tag.
269      */
270     public final Name[] boxedName = new Name[TypeTag.getTypeTagCount()];
271 
272     /** A hashtable containing the encountered top-level and member classes,
273      *  indexed by flat names. The table does not contain local classes.
274      *  It should be updated from the outside to reflect classes defined
275      *  by compiled source files.
276      */
277     private final Map<Name, Map<ModuleSymbol,ClassSymbol>> classes = new HashMap<>();
278 
279     /** A hashtable containing the encountered packages.
280      *  the table should be updated from outside to reflect packages defined
281      *  by compiled source files.
282      */
283     private final Map<Name, Map<ModuleSymbol,PackageSymbol>> packages = new HashMap<>();
284 
285     /** A hashtable giving the encountered modules.
286      */
287     private final Map<Name, ModuleSymbol> modules = new LinkedHashMap<>();
288 
289     private final Map<Types.UniqueType, VarSymbol> classFields = new HashMap<>();
290 
291     public VarSymbol getClassField(Type type, Types types) {
292         return classFields.computeIfAbsent(
293             new UniqueType(type, types), k -> {
294                 Type arg = null;
295                 if (type.getTag() == ARRAY || type.getTag() == CLASS)
296                     arg = types.erasure(type);
297                 else if (type.isPrimitiveOrVoid())
298                     arg = types.boxedClass(type).type;
299                 else
300                     throw new AssertionError(type);
301 
302                 Type t = new ClassType(
303                     classType.getEnclosingType(), List.of(arg), classType.tsym);
304                 return new VarSymbol(
305                     STATIC | PUBLIC | FINAL, names._class, t, type.tsym);
306             });
307     }
308 
309     public void initType(Type type, ClassSymbol c) {
310         type.tsym = c;
311         typeOfTag[type.getTag().ordinal()] = type;
312     }
313 
314     public void initType(Type type, String name) {
315         initType(
316             type,
317             new ClassSymbol(
318                 PUBLIC, names.fromString(name), type, rootPackage));
319     }
320 
321     public void initType(Type type, String name, String bname) {
322         initType(type, name);
323         boxedName[type.getTag().ordinal()] = names.fromString("java.lang." + bname);
324     }
325 
326     /** The class symbol that owns all predefined symbols.
327      */
328     public final ClassSymbol predefClass;
329 
330     /** Enter a class into symbol table.
331      *  @param s The name of the class.
332      */
333     private Type enterClass(String s) {
334         return enterClass(java_base, names.fromString(s)).type;
335     }
336 
337     public void synthesizeEmptyInterfaceIfMissing(final Type type) {
338         final Completer completer = type.tsym.completer;
339         type.tsym.completer = new Completer() {
340             @Override
341             public void complete(Symbol sym) throws CompletionFailure {
342                 try {
343                     completer.complete(sym);
344                 } catch (CompletionFailure e) {
345                     sym.flags_field |= (PUBLIC | INTERFACE);
346                     ((ClassType) sym.type).supertype_field = objectType;
347                 }
348             }
349 
350             @Override
351             public boolean isTerminal() {
352                 return completer.isTerminal();
353             }
354         };
355     }
356 
357     public void synthesizeBoxTypeIfMissing(final Type type) {
358         ClassSymbol sym = enterClass(java_base, boxedName[type.getTag().ordinal()]);
359         final Completer completer = sym.completer;
360         sym.completer = new Completer() {
361             @Override
362             public void complete(Symbol sym) throws CompletionFailure {
363                 try {
364                     completer.complete(sym);
365                 } catch (CompletionFailure e) {
366                     sym.flags_field |= PUBLIC;
367                     ((ClassType) sym.type).supertype_field = objectType;
368                     MethodSymbol boxMethod =
369                         new MethodSymbol(PUBLIC | STATIC, names.valueOf,
370                                          new MethodType(List.of(type), sym.type,
371                                 List.nil(), methodClass),
372                             sym);
373                     sym.members().enter(boxMethod);
374                     MethodSymbol unboxMethod =
375                         new MethodSymbol(PUBLIC,
376                             type.tsym.name.append(names.Value), // x.intValue()
377                             new MethodType(List.nil(), type,
378                                 List.nil(), methodClass),
379                             sym);
380                     sym.members().enter(unboxMethod);
381                 }
382             }
383 
384             @Override
385             public boolean isTerminal() {
386                 return completer.isTerminal();
387             }
388         };
389     }
390 
391     // Enter a synthetic class that is used to mark classes in ct.sym.
392     // This class does not have a class file.
393     private Type enterSyntheticAnnotation(String name) {
394         return enterSyntheticAnnotation(names.fromString(name));
395     }
396 
397     // Enter a synthetic class that is used to mark classes in ct.sym.
398     // This class does not have a class file.
399     private Type enterSyntheticAnnotation(Name name) {
400         // for now, leave the module null, to prevent problems from synthesizing the
401         // existence of a class in any specific module, including noModule
402         ClassType type = (ClassType)enterClass(java_base, name).type;
403         ClassSymbol sym = (ClassSymbol)type.tsym;
404         sym.completer = Completer.NULL_COMPLETER;
405         sym.flags_field = PUBLIC|ACYCLIC|ANNOTATION|INTERFACE;
406         sym.erasure_field = type;
407         sym.members_field = WriteableScope.create(sym);
408         type.typarams_field = List.nil();
409         type.allparams_field = List.nil();
410         type.supertype_field = annotationType;
411         type.interfaces_field = List.nil();
412         return type;
413     }
414 
415     /** Constructor; enters all predefined identifiers and operators
416      *  into symbol table.
417      */
418     @SuppressWarnings("this-escape")
419     protected Symtab(Context context) throws CompletionFailure {
420         context.put(symtabKey, this);
421 
422         names = Names.instance(context);
423 
424         messages = JavacMessages.instance(context);
425 
426         MissingInfoHandler missingInfoHandler = MissingInfoHandler.instance(context);
427 
428         Target target = Target.instance(context);
429         rootPackage = new RootPackageSymbol(names.empty, null,
430                                             missingInfoHandler,
431                                             target.runtimeUseNestAccess());
432 
433         noModule = new ModuleSymbol(names.empty, null) {
434             @Override public boolean isNoModule() {
435                 return true;
436             }
437         };
438         addRootPackageFor(noModule);
439 
440         Source source = Source.instance(context);
441         if (Feature.MODULES.allowedInSource(source)) {
442             java_base = enterModule(names.java_base);
443             //avoid completing java.base during the Symtab initialization
444             java_base.completer = Completer.NULL_COMPLETER;
445             java_base.visiblePackages = Collections.emptyMap();
446         } else {
447             java_base = noModule;
448         }
449 
450         // create the basic builtin symbols
451         unnamedModule = new ModuleSymbol(names.empty, null) {
452                 {
453                     directives = List.nil();
454                     exports = List.nil();
455                     provides = List.nil();
456                     uses = List.nil();
457                     com.sun.tools.javac.code.Directive.RequiresDirective d =
458                             new com.sun.tools.javac.code.Directive.RequiresDirective(java_base,
459                                     EnumSet.of(com.sun.tools.javac.code.Directive.RequiresFlag.MANDATED));
460                     requires = List.of(d);
461                 }
462                 @Override
463                 public String toString() {
464                     return messages.getLocalizedString("compiler.misc.unnamed.module");
465                 }
466             };
467         addRootPackageFor(unnamedModule);
468         unnamedModule.enclosedPackages = unnamedModule.enclosedPackages.prepend(unnamedModule.unnamedPackage);
469 
470         errModule = new ModuleSymbol(names.empty, null) {
471                 {
472                     directives = List.nil();
473                     exports = List.nil();
474                     provides = List.nil();
475                     uses = List.nil();
476                     com.sun.tools.javac.code.Directive.RequiresDirective d =
477                             new com.sun.tools.javac.code.Directive.RequiresDirective(java_base,
478                                     EnumSet.of(com.sun.tools.javac.code.Directive.RequiresFlag.MANDATED));
479                     requires = List.of(d);
480                 }
481             };
482         addRootPackageFor(errModule);
483 
484         noSymbol = new TypeSymbol(NIL, 0, names.empty, Type.noType, rootPackage) {
485             @Override @DefinedBy(Api.LANGUAGE_MODEL)
486             public <R, P> R accept(ElementVisitor<R, P> v, P p) {
487                 return v.visitUnknown(this, p);
488             }
489         };
490 
491         // create the error symbols
492         errSymbol = new ClassSymbol(PUBLIC|STATIC|ACYCLIC, names.any, null, rootPackage);
493         errType = new ErrorType(errSymbol, Type.noType);
494 
495         unknownSymbol = new ClassSymbol(PUBLIC|STATIC|ACYCLIC, names.fromString("<any?>"), null, rootPackage);
496         // Create the unknown type
497         unknownType = new ErrorType(unknownSymbol, Type.noType);
498 
499         // initialize builtin types
500         initType(byteType, "byte", "Byte");
501         initType(shortType, "short", "Short");
502         initType(charType, "char", "Character");
503         initType(intType, "int", "Integer");
504         initType(longType, "long", "Long");
505         initType(floatType, "float", "Float");
506         initType(doubleType, "double", "Double");
507         initType(booleanType, "boolean", "Boolean");
508         initType(voidType, "void", "Void");
509         initType(botType, "<nulltype>");
510         initType(errType, errSymbol);
511         initType(unknownType, unknownSymbol);
512 
513         // the builtin class of all arrays
514         arrayClass = new ClassSymbol(PUBLIC|ACYCLIC, names.Array, noSymbol);
515 
516         // VGJ
517         boundClass = new ClassSymbol(PUBLIC|ACYCLIC, names.Bound, noSymbol);
518         boundClass.members_field = new Scope.ErrorScope(boundClass);
519 
520         // the builtin class of all methods
521         methodClass = new ClassSymbol(PUBLIC|ACYCLIC, names.Method, noSymbol);
522         methodClass.members_field = new Scope.ErrorScope(boundClass);
523 
524         // Create class to hold all predefined constants and operations.
525         predefClass = new ClassSymbol(PUBLIC|ACYCLIC, names.empty, rootPackage);
526         WriteableScope scope = WriteableScope.create(predefClass);
527         predefClass.members_field = scope;
528 
529         // Get the initial completer for Symbols from the ClassFinder
530         initialCompleter = ClassFinder.instance(context).getCompleter();
531         rootPackage.members_field = WriteableScope.create(rootPackage);
532 
533         // Enter symbols for basic types.
534         scope.enter(byteType.tsym);
535         scope.enter(shortType.tsym);
536         scope.enter(charType.tsym);
537         scope.enter(intType.tsym);
538         scope.enter(longType.tsym);
539         scope.enter(floatType.tsym);
540         scope.enter(doubleType.tsym);
541         scope.enter(booleanType.tsym);
542         scope.enter(errType.tsym);
543 
544         // Enter symbol for the errSymbol
545         scope.enter(errSymbol);
546 
547         // Get the initial completer for ModuleSymbols from Modules
548         moduleCompleter = Modules.instance(context).getCompleter();
549 
550         // Enter predefined classes. All are assumed to be in the java.base module.
551         objectType = enterClass("java.lang.Object");
552         throwableType = enterClass("java.lang.Throwable");
553         objectFinalize = new MethodSymbol(PROTECTED,
554                 names.finalize,
555                 new MethodType(List.nil(), voidType,
556                         List.of(throwableType), methodClass),
557                 objectType.tsym);
558         objectMethodsType = enterClass("java.lang.runtime.ObjectMethods");
559         exactConversionsSupportType = enterClass("java.lang.runtime.ExactConversionsSupport");
560         objectsType = enterClass("java.util.Objects");
561         classType = enterClass("java.lang.Class");
562         stringType = enterClass("java.lang.String");
563         stringBufferType = enterClass("java.lang.StringBuffer");
564         stringBuilderType = enterClass("java.lang.StringBuilder");
565         cloneableType = enterClass("java.lang.Cloneable");
566         serializableType = enterClass("java.io.Serializable");
567         serializedLambdaType = enterClass("java.lang.invoke.SerializedLambda");
568         varHandleType = enterClass("java.lang.invoke.VarHandle");
569         methodHandleType = enterClass("java.lang.invoke.MethodHandle");
570         methodHandlesType = enterClass("java.lang.invoke.MethodHandles");
571         methodHandleLookupType = enterClass("java.lang.invoke.MethodHandles$Lookup");
572         methodTypeType = enterClass("java.lang.invoke.MethodType");
573         errorType = enterClass("java.lang.Error");
574         illegalArgumentExceptionType = enterClass("java.lang.IllegalArgumentException");
575         interruptedExceptionType = enterClass("java.lang.InterruptedException");
576         exceptionType = enterClass("java.lang.Exception");
577         runtimeExceptionType = enterClass("java.lang.RuntimeException");
578         classNotFoundExceptionType = enterClass("java.lang.ClassNotFoundException");
579         noClassDefFoundErrorType = enterClass("java.lang.NoClassDefFoundError");
580         noSuchFieldErrorType = enterClass("java.lang.NoSuchFieldError");
581         assertionErrorType = enterClass("java.lang.AssertionError");
582         incompatibleClassChangeErrorType = enterClass("java.lang.IncompatibleClassChangeError");
583         cloneNotSupportedExceptionType = enterClass("java.lang.CloneNotSupportedException");
584         matchExceptionType = enterClass("java.lang.MatchException");
585         annotationType = enterClass("java.lang.annotation.Annotation");
586         classLoaderType = enterClass("java.lang.ClassLoader");
587         enumSym = enterClass(java_base, names.java_lang_Enum);
588         enumFinalFinalize =
589             new MethodSymbol(PROTECTED|FINAL|HYPOTHETICAL,
590                              names.finalize,
591                              new MethodType(List.nil(), voidType,
592                                             List.nil(), methodClass),
593                              enumSym);
594         listType = enterClass("java.util.List");
595         collectionsType = enterClass("java.util.Collections");
596         comparableType = enterClass("java.lang.Comparable");
597         comparatorType = enterClass("java.util.Comparator");
598         arraysType = enterClass("java.util.Arrays");
599         iterableType = enterClass("java.lang.Iterable");
600         iteratorType = enterClass("java.util.Iterator");
601         annotationTargetType = enterClass("java.lang.annotation.Target");
602         overrideType = enterClass("java.lang.Override");
603         retentionType = enterClass("java.lang.annotation.Retention");
604         deprecatedType = enterClass("java.lang.Deprecated");
605         suppressWarningsType = enterClass("java.lang.SuppressWarnings");
606         supplierType = enterClass("java.util.function.Supplier");
607         inheritedType = enterClass("java.lang.annotation.Inherited");
608         repeatableType = enterClass("java.lang.annotation.Repeatable");
609         documentedType = enterClass("java.lang.annotation.Documented");
610         elementTypeType = enterClass("java.lang.annotation.ElementType");
611         systemType = enterClass("java.lang.System");
612         autoCloseableType = enterClass("java.lang.AutoCloseable");
613         autoCloseableClose = new MethodSymbol(PUBLIC,
614                              names.close,
615                              new MethodType(List.nil(), voidType,
616                                             List.of(exceptionType), methodClass),
617                              autoCloseableType.tsym);
618         trustMeType = enterClass("java.lang.SafeVarargs");
619         nativeHeaderType = enterClass("java.lang.annotation.Native");
620         lambdaMetafactory = enterClass("java.lang.invoke.LambdaMetafactory");
621         stringConcatFactory = enterClass("java.lang.invoke.StringConcatFactory");
622         functionalInterfaceType = enterClass("java.lang.FunctionalInterface");
623         previewFeatureType = enterClass("jdk.internal.javac.PreviewFeature");
624         previewFeatureInternalType = enterSyntheticAnnotation("jdk.internal.PreviewFeature+Annotation");
625         restrictedType = enterClass("jdk.internal.javac.Restricted");
626         restrictedInternalType = enterSyntheticAnnotation("jdk.internal.javac.Restricted+Annotation");
627         typeDescriptorType = enterClass("java.lang.invoke.TypeDescriptor");
628         recordType = enterClass("java.lang.Record");
629         switchBootstrapsType = enterClass("java.lang.runtime.SwitchBootstraps");
630         constantBootstrapsType = enterClass("java.lang.invoke.ConstantBootstraps");
631         valueBasedType = enterClass("jdk.internal.ValueBased");
632         valueBasedInternalType = enterSyntheticAnnotation("jdk.internal.ValueBased+Annotation");
633         migratedValueClassType = enterClass("jdk.internal.MigratedValueClass");
634         migratedValueClassInternalType = enterSyntheticAnnotation("jdk.internal.MigratedValueClass+Annotation");
635         requiresIdentityType = enterClass("jdk.internal.RequiresIdentity");
636         requiresIdentityInternalType = enterSyntheticAnnotation(names.requiresIdentityInternal);
637         classDescType = enterClass("java.lang.constant.ClassDesc");
638         enumDescType = enterClass("java.lang.Enum$EnumDesc");
639         // For serialization lint checking
640         objectStreamFieldType = enterClass("java.io.ObjectStreamField");
641         objectInputStreamType = enterClass("java.io.ObjectInputStream");
642         objectOutputStreamType = enterClass("java.io.ObjectOutputStream");
643         ioExceptionType = enterClass("java.io.IOException");
644         objectStreamExceptionType = enterClass("java.io.ObjectStreamException");
645         externalizableType = enterClass("java.io.Externalizable");
646         objectInputType  = enterClass("java.io.ObjectInput");
647         objectOutputType = enterClass("java.io.ObjectOutput");
648         synthesizeEmptyInterfaceIfMissing(autoCloseableType);
649         synthesizeEmptyInterfaceIfMissing(cloneableType);
650         synthesizeEmptyInterfaceIfMissing(serializableType);
651         synthesizeEmptyInterfaceIfMissing(lambdaMetafactory);
652         synthesizeEmptyInterfaceIfMissing(serializedLambdaType);
653         synthesizeEmptyInterfaceIfMissing(stringConcatFactory);
654         synthesizeBoxTypeIfMissing(doubleType);
655         synthesizeBoxTypeIfMissing(floatType);
656         synthesizeBoxTypeIfMissing(voidType);
657 
658         numberType = enterClass("java.lang.Number");
659 
660         // Enter a synthetic class that is used to mark internal
661         // proprietary classes in ct.sym.  This class does not have a
662         // class file.
663         proprietaryType = enterSyntheticAnnotation("sun.Proprietary+Annotation");
664 
665         // Enter a synthetic class that is used to provide profile info for
666         // classes in ct.sym.  This class does not have a class file.
667         profileType = enterSyntheticAnnotation("jdk.Profile+Annotation");
668         MethodSymbol m = new MethodSymbol(PUBLIC | ABSTRACT, names.value, intType, profileType.tsym);
669         profileType.tsym.members().enter(m);
670 
671         // Enter a class for arrays.
672         // The class implements java.lang.Cloneable and java.io.Serializable.
673         // It has a final length field and a clone method.
674         ClassType arrayClassType = (ClassType)arrayClass.type;
675         arrayClassType.supertype_field = objectType;
676         arrayClassType.interfaces_field = List.of(cloneableType, serializableType);
677         arrayClass.members_field = WriteableScope.create(arrayClass);
678         lengthVar = new VarSymbol(
679             PUBLIC | FINAL,
680             names.length,
681             intType,
682             arrayClass);
683         arrayClass.members().enter(lengthVar);
684         arrayCloneMethod = new MethodSymbol(
685             PUBLIC,
686             names.clone,
687             new MethodType(List.nil(), objectType,
688                            List.nil(), methodClass),
689             arrayClass);
690         arrayClass.members().enter(arrayCloneMethod);
691 
692         if (java_base != noModule)
693             java_base.completer = moduleCompleter::complete; //bootstrap issues
694 
695     }
696 
697     /** Define a new class given its name and owner.
698      */
699     public ClassSymbol defineClass(Name name, Symbol owner) {
700         ClassSymbol c = new ClassSymbol(0, name, owner);
701         c.completer = initialCompleter;
702         return c;
703     }
704 
705     /** Create a new toplevel or member class symbol with given name
706      *  and owner and enter in `classes' unless already there.
707      */
708     public ClassSymbol enterClass(ModuleSymbol msym, Name name, TypeSymbol owner) {
709         Assert.checkNonNull(msym);
710         Name flatname = TypeSymbol.formFlatName(name, owner);
711         ClassSymbol c = getClass(msym, flatname);
712         if (c == null) {
713             c = defineClass(name, owner);
714             doEnterClass(msym, c);
715         } else if ((c.name != name || c.owner != owner) && owner.kind == TYP &&
716                    c.owner.kind == PCK && ((c.flags_field & FROM_SOURCE) == 0)) {
717             // reassign fields of classes that might have been loaded with
718             // their flat names.
719             c.owner.members().remove(c);
720             c.name = name;
721             c.owner = owner;
722             c.fullname = ClassSymbol.formFullName(name, owner);
723         }
724         return c;
725     }
726 
727     public ClassSymbol getClass(ModuleSymbol msym, Name flatName) {
728         Assert.checkNonNull(msym, flatName::toString);
729         return classes.getOrDefault(flatName, Collections.emptyMap()).get(msym);
730     }
731 
732     public PackageSymbol lookupPackage(ModuleSymbol msym, Name flatName) {
733         return lookupPackage(msym, flatName, false);
734     }
735 
736     private PackageSymbol lookupPackage(ModuleSymbol msym, Name flatName, boolean onlyExisting) {
737         Assert.checkNonNull(msym);
738 
739         if (flatName.isEmpty()) {
740             //unnamed packages only from the current module - visiblePackages contains *root* package, not unnamed package!
741             return msym.unnamedPackage;
742         }
743 
744         if (msym == noModule) {
745             return enterPackage(msym, flatName);
746         }
747 
748         msym.complete();
749 
750         PackageSymbol pack;
751 
752         pack = msym.visiblePackages.get(flatName);
753 
754         if (pack != null)
755             return pack;
756 
757         pack = getPackage(msym, flatName);
758 
759         if ((pack != null && pack.exists()) || onlyExisting)
760             return pack;
761 
762         boolean dependsOnUnnamed = msym.requires != null &&
763                                    msym.requires.stream()
764                                                 .map(rd -> rd.module)
765                                                 .anyMatch(mod -> mod == unnamedModule);
766 
767         if (dependsOnUnnamed) {
768             //msyms depends on the unnamed module, for which we generally don't know
769             //the list of packages it "exports" ahead of time. So try to lookup the package in the
770             //current module, and in the unnamed module and see if it exists in one of them
771             PackageSymbol unnamedPack = getPackage(unnamedModule, flatName);
772 
773             if (unnamedPack != null && unnamedPack.exists()) {
774                 msym.visiblePackages.put(unnamedPack.fullname, unnamedPack);
775                 return unnamedPack;
776             }
777 
778             pack = enterPackage(msym, flatName);
779             pack.complete();
780             if (pack.exists())
781                 return pack;
782 
783             unnamedPack = enterPackage(unnamedModule, flatName);
784             unnamedPack.complete();
785             if (unnamedPack.exists()) {
786                 msym.visiblePackages.put(unnamedPack.fullname, unnamedPack);
787                 return unnamedPack;
788             }
789 
790             return pack;
791         }
792 
793         return enterPackage(msym, flatName);
794     }
795 
796     private static final Map<ModuleSymbol, ClassSymbol> EMPTY = new HashMap<>();
797 
798     public void removeClass(ModuleSymbol msym, Name flatName) {
799         classes.getOrDefault(flatName, EMPTY).remove(msym);
800     }
801 
802     public Iterable<ClassSymbol> getAllClasses() {
803         return () -> Iterators.createCompoundIterator(classes.values(), v -> v.values().iterator());
804     }
805 
806     private void doEnterClass(ModuleSymbol msym, ClassSymbol cs) {
807         classes.computeIfAbsent(cs.flatname, n -> new HashMap<>()).put(msym, cs);
808     }
809 
810     /** Create a new member or toplevel class symbol with given flat name
811      *  and enter in `classes' unless already there.
812      */
813     public ClassSymbol enterClass(ModuleSymbol msym, Name flatname) {
814         Assert.checkNonNull(msym);
815         PackageSymbol ps = lookupPackage(msym, Convert.packagePart(flatname));
816         Assert.checkNonNull(ps);
817         Assert.checkNonNull(ps.modle);
818         ClassSymbol c = getClass(ps.modle, flatname);
819         if (c == null) {
820             c = defineClass(Convert.shortName(flatname), ps);
821             doEnterClass(ps.modle, c);
822             return c;
823         } else
824             return c;
825     }
826 
827     /** Check to see if a package exists, given its fully qualified name.
828      */
829     public boolean packageExists(ModuleSymbol msym, Name fullname) {
830         Assert.checkNonNull(msym);
831         PackageSymbol pack = lookupPackage(msym, fullname, true);
832         return pack != null && pack.exists();
833     }
834 
835     /** Make a package, given its fully qualified name.
836      */
837     public PackageSymbol enterPackage(ModuleSymbol currModule, Name fullname) {
838         Assert.checkNonNull(currModule);
839         PackageSymbol p = getPackage(currModule, fullname);
840         if (p == null) {
841             Assert.check(!fullname.isEmpty(), () -> "rootPackage missing!; currModule: " + currModule);
842             p = new PackageSymbol(
843                     Convert.shortName(fullname),
844                     enterPackage(currModule, Convert.packagePart(fullname)));
845             p.completer = initialCompleter;
846             p.modle = currModule;
847             doEnterPackage(currModule, p);
848         }
849         return p;
850     }
851 
852     private void doEnterPackage(ModuleSymbol msym, PackageSymbol pack) {
853         packages.computeIfAbsent(pack.fullname, n -> new HashMap<>()).put(msym, pack);
854         msym.enclosedPackages = msym.enclosedPackages.prepend(pack);
855     }
856 
857     private void addRootPackageFor(ModuleSymbol module) {
858         doEnterPackage(module, rootPackage);
859         PackageSymbol unnamedPackage = new PackageSymbol(names.empty, rootPackage) {
860                 @Override
861                 public String toString() {
862                     return messages.getLocalizedString("compiler.misc.unnamed.package");
863                 }
864             };
865         unnamedPackage.modle = module;
866         //we cannot use a method reference below, as initialCompleter might be null now
867         unnamedPackage.completer = s -> initialCompleter.complete(s);
868         unnamedPackage.flags_field |= EXISTS;
869         module.unnamedPackage = unnamedPackage;
870     }
871 
872     public PackageSymbol getPackage(ModuleSymbol module, Name fullname) {
873         return packages.getOrDefault(fullname, Collections.emptyMap()).get(module);
874     }
875 
876     public ModuleSymbol enterModule(Name name) {
877         ModuleSymbol msym = modules.get(name);
878         if (msym == null) {
879             msym = ModuleSymbol.create(name, names.module_info);
880             addRootPackageFor(msym);
881             msym.completer = s -> moduleCompleter.complete(s); //bootstrap issues
882             modules.put(name, msym);
883         }
884         return msym;
885     }
886 
887     public ModuleSymbol getModule(Name name) {
888         return modules.get(name);
889     }
890 
891     //temporary:
892     public ModuleSymbol inferModule(Name packageName) {
893         if (packageName.isEmpty())
894             return java_base == noModule ? noModule : unnamedModule;//!
895 
896         ModuleSymbol msym = null;
897         Map<ModuleSymbol,PackageSymbol> map = packages.get(packageName);
898         if (map == null)
899             return null;
900         for (Map.Entry<ModuleSymbol,PackageSymbol> e: map.entrySet()) {
901             if (!e.getValue().members().isEmpty()) {
902                 if (msym == null) {
903                     msym = e.getKey();
904                 } else {
905                     return null;
906                 }
907             }
908         }
909         return msym;
910     }
911 
912     public List<ModuleSymbol> listPackageModules(Name packageName) {
913         if (packageName.isEmpty())
914             return List.nil();
915 
916         List<ModuleSymbol> result = List.nil();
917         Map<ModuleSymbol,PackageSymbol> map = packages.get(packageName);
918         if (map != null) {
919             for (Map.Entry<ModuleSymbol, PackageSymbol> e: map.entrySet()) {
920                 if (!e.getValue().members().isEmpty()) {
921                     result = result.prepend(e.getKey());
922                 }
923             }
924         }
925         return result;
926     }
927 
928     public Collection<ModuleSymbol> getAllModules() {
929         return modules.values();
930     }
931 
932     public Iterable<ClassSymbol> getClassesForName(Name candidate) {
933         return classes.getOrDefault(candidate, Collections.emptyMap()).values();
934     }
935 
936     public Iterable<PackageSymbol> getPackagesForName(Name candidate) {
937         return packages.getOrDefault(candidate, Collections.emptyMap()).values();
938     }
939 }