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