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