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