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