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