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