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