1 /*
   2  * Copyright (c) 2005, 2025, 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 package com.sun.tools.javac.file;
  27 
  28 import java.io.File;
  29 import java.io.IOException;
  30 import java.io.UncheckedIOException;
  31 import java.lang.module.Configuration;
  32 import java.lang.module.ModuleFinder;
  33 import java.net.MalformedURLException;
  34 import java.net.URI;
  35 import java.net.URISyntaxException;
  36 import java.net.URL;
  37 import java.nio.CharBuffer;
  38 import java.nio.charset.Charset;
  39 import java.nio.file.FileSystem;
  40 import java.nio.file.FileSystems;
  41 import java.nio.file.FileVisitOption;
  42 import java.nio.file.FileVisitResult;
  43 import java.nio.file.Files;
  44 import java.nio.file.InvalidPathException;
  45 import java.nio.file.LinkOption;
  46 import java.nio.file.Path;
  47 import java.nio.file.Paths;
  48 import java.nio.file.ProviderNotFoundException;
  49 import java.nio.file.SimpleFileVisitor;
  50 import java.nio.file.attribute.BasicFileAttributes;
  51 import java.nio.file.spi.FileSystemProvider;
  52 import java.util.ArrayList;
  53 import java.util.Arrays;
  54 import java.util.Collection;
  55 import java.util.Collections;
  56 import java.util.Comparator;
  57 import java.util.HashMap;
  58 import java.util.Iterator;
  59 import java.util.Map;
  60 import java.util.Objects;
  61 import java.util.ServiceLoader;
  62 import java.util.Set;
  63 import java.util.stream.Stream;
  64 import java.util.zip.ZipException;
  65 
  66 import javax.lang.model.SourceVersion;
  67 import javax.tools.FileObject;
  68 import javax.tools.JavaFileManager;
  69 import javax.tools.JavaFileObject;
  70 import javax.tools.StandardJavaFileManager;
  71 
  72 import com.sun.tools.javac.file.RelativePath.RelativeDirectory;
  73 import com.sun.tools.javac.file.RelativePath.RelativeFile;
  74 import com.sun.tools.javac.main.JavaCompiler;
  75 import com.sun.tools.javac.main.JavaCompiler.CodeReflectionSupport;
  76 import com.sun.tools.javac.main.Option;
  77 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  78 import com.sun.tools.javac.util.Assert;
  79 import com.sun.tools.javac.util.Context;
  80 import com.sun.tools.javac.util.Context.Factory;
  81 import com.sun.tools.javac.util.DefinedBy;
  82 import com.sun.tools.javac.util.DefinedBy.Api;
  83 import com.sun.tools.javac.util.List;
  84 import com.sun.tools.javac.util.ListBuffer;
  85 import com.sun.tools.javac.util.Options;
  86 
  87 import static java.nio.charset.StandardCharsets.US_ASCII;
  88 import static java.nio.file.FileVisitOption.FOLLOW_LINKS;
  89 
  90 import static javax.tools.StandardLocation.*;
  91 
  92 /**
  93  * This class provides access to the source, class and other files
  94  * used by the compiler and related tools.
  95  *
  96  * <p><b>This is NOT part of any supported API.
  97  * If you write code that depends on this, you do so at your own risk.
  98  * This code and its internal interfaces are subject to change or
  99  * deletion without notice.</b>
 100  */
 101 public class JavacFileManager extends BaseFileManager implements StandardJavaFileManager {
 102 
 103     public static char[] toArray(CharBuffer buffer) {
 104         if (buffer.hasArray())
 105             return buffer.compact().flip().array();
 106         else
 107             return buffer.toString().toCharArray();
 108     }
 109 
 110     private FSInfo fsInfo;
 111 
 112     private static final Set<JavaFileObject.Kind> SOURCE_OR_CLASS =
 113         Set.of(JavaFileObject.Kind.SOURCE, JavaFileObject.Kind.CLASS);
 114 
 115     protected boolean symbolFileEnabled = true;
 116 
 117     private PathFactory pathFactory = Paths::get;
 118 
 119     protected enum SortFiles implements Comparator<Path> {
 120         FORWARD {
 121             @Override
 122             public int compare(Path f1, Path f2) {
 123                 return f1.getFileName().compareTo(f2.getFileName());
 124             }
 125         },
 126         REVERSE {
 127             @Override
 128             public int compare(Path f1, Path f2) {
 129                 return f2.getFileName().compareTo(f1.getFileName());
 130             }
 131         }
 132     }
 133 
 134     protected SortFiles sortFiles;
 135 
 136     /**
 137      * We use a two-layered map instead of a map with a complex key because we don't want to reindex
 138      * the values for every Location+RelativeDirectory pair. Once the PathsAndContainers are needed
 139      * for a single Location, we should know all valid RelativeDirectory mappings. Because the
 140      * indexing is costly for very large classpaths, this can result in a significant savings.
 141      */
 142     private Map<Location, Map<RelativeDirectory, java.util.List<PathAndContainer>>>
 143         pathsAndContainersByLocationAndRelativeDirectory = new HashMap<>();
 144 
 145     /** Containers that have no indexing by {@link RelativeDirectory}, keyed by {@link Location}. */
 146     private Map<Location, java.util.List<PathAndContainer>> nonIndexingContainersByLocation =
 147         new HashMap<>();
 148 
 149     /**
 150      * Register a Context.Factory to create a JavacFileManager.
 151      */
 152     public static void preRegister(Context context) {
 153         context.put(JavaFileManager.class,
 154                 (Factory<JavaFileManager>)c -> new JavacFileManager(c, true, null));
 155     }
 156 
 157     /**
 158      * Create a JavacFileManager using a given context, optionally registering
 159      * it as the JavaFileManager for that context.
 160      */
 161     @SuppressWarnings("this-escape")
 162     public JavacFileManager(Context context, boolean register, Charset charset) {
 163         super(charset);
 164         if (register)
 165             context.put(JavaFileManager.class, this);
 166         setContext(context);
 167     }
 168 
 169     /**
 170      * Set the context for JavacFileManager.
 171      */
 172     @Override
 173     public void setContext(Context context) {
 174         super.setContext(context);
 175         fsInfo = FSInfo.instance(context);
 176     }
 177 
 178     @Override
 179     protected void applyOptions(Options options) {
 180         super.applyOptions(options);
 181 
 182         symbolFileEnabled = !options.isSet("ignore.symbol.file");
 183 
 184         String sf = options.get("sortFiles");
 185         if (sf != null) {
 186             sortFiles = (sf.equals("reverse") ? SortFiles.REVERSE : SortFiles.FORWARD);
 187         }
 188     }
 189 
 190     @Override @DefinedBy(DefinedBy.Api.COMPILER)
 191     public void setPathFactory(PathFactory f) {
 192         pathFactory = Objects.requireNonNull(f);
 193         locations.setPathFactory(f);
 194     }
 195 
 196     private Path getPath(String first, String... more) {
 197         return pathFactory.getPath(first, more);
 198     }
 199 
 200     /**
 201      * Set whether or not to use ct.sym as an alternate to the current runtime.
 202      */
 203     public void setSymbolFileEnabled(boolean b) {
 204         symbolFileEnabled = b;
 205     }
 206 
 207     public boolean isSymbolFileEnabled() {
 208         return symbolFileEnabled;
 209     }
 210 
 211     // used by tests
 212     public JavaFileObject getJavaFileObject(String name) {
 213         return getJavaFileObjects(name).iterator().next();
 214     }
 215 
 216     // used by tests
 217     public JavaFileObject getJavaFileObject(Path file) {
 218         return getJavaFileObjects(file).iterator().next();
 219     }
 220 
 221     public JavaFileObject getFileForOutput(String classname,
 222                                            JavaFileObject.Kind kind,
 223                                            JavaFileObject sibling)
 224         throws IOException
 225     {
 226         return getJavaFileForOutput(CLASS_OUTPUT, classname, kind, sibling);
 227     }
 228 
 229     @Override @DefinedBy(Api.COMPILER)
 230     public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
 231         ListBuffer<Path> paths = new ListBuffer<>();
 232         for (String name : names)
 233             paths.append(getPath(nullCheck(name)));
 234         return getJavaFileObjectsFromPaths(paths.toList());
 235     }
 236 
 237     @Override @DefinedBy(Api.COMPILER)
 238     public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
 239         return getJavaFileObjectsFromStrings(Arrays.asList(nullCheck(names)));
 240     }
 241 
 242     private static boolean isValidName(String name) {
 243         // Arguably, isValidName should reject keywords (such as in SourceVersion.isName() ),
 244         // but the set of keywords depends on the source level, and we don't want
 245         // impls of JavaFileManager to have to be dependent on the source level.
 246         // Therefore we simply check that the argument is a sequence of identifiers
 247         // separated by ".".
 248         for (String s : name.split("\\.", -1)) {
 249             if (!SourceVersion.isIdentifier(s))
 250                 return false;
 251         }
 252         return true;
 253     }
 254 
 255     private static void validateClassName(String className) {
 256         if (!isValidName(className))
 257             throw new IllegalArgumentException("Invalid class name: " + className);
 258     }
 259 
 260     private static void validatePackageName(String packageName) {
 261         if (packageName.length() > 0 && !isValidName(packageName))
 262             throw new IllegalArgumentException("Invalid packageName name: " + packageName);
 263     }
 264 
 265     public static void testName(String name,
 266                                 boolean isValidPackageName,
 267                                 boolean isValidClassName)
 268     {
 269         try {
 270             validatePackageName(name);
 271             if (!isValidPackageName)
 272                 throw new AssertionError("Invalid package name accepted: " + name);
 273             printAscii("Valid package name: \"%s\"", name);
 274         } catch (IllegalArgumentException e) {
 275             if (isValidPackageName)
 276                 throw new AssertionError("Valid package name rejected: " + name);
 277             printAscii("Invalid package name: \"%s\"", name);
 278         }
 279         try {
 280             validateClassName(name);
 281             if (!isValidClassName)
 282                 throw new AssertionError("Invalid class name accepted: " + name);
 283             printAscii("Valid class name: \"%s\"", name);
 284         } catch (IllegalArgumentException e) {
 285             if (isValidClassName)
 286                 throw new AssertionError("Valid class name rejected: " + name);
 287             printAscii("Invalid class name: \"%s\"", name);
 288         }
 289     }
 290 
 291     private static void printAscii(String format, Object... args) {
 292         String message = new String(
 293                 String.format(null, format, args).getBytes(US_ASCII), US_ASCII);
 294         System.out.println(message);
 295     }
 296 
 297     private final Map<Path, Container> containers = new HashMap<>();
 298 
 299     synchronized Container getContainer(Path path) throws IOException {
 300         Container fs = containers.get(path);
 301 
 302         if (fs != null) {
 303             return fs;
 304         }
 305 
 306         if (fsInfo.isFile(path) && path.equals(Locations.thisSystemModules)) {
 307             containers.put(path, fs = new JRTImageContainer());
 308             return fs;
 309         }
 310 
 311         Path realPath = fsInfo.getCanonicalFile(path);
 312 
 313         fs = containers.get(realPath);
 314 
 315         if (fs != null) {
 316             containers.put(path, fs);
 317             return fs;
 318         }
 319 
 320         BasicFileAttributes attr = null;
 321 
 322         try {
 323             attr = Files.readAttributes(realPath, BasicFileAttributes.class);
 324         } catch (IOException ex) {
 325             //non-existing
 326             fs = MISSING_CONTAINER;
 327         }
 328 
 329         if (attr != null) {
 330             if (attr.isDirectory()) {
 331                 fs = new DirectoryContainer(realPath);
 332             } else {
 333                 try {
 334                     fs = new ArchiveContainer(path);
 335                 } catch (ProviderNotFoundException ex) {
 336                     throw new IOException(ex);
 337                 }
 338             }
 339         }
 340 
 341         containers.put(realPath, fs);
 342         containers.put(path, fs);
 343 
 344         return fs;
 345     }
 346 
 347     private interface Container {
 348         /**
 349          * Insert all files in subdirectory subdirectory of container which
 350          * match fileKinds into resultList
 351          */
 352         public abstract void list(Path userPath,
 353                                   RelativeDirectory subdirectory,
 354                                   Set<JavaFileObject.Kind> fileKinds,
 355                                   boolean recurse,
 356                                   ListBuffer<JavaFileObject> resultList) throws IOException;
 357         public abstract JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException;
 358         public abstract void close() throws IOException;
 359         public abstract boolean maintainsDirectoryIndex();
 360 
 361         /**
 362          * The directories this container indexes if {@link #maintainsDirectoryIndex()}, otherwise
 363          * an empty iterable.
 364          */
 365         public abstract Iterable<RelativeDirectory> indexedDirectories();
 366     }
 367 
 368     private static final Container MISSING_CONTAINER =  new Container() {
 369         @Override
 370         public void list(Path userPath,
 371                          RelativeDirectory subdirectory,
 372                          Set<JavaFileObject.Kind> fileKinds,
 373                          boolean recurse,
 374                          ListBuffer<JavaFileObject> resultList) throws IOException {
 375         }
 376         @Override
 377         public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
 378             return null;
 379         }
 380         @Override
 381         public void close() throws IOException {}
 382         @Override
 383         public boolean maintainsDirectoryIndex() {
 384             return false;
 385         }
 386         @Override
 387         public Iterable<RelativeDirectory> indexedDirectories() {
 388             return List.nil();
 389         }
 390     };
 391 
 392     private final class JRTImageContainer implements Container {
 393 
 394         /**
 395          * Insert all files in a subdirectory of the platform image
 396          * which match fileKinds into resultList.
 397          */
 398         @Override
 399         public void list(Path userPath,
 400                          RelativeDirectory subdirectory,
 401                          Set<JavaFileObject.Kind> fileKinds,
 402                          boolean recurse,
 403                          ListBuffer<JavaFileObject> resultList) throws IOException {
 404             try {
 405                 JRTIndex.Entry e = getJRTIndex().getEntry(subdirectory);
 406                 if (symbolFileEnabled && e.ctSym.hidden)
 407                     return;
 408                 for (Path file: e.files.values()) {
 409                     if (fileKinds.contains(getKind(file))) {
 410                         JavaFileObject fe
 411                                 = PathFileObject.forJRTPath(JavacFileManager.this, file);
 412                         resultList.append(fe);
 413                     }
 414                 }
 415 
 416                 if (recurse) {
 417                     for (RelativeDirectory rd: e.subdirs) {
 418                         list(userPath, rd, fileKinds, recurse, resultList);
 419                     }
 420                 }
 421             } catch (IOException ex) {
 422                 ex.printStackTrace(System.err);
 423                 log.error(Errors.ErrorReadingFile(userPath, getMessage(ex)));
 424             }
 425         }
 426 
 427         @Override
 428         public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
 429             JRTIndex.Entry e = getJRTIndex().getEntry(name.dirname());
 430             if (symbolFileEnabled && e.ctSym.hidden)
 431                 return null;
 432             Path p = e.files.get(name.basename());
 433             if (p != null) {
 434                 return PathFileObject.forJRTPath(JavacFileManager.this, p);
 435             } else {
 436                 return null;
 437             }
 438         }
 439 
 440         @Override
 441         public void close() throws IOException {
 442         }
 443 
 444         @Override
 445         public boolean maintainsDirectoryIndex() {
 446             return false;
 447         }
 448 
 449         @Override
 450         public Iterable<RelativeDirectory> indexedDirectories() {
 451             return List.nil();
 452         }
 453     }
 454 
 455     private synchronized JRTIndex getJRTIndex() {
 456         if (jrtIndex == null)
 457             jrtIndex = JRTIndex.getSharedInstance();
 458         return jrtIndex;
 459     }
 460 
 461     private JRTIndex jrtIndex;
 462 
 463     private final class DirectoryContainer implements Container {
 464         private final Path directory;
 465 
 466         public DirectoryContainer(Path directory) {
 467             this.directory = directory;
 468         }
 469 
 470         /**
 471          * Insert all files in subdirectory subdirectory of directory userPath
 472          * which match fileKinds into resultList
 473          */
 474         @Override
 475         public void list(Path userPath,
 476                          RelativeDirectory subdirectory,
 477                          Set<JavaFileObject.Kind> fileKinds,
 478                          boolean recurse,
 479                          ListBuffer<JavaFileObject> resultList) throws IOException {
 480             Path d;
 481             try {
 482                 d = subdirectory.resolveAgainst(userPath);
 483             } catch (InvalidPathException ignore) {
 484                 return ;
 485             }
 486 
 487             if (!Files.exists(d)) {
 488                return;
 489             }
 490 
 491             if (!caseMapCheck(d, subdirectory)) {
 492                 return;
 493             }
 494 
 495             java.util.List<Path> files;
 496             try (Stream<Path> s = Files.list(d)) {
 497                 files = (sortFiles == null ? s : s.sorted(sortFiles)).toList();
 498             } catch (IOException ignore) {
 499                 return;
 500             }
 501 
 502             for (Path f: files) {
 503                 String fname = f.getFileName().toString();
 504                 if (fname.endsWith("/"))
 505                     fname = fname.substring(0, fname.length() - 1);
 506                 if (Files.isDirectory(f)) {
 507                     if (recurse && SourceVersion.isIdentifier(fname)) {
 508                         list(userPath,
 509                              new RelativeDirectory(subdirectory, fname),
 510                              fileKinds,
 511                              recurse,
 512                              resultList);
 513                     }
 514                 } else {
 515                     if (isValidFile(fname, fileKinds)) {
 516                         try {
 517                             RelativeFile file = new RelativeFile(subdirectory, fname);
 518                             JavaFileObject fe = PathFileObject.forDirectoryPath(JavacFileManager.this,
 519                                     file.resolveAgainst(directory), userPath, file);
 520                             resultList.append(fe);
 521                         } catch (InvalidPathException e) {
 522                             throw new IOException("error accessing directory " + directory + e);
 523                         }
 524                     }
 525                 }
 526             }
 527         }
 528 
 529         @Override
 530         public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
 531             try {
 532                 Path f = name.resolveAgainst(userPath);
 533                 if (Files.exists(f))
 534                     return PathFileObject.forSimplePath(JavacFileManager.this,
 535                             fsInfo.getCanonicalFile(f), f);
 536             } catch (InvalidPathException ignore) {
 537             }
 538             return null;
 539         }
 540 
 541         @Override
 542         public void close() throws IOException {
 543         }
 544 
 545         @Override
 546         public boolean maintainsDirectoryIndex() {
 547             return false;
 548         }
 549 
 550         @Override
 551         public Iterable<RelativeDirectory> indexedDirectories() {
 552             return List.nil();
 553         }
 554     }
 555 
 556     private static final Set<FileVisitOption> NO_FILE_VISIT_OPTIONS = Set.of();
 557     private static final Set<FileVisitOption> FOLLOW_LINKS_OPTIONS = Set.of(FOLLOW_LINKS);
 558 
 559     private final class ArchiveContainer implements Container {
 560         private final Path archivePath;
 561         private final FileSystem fileSystem;
 562         private final Map<RelativeDirectory, Path> packages;
 563 
 564         public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException {
 565             this.archivePath = archivePath;
 566             if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
 567                 FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider();
 568                 Assert.checkNonNull(jarFSProvider, "should have been caught before!");
 569                 Map<String, ?> env = fsInfo.readOnlyJarFSEnv(multiReleaseValue);
 570                 try {
 571                     this.fileSystem = jarFSProvider.newFileSystem(archivePath, env);
 572                 } catch (ZipException ze) {
 573                     throw new IOException("ZipException opening \"" + archivePath.getFileName() + "\": " + ze.getMessage(), ze);
 574                 }
 575             } else {
 576                 // Less common case is possible if the file manager was not initialized in JavacTask,
 577                 // or if non "*.jar" files are on the classpath. If this is not a ZIP/JAR file then it
 578                 // will ignore ZIP specific parameters in env, and may not end up being read-only.
 579                 // However, Javac should never attempt to write back to archives either way.
 580                 Map<String, ?> env = fsInfo.readOnlyJarFSEnv(null);
 581                 this.fileSystem = FileSystems.newFileSystem(archivePath, env);
 582             }
 583             packages = new HashMap<>();
 584             for (Path root : fileSystem.getRootDirectories()) {
 585                 Files.walkFileTree(root, NO_FILE_VISIT_OPTIONS, Integer.MAX_VALUE,
 586                         new SimpleFileVisitor<Path>() {
 587                             @Override
 588                             public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
 589                                 if (isValid(dir.getFileName())) {
 590                                     packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir);
 591                                     return FileVisitResult.CONTINUE;
 592                                 } else {
 593                                     return FileVisitResult.SKIP_SUBTREE;
 594                                 }
 595                             }
 596                         });
 597             }
 598         }
 599 
 600         /**
 601          * Insert all files in subdirectory subdirectory of this archive
 602          * which match fileKinds into resultList
 603          */
 604         @Override
 605         public void list(Path userPath,
 606                          RelativeDirectory subdirectory,
 607                          Set<JavaFileObject.Kind> fileKinds,
 608                          boolean recurse,
 609                          ListBuffer<JavaFileObject> resultList) throws IOException {
 610             Path resolvedSubdirectory = packages.get(subdirectory);
 611 
 612             if (resolvedSubdirectory == null)
 613                 return ;
 614 
 615             int maxDepth = (recurse ? Integer.MAX_VALUE : 1);
 616             Files.walkFileTree(resolvedSubdirectory, FOLLOW_LINKS_OPTIONS, maxDepth,
 617                     new SimpleFileVisitor<Path>() {
 618                         @Override
 619                         public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
 620                             if (isValid(dir.getFileName())) {
 621                                 return FileVisitResult.CONTINUE;
 622                             } else {
 623                                 return FileVisitResult.SKIP_SUBTREE;
 624                             }
 625                         }
 626 
 627                         @Override
 628                         public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
 629                             if (attrs.isRegularFile() && fileKinds.contains(getKind(file.getFileName().toString()))) {
 630                                 JavaFileObject fe = PathFileObject.forJarPath(
 631                                         JavacFileManager.this, file, archivePath);
 632                                 resultList.append(fe);
 633                             }
 634                             return FileVisitResult.CONTINUE;
 635                         }
 636                     });
 637 
 638         }
 639 
 640         private boolean isValid(Path fileName) {
 641             if (fileName == null) {
 642                 return true;
 643             } else {
 644                 String name = fileName.toString();
 645                 if (name.endsWith("/")) {
 646                     name = name.substring(0, name.length() - 1);
 647                 }
 648                 return SourceVersion.isIdentifier(name);
 649             }
 650         }
 651 
 652         @Override
 653         public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
 654             RelativeDirectory root = name.dirname();
 655             Path packagepath = packages.get(root);
 656             if (packagepath != null) {
 657                 Path relpath = packagepath.resolve(name.basename());
 658                 if (Files.exists(relpath)) {
 659                     return PathFileObject.forJarPath(JavacFileManager.this, relpath, userPath);
 660                 }
 661             }
 662             return null;
 663         }
 664 
 665         @Override
 666         public void close() throws IOException {
 667             fileSystem.close();
 668         }
 669 
 670         @Override
 671         public boolean maintainsDirectoryIndex() {
 672             return true;
 673         }
 674 
 675         @Override
 676         public Iterable<RelativeDirectory> indexedDirectories() {
 677             return packages.keySet();
 678         }
 679     }
 680 
 681     /**
 682      * container is a directory, a zip file, or a non-existent path.
 683      */
 684     private boolean isValidFile(String s, Set<JavaFileObject.Kind> fileKinds) {
 685         JavaFileObject.Kind kind = getKind(s);
 686         return fileKinds.contains(kind);
 687     }
 688 
 689     private static final boolean fileSystemIsCaseSensitive =
 690         File.separatorChar == '/';
 691 
 692     /** Hack to make Windows case sensitive. Test whether given path
 693      *  ends in a string of characters with the same case as given name.
 694      *  Ignore file separators in both path and name.
 695      */
 696     private boolean caseMapCheck(Path f, RelativePath name) {
 697         if (fileSystemIsCaseSensitive) return true;
 698         // Note that toRealPath() returns the case-sensitive
 699         // spelled file name.
 700         String path;
 701         char sep;
 702         try {
 703             path = f.toRealPath(LinkOption.NOFOLLOW_LINKS).toString();
 704             sep = f.getFileSystem().getSeparator().charAt(0);
 705         } catch (IOException ex) {
 706             return false;
 707         }
 708         char[] pcs = path.toCharArray();
 709         char[] ncs = name.path.toCharArray();
 710         int i = pcs.length - 1;
 711         int j = ncs.length - 1;
 712         while (i >= 0 && j >= 0) {
 713             while (i >= 0 && pcs[i] == sep) i--;
 714             while (j >= 0 && ncs[j] == '/') j--;
 715             if (i >= 0 && j >= 0) {
 716                 if (pcs[i] != ncs[j]) return false;
 717                 i--;
 718                 j--;
 719             }
 720         }
 721         return j < 0;
 722     }
 723 
 724     /** Flush any output resources.
 725      */
 726     @Override @DefinedBy(Api.COMPILER)
 727     public void flush() {
 728         contentCache.clear();
 729         pathsAndContainersByLocationAndRelativeDirectory.clear();
 730         nonIndexingContainersByLocation.clear();
 731     }
 732 
 733     /**
 734      * Close the JavaFileManager, releasing resources.
 735      */
 736     @Override @DefinedBy(Api.COMPILER)
 737     public void close() throws IOException {
 738         if (deferredCloseTimeout > 0) {
 739             deferredClose();
 740             return;
 741         }
 742 
 743         locations.close();
 744         for (Container container: containers.values()) {
 745             container.close();
 746         }
 747         containers.clear();
 748         pathsAndContainersByLocationAndRelativeDirectory.clear();
 749         nonIndexingContainersByLocation.clear();
 750         contentCache.clear();
 751         resetOutputFilesWritten();
 752     }
 753 
 754     @Override @DefinedBy(Api.COMPILER)
 755     public ClassLoader getClassLoader(Location location) {
 756         checkNotModuleOrientedLocation(location);
 757         Iterable<? extends File> path = getLocation(location);
 758         if (path == null)
 759             return null;
 760         ListBuffer<URL> lb = new ListBuffer<>();
 761         for (File f: path) {
 762             try {
 763                 lb.append(f.toURI().toURL());
 764             } catch (MalformedURLException e) {
 765                 throw new AssertionError(e);
 766             }
 767         }
 768 
 769         return getClassLoader(lb.toArray(new URL[lb.size()]));
 770     }
 771 
 772     @Override @DefinedBy(Api.COMPILER)
 773     public Iterable<JavaFileObject> list(Location location,
 774                                          String packageName,
 775                                          Set<JavaFileObject.Kind> kinds,
 776                                          boolean recurse)
 777         throws IOException
 778     {
 779         checkNotModuleOrientedLocation(location);
 780         // validatePackageName(packageName);
 781         nullCheck(packageName);
 782         nullCheck(kinds);
 783 
 784         RelativeDirectory subdirectory = RelativeDirectory.forPackage(packageName);
 785         ListBuffer<JavaFileObject> results = new ListBuffer<>();
 786 
 787         for (PathAndContainer pathAndContainer : pathsAndContainers(location, subdirectory)) {
 788             Path directory = pathAndContainer.path;
 789             Container container = pathAndContainer.container;
 790             container.list(directory, subdirectory, kinds, recurse, results);
 791         }
 792 
 793         return results.toList();
 794     }
 795 
 796     @Override @DefinedBy(Api.COMPILER)
 797     public String inferBinaryName(Location location, JavaFileObject file) {
 798         checkNotModuleOrientedLocation(location);
 799         Objects.requireNonNull(file);
 800         // Need to match the path semantics of list(location, ...)
 801         Iterable<? extends Path> path = getLocationAsPaths(location);
 802         if (path == null) {
 803             return null;
 804         }
 805 
 806         if (file instanceof PathFileObject pathFileObject) {
 807             return pathFileObject.inferBinaryName(path);
 808         } else
 809             throw new IllegalArgumentException(file.getClass().getName());
 810     }
 811 
 812     @Override @DefinedBy(Api.COMPILER)
 813     public boolean isSameFile(FileObject a, FileObject b) {
 814         nullCheck(a);
 815         nullCheck(b);
 816         if (a instanceof PathFileObject pathFileObjectA && b instanceof PathFileObject pathFileObjectB)
 817             return pathFileObjectA.isSameFile(pathFileObjectB);
 818         return a.equals(b);
 819     }
 820 
 821     @Override @DefinedBy(Api.COMPILER)
 822     public boolean hasLocation(Location location) {
 823         nullCheck(location);
 824         return locations.hasLocation(location);
 825     }
 826 
 827     protected boolean hasExplicitLocation(Location location) {
 828         nullCheck(location);
 829         return locations.hasExplicitLocation(location);
 830     }
 831 
 832     @Override @DefinedBy(Api.COMPILER)
 833     public JavaFileObject getJavaFileForInput(Location location,
 834                                               String className,
 835                                               JavaFileObject.Kind kind)
 836         throws IOException
 837     {
 838         checkNotModuleOrientedLocation(location);
 839         // validateClassName(className);
 840         nullCheck(className);
 841         nullCheck(kind);
 842         if (!SOURCE_OR_CLASS.contains(kind))
 843             throw new IllegalArgumentException("Invalid kind: " + kind);
 844         return getFileForInput(location, RelativeFile.forClass(className, kind));
 845     }
 846 
 847     @Override @DefinedBy(Api.COMPILER)
 848     public FileObject getFileForInput(Location location,
 849                                       String packageName,
 850                                       String relativeName)
 851         throws IOException
 852     {
 853         checkNotModuleOrientedLocation(location);
 854         // validatePackageName(packageName);
 855         nullCheck(packageName);
 856         if (!isRelativeUri(relativeName))
 857             throw new IllegalArgumentException("Invalid relative name: " + relativeName);
 858         RelativeFile name = packageName.length() == 0
 859             ? new RelativeFile(relativeName)
 860             : new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName);
 861         return getFileForInput(location, name);
 862     }
 863 
 864     private JavaFileObject getFileForInput(Location location, RelativeFile name) throws IOException {
 865         Iterable<? extends Path> path = getLocationAsPaths(location);
 866         if (path == null)
 867             return null;
 868 
 869         for (Path file: path) {
 870             JavaFileObject fo = getContainer(file).getFileObject(file, name);
 871 
 872             if (fo != null) {
 873                 return fo;
 874             }
 875         }
 876         return null;
 877     }
 878 
 879     @Override @DefinedBy(Api.COMPILER)
 880     public JavaFileObject getJavaFileForOutput(Location location,
 881                                                String className,
 882                                                JavaFileObject.Kind kind,
 883                                                FileObject sibling)
 884         throws IOException
 885     {
 886         checkOutputLocation(location);
 887         // validateClassName(className);
 888         nullCheck(className);
 889         nullCheck(kind);
 890         if (!SOURCE_OR_CLASS.contains(kind))
 891             throw new IllegalArgumentException("Invalid kind: " + kind);
 892         return getFileForOutput(location, RelativeFile.forClass(className, kind), sibling);
 893     }
 894 
 895     @Override @DefinedBy(Api.COMPILER)
 896     public FileObject getFileForOutput(Location location,
 897                                        String packageName,
 898                                        String relativeName,
 899                                        FileObject sibling)
 900         throws IOException
 901     {
 902         checkOutputLocation(location);
 903         // validatePackageName(packageName);
 904         nullCheck(packageName);
 905         if (!isRelativeUri(relativeName))
 906             throw new IllegalArgumentException("Invalid relative name: " + relativeName);
 907         RelativeFile name = packageName.length() == 0
 908             ? new RelativeFile(relativeName)
 909             : new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName);
 910         return getFileForOutput(location, name, sibling);
 911     }
 912 
 913     private JavaFileObject getFileForOutput(Location location,
 914                                             RelativeFile fileName,
 915                                             FileObject sibling)
 916         throws IOException
 917     {
 918         Path dir;
 919         if (location == CLASS_OUTPUT) {
 920             if (getClassOutDir() != null) {
 921                 dir = getClassOutDir();
 922             } else {
 923                 // Sibling is the associated source of the class file (e.g. x/y/Foo.java).
 924                 // The base name for class output is the class file name (e.g. "Foo.class").
 925                 String baseName = fileName.basename();
 926                 // Use the sibling to determine the output location where possible, unless
 927                 // it is in a JAR/ZIP file (we don't attempt to write class files back into
 928                 // archives).
 929                 if (sibling instanceof PathFileObject pathFileObject && !pathFileObject.isJarFile()) {
 930                     return pathFileObject.getSibling(baseName);
 931                 } else {
 932                     // Without the sibling present, we just create an output path in the
 933                     // current working directory (this isn't great, but it is what older
 934                     // versions of the JDK did).
 935                     Path userPath = getPath(baseName);
 936                     Path realPath = fsInfo.getCanonicalFile(userPath);
 937                     return PathFileObject.forSimplePath(this, realPath, userPath);
 938                 }
 939             }
 940         } else if (location == SOURCE_OUTPUT) {
 941             dir = (getSourceOutDir() != null ? getSourceOutDir() : getClassOutDir());
 942         } else {
 943             Iterable<? extends Path> path = locations.getLocation(location);
 944             dir = null;
 945             for (Path f: path) {
 946                 dir = f;
 947                 break;
 948             }
 949         }
 950 
 951         try {
 952             if (dir == null) {
 953                 dir = getPath(System.getProperty("user.dir"));
 954             }
 955             Path path = fileName.resolveAgainst(fsInfo.getCanonicalFile(dir));
 956             return PathFileObject.forDirectoryPath(this, path, dir, fileName);
 957         } catch (InvalidPathException e) {
 958             throw new IOException("bad filename " + fileName, e);
 959         }
 960     }
 961 
 962     @Override @DefinedBy(Api.COMPILER)
 963     public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(
 964         Iterable<? extends File> files)
 965     {
 966         ArrayList<PathFileObject> result;
 967         if (files instanceof Collection<?> collection)
 968             result = new ArrayList<>(collection.size());
 969         else
 970             result = new ArrayList<>();
 971         for (File f: files) {
 972             Objects.requireNonNull(f);
 973             Path p = f.toPath();
 974             result.add(PathFileObject.forSimplePath(this,
 975                     fsInfo.getCanonicalFile(p), p));
 976         }
 977         return result;
 978     }
 979 
 980     @Override @DefinedBy(Api.COMPILER)
 981     public Iterable<? extends JavaFileObject> getJavaFileObjectsFromPaths(Collection<? extends Path> paths) {
 982         ArrayList<PathFileObject> result;
 983         if (paths != null) {
 984             result = new ArrayList<>(paths.size());
 985             for (Path p: paths)
 986                 result.add(PathFileObject.forSimplePath(this,
 987                         fsInfo.getCanonicalFile(p), p));
 988         } else {
 989             result = new ArrayList<>();
 990         }
 991         return result;
 992     }
 993 
 994     @Override @DefinedBy(Api.COMPILER)
 995     public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
 996         return getJavaFileObjectsFromFiles(Arrays.asList(nullCheck(files)));
 997     }
 998 
 999     @Override @DefinedBy(Api.COMPILER)
