Modules.java revision 4109:6190dbeac954
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                chk.checkModuleRequires(tree.moduleName.pos(), tree.directive);
1079                msym.directives = msym.directives.prepend(tree.directive);
1080            }
1081        }
1082
1083        @Override
1084        public void visitUses(JCUses tree) {
1085            Type st = attr.attribType(tree.qualid, env, syms.objectType);
1086            Symbol sym = TreeInfo.symbol(tree.qualid);
1087            if ((sym.flags() & ENUM) != 0) {
1088                log.error(tree.qualid.pos(), Errors.ServiceDefinitionIsEnum(st.tsym));
1089            } else if (st.hasTag(CLASS)) {
1090                ClassSymbol service = (ClassSymbol) st.tsym;
1091                if (allUses.add(service)) {
1092                    Directive.UsesDirective d = new Directive.UsesDirective(service);
1093                    msym.uses = msym.uses.prepend(d);
1094                    msym.directives = msym.directives.prepend(d);
1095                } else {
1096                    log.error(tree.pos(), Errors.DuplicateUses(service));
1097                }
1098            }
1099        }
1100
1101        private void checkForCorrectness() {
1102            for (Directive.ProvidesDirective provides : msym.provides) {
1103                JCProvides tree = directiveToTreeMap.get(provides);
1104                for (ClassSymbol impl : provides.impls) {
1105                    /* The implementation must be defined in the same module as the provides directive
1106                     * (else, error)
1107                     */
1108                    PackageSymbol implementationDefiningPackage = impl.packge();
1109                    if (implementationDefiningPackage.modle != msym) {
1110                        // TODO: should use tree for the implentation name, not the entire provides tree
1111                        // TODO: should improve error message to identify the implementation type
1112                        log.error(tree.pos(), Errors.ServiceImplementationNotInRightModule(implementationDefiningPackage.modle));
1113                    }
1114
1115                    /* There is no inherent requirement that module that provides a service should actually
1116                     * use it itself. However, it is a pointless declaration if the service package is not
1117                     * exported and there is no uses for the service.
1118                     */
1119                    PackageSymbol interfaceDeclaringPackage = provides.service.packge();
1120                    boolean isInterfaceDeclaredInCurrentModule = interfaceDeclaringPackage.modle == msym;
1121                    boolean isInterfaceExportedFromAReadableModule =
1122                            msym.visiblePackages.get(interfaceDeclaringPackage.fullname) == interfaceDeclaringPackage;
1123                    if (isInterfaceDeclaredInCurrentModule && !isInterfaceExportedFromAReadableModule) {
1124                        // ok the interface is declared in this module. Let's check if it's exported
1125                        boolean warn = true;
1126                        for (ExportsDirective export : msym.exports) {
1127                            if (interfaceDeclaringPackage == export.packge) {
1128                                warn = false;
1129                                break;
1130                            }
1131                        }
1132                        if (warn) {
1133                            for (UsesDirective uses : msym.uses) {
1134                                if (provides.service == uses.service) {
1135                                    warn = false;
1136                                    break;
1137                                }
1138                            }
1139                        }
1140                        if (warn) {
1141                            log.warning(tree.pos(), Warnings.ServiceProvidedButNotExportedOrUsed(provides.service));
1142                        }
1143                    }
1144                }
1145            }
1146        }
1147    }
1148
1149    private Set<ModuleSymbol> allModules;
1150
1151    public Set<ModuleSymbol> allModules() {
1152        Assert.checkNonNull(allModules);
1153        return allModules;
1154    }
1155
1156    private void setupAllModules() {
1157        Assert.checkNonNull(rootModules);
1158        Assert.checkNull(allModules);
1159
1160        Set<ModuleSymbol> observable;
1161
1162        if (limitModsOpt == null && extraLimitMods.isEmpty()) {
1163            observable = null;
1164        } else {
1165            Set<ModuleSymbol> limitMods = new HashSet<>();
1166            if (limitModsOpt != null) {
1167                for (String limit : limitModsOpt.split(",")) {
1168                    if (!isValidName(limit))
1169                        continue;
1170                    limitMods.add(syms.enterModule(names.fromString(limit)));
1171                }
1172            }
1173            for (String limit : extraLimitMods) {
1174                limitMods.add(syms.enterModule(names.fromString(limit)));
1175            }
1176            observable = computeTransitiveClosure(limitMods, null);
1177            observable.addAll(rootModules);
1178            if (lintOptions) {
1179                for (ModuleSymbol msym : limitMods) {
1180                    if (!observable.contains(msym)) {
1181                        log.warning(LintCategory.OPTIONS,
1182                                Warnings.ModuleForOptionNotFound(Option.LIMIT_MODULES, msym));
1183                    }
1184                }
1185            }
1186        }
1187
1188        Predicate<ModuleSymbol> observablePred = sym ->
1189             (observable == null) ? (moduleFinder.findModule(sym).kind != ERR) : observable.contains(sym);
1190        Predicate<ModuleSymbol> systemModulePred = sym -> (sym.flags() & Flags.SYSTEM_MODULE) != 0;
1191        Predicate<ModuleSymbol> noIncubatorPred = sym -> {
1192            sym.complete();
1193            return !sym.resolutionFlags.contains(ModuleResolutionFlags.DO_NOT_RESOLVE_BY_DEFAULT);
1194        };
1195        Set<ModuleSymbol> enabledRoot = new LinkedHashSet<>();
1196
1197        if (rootModules.contains(syms.unnamedModule)) {
1198            ModuleSymbol javaSE = syms.getModule(java_se);
1199            Predicate<ModuleSymbol> jdkModulePred;
1200
1201            if (javaSE != null && (observable == null || observable.contains(javaSE))) {
1202                jdkModulePred = sym -> {
1203                    sym.complete();
1204                    return   !sym.name.startsWith(java_)
1205                           && sym.exports.stream().anyMatch(e -> e.modules == null);
1206                };
1207                enabledRoot.add(javaSE);
1208            } else {
1209                jdkModulePred = sym -> true;
1210            }
1211
1212            for (ModuleSymbol sym : new HashSet<>(syms.getAllModules())) {
1213                if (systemModulePred.test(sym) && observablePred.test(sym) && jdkModulePred.test(sym) && noIncubatorPred.test(sym)) {
1214                    enabledRoot.add(sym);
1215                }
1216            }
1217        }
1218
1219        enabledRoot.addAll(rootModules);
1220
1221        if (addModsOpt != null || !extraAddMods.isEmpty()) {
1222            Set<String> fullAddMods = new HashSet<>();
1223            fullAddMods.addAll(extraAddMods);
1224
1225            if (addModsOpt != null) {
1226                fullAddMods.addAll(Arrays.asList(addModsOpt.split(",")));
1227            }
1228
1229            for (String added : fullAddMods) {
1230                Stream<ModuleSymbol> modules;
1231                switch (added) {
1232                    case ALL_SYSTEM:
1233                        modules = new HashSet<>(syms.getAllModules())
1234                                .stream()
1235                                .filter(systemModulePred.and(observablePred));
1236                        break;
1237                    case ALL_MODULE_PATH:
1238                        modules = new HashSet<>(syms.getAllModules())
1239                                .stream()
1240                                .filter(systemModulePred.negate().and(observablePred));
1241                        break;
1242                    default:
1243                        if (!isValidName(added))
1244                            continue;
1245                        modules = Stream.of(syms.enterModule(names.fromString(added)));
1246                        break;
1247                }
1248                modules.forEach(sym -> {
1249                    enabledRoot.add(sym);
1250                    if (observable != null)
1251                        observable.add(sym);
1252                });
1253            }
1254        }
1255
1256        Set<ModuleSymbol> result = computeTransitiveClosure(enabledRoot, observable);
1257
1258        result.add(syms.unnamedModule);
1259
1260        boolean hasAutomatic = result.stream().anyMatch(IS_AUTOMATIC);
1261
1262        if (hasAutomatic) {
1263            syms.getAllModules()
1264                .stream()
1265                .filter(IS_AUTOMATIC)
1266                .forEach(result::add);
1267        }
1268
1269        String incubatingModules = result.stream()
1270                .filter(msym -> msym.resolutionFlags.contains(ModuleResolutionFlags.WARN_INCUBATING))
1271                .map(msym -> msym.name.toString())
1272                .collect(Collectors.joining(","));
1273
1274        if (!incubatingModules.isEmpty()) {
1275            log.warning(Warnings.IncubatingModules(incubatingModules));
1276        }
1277
1278        allModules = result;
1279
1280        //add module versions from options, if any:
1281        if (moduleVersionOpt != null) {
1282            Name version = names.fromString(moduleVersionOpt);
1283            rootModules.forEach(m -> m.version = version);
1284        }
1285    }
1286    //where:
1287        private static final Predicate<ModuleSymbol> IS_AUTOMATIC =
1288                m -> (m.flags_field & Flags.AUTOMATIC_MODULE) != 0;
1289
1290    public boolean isInModuleGraph(ModuleSymbol msym) {
1291        return allModules == null || allModules.contains(msym);
1292    }
1293
1294    private Set<ModuleSymbol> computeTransitiveClosure(Set<? extends ModuleSymbol> base, Set<ModuleSymbol> observable) {
1295        List<ModuleSymbol> primaryTodo = List.nil();
1296        List<ModuleSymbol> secondaryTodo = List.nil();
1297
1298        for (ModuleSymbol ms : base) {
1299            primaryTodo = primaryTodo.prepend(ms);
1300        }
1301
1302        Set<ModuleSymbol> result = new LinkedHashSet<>();
1303        result.add(syms.java_base);
1304
1305        while (primaryTodo.nonEmpty() || secondaryTodo.nonEmpty()) {
1306            ModuleSymbol current;
1307            boolean isPrimaryTodo;
1308            if (primaryTodo.nonEmpty()) {
1309                current = primaryTodo.head;
1310                primaryTodo = primaryTodo.tail;
1311                isPrimaryTodo = true;
1312            } else {
1313                current = secondaryTodo.head;
1314                secondaryTodo = secondaryTodo.tail;
1315                isPrimaryTodo = false;
1316            }
1317            if (observable != null && !observable.contains(current))
1318                continue;
1319            if (!result.add(current) || current == syms.unnamedModule || ((current.flags_field & Flags.AUTOMATIC_MODULE) != 0))
1320                continue;
1321            current.complete();
1322            if (current.kind == ERR && isPrimaryTodo && warnedMissing.add(current)) {
1323                log.error(Errors.ModuleNotFound(current));
1324            }
1325            for (RequiresDirective rd : current.requires) {
1326                if (rd.module == syms.java_base) continue;
1327                if ((rd.isTransitive() && isPrimaryTodo) || base.contains(current)) {
1328                    primaryTodo = primaryTodo.prepend(rd.module);
1329                } else {
1330                    secondaryTodo = secondaryTodo.prepend(rd.module);
1331                }
1332            }
1333        }
1334
1335        return result;
1336    }
1337
1338    public ModuleSymbol getObservableModule(Name name) {
1339        ModuleSymbol mod = syms.getModule(name);
1340
1341        if (allModules().contains(mod)) {
1342            return mod;
1343        }
1344
1345        return null;
1346    }
1347
1348    private Completer getUnnamedModuleCompleter() {
1349        moduleFinder.findAllModules();
1350        return new Symbol.Completer() {
1351            @Override
1352            public void complete(Symbol sym) throws CompletionFailure {
1353                if (inInitModules) {
1354                    sym.completer = this;
1355                    return ;
1356                }
1357                ModuleSymbol msym = (ModuleSymbol) sym;
1358                Set<ModuleSymbol> allModules = new HashSet<>(allModules());
1359                allModules.remove(syms.unnamedModule);
1360                for (ModuleSymbol m : allModules) {
1361                    m.complete();
1362                }
1363                initVisiblePackages(msym, allModules);
1364            }
1365
1366            @Override
1367            public String toString() {
1368                return "unnamedModule Completer";
1369            }
1370        };
1371    }
1372
1373    private final Map<ModuleSymbol, Set<ModuleSymbol>> requiresTransitiveCache = new HashMap<>();
1374
1375    private void completeModule(ModuleSymbol msym) {
1376        if (inInitModules) {
1377            msym.completer = sym -> completeModule(msym);
1378            return ;
1379        }
1380
1381        if ((msym.flags_field & Flags.AUTOMATIC_MODULE) != 0) {
1382            completeAutomaticModule(msym);
1383        }
1384
1385        Assert.checkNonNull(msym.requires);
1386
1387        initAddReads();
1388
1389        msym.requires = msym.requires.appendList(List.from(addReads.getOrDefault(msym, Collections.emptySet())));
1390
1391        List<RequiresDirective> requires = msym.requires;
1392
1393        while (requires.nonEmpty()) {
1394            if (!allModules().contains(requires.head.module)) {
1395                Env<AttrContext> env = typeEnvs.get(msym);
1396                if (env != null) {
1397                    JavaFileObject origSource = log.useSource(env.toplevel.sourcefile);
1398                    try {
1399                        log.error(/*XXX*/env.tree, Errors.ModuleNotFound(requires.head.module));
1400                    } finally {
1401                        log.useSource(origSource);
1402                    }
1403                } else {
1404                    Assert.check((msym.flags() & Flags.AUTOMATIC_MODULE) == 0);
1405                }
1406                msym.requires = List.filter(msym.requires, requires.head);
1407            }
1408            requires = requires.tail;
1409        }
1410
1411        Set<ModuleSymbol> readable = new LinkedHashSet<>();
1412        Set<ModuleSymbol> requiresTransitive = new HashSet<>();
1413
1414        for (RequiresDirective d : msym.requires) {
1415            d.module.complete();
1416            readable.add(d.module);
1417            Set<ModuleSymbol> s = retrieveRequiresTransitive(d.module);
1418            Assert.checkNonNull(s, () -> "no entry in cache for " + d.module);
1419            readable.addAll(s);
1420            if (d.flags.contains(RequiresFlag.TRANSITIVE)) {
1421                requiresTransitive.add(d.module);
1422                requiresTransitive.addAll(s);
1423            }
1424        }
1425
1426        requiresTransitiveCache.put(msym, requiresTransitive);
1427        initVisiblePackages(msym, readable);
1428        for (ExportsDirective d: msym.exports) {
1429            if (d.packge != null) {
1430                d.packge.modle = msym;
1431            }
1432        }
1433
1434    }
1435
1436    private Set<ModuleSymbol> retrieveRequiresTransitive(ModuleSymbol msym) {
1437        Set<ModuleSymbol> requiresTransitive = requiresTransitiveCache.get(msym);
1438
1439        if (requiresTransitive == null) {
1440            //the module graph may contain cycles involving automatic modules or --add-reads edges
1441            requiresTransitive = new HashSet<>();
1442
1443            Set<ModuleSymbol> seen = new HashSet<>();
1444            List<ModuleSymbol> todo = List.of(msym);
1445
1446            while (todo.nonEmpty()) {
1447                ModuleSymbol current = todo.head;
1448                todo = todo.tail;
1449                if (!seen.add(current))
1450                    continue;
1451                requiresTransitive.add(current);
1452                current.complete();
1453                Iterable<? extends RequiresDirective> requires;
1454                if (current != syms.unnamedModule) {
1455                    Assert.checkNonNull(current.requires, () -> current + ".requires == null; " + msym);
1456                    requires = current.requires;
1457                    for (RequiresDirective rd : requires) {
1458                        if (rd.isTransitive())
1459                            todo = todo.prepend(rd.module);
1460                    }
1461                } else {
1462                    for (ModuleSymbol mod : allModules()) {
1463                        todo = todo.prepend(mod);
1464                    }
1465                }
1466            }
1467
1468            requiresTransitive.remove(msym);
1469        }
1470
1471        return requiresTransitive;
1472    }
1473
1474    private void initVisiblePackages(ModuleSymbol msym, Collection<ModuleSymbol> readable) {
1475        initAddExports();
1476
1477        msym.visiblePackages = new LinkedHashMap<>();
1478        msym.readModules = new HashSet<>(readable);
1479
1480        Map<Name, ModuleSymbol> seen = new HashMap<>();
1481
1482        for (ModuleSymbol rm : readable) {
1483            if (rm == syms.unnamedModule)
1484                continue;
1485            addVisiblePackages(msym, seen, rm, rm.exports);
1486        }
1487
1488        addExports.forEach((exportsFrom, exports) -> {
1489            addVisiblePackages(msym, seen, exportsFrom, exports);
1490        });
1491    }
1492
1493    private void addVisiblePackages(ModuleSymbol msym,
1494                                    Map<Name, ModuleSymbol> seenPackages,
1495                                    ModuleSymbol exportsFrom,
1496                                    Collection<ExportsDirective> exports) {
1497        for (ExportsDirective d : exports) {
1498            if (d.modules == null || d.modules.contains(msym)) {
1499                Name packageName = d.packge.fullname;
1500                ModuleSymbol previousModule = seenPackages.get(packageName);
1501
1502                if (previousModule != null && previousModule != exportsFrom) {
1503                    Env<AttrContext> env = typeEnvs.get(msym);
1504                    JavaFileObject origSource = env != null ? log.useSource(env.toplevel.sourcefile)
1505                                                            : null;
1506                    DiagnosticPosition pos = env != null ? env.tree.pos() : null;
1507                    try {
1508                        log.error(pos, Errors.PackageClashFromRequires(msym, packageName,
1509                                                                      previousModule, exportsFrom));
1510                    } finally {
1511                        if (env != null)
1512                            log.useSource(origSource);
1513                    }
1514                    continue;
1515                }
1516
1517                seenPackages.put(packageName, exportsFrom);
1518                msym.visiblePackages.put(d.packge.fullname, d.packge);
1519            }
1520        }
1521    }
1522
1523    private void initAddExports() {
1524        if (addExports != null)
1525            return;
1526
1527        addExports = new LinkedHashMap<>();
1528        Set<ModuleSymbol> unknownModules = new HashSet<>();
1529
1530        if (addExportsOpt == null)
1531            return;
1532
1533        Pattern ep = Pattern.compile("([^/]+)/([^=]+)=(.*)");
1534        for (String s: addExportsOpt.split("\0+")) {
1535            if (s.isEmpty())
1536                continue;
1537            Matcher em = ep.matcher(s);
1538            if (!em.matches()) {
1539                continue;
1540            }
1541
1542            // Terminology comes from
1543            //  --add-exports module/package=target,...
1544            // Compare to
1545            //  module module { exports package to target, ... }
1546            String moduleName = em.group(1);
1547            String packageName = em.group(2);
1548            String targetNames = em.group(3);
1549
1550            if (!isValidName(moduleName))
1551                continue;
1552
1553            ModuleSymbol msym = syms.enterModule(names.fromString(moduleName));
1554            if (!isKnownModule(msym, unknownModules))
1555                continue;
1556
1557            if (!isValidName(packageName))
1558                continue;
1559            PackageSymbol p = syms.enterPackage(msym, names.fromString(packageName));
1560            p.modle = msym;  // TODO: do we need this?
1561
1562            List<ModuleSymbol> targetModules = List.nil();
1563            for (String toModule : targetNames.split("[ ,]+")) {
1564                ModuleSymbol m;
1565                if (toModule.equals("ALL-UNNAMED")) {
1566                    m = syms.unnamedModule;
1567                } else {
1568                    if (!isValidName(toModule))
1569                        continue;
1570                    m = syms.enterModule(names.fromString(toModule));
1571                    if (!isKnownModule(m, unknownModules))
1572                        continue;
1573                }
1574                targetModules = targetModules.prepend(m);
1575            }
1576
1577            Set<ExportsDirective> extra = addExports.computeIfAbsent(msym, _x -> new LinkedHashSet<>());
1578            ExportsDirective d = new ExportsDirective(p, targetModules);
1579            extra.add(d);
1580        }
1581    }
1582
1583    private boolean isKnownModule(ModuleSymbol msym, Set<ModuleSymbol> unknownModules) {
1584        if (allModules.contains(msym)) {
1585            return true;
1586        }
1587
1588        if (!unknownModules.contains(msym)) {
1589            if (lintOptions) {
1590                log.warning(LintCategory.OPTIONS,
1591                        Warnings.ModuleForOptionNotFound(Option.ADD_EXPORTS, msym));
1592            }
1593            unknownModules.add(msym);
1594        }
1595        return false;
1596    }
1597
1598    private void initAddReads() {
1599        if (addReads != null)
1600            return;
1601
1602        addReads = new LinkedHashMap<>();
1603
1604        if (addReadsOpt == null)
1605            return;
1606
1607        Pattern rp = Pattern.compile("([^=]+)=(.*)");
1608        for (String s : addReadsOpt.split("\0+")) {
1609            if (s.isEmpty())
1610                continue;
1611            Matcher rm = rp.matcher(s);
1612            if (!rm.matches()) {
1613                continue;
1614            }
1615
1616            // Terminology comes from
1617            //  --add-reads source-module=target-module,...
1618            // Compare to
1619            //  module source-module { requires target-module; ... }
1620            String sourceName = rm.group(1);
1621            String targetNames = rm.group(2);
1622
1623            if (!isValidName(sourceName))
1624                continue;
1625
1626            ModuleSymbol msym = syms.enterModule(names.fromString(sourceName));
1627            if (!allModules.contains(msym)) {
1628                if (lintOptions) {
1629                    log.warning(Warnings.ModuleForOptionNotFound(Option.ADD_READS, msym));
1630                }
1631                continue;
1632            }
1633
1634            for (String targetName : targetNames.split("[ ,]+", -1)) {
1635                ModuleSymbol targetModule;
1636                if (targetName.equals("ALL-UNNAMED")) {
1637                    targetModule = syms.unnamedModule;
1638                } else {
1639                    if (!isValidName(targetName))
1640                        continue;
1641                    targetModule = syms.enterModule(names.fromString(targetName));
1642                    if (!allModules.contains(targetModule)) {
1643                        if (lintOptions) {
1644                            log.warning(LintCategory.OPTIONS, Warnings.ModuleForOptionNotFound(Option.ADD_READS, targetModule));
1645                        }
1646                        continue;
1647                    }
1648                }
1649                addReads.computeIfAbsent(msym, m -> new HashSet<>())
1650                        .add(new RequiresDirective(targetModule, EnumSet.of(RequiresFlag.EXTRA)));
1651            }
1652        }
1653    }
1654
1655    private void checkCyclicDependencies(JCModuleDecl mod) {
1656        for (JCDirective d : mod.directives) {
1657            JCRequires rd;
1658            if (!d.hasTag(Tag.REQUIRES) || (rd = (JCRequires) d).directive == null)
1659                continue;
1660            Set<ModuleSymbol> nonSyntheticDeps = new HashSet<>();
1661            List<ModuleSymbol> queue = List.of(rd.directive.module);
1662            while (queue.nonEmpty()) {
1663                ModuleSymbol current = queue.head;
1664                queue = queue.tail;
1665                if (!nonSyntheticDeps.add(current))
1666                    continue;
1667                current.complete();
1668                if ((current.flags() & Flags.ACYCLIC) != 0)
1669                    continue;
1670                Assert.checkNonNull(current.requires, current::toString);
1671                for (RequiresDirective dep : current.requires) {
1672                    if (!dep.flags.contains(RequiresFlag.EXTRA))
1673                        queue = queue.prepend(dep.module);
1674                }
1675            }
1676            if (nonSyntheticDeps.contains(mod.sym)) {
1677                log.error(rd.moduleName.pos(), Errors.CyclicRequires(rd.directive.module));
1678            }
1679            mod.sym.flags_field |= Flags.ACYCLIC;
1680        }
1681    }
1682
1683    private boolean isValidName(CharSequence name) {
1684        return SourceVersion.isName(name, Source.toSourceVersion(source));
1685    }
1686
1687    // DEBUG
1688    private String toString(ModuleSymbol msym) {
1689        return msym.name + "["
1690                + "kind:" + msym.kind + ";"
1691                + "locn:" + toString(msym.sourceLocation) + "," + toString(msym.classLocation) + ";"
1692                + "info:" + toString(msym.module_info.sourcefile) + ","
1693                            + toString(msym.module_info.classfile) + ","
1694                            + msym.module_info.completer
1695                + "]";
1696    }
1697
1698    // DEBUG
1699    String toString(Location locn) {
1700        return (locn == null) ? "--" : locn.getName();
1701    }
1702
1703    // DEBUG
1704    String toString(JavaFileObject fo) {
1705        return (fo == null) ? "--" : fo.getName();
1706    }
1707
1708    public void newRound() {
1709        allModules = null;
1710        rootModules = null;
1711        warnedMissing.clear();
1712    }
1713
1714    public interface PackageNameFinder {
1715        public Name findPackageNameOf(JavaFileObject jfo);
1716    }
1717}
1718