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