1000     public Iterable<? extends JavaFileObject> getJavaFileObjects(Path... paths) {
1001         return getJavaFileObjectsFromPaths(Arrays.asList(nullCheck(paths)));
1002     }
1003 
1004     @Override @DefinedBy(Api.COMPILER)
1005     public void setLocation(Location location,
1006                             Iterable<? extends File> searchpath)
1007         throws IOException
1008     {
1009         nullCheck(location);
1010         locations.setLocation(location, asPaths(searchpath));
1011         clearCachesForLocation(location);
1012     }
1013 
1014     @Override @DefinedBy(Api.COMPILER)
1015     public void setLocationFromPaths(Location location,
1016                             Collection<? extends Path> searchpath)
1017         throws IOException
1018     {
1019         nullCheck(location);
1020         locations.setLocation(location, nullCheck(searchpath));
1021         clearCachesForLocation(location);
1022     }
1023 
1024     @Override @DefinedBy(Api.COMPILER)
1025     public Iterable<? extends File> getLocation(Location location) {
1026         nullCheck(location);
1027         return asFiles(locations.getLocation(location));
1028     }
1029 
1030     @Override @DefinedBy(Api.COMPILER)
1031     public Collection<? extends Path> getLocationAsPaths(Location location) {
1032         nullCheck(location);
1033         return locations.getLocation(location);
1034     }
1035 
1036     private java.util.List<PathAndContainer> pathsAndContainers(
1037             Location location, RelativeDirectory relativeDirectory) throws IOException {
1038         try {
1039             return pathsAndContainersByLocationAndRelativeDirectory.computeIfAbsent(
1040                     location, this::indexPathsAndContainersByRelativeDirectory)
1041                 .computeIfAbsent(
1042                     relativeDirectory, d -> nonIndexingContainersByLocation.get(location));
1043         } catch (UncheckedIOException e) {
1044             throw e.getCause();
1045         }
1046     }
1047 
1048     private Map<RelativeDirectory, java.util.List<PathAndContainer>> indexPathsAndContainersByRelativeDirectory(
1049             Location location) {
1050         Map<RelativeDirectory, java.util.List<PathAndContainer>> result = new HashMap<>();
1051         java.util.List<PathAndContainer> allPathsAndContainers = pathsAndContainers(location);
1052 
1053         // First collect all of the containers that don't maintain their own index on
1054         // RelativeDirectory. These need to always be included for all mappings
1055         java.util.List<PathAndContainer> nonIndexingContainers = new ArrayList<>();
1056         for (PathAndContainer pathAndContainer : allPathsAndContainers) {
1057             if (!pathAndContainer.container.maintainsDirectoryIndex()) {
1058                 nonIndexingContainers.add(pathAndContainer);
1059             }
1060         }
1061 
1062         // Next, use the container that do maintain their own RelativeDirectory index to create a
1063         // single master index.
1064         for (PathAndContainer pathAndContainer : allPathsAndContainers) {
1065             Container container = pathAndContainer.container;
1066             if (container.maintainsDirectoryIndex()) {
1067                 for (RelativeDirectory directory : container.indexedDirectories()) {
1068                     result.computeIfAbsent(directory, d -> new ArrayList<>(nonIndexingContainers))
1069                           .add(pathAndContainer);
1070                 }
1071             }
1072         }
1073         nonIndexingContainersByLocation.put(location, nonIndexingContainers);
1074 
1075         // Sorting preserves the search order used in the uncached Location path, which has
1076         // maintains consistency with the classpath order
1077         result.values().forEach(pathAndContainerList -> Collections.sort(pathAndContainerList));
1078 
1079         return result;
1080     }
1081 
1082     /**
1083      * For each {@linkplain #getLocationAsPaths(Location) path of the location}, compute the
1084      * corresponding {@link Container}.
1085      */
1086     private java.util.List<PathAndContainer> pathsAndContainers(Location location) {
1087         Collection<? extends Path> paths = getLocationAsPaths(location);
1088         if (paths == null) {
1089             return List.nil();
1090         }
1091         java.util.List<PathAndContainer> pathsAndContainers =
1092             new ArrayList<>(paths.size());
1093         for (Path path : paths) {
1094             Container container;
1095             try {
1096                 container = getContainer(path);
1097             } catch (IOException e) {
1098                 throw new UncheckedIOException(e);
1099             }
1100             pathsAndContainers.add(new PathAndContainer(path, container, pathsAndContainers.size()));
1101         }
1102         return pathsAndContainers;
1103     }
1104 
1105     private static class PathAndContainer implements Comparable<PathAndContainer> {
1106         private final Path path;
1107         private final Container container;
1108         private final int index;
1109 
1110         PathAndContainer(Path path, Container container, int index) {
1111             this.path = path;
1112             this.container = container;
1113             this.index = index;
1114         }
1115 
1116         @Override
1117         public int compareTo(PathAndContainer other) {
1118             return index - other.index;
1119         }
1120 
1121         @Override
1122         public boolean equals(Object o) {
1123             return (o instanceof PathAndContainer pathAndContainer)
1124                     && path.equals(pathAndContainer.path)
1125                     && container.equals(pathAndContainer.container)
1126                     && index == pathAndContainer.index;
1127         }
1128 
1129         @Override
1130         public int hashCode() {
1131           return Objects.hash(path, container, index);
1132         }
1133     }
1134 
1135     @Override @DefinedBy(Api.COMPILER)
1136     public boolean contains(Location location, FileObject fo) throws IOException {
1137         nullCheck(location);
1138         nullCheck(fo);
1139         Path p = asPath(fo);
1140         return locations.contains(location, p);
1141     }
1142 
1143     private Path getClassOutDir() {
1144         return locations.getOutputLocation(CLASS_OUTPUT);
1145     }
1146 
1147     private Path getSourceOutDir() {
1148         return locations.getOutputLocation(SOURCE_OUTPUT);
1149     }
1150 
1151     @Override @DefinedBy(Api.COMPILER)
1152     public Location getLocationForModule(Location location, String moduleName) throws IOException {
1153         checkModuleOrientedOrOutputLocation(location);
1154         nullCheck(moduleName);
1155         if (location == SOURCE_OUTPUT && getSourceOutDir() == null)
1156             location = CLASS_OUTPUT;
1157         return locations.getLocationForModule(location, moduleName);
1158     }
1159 
1160     @Override @DefinedBy(Api.COMPILER)
1161     public <S> ServiceLoader<S> getServiceLoader(Location location, Class<S> service) throws IOException {
1162         nullCheck(location);
1163         nullCheck(service);
1164         getClass().getModule().addUses(service);
1165         if (location.isModuleOrientedLocation()) {
1166             Collection<Path> paths = locations.getLocation(location);
1167             ModuleFinder finder = ModuleFinder.of(paths.toArray(new Path[paths.size()]));
1168             ModuleLayer bootLayer = ModuleLayer.boot();
1169             ModuleLayer augmentedModuleLayer;
1170             ClassLoader parentCL;
1171             if (CodeReflectionSupport.CODE_LAYER != null) {
1172                 // create a layer whose parent is Babylon's code layer
1173                 augmentedModuleLayer = CodeReflectionSupport.CODE_LAYER;
1174                 parentCL = CodeReflectionSupport.CODE_LAYER.findLoader("jdk.incubator.code");
1175             } else {
1176                 augmentedModuleLayer = bootLayer;
1177                 parentCL = ClassLoader.getSystemClassLoader();
1178             }
1179             Configuration cf = augmentedModuleLayer.configuration()
1180                     .resolveAndBind(ModuleFinder.of(), finder, Collections.emptySet());
1181             ModuleLayer layer = augmentedModuleLayer.defineModulesWithOneLoader(cf, parentCL);
1182             return ServiceLoader.load(layer, service);
1183         } else {
1184             return ServiceLoader.load(service, getClassLoader(location));
1185         }
1186     }
1187 
1188     @Override @DefinedBy(Api.COMPILER)
1189     public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException {
1190         checkModuleOrientedOrOutputLocation(location);
1191         if (!(fo instanceof PathFileObject pathFileObject))
1192             return null;
1193         Path p = Locations.normalize(pathFileObject.path);
1194             // need to find p in location
1195         return locations.getLocationForModule(location, p);
1196     }
1197 
1198     @Override @DefinedBy(Api.COMPILER)
1199     public void setLocationForModule(Location location, String moduleName, Collection<? extends Path> paths)
1200             throws IOException {
1201         nullCheck(location);
1202         checkModuleOrientedOrOutputLocation(location);
1203         locations.setLocationForModule(location, nullCheck(moduleName), nullCheck(paths));
1204         clearCachesForLocation(location);
1205     }
1206 
1207     @Override @DefinedBy(Api.COMPILER)
1208     public String inferModuleName(Location location) {
1209         checkNotModuleOrientedLocation(location);
1210         return locations.inferModuleName(location);
1211     }
1212 
1213     @Override @DefinedBy(Api.COMPILER)
1214     public Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
1215         checkModuleOrientedOrOutputLocation(location);
1216         return locations.listLocationsForModules(location);
1217     }
1218 
1219     @Override @DefinedBy(Api.COMPILER)
1220     public Path asPath(FileObject file) {
1221         if (file instanceof PathFileObject pathFileObject) {
1222             return pathFileObject.path;
1223         } else
1224             throw new IllegalArgumentException(file.getName());
1225     }
1226 
1227     /**
1228      * Enforces the specification of a "relative" name as used in
1229      * {@linkplain #getFileForInput(Location,String,String)
1230      * getFileForInput}.  This method must follow the rules defined in
1231      * that method, do not make any changes without consulting the
1232      * specification.
1233      */
1234     protected static boolean isRelativeUri(URI uri) {
1235         if (uri.isAbsolute())
1236             return false;
1237         String path = uri.normalize().getPath();
1238         if (path.length() == 0 /* isEmpty() is mustang API */)
1239             return false;
1240         if (!path.equals(uri.getPath())) // implicitly checks for embedded . and ..
1241             return false;
1242         if (path.startsWith("/") || path.startsWith("./") || path.startsWith("../"))
1243             return false;
1244         return true;
1245     }
1246 
1247     // Convenience method
1248     protected static boolean isRelativeUri(String u) {
1249         try {
1250             return isRelativeUri(new URI(u));
1251         } catch (URISyntaxException e) {
1252             return false;
1253         }
1254     }
1255 
1256     /**
1257      * Converts a relative file name to a relative URI.  This is
1258      * different from File.toURI as this method does not canonicalize
1259      * the file before creating the URI.  Furthermore, no schema is
1260      * used.
1261      * @param file a relative file name
1262      * @return a relative URI
1263      * @throws IllegalArgumentException if the file name is not
1264      * relative according to the definition given in {@link
1265      * javax.tools.JavaFileManager#getFileForInput}
1266      */
1267     public static String getRelativeName(File file) {
1268         if (!file.isAbsolute()) {
1269             String result = file.getPath().replace(File.separatorChar, '/');
1270             if (isRelativeUri(result))
1271                 return result;
1272         }
1273         throw new IllegalArgumentException("Invalid relative path: " + file);
1274     }
1275 
1276     /**
1277      * Get a detail message from an IOException.
1278      * Most, but not all, instances of IOException provide a non-null result
1279      * for getLocalizedMessage().  But some instances return null: in these
1280      * cases, fall back to getMessage(), and if even that is null, return the
1281      * name of the exception itself.
1282      * @param e an IOException
1283      * @return a string to include in a compiler diagnostic
1284      */
1285     public static String getMessage(IOException e) {
1286         String s = e.getLocalizedMessage();
1287         if (s != null)
1288             return s;
1289         s = e.getMessage();
1290         if (s != null)
1291             return s;
1292         return e.toString();
1293     }
1294 
1295     private void checkOutputLocation(Location location) {
1296         Objects.requireNonNull(location);
1297         if (!location.isOutputLocation())
1298             throw new IllegalArgumentException("location is not an output location: " + location.getName());
1299     }
1300 
1301     private void checkModuleOrientedOrOutputLocation(Location location) {
1302         Objects.requireNonNull(location);
1303         if (!location.isModuleOrientedLocation() && !location.isOutputLocation())
1304             throw new IllegalArgumentException(
1305                     "location is not an output location or a module-oriented location: "
1306                             + location.getName());
1307     }
1308 
1309     private void checkNotModuleOrientedLocation(Location location) {
1310         Objects.requireNonNull(location);
1311         if (location.isModuleOrientedLocation())
1312             throw new IllegalArgumentException("location is module-oriented: " + location.getName());
1313     }
1314 
1315     /* Converters between files and paths.
1316      * These are temporary until we can update the StandardJavaFileManager API.
1317      */
1318 
1319     private static Iterable<Path> asPaths(final Iterable<? extends File> files) {
1320         if (files == null)
1321             return null;
1322 
1323         return () -> new Iterator<Path>() {
1324             Iterator<? extends File> iter = files.iterator();
1325 
1326             @Override
1327             public boolean hasNext() {
1328                 return iter.hasNext();
1329             }
1330 
1331             @Override
1332             public Path next() {
1333                 return iter.next().toPath();
1334             }
1335         };
1336     }
1337 
1338     private static Iterable<File> asFiles(final Iterable<? extends Path> paths) {
1339         if (paths == null)
1340             return null;
1341 
1342         return () -> new Iterator<File>() {
1343             Iterator<? extends Path> iter = paths.iterator();
1344 
1345             @Override
1346             public boolean hasNext() {
1347                 return iter.hasNext();
1348             }
1349 
1350             @Override
1351             public File next() {
1352                 try {
1353                     return iter.next().toFile();
1354                 } catch (UnsupportedOperationException e) {
1355                     throw new IllegalStateException(e);
1356                 }
1357             }
1358         };
1359     }
1360 
1361     @Override
1362     public boolean handleOption(Option option, String value) {
1363         if (javacFileManagerOptions.contains(option)) {
1364             pathsAndContainersByLocationAndRelativeDirectory.clear();
1365             nonIndexingContainersByLocation.clear();
1366         }
1367         return super.handleOption(option, value);
1368     }
1369 
1370     private void clearCachesForLocation(Location location) {
1371         nullCheck(location);
1372         pathsAndContainersByLocationAndRelativeDirectory.remove(location);
1373         nonIndexingContainersByLocation.remove(location);
1374     }
1375 }