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