Symtab.java revision 3640:53ebb47dc802
1321369Sdim/*
2274955Ssvnmir * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
3353358Sdim * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4353358Sdim *
5353358Sdim * This code is free software; you can redistribute it and/or modify it
6274955Ssvnmir * under the terms of the GNU General Public License version 2 only, as
7274955Ssvnmir * published by the Free Software Foundation.  Oracle designates this
8274955Ssvnmir * particular file as subject to the "Classpath" exception as provided
9274955Ssvnmir * by Oracle in the LICENSE file that accompanied this code.
10274955Ssvnmir *
11274955Ssvnmir * This code is distributed in the hope that it will be useful, but WITHOUT
12321369Sdim * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13280031Sdim * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14274955Ssvnmir * version 2 for more details (a copy is included in the LICENSE file that
15321369Sdim * accompanied this code).
16274955Ssvnmir *
17274955Ssvnmir * You should have received a copy of the GNU General Public License version
18321369Sdim * 2 along with this work; if not, write to the Free Software Foundation,
19274955Ssvnmir * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20274955Ssvnmir *
21321369Sdim * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22274955Ssvnmir * or visit www.oracle.com if you need additional information or have any
23274955Ssvnmir * questions.
24274955Ssvnmir */
25274955Ssvnmir
26274955Ssvnmirpackage com.sun.tools.javac.code;
27274955Ssvnmir
28274955Ssvnmirimport java.util.Collection;
29274955Ssvnmirimport java.util.Collections;
30309124Sdimimport java.util.EnumSet;
31309124Sdimimport java.util.HashMap;
32309124Sdimimport java.util.LinkedHashMap;
33309124Sdimimport java.util.Map;
34274955Ssvnmir
35274955Ssvnmirimport javax.lang.model.element.ElementVisitor;
36274955Ssvnmir
37274955Ssvnmirimport com.sun.tools.javac.code.Scope.WriteableScope;
38274955Ssvnmirimport com.sun.tools.javac.code.Symbol.ClassSymbol;
39274955Ssvnmirimport com.sun.tools.javac.code.Symbol.Completer;
40296417Sdimimport com.sun.tools.javac.code.Symbol.CompletionFailure;
41314564Sdimimport com.sun.tools.javac.code.Symbol.MethodSymbol;
42314564Sdimimport com.sun.tools.javac.code.Symbol.ModuleSymbol;
43314564Sdimimport com.sun.tools.javac.code.Symbol.PackageSymbol;
44314564Sdimimport com.sun.tools.javac.code.Symbol.TypeSymbol;
45314564Sdimimport com.sun.tools.javac.code.Symbol.VarSymbol;
46314564Sdimimport com.sun.tools.javac.code.Type.BottomType;
47314564Sdimimport com.sun.tools.javac.code.Type.ClassType;
48288943Sdimimport com.sun.tools.javac.code.Type.ErrorType;
49274955Ssvnmirimport com.sun.tools.javac.code.Type.JCPrimitiveType;
50296417Sdimimport com.sun.tools.javac.code.Type.JCVoidType;
51314564Sdimimport com.sun.tools.javac.code.Type.MethodType;
52314564Sdimimport com.sun.tools.javac.code.Type.UnknownType;
53314564Sdimimport com.sun.tools.javac.comp.Modules;
54314564Sdimimport com.sun.tools.javac.util.Assert;
55274955Ssvnmirimport com.sun.tools.javac.util.Context;
56274955Ssvnmirimport com.sun.tools.javac.util.Convert;
57274955Ssvnmirimport com.sun.tools.javac.util.DefinedBy;
58274955Ssvnmirimport com.sun.tools.javac.util.DefinedBy.Api;
59318655Sdimimport com.sun.tools.javac.util.Iterators;
60318655Sdimimport com.sun.tools.javac.util.JavacMessages;
61318655Sdimimport com.sun.tools.javac.util.List;
62318655Sdimimport com.sun.tools.javac.util.Name;
63274955Ssvnmirimport com.sun.tools.javac.util.Names;
64274955Ssvnmirimport com.sun.tools.javac.util.Options;
65274955Ssvnmir
66288943Sdimimport static com.sun.tools.javac.code.Flags.*;
67274955Ssvnmirimport static com.sun.tools.javac.code.Kinds.Kind.*;
68274955Ssvnmirimport static com.sun.tools.javac.code.TypeTag.*;
69274955Ssvnmir
70274955Ssvnmir/** A class that defines all predefined constants and operators
71274955Ssvnmir *  as well as special classes such as java.lang.Object, which need
72274955Ssvnmir *  to be known to the compiler. All symbols are held in instance
73274955Ssvnmir *  fields. This makes it possible to work in multiple concurrent
74274955Ssvnmir *  projects, which might use different class files for library classes.
75288943Sdim *
76274955Ssvnmir *  <p><b>This is NOT part of any supported API.
77274955Ssvnmir *  If you write code that depends on this, you do so at your own risk.
78274955Ssvnmir *  This code and its internal interfaces are subject to change or
79288943Sdim *  deletion without notice.</b>
80274955Ssvnmir */
81274955Ssvnmirpublic class Symtab {
82274955Ssvnmir    /** The context key for the symbol table. */
83274955Ssvnmir    protected static final Context.Key<Symtab> symtabKey = new Context.Key<>();
84274955Ssvnmir
85274955Ssvnmir    /** Get the symbol table instance. */
86274955Ssvnmir    public static Symtab instance(Context context) {
87274955Ssvnmir        Symtab instance = context.get(symtabKey);
88274955Ssvnmir        if (instance == null)
89309124Sdim            instance = new Symtab(context);
90309124Sdim        return instance;
91309124Sdim    }
92274955Ssvnmir
93274955Ssvnmir    /** Builtin types.
94274955Ssvnmir     */
95274955Ssvnmir    public final JCPrimitiveType byteType = new JCPrimitiveType(BYTE, null);
96274955Ssvnmir    public final JCPrimitiveType charType = new JCPrimitiveType(CHAR, null);
97274955Ssvnmir    public final JCPrimitiveType shortType = new JCPrimitiveType(SHORT, null);
98314564Sdim    public final JCPrimitiveType intType = new JCPrimitiveType(INT, null);
99344779Sdim    public final JCPrimitiveType longType = new JCPrimitiveType(LONG, null);
100274955Ssvnmir    public final JCPrimitiveType floatType = new JCPrimitiveType(FLOAT, null);
101274955Ssvnmir    public final JCPrimitiveType doubleType = new JCPrimitiveType(DOUBLE, null);
102274955Ssvnmir    public final JCPrimitiveType booleanType = new JCPrimitiveType(BOOLEAN, null);
103318655Sdim    public final Type botType = new BottomType();
104318655Sdim    public final JCVoidType voidType = new JCVoidType();
105344779Sdim
106318655Sdim    private final Names names;
107318655Sdim    private final JavacMessages messages;
108318655Sdim    private final Completer initialCompleter;
109274955Ssvnmir    private final Completer moduleCompleter;
110274955Ssvnmir
111296417Sdim    /** A symbol for the unnamed module.
112314564Sdim     */
113274955Ssvnmir    public final ModuleSymbol unnamedModule;
114296417Sdim
115274955Ssvnmir    /** The error module.
116     */
117    public final ModuleSymbol errModule;
118
119    /** A symbol for no module, for use with -source 8 or less
120     */
121    public final ModuleSymbol noModule;
122
123    /** A symbol for the root package.
124     */
125    public final PackageSymbol rootPackage;
126
127    /** A symbol that stands for a missing symbol.
128     */
129    public final TypeSymbol noSymbol;
130
131    /** The error symbol.
132     */
133    public final ClassSymbol errSymbol;
134
135    /** The unknown symbol.
136     */
137    public final ClassSymbol unknownSymbol;
138
139    /** A value for the errType, with a originalType of noType */
140    public final Type errType;
141
142    /** A value for the unknown type. */
143    public final Type unknownType;
144
145    /** The builtin type of all arrays. */
146    public final ClassSymbol arrayClass;
147    public final MethodSymbol arrayCloneMethod;
148
149    /** VGJ: The (singleton) type of all bound types. */
150    public final ClassSymbol boundClass;
151
152    /** The builtin type of all methods. */
153    public final ClassSymbol methodClass;
154
155    /** A symbol for the java.base module.
156     */
157    public final ModuleSymbol java_base;
158
159    /** Predefined types.
160     */
161    public final Type objectType;
162    public final Type objectsType;
163    public final Type classType;
164    public final Type classLoaderType;
165    public final Type stringType;
166    public final Type stringBufferType;
167    public final Type stringBuilderType;
168    public final Type cloneableType;
169    public final Type serializableType;
170    public final Type serializedLambdaType;
171    public final Type varHandleType;
172    public final Type methodHandleType;
173    public final Type methodHandleLookupType;
174    public final Type methodTypeType;
175    public final Type nativeHeaderType;
176    public final Type throwableType;
177    public final Type errorType;
178    public final Type interruptedExceptionType;
179    public final Type illegalArgumentExceptionType;
180    public final Type exceptionType;
181    public final Type runtimeExceptionType;
182    public final Type classNotFoundExceptionType;
183    public final Type noClassDefFoundErrorType;
184    public final Type noSuchFieldErrorType;
185    public final Type assertionErrorType;
186    public final Type cloneNotSupportedExceptionType;
187    public final Type annotationType;
188    public final TypeSymbol enumSym;
189    public final Type listType;
190    public final Type collectionsType;
191    public final Type comparableType;
192    public final Type comparatorType;
193    public final Type arraysType;
194    public final Type iterableType;
195    public final Type iteratorType;
196    public final Type annotationTargetType;
197    public final Type overrideType;
198    public final Type retentionType;
199    public final Type deprecatedType;
200    public final Type suppressWarningsType;
201    public final Type supplierType;
202    public final Type inheritedType;
203    public final Type profileType;
204    public final Type proprietaryType;
205    public final Type systemType;
206    public final Type autoCloseableType;
207    public final Type trustMeType;
208    public final Type lambdaMetafactory;
209    public final Type stringConcatFactory;
210    public final Type repeatableType;
211    public final Type documentedType;
212    public final Type elementTypeType;
213    public final Type functionalInterfaceType;
214
215    /** The symbol representing the length field of an array.
216     */
217    public final VarSymbol lengthVar;
218
219    /** The symbol representing the final finalize method on enums */
220    public final MethodSymbol enumFinalFinalize;
221
222    /** The symbol representing the close method on TWR AutoCloseable type */
223    public final MethodSymbol autoCloseableClose;
224
225    /** The predefined type that belongs to a tag.
226     */
227    public final Type[] typeOfTag = new Type[TypeTag.getTypeTagCount()];
228
229    /** The name of the class that belongs to a basic type tag.
230     */
231    public final Name[] boxedName = new Name[TypeTag.getTypeTagCount()];
232
233    /** A hashtable containing the encountered top-level and member classes,
234     *  indexed by flat names. The table does not contain local classes.
235     *  It should be updated from the outside to reflect classes defined
236     *  by compiled source files.
237     */
238    private final Map<Name, Map<ModuleSymbol,ClassSymbol>> classes = new HashMap<>();
239
240    /** A hashtable containing the encountered packages.
241     *  the table should be updated from outside to reflect packages defined
242     *  by compiled source files.
243     */
244    private final Map<Name, Map<ModuleSymbol,PackageSymbol>> packages = new HashMap<>();
245
246    /** A hashtable giving the encountered modules.
247     */
248    private final Map<Name, ModuleSymbol> modules = new LinkedHashMap<>();
249
250    public void initType(Type type, ClassSymbol c) {
251        type.tsym = c;
252        typeOfTag[type.getTag().ordinal()] = type;
253    }
254
255    public void initType(Type type, String name) {
256        initType(
257            type,
258            new ClassSymbol(
259                PUBLIC, names.fromString(name), type, rootPackage));
260    }
261
262    public void initType(Type type, String name, String bname) {
263        initType(type, name);
264        boxedName[type.getTag().ordinal()] = names.fromString("java.lang." + bname);
265    }
266
267    /** The class symbol that owns all predefined symbols.
268     */
269    public final ClassSymbol predefClass;
270
271    /** Enter a class into symbol table.
272     *  @param s The name of the class.
273     */
274    private Type enterClass(String s) {
275        return enterClass(java_base, names.fromString(s)).type;
276    }
277
278    public void synthesizeEmptyInterfaceIfMissing(final Type type) {
279        final Completer completer = type.tsym.completer;
280        type.tsym.completer = new Completer() {
281            @Override
282            public void complete(Symbol sym) throws CompletionFailure {
283                try {
284                    completer.complete(sym);
285                } catch (CompletionFailure e) {
286                    sym.flags_field |= (PUBLIC | INTERFACE);
287                    ((ClassType) sym.type).supertype_field = objectType;
288                }
289            }
290
291            @Override
292            public boolean isTerminal() {
293                return completer.isTerminal();
294            }
295        };
296    }
297
298    public void synthesizeBoxTypeIfMissing(final Type type) {
299        ClassSymbol sym = enterClass(java_base, boxedName[type.getTag().ordinal()]);
300        final Completer completer = sym.completer;
301        sym.completer = new Completer() {
302            @Override
303            public void complete(Symbol sym) throws CompletionFailure {
304                try {
305                    completer.complete(sym);
306                } catch (CompletionFailure e) {
307                    sym.flags_field |= PUBLIC;
308                    ((ClassType) sym.type).supertype_field = objectType;
309                    MethodSymbol boxMethod =
310                        new MethodSymbol(PUBLIC | STATIC, names.valueOf,
311                                         new MethodType(List.of(type), sym.type,
312                                List.<Type>nil(), methodClass),
313                            sym);
314                    sym.members().enter(boxMethod);
315                    MethodSymbol unboxMethod =
316                        new MethodSymbol(PUBLIC,
317                            type.tsym.name.append(names.Value), // x.intValue()
318                            new MethodType(List.<Type>nil(), type,
319                                List.<Type>nil(), methodClass),
320                            sym);
321                    sym.members().enter(unboxMethod);
322                }
323            }
324
325            @Override
326            public boolean isTerminal() {
327                return completer.isTerminal();
328            }
329        };
330    }
331
332    // Enter a synthetic class that is used to mark classes in ct.sym.
333    // This class does not have a class file.
334    private Type enterSyntheticAnnotation(String name) {
335        // for now, leave the module null, to prevent problems from synthesizing the
336        // existence of a class in any specific module, including noModule
337        ClassType type = (ClassType)enterClass(java_base, names.fromString(name)).type;
338        ClassSymbol sym = (ClassSymbol)type.tsym;
339        sym.completer = Completer.NULL_COMPLETER;
340        sym.flags_field = PUBLIC|ACYCLIC|ANNOTATION|INTERFACE;
341        sym.erasure_field = type;
342        sym.members_field = WriteableScope.create(sym);
343        type.typarams_field = List.nil();
344        type.allparams_field = List.nil();
345        type.supertype_field = annotationType;
346        type.interfaces_field = List.nil();
347        return type;
348    }
349
350    /** Constructor; enters all predefined identifiers and operators
351     *  into symbol table.
352     */
353    protected Symtab(Context context) throws CompletionFailure {
354        context.put(symtabKey, this);
355
356        names = Names.instance(context);
357
358        // Create the unknown type
359        unknownType = new UnknownType();
360
361        messages = JavacMessages.instance(context);
362
363        rootPackage = new PackageSymbol(names.empty, null);
364
365        // create the basic builtin symbols
366        unnamedModule = new ModuleSymbol(names.empty, null) {
367                {
368                    directives = List.nil();
369                    exports = List.nil();
370                    provides = List.nil();
371                    uses = List.nil();
372                    ModuleSymbol java_base = enterModule(names.java_base);
373                    com.sun.tools.javac.code.Directive.RequiresDirective d =
374                            new com.sun.tools.javac.code.Directive.RequiresDirective(java_base,
375                                    EnumSet.of(com.sun.tools.javac.code.Directive.RequiresFlag.MANDATED));
376                    requires = List.of(d);
377                }
378                @Override
379                public String toString() {
380                    return messages.getLocalizedString("compiler.misc.unnamed.module");
381                }
382            };
383        addRootPackageFor(unnamedModule);
384        unnamedModule.enclosedPackages = unnamedModule.enclosedPackages.prepend(unnamedModule.unnamedPackage);
385
386        errModule = new ModuleSymbol(names.empty, null) { };
387        addRootPackageFor(errModule);
388
389        noModule = new ModuleSymbol(names.empty, null) {
390            @Override public boolean isNoModule() {
391                return true;
392            }
393        };
394        addRootPackageFor(noModule);
395
396        noSymbol = new TypeSymbol(NIL, 0, names.empty, Type.noType, rootPackage) {
397            @Override @DefinedBy(Api.LANGUAGE_MODEL)
398            public <R, P> R accept(ElementVisitor<R, P> v, P p) {
399                return v.visitUnknown(this, p);
400            }
401        };
402
403        // create the error symbols
404        errSymbol = new ClassSymbol(PUBLIC|STATIC|ACYCLIC, names.any, null, rootPackage);
405        errType = new ErrorType(errSymbol, Type.noType);
406
407        unknownSymbol = new ClassSymbol(PUBLIC|STATIC|ACYCLIC, names.fromString("<any?>"), null, rootPackage);
408        unknownSymbol.members_field = new Scope.ErrorScope(unknownSymbol);
409        unknownSymbol.type = unknownType;
410
411        // initialize builtin types
412        initType(byteType, "byte", "Byte");
413        initType(shortType, "short", "Short");
414        initType(charType, "char", "Character");
415        initType(intType, "int", "Integer");
416        initType(longType, "long", "Long");
417        initType(floatType, "float", "Float");
418        initType(doubleType, "double", "Double");
419        initType(booleanType, "boolean", "Boolean");
420        initType(voidType, "void", "Void");
421        initType(botType, "<nulltype>");
422        initType(errType, errSymbol);
423        initType(unknownType, unknownSymbol);
424
425        // the builtin class of all arrays
426        arrayClass = new ClassSymbol(PUBLIC|ACYCLIC, names.Array, noSymbol);
427
428        // VGJ
429        boundClass = new ClassSymbol(PUBLIC|ACYCLIC, names.Bound, noSymbol);
430        boundClass.members_field = new Scope.ErrorScope(boundClass);
431
432        // the builtin class of all methods
433        methodClass = new ClassSymbol(PUBLIC|ACYCLIC, names.Method, noSymbol);
434        methodClass.members_field = new Scope.ErrorScope(boundClass);
435
436        // Create class to hold all predefined constants and operations.
437        predefClass = new ClassSymbol(PUBLIC|ACYCLIC, names.empty, rootPackage);
438        WriteableScope scope = WriteableScope.create(predefClass);
439        predefClass.members_field = scope;
440
441        // Get the initial completer for Symbols from the ClassFinder
442        initialCompleter = ClassFinder.instance(context).getCompleter();
443        rootPackage.members_field = WriteableScope.create(rootPackage);
444
445        // Enter symbols for basic types.
446        scope.enter(byteType.tsym);
447        scope.enter(shortType.tsym);
448        scope.enter(charType.tsym);
449        scope.enter(intType.tsym);
450        scope.enter(longType.tsym);
451        scope.enter(floatType.tsym);
452        scope.enter(doubleType.tsym);
453        scope.enter(booleanType.tsym);
454        scope.enter(errType.tsym);
455
456        // Enter symbol for the errSymbol
457        scope.enter(errSymbol);
458
459        Source source = Source.instance(context);
460        Options options = Options.instance(context);
461        boolean noModules = options.isSet("noModules");
462        if (source.allowModules() && !noModules) {
463            java_base = enterModule(names.java_base);
464            //avoid completing java.base during the Symtab initialization
465            java_base.completer = Completer.NULL_COMPLETER;
466            java_base.visiblePackages = Collections.emptyMap();
467        } else {
468            java_base = noModule;
469        }
470
471        // Get the initial completer for ModuleSymbols from Modules
472        moduleCompleter = Modules.instance(context).getCompleter();
473
474        // Enter predefined classes. All are assumed to be in the java.base module.
475        objectType = enterClass("java.lang.Object");
476        objectsType = enterClass("java.util.Objects");
477        classType = enterClass("java.lang.Class");
478        stringType = enterClass("java.lang.String");
479        stringBufferType = enterClass("java.lang.StringBuffer");
480        stringBuilderType = enterClass("java.lang.StringBuilder");
481        cloneableType = enterClass("java.lang.Cloneable");
482        throwableType = enterClass("java.lang.Throwable");
483        serializableType = enterClass("java.io.Serializable");
484        serializedLambdaType = enterClass("java.lang.invoke.SerializedLambda");
485        varHandleType = enterClass("java.lang.invoke.VarHandle");
486        methodHandleType = enterClass("java.lang.invoke.MethodHandle");
487        methodHandleLookupType = enterClass("java.lang.invoke.MethodHandles$Lookup");
488        methodTypeType = enterClass("java.lang.invoke.MethodType");
489        errorType = enterClass("java.lang.Error");
490        illegalArgumentExceptionType = enterClass("java.lang.IllegalArgumentException");
491        interruptedExceptionType = enterClass("java.lang.InterruptedException");
492        exceptionType = enterClass("java.lang.Exception");
493        runtimeExceptionType = enterClass("java.lang.RuntimeException");
494        classNotFoundExceptionType = enterClass("java.lang.ClassNotFoundException");
495        noClassDefFoundErrorType = enterClass("java.lang.NoClassDefFoundError");
496        noSuchFieldErrorType = enterClass("java.lang.NoSuchFieldError");
497        assertionErrorType = enterClass("java.lang.AssertionError");
498        cloneNotSupportedExceptionType = enterClass("java.lang.CloneNotSupportedException");
499        annotationType = enterClass("java.lang.annotation.Annotation");
500        classLoaderType = enterClass("java.lang.ClassLoader");
501        enumSym = enterClass(java_base, names.java_lang_Enum);
502        enumFinalFinalize =
503            new MethodSymbol(PROTECTED|FINAL|HYPOTHETICAL,
504                             names.finalize,
505                             new MethodType(List.<Type>nil(), voidType,
506                                            List.<Type>nil(), methodClass),
507                             enumSym);
508        listType = enterClass("java.util.List");
509        collectionsType = enterClass("java.util.Collections");
510        comparableType = enterClass("java.lang.Comparable");
511        comparatorType = enterClass("java.util.Comparator");
512        arraysType = enterClass("java.util.Arrays");
513        iterableType = enterClass("java.lang.Iterable");
514        iteratorType = enterClass("java.util.Iterator");
515        annotationTargetType = enterClass("java.lang.annotation.Target");
516        overrideType = enterClass("java.lang.Override");
517        retentionType = enterClass("java.lang.annotation.Retention");
518        deprecatedType = enterClass("java.lang.Deprecated");
519        suppressWarningsType = enterClass("java.lang.SuppressWarnings");
520        supplierType = enterClass("java.util.function.Supplier");
521        inheritedType = enterClass("java.lang.annotation.Inherited");
522        repeatableType = enterClass("java.lang.annotation.Repeatable");
523        documentedType = enterClass("java.lang.annotation.Documented");
524        elementTypeType = enterClass("java.lang.annotation.ElementType");
525        systemType = enterClass("java.lang.System");
526        autoCloseableType = enterClass("java.lang.AutoCloseable");
527        autoCloseableClose = new MethodSymbol(PUBLIC,
528                             names.close,
529                             new MethodType(List.<Type>nil(), voidType,
530                                            List.of(exceptionType), methodClass),
531                             autoCloseableType.tsym);
532        trustMeType = enterClass("java.lang.SafeVarargs");
533        nativeHeaderType = enterClass("java.lang.annotation.Native");
534        lambdaMetafactory = enterClass("java.lang.invoke.LambdaMetafactory");
535        stringConcatFactory = enterClass("java.lang.invoke.StringConcatFactory");
536        functionalInterfaceType = enterClass("java.lang.FunctionalInterface");
537
538        synthesizeEmptyInterfaceIfMissing(autoCloseableType);
539        synthesizeEmptyInterfaceIfMissing(cloneableType);
540        synthesizeEmptyInterfaceIfMissing(serializableType);
541        synthesizeEmptyInterfaceIfMissing(lambdaMetafactory);
542        synthesizeEmptyInterfaceIfMissing(serializedLambdaType);
543        synthesizeEmptyInterfaceIfMissing(stringConcatFactory);
544        synthesizeBoxTypeIfMissing(doubleType);
545        synthesizeBoxTypeIfMissing(floatType);
546        synthesizeBoxTypeIfMissing(voidType);
547
548        // Enter a synthetic class that is used to mark internal
549        // proprietary classes in ct.sym.  This class does not have a
550        // class file.
551        proprietaryType = enterSyntheticAnnotation("sun.Proprietary+Annotation");
552
553        // Enter a synthetic class that is used to provide profile info for
554        // classes in ct.sym.  This class does not have a class file.
555        profileType = enterSyntheticAnnotation("jdk.Profile+Annotation");
556        MethodSymbol m = new MethodSymbol(PUBLIC | ABSTRACT, names.value, intType, profileType.tsym);
557        profileType.tsym.members().enter(m);
558
559        // Enter a class for arrays.
560        // The class implements java.lang.Cloneable and java.io.Serializable.
561        // It has a final length field and a clone method.
562        ClassType arrayClassType = (ClassType)arrayClass.type;
563        arrayClassType.supertype_field = objectType;
564        arrayClassType.interfaces_field = List.of(cloneableType, serializableType);
565        arrayClass.members_field = WriteableScope.create(arrayClass);
566        lengthVar = new VarSymbol(
567            PUBLIC | FINAL,
568            names.length,
569            intType,
570            arrayClass);
571        arrayClass.members().enter(lengthVar);
572        arrayCloneMethod = new MethodSymbol(
573            PUBLIC,
574            names.clone,
575            new MethodType(List.<Type>nil(), objectType,
576                           List.<Type>nil(), methodClass),
577            arrayClass);
578        arrayClass.members().enter(arrayCloneMethod);
579
580        if (java_base != noModule)
581            java_base.completer = sym -> moduleCompleter.complete(sym); //bootstrap issues
582
583    }
584
585    /** Define a new class given its name and owner.
586     */
587    public ClassSymbol defineClass(Name name, Symbol owner) {
588        ClassSymbol c = new ClassSymbol(0, name, owner);
589        c.completer = initialCompleter;
590        return c;
591    }
592
593    /** Create a new toplevel or member class symbol with given name
594     *  and owner and enter in `classes' unless already there.
595     */
596    public ClassSymbol enterClass(ModuleSymbol msym, Name name, TypeSymbol owner) {
597        Assert.checkNonNull(msym);
598        Name flatname = TypeSymbol.formFlatName(name, owner);
599        ClassSymbol c = getClass(msym, flatname);
600        if (c == null) {
601            c = defineClass(name, owner);
602            doEnterClass(msym, c);
603        } else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
604            // reassign fields of classes that might have been loaded with
605            // their flat names.
606            c.owner.members().remove(c);
607            c.name = name;
608            c.owner = owner;
609            c.fullname = ClassSymbol.formFullName(name, owner);
610        }
611        return c;
612    }
613
614    public ClassSymbol getClass(ModuleSymbol msym, Name flatName) {
615        Assert.checkNonNull(msym, () -> flatName.toString());
616        return classes.getOrDefault(flatName, Collections.emptyMap()).get(msym);
617    }
618
619    public PackageSymbol lookupPackage(ModuleSymbol msym, Name flatName) {
620        Assert.checkNonNull(msym);
621
622        if (flatName.isEmpty()) {
623            //unnamed packages only from the current module - visiblePackages contains *root* package, not unnamed package!
624            return msym.unnamedPackage;
625        }
626
627        if (msym == noModule) {
628            return enterPackage(msym, flatName);
629        }
630
631        msym.complete();
632
633        PackageSymbol pack;
634
635        pack = msym.visiblePackages.get(flatName);
636
637        if (pack != null)
638            return pack;
639
640        pack = getPackage(msym, flatName);
641
642        if (pack != null && pack.exists())
643            return pack;
644
645        boolean dependsOnUnnamed = msym.requires != null &&
646                                   msym.requires.stream()
647                                                .map(rd -> rd.module)
648                                                .anyMatch(mod -> mod == unnamedModule);
649
650        if (dependsOnUnnamed) {
651            //msyms depends on the unnamed module, for which we generally don't know
652            //the list of packages it "exports" ahead of time. So try to lookup the package in the
653            //current module, and in the unnamed module and see if it exists in one of them
654            PackageSymbol unnamedPack = getPackage(unnamedModule, flatName);
655
656            if (unnamedPack != null && unnamedPack.exists()) {
657                msym.visiblePackages.put(unnamedPack.fullname, unnamedPack);
658                return unnamedPack;
659            }
660
661            pack = enterPackage(msym, flatName);
662            pack.complete();
663            if (pack.exists())
664                return pack;
665
666            unnamedPack = enterPackage(unnamedModule, flatName);
667            unnamedPack.complete();
668            if (unnamedPack.exists()) {
669                msym.visiblePackages.put(unnamedPack.fullname, unnamedPack);
670                return unnamedPack;
671            }
672
673            return pack;
674        }
675
676        return enterPackage(msym, flatName);
677    }
678
679    private static final Map<ModuleSymbol, ClassSymbol> EMPTY = new HashMap<>();
680
681    public void removeClass(ModuleSymbol msym, Name flatName) {
682        classes.getOrDefault(flatName, EMPTY).remove(msym);
683    }
684
685    public Iterable<ClassSymbol> getAllClasses() {
686        return () -> Iterators.createCompoundIterator(classes.values(), v -> v.values().iterator());
687    }
688
689    private void doEnterClass(ModuleSymbol msym, ClassSymbol cs) {
690        classes.computeIfAbsent(cs.flatname, n -> new HashMap<>()).put(msym, cs);
691    }
692
693    /** Create a new member or toplevel class symbol with given flat name
694     *  and enter in `classes' unless already there.
695     */
696    public ClassSymbol enterClass(ModuleSymbol msym, Name flatname) {
697        Assert.checkNonNull(msym);
698        PackageSymbol ps = lookupPackage(msym, Convert.packagePart(flatname));
699        Assert.checkNonNull(ps);
700        Assert.checkNonNull(ps.modle);
701        ClassSymbol c = getClass(ps.modle, flatname);
702        if (c == null) {
703            c = defineClass(Convert.shortName(flatname), ps);
704            doEnterClass(ps.modle, c);
705            return c;
706        } else
707            return c;
708    }
709
710    /** Check to see if a package exists, given its fully qualified name.
711     */
712    public boolean packageExists(ModuleSymbol msym, Name fullname) {
713        Assert.checkNonNull(msym);
714        return lookupPackage(msym, fullname).exists();
715    }
716
717    /** Make a package, given its fully qualified name.
718     */
719    public PackageSymbol enterPackage(ModuleSymbol currModule, Name fullname) {
720        Assert.checkNonNull(currModule);
721        PackageSymbol p = getPackage(currModule, fullname);
722        if (p == null) {
723            Assert.check(!fullname.isEmpty(), () -> "rootPackage missing!; currModule: " + currModule);
724            p = new PackageSymbol(
725                    Convert.shortName(fullname),
726                    enterPackage(currModule, Convert.packagePart(fullname)));
727            p.completer = initialCompleter;
728            p.modle = currModule;
729            doEnterPackage(currModule, p);
730        }
731        return p;
732    }
733
734    private void doEnterPackage(ModuleSymbol msym, PackageSymbol pack) {
735        packages.computeIfAbsent(pack.fullname, n -> new HashMap<>()).put(msym, pack);
736        msym.enclosedPackages = msym.enclosedPackages.prepend(pack);
737    }
738
739    private void addRootPackageFor(ModuleSymbol module) {
740        doEnterPackage(module, rootPackage);
741        PackageSymbol unnamedPackage = new PackageSymbol(names.empty, rootPackage) {
742                @Override
743                public String toString() {
744                    return messages.getLocalizedString("compiler.misc.unnamed.package");
745                }
746            };
747        unnamedPackage.modle = module;
748        unnamedPackage.completer = sym -> initialCompleter.complete(sym);
749        module.unnamedPackage = unnamedPackage;
750    }
751
752    public PackageSymbol getPackage(ModuleSymbol module, Name fullname) {
753        return packages.getOrDefault(fullname, Collections.emptyMap()).get(module);
754    }
755
756    public ModuleSymbol enterModule(Name name) {
757        ModuleSymbol msym = modules.get(name);
758        if (msym == null) {
759            msym = ModuleSymbol.create(name, names.module_info);
760            addRootPackageFor(msym);
761            msym.completer = sym -> moduleCompleter.complete(sym); //bootstrap issues
762            modules.put(name, msym);
763        }
764        return msym;
765    }
766
767    public void enterModule(ModuleSymbol msym, Name name) {
768        Assert.checkNull(modules.get(name));
769        Assert.checkNull(msym.name);
770        msym.name = name;
771        addRootPackageFor(msym);
772        ClassSymbol info = msym.module_info;
773        info.fullname = msym.name.append('.', names.module_info);
774        info.flatname = info.fullname;
775        modules.put(name, msym);
776    }
777
778    public ModuleSymbol getModule(Name name) {
779        return modules.get(name);
780    }
781
782    //temporary:
783    public ModuleSymbol inferModule(Name packageName) {
784        if (packageName.isEmpty())
785            return java_base == noModule ? noModule : unnamedModule;//!
786
787        ModuleSymbol msym = null;
788        Map<ModuleSymbol,PackageSymbol> map = packages.get(packageName);
789        if (map == null)
790            return null;
791        for (Map.Entry<ModuleSymbol,PackageSymbol> e: map.entrySet()) {
792            if (!e.getValue().members().isEmpty()) {
793                if (msym == null) {
794                    msym = e.getKey();
795                } else {
796                    return null;
797                }
798            }
799        }
800        return msym;
801    }
802
803    public List<ModuleSymbol> listPackageModules(Name packageName) {
804        if (packageName.isEmpty())
805            return List.nil();
806
807        List<ModuleSymbol> result = List.nil();
808        Map<ModuleSymbol,PackageSymbol> map = packages.get(packageName);
809        if (map != null) {
810            for (Map.Entry<ModuleSymbol, PackageSymbol> e: map.entrySet()) {
811                if (!e.getValue().members().isEmpty()) {
812                    result = result.prepend(e.getKey());
813                }
814            }
815        }
816        return result;
817    }
818
819    public Collection<ModuleSymbol> getAllModules() {
820        return modules.values();
821    }
822}
823