Modules.java revision 4107:98108b7d4cb6
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 chk.checkModuleRequires(tree.moduleName.pos(), tree.directive); 1088 msym.directives = msym.directives.prepend(tree.directive); 1089 } 1090 } 1091 1092 @Override 1093 public void visitUses(JCUses tree) { 1094 Type st = attr.attribType(tree.qualid, env, syms.objectType); 1095 Symbol sym = TreeInfo.symbol(tree.qualid); 1096 if ((sym.flags() & ENUM) != 0) { 1097 log.error(tree.qualid.pos(), Errors.ServiceDefinitionIsEnum(st.tsym)); 1098 } else if (st.hasTag(CLASS)) { 1099 ClassSymbol service = (ClassSymbol) st.tsym; 1100 if (allUses.add(service)) { 1101 Directive.UsesDirective d = new Directive.UsesDirective(service); 1102 msym.uses = msym.uses.prepend(d); 1103 msym.directives = msym.directives.prepend(d); 1104 } else { 1105 log.error(tree.pos(), Errors.DuplicateUses(service)); 1106 } 1107 } 1108 } 1109 1110 private void checkForCorrectness() { 1111 for (Directive.ProvidesDirective provides : msym.provides) { 1112 JCProvides tree = directiveToTreeMap.get(provides); 1113 for (ClassSymbol impl : provides.impls) { 1114 /* The implementation must be defined in the same module as the provides directive 1115 * (else, error) 1116 */ 1117 PackageSymbol implementationDefiningPackage = impl.packge(); 1118 if (implementationDefiningPackage.modle != msym) { 1119 // TODO: should use tree for the implentation name, not the entire provides tree 1120 // TODO: should improve error message to identify the implementation type 1121 log.error(tree.pos(), Errors.ServiceImplementationNotInRightModule(implementationDefiningPackage.modle)); 1122 } 1123 1124 /* There is no inherent requirement that module that provides a service should actually 1125 * use it itself. However, it is a pointless declaration if the service package is not 1126 * exported and there is no uses for the service. 1127 */ 1128 PackageSymbol interfaceDeclaringPackage = provides.service.packge(); 1129 boolean isInterfaceDeclaredInCurrentModule = interfaceDeclaringPackage.modle == msym; 1130 boolean isInterfaceExportedFromAReadableModule = 1131 msym.visiblePackages.get(interfaceDeclaringPackage.fullname) == interfaceDeclaringPackage; 1132 if (isInterfaceDeclaredInCurrentModule && !isInterfaceExportedFromAReadableModule) { 1133 // ok the interface is declared in this module. Let's check if it's exported 1134 boolean warn = true; 1135 for (ExportsDirective export : msym.exports) { 1136 if (interfaceDeclaringPackage == export.packge) { 1137 warn = false; 1138 break; 1139 } 1140 } 1141 if (warn) { 1142 for (UsesDirective uses : msym.uses) { 1143 if (provides.service == uses.service) { 1144 warn = false; 1145 break; 1146 } 1147 } 1148 } 1149 if (warn) { 1150 log.warning(tree.pos(), Warnings.ServiceProvidedButNotExportedOrUsed(provides.service)); 1151 } 1152 } 1153 } 1154 } 1155 } 1156 } 1157 1158 private Set<ModuleSymbol> allModules; 1159 1160 public Set<ModuleSymbol> allModules() { 1161 Assert.checkNonNull(allModules); 1162 return allModules; 1163 } 1164 1165 private void setupAllModules() { 1166 Assert.checkNonNull(rootModules); 1167 Assert.checkNull(allModules); 1168 1169 Set<ModuleSymbol> observable; 1170 1171 if (limitModsOpt == null && extraLimitMods.isEmpty()) { 1172 observable = null; 1173 } else { 1174 Set<ModuleSymbol> limitMods = new HashSet<>(); 1175 if (limitModsOpt != null) { 1176 for (String limit : limitModsOpt.split(",")) { 1177 if (!isValidName(limit)) 1178 continue; 1179 limitMods.add(syms.enterModule(names.fromString(limit))); 1180 } 1181 } 1182 for (String limit : extraLimitMods) { 1183 limitMods.add(syms.enterModule(names.fromString(limit))); 1184 } 1185 observable = computeTransitiveClosure(limitMods, null); 1186 observable.addAll(rootModules); 1187 if (lintOptions) { 1188 for (ModuleSymbol msym : limitMods) { 1189 if (!observable.contains(msym)) { 1190 log.warning(LintCategory.OPTIONS, 1191 Warnings.ModuleForOptionNotFound(Option.LIMIT_MODULES, msym)); 1192 } 1193 } 1194 } 1195 } 1196 1197 Predicate<ModuleSymbol> observablePred = sym -> 1198 (observable == null) ? (moduleFinder.findModule(sym).kind != ERR) : observable.contains(sym); 1199 Predicate<ModuleSymbol> systemModulePred = sym -> (sym.flags() & Flags.SYSTEM_MODULE) != 0; 1200 Predicate<ModuleSymbol> noIncubatorPred = sym -> { 1201 sym.complete(); 1202 return !sym.resolutionFlags.contains(ModuleResolutionFlags.DO_NOT_RESOLVE_BY_DEFAULT); 1203 }; 1204 Set<ModuleSymbol> enabledRoot = new LinkedHashSet<>(); 1205 1206 if (rootModules.contains(syms.unnamedModule)) { 1207 ModuleSymbol javaSE = syms.getModule(java_se); 1208 Predicate<ModuleSymbol> jdkModulePred; 1209 1210 if (javaSE != null && (observable == null || observable.contains(javaSE))) { 1211 jdkModulePred = sym -> { 1212 sym.complete(); 1213 return !sym.name.startsWith(java_) 1214 && sym.exports.stream().anyMatch(e -> e.modules == null); 1215 }; 1216 enabledRoot.add(javaSE); 1217 } else { 1218 jdkModulePred = sym -> true; 1219 } 1220 1221 for (ModuleSymbol sym : new HashSet<>(syms.getAllModules())) { 1222 if (systemModulePred.test(sym) && observablePred.test(sym) && jdkModulePred.test(sym) && noIncubatorPred.test(sym)) { 1223 enabledRoot.add(sym); 1224 } 1225 } 1226 } 1227 1228 enabledRoot.addAll(rootModules); 1229 1230 if (addModsOpt != null || !extraAddMods.isEmpty()) { 1231 Set<String> fullAddMods = new HashSet<>(); 1232 fullAddMods.addAll(extraAddMods); 1233 1234 if (addModsOpt != null) { 1235 fullAddMods.addAll(Arrays.asList(addModsOpt.split(","))); 1236 } 1237 1238 for (String added : fullAddMods) { 1239 Stream<ModuleSymbol> modules; 1240 switch (added) { 1241 case ALL_SYSTEM: 1242 modules = new HashSet<>(syms.getAllModules()) 1243 .stream() 1244 .filter(systemModulePred.and(observablePred)); 1245 break; 1246 case ALL_MODULE_PATH: 1247 modules = new HashSet<>(syms.getAllModules()) 1248 .stream() 1249 .filter(systemModulePred.negate().and(observablePred)); 1250 break; 1251 default: 1252 if (!isValidName(added)) 1253 continue; 1254 modules = Stream.of(syms.enterModule(names.fromString(added))); 1255 break; 1256 } 1257 modules.forEach(sym -> { 1258 enabledRoot.add(sym); 1259 if (observable != null) 1260 observable.add(sym); 1261 }); 1262 } 1263 } 1264 1265 Set<ModuleSymbol> result = computeTransitiveClosure(enabledRoot, observable); 1266 1267 result.add(syms.unnamedModule); 1268 1269 boolean hasAutomatic = result.stream().anyMatch(IS_AUTOMATIC); 1270 1271 if (hasAutomatic) { 1272 syms.getAllModules() 1273 .stream() 1274 .filter(IS_AUTOMATIC) 1275 .forEach(result::add); 1276 } 1277 1278 String incubatingModules = result.stream() 1279 .filter(msym -> msym.resolutionFlags.contains(ModuleResolutionFlags.WARN_INCUBATING)) 1280 .map(msym -> msym.name.toString()) 1281 .collect(Collectors.joining(",")); 1282 1283 if (!incubatingModules.isEmpty()) { 1284 log.warning(Warnings.IncubatingModules(incubatingModules)); 1285 } 1286 1287 allModules = result; 1288 1289 //add module versions from options, if any: 1290 if (moduleVersionOpt != null) { 1291 Name version = names.fromString(moduleVersionOpt); 1292 rootModules.forEach(m -> m.version = version); 1293 } 1294 } 1295 //where: 1296 private static final Predicate<ModuleSymbol> IS_AUTOMATIC = 1297 m -> (m.flags_field & Flags.AUTOMATIC_MODULE) != 0; 1298 1299 public boolean isInModuleGraph(ModuleSymbol msym) { 1300 return allModules == null || allModules.contains(msym); 1301 } 1302 1303 private Set<ModuleSymbol> computeTransitiveClosure(Set<? extends ModuleSymbol> base, Set<ModuleSymbol> observable) { 1304 List<ModuleSymbol> primaryTodo = List.nil(); 1305 List<ModuleSymbol> secondaryTodo = List.nil(); 1306 1307 for (ModuleSymbol ms : base) { 1308 primaryTodo = primaryTodo.prepend(ms); 1309 } 1310 1311 Set<ModuleSymbol> result = new LinkedHashSet<>(); 1312 result.add(syms.java_base); 1313 1314 while (primaryTodo.nonEmpty() || secondaryTodo.nonEmpty()) { 1315 ModuleSymbol current; 1316 boolean isPrimaryTodo; 1317 if (primaryTodo.nonEmpty()) { 1318 current = primaryTodo.head; 1319 primaryTodo = primaryTodo.tail; 1320 isPrimaryTodo = true; 1321 } else { 1322 current = secondaryTodo.head; 1323 secondaryTodo = secondaryTodo.tail; 1324 isPrimaryTodo = false; 1325 } 1326 if (observable != null && !observable.contains(current)) 1327 continue; 1328 if (!result.add(current) || current == syms.unnamedModule || ((current.flags_field & Flags.AUTOMATIC_MODULE) != 0)) 1329 continue; 1330 current.complete(); 1331 if (current.kind == ERR && isPrimaryTodo && warnedMissing.add(current)) { 1332 log.error(Errors.ModuleNotFound(current)); 1333 } 1334 for (RequiresDirective rd : current.requires) { 1335 if (rd.module == syms.java_base) continue; 1336 if ((rd.isTransitive() && isPrimaryTodo) || base.contains(current)) { 1337 primaryTodo = primaryTodo.prepend(rd.module); 1338 } else { 1339 secondaryTodo = secondaryTodo.prepend(rd.module); 1340 } 1341 } 1342 } 1343 1344 return result; 1345 } 1346 1347 public ModuleSymbol getObservableModule(Name name) { 1348 ModuleSymbol mod = syms.getModule(name); 1349 1350 if (allModules().contains(mod)) { 1351 return mod; 1352 } 1353 1354 return null; 1355 } 1356 1357 private Completer getUnnamedModuleCompleter() { 1358 moduleFinder.findAllModules(); 1359 return new Symbol.Completer() { 1360 @Override 1361 public void complete(Symbol sym) throws CompletionFailure { 1362 if (inInitModules) { 1363 sym.completer = this; 1364 return ; 1365 } 1366 ModuleSymbol msym = (ModuleSymbol) sym; 1367 Set<ModuleSymbol> allModules = new HashSet<>(allModules()); 1368 allModules.remove(syms.unnamedModule); 1369 for (ModuleSymbol m : allModules) { 1370 m.complete(); 1371 } 1372 initVisiblePackages(msym, allModules); 1373 } 1374 1375 @Override 1376 public String toString() { 1377 return "unnamedModule Completer"; 1378 } 1379 }; 1380 } 1381 1382 private final Map<ModuleSymbol, Set<ModuleSymbol>> requiresTransitiveCache = new HashMap<>(); 1383 1384 private void completeModule(ModuleSymbol msym) { 1385 if (inInitModules) { 1386 msym.completer = sym -> completeModule(msym); 1387 return ; 1388 } 1389 1390 if ((msym.flags_field & Flags.AUTOMATIC_MODULE) != 0) { 1391 completeAutomaticModule(msym); 1392 } 1393 1394 Assert.checkNonNull(msym.requires); 1395 1396 initAddReads(); 1397 1398 msym.requires = msym.requires.appendList(List.from(addReads.getOrDefault(msym, Collections.emptySet()))); 1399 1400 List<RequiresDirective> requires = msym.requires; 1401 1402 while (requires.nonEmpty()) { 1403 if (!allModules().contains(requires.head.module)) { 1404 Env<AttrContext> env = typeEnvs.get(msym); 1405 if (env != null) { 1406 JavaFileObject origSource = log.useSource(env.toplevel.sourcefile); 1407 try { 1408 log.error(/*XXX*/env.tree, Errors.ModuleNotFound(requires.head.module)); 1409 } finally { 1410 log.useSource(origSource); 1411 } 1412 } else { 1413 Assert.check((msym.flags() & Flags.AUTOMATIC_MODULE) == 0); 1414 } 1415 msym.requires = List.filter(msym.requires, requires.head); 1416 } 1417 requires = requires.tail; 1418 } 1419 1420 Set<ModuleSymbol> readable = new LinkedHashSet<>(); 1421 Set<ModuleSymbol> requiresTransitive = new HashSet<>(); 1422 1423 for (RequiresDirective d : msym.requires) { 1424 d.module.complete(); 1425 readable.add(d.module); 1426 Set<ModuleSymbol> s = retrieveRequiresTransitive(d.module); 1427 Assert.checkNonNull(s, () -> "no entry in cache for " + d.module); 1428 readable.addAll(s); 1429 if (d.flags.contains(RequiresFlag.TRANSITIVE)) { 1430 requiresTransitive.add(d.module); 1431 requiresTransitive.addAll(s); 1432 } 1433 } 1434 1435 requiresTransitiveCache.put(msym, requiresTransitive); 1436 initVisiblePackages(msym, readable); 1437 for (ExportsDirective d: msym.exports) { 1438 if (d.packge != null) { 1439 d.packge.modle = msym; 1440 } 1441 } 1442 1443 } 1444 1445 private Set<ModuleSymbol> retrieveRequiresTransitive(ModuleSymbol msym) { 1446 Set<ModuleSymbol> requiresTransitive = requiresTransitiveCache.get(msym); 1447 1448 if (requiresTransitive == null) { 1449 //the module graph may contain cycles involving automatic modules or --add-reads edges 1450 requiresTransitive = new HashSet<>(); 1451 1452 Set<ModuleSymbol> seen = new HashSet<>(); 1453 List<ModuleSymbol> todo = List.of(msym); 1454 1455 while (todo.nonEmpty()) { 1456 ModuleSymbol current = todo.head; 1457 todo = todo.tail; 1458 if (!seen.add(current)) 1459 continue; 1460 requiresTransitive.add(current); 1461 current.complete(); 1462 Iterable<? extends RequiresDirective> requires; 1463 if (current != syms.unnamedModule) { 1464 Assert.checkNonNull(current.requires, () -> current + ".requires == null; " + msym); 1465 requires = current.requires; 1466 for (RequiresDirective rd : requires) { 1467 if (rd.isTransitive()) 1468 todo = todo.prepend(rd.module); 1469 } 1470 } else { 1471 for (ModuleSymbol mod : allModules()) { 1472 todo = todo.prepend(mod); 1473 } 1474 } 1475 } 1476 1477 requiresTransitive.remove(msym); 1478 } 1479 1480 return requiresTransitive; 1481 } 1482 1483 private void initVisiblePackages(ModuleSymbol msym, Collection<ModuleSymbol> readable) { 1484 initAddExports(); 1485 1486 msym.visiblePackages = new LinkedHashMap<>(); 1487 msym.readModules = new HashSet<>(readable); 1488 1489 Map<Name, ModuleSymbol> seen = new HashMap<>(); 1490 1491 for (ModuleSymbol rm : readable) { 1492 if (rm == syms.unnamedModule) 1493 continue; 1494 addVisiblePackages(msym, seen, rm, rm.exports); 1495 } 1496 1497 addExports.forEach((exportsFrom, exports) -> { 1498 addVisiblePackages(msym, seen, exportsFrom, exports); 1499 }); 1500 } 1501 1502 private void addVisiblePackages(ModuleSymbol msym, 1503 Map<Name, ModuleSymbol> seenPackages, 1504 ModuleSymbol exportsFrom, 1505 Collection<ExportsDirective> exports) { 1506 for (ExportsDirective d : exports) { 1507 if (d.modules == null || d.modules.contains(msym)) { 1508 Name packageName = d.packge.fullname; 1509 ModuleSymbol previousModule = seenPackages.get(packageName); 1510 1511 if (previousModule != null && previousModule != exportsFrom) { 1512 Env<AttrContext> env = typeEnvs.get(msym); 1513 JavaFileObject origSource = env != null ? log.useSource(env.toplevel.sourcefile) 1514 : null; 1515 DiagnosticPosition pos = env != null ? env.tree.pos() : null; 1516 try { 1517 log.error(pos, Errors.PackageClashFromRequires(msym, packageName, 1518 previousModule, exportsFrom)); 1519 } finally { 1520 if (env != null) 1521 log.useSource(origSource); 1522 } 1523 continue; 1524 } 1525 1526 seenPackages.put(packageName, exportsFrom); 1527 msym.visiblePackages.put(d.packge.fullname, d.packge); 1528 } 1529 } 1530 } 1531 1532 private void initAddExports() { 1533 if (addExports != null) 1534 return; 1535 1536 addExports = new LinkedHashMap<>(); 1537 Set<ModuleSymbol> unknownModules = new HashSet<>(); 1538 1539 if (addExportsOpt == null) 1540 return; 1541 1542 Pattern ep = Pattern.compile("([^/]+)/([^=]+)=(.*)"); 1543 for (String s: addExportsOpt.split("\0+")) { 1544 if (s.isEmpty()) 1545 continue; 1546 Matcher em = ep.matcher(s); 1547 if (!em.matches()) { 1548 continue; 1549 } 1550 1551 // Terminology comes from 1552 // --add-exports module/package=target,... 1553 // Compare to 1554 // module module { exports package to target, ... } 1555 String moduleName = em.group(1); 1556 String packageName = em.group(2); 1557 String targetNames = em.group(3); 1558 1559 if (!isValidName(moduleName)) 1560 continue; 1561 1562 ModuleSymbol msym = syms.enterModule(names.fromString(moduleName)); 1563 if (!isKnownModule(msym, unknownModules)) 1564 continue; 1565 1566 if (!isValidName(packageName)) 1567 continue; 1568 PackageSymbol p = syms.enterPackage(msym, names.fromString(packageName)); 1569 p.modle = msym; // TODO: do we need this? 1570 1571 List<ModuleSymbol> targetModules = List.nil(); 1572 for (String toModule : targetNames.split("[ ,]+")) { 1573 ModuleSymbol m; 1574 if (toModule.equals("ALL-UNNAMED")) { 1575 m = syms.unnamedModule; 1576 } else { 1577 if (!isValidName(toModule)) 1578 continue; 1579 m = syms.enterModule(names.fromString(toModule)); 1580 if (!isKnownModule(m, unknownModules)) 1581 continue; 1582 } 1583 targetModules = targetModules.prepend(m); 1584 } 1585 1586 Set<ExportsDirective> extra = addExports.computeIfAbsent(msym, _x -> new LinkedHashSet<>()); 1587 ExportsDirective d = new ExportsDirective(p, targetModules); 1588 extra.add(d); 1589 } 1590 } 1591 1592 private boolean isKnownModule(ModuleSymbol msym, Set<ModuleSymbol> unknownModules) { 1593 if (allModules.contains(msym)) { 1594 return true; 1595 } 1596 1597 if (!unknownModules.contains(msym)) { 1598 if (lintOptions) { 1599 log.warning(LintCategory.OPTIONS, 1600 Warnings.ModuleForOptionNotFound(Option.ADD_EXPORTS, msym)); 1601 } 1602 unknownModules.add(msym); 1603 } 1604 return false; 1605 } 1606 1607 private void initAddReads() { 1608 if (addReads != null) 1609 return; 1610 1611 addReads = new LinkedHashMap<>(); 1612 1613 if (addReadsOpt == null) 1614 return; 1615 1616 Pattern rp = Pattern.compile("([^=]+)=(.*)"); 1617 for (String s : addReadsOpt.split("\0+")) { 1618 if (s.isEmpty()) 1619 continue; 1620 Matcher rm = rp.matcher(s); 1621 if (!rm.matches()) { 1622 continue; 1623 } 1624 1625 // Terminology comes from 1626 // --add-reads source-module=target-module,... 1627 // Compare to 1628 // module source-module { requires target-module; ... } 1629 String sourceName = rm.group(1); 1630 String targetNames = rm.group(2); 1631 1632 if (!isValidName(sourceName)) 1633 continue; 1634 1635 ModuleSymbol msym = syms.enterModule(names.fromString(sourceName)); 1636 if (!allModules.contains(msym)) { 1637 if (lintOptions) { 1638 log.warning(Warnings.ModuleForOptionNotFound(Option.ADD_READS, msym)); 1639 } 1640 continue; 1641 } 1642 1643 for (String targetName : targetNames.split("[ ,]+", -1)) { 1644 ModuleSymbol targetModule; 1645 if (targetName.equals("ALL-UNNAMED")) { 1646 targetModule = syms.unnamedModule; 1647 } else { 1648 if (!isValidName(targetName)) 1649 continue; 1650 targetModule = syms.enterModule(names.fromString(targetName)); 1651 if (!allModules.contains(targetModule)) { 1652 if (lintOptions) { 1653 log.warning(LintCategory.OPTIONS, Warnings.ModuleForOptionNotFound(Option.ADD_READS, targetModule)); 1654 } 1655 continue; 1656 } 1657 } 1658 addReads.computeIfAbsent(msym, m -> new HashSet<>()) 1659 .add(new RequiresDirective(targetModule, EnumSet.of(RequiresFlag.EXTRA))); 1660 } 1661 } 1662 } 1663 1664 private void checkCyclicDependencies(JCModuleDecl mod) { 1665 for (JCDirective d : mod.directives) { 1666 JCRequires rd; 1667 if (!d.hasTag(Tag.REQUIRES) || (rd = (JCRequires) d).directive == null) 1668 continue; 1669 Set<ModuleSymbol> nonSyntheticDeps = new HashSet<>(); 1670 List<ModuleSymbol> queue = List.of(rd.directive.module); 1671 while (queue.nonEmpty()) { 1672 ModuleSymbol current = queue.head; 1673 queue = queue.tail; 1674 if (!nonSyntheticDeps.add(current)) 1675 continue; 1676 current.complete(); 1677 if ((current.flags() & Flags.ACYCLIC) != 0) 1678 continue; 1679 Assert.checkNonNull(current.requires, current::toString); 1680 for (RequiresDirective dep : current.requires) { 1681 if (!dep.flags.contains(RequiresFlag.EXTRA)) 1682 queue = queue.prepend(dep.module); 1683 } 1684 } 1685 if (nonSyntheticDeps.contains(mod.sym)) { 1686 log.error(rd.moduleName.pos(), Errors.CyclicRequires(rd.directive.module)); 1687 } 1688 mod.sym.flags_field |= Flags.ACYCLIC; 1689 } 1690 } 1691 1692 private boolean isValidName(CharSequence name) { 1693 return SourceVersion.isName(name, Source.toSourceVersion(source)); 1694 } 1695 1696 // DEBUG 1697 private String toString(ModuleSymbol msym) { 1698 return msym.name + "[" 1699 + "kind:" + msym.kind + ";" 1700 + "locn:" + toString(msym.sourceLocation) + "," + toString(msym.classLocation) + ";" 1701 + "info:" + toString(msym.module_info.sourcefile) + "," 1702 + toString(msym.module_info.classfile) + "," 1703 + msym.module_info.completer 1704 + "]"; 1705 } 1706 1707 // DEBUG 1708 String toString(Location locn) { 1709 return (locn == null) ? "--" : locn.getName(); 1710 } 1711 1712 // DEBUG 1713 String toString(JavaFileObject fo) { 1714 return (fo == null) ? "--" : fo.getName(); 1715 } 1716 1717 public void newRound() { 1718 allModules = null; 1719 rootModules = null; 1720 warnedMissing.clear(); 1721 } 1722 1723 public interface PackageNameFinder { 1724 public Name findPackageNameOf(JavaFileObject jfo); 1725 } 1726} 1727