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