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