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