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