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