Modules.java revision 3823:cd0a8a7a0199
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); 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) { 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 { 389 log.error(tree.pos(), Errors.UnnamedPkgNotAllowedNamedModules); 390 tree.modle = syms.errModule; 391 } 392 } catch (IOException e) { 393 throw new Error(e); // FIXME 394 } finally { 395 log.useSource(prev); 396 } 397 } 398 if (syms.unnamedModule.sourceLocation == null) { 399 syms.unnamedModule.completer = getUnnamedModuleCompleter(); 400 syms.unnamedModule.sourceLocation = StandardLocation.SOURCE_PATH; 401 syms.unnamedModule.classLocation = StandardLocation.CLASS_PATH; 402 } 403 defaultModule = syms.unnamedModule; 404 } else { 405 if (defaultModule == null) { 406 switch (rootModules.size()) { 407 case 0: 408 defaultModule = moduleFinder.findSingleModule(); 409 if (defaultModule == syms.unnamedModule) { 410 if (moduleOverride != null) { 411 checkNoAllModulePath(); 412 defaultModule = moduleFinder.findModule(names.fromString(moduleOverride)); 413 defaultModule.sourceLocation = StandardLocation.SOURCE_PATH; 414 } else { 415 // Question: why not do findAllModules and initVisiblePackages here? 416 // i.e. body of unnamedModuleCompleter 417 defaultModule.completer = getUnnamedModuleCompleter(); 418 defaultModule.classLocation = StandardLocation.CLASS_PATH; 419 } 420 } else { 421 checkSpecifiedModule(trees, Errors.ModuleInfoWithXmoduleClasspath); 422 checkNoAllModulePath(); 423 defaultModule.complete(); 424 // Question: why not do completeModule here? 425 defaultModule.completer = new Completer() { 426 @Override 427 public void complete(Symbol sym) throws CompletionFailure { 428 completeModule((ModuleSymbol) sym); 429 } 430 }; 431 } 432 rootModules.add(defaultModule); 433 break; 434 case 1: 435 checkSpecifiedModule(trees, Errors.ModuleInfoWithXmoduleSourcepath); 436 checkNoAllModulePath(); 437 defaultModule = rootModules.iterator().next(); 438 defaultModule.classLocation = StandardLocation.CLASS_OUTPUT; 439 break; 440 default: 441 Assert.error("too many modules"); 442 } 443 defaultModule.sourceLocation = StandardLocation.SOURCE_PATH; 444 } else if (rootModules.size() == 1 && defaultModule == rootModules.iterator().next()) { 445 defaultModule.complete(); 446 defaultModule.completer = sym -> completeModule((ModuleSymbol) sym); 447 } else { 448 Assert.check(rootModules.isEmpty()); 449 rootModules.add(defaultModule); 450 } 451 452 if (defaultModule != syms.unnamedModule) { 453 syms.unnamedModule.completer = getUnnamedModuleCompleter(); 454 if (moduleOverride == null) { 455 syms.unnamedModule.sourceLocation = StandardLocation.SOURCE_PATH; 456 } 457 syms.unnamedModule.classLocation = StandardLocation.CLASS_PATH; 458 } 459 460 for (JCCompilationUnit tree: trees) { 461 tree.modle = defaultModule; 462 } 463 } 464 } 465 466 private Location getModuleLocation(JCCompilationUnit tree) throws IOException { 467 if (tree.getModuleDecl() != null) { 468 return getModuleLocation(tree.sourcefile, null); 469 } else if (tree.getPackage() != null) { 470 JCPackageDecl pkg = tree.getPackage(); 471 return getModuleLocation(tree.sourcefile, TreeInfo.fullName(pkg.pid)); 472 } else { 473 // code in unnamed module 474 return null; 475 } 476 } 477 478 private Location getModuleLocation(JavaFileObject fo, Name pkgName) throws IOException { 479 // For now, just check module source path. 480 // We may want to check source path as well. 481 Location loc = 482 fileManager.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, 483 fo, (pkgName == null) ? null : pkgName.toString()); 484 if (loc == null) { 485 Location sourceOutput = fileManager.hasLocation(StandardLocation.SOURCE_OUTPUT) ? 486 StandardLocation.SOURCE_OUTPUT : StandardLocation.CLASS_OUTPUT; 487 loc = 488 fileManager.getLocationForModule(sourceOutput, 489 fo, (pkgName == null) ? null : pkgName.toString()); 490 } 491 492 return loc; 493 } 494 495 private void checkSpecifiedModule(List<JCCompilationUnit> trees, JCDiagnostic.Error error) { 496 if (moduleOverride != null) { 497 JavaFileObject prev = log.useSource(trees.head.sourcefile); 498 try { 499 log.error(trees.head.pos(), error); 500 } finally { 501 log.useSource(prev); 502 } 503 } 504 } 505 506 private void checkNoAllModulePath() { 507 if (addModsOpt != null && Arrays.asList(addModsOpt.split(",")).contains(ALL_MODULE_PATH)) { 508 log.error(Errors.AddmodsAllModulePathInvalid); 509 } 510 } 511 512 private final Completer mainCompleter = new Completer() { 513 @Override 514 public void complete(Symbol sym) throws CompletionFailure { 515 ModuleSymbol msym = moduleFinder.findModule((ModuleSymbol) sym); 516 517 if (msym.kind == Kinds.Kind.ERR) { 518 log.error(Errors.ModuleNotFound(msym)); 519 //make sure the module is initialized: 520 msym.directives = List.nil(); 521 msym.exports = List.nil(); 522 msym.provides = List.nil(); 523 msym.requires = List.nil(); 524 msym.uses = List.nil(); 525 } else if ((msym.flags_field & Flags.AUTOMATIC_MODULE) != 0) { 526 setupAutomaticModule(msym); 527 } else { 528 msym.module_info.complete(); 529 } 530 531 // If module-info comes from a .java file, the underlying 532 // call of classFinder.fillIn will have called through the 533 // source completer, to Enter, and then to Modules.enter, 534 // which will call completeModule. 535 // But, if module-info comes from a .class file, the underlying 536 // call of classFinder.fillIn will just call ClassReader to read 537 // the .class file, and so we call completeModule here. 538 if (msym.module_info.classfile == null || msym.module_info.classfile.getKind() == Kind.CLASS) { 539 completeModule(msym); 540 } 541 } 542 543 @Override 544 public String toString() { 545 return "mainCompleter"; 546 } 547 }; 548 549 private void setupAutomaticModule(ModuleSymbol msym) throws CompletionFailure { 550 try { 551 ListBuffer<Directive> directives = new ListBuffer<>(); 552 ListBuffer<ExportsDirective> exports = new ListBuffer<>(); 553 Set<String> seenPackages = new HashSet<>(); 554 555 for (JavaFileObject clazz : fileManager.list(msym.classLocation, "", EnumSet.of(Kind.CLASS), true)) { 556 String binName = fileManager.inferBinaryName(msym.classLocation, clazz); 557 String pack = binName.lastIndexOf('.') != (-1) ? binName.substring(0, binName.lastIndexOf('.')) : ""; //unnamed package???? 558 if (seenPackages.add(pack)) { 559 ExportsDirective d = new ExportsDirective(syms.enterPackage(msym, names.fromString(pack)), null); 560 //TODO: opens? 561 directives.add(d); 562 exports.add(d); 563 } 564 } 565 566 msym.exports = exports.toList(); 567 msym.provides = List.nil(); 568 msym.requires = List.nil(); 569 msym.uses = List.nil(); 570 msym.directives = directives.toList(); 571 msym.flags_field |= Flags.ACYCLIC; 572 } catch (IOException ex) { 573 throw new IllegalStateException(ex); 574 } 575 } 576 577 private void completeAutomaticModule(ModuleSymbol msym) throws CompletionFailure { 578 ListBuffer<Directive> directives = new ListBuffer<>(); 579 580 directives.addAll(msym.directives); 581 582 ListBuffer<RequiresDirective> requires = new ListBuffer<>(); 583 584 for (ModuleSymbol ms : allModules()) { 585 if (ms == syms.unnamedModule || ms == msym) 586 continue; 587 Set<RequiresFlag> flags = (ms.flags_field & Flags.AUTOMATIC_MODULE) != 0 ? 588 EnumSet.of(RequiresFlag.TRANSITIVE) : EnumSet.noneOf(RequiresFlag.class); 589 RequiresDirective d = new RequiresDirective(ms, flags); 590 directives.add(d); 591 requires.add(d); 592 } 593 594 RequiresDirective requiresUnnamed = new RequiresDirective(syms.unnamedModule); 595 directives.add(requiresUnnamed); 596 requires.add(requiresUnnamed); 597 598 msym.requires = requires.toList(); 599 msym.directives = directives.toList(); 600 } 601 602 private Completer getSourceCompleter(JCCompilationUnit tree) { 603 return new Completer() { 604 @Override 605 public void complete(Symbol sym) throws CompletionFailure { 606 ModuleSymbol msym = (ModuleSymbol) sym; 607 msym.flags_field |= UNATTRIBUTED; 608 ModuleVisitor v = new ModuleVisitor(); 609 JavaFileObject prev = log.useSource(tree.sourcefile); 610 JCModuleDecl moduleDecl = tree.getModuleDecl(); 611 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(moduleDecl.pos()); 612 613 try { 614 moduleDecl.accept(v); 615 completeModule(msym); 616 checkCyclicDependencies(moduleDecl); 617 } finally { 618 log.useSource(prev); 619 deferredLintHandler.setPos(prevLintPos); 620 msym.flags_field &= ~UNATTRIBUTED; 621 } 622 } 623 624 @Override 625 public String toString() { 626 return "SourceCompleter: " + tree.sourcefile.getName(); 627 } 628 629 }; 630 } 631 632 public boolean isRootModule(ModuleSymbol module) { 633 Assert.checkNonNull(rootModules); 634 return rootModules.contains(module); 635 } 636 637 class ModuleVisitor extends JCTree.Visitor { 638 private ModuleSymbol sym; 639 private final Set<ModuleSymbol> allRequires = new HashSet<>(); 640 private final Map<PackageSymbol,List<ExportsDirective>> allExports = new HashMap<>(); 641 private final Map<PackageSymbol,List<OpensDirective>> allOpens = new HashMap<>(); 642 643 @Override 644 public void visitModuleDef(JCModuleDecl tree) { 645 sym = Assert.checkNonNull(tree.sym); 646 647 if (tree.getModuleType() == ModuleKind.OPEN) { 648 sym.flags.add(ModuleFlags.OPEN); 649 } 650 sym.flags_field |= (tree.mods.flags & Flags.DEPRECATED); 651 652 sym.requires = List.nil(); 653 sym.exports = List.nil(); 654 sym.opens = List.nil(); 655 tree.directives.forEach(t -> t.accept(this)); 656 sym.requires = sym.requires.reverse(); 657 sym.exports = sym.exports.reverse(); 658 sym.opens = sym.opens.reverse(); 659 ensureJavaBase(); 660 } 661 662 @Override 663 public void visitRequires(JCRequires tree) { 664 ModuleSymbol msym = lookupModule(tree.moduleName); 665 if (msym.kind != MDL) { 666 log.error(tree.moduleName.pos(), Errors.ModuleNotFound(msym)); 667 } else if (allRequires.contains(msym)) { 668 log.error(tree.moduleName.pos(), Errors.DuplicateRequires(msym)); 669 } else { 670 allRequires.add(msym); 671 Set<RequiresFlag> flags = EnumSet.noneOf(RequiresFlag.class); 672 if (tree.isTransitive) 673 flags.add(RequiresFlag.TRANSITIVE); 674 if (tree.isStaticPhase) 675 flags.add(RequiresFlag.STATIC_PHASE); 676 RequiresDirective d = new RequiresDirective(msym, flags); 677 tree.directive = d; 678 sym.requires = sym.requires.prepend(d); 679 } 680 } 681 682 @Override 683 public void visitExports(JCExports tree) { 684 Name name = TreeInfo.fullName(tree.qualid); 685 PackageSymbol packge = syms.enterPackage(sym, name); 686 attr.setPackageSymbols(tree.qualid, packge); 687 688 if (tree.hasTag(Tag.OPENS) && sym.flags.contains(ModuleFlags.OPEN)) { 689 log.error(tree.pos(), Errors.NoOpensUnlessStrong); 690 } 691 List<ExportsDirective> exportsForPackage = allExports.computeIfAbsent(packge, p -> List.nil()); 692 for (ExportsDirective d : exportsForPackage) { 693 reportExportsConflict(tree, packge); 694 } 695 696 List<ModuleSymbol> toModules = null; 697 if (tree.moduleNames != null) { 698 Set<ModuleSymbol> to = new LinkedHashSet<>(); 699 for (JCExpression n: tree.moduleNames) { 700 ModuleSymbol msym = lookupModule(n); 701 chk.checkModuleExists(n.pos(), msym); 702 for (ExportsDirective d : exportsForPackage) { 703 checkDuplicateExportsToModule(n, msym, d); 704 } 705 if (!to.add(msym)) { 706 reportExportsConflictToModule(n, msym); 707 } 708 } 709 toModules = List.from(to); 710 } 711 712 if (toModules == null || !toModules.isEmpty()) { 713 Set<ExportsFlag> flags = EnumSet.noneOf(ExportsFlag.class); 714 ExportsDirective d = new ExportsDirective(packge, toModules, flags); 715 sym.exports = sym.exports.prepend(d); 716 tree.directive = d; 717 718 allExports.put(packge, exportsForPackage.prepend(d)); 719 } 720 } 721 722 private void reportExportsConflict(JCExports tree, PackageSymbol packge) { 723 log.error(tree.qualid.pos(), Errors.ConflictingExports(packge)); 724 } 725 726 private void checkDuplicateExportsToModule(JCExpression name, ModuleSymbol msym, 727 ExportsDirective d) { 728 if (d.modules != null) { 729 for (ModuleSymbol other : d.modules) { 730 if (msym == other) { 731 reportExportsConflictToModule(name, msym); 732 } 733 } 734 } 735 } 736 737 private void reportExportsConflictToModule(JCExpression name, ModuleSymbol msym) { 738 log.error(name.pos(), Errors.ConflictingExportsToModule(msym)); 739 } 740 741 @Override 742 public void visitOpens(JCOpens tree) { 743 Name name = TreeInfo.fullName(tree.qualid); 744 PackageSymbol packge = syms.enterPackage(sym, name); 745 attr.setPackageSymbols(tree.qualid, packge); 746 747 if (sym.flags.contains(ModuleFlags.OPEN)) { 748 log.error(tree.pos(), Errors.NoOpensUnlessStrong); 749 } 750 List<OpensDirective> opensForPackage = allOpens.computeIfAbsent(packge, p -> List.nil()); 751 for (OpensDirective d : opensForPackage) { 752 reportOpensConflict(tree, packge); 753 } 754 755 List<ModuleSymbol> toModules = null; 756 if (tree.moduleNames != null) { 757 Set<ModuleSymbol> to = new LinkedHashSet<>(); 758 for (JCExpression n: tree.moduleNames) { 759 ModuleSymbol msym = lookupModule(n); 760 chk.checkModuleExists(n.pos(), msym); 761 for (OpensDirective d : opensForPackage) { 762 checkDuplicateOpensToModule(n, msym, d); 763 } 764 if (!to.add(msym)) { 765 reportOpensConflictToModule(n, msym); 766 } 767 } 768 toModules = List.from(to); 769 } 770 771 if (toModules == null || !toModules.isEmpty()) { 772 Set<OpensFlag> flags = EnumSet.noneOf(OpensFlag.class); 773 OpensDirective d = new OpensDirective(packge, toModules, flags); 774 sym.opens = sym.opens.prepend(d); 775 tree.directive = d; 776 777 allOpens.put(packge, opensForPackage.prepend(d)); 778 } 779 } 780 781 private void reportOpensConflict(JCOpens tree, PackageSymbol packge) { 782 log.error(tree.qualid.pos(), Errors.ConflictingOpens(packge)); 783 } 784 785 private void checkDuplicateOpensToModule(JCExpression name, ModuleSymbol msym, 786 OpensDirective d) { 787 if (d.modules != null) { 788 for (ModuleSymbol other : d.modules) { 789 if (msym == other) { 790 reportOpensConflictToModule(name, msym); 791 } 792 } 793 } 794 } 795 796 private void reportOpensConflictToModule(JCExpression name, ModuleSymbol msym) { 797 log.error(name.pos(), Errors.ConflictingOpensToModule(msym)); 798 } 799 800 @Override 801 public void visitProvides(JCProvides tree) { } 802 803 @Override 804 public void visitUses(JCUses tree) { } 805 806 private void ensureJavaBase() { 807 if (sym.name == names.java_base) 808 return; 809 810 for (RequiresDirective d: sym.requires) { 811 if (d.module.name == names.java_base) 812 return; 813 } 814 815 ModuleSymbol java_base = syms.enterModule(names.java_base); 816 Directive.RequiresDirective d = 817 new Directive.RequiresDirective(java_base, 818 EnumSet.of(Directive.RequiresFlag.MANDATED)); 819 sym.requires = sym.requires.prepend(d); 820 } 821 822 private ModuleSymbol lookupModule(JCExpression moduleName) { 823 Name name = TreeInfo.fullName(moduleName); 824 ModuleSymbol msym = moduleFinder.findModule(name); 825 TreeInfo.setSymbol(moduleName, msym); 826 return msym; 827 } 828 } 829 830 public Completer getUsesProvidesCompleter() { 831 return sym -> { 832 ModuleSymbol msym = (ModuleSymbol) sym; 833 834 msym.complete(); 835 836 Env<AttrContext> env = typeEnvs.get(msym); 837 UsesProvidesVisitor v = new UsesProvidesVisitor(msym, env); 838 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 839 JCModuleDecl decl = env.toplevel.getModuleDecl(); 840 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(decl.pos()); 841 842 try { 843 decl.accept(v); 844 } finally { 845 log.useSource(prev); 846 deferredLintHandler.setPos(prevLintPos); 847 } 848 }; 849 } 850 851 class UsesProvidesVisitor extends JCTree.Visitor { 852 private final ModuleSymbol msym; 853 private final Env<AttrContext> env; 854 855 private final Set<ClassSymbol> allUses = new HashSet<>(); 856 private final Map<ClassSymbol, Set<ClassSymbol>> allProvides = new HashMap<>(); 857 858 public UsesProvidesVisitor(ModuleSymbol msym, Env<AttrContext> env) { 859 this.msym = msym; 860 this.env = env; 861 } 862 863 @Override @SuppressWarnings("unchecked") 864 public void visitModuleDef(JCModuleDecl tree) { 865 msym.directives = List.nil(); 866 msym.provides = List.nil(); 867 msym.uses = List.nil(); 868 tree.directives.forEach(t -> t.accept(this)); 869 msym.directives = msym.directives.reverse(); 870 msym.provides = msym.provides.reverse(); 871 msym.uses = msym.uses.reverse(); 872 873 if (msym.requires.nonEmpty() && msym.requires.head.flags.contains(RequiresFlag.MANDATED)) 874 msym.directives = msym.directives.prepend(msym.requires.head); 875 876 msym.directives = msym.directives.appendList(List.from(addReads.getOrDefault(msym, Collections.emptySet()))); 877 878 checkForCorrectness(); 879 } 880 881 @Override 882 public void visitExports(JCExports tree) { 883 if (tree.directive.packge.members().isEmpty()) { 884 log.error(tree.qualid.pos(), Errors.PackageEmptyOrNotFound(tree.directive.packge)); 885 } 886 msym.directives = msym.directives.prepend(tree.directive); 887 } 888 889 @Override 890 public void visitOpens(JCOpens tree) { 891 if (tree.directive.packge.members().isEmpty() && 892 ((tree.directive.packge.flags() & Flags.HAS_RESOURCE) == 0)) { 893 log.error(tree.qualid.pos(), Errors.PackageEmptyOrNotFound(tree.directive.packge)); 894 } 895 msym.directives = msym.directives.prepend(tree.directive); 896 } 897 898 MethodSymbol noArgsConstructor(ClassSymbol tsym) { 899 for (Symbol sym : tsym.members().getSymbolsByName(names.init)) { 900 MethodSymbol mSym = (MethodSymbol)sym; 901 if (mSym.params().isEmpty()) { 902 return mSym; 903 } 904 } 905 return null; 906 } 907 908 MethodSymbol factoryMethod(ClassSymbol tsym) { 909 for (Symbol sym : tsym.members().getSymbolsByName(names.provider, sym -> sym.kind == MTH)) { 910 MethodSymbol mSym = (MethodSymbol)sym; 911 if (mSym.isStatic() && (mSym.flags() & Flags.PUBLIC) != 0 && mSym.params().isEmpty()) { 912 return mSym; 913 } 914 } 915 return null; 916 } 917 918 Map<Directive.ProvidesDirective, JCProvides> directiveToTreeMap = new HashMap<>(); 919 920 @Override 921 public void visitProvides(JCProvides tree) { 922 Type st = attr.attribType(tree.serviceName, env, syms.objectType); 923 ClassSymbol service = (ClassSymbol) st.tsym; 924 ListBuffer<ClassSymbol> impls = new ListBuffer<>(); 925 for (JCExpression implName : tree.implNames) { 926 Type it = attr.attribType(implName, env, syms.objectType); 927 ClassSymbol impl = (ClassSymbol) it.tsym; 928 //find provider factory: 929 MethodSymbol factory = factoryMethod(impl); 930 if (factory != null) { 931 Type returnType = factory.type.getReturnType(); 932 if (!types.isSubtype(returnType, st)) { 933 log.error(implName.pos(), Errors.ServiceImplementationProviderReturnMustBeSubtypeOfServiceInterface); 934 } 935 } else { 936 if (!types.isSubtype(it, st)) { 937 log.error(implName.pos(), Errors.ServiceImplementationMustBeSubtypeOfServiceInterface); 938 } else if ((impl.flags() & ABSTRACT) != 0) { 939 log.error(implName.pos(), Errors.ServiceImplementationIsAbstract(impl)); 940 } else if (impl.isInner()) { 941 log.error(implName.pos(), Errors.ServiceImplementationIsInner(impl)); 942 } else { 943 MethodSymbol constr = noArgsConstructor(impl); 944 if (constr == null) { 945 log.error(implName.pos(), Errors.ServiceImplementationDoesntHaveANoArgsConstructor(impl)); 946 } else if ((constr.flags() & PUBLIC) == 0) { 947 log.error(implName.pos(), Errors.ServiceImplementationNoArgsConstructorNotPublic(impl)); 948 } 949 } 950 } 951 if (it.hasTag(CLASS)) { 952 // For now, we just check the pair (service-type, impl-type) is unique 953 // TODO, check only one provides per service type as well 954 if (allProvides.computeIfAbsent(service, s -> new HashSet<>()).add(impl)) { 955 impls.append(impl); 956 } else { 957 log.error(implName.pos(), Errors.DuplicateProvides(service, impl)); 958 } 959 } 960 } 961 if (st.hasTag(CLASS) && !impls.isEmpty()) { 962 Directive.ProvidesDirective d = new Directive.ProvidesDirective(service, impls.toList()); 963 msym.provides = msym.provides.prepend(d); 964 msym.directives = msym.directives.prepend(d); 965 directiveToTreeMap.put(d, tree); 966 } 967 } 968 969 @Override 970 public void visitRequires(JCRequires tree) { 971 if (tree.directive != null) { 972 chk.checkDeprecated(tree.moduleName.pos(), msym, tree.directive.module); 973 msym.directives = msym.directives.prepend(tree.directive); 974 } 975 } 976 977 @Override 978 public void visitUses(JCUses tree) { 979 Type st = attr.attribType(tree.qualid, env, syms.objectType); 980 Symbol sym = TreeInfo.symbol(tree.qualid); 981 if ((sym.flags() & ENUM) != 0) { 982 log.error(tree.qualid.pos(), Errors.ServiceDefinitionIsEnum(st.tsym)); 983 } else if (st.hasTag(CLASS)) { 984 ClassSymbol service = (ClassSymbol) st.tsym; 985 if (allUses.add(service)) { 986 Directive.UsesDirective d = new Directive.UsesDirective(service); 987 msym.uses = msym.uses.prepend(d); 988 msym.directives = msym.directives.prepend(d); 989 } else { 990 log.error(tree.pos(), Errors.DuplicateUses(service)); 991 } 992 } 993 } 994 995 private void checkForCorrectness() { 996 for (Directive.ProvidesDirective provides : msym.provides) { 997 JCProvides tree = directiveToTreeMap.get(provides); 998 for (ClassSymbol impl : provides.impls) { 999 /* The implementation must be defined in the same module as the provides directive 1000 * (else, error) 1001 */ 1002 PackageSymbol implementationDefiningPackage = impl.packge(); 1003 if (implementationDefiningPackage.modle != msym) { 1004 // TODO: should use tree for the implentation name, not the entire provides tree 1005 // TODO: should improve error message to identify the implementation type 1006 log.error(tree.pos(), Errors.ServiceImplementationNotInRightModule(implementationDefiningPackage.modle)); 1007 } 1008 1009 /* There is no inherent requirement that module that provides a service should actually 1010 * use it itself. However, it is a pointless declaration if the service package is not 1011 * exported and there is no uses for the service. 1012 */ 1013 PackageSymbol interfaceDeclaringPackage = provides.service.packge(); 1014 boolean isInterfaceDeclaredInCurrentModule = interfaceDeclaringPackage.modle == msym; 1015 boolean isInterfaceExportedFromAReadableModule = 1016 msym.visiblePackages.get(interfaceDeclaringPackage.fullname) == interfaceDeclaringPackage; 1017 if (isInterfaceDeclaredInCurrentModule && !isInterfaceExportedFromAReadableModule) { 1018 // ok the interface is declared in this module. Let's check if it's exported 1019 boolean warn = true; 1020 for (ExportsDirective export : msym.exports) { 1021 if (interfaceDeclaringPackage == export.packge) { 1022 warn = false; 1023 break; 1024 } 1025 } 1026 if (warn) { 1027 for (UsesDirective uses : msym.uses) { 1028 if (provides.service == uses.service) { 1029 warn = false; 1030 break; 1031 } 1032 } 1033 } 1034 if (warn) { 1035 log.warning(tree.pos(), Warnings.ServiceProvidedButNotExportedOrUsed(provides.service)); 1036 } 1037 } 1038 } 1039 } 1040 } 1041 } 1042 1043 private Set<ModuleSymbol> allModules; 1044 1045 public Set<ModuleSymbol> allModules() { 1046 Assert.checkNonNull(allModules); 1047 return allModules; 1048 } 1049 1050 private void setupAllModules() { 1051 Assert.checkNonNull(rootModules); 1052 Assert.checkNull(allModules); 1053 1054 Set<ModuleSymbol> observable; 1055 1056 if (limitModsOpt == null && extraLimitMods.isEmpty()) { 1057 observable = null; 1058 } else { 1059 Set<ModuleSymbol> limitMods = new HashSet<>(); 1060 if (limitModsOpt != null) { 1061 for (String limit : limitModsOpt.split(",")) { 1062 if (!isValidName(limit)) 1063 continue; 1064 limitMods.add(syms.enterModule(names.fromString(limit))); 1065 } 1066 } 1067 for (String limit : extraLimitMods) { 1068 limitMods.add(syms.enterModule(names.fromString(limit))); 1069 } 1070 observable = computeTransitiveClosure(limitMods, null); 1071 observable.addAll(rootModules); 1072 if (lintOptions) { 1073 for (ModuleSymbol msym : limitMods) { 1074 if (!observable.contains(msym)) { 1075 log.warning(LintCategory.OPTIONS, 1076 Warnings.ModuleForOptionNotFound(Option.LIMIT_MODULES, msym)); 1077 } 1078 } 1079 } 1080 } 1081 1082 Predicate<ModuleSymbol> observablePred = sym -> observable == null || observable.contains(sym); 1083 Predicate<ModuleSymbol> systemModulePred = sym -> (sym.flags() & Flags.SYSTEM_MODULE) != 0; 1084 Set<ModuleSymbol> enabledRoot = new LinkedHashSet<>(); 1085 1086 if (rootModules.contains(syms.unnamedModule)) { 1087 ModuleSymbol javaSE = syms.getModule(java_se); 1088 Predicate<ModuleSymbol> jdkModulePred; 1089 1090 if (javaSE != null && (observable == null || observable.contains(javaSE))) { 1091 jdkModulePred = sym -> { 1092 sym.complete(); 1093 return !sym.name.startsWith(java_) 1094 && sym.exports.stream().anyMatch(e -> e.modules == null); 1095 }; 1096 enabledRoot.add(javaSE); 1097 } else { 1098 jdkModulePred = sym -> true; 1099 } 1100 1101 for (ModuleSymbol sym : new HashSet<>(syms.getAllModules())) { 1102 if (systemModulePred.test(sym) && observablePred.test(sym) && jdkModulePred.test(sym)) { 1103 enabledRoot.add(sym); 1104 } 1105 } 1106 } 1107 1108 enabledRoot.addAll(rootModules); 1109 1110 if (addModsOpt != null || !extraAddMods.isEmpty()) { 1111 Set<String> fullAddMods = new HashSet<>(); 1112 fullAddMods.addAll(extraAddMods); 1113 1114 if (addModsOpt != null) { 1115 fullAddMods.addAll(Arrays.asList(addModsOpt.split(","))); 1116 } 1117 1118 for (String added : fullAddMods) { 1119 Stream<ModuleSymbol> modules; 1120 switch (added) { 1121 case ALL_SYSTEM: 1122 modules = syms.getAllModules() 1123 .stream() 1124 .filter(systemModulePred.and(observablePred)); 1125 break; 1126 case ALL_MODULE_PATH: 1127 modules = syms.getAllModules() 1128 .stream() 1129 .filter(systemModulePred.negate().and(observablePred)); 1130 break; 1131 default: 1132 if (!isValidName(added)) 1133 continue; 1134 modules = Stream.of(syms.enterModule(names.fromString(added))); 1135 break; 1136 } 1137 modules.forEach(sym -> { 1138 enabledRoot.add(sym); 1139 if (observable != null) 1140 observable.add(sym); 1141 }); 1142 } 1143 } 1144 1145 Set<ModuleSymbol> result = computeTransitiveClosure(enabledRoot, observable); 1146 1147 result.add(syms.unnamedModule); 1148 1149 allModules = result; 1150 1151 //add module versions from options, if any: 1152 if (moduleVersionOpt != null) { 1153 Name version = names.fromString(moduleVersionOpt); 1154 rootModules.forEach(m -> m.version = version); 1155 } 1156 } 1157 1158 public boolean isInModuleGraph(ModuleSymbol msym) { 1159 return allModules == null || allModules.contains(msym); 1160 } 1161 1162 private Set<ModuleSymbol> computeTransitiveClosure(Iterable<? extends ModuleSymbol> base, Set<ModuleSymbol> observable) { 1163 List<ModuleSymbol> todo = List.nil(); 1164 1165 for (ModuleSymbol ms : base) { 1166 todo = todo.prepend(ms); 1167 } 1168 1169 Set<ModuleSymbol> result = new LinkedHashSet<>(); 1170 result.add(syms.java_base); 1171 1172 while (todo.nonEmpty()) { 1173 ModuleSymbol current = todo.head; 1174 todo = todo.tail; 1175 if (observable != null && !observable.contains(current)) 1176 continue; 1177 if (!result.add(current) || current == syms.unnamedModule || ((current.flags_field & Flags.AUTOMATIC_MODULE) != 0)) 1178 continue; 1179 current.complete(); 1180 for (RequiresDirective rd : current.requires) { 1181 todo = todo.prepend(rd.module); 1182 } 1183 } 1184 1185 return result; 1186 } 1187 1188 public ModuleSymbol getObservableModule(Name name) { 1189 ModuleSymbol mod = syms.getModule(name); 1190 1191 if (allModules().contains(mod)) { 1192 return mod; 1193 } 1194 1195 return null; 1196 } 1197 1198 private Completer getUnnamedModuleCompleter() { 1199 moduleFinder.findAllModules(); 1200 return new Symbol.Completer() { 1201 @Override 1202 public void complete(Symbol sym) throws CompletionFailure { 1203 if (inInitModules) { 1204 sym.completer = this; 1205 return ; 1206 } 1207 ModuleSymbol msym = (ModuleSymbol) sym; 1208 Set<ModuleSymbol> allModules = new HashSet<>(allModules()); 1209 allModules.remove(syms.unnamedModule); 1210 for (ModuleSymbol m : allModules) { 1211 m.complete(); 1212 } 1213 initVisiblePackages(msym, allModules); 1214 } 1215 1216 @Override 1217 public String toString() { 1218 return "unnamedModule Completer"; 1219 } 1220 }; 1221 } 1222 1223 private final Map<ModuleSymbol, Set<ModuleSymbol>> requiresTransitiveCache = new HashMap<>(); 1224 1225 private void completeModule(ModuleSymbol msym) { 1226 if (inInitModules) { 1227 msym.completer = sym -> completeModule(msym); 1228 return ; 1229 } 1230 1231 if ((msym.flags_field & Flags.AUTOMATIC_MODULE) != 0) { 1232 completeAutomaticModule(msym); 1233 } 1234 1235 Assert.checkNonNull(msym.requires); 1236 1237 initAddReads(); 1238 1239 msym.requires = msym.requires.appendList(List.from(addReads.getOrDefault(msym, Collections.emptySet()))); 1240 1241 List<RequiresDirective> requires = msym.requires; 1242 List<RequiresDirective> previous = null; 1243 1244 while (requires.nonEmpty()) { 1245 if (!allModules().contains(requires.head.module)) { 1246 Env<AttrContext> env = typeEnvs.get(msym); 1247 if (env != null) { 1248 JavaFileObject origSource = log.useSource(env.toplevel.sourcefile); 1249 try { 1250 log.error(/*XXX*/env.tree, Errors.ModuleNotFound(requires.head.module)); 1251 } finally { 1252 log.useSource(origSource); 1253 } 1254 } else { 1255 Assert.check((msym.flags() & Flags.AUTOMATIC_MODULE) == 0); 1256 } 1257 if (previous != null) { 1258 previous.tail = requires.tail; 1259 } else { 1260 msym.requires.tail = requires.tail; 1261 } 1262 } else { 1263 previous = requires; 1264 } 1265 requires = requires.tail; 1266 } 1267 1268 Set<ModuleSymbol> readable = new LinkedHashSet<>(); 1269 Set<ModuleSymbol> requiresTransitive = new HashSet<>(); 1270 1271 for (RequiresDirective d : msym.requires) { 1272 d.module.complete(); 1273 readable.add(d.module); 1274 Set<ModuleSymbol> s = retrieveRequiresTransitive(d.module); 1275 Assert.checkNonNull(s, () -> "no entry in cache for " + d.module); 1276 readable.addAll(s); 1277 if (d.flags.contains(RequiresFlag.TRANSITIVE)) { 1278 requiresTransitive.add(d.module); 1279 requiresTransitive.addAll(s); 1280 } 1281 } 1282 1283 requiresTransitiveCache.put(msym, requiresTransitive); 1284 initVisiblePackages(msym, readable); 1285 for (ExportsDirective d: msym.exports) { 1286 if (d.packge != null) { 1287 d.packge.modle = msym; 1288 } 1289 } 1290 1291 } 1292 1293 private Set<ModuleSymbol> retrieveRequiresTransitive(ModuleSymbol msym) { 1294 Set<ModuleSymbol> requiresTransitive = requiresTransitiveCache.get(msym); 1295 1296 if (requiresTransitive == null) { 1297 //the module graph may contain cycles involving automatic modules or --add-reads edges 1298 requiresTransitive = new HashSet<>(); 1299 1300 Set<ModuleSymbol> seen = new HashSet<>(); 1301 List<ModuleSymbol> todo = List.of(msym); 1302 1303 while (todo.nonEmpty()) { 1304 ModuleSymbol current = todo.head; 1305 todo = todo.tail; 1306 if (!seen.add(current)) 1307 continue; 1308 requiresTransitive.add(current); 1309 current.complete(); 1310 Iterable<? extends RequiresDirective> requires; 1311 if (current != syms.unnamedModule) { 1312 Assert.checkNonNull(current.requires, () -> current + ".requires == null; " + msym); 1313 requires = current.requires; 1314 for (RequiresDirective rd : requires) { 1315 if (rd.isTransitive()) 1316 todo = todo.prepend(rd.module); 1317 } 1318 } else { 1319 for (ModuleSymbol mod : allModules()) { 1320 todo = todo.prepend(mod); 1321 } 1322 } 1323 } 1324 1325 requiresTransitive.remove(msym); 1326 } 1327 1328 return requiresTransitive; 1329 } 1330 1331 private void initVisiblePackages(ModuleSymbol msym, Collection<ModuleSymbol> readable) { 1332 initAddExports(); 1333 1334 msym.visiblePackages = new LinkedHashMap<>(); 1335 1336 Map<Name, ModuleSymbol> seen = new HashMap<>(); 1337 1338 for (ModuleSymbol rm : readable) { 1339 if (rm == syms.unnamedModule) 1340 continue; 1341 addVisiblePackages(msym, seen, rm, rm.exports); 1342 } 1343 1344 addExports.forEach((exportsFrom, exports) -> { 1345 addVisiblePackages(msym, seen, exportsFrom, exports); 1346 }); 1347 } 1348 1349 private void addVisiblePackages(ModuleSymbol msym, 1350 Map<Name, ModuleSymbol> seenPackages, 1351 ModuleSymbol exportsFrom, 1352 Collection<ExportsDirective> exports) { 1353 for (ExportsDirective d : exports) { 1354 if (d.modules == null || d.modules.contains(msym)) { 1355 Name packageName = d.packge.fullname; 1356 ModuleSymbol previousModule = seenPackages.get(packageName); 1357 1358 if (previousModule != null && previousModule != exportsFrom) { 1359 Env<AttrContext> env = typeEnvs.get(msym); 1360 JavaFileObject origSource = env != null ? log.useSource(env.toplevel.sourcefile) 1361 : null; 1362 DiagnosticPosition pos = env != null ? env.tree.pos() : null; 1363 try { 1364 log.error(pos, Errors.PackageClashFromRequires(msym, packageName, 1365 previousModule, exportsFrom)); 1366 } finally { 1367 if (env != null) 1368 log.useSource(origSource); 1369 } 1370 continue; 1371 } 1372 1373 seenPackages.put(packageName, exportsFrom); 1374 msym.visiblePackages.put(d.packge.fullname, d.packge); 1375 } 1376 } 1377 } 1378 1379 private void initAddExports() { 1380 if (addExports != null) 1381 return; 1382 1383 addExports = new LinkedHashMap<>(); 1384 Set<ModuleSymbol> unknownModules = new HashSet<>(); 1385 1386 if (addExportsOpt == null) 1387 return; 1388 1389 Pattern ep = Pattern.compile("([^/]+)/([^=]+)=(.*)"); 1390 for (String s: addExportsOpt.split("\0+")) { 1391 if (s.isEmpty()) 1392 continue; 1393 Matcher em = ep.matcher(s); 1394 if (!em.matches()) { 1395 continue; 1396 } 1397 1398 // Terminology comes from 1399 // --add-exports module/package=target,... 1400 // Compare to 1401 // module module { exports package to target, ... } 1402 String moduleName = em.group(1); 1403 String packageName = em.group(2); 1404 String targetNames = em.group(3); 1405 1406 if (!isValidName(moduleName)) 1407 continue; 1408 1409 ModuleSymbol msym = syms.enterModule(names.fromString(moduleName)); 1410 if (!isKnownModule(msym, unknownModules)) 1411 continue; 1412 1413 if (!isValidName(packageName)) 1414 continue; 1415 PackageSymbol p = syms.enterPackage(msym, names.fromString(packageName)); 1416 p.modle = msym; // TODO: do we need this? 1417 1418 List<ModuleSymbol> targetModules = List.nil(); 1419 for (String toModule : targetNames.split("[ ,]+")) { 1420 ModuleSymbol m; 1421 if (toModule.equals("ALL-UNNAMED")) { 1422 m = syms.unnamedModule; 1423 } else { 1424 if (!isValidName(toModule)) 1425 continue; 1426 m = syms.enterModule(names.fromString(toModule)); 1427 if (!isKnownModule(m, unknownModules)) 1428 continue; 1429 } 1430 targetModules = targetModules.prepend(m); 1431 } 1432 1433 Set<ExportsDirective> extra = addExports.computeIfAbsent(msym, _x -> new LinkedHashSet<>()); 1434 ExportsDirective d = new ExportsDirective(p, targetModules); 1435 extra.add(d); 1436 } 1437 } 1438 1439 private boolean isKnownModule(ModuleSymbol msym, Set<ModuleSymbol> unknownModules) { 1440 if (allModules.contains(msym)) { 1441 return true; 1442 } 1443 1444 if (!unknownModules.contains(msym)) { 1445 if (lintOptions) { 1446 log.warning(LintCategory.OPTIONS, 1447 Warnings.ModuleForOptionNotFound(Option.ADD_EXPORTS, msym)); 1448 } 1449 unknownModules.add(msym); 1450 } 1451 return false; 1452 } 1453 1454 private void initAddReads() { 1455 if (addReads != null) 1456 return; 1457 1458 addReads = new LinkedHashMap<>(); 1459 1460 if (addReadsOpt == null) 1461 return; 1462 1463 Pattern rp = Pattern.compile("([^=]+)=(.*)"); 1464 for (String s : addReadsOpt.split("\0+")) { 1465 if (s.isEmpty()) 1466 continue; 1467 Matcher rm = rp.matcher(s); 1468 if (!rm.matches()) { 1469 continue; 1470 } 1471 1472 // Terminology comes from 1473 // --add-reads source-module=target-module,... 1474 // Compare to 1475 // module source-module { requires target-module; ... } 1476 String sourceName = rm.group(1); 1477 String targetNames = rm.group(2); 1478 1479 if (!isValidName(sourceName)) 1480 continue; 1481 1482 ModuleSymbol msym = syms.enterModule(names.fromString(sourceName)); 1483 if (!allModules.contains(msym)) { 1484 if (lintOptions) { 1485 log.warning(Warnings.ModuleForOptionNotFound(Option.ADD_READS, msym)); 1486 } 1487 continue; 1488 } 1489 1490 for (String targetName : targetNames.split("[ ,]+", -1)) { 1491 ModuleSymbol targetModule; 1492 if (targetName.equals("ALL-UNNAMED")) { 1493 targetModule = syms.unnamedModule; 1494 } else { 1495 if (!isValidName(targetName)) 1496 continue; 1497 targetModule = syms.enterModule(names.fromString(targetName)); 1498 if (!allModules.contains(targetModule)) { 1499 if (lintOptions) { 1500 log.warning(LintCategory.OPTIONS, Warnings.ModuleForOptionNotFound(Option.ADD_READS, targetModule)); 1501 } 1502 continue; 1503 } 1504 } 1505 addReads.computeIfAbsent(msym, m -> new HashSet<>()) 1506 .add(new RequiresDirective(targetModule, EnumSet.of(RequiresFlag.EXTRA))); 1507 } 1508 } 1509 } 1510 1511 private void checkCyclicDependencies(JCModuleDecl mod) { 1512 for (JCDirective d : mod.directives) { 1513 JCRequires rd; 1514 if (!d.hasTag(Tag.REQUIRES) || (rd = (JCRequires) d).directive == null) 1515 continue; 1516 Set<ModuleSymbol> nonSyntheticDeps = new HashSet<>(); 1517 List<ModuleSymbol> queue = List.of(rd.directive.module); 1518 while (queue.nonEmpty()) { 1519 ModuleSymbol current = queue.head; 1520 queue = queue.tail; 1521 if (!nonSyntheticDeps.add(current)) 1522 continue; 1523 current.complete(); 1524 if ((current.flags() & Flags.ACYCLIC) != 0) 1525 continue; 1526 Assert.checkNonNull(current.requires, () -> current.toString()); 1527 for (RequiresDirective dep : current.requires) { 1528 if (!dep.flags.contains(RequiresFlag.EXTRA)) 1529 queue = queue.prepend(dep.module); 1530 } 1531 } 1532 if (nonSyntheticDeps.contains(mod.sym)) { 1533 log.error(rd.moduleName.pos(), Errors.CyclicRequires(rd.directive.module)); 1534 } 1535 mod.sym.flags_field |= Flags.ACYCLIC; 1536 } 1537 } 1538 1539 private boolean isValidName(CharSequence name) { 1540 return SourceVersion.isName(name, Source.toSourceVersion(source)); 1541 } 1542 1543 // DEBUG 1544 private String toString(ModuleSymbol msym) { 1545 return msym.name + "[" 1546 + "kind:" + msym.kind + ";" 1547 + "locn:" + toString(msym.sourceLocation) + "," + toString(msym.classLocation) + ";" 1548 + "info:" + toString(msym.module_info.sourcefile) + "," 1549 + toString(msym.module_info.classfile) + "," 1550 + msym.module_info.completer 1551 + "]"; 1552 } 1553 1554 // DEBUG 1555 String toString(Location locn) { 1556 return (locn == null) ? "--" : locn.getName(); 1557 } 1558 1559 // DEBUG 1560 String toString(JavaFileObject fo) { 1561 return (fo == null) ? "--" : fo.getName(); 1562 } 1563 1564 public void newRound() { 1565 rootModules = null; 1566 allModules = null; 1567 } 1568} 1569