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