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