Modules.java revision 4068:c07524646483
1/*
2 * Copyright (c) 2009, 2017, 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
27package com.sun.tools.javac.comp;
28
29import java.io.IOException;
30import java.util.Arrays;
31import java.util.Collection;
32import java.util.Collections;
33import java.util.EnumSet;
34import java.util.HashMap;
35import java.util.HashSet;
36import java.util.LinkedHashMap;
37import java.util.LinkedHashSet;
38import java.util.Map;
39import java.util.Set;
40import java.util.function.Consumer;
41import java.util.function.Predicate;
42import java.util.regex.Matcher;
43import java.util.regex.Pattern;
44import java.util.stream.Collectors;
45import java.util.stream.Stream;
46
47import javax.lang.model.SourceVersion;
48import javax.tools.JavaFileManager;
49import javax.tools.JavaFileManager.Location;
50import javax.tools.JavaFileObject;
51import javax.tools.JavaFileObject.Kind;
52import javax.tools.StandardLocation;
53
54import com.sun.source.tree.ModuleTree.ModuleKind;
55import com.sun.tools.javac.code.ClassFinder;
56import com.sun.tools.javac.code.DeferredLintHandler;
57import com.sun.tools.javac.code.Directive;
58import com.sun.tools.javac.code.Directive.ExportsDirective;
59import com.sun.tools.javac.code.Directive.ExportsFlag;
60import com.sun.tools.javac.code.Directive.OpensDirective;
61import com.sun.tools.javac.code.Directive.OpensFlag;
62import com.sun.tools.javac.code.Directive.RequiresDirective;
63import com.sun.tools.javac.code.Directive.RequiresFlag;
64import com.sun.tools.javac.code.Directive.UsesDirective;
65import com.sun.tools.javac.code.Flags;
66import com.sun.tools.javac.code.Lint.LintCategory;
67import com.sun.tools.javac.code.ModuleFinder;
68import com.sun.tools.javac.code.Source;
69import com.sun.tools.javac.code.Symbol;
70import com.sun.tools.javac.code.Symbol.ClassSymbol;
71import com.sun.tools.javac.code.Symbol.Completer;
72import com.sun.tools.javac.code.Symbol.CompletionFailure;
73import com.sun.tools.javac.code.Symbol.MethodSymbol;
74import com.sun.tools.javac.code.Symbol.ModuleFlags;
75import com.sun.tools.javac.code.Symbol.ModuleSymbol;
76import com.sun.tools.javac.code.Symbol.PackageSymbol;
77import com.sun.tools.javac.code.Symtab;
78import com.sun.tools.javac.code.Type;
79import com.sun.tools.javac.code.Types;
80import com.sun.tools.javac.jvm.ClassWriter;
81import com.sun.tools.javac.jvm.JNIWriter;
82import com.sun.tools.javac.main.Option;
83import com.sun.tools.javac.resources.CompilerProperties.Errors;
84import com.sun.tools.javac.resources.CompilerProperties.Warnings;
85import com.sun.tools.javac.tree.JCTree;
86import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
87import com.sun.tools.javac.tree.JCTree.JCDirective;
88import com.sun.tools.javac.tree.JCTree.JCExports;
89import com.sun.tools.javac.tree.JCTree.JCExpression;
90import com.sun.tools.javac.tree.JCTree.JCModuleDecl;
91import com.sun.tools.javac.tree.JCTree.JCOpens;
92import com.sun.tools.javac.tree.JCTree.JCProvides;
93import com.sun.tools.javac.tree.JCTree.JCRequires;
94import com.sun.tools.javac.tree.JCTree.JCUses;
95import com.sun.tools.javac.tree.JCTree.Tag;
96import com.sun.tools.javac.tree.TreeInfo;
97import com.sun.tools.javac.util.Abort;
98import com.sun.tools.javac.util.Assert;
99import com.sun.tools.javac.util.Context;
100import com.sun.tools.javac.util.JCDiagnostic;
101import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
102import com.sun.tools.javac.util.List;
103import com.sun.tools.javac.util.ListBuffer;
104import com.sun.tools.javac.util.Log;
105import com.sun.tools.javac.util.Name;
106import com.sun.tools.javac.util.Names;
107import com.sun.tools.javac.util.Options;
108import com.sun.tools.javac.util.Position;
109
110import static com.sun.tools.javac.code.Flags.ABSTRACT;
111import static com.sun.tools.javac.code.Flags.ENUM;
112import static com.sun.tools.javac.code.Flags.PUBLIC;
113import static com.sun.tools.javac.code.Flags.UNATTRIBUTED;
114import com.sun.tools.javac.code.Kinds;
115import static com.sun.tools.javac.code.Kinds.Kind.ERR;
116import static com.sun.tools.javac.code.Kinds.Kind.MDL;
117import static com.sun.tools.javac.code.Kinds.Kind.MTH;
118import com.sun.tools.javac.code.Symbol.ModuleResolutionFlags;
119import static com.sun.tools.javac.code.TypeTag.CLASS;
120
121/**
122 *  TODO: fill in
123 *
124 *  <p><b>This is NOT part of any supported API.
125 *  If you write code that depends on this, you do so at your own risk.
126 *  This code and its internal interfaces are subject to change or
127 *  deletion without notice.</b>
128 */
129public class Modules extends JCTree.Visitor {
130    private static final String ALL_SYSTEM = "ALL-SYSTEM";
131    private static final String ALL_MODULE_PATH = "ALL-MODULE-PATH";
132
133    private final Log log;
134    private final Names names;
135    private final Symtab syms;
136    private final Attr attr;
137    private final Check chk;
138    private final DeferredLintHandler deferredLintHandler;
139    private final TypeEnvs typeEnvs;
140    private final Types types;
141    private final JavaFileManager fileManager;
142    private final ModuleFinder moduleFinder;
143    private final Source source;
144    private final boolean allowModules;
145
146    public final boolean multiModuleMode;
147
148    private final String legacyModuleOverride;
149
150    private final Name java_se;
151    private final Name java_;
152
153    ModuleSymbol defaultModule;
154
155    private final String addExportsOpt;
156    private Map<ModuleSymbol, Set<ExportsDirective>> addExports;
157    private final String addReadsOpt;
158    private Map<ModuleSymbol, Set<RequiresDirective>> addReads;
159    private final String addModsOpt;
160    private final Set<String> extraAddMods = new HashSet<>();
161    private final String limitModsOpt;
162    private final Set<String> extraLimitMods = new HashSet<>();
163    private final String moduleVersionOpt;
164
165    private final boolean lintOptions;
166
167    private Set<ModuleSymbol> rootModules = null;
168    private final Set<ModuleSymbol> warnedMissing = new HashSet<>();
169
170    public PackageNameFinder findPackageInFile;
171
172    public static Modules instance(Context context) {
173        Modules instance = context.get(Modules.class);
174        if (instance == null)
175            instance = new Modules(context);
176        return instance;
177    }
178
179    protected Modules(Context context) {
180        context.put(Modules.class, this);
181        log = Log.instance(context);
182        names = Names.instance(context);
183        syms = Symtab.instance(context);
184        attr = Attr.instance(context);
185        chk = Check.instance(context);
186        deferredLintHandler = DeferredLintHandler.instance(context);
187        typeEnvs = TypeEnvs.instance(context);
188        moduleFinder = ModuleFinder.instance(context);
189        types = Types.instance(context);
190        fileManager = context.get(JavaFileManager.class);
191        source = Source.instance(context);
192        allowModules = source.allowModules();
193        Options options = Options.instance(context);
194
195        lintOptions = options.isUnset(Option.XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option);
196
197        legacyModuleOverride = options.get(Option.XMODULE);
198
199        multiModuleMode = fileManager.hasLocation(StandardLocation.MODULE_SOURCE_PATH);
200        ClassWriter classWriter = ClassWriter.instance(context);
201        classWriter.multiModuleMode = multiModuleMode;
202        JNIWriter jniWriter = JNIWriter.instance(context);
203        jniWriter.multiModuleMode = multiModuleMode;
204
205        java_se = names.fromString("java.se");
206        java_ = names.fromString("java.");
207
208        addExportsOpt = options.get(Option.ADD_EXPORTS);
209        addReadsOpt = options.get(Option.ADD_READS);
210        addModsOpt = options.get(Option.ADD_MODULES);
211        limitModsOpt = options.get(Option.LIMIT_MODULES);
212        moduleVersionOpt = options.get(Option.MODULE_VERSION);
213    }
214
215    int depth = -1;
216
217    public void addExtraAddModules(String... extras) {
218        extraAddMods.addAll(Arrays.asList(extras));
219    }
220
221    boolean inInitModules;
222    public void initModules(List<JCCompilationUnit> trees) {
223        Assert.check(!inInitModules);
224        try {
225            inInitModules = true;
226            Assert.checkNull(rootModules);
227            enter(trees, modules -> {
228                Assert.checkNull(rootModules);
229                Assert.checkNull(allModules);
230                this.rootModules = modules;
231                setupAllModules(); //initialize the module graph
232                Assert.checkNonNull(allModules);
233                inInitModules = false;
234            }, null);
235        } finally {
236            inInitModules = false;
237        }
238    }
239
240    public boolean enter(List<JCCompilationUnit> trees, ClassSymbol c) {
241        Assert.check(rootModules != null || inInitModules || !allowModules);
242        return enter(trees, modules -> {}, c);
243    }
244
245    private boolean enter(List<JCCompilationUnit> trees, Consumer<Set<ModuleSymbol>> init, ClassSymbol c) {
246        if (!allowModules) {
247            for (JCCompilationUnit tree: trees) {
248                tree.modle = syms.noModule;
249            }
250            defaultModule = syms.noModule;
251            return true;
252        }
253
254        int startErrors = log.nerrors;
255
256        depth++;
257        try {
258            // scan trees for module defs
259            Set<ModuleSymbol> roots = enterModules(trees, c);
260
261            setCompilationUnitModules(trees, roots, c);
262
263            init.accept(roots);
264
265            for (ModuleSymbol msym: roots) {
266                msym.complete();
267            }
268        } catch (CompletionFailure ex) {
269            log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, Position.NOPOS, "cant.access", ex.sym, ex.getDetailValue());
270            if (ex instanceof ClassFinder.BadClassFile) throw new Abort();
271        } finally {
272            depth--;
273        }
274
275        return (log.nerrors == startErrors);
276    }
277
278    public Completer getCompleter() {
279        return mainCompleter;
280    }
281
282    public ModuleSymbol getDefaultModule() {
283        return defaultModule;
284    }
285
286    public boolean modulesInitialized() {
287        return allModules != null;
288    }
289
290    private Set<ModuleSymbol> enterModules(List<JCCompilationUnit> trees, ClassSymbol c) {
291        Set<ModuleSymbol> modules = new LinkedHashSet<>();
292        for (JCCompilationUnit tree : trees) {
293            JavaFileObject prev = log.useSource(tree.sourcefile);
294            try {
295                enterModule(tree, c, modules);
296            } finally {
297                log.useSource(prev);
298            }
299        }
300        return modules;
301    }
302
303
304    private void enterModule(JCCompilationUnit toplevel, ClassSymbol c, Set<ModuleSymbol> modules) {
305        boolean isModuleInfo = toplevel.sourcefile.isNameCompatible("module-info", Kind.SOURCE);
306        boolean isModuleDecl = toplevel.getModuleDecl() != null;
307        if (isModuleDecl) {
308            JCModuleDecl decl = toplevel.getModuleDecl();
309            if (!isModuleInfo) {
310                log.error(decl.pos(), Errors.ModuleDeclSbInModuleInfoJava);
311            }
312            Name name = TreeInfo.fullName(decl.qualId);
313            ModuleSymbol sym;
314            if (c != null) {
315                sym = (ModuleSymbol) c.owner;
316                Assert.checkNonNull(sym.name);
317                Name treeName = TreeInfo.fullName(decl.qualId);
318                if (sym.name != treeName) {
319                    log.error(decl.pos(), Errors.ModuleNameMismatch(name, sym.name));
320                }
321            } else {
322                sym = syms.enterModule(name);
323                if (sym.module_info.sourcefile != null && sym.module_info.sourcefile != toplevel.sourcefile) {
324                    log.error(decl.pos(), Errors.DuplicateModule(sym));
325                    return;
326                }
327            }
328            sym.completer = getSourceCompleter(toplevel);
329            sym.module_info.sourcefile = toplevel.sourcefile;
330            decl.sym = sym;
331
332            if (multiModuleMode || modules.isEmpty()) {
333                modules.add(sym);
334            } else {
335                log.error(toplevel.pos(), Errors.TooManyModules);
336            }
337
338            Env<AttrContext> provisionalEnv = new Env<>(decl, null);
339
340            provisionalEnv.toplevel = toplevel;
341            typeEnvs.put(sym, provisionalEnv);
342        } else if (isModuleInfo) {
343            if (multiModuleMode) {
344                JCTree tree = toplevel.defs.isEmpty() ? toplevel : toplevel.defs.head;
345                log.error(tree.pos(), Errors.ExpectedModule);
346            }
347        }
348    }
349
350    private void setCompilationUnitModules(List<JCCompilationUnit> trees, Set<ModuleSymbol> rootModules, ClassSymbol c) {
351        // update the module for each compilation unit
352        if (multiModuleMode) {
353            checkNoAllModulePath();
354            for (JCCompilationUnit tree: trees) {
355                if (tree.defs.isEmpty()) {
356                    tree.modle = syms.unnamedModule;
357                    continue;
358                }
359
360                JavaFileObject prev = log.useSource(tree.sourcefile);
361                try {
362                    Location msplocn = getModuleLocation(tree);
363                    Location plocn = fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH) ?
364                            fileManager.getLocationForModule(StandardLocation.PATCH_MODULE_PATH,
365                                                             tree.sourcefile) :
366                            null;
367
368                    if (plocn != null) {
369                        Name name = names.fromString(fileManager.inferModuleName(plocn));
370                        ModuleSymbol msym = moduleFinder.findModule(name);
371                        tree.modle = msym;
372                        rootModules.add(msym);
373
374                        if (msplocn != null) {
375                            Name mspname = names.fromString(fileManager.inferModuleName(msplocn));
376                            if (name != mspname) {
377                                log.error(tree.pos(), Errors.FilePatchedAndMsp(name, mspname));
378                            }
379                        }
380                    } else if (msplocn != null) {
381                        if (tree.getModuleDecl() != null) {
382                            JavaFileObject canonical =
383                                    fileManager.getJavaFileForInput(msplocn, "module-info", Kind.SOURCE);
384                            if (canonical == null || !fileManager.isSameFile(canonical, tree.sourcefile)) {
385                                log.error(tree.pos(), Errors.ModuleNotFoundOnModuleSourcePath);
386                            }
387                        }
388                        Name name = names.fromString(fileManager.inferModuleName(msplocn));
389                        ModuleSymbol msym;
390                        JCModuleDecl decl = tree.getModuleDecl();
391                        if (decl != null) {
392                            msym = decl.sym;
393                            if (msym.name != name) {
394                                log.error(decl.qualId, Errors.ModuleNameMismatch(msym.name, name));
395                            }
396                        } else {
397                            if (tree.getPackage() == null) {
398                                log.error(tree.pos(), Errors.UnnamedPkgNotAllowedNamedModules);
399                            }
400                            msym = syms.enterModule(name);
401                        }
402                        if (msym.sourceLocation == null) {
403                            msym.sourceLocation = msplocn;
404                            if (fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH)) {
405                                msym.patchLocation = fileManager.getLocationForModule(
406                                        StandardLocation.PATCH_MODULE_PATH, msym.name.toString());
407                            }
408                            if (fileManager.hasLocation(StandardLocation.CLASS_OUTPUT)) {
409                                Location outputLocn = fileManager.getLocationForModule(
410                                        StandardLocation.CLASS_OUTPUT, msym.name.toString());
411                                if (msym.patchLocation == null) {
412                                    msym.classLocation = outputLocn;
413                                } else {
414                                    msym.patchOutputLocation = outputLocn;
415                                }
416                            }
417                        }
418                        tree.modle = msym;
419                        rootModules.add(msym);
420                    } else if (c != null && c.packge().modle == syms.unnamedModule) {
421                        tree.modle = syms.unnamedModule;
422                    } else {
423                        if (tree.getModuleDecl() != null) {
424                            log.error(tree.pos(), Errors.ModuleNotFoundOnModuleSourcePath);
425                        } else {
426                            log.error(tree.pos(), Errors.NotInModuleOnModuleSourcePath);
427                        }
428                        tree.modle = syms.errModule;
429                    }
430                } catch (IOException e) {
431                    throw new Error(e); // FIXME
432                } finally {
433                    log.useSource(prev);
434                }
435            }
436            if (syms.unnamedModule.sourceLocation == null) {
437                syms.unnamedModule.completer = getUnnamedModuleCompleter();
438                syms.unnamedModule.sourceLocation = StandardLocation.SOURCE_PATH;
439                syms.unnamedModule.classLocation = StandardLocation.CLASS_PATH;
440            }
441            defaultModule = syms.unnamedModule;
442        } else {
443            ModuleSymbol module = null;
444            if (defaultModule == null) {
445                String moduleOverride = singleModuleOverride(trees);
446                switch (rootModules.size()) {
447                    case 0:
448                        defaultModule = moduleFinder.findSingleModule();
449                        if (defaultModule == syms.unnamedModule) {
450                            if (moduleOverride != null) {
451                                checkNoAllModulePath();
452                                defaultModule = moduleFinder.findModule(names.fromString(moduleOverride));
453                                if (legacyModuleOverride != null) {
454                                    defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
455                                }
456                                defaultModule.patchOutputLocation = StandardLocation.CLASS_OUTPUT;
457                            } else {
458                                // Question: why not do findAllModules and initVisiblePackages here?
459                                // i.e. body of unnamedModuleCompleter
460                                defaultModule.completer = getUnnamedModuleCompleter();
461                                defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
462                                defaultModule.classLocation = StandardLocation.CLASS_PATH;
463                            }
464                        } else {
465                            checkNoAllModulePath();
466                            defaultModule.complete();
467                            // Question: why not do completeModule here?
468                            defaultModule.completer = sym -> completeModule((ModuleSymbol) sym);
469                            defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
470                        }
471                        rootModules.add(defaultModule);
472                        break;
473                    case 1:
474                        checkNoAllModulePath();
475                        defaultModule = rootModules.iterator().next();
476                        defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
477                        if (fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH)) {
478                            try {
479                                defaultModule.patchLocation = fileManager.getLocationForModule(
480                                        StandardLocation.PATCH_MODULE_PATH, defaultModule.name.toString());
481                            } catch (IOException ex) {
482                                throw new Error(ex);
483                            }
484                        }
485                        if (defaultModule.patchLocation == null) {
486                            defaultModule.classLocation = StandardLocation.CLASS_OUTPUT;
487                        } else {
488                            defaultModule.patchOutputLocation = StandardLocation.CLASS_OUTPUT;
489                        }
490                        break;
491                    default:
492                        Assert.error("too many modules");
493                }
494            } else if (rootModules.size() == 1) {
495                module = rootModules.iterator().next();
496                module.complete();
497                module.completer = sym -> completeModule((ModuleSymbol) sym);
498            } else {
499                Assert.check(rootModules.isEmpty());
500                String moduleOverride = singleModuleOverride(trees);
501                if (moduleOverride != null) {
502                    module = moduleFinder.findModule(names.fromString(moduleOverride));
503                } else {
504                    module = defaultModule;
505                }
506                rootModules.add(module);
507            }
508
509            if (defaultModule != syms.unnamedModule) {
510                syms.unnamedModule.completer = getUnnamedModuleCompleter();
511                syms.unnamedModule.classLocation = StandardLocation.CLASS_PATH;
512            }
513
514            if (module == null) {
515                module = defaultModule;
516            }
517
518            for (JCCompilationUnit tree: trees) {
519                tree.modle = module;
520            }
521        }
522    }
523
524    private String singleModuleOverride(List<JCCompilationUnit> trees) {
525        if (!fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH)) {
526            return legacyModuleOverride;
527        }
528
529        Set<String> override = new LinkedHashSet<>();
530        for (JCCompilationUnit tree : trees) {
531            JavaFileObject fo = tree.sourcefile;
532
533            try {
534                Location loc =
535                        fileManager.getLocationForModule(StandardLocation.PATCH_MODULE_PATH, fo);
536
537                if (loc != null) {
538                    override.add(fileManager.inferModuleName(loc));
539                }
540            } catch (IOException ex) {
541                throw new Error(ex);
542            }
543        }
544
545        switch (override.size()) {
546            case 0: return legacyModuleOverride;
547            case 1: return override.iterator().next();
548            default:
549                log.error(Errors.TooManyPatchedModules(override));
550                return null;
551        }
552    }
553
554    /**
555     * Determine the location for the module on the module source path
556     * or source output directory which contains a given CompilationUnit.
557     * If the source output directory is unset, the class output directory
558     * will be checked instead.
559     * {@code null} is returned if no such module can be found.
560     * @param tree the compilation unit tree
561     * @return the location for the enclosing module
562     * @throws IOException if there is a problem while searching for the module.
563     */
564    private Location getModuleLocation(JCCompilationUnit tree) throws IOException {
565        JavaFileObject fo = tree.sourcefile;
566
567        Location loc =
568                fileManager.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, fo);
569        if (loc == null) {
570            Location sourceOutput = fileManager.hasLocation(StandardLocation.SOURCE_OUTPUT) ?
571                    StandardLocation.SOURCE_OUTPUT : StandardLocation.CLASS_OUTPUT;
572            loc =
573                fileManager.getLocationForModule(sourceOutput, fo);
574        }
575        return loc;
576    }
577
578    private void checkNoAllModulePath() {
579        if (addModsOpt != null && Arrays.asList(addModsOpt.split(",")).contains(ALL_MODULE_PATH)) {
580            log.error(Errors.AddmodsAllModulePathInvalid);
581        }
582    }
583
584    private final Completer mainCompleter = new Completer() {
585        @Override
586        public void complete(Symbol sym) throws CompletionFailure {
587            ModuleSymbol msym = moduleFinder.findModule((ModuleSymbol) sym);
588
589            if (msym.kind == ERR) {
590                //make sure the module is initialized:
591                msym.directives = List.nil();
592                msym.exports = List.nil();
593                msym.provides = List.nil();
594                msym.requires = List.nil();
595                msym.uses = List.nil();
596            } else if ((msym.flags_field & Flags.AUTOMATIC_MODULE) != 0) {
597                setupAutomaticModule(msym);
598            } else {
599                msym.module_info.complete();
600            }
601
602            // If module-info comes from a .java file, the underlying
603            // call of classFinder.fillIn will have called through the
604            // source completer, to Enter, and then to Modules.enter,
605            // which will call completeModule.
606            // But, if module-info comes from a .class file, the underlying
607            // call of classFinder.fillIn will just call ClassReader to read
608            // the .class file, and so we call completeModule here.
609            if (msym.module_info.classfile == null || msym.module_info.classfile.getKind() == Kind.CLASS) {
610                completeModule(msym);
611            }
612        }
613
614        @Override
615        public String toString() {
616            return "mainCompleter";
617        }
618    };
619
620    private void setupAutomaticModule(ModuleSymbol msym) throws CompletionFailure {
621        try {
622            ListBuffer<Directive> directives = new ListBuffer<>();
623            ListBuffer<ExportsDirective> exports = new ListBuffer<>();
624            Set<String> seenPackages = new HashSet<>();
625
626            for (JavaFileObject clazz : fileManager.list(msym.classLocation, "", EnumSet.of(Kind.CLASS), true)) {
627                String binName = fileManager.inferBinaryName(msym.classLocation, clazz);
628                String pack = binName.lastIndexOf('.') != (-1) ? binName.substring(0, binName.lastIndexOf('.')) : ""; //unnamed package????
629                if (seenPackages.add(pack)) {
630                    ExportsDirective d = new ExportsDirective(syms.enterPackage(msym, names.fromString(pack)), null);
631                    //TODO: opens?
632                    directives.add(d);
633                    exports.add(d);
634                }
635            }
636
637            msym.exports = exports.toList();
638            msym.provides = List.nil();
639            msym.requires = List.nil();
640            msym.uses = List.nil();
641            msym.directives = directives.toList();
642            msym.flags_field |= Flags.ACYCLIC;
643        } catch (IOException ex) {
644            throw new IllegalStateException(ex);
645        }
646    }
647
648    private void completeAutomaticModule(ModuleSymbol msym) throws CompletionFailure {
649        ListBuffer<Directive> directives = new ListBuffer<>();
650
651        directives.addAll(msym.directives);
652
653        ListBuffer<RequiresDirective> requires = new ListBuffer<>();
654
655        for (ModuleSymbol ms : allModules()) {
656            if (ms == syms.unnamedModule || ms == msym)
657                continue;
658            Set<RequiresFlag> flags = (ms.flags_field & Flags.AUTOMATIC_MODULE) != 0 ?
659                    EnumSet.of(RequiresFlag.TRANSITIVE) : EnumSet.noneOf(RequiresFlag.class);
660            RequiresDirective d = new RequiresDirective(ms, flags);
661            directives.add(d);
662            requires.add(d);
663        }
664
665        RequiresDirective requiresUnnamed = new RequiresDirective(syms.unnamedModule);
666        directives.add(requiresUnnamed);
667        requires.add(requiresUnnamed);
668
669        msym.requires = requires.toList();
670        msym.directives = directives.toList();
671    }
672
673    private Completer getSourceCompleter(JCCompilationUnit tree) {
674        return new Completer() {
675            @Override
676            public void complete(Symbol sym) throws CompletionFailure {
677                ModuleSymbol msym = (ModuleSymbol) sym;
678                msym.flags_field |= UNATTRIBUTED;
679                ModuleVisitor v = new ModuleVisitor();
680                JavaFileObject prev = log.useSource(tree.sourcefile);
681                JCModuleDecl moduleDecl = tree.getModuleDecl();
682                DiagnosticPosition prevLintPos = deferredLintHandler.setPos(moduleDecl.pos());
683
684                try {
685                    moduleDecl.accept(v);
686                    completeModule(msym);
687                    checkCyclicDependencies(moduleDecl);
688                } finally {
689                    log.useSource(prev);
690                    deferredLintHandler.setPos(prevLintPos);
691                    msym.flags_field &= ~UNATTRIBUTED;
692                }
693            }
694
695            @Override
696            public String toString() {
697                return "SourceCompleter: " + tree.sourcefile.getName();
698            }
699
700        };
701    }
702
703    public boolean isRootModule(ModuleSymbol module) {
704        Assert.checkNonNull(rootModules);
705        return rootModules.contains(module);
706    }
707
708    public Set<ModuleSymbol> getRootModules() {
709        Assert.checkNonNull(rootModules);
710        return rootModules;
711    }
712
713    class ModuleVisitor extends JCTree.Visitor {
714        private ModuleSymbol sym;
715        private final Set<ModuleSymbol> allRequires = new HashSet<>();
716        private final Map<PackageSymbol,List<ExportsDirective>> allExports = new HashMap<>();
717        private final Map<PackageSymbol,List<OpensDirective>> allOpens = new HashMap<>();
718
719        @Override
720        public void visitModuleDef(JCModuleDecl tree) {
721            sym = Assert.checkNonNull(tree.sym);
722
723            if (tree.getModuleType() == ModuleKind.OPEN) {
724                sym.flags.add(ModuleFlags.OPEN);
725            }
726            sym.flags_field |= (tree.mods.flags & Flags.DEPRECATED);
727
728            sym.requires = List.nil();
729            sym.exports = List.nil();
730            sym.opens = List.nil();
731            tree.directives.forEach(t -> t.accept(this));
732            sym.requires = sym.requires.reverse();
733            sym.exports = sym.exports.reverse();
734            sym.opens = sym.opens.reverse();
735            ensureJavaBase();
736        }
737
738        @Override
739        public void visitRequires(JCRequires tree) {
740            ModuleSymbol msym = lookupModule(tree.moduleName);
741            if (msym.kind != MDL) {
742                log.error(tree.moduleName.pos(), Errors.ModuleNotFound(msym));
743                warnedMissing.add(msym);
744            } else if (allRequires.contains(msym)) {
745                log.error(tree.moduleName.pos(), Errors.DuplicateRequires(msym));
746            } else {
747                allRequires.add(msym);
748                Set<RequiresFlag> flags = EnumSet.noneOf(RequiresFlag.class);
749                if (tree.isTransitive)
750                    flags.add(RequiresFlag.TRANSITIVE);
751                if (tree.isStaticPhase)
752                    flags.add(RequiresFlag.STATIC_PHASE);
753                RequiresDirective d = new RequiresDirective(msym, flags);
754                tree.directive = d;
755                sym.requires = sym.requires.prepend(d);
756            }
757        }
758
759        @Override
760        public void visitExports(JCExports tree) {
761            Name name = TreeInfo.fullName(tree.qualid);
762            PackageSymbol packge = syms.enterPackage(sym, name);
763            attr.setPackageSymbols(tree.qualid, packge);
764
765            List<ExportsDirective> exportsForPackage = allExports.computeIfAbsent(packge, p -> List.nil());
766            for (ExportsDirective d : exportsForPackage) {
767                reportExportsConflict(tree, packge);
768            }
769
770            List<ModuleSymbol> toModules = null;
771            if (tree.moduleNames != null) {
772                Set<ModuleSymbol> to = new LinkedHashSet<>();
773                for (JCExpression n: tree.moduleNames) {
774                    ModuleSymbol msym = lookupModule(n);
775                    chk.checkModuleExists(n.pos(), msym);
776                    for (ExportsDirective d : exportsForPackage) {
777                        checkDuplicateExportsToModule(n, msym, d);
778                    }
779                    if (!to.add(msym)) {
780                        reportExportsConflictToModule(n, msym);
781                    }
782                }
783                toModules = List.from(to);
784            }
785
786            if (toModules == null || !toModules.isEmpty()) {
787                Set<ExportsFlag> flags = EnumSet.noneOf(ExportsFlag.class);
788                ExportsDirective d = new ExportsDirective(packge, toModules, flags);
789                sym.exports = sym.exports.prepend(d);
790                tree.directive = d;
791
792                allExports.put(packge, exportsForPackage.prepend(d));
793            }
794        }
795
796        private void reportExportsConflict(JCExports tree, PackageSymbol packge) {
797            log.error(tree.qualid.pos(), Errors.ConflictingExports(packge));
798        }
799
800        private void checkDuplicateExportsToModule(JCExpression name, ModuleSymbol msym,
801                ExportsDirective d) {
802            if (d.modules != null) {
803                for (ModuleSymbol other : d.modules) {
804                    if (msym == other) {
805                        reportExportsConflictToModule(name, msym);
806                    }
807                }
808            }
809        }
810
811        private void reportExportsConflictToModule(JCExpression name, ModuleSymbol msym) {
812            log.error(name.pos(), Errors.ConflictingExportsToModule(msym));
813        }
814
815        @Override
816        public void visitOpens(JCOpens tree) {
817            Name name = TreeInfo.fullName(tree.qualid);
818            PackageSymbol packge = syms.enterPackage(sym, name);
819            attr.setPackageSymbols(tree.qualid, packge);
820
821            if (sym.flags.contains(ModuleFlags.OPEN)) {
822                log.error(tree.pos(), Errors.NoOpensUnlessStrong);
823            }
824            List<OpensDirective> opensForPackage = allOpens.computeIfAbsent(packge, p -> List.nil());
825            for (OpensDirective d : opensForPackage) {
826                reportOpensConflict(tree, packge);
827            }
828
829            List<ModuleSymbol> toModules = null;
830            if (tree.moduleNames != null) {
831                Set<ModuleSymbol> to = new LinkedHashSet<>();
832                for (JCExpression n: tree.moduleNames) {
833                    ModuleSymbol msym = lookupModule(n);
834                    chk.checkModuleExists(n.pos(), msym);
835                    for (OpensDirective d : opensForPackage) {
836                        checkDuplicateOpensToModule(n, msym, d);
837                    }
838                    if (!to.add(msym)) {
839                        reportOpensConflictToModule(n, msym);
840                    }
841                }
842                toModules = List.from(to);
843            }
844
845            if (toModules == null || !toModules.isEmpty()) {
846                Set<OpensFlag> flags = EnumSet.noneOf(OpensFlag.class);
847                OpensDirective d = new OpensDirective(packge, toModules, flags);
848                sym.opens = sym.opens.prepend(d);
849                tree.directive = d;
850
851                allOpens.put(packge, opensForPackage.prepend(d));
852            }
853        }
854
855        private void reportOpensConflict(JCOpens tree, PackageSymbol packge) {
856            log.error(tree.qualid.pos(), Errors.ConflictingOpens(packge));
857        }
858
859        private void checkDuplicateOpensToModule(JCExpression name, ModuleSymbol msym,
860                OpensDirective d) {
861            if (d.modules != null) {
862                for (ModuleSymbol other : d.modules) {
863                    if (msym == other) {
864                        reportOpensConflictToModule(name, msym);
865                    }
866                }
867            }
868        }
869
870        private void reportOpensConflictToModule(JCExpression name, ModuleSymbol msym) {
871            log.error(name.pos(), Errors.ConflictingOpensToModule(msym));
872        }
873
874        @Override
875        public void visitProvides(JCProvides tree) { }
876
877        @Override
878        public void visitUses(JCUses tree) { }
879
880        private void ensureJavaBase() {
881            if (sym.name == names.java_base)
882                return;
883
884            for (RequiresDirective d: sym.requires) {
885                if (d.module.name == names.java_base)
886                    return;
887            }
888
889            ModuleSymbol java_base = syms.enterModule(names.java_base);
890            Directive.RequiresDirective d =
891                    new Directive.RequiresDirective(java_base,
892                            EnumSet.of(Directive.RequiresFlag.MANDATED));
893            sym.requires = sym.requires.prepend(d);
894        }
895
896        private ModuleSymbol lookupModule(JCExpression moduleName) {
897            Name name = TreeInfo.fullName(moduleName);
898            ModuleSymbol msym = moduleFinder.findModule(name);
899            TreeInfo.setSymbol(moduleName, msym);
900            return msym;
901        }
902    }
903
904    public Completer getUsesProvidesCompleter() {
905        return sym -> {
906            ModuleSymbol msym = (ModuleSymbol) sym;
907
908            msym.complete();
909
910            Env<AttrContext> env = typeEnvs.get(msym);
911            UsesProvidesVisitor v = new UsesProvidesVisitor(msym, env);
912            JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
913            JCModuleDecl decl = env.toplevel.getModuleDecl();
914            DiagnosticPosition prevLintPos = deferredLintHandler.setPos(decl.pos());
915
916            try {
917                decl.accept(v);
918            } finally {
919                log.useSource(prev);
920                deferredLintHandler.setPos(prevLintPos);
921            }
922        };
923    }
924
925    class UsesProvidesVisitor extends JCTree.Visitor {
926        private final ModuleSymbol msym;
927        private final Env<AttrContext> env;
928
929        private final Set<ClassSymbol> allUses = new HashSet<>();
930        private final Map<ClassSymbol, Set<ClassSymbol>> allProvides = new HashMap<>();
931
932        public UsesProvidesVisitor(ModuleSymbol msym, Env<AttrContext> env) {
933            this.msym = msym;
934            this.env = env;
935        }
936
937        @Override @SuppressWarnings("unchecked")
938        public void visitModuleDef(JCModuleDecl tree) {
939            msym.directives = List.nil();
940            msym.provides = List.nil();
941            msym.uses = List.nil();
942            tree.directives.forEach(t -> t.accept(this));
943            msym.directives = msym.directives.reverse();
944            msym.provides = msym.provides.reverse();
945            msym.uses = msym.uses.reverse();
946
947            if (msym.requires.nonEmpty() && msym.requires.head.flags.contains(RequiresFlag.MANDATED))
948                msym.directives = msym.directives.prepend(msym.requires.head);
949
950            msym.directives = msym.directives.appendList(List.from(addReads.getOrDefault(msym, Collections.emptySet())));
951
952            checkForCorrectness();
953        }
954
955        @Override
956        public void visitExports(JCExports tree) {
957            Iterable<Symbol> packageContent = tree.directive.packge.members().getSymbols();
958            List<JavaFileObject> filesToCheck = List.nil();
959            boolean packageNotEmpty = false;
960            for (Symbol sym : packageContent) {
961                if (sym.kind != Kinds.Kind.TYP)
962                    continue;
963                ClassSymbol csym = (ClassSymbol) sym;
964                if (sym.completer.isTerminal() ||
965                    csym.classfile.getKind() == Kind.CLASS) {
966                    packageNotEmpty = true;
967                    filesToCheck = List.nil();
968                    break;
969                }
970                if (csym.classfile.getKind() == Kind.SOURCE) {
971                    filesToCheck = filesToCheck.prepend(csym.classfile);
972                }
973            }
974            for (JavaFileObject jfo : filesToCheck) {
975                if (findPackageInFile.findPackageNameOf(jfo) == tree.directive.packge.fullname) {
976                    packageNotEmpty = true;
977                    break;
978                }
979            }
980            if (!packageNotEmpty) {
981                log.error(tree.qualid.pos(), Errors.PackageEmptyOrNotFound(tree.directive.packge));
982            }
983            msym.directives = msym.directives.prepend(tree.directive);
984        }
985
986        @Override
987        public void visitOpens(JCOpens tree) {
988            chk.checkPackageExistsForOpens(tree.qualid, tree.directive.packge);
989            msym.directives = msym.directives.prepend(tree.directive);
990        }
991
992        MethodSymbol noArgsConstructor(ClassSymbol tsym) {
993            for (Symbol sym : tsym.members().getSymbolsByName(names.init)) {
994                MethodSymbol mSym = (MethodSymbol)sym;
995                if (mSym.params().isEmpty()) {
996                    return mSym;
997                }
998            }
999            return null;
1000        }
1001
1002        MethodSymbol factoryMethod(ClassSymbol tsym) {
1003            for (Symbol sym : tsym.members().getSymbolsByName(names.provider, sym -> sym.kind == MTH)) {
1004                MethodSymbol mSym = (MethodSymbol)sym;
1005                if (mSym.isStatic() && (mSym.flags() & Flags.PUBLIC) != 0 && mSym.params().isEmpty()) {
1006                    return mSym;
1007                }
1008            }
1009            return null;
1010        }
1011
1012        Map<Directive.ProvidesDirective, JCProvides> directiveToTreeMap = new HashMap<>();
1013
1014        @Override
1015        public void visitProvides(JCProvides tree) {
1016            Type st = attr.attribType(tree.serviceName, env, syms.objectType);
1017            ClassSymbol service = (ClassSymbol) st.tsym;
1018            if (allProvides.containsKey(service)) {
1019                log.error(tree.serviceName.pos(), Errors.RepeatedProvidesForService(service));
1020            }
1021            ListBuffer<ClassSymbol> impls = new ListBuffer<>();
1022            for (JCExpression implName : tree.implNames) {
1023                Type it;
1024                boolean prevVisitingServiceImplementation = env.info.visitingServiceImplementation;
1025                try {
1026                    env.info.visitingServiceImplementation = true;
1027                    it = attr.attribType(implName, env, syms.objectType);
1028                } finally {
1029                    env.info.visitingServiceImplementation = prevVisitingServiceImplementation;
1030                }
1031                ClassSymbol impl = (ClassSymbol) it.tsym;
1032                if ((impl.flags_field & PUBLIC) == 0) {
1033                    log.error(implName.pos(), Errors.NotDefPublic(impl, impl.location()));
1034                }
1035                //find provider factory:
1036                MethodSymbol factory = factoryMethod(impl);
1037                if (factory != null) {
1038                    Type returnType = factory.type.getReturnType();
1039                    if (!types.isSubtype(returnType, st)) {
1040                        log.error(implName.pos(), Errors.ServiceImplementationProviderReturnMustBeSubtypeOfServiceInterface);
1041                    }
1042                } else {
1043                    if (!types.isSubtype(it, st)) {
1044                        log.error(implName.pos(), Errors.ServiceImplementationMustBeSubtypeOfServiceInterface);
1045                    } else if ((impl.flags() & ABSTRACT) != 0) {
1046                        log.error(implName.pos(), Errors.ServiceImplementationIsAbstract(impl));
1047                    } else if (impl.isInner()) {
1048                        log.error(implName.pos(), Errors.ServiceImplementationIsInner(impl));
1049                    } else {
1050                        MethodSymbol constr = noArgsConstructor(impl);
1051                        if (constr == null) {
1052                            log.error(implName.pos(), Errors.ServiceImplementationDoesntHaveANoArgsConstructor(impl));
1053                        } else if ((constr.flags() & PUBLIC) == 0) {
1054                            log.error(implName.pos(), Errors.ServiceImplementationNoArgsConstructorNotPublic(impl));
1055                        }
1056                    }
1057                }
1058                if (it.hasTag(CLASS)) {
1059                    if (allProvides.computeIfAbsent(service, s -> new HashSet<>()).add(impl)) {
1060                        impls.append(impl);
1061                    } else {
1062                        log.error(implName.pos(), Errors.DuplicateProvides(service, impl));
1063                    }
1064                }
1065            }
1066            if (st.hasTag(CLASS) && !impls.isEmpty()) {
1067                Directive.ProvidesDirective d = new Directive.ProvidesDirective(service, impls.toList());
1068                msym.provides = msym.provides.prepend(d);
1069                msym.directives = msym.directives.prepend(d);
1070                directiveToTreeMap.put(d, tree);
1071            }
1072        }
1073
1074        @Override
1075        public void visitRequires(JCRequires tree) {
1076            if (tree.directive != null && allModules().contains(tree.directive.module)) {
1077                chk.checkDeprecated(tree.moduleName.pos(), msym, tree.directive.module);
1078                msym.directives = msym.directives.prepend(tree.directive);
1079            }
1080        }
1081
1082        @Override
1083        public void visitUses(JCUses tree) {
1084            Type st = attr.attribType(tree.qualid, env, syms.objectType);
1085            Symbol sym = TreeInfo.symbol(tree.qualid);
1086            if ((sym.flags() & ENUM) != 0) {
1087                log.error(tree.qualid.pos(), Errors.ServiceDefinitionIsEnum(st.tsym));
1088            } else if (st.hasTag(CLASS)) {
1089                ClassSymbol service = (ClassSymbol) st.tsym;
1090                if (allUses.add(service)) {
1091                    Directive.UsesDirective d = new Directive.UsesDirective(service);
1092                    msym.uses = msym.uses.prepend(d);
1093                    msym.directives = msym.directives.prepend(d);
1094                } else {
1095                    log.error(tree.pos(), Errors.DuplicateUses(service));
1096                }
1097            }
1098        }
1099
1100        private void checkForCorrectness() {
1101            for (Directive.ProvidesDirective provides : msym.provides) {
1102                JCProvides tree = directiveToTreeMap.get(provides);
1103                for (ClassSymbol impl : provides.impls) {
1104                    /* The implementation must be defined in the same module as the provides directive
1105                     * (else, error)
1106                     */
1107                    PackageSymbol implementationDefiningPackage = impl.packge();
1108                    if (implementationDefiningPackage.modle != msym) {
1109                        // TODO: should use tree for the implentation name, not the entire provides tree
1110                        // TODO: should improve error message to identify the implementation type
1111                        log.error(tree.pos(), Errors.ServiceImplementationNotInRightModule(implementationDefiningPackage.modle));
1112                    }
1113
1114                    /* There is no inherent requirement that module that provides a service should actually
1115                     * use it itself. However, it is a pointless declaration if the service package is not
1116                     * exported and there is no uses for the service.
1117                     */
1118                    PackageSymbol interfaceDeclaringPackage = provides.service.packge();
1119                    boolean isInterfaceDeclaredInCurrentModule = interfaceDeclaringPackage.modle == msym;
1120                    boolean isInterfaceExportedFromAReadableModule =
1121                            msym.visiblePackages.get(interfaceDeclaringPackage.fullname) == interfaceDeclaringPackage;
1122                    if (isInterfaceDeclaredInCurrentModule && !isInterfaceExportedFromAReadableModule) {
1123                        // ok the interface is declared in this module. Let's check if it's exported
1124                        boolean warn = true;
1125                        for (ExportsDirective export : msym.exports) {
1126                            if (interfaceDeclaringPackage == export.packge) {
1127                                warn = false;
1128                                break;
1129                            }
1130                        }
1131                        if (warn) {
1132                            for (UsesDirective uses : msym.uses) {
1133                                if (provides.service == uses.service) {
1134                                    warn = false;
1135                                    break;
1136                                }
1137                            }
1138                        }
1139                        if (warn) {
1140                            log.warning(tree.pos(), Warnings.ServiceProvidedButNotExportedOrUsed(provides.service));
1141                        }
1142                    }
1143                }
1144            }
1145        }
1146    }
1147
1148    private Set<ModuleSymbol> allModules;
1149
1150    public Set<ModuleSymbol> allModules() {
1151        Assert.checkNonNull(allModules);
1152        return allModules;
1153    }
1154
1155    private void setupAllModules() {
1156        Assert.checkNonNull(rootModules);
1157        Assert.checkNull(allModules);
1158
1159        Set<ModuleSymbol> observable;
1160
1161        if (limitModsOpt == null && extraLimitMods.isEmpty()) {
1162            observable = null;
1163        } else {
1164            Set<ModuleSymbol> limitMods = new HashSet<>();
1165            if (limitModsOpt != null) {
1166                for (String limit : limitModsOpt.split(",")) {
1167                    if (!isValidName(limit))
1168                        continue;
1169                    limitMods.add(syms.enterModule(names.fromString(limit)));
1170                }
1171            }
1172            for (String limit : extraLimitMods) {
1173                limitMods.add(syms.enterModule(names.fromString(limit)));
1174            }
1175            observable = computeTransitiveClosure(limitMods, null);
1176            observable.addAll(rootModules);
1177            if (lintOptions) {
1178                for (ModuleSymbol msym : limitMods) {
1179                    if (!observable.contains(msym)) {
1180                        log.warning(LintCategory.OPTIONS,
1181                                Warnings.ModuleForOptionNotFound(Option.LIMIT_MODULES, msym));
1182                    }
1183                }
1184            }
1185        }
1186
1187        Predicate<ModuleSymbol> observablePred = sym ->
1188             (observable == null) ? (moduleFinder.findModule(sym).kind != ERR) : observable.contains(sym);
1189        Predicate<ModuleSymbol> systemModulePred = sym -> (sym.flags() & Flags.SYSTEM_MODULE) != 0;
1190        Predicate<ModuleSymbol> noIncubatorPred = sym -> {
1191            sym.complete();
1192            return !sym.resolutionFlags.contains(ModuleResolutionFlags.DO_NOT_RESOLVE_BY_DEFAULT);
1193        };
1194        Set<ModuleSymbol> enabledRoot = new LinkedHashSet<>();
1195
1196        if (rootModules.contains(syms.unnamedModule)) {
1197            ModuleSymbol javaSE = syms.getModule(java_se);
1198            Predicate<ModuleSymbol> jdkModulePred;
1199
1200            if (javaSE != null && (observable == null || observable.contains(javaSE))) {
1201                jdkModulePred = sym -> {
1202                    sym.complete();
1203                    return   !sym.name.startsWith(java_)
1204                           && sym.exports.stream().anyMatch(e -> e.modules == null);
1205                };
1206                enabledRoot.add(javaSE);
1207            } else {
1208                jdkModulePred = sym -> true;
1209            }
1210
1211            for (ModuleSymbol sym : new HashSet<>(syms.getAllModules())) {
1212                if (systemModulePred.test(sym) && observablePred.test(sym) && jdkModulePred.test(sym) && noIncubatorPred.test(sym)) {
1213                    enabledRoot.add(sym);
1214                }
1215            }
1216        }
1217
1218        enabledRoot.addAll(rootModules);
1219
1220        if (addModsOpt != null || !extraAddMods.isEmpty()) {
1221            Set<String> fullAddMods = new HashSet<>();
1222            fullAddMods.addAll(extraAddMods);
1223
1224            if (addModsOpt != null) {
1225                fullAddMods.addAll(Arrays.asList(addModsOpt.split(",")));
1226            }
1227
1228            for (String added : fullAddMods) {
1229                Stream<ModuleSymbol> modules;
1230                switch (added) {
1231                    case ALL_SYSTEM:
1232                        modules = new HashSet<>(syms.getAllModules())
1233                                .stream()
1234                                .filter(systemModulePred.and(observablePred).and(noIncubatorPred));
1235                        break;
1236                    case ALL_MODULE_PATH:
1237                        modules = new HashSet<>(syms.getAllModules())
1238                                .stream()
1239                                .filter(systemModulePred.negate().and(observablePred));
1240                        break;
1241                    default:
1242                        if (!isValidName(added))
1243                            continue;
1244                        modules = Stream.of(syms.enterModule(names.fromString(added)));
1245                        break;
1246                }
1247                modules.forEach(sym -> {
1248                    enabledRoot.add(sym);
1249                    if (observable != null)
1250                        observable.add(sym);
1251                });
1252            }
1253        }
1254
1255        Set<ModuleSymbol> result = computeTransitiveClosure(enabledRoot, observable);
1256
1257        result.add(syms.unnamedModule);
1258
1259        String incubatingModules = result.stream()
1260                .filter(msym -> msym.resolutionFlags.contains(ModuleResolutionFlags.WARN_INCUBATING))
1261                .map(msym -> msym.name.toString())
1262                .collect(Collectors.joining(","));
1263
1264        if (!incubatingModules.isEmpty()) {
1265            log.warning(Warnings.IncubatingModules(incubatingModules));
1266        }
1267
1268        allModules = result;
1269
1270        //add module versions from options, if any:
1271        if (moduleVersionOpt != null) {
1272            Name version = names.fromString(moduleVersionOpt);
1273            rootModules.forEach(m -> m.version = version);
1274        }
1275    }
1276
1277    public boolean isInModuleGraph(ModuleSymbol msym) {
1278        return allModules == null || allModules.contains(msym);
1279    }
1280
1281    private Set<ModuleSymbol> computeTransitiveClosure(Set<? extends ModuleSymbol> base, Set<ModuleSymbol> observable) {
1282        List<ModuleSymbol> primaryTodo = List.nil();
1283        List<ModuleSymbol> secondaryTodo = List.nil();
1284
1285        for (ModuleSymbol ms : base) {
1286            primaryTodo = primaryTodo.prepend(ms);
1287        }
1288
1289        Set<ModuleSymbol> result = new LinkedHashSet<>();
1290        result.add(syms.java_base);
1291
1292        while (primaryTodo.nonEmpty() || secondaryTodo.nonEmpty()) {
1293            ModuleSymbol current;
1294            boolean isPrimaryTodo;
1295            if (primaryTodo.nonEmpty()) {
1296                current = primaryTodo.head;
1297                primaryTodo = primaryTodo.tail;
1298                isPrimaryTodo = true;
1299            } else {
1300                current = secondaryTodo.head;
1301                secondaryTodo = secondaryTodo.tail;
1302                isPrimaryTodo = false;
1303            }
1304            if (observable != null && !observable.contains(current))
1305                continue;
1306            if (!result.add(current) || current == syms.unnamedModule || ((current.flags_field & Flags.AUTOMATIC_MODULE) != 0))
1307                continue;
1308            current.complete();
1309            if (current.kind == ERR && isPrimaryTodo && warnedMissing.add(current)) {
1310                log.error(Errors.ModuleNotFound(current));
1311            }
1312            for (RequiresDirective rd : current.requires) {
1313                if (rd.module == syms.java_base) continue;
1314                if ((rd.isTransitive() && isPrimaryTodo) || base.contains(current)) {
1315                    primaryTodo = primaryTodo.prepend(rd.module);
1316                } else {
1317                    secondaryTodo = secondaryTodo.prepend(rd.module);
1318                }
1319            }
1320        }
1321
1322        return result;
1323    }
1324
1325    public ModuleSymbol getObservableModule(Name name) {
1326        ModuleSymbol mod = syms.getModule(name);
1327
1328        if (allModules().contains(mod)) {
1329            return mod;
1330        }
1331
1332        return null;
1333    }
1334
1335    private Completer getUnnamedModuleCompleter() {
1336        moduleFinder.findAllModules();
1337        return new Symbol.Completer() {
1338            @Override
1339            public void complete(Symbol sym) throws CompletionFailure {
1340                if (inInitModules) {
1341                    sym.completer = this;
1342                    return ;
1343                }
1344                ModuleSymbol msym = (ModuleSymbol) sym;
1345                Set<ModuleSymbol> allModules = new HashSet<>(allModules());
1346                allModules.remove(syms.unnamedModule);
1347                for (ModuleSymbol m : allModules) {
1348                    m.complete();
1349                }
1350                initVisiblePackages(msym, allModules);
1351            }
1352
1353            @Override
1354            public String toString() {
1355                return "unnamedModule Completer";
1356            }
1357        };
1358    }
1359
1360    private final Map<ModuleSymbol, Set<ModuleSymbol>> requiresTransitiveCache = new HashMap<>();
1361
1362    private void completeModule(ModuleSymbol msym) {
1363        if (inInitModules) {
1364            msym.completer = sym -> completeModule(msym);
1365            return ;
1366        }
1367
1368        if ((msym.flags_field & Flags.AUTOMATIC_MODULE) != 0) {
1369            completeAutomaticModule(msym);
1370        }
1371
1372        Assert.checkNonNull(msym.requires);
1373
1374        initAddReads();
1375
1376        msym.requires = msym.requires.appendList(List.from(addReads.getOrDefault(msym, Collections.emptySet())));
1377
1378        List<RequiresDirective> requires = msym.requires;
1379
1380        while (requires.nonEmpty()) {
1381            if (!allModules().contains(requires.head.module)) {
1382                Env<AttrContext> env = typeEnvs.get(msym);
1383                if (env != null) {
1384                    JavaFileObject origSource = log.useSource(env.toplevel.sourcefile);
1385                    try {
1386                        log.error(/*XXX*/env.tree, Errors.ModuleNotFound(requires.head.module));
1387                    } finally {
1388                        log.useSource(origSource);
1389                    }
1390                } else {
1391                    Assert.check((msym.flags() & Flags.AUTOMATIC_MODULE) == 0);
1392                }
1393                msym.requires = List.filter(msym.requires, requires.head);
1394            }
1395            requires = requires.tail;
1396        }
1397
1398        Set<ModuleSymbol> readable = new LinkedHashSet<>();
1399        Set<ModuleSymbol> requiresTransitive = new HashSet<>();
1400
1401        for (RequiresDirective d : msym.requires) {
1402            d.module.complete();
1403            readable.add(d.module);
1404            Set<ModuleSymbol> s = retrieveRequiresTransitive(d.module);
1405            Assert.checkNonNull(s, () -> "no entry in cache for " + d.module);
1406            readable.addAll(s);
1407            if (d.flags.contains(RequiresFlag.TRANSITIVE)) {
1408                requiresTransitive.add(d.module);
1409                requiresTransitive.addAll(s);
1410            }
1411        }
1412
1413        requiresTransitiveCache.put(msym, requiresTransitive);
1414        initVisiblePackages(msym, readable);
1415        for (ExportsDirective d: msym.exports) {
1416            if (d.packge != null) {
1417                d.packge.modle = msym;
1418            }
1419        }
1420
1421    }
1422
1423    private Set<ModuleSymbol> retrieveRequiresTransitive(ModuleSymbol msym) {
1424        Set<ModuleSymbol> requiresTransitive = requiresTransitiveCache.get(msym);
1425
1426        if (requiresTransitive == null) {
1427            //the module graph may contain cycles involving automatic modules or --add-reads edges
1428            requiresTransitive = new HashSet<>();
1429
1430            Set<ModuleSymbol> seen = new HashSet<>();
1431            List<ModuleSymbol> todo = List.of(msym);
1432
1433            while (todo.nonEmpty()) {
1434                ModuleSymbol current = todo.head;
1435                todo = todo.tail;
1436                if (!seen.add(current))
1437                    continue;
1438                requiresTransitive.add(current);
1439                current.complete();
1440                Iterable<? extends RequiresDirective> requires;
1441                if (current != syms.unnamedModule) {
1442                    Assert.checkNonNull(current.requires, () -> current + ".requires == null; " + msym);
1443                    requires = current.requires;
1444                    for (RequiresDirective rd : requires) {
1445                        if (rd.isTransitive())
1446                            todo = todo.prepend(rd.module);
1447                    }
1448                } else {
1449                    for (ModuleSymbol mod : allModules()) {
1450                        todo = todo.prepend(mod);
1451                    }
1452                }
1453            }
1454
1455            requiresTransitive.remove(msym);
1456        }
1457
1458        return requiresTransitive;
1459    }
1460
1461    private void initVisiblePackages(ModuleSymbol msym, Collection<ModuleSymbol> readable) {
1462        initAddExports();
1463
1464        msym.visiblePackages = new LinkedHashMap<>();
1465        msym.readModules = new HashSet<>(readable);
1466
1467        Map<Name, ModuleSymbol> seen = new HashMap<>();
1468
1469        for (ModuleSymbol rm : readable) {
1470            if (rm == syms.unnamedModule)
1471                continue;
1472            addVisiblePackages(msym, seen, rm, rm.exports);
1473        }
1474
1475        addExports.forEach((exportsFrom, exports) -> {
1476            addVisiblePackages(msym, seen, exportsFrom, exports);
1477        });
1478    }
1479
1480    private void addVisiblePackages(ModuleSymbol msym,
1481                                    Map<Name, ModuleSymbol> seenPackages,
1482                                    ModuleSymbol exportsFrom,
1483                                    Collection<ExportsDirective> exports) {
1484        for (ExportsDirective d : exports) {
1485            if (d.modules == null || d.modules.contains(msym)) {
1486                Name packageName = d.packge.fullname;
1487                ModuleSymbol previousModule = seenPackages.get(packageName);
1488
1489                if (previousModule != null && previousModule != exportsFrom) {
1490                    Env<AttrContext> env = typeEnvs.get(msym);
1491                    JavaFileObject origSource = env != null ? log.useSource(env.toplevel.sourcefile)
1492                                                            : null;
1493                    DiagnosticPosition pos = env != null ? env.tree.pos() : null;
1494                    try {
1495                        log.error(pos, Errors.PackageClashFromRequires(msym, packageName,
1496                                                                      previousModule, exportsFrom));
1497                    } finally {
1498                        if (env != null)
1499                            log.useSource(origSource);
1500                    }
1501                    continue;
1502                }
1503
1504                seenPackages.put(packageName, exportsFrom);
1505                msym.visiblePackages.put(d.packge.fullname, d.packge);
1506            }
1507        }
1508    }
1509
1510    private void initAddExports() {
1511        if (addExports != null)
1512            return;
1513
1514        addExports = new LinkedHashMap<>();
1515        Set<ModuleSymbol> unknownModules = new HashSet<>();
1516
1517        if (addExportsOpt == null)
1518            return;
1519
1520        Pattern ep = Pattern.compile("([^/]+)/([^=]+)=(.*)");
1521        for (String s: addExportsOpt.split("\0+")) {
1522            if (s.isEmpty())
1523                continue;
1524            Matcher em = ep.matcher(s);
1525            if (!em.matches()) {
1526                continue;
1527            }
1528
1529            // Terminology comes from
1530            //  --add-exports module/package=target,...
1531            // Compare to
1532            //  module module { exports package to target, ... }
1533            String moduleName = em.group(1);
1534            String packageName = em.group(2);
1535            String targetNames = em.group(3);
1536
1537            if (!isValidName(moduleName))
1538                continue;
1539
1540            ModuleSymbol msym = syms.enterModule(names.fromString(moduleName));
1541            if (!isKnownModule(msym, unknownModules))
1542                continue;
1543
1544            if (!isValidName(packageName))
1545                continue;
1546            PackageSymbol p = syms.enterPackage(msym, names.fromString(packageName));
1547            p.modle = msym;  // TODO: do we need this?
1548
1549            List<ModuleSymbol> targetModules = List.nil();
1550            for (String toModule : targetNames.split("[ ,]+")) {
1551                ModuleSymbol m;
1552                if (toModule.equals("ALL-UNNAMED")) {
1553                    m = syms.unnamedModule;
1554                } else {
1555                    if (!isValidName(toModule))
1556                        continue;
1557                    m = syms.enterModule(names.fromString(toModule));
1558                    if (!isKnownModule(m, unknownModules))
1559                        continue;
1560                }
1561                targetModules = targetModules.prepend(m);
1562            }
1563
1564            Set<ExportsDirective> extra = addExports.computeIfAbsent(msym, _x -> new LinkedHashSet<>());
1565            ExportsDirective d = new ExportsDirective(p, targetModules);
1566            extra.add(d);
1567        }
1568    }
1569
1570    private boolean isKnownModule(ModuleSymbol msym, Set<ModuleSymbol> unknownModules) {
1571        if (allModules.contains(msym)) {
1572            return true;
1573        }
1574
1575        if (!unknownModules.contains(msym)) {
1576            if (lintOptions) {
1577                log.warning(LintCategory.OPTIONS,
1578                        Warnings.ModuleForOptionNotFound(Option.ADD_EXPORTS, msym));
1579            }
1580            unknownModules.add(msym);
1581        }
1582        return false;
1583    }
1584
1585    private void initAddReads() {
1586        if (addReads != null)
1587            return;
1588
1589        addReads = new LinkedHashMap<>();
1590
1591        if (addReadsOpt == null)
1592            return;
1593
1594        Pattern rp = Pattern.compile("([^=]+)=(.*)");
1595        for (String s : addReadsOpt.split("\0+")) {
1596            if (s.isEmpty())
1597                continue;
1598            Matcher rm = rp.matcher(s);
1599            if (!rm.matches()) {
1600                continue;
1601            }
1602
1603            // Terminology comes from
1604            //  --add-reads source-module=target-module,...
1605            // Compare to
1606            //  module source-module { requires target-module; ... }
1607            String sourceName = rm.group(1);
1608            String targetNames = rm.group(2);
1609
1610            if (!isValidName(sourceName))
1611                continue;
1612
1613            ModuleSymbol msym = syms.enterModule(names.fromString(sourceName));
1614            if (!allModules.contains(msym)) {
1615                if (lintOptions) {
1616                    log.warning(Warnings.ModuleForOptionNotFound(Option.ADD_READS, msym));
1617                }
1618                continue;
1619            }
1620
1621            for (String targetName : targetNames.split("[ ,]+", -1)) {
1622                ModuleSymbol targetModule;
1623                if (targetName.equals("ALL-UNNAMED")) {
1624                    targetModule = syms.unnamedModule;
1625                } else {
1626                    if (!isValidName(targetName))
1627                        continue;
1628                    targetModule = syms.enterModule(names.fromString(targetName));
1629                    if (!allModules.contains(targetModule)) {
1630                        if (lintOptions) {
1631                            log.warning(LintCategory.OPTIONS, Warnings.ModuleForOptionNotFound(Option.ADD_READS, targetModule));
1632                        }
1633                        continue;
1634                    }
1635                }
1636                addReads.computeIfAbsent(msym, m -> new HashSet<>())
1637                        .add(new RequiresDirective(targetModule, EnumSet.of(RequiresFlag.EXTRA)));
1638            }
1639        }
1640    }
1641
1642    private void checkCyclicDependencies(JCModuleDecl mod) {
1643        for (JCDirective d : mod.directives) {
1644            JCRequires rd;
1645            if (!d.hasTag(Tag.REQUIRES) || (rd = (JCRequires) d).directive == null)
1646                continue;
1647            Set<ModuleSymbol> nonSyntheticDeps = new HashSet<>();
1648            List<ModuleSymbol> queue = List.of(rd.directive.module);
1649            while (queue.nonEmpty()) {
1650                ModuleSymbol current = queue.head;
1651                queue = queue.tail;
1652                if (!nonSyntheticDeps.add(current))
1653                    continue;
1654                current.complete();
1655                if ((current.flags() & Flags.ACYCLIC) != 0)
1656                    continue;
1657                Assert.checkNonNull(current.requires, current::toString);
1658                for (RequiresDirective dep : current.requires) {
1659                    if (!dep.flags.contains(RequiresFlag.EXTRA))
1660                        queue = queue.prepend(dep.module);
1661                }
1662            }
1663            if (nonSyntheticDeps.contains(mod.sym)) {
1664                log.error(rd.moduleName.pos(), Errors.CyclicRequires(rd.directive.module));
1665            }
1666            mod.sym.flags_field |= Flags.ACYCLIC;
1667        }
1668    }
1669
1670    private boolean isValidName(CharSequence name) {
1671        return SourceVersion.isName(name, Source.toSourceVersion(source));
1672    }
1673
1674    // DEBUG
1675    private String toString(ModuleSymbol msym) {
1676        return msym.name + "["
1677                + "kind:" + msym.kind + ";"
1678                + "locn:" + toString(msym.sourceLocation) + "," + toString(msym.classLocation) + ";"
1679                + "info:" + toString(msym.module_info.sourcefile) + ","
1680                            + toString(msym.module_info.classfile) + ","
1681                            + msym.module_info.completer
1682                + "]";
1683    }
1684
1685    // DEBUG
1686    String toString(Location locn) {
1687        return (locn == null) ? "--" : locn.getName();
1688    }
1689
1690    // DEBUG
1691    String toString(JavaFileObject fo) {
1692        return (fo == null) ? "--" : fo.getName();
1693    }
1694
1695    public void newRound() {
1696        allModules = null;
1697        rootModules = null;
1698        warnedMissing.clear();
1699    }
1700
1701    public interface PackageNameFinder {
1702        public Name findPackageNameOf(JavaFileObject jfo);
1703    }
1704}
1705