1 /*
   2  * Copyright (c) 2009, 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 java.lang.module;
  27 
  28 import java.io.InputStream;
  29 import java.io.IOException;
  30 import java.io.PrintStream;
  31 import java.io.UncheckedIOException;
  32 import java.lang.reflect.AccessFlag;
  33 import java.nio.ByteBuffer;
  34 import java.nio.file.Path;
  35 import java.util.ArrayList;
  36 import java.util.Arrays;
  37 import java.util.Collection;
  38 import java.util.Collections;
  39 import java.util.EnumSet;
  40 import java.util.HashMap;
  41 import java.util.HashSet;
  42 import java.util.List;
  43 import java.util.Locale;
  44 import java.util.Map;
  45 import java.util.Objects;
  46 import java.util.Optional;
  47 import java.util.Set;
  48 import java.util.function.Supplier;
  49 import java.util.stream.Collectors;
  50 import java.util.stream.Stream;
  51 
  52 import static jdk.internal.module.Checks.*;
  53 import static java.util.Objects.*;
  54 
  55 import jdk.internal.module.Checks;
  56 import jdk.internal.module.ModuleInfo;
  57 
  58 
  59 /**
  60  * A module descriptor.
  61  *
  62  * <p> A module descriptor describes a named module and defines methods to
  63  * obtain each of its components. The module descriptor for a named module
  64  * in the Java virtual machine is obtained by invoking the {@link
  65  * java.lang.Module Module}'s {@link java.lang.Module#getDescriptor
  66  * getDescriptor} method. Module descriptors can also be created using the
  67  * {@link ModuleDescriptor.Builder} class or by reading the binary form of a
  68  * module declaration ({@code module-info.class}) using the {@link
  69  * #read(InputStream,Supplier) read} methods defined here. </p>
  70  *
  71  * <p> A module descriptor describes a <em>normal</em>, open, or automatic
  72  * module. <em>Normal</em> modules and open modules describe their {@linkplain
  73  * #requires() dependences}, {@link #exports() exported-packages}, the services
  74  * that they {@linkplain #uses() use} or {@linkplain #provides() provide}, and other
  75  * components. <em>Normal</em> modules may {@linkplain #opens() open} specific
  76  * packages. The module descriptor for an open module does not declare any
  77  * open packages (its {@code opens} method returns an empty set) but when
  78  * instantiated in the Java virtual machine then it is treated as if all
  79  * packages are open. The module descriptor for an automatic module does not
  80  * declare any dependences (except for the mandatory dependency on {@code
  81  * java.base}), and does not declare any exported or open packages. Automatic
  82  * modules receive special treatment during resolution so that they read all
  83  * other modules in the configuration. When an automatic module is instantiated
  84  * in the Java virtual machine then it reads every unnamed module and is
  85  * treated as if all packages are exported and open. </p>
  86  *
  87  * <p> {@code ModuleDescriptor} objects are immutable and safe for use by
  88  * multiple concurrent threads.</p>
  89  *
  90  * @see java.lang.Module
  91  * @since 9
  92  */
  93 
  94 public final class ModuleDescriptor
  95     implements Comparable<ModuleDescriptor>
  96 {
  97 
  98     /**
  99      * A modifier on a module.
 100      *
 101      * @see ModuleDescriptor#modifiers()
 102      * @since 9
 103      */
 104     public enum Modifier {
 105         /**
 106          * An open module. An open module does not declare any open packages
 107          * but the resulting module is treated as if all packages are open.
 108          */
 109         OPEN(AccessFlag.OPEN.mask()),
 110 
 111         /**
 112          * An automatic module. An automatic module is treated as if it exports
 113          * and opens all packages.
 114          *
 115          * @apiNote This modifier does not correspond to a module flag in the
 116          * binary form of a module declaration ({@code module-info.class}).
 117          */
 118         AUTOMATIC(0 /* no flag per above comment */),
 119 
 120         /**
 121          * The module was not explicitly or implicitly declared.
 122          */
 123         SYNTHETIC(AccessFlag.SYNTHETIC.mask()),
 124 
 125         /**
 126          * The module was implicitly declared.
 127          */
 128         MANDATED(AccessFlag.MANDATED.mask());
 129 
 130         private final int mask;
 131         private Modifier(int mask) {
 132             this.mask = mask;
 133         }
 134         private int mask() {return mask;}
 135     }
 136 
 137     /**
 138      * <p> A dependence upon a module. </p>
 139      *
 140      * @see ModuleDescriptor#requires()
 141      * @since 9
 142      */
 143 
 144     public static final class Requires
 145         implements Comparable<Requires>
 146     {
 147 
 148         /**
 149          * A modifier on a module dependence.
 150          *
 151          * @see Requires#modifiers()
 152          * @since 9
 153          */
 154         public enum Modifier {
 155 
 156             /**
 157              * The dependence causes any module which depends on the <i>current
 158              * module</i> to have an implicitly declared dependence on the module
 159              * named by the {@code Requires}.
 160              */
 161             TRANSITIVE(AccessFlag.TRANSITIVE.mask()),
 162 
 163             /**
 164              * The dependence is mandatory in the static phase, during compilation,
 165              * but is optional in the dynamic phase, during execution.
 166              */
 167             STATIC(AccessFlag.STATIC_PHASE.mask()),
 168 
 169             /**
 170              * The dependence was not explicitly or implicitly declared in the
 171              * source of the module declaration.
 172              */
 173             SYNTHETIC(AccessFlag.SYNTHETIC.mask()),
 174 
 175             /**
 176              * The dependence was implicitly declared in the source of the module
 177              * declaration.
 178              */
 179             MANDATED(AccessFlag.MANDATED.mask());
 180             private final int mask;
 181             private Modifier(int mask) {
 182                 this.mask = mask;
 183             }
 184             private int mask() {return mask;}
 185         }
 186         private final Set<Modifier> mods;
 187         private final String name;
 188         private final Version compiledVersion;
 189         private final String rawCompiledVersion;
 190 
 191         private Requires(Set<Modifier> ms, String mn, Version v, String vs) {
 192             assert v == null || vs == null;
 193             this.mods = Set.copyOf(ms);
 194             this.name = mn;
 195             this.compiledVersion = v;
 196             this.rawCompiledVersion = vs;
 197         }
 198 
 199         private Requires(Set<Modifier> ms, String mn, Version v, boolean unused) {
 200             this.mods = ms;
 201             this.name = mn;
 202             this.compiledVersion = v;
 203             this.rawCompiledVersion = null;
 204         }
 205 
 206         /**
 207          * Returns the set of modifiers.
 208          *
 209          * @return A possibly-empty unmodifiable set of modifiers
 210          */
 211         public Set<Modifier> modifiers() {
 212             return mods;
 213         }
 214 
 215         /**
 216          * Returns the set of the module {@linkplain AccessFlag
 217          * requires flags}.
 218          *
 219          * @return A possibly-empty unmodifiable set of requires flags
 220          * @see #modifiers()
 221          * @jvms 4.7.25 The Module Attribute
 222          * @since 20
 223          */
 224         public Set<AccessFlag> accessFlags() {
 225             int mask = 0;
 226             for (var modifier : mods) {
 227                 mask |= modifier.mask();
 228             }
 229             return AccessFlag.maskToAccessFlags(mask, AccessFlag.Location.MODULE_REQUIRES);
 230         }
 231 
 232         /**
 233          * Return the module name.
 234          *
 235          * @return The module name
 236          */
 237         public String name() {
 238             return name;
 239         }
 240 
 241         /**
 242          * Returns the version of the module if recorded at compile-time.
 243          *
 244          * @return The version of the module if recorded at compile-time,
 245          *         or an empty {@code Optional} if no version was recorded or
 246          *         the version string recorded is {@linkplain Version#parse(String)
 247          *         unparseable}
 248          */
 249         public Optional<Version> compiledVersion() {
 250             return Optional.ofNullable(compiledVersion);
 251         }
 252 
 253         /**
 254          * Returns the string with the possibly-unparseable version of the module
 255          * if recorded at compile-time.
 256          *
 257          * @return The string containing the version of the module if recorded
 258          *         at compile-time, or an empty {@code Optional} if no version
 259          *         was recorded
 260          *
 261          * @see #compiledVersion()
 262          */
 263         public Optional<String> rawCompiledVersion() {
 264             if (compiledVersion != null) {
 265                 return Optional.of(compiledVersion.toString());
 266             } else {
 267                 return Optional.ofNullable(rawCompiledVersion);
 268             }
 269         }
 270 
 271         /**
 272          * Compares this module dependence to another.
 273          *
 274          * <p> Two {@code Requires} objects are compared by comparing their
 275          * module names lexicographically. Where the module names are equal
 276          * then the sets of modifiers are compared in the same way that
 277          * module modifiers are compared (see {@link ModuleDescriptor#compareTo
 278          * ModuleDescriptor.compareTo}). Where the module names are equal and
 279          * the set of modifiers are equal then the version of the modules
 280          * recorded at compile-time are compared. When comparing the versions
 281          * recorded at compile-time then a dependence that has a recorded
 282          * version is considered to succeed a dependence that does not have a
 283          * recorded version. If both recorded versions are {@linkplain
 284          * Version#parse(String) unparseable} then the {@linkplain
 285          * #rawCompiledVersion() raw version strings} are compared
 286          * lexicographically. </p>
 287          *
 288          * @param  that
 289          *         The module dependence to compare
 290          *
 291          * @return A negative integer, zero, or a positive integer if this module
 292          *         dependence is less than, equal to, or greater than the given
 293          *         module dependence
 294          */
 295         @Override
 296         public int compareTo(Requires that) {
 297             if (this == that) return 0;
 298 
 299             int c = this.name().compareTo(that.name());
 300             if (c != 0) return c;
 301 
 302             // modifiers
 303             long v1 = modsValue(this.modifiers());
 304             long v2 = modsValue(that.modifiers());
 305             c = Long.compare(v1, v2);
 306             if (c != 0) return c;
 307 
 308             // compiledVersion
 309             c = compare(this.compiledVersion, that.compiledVersion);
 310             if (c != 0) return c;
 311 
 312             // rawCompiledVersion
 313             c = compare(this.rawCompiledVersion, that.rawCompiledVersion);
 314             if (c != 0) return c;
 315 
 316             return 0;
 317         }
 318 
 319         /**
 320          * Tests this module dependence for equality with the given object.
 321          *
 322          * <p> If the given object is not a {@code Requires} then this method
 323          * returns {@code false}. Two module dependence objects are equal if
 324          * the module names are equal, set of modifiers are equal, and the
 325          * compiled version of both modules is equal or not recorded for
 326          * both modules. </p>
 327          *
 328          * <p> This method satisfies the general contract of the {@link
 329          * java.lang.Object#equals(Object) Object.equals} method. </p>
 330          *
 331          * @param   ob
 332          *          the object to which this object is to be compared
 333          *
 334          * @return  {@code true} if, and only if, the given object is a module
 335          *          dependence that is equal to this module dependence
 336          */
 337         @Override
 338         public boolean equals(Object ob) {
 339             return (ob instanceof Requires that)
 340                     && name.equals(that.name) && mods.equals(that.mods)
 341                     && Objects.equals(compiledVersion, that.compiledVersion)
 342                     && Objects.equals(rawCompiledVersion, that.rawCompiledVersion);
 343         }
 344 
 345         /**
 346          * Computes a hash code for this module dependence.
 347          *
 348          * <p> The hash code is based upon the module name, modifiers, and the
 349          * module version if recorded at compile time. It satisfies the general
 350          * contract of the {@link Object#hashCode Object.hashCode} method. </p>
 351          *
 352          * @return The hash-code value for this module dependence
 353          */
 354         @Override
 355         public int hashCode() {
 356             int hash = name.hashCode() * 43 + modsHashCode(mods);
 357             if (compiledVersion != null)
 358                 hash = hash * 43 + compiledVersion.hashCode();
 359             if (rawCompiledVersion != null)
 360                 hash = hash * 43 + rawCompiledVersion.hashCode();
 361             return hash;
 362         }
 363 
 364         /**
 365          * Returns a string describing this module dependence.
 366          *
 367          * @return A string describing this module dependence
 368          */
 369         @Override
 370         public String toString() {
 371             String what;
 372             if (compiledVersion != null) {
 373                 what = name() + " (@" + compiledVersion + ")";
 374             } else {
 375                 what = name();
 376             }
 377             return ModuleDescriptor.toString(mods, what);
 378         }
 379     }
 380 
 381 
 382     /**
 383      * <p> A package exported by a module, may be qualified or unqualified. </p>
 384      *
 385      * @see ModuleDescriptor#exports()
 386      * @since 9
 387      */
 388 
 389     public static final class Exports
 390         implements Comparable<Exports>
 391     {
 392 
 393         /**
 394          * A modifier on an exported package.
 395          *
 396          * @see Exports#modifiers()
 397          * @since 9
 398          */
 399         public enum Modifier {
 400 
 401             /**
 402              * The export was not explicitly or implicitly declared in the
 403              * source of the module declaration.
 404              */
 405             SYNTHETIC(AccessFlag.SYNTHETIC.mask()),
 406 
 407             /**
 408              * The export was implicitly declared in the source of the module
 409              * declaration.
 410              */
 411             MANDATED(AccessFlag.MANDATED.mask());
 412 
 413             private final int mask;
 414             private Modifier(int mask) {
 415                 this.mask = mask;
 416             }
 417             private int mask() {return mask;}
 418         }
 419 
 420         private final Set<Modifier> mods;
 421         private final String source;
 422         private final Set<String> targets;  // empty if unqualified export
 423 
 424         /**
 425          * Constructs an export
 426          */
 427         private Exports(Set<Modifier> ms, String source, Set<String> targets) {
 428             this.mods = Set.copyOf(ms);
 429             this.source = source;
 430             this.targets = Set.copyOf(targets);
 431         }
 432 
 433         private Exports(Set<Modifier> ms,
 434                         String source,
 435                         Set<String> targets,
 436                         boolean unused) {
 437             this.mods = ms;
 438             this.source = source;
 439             this.targets = targets;
 440         }
 441 
 442         /**
 443          * Returns the set of modifiers.
 444          *
 445          * @return A possibly-empty unmodifiable set of modifiers
 446          */
 447         public Set<Modifier> modifiers() {
 448             return mods;
 449         }
 450 
 451         /**
 452          * Returns the set of the module {@linkplain AccessFlag
 453          * export flags} for this module descriptor.
 454          *
 455          * @return A possibly-empty unmodifiable set of export flags
 456          * @see #modifiers()
 457          * @jvms 4.7.25 The Module Attribute
 458          * @since 20
 459          */
 460         public Set<AccessFlag> accessFlags() {
 461             int mask = 0;
 462             for (var modifier : mods) {
 463                 mask |= modifier.mask();
 464             }
 465             return AccessFlag.maskToAccessFlags(mask, AccessFlag.Location.MODULE_EXPORTS);
 466         }
 467 
 468         /**
 469          * Returns {@code true} if this is a qualified export.
 470          *
 471          * @return {@code true} if this is a qualified export
 472          */
 473         public boolean isQualified() {
 474             return !targets.isEmpty();
 475         }
 476 
 477         /**
 478          * Returns the package name.
 479          *
 480          * @return The package name
 481          */
 482         public String source() {
 483             return source;
 484         }
 485 
 486         /**
 487          * For a qualified export, returns the non-empty and immutable set
 488          * of the module names to which the package is exported. For an
 489          * unqualified export, returns an empty set.
 490          *
 491          * @return The set of target module names or for an unqualified
 492          *         export, an empty set
 493          */
 494         public Set<String> targets() {
 495             return targets;
 496         }
 497 
 498         /**
 499          * Compares this module export to another.
 500          *
 501          * <p> Two {@code Exports} objects are compared by comparing the package
 502          * names lexicographically. Where the packages names are equal then the
 503          * sets of modifiers are compared in the same way that module modifiers
 504          * are compared (see {@link ModuleDescriptor#compareTo
 505          * ModuleDescriptor.compareTo}). Where the package names are equal and
 506          * the set of modifiers are equal then the set of target modules are
 507          * compared. This is done by sorting the names of the target modules
 508          * in ascending order, and according to their natural ordering, and then
 509          * comparing the corresponding elements lexicographically. Where the
 510          * sets differ in size, and the larger set contains all elements of the
 511          * smaller set, then the larger set is considered to succeed the smaller
 512          * set. </p>
 513          *
 514          * @param  that
 515          *         The module export to compare
 516          *
 517          * @return A negative integer, zero, or a positive integer if this module
 518          *         export is less than, equal to, or greater than the given
 519          *         export dependence
 520          */
 521         @Override
 522         public int compareTo(Exports that) {
 523             if (this == that) return 0;
 524 
 525             int c = source.compareTo(that.source);
 526             if (c != 0)
 527                 return c;
 528 
 529             // modifiers
 530             long v1 = modsValue(this.modifiers());
 531             long v2 = modsValue(that.modifiers());
 532             c = Long.compare(v1, v2);
 533             if (c != 0)
 534                 return c;
 535 
 536             // targets
 537             c = compare(targets, that.targets);
 538             if (c != 0)
 539                 return c;
 540 
 541             return 0;
 542         }
 543 
 544         /**
 545          * Computes a hash code for this module export.
 546          *
 547          * <p> The hash code is based upon the modifiers, the package name,
 548          * and for a qualified export, the set of modules names to which the
 549          * package is exported. It satisfies the general contract of the
 550          * {@link Object#hashCode Object.hashCode} method.
 551          *
 552          * @return The hash-code value for this module export
 553          */
 554         @Override
 555         public int hashCode() {
 556             int hash = modsHashCode(mods);
 557             hash = hash * 43 + source.hashCode();
 558             return hash * 43 + targets.hashCode();
 559         }
 560 
 561         /**
 562          * Tests this module export for equality with the given object.
 563          *
 564          * <p> If the given object is not an {@code Exports} then this method
 565          * returns {@code false}. Two module exports objects are equal if their
 566          * set of modifiers is equal, the package names are equal and the set
 567          * of target module names is equal. </p>
 568          *
 569          * <p> This method satisfies the general contract of the {@link
 570          * java.lang.Object#equals(Object) Object.equals} method. </p>
 571          *
 572          * @param   ob
 573          *          the object to which this object is to be compared
 574          *
 575          * @return  {@code true} if, and only if, the given object is a module
 576          *          dependence that is equal to this module dependence
 577          */
 578         @Override
 579         public boolean equals(Object ob) {
 580             return (ob instanceof Exports other)
 581                     && Objects.equals(this.mods, other.mods)
 582                     && Objects.equals(this.source, other.source)
 583                     && Objects.equals(this.targets, other.targets);
 584         }
 585 
 586         /**
 587          * Returns a string describing the exported package.
 588          *
 589          * @return A string describing the exported package
 590          */
 591         @Override
 592         public String toString() {
 593             String s = ModuleDescriptor.toString(mods, source);
 594             if (targets.isEmpty())
 595                 return s;
 596             else
 597                 return s + " to " + targets;
 598         }
 599     }
 600 
 601 
 602     /**
 603      * <p> A package opened by a module, may be qualified or unqualified. </p>
 604      *
 605      * <p> The <em>opens</em> directive in a module declaration declares a
 606      * package to be open to allow all types in the package, and all their
 607      * members, not just public types and their public members to be reflected
 608      * on by APIs that support private access or a way to bypass or suppress
 609      * default Java language access control checks. </p>
 610      *
 611      * @see ModuleDescriptor#opens()
 612      * @since 9
 613      */
 614 
 615     public static final class Opens
 616         implements Comparable<Opens>
 617     {
 618         /**
 619          * A modifier on an open package.
 620          *
 621          * @see Opens#modifiers()
 622          * @since 9
 623          */
 624         public enum Modifier {
 625 
 626             /**
 627              * The open package was not explicitly or implicitly declared in
 628              * the source of the module declaration.
 629              */
 630             SYNTHETIC(AccessFlag.SYNTHETIC.mask()),
 631 
 632             /**
 633              * The open package was implicitly declared in the source of the
 634              * module declaration.
 635              */
 636             MANDATED(AccessFlag.MANDATED.mask());
 637             private final int mask;
 638             private Modifier(int mask) {
 639                 this.mask = mask;
 640             }
 641             private int mask() {return mask;}
 642         }
 643 
 644         private final Set<Modifier> mods;
 645         private final String source;
 646         private final Set<String> targets;  // empty if unqualified export
 647 
 648         /**
 649          * Constructs an {@code Opens}.
 650          */
 651         private Opens(Set<Modifier> ms, String source, Set<String> targets) {
 652             this.mods = Set.copyOf(ms);
 653             this.source = source;
 654             this.targets = Set.copyOf(targets);
 655         }
 656 
 657         private Opens(Set<Modifier> ms,
 658                       String source,
 659                       Set<String> targets,
 660                       boolean unused) {
 661             this.mods = ms;
 662             this.source = source;
 663             this.targets = targets;
 664         }
 665 
 666         /**
 667          * Returns the set of modifiers.
 668          *
 669          * @return A possibly-empty unmodifiable set of modifiers
 670          */
 671         public Set<Modifier> modifiers() {
 672             return mods;
 673         }
 674 
 675         /**
 676          * Returns the set of the module {@linkplain AccessFlag opens
 677          * flags}.
 678          *
 679          * @return A possibly-empty unmodifiable set of opens flags
 680          * @see #modifiers()
 681          * @jvms 4.7.25 The Module Attribute
 682          * @since 20
 683          */
 684         public Set<AccessFlag> accessFlags() {
 685             int mask = 0;
 686             for (var modifier : mods) {
 687                 mask |= modifier.mask();
 688             }
 689             return AccessFlag.maskToAccessFlags(mask, AccessFlag.Location.MODULE_OPENS);
 690         }
 691 
 692         /**
 693          * Returns {@code true} if this is a qualified {@code Opens}.
 694          *
 695          * @return {@code true} if this is a qualified {@code Opens}
 696          */
 697         public boolean isQualified() {
 698             return !targets.isEmpty();
 699         }
 700 
 701         /**
 702          * Returns the package name.
 703          *
 704          * @return The package name
 705          */
 706         public String source() {
 707             return source;
 708         }
 709 
 710         /**
 711          * For a qualified {@code Opens}, returns the non-empty and immutable set
 712          * of the module names to which the package is open. For an
 713          * unqualified {@code Opens}, returns an empty set.
 714          *
 715          * @return The set of target module names or for an unqualified
 716          *         {@code Opens}, an empty set
 717          */
 718         public Set<String> targets() {
 719             return targets;
 720         }
 721 
 722         /**
 723          * Compares this module {@code Opens} to another.
 724          *
 725          * <p> Two {@code Opens} objects are compared by comparing the package
 726          * names lexicographically. Where the packages names are equal then the
 727          * sets of modifiers are compared in the same way that module modifiers
 728          * are compared (see {@link ModuleDescriptor#compareTo
 729          * ModuleDescriptor.compareTo}). Where the package names are equal and
 730          * the set of modifiers are equal then the set of target modules are
 731          * compared. This is done by sorting the names of the target modules
 732          * in ascending order, and according to their natural ordering, and then
 733          * comparing the corresponding elements lexicographically. Where the
 734          * sets differ in size, and the larger set contains all elements of the
 735          * smaller set, then the larger set is considered to succeed the smaller
 736          * set. </p>
 737          *
 738          * @param  that
 739          *         The module {@code Opens} to compare
 740          *
 741          * @return A negative integer, zero, or a positive integer if this module
 742          *         {@code Opens} is less than, equal to, or greater than the given
 743          *         module {@code Opens}
 744          */
 745         @Override
 746         public int compareTo(Opens that) {
 747             if (this == that) return 0;
 748 
 749             int c = source.compareTo(that.source);
 750             if (c != 0)
 751                 return c;
 752 
 753             // modifiers
 754             long v1 = modsValue(this.modifiers());
 755             long v2 = modsValue(that.modifiers());
 756             c = Long.compare(v1, v2);
 757             if (c != 0)
 758                 return c;
 759 
 760             // targets
 761             c = compare(targets, that.targets);
 762             if (c != 0)
 763                 return c;
 764 
 765             return 0;
 766         }
 767 
 768         /**
 769          * Computes a hash code for this module {@code Opens}.
 770          *
 771          * <p> The hash code is based upon the modifiers, the package name,
 772          * and for a qualified {@code Opens}, the set of modules names to which the
 773          * package is opened. It satisfies the general contract of the
 774          * {@link Object#hashCode Object.hashCode} method.
 775          *
 776          * @return The hash-code value for this module {@code Opens}
 777          */
 778         @Override
 779         public int hashCode() {
 780             int hash = modsHashCode(mods);
 781             hash = hash * 43 + source.hashCode();
 782             return hash * 43 + targets.hashCode();
 783         }
 784 
 785         /**
 786          * Tests this module {@code Opens} for equality with the given object.
 787          *
 788          * <p> If the given object is not an {@code Opens} then this method
 789          * returns {@code false}. Two {@code Opens} objects are equal if their
 790          * set of modifiers is equal, the package names are equal and the set
 791          * of target module names is equal. </p>
 792          *
 793          * <p> This method satisfies the general contract of the {@link
 794          * java.lang.Object#equals(Object) Object.equals} method. </p>
 795          *
 796          * @param   ob
 797          *          the object to which this object is to be compared
 798          *
 799          * @return  {@code true} if, and only if, the given object is a module
 800          *          dependence that is equal to this module dependence
 801          */
 802         @Override
 803         public boolean equals(Object ob) {
 804            return (ob instanceof Opens other)
 805                    && Objects.equals(this.mods, other.mods)
 806                    && Objects.equals(this.source, other.source)
 807                    && Objects.equals(this.targets, other.targets);
 808         }
 809 
 810         /**
 811          * Returns a string describing the open package.
 812          *
 813          * @return A string describing the open package
 814          */
 815         @Override
 816         public String toString() {
 817             String s = ModuleDescriptor.toString(mods, source);
 818             if (targets.isEmpty())
 819                 return s;
 820             else
 821                 return s + " to " + targets;
 822         }
 823     }
 824 
 825 
 826     /**
 827      * <p> A service that a module provides one or more implementations of. </p>
 828      *
 829      * @see ModuleDescriptor#provides()
 830      * @since 9
 831      */
 832 
 833     public static final class Provides
 834         implements Comparable<Provides>
 835     {
 836         private final String service;
 837         private final List<String> providers;
 838 
 839         private Provides(String service, List<String> providers) {
 840             this.service = service;
 841             this.providers = List.copyOf(providers);
 842         }
 843 
 844         private Provides(String service, List<String> providers, boolean unused) {
 845             this.service = service;
 846             this.providers = providers;
 847         }
 848 
 849         /**
 850          * {@return the {@linkplain ClassLoader##binary-name binary name} of the service type}
 851          */
 852         public String service() { return service; }
 853 
 854         /**
 855          * Returns the list of the {@linkplain ClassLoader##binary-name binary names}
 856          * of the providers or provider factories.
 857          *
 858          * @return A non-empty and unmodifiable list of the {@linkplain ClassLoader##binary-name
 859          *         binary names} of the providers or provider factories
 860          */
 861         public List<String> providers() { return providers; }
 862 
 863         /**
 864          * Compares this {@code Provides} to another.
 865          *
 866          * <p> Two {@code Provides} objects are compared by comparing the
 867          * {@linkplain ClassLoader##binary-name binary name}
 868          * of the service type lexicographically. Where the
 869          * class names are equal then the list of the provider class names are
 870          * compared by comparing the corresponding elements of both lists
 871          * lexicographically and in sequence. Where the lists differ in size,
 872          * {@code N} is the size of the shorter list, and the first {@code N}
 873          * corresponding elements are equal, then the longer list is considered
 874          * to succeed the shorter list. </p>
 875          *
 876          * @param  that
 877          *         The {@code Provides} to compare
 878          *
 879          * @return A negative integer, zero, or a positive integer if this
 880          *         {@code Provides} is less than, equal to, or greater than
 881          *         the given {@code Provides}
 882          */
 883         public int compareTo(Provides that) {
 884             if (this == that) return 0;
 885 
 886             int c = service.compareTo(that.service);
 887             if (c != 0) return c;
 888 
 889             // compare provider class names in sequence
 890             int size1 = this.providers.size();
 891             int size2 = that.providers.size();
 892             for (int index=0; index<Math.min(size1, size2); index++) {
 893                 String e1 = this.providers.get(index);
 894                 String e2 = that.providers.get(index);
 895                 c = e1.compareTo(e2);
 896                 if (c != 0) return c;
 897             }
 898             if (size1 == size2) {
 899                 return 0;
 900             } else {
 901                 return (size1 > size2) ? 1 : -1;
 902             }
 903         }
 904 
 905         /**
 906          * Computes a hash code for this {@code Provides}.
 907          *
 908          * <p> The hash code is based upon the service type and the set of
 909          * providers. It satisfies the general contract of the {@link
 910          * Object#hashCode Object.hashCode} method. </p>
 911          *
 912          * @return The hash-code value for this module provides
 913          */
 914         @Override
 915         public int hashCode() {
 916             return service.hashCode() * 43 + providers.hashCode();
 917         }
 918 
 919         /**
 920          * Tests this {@code Provides} for equality with the given object.
 921          *
 922          * <p> If the given object is not a {@code Provides} then this method
 923          * returns {@code false}. Two {@code Provides} objects are equal if the
 924          * service type is equal and the list of providers is equal. </p>
 925          *
 926          * <p> This method satisfies the general contract of the {@link
 927          * java.lang.Object#equals(Object) Object.equals} method. </p>
 928          *
 929          * @param   ob
 930          *          the object to which this object is to be compared
 931          *
 932          * @return  {@code true} if, and only if, the given object is a
 933          *          {@code Provides} that is equal to this {@code Provides}
 934          */
 935         @Override
 936         public boolean equals(Object ob) {
 937             return (ob instanceof Provides other)
 938                     && Objects.equals(this.service, other.service)
 939                     && Objects.equals(this.providers, other.providers);
 940         }
 941 
 942         /**
 943          * Returns a string describing this {@code Provides}.
 944          *
 945          * @return A string describing this {@code Provides}
 946          */
 947         @Override
 948         public String toString() {
 949             return service + " with " + providers;
 950         }
 951 
 952     }
 953 
 954 
 955     /**
 956      * A module's version string.
 957      *
 958      * <p> A version string has three components: The version number itself, an
 959      * optional pre-release version, and an optional build version.  Each
 960      * component is a sequence of tokens; each token is either a non-negative
 961      * integer or a string.  Tokens are separated by the punctuation characters
 962      * {@code '.'}, {@code '-'}, or {@code '+'}, or by transitions from a
 963      * sequence of digits to a sequence of characters that are neither digits
 964      * nor punctuation characters, or vice versa.  Consecutive repeated
 965      * punctuation characters are treated as a single punctuation character.
 966      *
 967      * <ul>
 968      *
 969      *   <li> The <i>version number</i> is a sequence of tokens separated by
 970      *   {@code '.'} characters, terminated by the first {@code '-'} or {@code
 971      *   '+'} character. </li>
 972      *
 973      *   <li> The <i>pre-release version</i> is a sequence of tokens separated
 974      *   by {@code '.'} or {@code '-'} characters, terminated by the first
 975      *   {@code '+'} character. </li>
 976      *
 977      *   <li> The <i>build version</i> is a sequence of tokens separated by
 978      *   {@code '.'}, {@code '-'}, or {@code '+'} characters.
 979      *
 980      * </ul>
 981      *
 982      * <p> When comparing two version strings, the elements of their
 983      * corresponding components are compared in pointwise fashion.  If one
 984      * component is longer than the other, but otherwise equal to it, then the
 985      * first component is considered the greater of the two; otherwise, if two
 986      * corresponding elements are integers then they are compared as such;
 987      * otherwise, at least one of the elements is a string, so the other is
 988      * converted into a string if it is an integer and the two are compared
 989      * lexicographically.  Trailing integer elements with the value zero are
 990      * ignored.
 991      *
 992      * <p> Given two version strings, if their version numbers differ then the
 993      * result of comparing them is the result of comparing their version
 994      * numbers; otherwise, if one of them has a pre-release version but the
 995      * other does not then the first is considered to precede the second,
 996      * otherwise the result of comparing them is the result of comparing their
 997      * pre-release versions; otherwise, the result of comparing them is the
 998      * result of comparing their build versions.
 999      *
1000      * @see ModuleDescriptor#version()
1001      * @since 9
1002      */
1003 
1004     public static final class Version
1005         implements Comparable<Version>
1006     {
1007 
1008         private final String version;
1009 
1010         // If Java had disjunctive types then we'd write List<Integer|String> here
1011         //
1012         private final List<Object> sequence;
1013         private final List<Object> pre;
1014         private final List<Object> build;
1015 
1016         // Take a numeric token starting at position i
1017         // Append it to the given list
1018         // Return the index of the first character not taken
1019         // Requires: s.charAt(i) is (decimal) numeric
1020         //
1021         private static int takeNumber(String s, int i, List<Object> acc) {
1022             char c = s.charAt(i);
1023             int d = (c - '0');
1024             int n = s.length();
1025             while (++i < n) {
1026                 c = s.charAt(i);
1027                 if (c >= '0' && c <= '9') {
1028                     d = d * 10 + (c - '0');
1029                     continue;
1030                 }
1031                 break;
1032             }
1033             acc.add(d);
1034             return i;
1035         }
1036 
1037         // Take a string token starting at position i
1038         // Append it to the given list
1039         // Return the index of the first character not taken
1040         // Requires: s.charAt(i) is not '.'
1041         //
1042         private static int takeString(String s, int i, List<Object> acc) {
1043             int b = i;
1044             int n = s.length();
1045             while (++i < n) {
1046                 char c = s.charAt(i);
1047                 if (c != '.' && c != '-' && c != '+' && !(c >= '0' && c <= '9'))
1048                     continue;
1049                 break;
1050             }
1051             acc.add(s.substring(b, i));
1052             return i;
1053         }
1054 
1055         // Syntax: tok+ ( '-' tok+)? ( '+' tok+)?
1056         // First token string is sequence, second is pre, third is build
1057         // Tokens are separated by '.' or '-', or by changes between alpha & numeric
1058         // Numeric tokens are compared as decimal integers
1059         // Non-numeric tokens are compared lexicographically
1060         // A version with a non-empty pre is less than a version with same seq but no pre
1061         // Tokens in build may contain '-' and '+'
1062         //
1063         private Version(String v) {
1064 
1065             if (v == null)
1066                 throw new IllegalArgumentException("Null version string");
1067             int n = v.length();
1068             if (n == 0)
1069                 throw new IllegalArgumentException("Empty version string");
1070 
1071             int i = 0;
1072             char c = v.charAt(i);
1073             if (!(c >= '0' && c <= '9'))
1074                 throw new IllegalArgumentException(v
1075                                                    + ": Version string does not start"
1076                                                    + " with a number");
1077 
1078             List<Object> sequence = new ArrayList<>(4);
1079             List<Object> pre = new ArrayList<>(2);
1080             List<Object> build = new ArrayList<>(2);
1081 
1082             i = takeNumber(v, i, sequence);
1083 
1084             while (i < n) {
1085                 c = v.charAt(i);
1086                 if (c == '.') {
1087                     i++;
1088                     continue;
1089                 }
1090                 if (c == '-' || c == '+') {
1091                     i++;
1092                     break;
1093                 }
1094                 if (c >= '0' && c <= '9')
1095                     i = takeNumber(v, i, sequence);
1096                 else
1097                     i = takeString(v, i, sequence);
1098             }
1099 
1100             if (c == '-' && i >= n)
1101                 throw new IllegalArgumentException(v + ": Empty pre-release");
1102 
1103             while (i < n) {
1104                 c = v.charAt(i);
1105                 if (c == '.' || c == '-') {
1106                     i++;
1107                     continue;
1108                 }
1109                 if (c == '+') {
1110                     i++;
1111                     break;
1112                 }
1113                 if (c >= '0' && c <= '9')
1114                     i = takeNumber(v, i, pre);
1115                 else
1116                     i = takeString(v, i, pre);
1117             }
1118 
1119             if (c == '+' && i >= n)
1120                 throw new IllegalArgumentException(v + ": Empty pre-release");
1121 
1122             while (i < n) {
1123                 c = v.charAt(i);
1124                 if (c == '.' || c == '-' || c == '+') {
1125                     i++;
1126                     continue;
1127                 }
1128                 if (c >= '0' && c <= '9')
1129                     i = takeNumber(v, i, build);
1130                 else
1131                     i = takeString(v, i, build);
1132             }
1133 
1134             this.version = v;
1135             this.sequence = sequence;
1136             this.pre = pre;
1137             this.build = build;
1138         }
1139 
1140         /**
1141          * Parses the given string as a version string.
1142          *
1143          * @param  v
1144          *         The string to parse
1145          *
1146          * @return The resulting {@code Version}
1147          *
1148          * @throws IllegalArgumentException
1149          *         If {@code v} is {@code null}, an empty string, or cannot be
1150          *         parsed as a version string
1151          */
1152         public static Version parse(String v) {
1153             return new Version(v);
1154         }
1155 
1156         @SuppressWarnings("unchecked")
1157         private int cmp(Object o1, Object o2) {
1158             return ((Comparable)o1).compareTo(o2);
1159         }
1160 
1161         private int compareTokens(List<Object> ts1, List<Object> ts2) {
1162             int n = Math.min(ts1.size(), ts2.size());
1163             for (int i = 0; i < n; i++) {
1164                 Object o1 = ts1.get(i);
1165                 Object o2 = ts2.get(i);
1166                 if ((o1 instanceof Integer && o2 instanceof Integer)
1167                     || (o1 instanceof String && o2 instanceof String))
1168                 {
1169                     int c = cmp(o1, o2);
1170                     if (c == 0)
1171                         continue;
1172                     return c;
1173                 }
1174                 // Types differ, so convert number to string form
1175                 int c = o1.toString().compareTo(o2.toString());
1176                 if (c == 0)
1177                     continue;
1178                 return c;
1179             }
1180             List<Object> rest = ts1.size() > ts2.size() ? ts1 : ts2;
1181             int e = rest.size();
1182             for (int i = n; i < e; i++) {
1183                 Object o = rest.get(i);
1184                 if (o instanceof Integer && ((Integer)o) == 0)
1185                     continue;
1186                 return ts1.size() - ts2.size();
1187             }
1188             return 0;
1189         }
1190 
1191         /**
1192          * Compares this module version to another module version. Module
1193          * versions are compared as described in the class description.
1194          *
1195          * @param that
1196          *        The module version to compare
1197          *
1198          * @return A negative integer, zero, or a positive integer as this
1199          *         module version is less than, equal to, or greater than the
1200          *         given module version
1201          */
1202         @Override
1203         public int compareTo(Version that) {
1204             int c = compareTokens(this.sequence, that.sequence);
1205             if (c != 0) return c;
1206             if (this.pre.isEmpty()) {
1207                 if (!that.pre.isEmpty()) return +1;
1208             } else {
1209                 if (that.pre.isEmpty()) return -1;
1210             }
1211             c = compareTokens(this.pre, that.pre);
1212             if (c != 0) return c;
1213             return compareTokens(this.build, that.build);
1214         }
1215 
1216         /**
1217          * Tests this module version for equality with the given object.
1218          *
1219          * <p> If the given object is not a {@code Version} then this method
1220          * returns {@code false}. Two module version are equal if their
1221          * corresponding components are equal. </p>
1222          *
1223          * <p> This method satisfies the general contract of the {@link
1224          * java.lang.Object#equals(Object) Object.equals} method. </p>
1225          *
1226          * @param   ob
1227          *          the object to which this object is to be compared
1228          *
1229          * @return  {@code true} if, and only if, the given object is a module
1230          *          reference that is equal to this module reference
1231          */
1232         @Override
1233         public boolean equals(Object ob) {
1234             if (!(ob instanceof Version))
1235                 return false;
1236             return compareTo((Version)ob) == 0;
1237         }
1238 
1239         /**
1240          * Computes a hash code for this module version.
1241          *
1242          * <p> The hash code is based upon the components of the version and
1243          * satisfies the general contract of the {@link Object#hashCode
1244          * Object.hashCode} method. </p>
1245          *
1246          * @return The hash-code value for this module version
1247          */
1248         @Override
1249         public int hashCode() {
1250             return version.hashCode();
1251         }
1252 
1253         /**
1254          * Returns the string from which this version was parsed.
1255          *
1256          * @return The string from which this version was parsed.
1257          */
1258         @Override
1259         public String toString() {
1260             return version;
1261         }
1262 
1263     }
1264 
1265 
1266     private final String name;
1267     private final Version version;
1268     private final String rawVersionString;
1269     private final Set<Modifier> modifiers;
1270     private final boolean open;  // true if modifiers contains OPEN
1271     private final boolean automatic;  // true if modifiers contains AUTOMATIC
1272     private final Set<Requires> requires;
1273     private final Set<Exports> exports;
1274     private final Set<Opens> opens;
1275     private final Set<String> uses;
1276     private final Set<Provides> provides;
1277     private final Set<String> packages;
1278     private final String mainClass;
1279 
1280     private ModuleDescriptor(String name,
1281                              Version version,
1282                              String rawVersionString,
1283                              Set<Modifier> modifiers,
1284                              Set<Requires> requires,
1285                              Set<Exports> exports,
1286                              Set<Opens> opens,
1287                              Set<String> uses,
1288                              Set<Provides> provides,
1289                              Set<String> packages,
1290                              String mainClass)
1291     {
1292         assert version == null || rawVersionString == null;
1293         this.name = name;
1294         this.version = version;
1295         this.rawVersionString = rawVersionString;
1296         this.modifiers = Set.copyOf(modifiers);
1297         this.open = modifiers.contains(Modifier.OPEN);
1298         this.automatic = modifiers.contains(Modifier.AUTOMATIC);
1299         assert (requires.stream().map(Requires::name).distinct().count()
1300                 == requires.size());
1301         this.requires = Set.copyOf(requires);
1302         this.exports = Set.copyOf(exports);
1303         this.opens = Set.copyOf(opens);
1304         this.uses = Set.copyOf(uses);
1305         this.provides = Set.copyOf(provides);
1306 
1307         this.packages = Set.copyOf(packages);
1308         this.mainClass = mainClass;
1309     }
1310 
1311     /**
1312      * Creates a module descriptor from its components.
1313      * The arguments are pre-validated and sets are unmodifiable sets.
1314      */
1315     private ModuleDescriptor(String name,
1316                              Version version,
1317                              Set<Modifier> modifiers,
1318                              Set<Requires> requires,
1319                              Set<Exports> exports,
1320                              Set<Opens> opens,
1321                              Set<String> uses,
1322                              Set<Provides> provides,
1323                              Set<String> packages,
1324                              String mainClass,
1325                              int hashCode,
1326                              boolean unused) {
1327         this.name = name;
1328         this.version = version;
1329         this.rawVersionString = null;
1330         this.modifiers = modifiers;
1331         this.open = modifiers.contains(Modifier.OPEN);
1332         this.automatic = modifiers.contains(Modifier.AUTOMATIC);
1333         this.requires = requires;
1334         this.exports = exports;
1335         this.opens = opens;
1336         this.uses = uses;
1337         this.provides = provides;
1338         this.packages = packages;
1339         this.mainClass = mainClass;
1340         this.hash = hashCode;
1341     }
1342 
1343     /**
1344      * <p> Returns the module name. </p>
1345      *
1346      * @return The module name
1347      */
1348     public String name() {
1349         return name;
1350     }
1351 
1352     /**
1353      * <p> Returns the set of module modifiers. </p>
1354      *
1355      * @return A possibly-empty unmodifiable set of modifiers
1356      */
1357     public Set<Modifier> modifiers() {
1358         return modifiers;
1359     }
1360 
1361     /**
1362      * Returns the set of the {@linkplain AccessFlag module flags}.
1363      *
1364      * @return A possibly-empty unmodifiable set of module flags
1365      * @see #modifiers()
1366      * @jvms 4.7.25 The Module Attribute
1367      * @since 20
1368      */
1369     public Set<AccessFlag> accessFlags() {
1370         int mask = 0;
1371         for (var modifier : modifiers) {
1372             mask |= modifier.mask();
1373         }
1374         return AccessFlag.maskToAccessFlags(mask, AccessFlag.Location.MODULE);
1375     }
1376 
1377     /**
1378      * <p> Returns {@code true} if this is an open module. </p>
1379      *
1380      * <p> This method is equivalent to testing if the set of {@link #modifiers()
1381      * modifiers} contains the {@link Modifier#OPEN OPEN} modifier. </p>
1382      *
1383      * @return  {@code true} if this is an open module
1384      */
1385     public boolean isOpen() {
1386         return open;
1387     }
1388 
1389     /**
1390      * <p> Returns {@code true} if this is an automatic module. </p>
1391      *
1392      * <p> This method is equivalent to testing if the set of {@link #modifiers()
1393      * modifiers} contains the {@link Modifier#AUTOMATIC AUTOMATIC} modifier. </p>
1394      *
1395      * @return  {@code true} if this is an automatic module
1396      */
1397     public boolean isAutomatic() {
1398         return automatic;
1399     }
1400 
1401     /**
1402      * <p> Returns the set of {@code Requires} objects representing the module
1403      * dependences. </p>
1404      *
1405      * <p> The set includes a dependency on "{@code java.base}" when this
1406      * module is not named "{@code java.base}". If this module is an automatic
1407      * module then it does not have a dependency on any module other than
1408      * "{@code java.base}". </p>
1409      *
1410      * @return  A possibly-empty unmodifiable set of {@link Requires} objects
1411      */
1412     public Set<Requires> requires() {
1413         return requires;
1414     }
1415 
1416     /**
1417      * <p> Returns the set of {@code Exports} objects representing the exported
1418      * packages. </p>
1419      *
1420      * <p> If this module is an automatic module then the set of exports
1421      * is empty. </p>
1422      *
1423      * @return  A possibly-empty unmodifiable set of exported packages
1424      */
1425     public Set<Exports> exports() {
1426         return exports;
1427     }
1428 
1429     /**
1430      * <p> Returns the set of {@code Opens} objects representing the open
1431      * packages. </p>
1432      *
1433      * <p> If this module is an open module or an automatic module then the
1434      * set of open packages is empty. </p>
1435      *
1436      * @return  A possibly-empty unmodifiable set of open packages
1437      */
1438     public Set<Opens> opens() {
1439         return opens;
1440     }
1441 
1442     /**
1443      * <p> Returns the set of service dependences. </p>
1444      *
1445      * <p> If this module is an automatic module then the set of service
1446      * dependences is empty. </p>
1447      *
1448      * @return  A possibly-empty unmodifiable set of the {@linkplain ClassLoader##binary-name
1449      *          binary names} of the service types used
1450      */
1451     public Set<String> uses() {
1452         return uses;
1453     }
1454 
1455     /**
1456      * <p> Returns the set of {@code Provides} objects representing the
1457      * services that the module provides. </p>
1458      *
1459      * @return The possibly-empty unmodifiable set of the services that this
1460      *         module provides
1461      */
1462     public Set<Provides> provides() {
1463         return provides;
1464     }
1465 
1466     /**
1467      * <p> Returns the module version. </p>
1468      *
1469      * @return This module's version, or an empty {@code Optional} if the
1470      *         module does not have a version or the version is
1471      *         {@linkplain Version#parse(String) unparseable}
1472      */
1473     public Optional<Version> version() {
1474         return Optional.ofNullable(version);
1475     }
1476 
1477     /**
1478      * <p> Returns the string with the possibly-unparseable version of the
1479      * module. </p>
1480      *
1481      * @return The string containing the version of the module or an empty
1482      *         {@code Optional} if the module does not have a version
1483      *
1484      * @see #version()
1485      */
1486     public Optional<String> rawVersion() {
1487         if (version != null) {
1488             return Optional.of(version.toString());
1489         } else {
1490             return Optional.ofNullable(rawVersionString);
1491         }
1492     }
1493 
1494     /**
1495      * <p> Returns a string containing the module name and, if present, its
1496      * version. </p>
1497      *
1498      * @return A string containing the module name and, if present, its
1499      *         version
1500      */
1501     public String toNameAndVersion() {
1502         if (version != null) {
1503             return name() + "@" + version;
1504         } else {
1505             return name();
1506         }
1507     }
1508 
1509     /**
1510      * <p> Returns the module main class. </p>
1511      *
1512      * @return The {@linkplain ClassLoader##binary-name binary name} of the module's main class
1513      */
1514     public Optional<String> mainClass() {
1515         return Optional.ofNullable(mainClass);
1516     }
1517 
1518     /**
1519      * Returns the set of all packages in the module.
1520      *
1521      * @return A possibly-empty unmodifiable set of the packages in the module
1522      */
1523     public Set<String> packages() {
1524         return packages;
1525     }
1526 
1527 
1528     /**
1529      * A builder for building {@link ModuleDescriptor} objects.
1530      *
1531      * <p> {@code ModuleDescriptor} defines the {@link #newModule newModule},
1532      * {@link #newOpenModule newOpenModule}, and {@link #newAutomaticModule
1533      * newAutomaticModule} methods to create builders for building
1534      * <em>normal</em>, open, and automatic modules. </p>
1535      *
1536      * <p> The set of packages in the module are accumulated by the {@code
1537      * Builder} as the {@link ModuleDescriptor.Builder#exports(String) exports},
1538      * {@link ModuleDescriptor.Builder#opens(String) opens},
1539      * {@link ModuleDescriptor.Builder#packages(Set) packages},
1540      * {@link ModuleDescriptor.Builder#provides(String,List) provides}, and
1541      * {@link ModuleDescriptor.Builder#mainClass(String) mainClass} methods are
1542      * invoked. </p>
1543      *
1544      * <p> The module names, package names, and class names that are parameters
1545      * specified to the builder methods are the module names, package names,
1546      * and qualified names of classes (in named packages) as defined in the
1547      * <cite>The Java Language Specification</cite>. </p>
1548      *
1549      * <p> Example usage: </p>
1550      * {@snippet :
1551      *     ModuleDescriptor descriptor = ModuleDescriptor.newModule("stats.core")
1552      *         .requires("java.base")
1553      *         .exports("org.acme.stats.core.clustering")
1554      *         .exports("org.acme.stats.core.regression")
1555      *         .packages(Set.of("org.acme.stats.core.internal"))
1556      *         .build();
1557      * }
1558      *
1559      * @apiNote A {@code Builder} checks the components and invariants as
1560      * components are added to the builder. The rationale for this is to detect
1561      * errors as early as possible and not defer all validation to the
1562      * {@link #build build} method.
1563      *
1564      * @since 9
1565      */
1566     public static final class Builder {
1567         final String name;
1568         final boolean strict;
1569         final Set<Modifier> modifiers;
1570         final boolean open;
1571         final boolean automatic;
1572         final Set<String> packages = new HashSet<>();
1573         final Map<String, Requires> requires = new HashMap<>();
1574         final Map<String, Exports> exports = new HashMap<>();
1575         final Map<String, Opens> opens = new HashMap<>();
1576         final Set<String> uses = new HashSet<>();
1577         final Map<String, Provides> provides = new HashMap<>();
1578         Version version;
1579         String rawVersionString;
1580         String mainClass;
1581 
1582         /**
1583          * Initializes a new builder with the given module name.
1584          *
1585          * If {@code strict} is {@code true} then module, package, and class
1586          * names are checked to ensure they are legal names. In addition, the
1587          * {@link #build build} method will add "{@code requires java.base}" if
1588          * the dependency is not declared.
1589          */
1590         Builder(String name, boolean strict, Set<Modifier> modifiers) {
1591             this.name = (strict) ? requireModuleName(name) : name;
1592             this.strict = strict;
1593             this.modifiers = modifiers;
1594             this.open = modifiers.contains(Modifier.OPEN);
1595             this.automatic = modifiers.contains(Modifier.AUTOMATIC);
1596             assert !open || !automatic;
1597         }
1598 
1599         /**
1600          * Returns a snapshot of the packages in the module.
1601          */
1602         /* package */ Set<String> packages() {
1603             return Collections.unmodifiableSet(packages);
1604         }
1605 
1606         /**
1607          * Adds a dependence on a module.
1608          *
1609          * @param  req
1610          *         The dependence
1611          *
1612          * @return This builder
1613          *
1614          * @throws IllegalArgumentException
1615          *         If the dependence is on the module that this builder was
1616          *         initialized to build
1617          * @throws IllegalStateException
1618          *         If the dependence on the module has already been declared
1619          *         or this builder is for an automatic module
1620          */
1621         public Builder requires(Requires req) {
1622             if (automatic)
1623                 throw new IllegalStateException("Automatic modules cannot declare"
1624                                                 + " dependences");
1625             String mn = req.name();
1626             if (name.equals(mn))
1627                 throw new IllegalArgumentException("Dependence on self");
1628             if (requires.containsKey(mn))
1629                 throw new IllegalStateException("Dependence upon " + mn
1630                                                 + " already declared");
1631             requires.put(mn, req);
1632             return this;
1633         }
1634 
1635         /**
1636          * Adds a dependence on a module with the given (and possibly empty)
1637          * set of modifiers. The dependence includes the version of the
1638          * module that was recorded at compile-time.
1639          *
1640          * @param  ms
1641          *         The set of modifiers
1642          * @param  mn
1643          *         The module name
1644          * @param  compiledVersion
1645          *         The version of the module recorded at compile-time
1646          *
1647          * @return This builder
1648          *
1649          * @throws IllegalArgumentException
1650          *         If the module name is {@code null}, is not a legal module
1651          *         name, or is equal to the module name that this builder
1652          *         was initialized to build
1653          * @throws IllegalStateException
1654          *         If the dependence on the module has already been declared
1655          *         or this builder is for an automatic module
1656          */
1657         public Builder requires(Set<Requires.Modifier> ms,
1658                                 String mn,
1659                                 Version compiledVersion) {
1660             Objects.requireNonNull(compiledVersion);
1661             if (strict)
1662                 mn = requireModuleName(mn);
1663             return requires(new Requires(ms, mn, compiledVersion, null));
1664         }
1665 
1666         /* package */Builder requires(Set<Requires.Modifier> ms,
1667                                       String mn,
1668                                       String rawCompiledVersion) {
1669             Requires r;
1670             try {
1671                 Version v = Version.parse(rawCompiledVersion);
1672                 r = new Requires(ms, mn, v, null);
1673             } catch (IllegalArgumentException e) {
1674                 if (strict) throw e;
1675                 r = new Requires(ms, mn, null, rawCompiledVersion);
1676             }
1677             return requires(r);
1678         }
1679 
1680         /**
1681          * Adds a dependence on a module with the given (and possibly empty)
1682          * set of modifiers.
1683          *
1684          * @param  ms
1685          *         The set of modifiers
1686          * @param  mn
1687          *         The module name
1688          *
1689          * @return This builder
1690          *
1691          * @throws IllegalArgumentException
1692          *         If the module name is {@code null}, is not a legal module
1693          *         name, or is equal to the module name that this builder
1694          *         was initialized to build
1695          * @throws IllegalStateException
1696          *         If the dependence on the module has already been declared
1697          *         or this builder is for an automatic module
1698          */
1699         public Builder requires(Set<Requires.Modifier> ms, String mn) {
1700             if (strict)
1701                 mn = requireModuleName(mn);
1702             return requires(new Requires(ms, mn, null, null));
1703         }
1704 
1705         /**
1706          * Adds a dependence on a module with an empty set of modifiers.
1707          *
1708          * @param  mn
1709          *         The module name
1710          *
1711          * @return This builder
1712          *
1713          * @throws IllegalArgumentException
1714          *         If the module name is {@code null}, is not a legal module
1715          *         name, or is equal to the module name that this builder
1716          *         was initialized to build
1717          * @throws IllegalStateException
1718          *         If the dependence on the module has already been declared
1719          *         or this builder is for an automatic module
1720          */
1721         public Builder requires(String mn) {
1722             return requires(EnumSet.noneOf(Requires.Modifier.class), mn);
1723         }
1724 
1725         /**
1726          * Adds an exported package.
1727          *
1728          * @param  e
1729          *         The export
1730          *
1731          * @return This builder
1732          *
1733          * @throws IllegalStateException
1734          *         If the {@link Exports#source() package} is already declared as
1735          *         exported or this builder is for an automatic module
1736          */
1737         public Builder exports(Exports e) {
1738             if (automatic) {
1739                 throw new IllegalStateException("Automatic modules cannot declare"
1740                                                  + " exported packages");
1741             }
1742             String source = e.source();
1743             if (exports.containsKey(source)) {
1744                 throw new IllegalStateException("Exported package " + source
1745                                                  + " already declared");
1746             }
1747             exports.put(source, e);
1748             packages.add(source);
1749             return this;
1750         }
1751 
1752         /**
1753          * Adds an exported package with the given (and possibly empty) set of
1754          * modifiers. The package is exported to a set of target modules.
1755          *
1756          * @param  ms
1757          *         The set of modifiers
1758          * @param  pn
1759          *         The package name
1760          * @param  targets
1761          *         The set of target modules names
1762          *
1763          * @return This builder
1764          *
1765          * @throws IllegalArgumentException
1766          *         If the package name is {@code null} or is not a legal
1767          *         package name, the set of target modules is empty, or the set
1768          *         of target modules contains a name that is not a legal module
1769          *         name
1770          * @throws IllegalStateException
1771          *         If the package is already declared as exported
1772          *         or this builder is for an automatic module
1773          */
1774         public Builder exports(Set<Exports.Modifier> ms,
1775                                String pn,
1776                                Set<String> targets)
1777         {
1778             targets = new HashSet<>(targets);
1779             if (targets.isEmpty())
1780                 throw new IllegalArgumentException("Empty target set");
1781             if (strict) {
1782                 requirePackageName(pn);
1783                 targets.forEach(Checks::requireModuleName);
1784             }
1785             Exports e = new Exports(ms, pn, targets);
1786             return exports(e);
1787         }
1788 
1789         /**
1790          * Adds an exported package with the given (and possibly empty) set of
1791          * modifiers. The package is exported to all modules.
1792          *
1793          * @param  ms
1794          *         The set of modifiers
1795          * @param  pn
1796          *         The package name
1797          *
1798          * @return This builder
1799          *
1800          * @throws IllegalArgumentException
1801          *         If the package name is {@code null} or is not a legal
1802          *         package name
1803          * @throws IllegalStateException
1804          *         If the package is already declared as exported
1805          *         or this builder is for an automatic module
1806          */
1807         public Builder exports(Set<Exports.Modifier> ms, String pn) {
1808             if (strict) {
1809                 requirePackageName(pn);
1810             }
1811             Exports e = new Exports(ms, pn, Set.of());
1812             return exports(e);
1813         }
1814 
1815         /**
1816          * Adds an exported package. The package is exported to a set of target
1817          * modules.
1818          *
1819          * @param  pn
1820          *         The package name
1821          * @param  targets
1822          *         The set of target modules names
1823          *
1824          * @return This builder
1825          *
1826          * @throws IllegalArgumentException
1827          *         If the package name is {@code null} or is not a legal
1828          *         package name, the set of target modules is empty, or the set
1829          *         of target modules contains a name that is not a legal module
1830          *         name
1831          * @throws IllegalStateException
1832          *         If the package is already declared as exported
1833          *         or this builder is for an automatic module
1834          */
1835         public Builder exports(String pn, Set<String> targets) {
1836             return exports(Set.of(), pn, targets);
1837         }
1838 
1839         /**
1840          * Adds an exported package. The package is exported to all modules.
1841          *
1842          * @param  pn
1843          *         The package name
1844          *
1845          * @return This builder
1846          *
1847          * @throws IllegalArgumentException
1848          *         If the package name is {@code null} or is not a legal
1849          *         package name
1850          * @throws IllegalStateException
1851          *         If the package is already declared as exported
1852          *         or this builder is for an automatic module
1853          */
1854         public Builder exports(String pn) {
1855             return exports(Set.of(), pn);
1856         }
1857 
1858         /**
1859          * Adds an open package.
1860          *
1861          * @param  obj
1862          *         The {@code Opens} object
1863          *
1864          * @return This builder
1865          *
1866          * @throws IllegalStateException
1867          *         If the package is already declared as open, or this is a
1868          *         builder for an open module or automatic module
1869          */
1870         public Builder opens(Opens obj) {
1871             if (open || automatic) {
1872                 throw new IllegalStateException("Open or automatic modules cannot"
1873                                                 + " declare open packages");
1874             }
1875             String source = obj.source();
1876             if (opens.containsKey(source)) {
1877                 throw new IllegalStateException("Open package " + source
1878                                                 + " already declared");
1879             }
1880             opens.put(source, obj);
1881             packages.add(source);
1882             return this;
1883         }
1884 
1885 
1886         /**
1887          * Adds an open package with the given (and possibly empty) set of
1888          * modifiers. The package is open to a set of target modules.
1889          *
1890          * @param  ms
1891          *         The set of modifiers
1892          * @param  pn
1893          *         The package name
1894          * @param  targets
1895          *         The set of target modules names
1896          *
1897          * @return This builder
1898          *
1899          * @throws IllegalArgumentException
1900          *         If the package name is {@code null} or is not a legal
1901          *         package name, the set of target modules is empty, or the set
1902          *         of target modules contains a name that is not a legal module
1903          *         name
1904          * @throws IllegalStateException
1905          *         If the package is already declared as open, or this is a
1906          *         builder for an open module or automatic module
1907          */
1908         public Builder opens(Set<Opens.Modifier> ms,
1909                              String pn,
1910                              Set<String> targets)
1911         {
1912             targets = new HashSet<>(targets);
1913             if (targets.isEmpty())
1914                 throw new IllegalArgumentException("Empty target set");
1915             if (strict) {
1916                 requirePackageName(pn);
1917                 targets.forEach(Checks::requireModuleName);
1918             }
1919             Opens opens = new Opens(ms, pn, targets);
1920             return opens(opens);
1921         }
1922 
1923         /**
1924          * Adds an open package with the given (and possibly empty) set of
1925          * modifiers. The package is open to all modules.
1926          *
1927          * @param  ms
1928          *         The set of modifiers
1929          * @param  pn
1930          *         The package name
1931          *
1932          * @return This builder
1933          *
1934          * @throws IllegalArgumentException
1935          *         If the package name is {@code null} or is not a legal
1936          *         package name
1937          * @throws IllegalStateException
1938          *         If the package is already declared as open, or this is a
1939          *         builder for an open module or automatic module
1940          */
1941         public Builder opens(Set<Opens.Modifier> ms, String pn) {
1942             if (strict) {
1943                 requirePackageName(pn);
1944             }
1945             Opens e = new Opens(ms, pn, Set.of());
1946             return opens(e);
1947         }
1948 
1949         /**
1950          * Adds an open package. The package is open to a set of target modules.
1951          *
1952          * @param  pn
1953          *         The package name
1954          * @param  targets
1955          *         The set of target modules names
1956          *
1957          * @return This builder
1958          *
1959          * @throws IllegalArgumentException
1960          *         If the package name is {@code null} or is not a legal
1961          *         package name, the set of target modules is empty, or the set
1962          *         of target modules contains a name that is not a legal module
1963          *         name
1964          * @throws IllegalStateException
1965          *         If the package is already declared as open, or this is a
1966          *         builder for an open module or automatic module
1967          */
1968         public Builder opens(String pn, Set<String> targets) {
1969             return opens(Set.of(), pn, targets);
1970         }
1971 
1972         /**
1973          * Adds an open package. The package is open to all modules.
1974          *
1975          * @param  pn
1976          *         The package name
1977          *
1978          * @return This builder
1979          *
1980          * @throws IllegalArgumentException
1981          *         If the package name is {@code null} or is not a legal
1982          *         package name
1983          * @throws IllegalStateException
1984          *         If the package is already declared as open, or this is a
1985          *         builder for an open module or automatic module
1986          */
1987         public Builder opens(String pn) {
1988             return opens(Set.of(), pn);
1989         }
1990 
1991         /**
1992          * Adds a service dependence.
1993          *
1994          * @param  service
1995          *         The service type
1996          *
1997          * @return This builder
1998          *
1999          * @throws IllegalArgumentException
2000          *         If the service type is {@code null} or not a qualified name of
2001          *         a class in a named package
2002          * @throws IllegalStateException
2003          *         If a dependency on the service type has already been declared
2004          *         or this is a builder for an automatic module
2005          */
2006         public Builder uses(String service) {
2007             if (automatic)
2008                 throw new IllegalStateException("Automatic modules can not declare"
2009                                                 + " service dependences");
2010             if (uses.contains(requireServiceTypeName(service)))
2011                 throw new IllegalStateException("Dependence upon service "
2012                                                 + service + " already declared");
2013             uses.add(service);
2014             return this;
2015         }
2016 
2017         /**
2018          * Provides a service with one or more implementations. The package for
2019          * each {@link Provides#providers() provider} (or provider factory) is
2020          * added to the module if not already added.
2021          *
2022          * @param  p
2023          *         The provides
2024          *
2025          * @return This builder
2026          *
2027          * @throws IllegalStateException
2028          *         If the providers for the service type have already been
2029          *         declared
2030          */
2031         public Builder provides(Provides p) {
2032             String service = p.service();
2033             if (provides.containsKey(service))
2034                 throw new IllegalStateException("Providers of service "
2035                                                 + service + " already declared");
2036             provides.put(service, p);
2037             p.providers().forEach(name -> packages.add(packageName(name)));
2038             return this;
2039         }
2040 
2041         /**
2042          * Provides implementations of a service. The package for each provider
2043          * (or provider factory) is added to the module if not already added.
2044          *
2045          * @param  service
2046          *         The service type
2047          * @param  providers
2048          *         The list of provider or provider factory class names
2049          *
2050          * @return This builder
2051          *
2052          * @throws IllegalArgumentException
2053          *         If the service type or any of the provider class names is
2054          *         {@code null} or not a qualified name of a class in a named
2055          *         package, or the list of provider class names is empty
2056          * @throws IllegalStateException
2057          *         If the providers for the service type have already been
2058          *         declared
2059          */
2060         public Builder provides(String service, List<String> providers) {
2061             providers = new ArrayList<>(providers);
2062             if (providers.isEmpty())
2063                 throw new IllegalArgumentException("Empty providers set");
2064             if (strict) {
2065                 requireServiceTypeName(service);
2066                 providers.forEach(Checks::requireServiceProviderName);
2067             } else {
2068                 // Disallow service/providers in unnamed package
2069                 String pn = packageName(service);
2070                 if (pn.isEmpty()) {
2071                     throw new IllegalArgumentException(service
2072                                                        + ": unnamed package");
2073                 }
2074                 for (String name : providers) {
2075                     pn = packageName(name);
2076                     if (pn.isEmpty()) {
2077                         throw new IllegalArgumentException(name
2078                                                            + ": unnamed package");
2079                     }
2080                 }
2081             }
2082             Provides p = new Provides(service, providers);
2083             return provides(p);
2084         }
2085 
2086         /**
2087          * Adds packages to the module. All packages in the set of package names
2088          * that are not in the module are added to module.
2089          *
2090          * @param  pns
2091          *         The (possibly empty) set of package names
2092          *
2093          * @return This builder
2094          *
2095          * @throws IllegalArgumentException
2096          *         If any of the package names is {@code null} or is not a
2097          *         legal package name
2098          */
2099         public Builder packages(Set<String> pns) {
2100             if (strict) {
2101                 pns = new HashSet<>(pns);
2102                 pns.forEach(Checks::requirePackageName);
2103             }
2104             this.packages.addAll(pns);
2105             return this;
2106         }
2107 
2108         /**
2109          * Sets the module version.
2110          *
2111          * @param  v
2112          *         The version
2113          *
2114          * @return This builder
2115          */
2116         public Builder version(Version v) {
2117             version = requireNonNull(v);
2118             rawVersionString = null;
2119             return this;
2120         }
2121 
2122         /**
2123          * Sets the module version.
2124          *
2125          * @param  vs
2126          *         The version string to parse
2127          *
2128          * @return This builder
2129          *
2130          * @throws IllegalArgumentException
2131          *         If {@code vs} is {@code null} or cannot be parsed as a
2132          *         version string
2133          *
2134          * @see Version#parse(String)
2135          */
2136         public Builder version(String vs) {
2137             try {
2138                 version = Version.parse(vs);
2139                 rawVersionString = null;
2140             } catch (IllegalArgumentException e) {
2141                 if (strict) throw e;
2142                 version = null;
2143                 rawVersionString = vs;
2144             }
2145             return this;
2146         }
2147 
2148         /**
2149          * Sets the module main class. The package for the main class is added
2150          * to the module if not already added. In other words, this method is
2151          * equivalent to first invoking this builder's {@link #packages(Set)
2152          * packages} method to add the package name of the main class.
2153          *
2154          * @param  mc
2155          *         The module main class
2156          *
2157          * @return This builder
2158          *
2159          * @throws IllegalArgumentException
2160          *         If {@code mainClass} is {@code null} or not a qualified
2161          *         name of a class in a named package
2162          */
2163         public Builder mainClass(String mc) {
2164             String pn;
2165             if (strict) {
2166                 mc = requireQualifiedClassName("main class name", mc);
2167                 pn = packageName(mc);
2168                 assert !pn.isEmpty();
2169             } else {
2170                 // Disallow main class in unnamed package
2171                 pn = packageName(mc);
2172                 if (pn.isEmpty()) {
2173                     throw new IllegalArgumentException(mc + ": unnamed package");
2174                 }
2175             }
2176             packages.add(pn);
2177             mainClass = mc;
2178             return this;
2179         }
2180 
2181         /**
2182          * Builds and returns a {@code ModuleDescriptor} from its components.
2183          *
2184          * <p> The module will require "{@code java.base}" even if the dependence
2185          * has not been declared (the exception is when building a module named
2186          * "{@code java.base}" as it cannot require itself). The dependence on
2187          * "{@code java.base}" will have the {@link
2188          * java.lang.module.ModuleDescriptor.Requires.Modifier#MANDATED MANDATED}
2189          * modifier if the dependence was not declared. </p>
2190          *
2191          * @return The module descriptor
2192          */
2193         public ModuleDescriptor build() {
2194             Set<Requires> requires = new HashSet<>(this.requires.values());
2195             Set<Exports> exports = new HashSet<>(this.exports.values());
2196             Set<Opens> opens = new HashSet<>(this.opens.values());
2197 
2198             // add dependency on java.base
2199             if (strict
2200                     && !name.equals("java.base")
2201                     && !this.requires.containsKey("java.base")) {
2202                 requires.add(new Requires(Set.of(Requires.Modifier.MANDATED),
2203                                           "java.base",
2204                                           null,
2205                                           null));
2206             }
2207 
2208             Set<Provides> provides = new HashSet<>(this.provides.values());
2209 
2210             return new ModuleDescriptor(name,
2211                                         version,
2212                                         rawVersionString,
2213                                         modifiers,
2214                                         requires,
2215                                         exports,
2216                                         opens,
2217                                         uses,
2218                                         provides,
2219                                         packages,
2220                                         mainClass);
2221         }
2222 
2223     }
2224 
2225     /**
2226      * Compares this module descriptor to another.
2227      *
2228      * <p> Two {@code ModuleDescriptor} objects are compared by comparing their
2229      * module names lexicographically. Where the module names are equal then the
2230      * module versions are compared. When comparing the module versions then a
2231      * module descriptor with a version is considered to succeed a module
2232      * descriptor that does not have a version. If both versions are {@linkplain
2233      * Version#parse(String) unparseable} then the {@linkplain #rawVersion()
2234      * raw version strings} are compared lexicographically. Where the module names
2235      * are equal and the versions are equal (or not present in both), then the
2236      * set of modifiers are compared. Sets of modifiers are compared by comparing
2237      * a <em>binary value</em> computed for each set. If a modifier is present
2238      * in the set then the bit at the position of its ordinal is {@code 1}
2239      * in the binary value, otherwise {@code 0}. If the two set of modifiers
2240      * are also equal then the other components of the module descriptors are
2241      * compared in a manner that is consistent with {@code equals}. </p>
2242      *
2243      * @param  that
2244      *         The module descriptor to compare
2245      *
2246      * @return A negative integer, zero, or a positive integer if this module
2247      *         descriptor is less than, equal to, or greater than the given
2248      *         module descriptor
2249      */
2250     @Override
2251     public int compareTo(ModuleDescriptor that) {
2252         if (this == that) return 0;
2253 
2254         int c = this.name().compareTo(that.name());
2255         if (c != 0) return c;
2256 
2257         c = compare(this.version, that.version);
2258         if (c != 0) return c;
2259 
2260         c = compare(this.rawVersionString, that.rawVersionString);
2261         if (c != 0) return c;
2262 
2263         long v1 = modsValue(this.modifiers());
2264         long v2 = modsValue(that.modifiers());
2265         c = Long.compare(v1, v2);
2266         if (c != 0) return c;
2267 
2268         c = compare(this.requires, that.requires);
2269         if (c != 0) return c;
2270 
2271         c = compare(this.packages, that.packages);
2272         if (c != 0) return c;
2273 
2274         c = compare(this.exports, that.exports);
2275         if (c != 0) return c;
2276 
2277         c = compare(this.opens, that.opens);
2278         if (c != 0) return c;
2279 
2280         c = compare(this.uses, that.uses);
2281         if (c != 0) return c;
2282 
2283         c = compare(this.provides, that.provides);
2284         if (c != 0) return c;
2285 
2286         c = compare(this.mainClass, that.mainClass);
2287         if (c != 0) return c;
2288 
2289         return 0;
2290     }
2291 
2292     /**
2293      * Tests this module descriptor for equality with the given object.
2294      *
2295      * <p> If the given object is not a {@code ModuleDescriptor} then this
2296      * method returns {@code false}. Two module descriptors are equal if each
2297      * of their corresponding components is equal. </p>
2298      *
2299      * <p> This method satisfies the general contract of the {@link
2300      * java.lang.Object#equals(Object) Object.equals} method. </p>
2301      *
2302      * @param   ob
2303      *          the object to which this object is to be compared
2304      *
2305      * @return  {@code true} if, and only if, the given object is a module
2306      *          descriptor that is equal to this module descriptor
2307      */
2308     @Override
2309     public boolean equals(Object ob) {
2310         if (ob == this)
2311             return true;
2312         return (ob instanceof ModuleDescriptor that)
2313                 && (name.equals(that.name)
2314                 && modifiers.equals(that.modifiers)
2315                 && requires.equals(that.requires)
2316                 && Objects.equals(packages, that.packages)
2317                 && exports.equals(that.exports)
2318                 && opens.equals(that.opens)
2319                 && uses.equals(that.uses)
2320                 && provides.equals(that.provides)
2321                 && Objects.equals(version, that.version)
2322                 && Objects.equals(rawVersionString, that.rawVersionString)
2323                 && Objects.equals(mainClass, that.mainClass));
2324     }
2325 
2326     /**
2327      * Computes a hash code for this module descriptor.
2328      *
2329      * <p> The hash code is based upon the components of the module descriptor,
2330      * and satisfies the general contract of the {@link Object#hashCode
2331      * Object.hashCode} method. </p>
2332      *
2333      * @return The hash-code value for this module descriptor
2334      */
2335     @Override
2336     public int hashCode() {
2337         int hc = hash;
2338         if (hc == 0) {
2339             hc = name.hashCode();
2340             hc = hc * 43 + modsHashCode(modifiers);
2341             hc = hc * 43 + requires.hashCode();
2342             hc = hc * 43 + Objects.hashCode(packages);
2343             hc = hc * 43 + exports.hashCode();
2344             hc = hc * 43 + opens.hashCode();
2345             hc = hc * 43 + uses.hashCode();
2346             hc = hc * 43 + provides.hashCode();
2347             hc = hc * 43 + Objects.hashCode(version);
2348             hc = hc * 43 + Objects.hashCode(rawVersionString);
2349             hc = hc * 43 + Objects.hashCode(mainClass);
2350             if (hc == 0)
2351                 hc = -1;
2352             hash = hc;
2353         }
2354         return hc;
2355     }
2356     private transient int hash;  // cached hash code
2357 
2358     /**
2359      * <p> Returns a string describing the module. </p>
2360      *
2361      * @return A string describing the module
2362      */
2363     @Override
2364     public String toString() {
2365         StringBuilder sb = new StringBuilder();
2366 
2367         if (isOpen())
2368             sb.append("open ");
2369         sb.append("module { name: ").append(toNameAndVersion());
2370         if (!requires.isEmpty())
2371             sb.append(", ").append(requires);
2372         if (!uses.isEmpty())
2373             sb.append(", uses: ").append(uses);
2374         if (!exports.isEmpty())
2375             sb.append(", exports: ").append(exports);
2376         if (!opens.isEmpty())
2377             sb.append(", opens: ").append(opens);
2378         if (!provides.isEmpty()) {
2379             sb.append(", provides: ").append(provides);
2380         }
2381         sb.append(" }");
2382         return sb.toString();
2383     }
2384 
2385 
2386     /**
2387      * Instantiates a builder to build a module descriptor.
2388      *
2389      * @param  name
2390      *         The module name
2391      * @param  ms
2392      *         The set of module modifiers
2393      *
2394      * @return A new builder
2395      *
2396      * @throws IllegalArgumentException
2397      *         If the module name is {@code null} or is not a legal module
2398      *         name, or the set of modifiers contains {@link
2399      *         Modifier#AUTOMATIC AUTOMATIC} with other modifiers
2400      */
2401     public static Builder newModule(String name, Set<Modifier> ms) {
2402         Set<Modifier> mods = new HashSet<>(ms);
2403         if (mods.contains(Modifier.AUTOMATIC) && mods.size() > 1)
2404             throw new IllegalArgumentException("AUTOMATIC cannot be used with"
2405                                                + " other modifiers");
2406 
2407         return new Builder(name, true, mods);
2408     }
2409 
2410     /**
2411      * Instantiates a builder to build a module descriptor for a <em>normal</em>
2412      * module. This method is equivalent to invoking {@link #newModule(String,Set)
2413      * newModule} with an empty set of {@link ModuleDescriptor.Modifier modifiers}.
2414      *
2415      * @param  name
2416      *         The module name
2417      *
2418      * @return A new builder
2419      *
2420      * @throws IllegalArgumentException
2421      *         If the module name is {@code null} or is not a legal module
2422      *         name
2423      */
2424     public static Builder newModule(String name) {
2425         return new Builder(name, true, Set.of());
2426     }
2427 
2428     /**
2429      * Instantiates a builder to build a module descriptor for an open module.
2430      * This method is equivalent to invoking {@link #newModule(String,Set)
2431      * newModule} with the {@link ModuleDescriptor.Modifier#OPEN OPEN} modifier.
2432      *
2433      * <p> The builder for an open module cannot be used to declare any open
2434      * packages. </p>
2435      *
2436      * @param  name
2437      *         The module name
2438      *
2439      * @return A new builder that builds an open module
2440      *
2441      * @throws IllegalArgumentException
2442      *         If the module name is {@code null} or is not a legal module
2443      *         name
2444      */
2445     public static Builder newOpenModule(String name) {
2446         return new Builder(name, true, Set.of(Modifier.OPEN));
2447     }
2448 
2449     /**
2450      * Instantiates a builder to build a module descriptor for an automatic
2451      * module. This method is equivalent to invoking {@link #newModule(String,Set)
2452      * newModule} with the {@link ModuleDescriptor.Modifier#AUTOMATIC AUTOMATIC}
2453      * modifier.
2454      *
2455      * <p> The builder for an automatic module cannot be used to declare module
2456      * or service dependences. It also cannot be used to declare any exported
2457      * or open packages. </p>
2458      *
2459      * @param  name
2460      *         The module name
2461      *
2462      * @return A new builder that builds an automatic module
2463      *
2464      * @throws IllegalArgumentException
2465      *         If the module name is {@code null} or is not a legal module
2466      *         name
2467      *
2468      * @see ModuleFinder#of(Path[])
2469      */
2470     public static Builder newAutomaticModule(String name) {
2471         return new Builder(name, true, Set.of(Modifier.AUTOMATIC));
2472     }
2473 
2474 
2475     /**
2476      * Reads the binary form of a module declaration from an input stream
2477      * as a module descriptor.
2478      *
2479      * <p> If the descriptor encoded in the input stream does not indicate a
2480      * set of packages in the module then the {@code packageFinder} will be
2481      * invoked. The set of packages that the {@code packageFinder} returns
2482      * must include all the packages that the module exports, opens, as well
2483      * as the packages of the service implementations that the module provides,
2484      * and the package of the main class (if the module has a main class). If
2485      * the {@code packageFinder} throws an {@link UncheckedIOException} then
2486      * {@link IOException} cause will be re-thrown. </p>
2487      *
2488      * <p> If there are bytes following the module descriptor then it is
2489      * implementation specific as to whether those bytes are read, ignored,
2490      * or reported as an {@code InvalidModuleDescriptorException}. If this
2491      * method fails with an {@code InvalidModuleDescriptorException} or {@code
2492      * IOException} then it may do so after some, but not all, bytes have
2493      * been read from the input stream. It is strongly recommended that the
2494      * stream be promptly closed and discarded if an exception occurs. </p>
2495      *
2496      * @apiNote The {@code packageFinder} parameter is for use when reading
2497      * module descriptors from legacy module-artifact formats that do not
2498      * record the set of packages in the descriptor itself.
2499      *
2500      * @param  in
2501      *         The input stream
2502      * @param  packageFinder
2503      *         A supplier that can produce the set of packages
2504      *
2505      * @return The module descriptor
2506      *
2507      * @throws InvalidModuleDescriptorException
2508      *         If an invalid module descriptor is detected or the set of
2509      *         packages returned by the {@code packageFinder} does not include
2510      *         all of the packages obtained from the module descriptor
2511      * @throws IOException
2512      *         If an I/O error occurs reading from the input stream or {@code
2513      *         UncheckedIOException} is thrown by the package finder
2514      */
2515     public static ModuleDescriptor read(InputStream in,
2516                                         Supplier<Set<String>> packageFinder)
2517         throws IOException
2518     {
2519         return ModuleInfo.read(in, requireNonNull(packageFinder)).descriptor();
2520     }
2521 
2522     /**
2523      * Reads the binary form of a module declaration from an input stream as a
2524      * module descriptor. This method works exactly as specified by the 2-arg
2525      * {@link #read(InputStream,Supplier) read} method with the exception that
2526      * a package finder is not used to find additional packages when the
2527      * module descriptor read from the stream does not indicate the set of
2528      * packages.
2529      *
2530      * @param  in
2531      *         The input stream
2532      *
2533      * @return The module descriptor
2534      *
2535      * @throws InvalidModuleDescriptorException
2536      *         If an invalid module descriptor is detected
2537      * @throws IOException
2538      *         If an I/O error occurs reading from the input stream
2539      */
2540     public static ModuleDescriptor read(InputStream in) throws IOException {
2541         return ModuleInfo.read(in, null).descriptor();
2542     }
2543 
2544     /**
2545      * Reads the binary form of a module declaration from a byte buffer
2546      * as a module descriptor.
2547      *
2548      * <p> If the descriptor encoded in the byte buffer does not indicate a
2549      * set of packages in the module then the {@code packageFinder} will be
2550      * invoked. The set of packages that the {@code packageFinder} returns
2551      * must include all the packages that the module exports, opens, as well
2552      * as the packages of the service implementations that the module provides,
2553      * and the package of the main class (if the module has a main class). If
2554      * the {@code packageFinder} throws an {@link UncheckedIOException} then
2555      * {@link IOException} cause will be re-thrown. </p>
2556      *
2557      * <p> The module descriptor is read from the buffer starting at index
2558      * {@code p}, where {@code p} is the buffer's {@link ByteBuffer#position()
2559      * position} when this method is invoked. Upon return the buffer's position
2560      * will be equal to {@code p + n} where {@code n} is the number of bytes
2561      * read from the buffer. </p>
2562      *
2563      * <p> If there are bytes following the module descriptor then it is
2564      * implementation specific as to whether those bytes are read, ignored,
2565      * or reported as an {@code InvalidModuleDescriptorException}. If this
2566      * method fails with an {@code InvalidModuleDescriptorException} then it
2567      * may do so after some, but not all, bytes have been read. </p>
2568      *
2569      * @apiNote The {@code packageFinder} parameter is for use when reading
2570      * module descriptors from legacy module-artifact formats that do not
2571      * record the set of packages in the descriptor itself.
2572      *
2573      * @param  bb
2574      *         The byte buffer
2575      * @param  packageFinder
2576      *         A supplier that can produce the set of packages
2577      *
2578      * @return The module descriptor
2579      *
2580      * @throws InvalidModuleDescriptorException
2581      *         If an invalid module descriptor is detected or the set of
2582      *         packages returned by the {@code packageFinder} does not include
2583      *         all of the packages obtained from the module descriptor
2584      */
2585     public static ModuleDescriptor read(ByteBuffer bb,
2586                                         Supplier<Set<String>> packageFinder)
2587     {
2588         return ModuleInfo.read(bb, requireNonNull(packageFinder)).descriptor();
2589     }
2590 
2591     /**
2592      * Reads the binary form of a module declaration from a byte buffer as a
2593      * module descriptor. This method works exactly as specified by the 2-arg
2594      * {@link #read(ByteBuffer,Supplier) read} method with the exception that a
2595      * package finder is not used to find additional packages when the module
2596      * descriptor encoded in the buffer does not indicate the set of packages.
2597      *
2598      * @param  bb
2599      *         The byte buffer
2600      *
2601      * @return The module descriptor
2602      *
2603      * @throws InvalidModuleDescriptorException
2604      *         If an invalid module descriptor is detected
2605      */
2606     public static ModuleDescriptor read(ByteBuffer bb) {
2607         return ModuleInfo.read(bb, null).descriptor();
2608     }
2609 
2610     private static String packageName(String cn) {
2611         int index = cn.lastIndexOf('.');
2612         return (index == -1) ? "" : cn.substring(0, index);
2613     }
2614 
2615     /**
2616      * Returns a string containing the given set of modifiers and label.
2617      */
2618     private static <M> String toString(Set<M> mods, String what) {
2619         return (Stream.concat(mods.stream().map(e -> e.toString()
2620                                                       .toLowerCase(Locale.ROOT)),
2621                               Stream.of(what)))
2622                 .collect(Collectors.joining(" "));
2623     }
2624 
2625     /**
2626      * Generates and returns a hashcode for the enum instances. The returned hashcode
2627      * is a value based on the {@link Enum#name() name} of each enum instance.
2628      */
2629     private static int modsHashCode(Iterable<? extends Enum<?>> enums) {
2630         int h = 0;
2631         for (Enum<?> e : enums) {
2632             h += e.name().hashCode();
2633         }
2634         return h;
2635     }
2636 
2637     private static <T extends Object & Comparable<? super T>>
2638     int compare(T obj1, T obj2) {
2639         if (obj1 != null) {
2640             return (obj2 != null) ? obj1.compareTo(obj2) : 1;
2641         } else {
2642             return (obj2 == null) ? 0 : -1;
2643         }
2644     }
2645 
2646     /**
2647      * Compares two sets of {@code Comparable} objects.
2648      */
2649     @SuppressWarnings("unchecked")
2650     private static <T extends Object & Comparable<? super T>>
2651     int compare(Set<T> s1, Set<T> s2) {
2652         T[] a1 = (T[]) s1.toArray();
2653         T[] a2 = (T[]) s2.toArray();
2654         Arrays.sort(a1);
2655         Arrays.sort(a2);
2656         return Arrays.compare(a1, a2);
2657     }
2658 
2659     private static <E extends Enum<E>> long modsValue(Set<E> set) {
2660         long value = 0;
2661         for (Enum<E> e : set) {
2662             value += 1 << e.ordinal();
2663         }
2664         return value;
2665     }
2666 
2667     static {
2668         runtimeSetup();
2669     }
2670 
2671     // Called from JVM when loading an AOT cache
2672     private static void runtimeSetup() {
2673         /**
2674          * Setup the shared secret to allow code in other packages access
2675          * private package methods in java.lang.module.
2676          */
2677         jdk.internal.access.SharedSecrets
2678             .setJavaLangModuleAccess(new jdk.internal.access.JavaLangModuleAccess() {
2679                 @Override
2680                 public Builder newModuleBuilder(String mn,
2681                                                 boolean strict,
2682                                                 Set<ModuleDescriptor.Modifier> modifiers) {
2683                     return new Builder(mn, strict, modifiers);
2684                 }
2685 
2686                 @Override
2687                 public Set<String> packages(ModuleDescriptor.Builder builder) {
2688                     return builder.packages();
2689                 }
2690 
2691                 @Override
2692                 public void requires(ModuleDescriptor.Builder builder,
2693                                      Set<Requires.Modifier> ms,
2694                                      String mn,
2695                                      String rawCompiledVersion) {
2696                     builder.requires(ms, mn, rawCompiledVersion);
2697                 }
2698 
2699                 @Override
2700                 public Requires newRequires(Set<Requires.Modifier> ms, String mn, Version v) {
2701                     return new Requires(ms, mn, v, true);
2702                 }
2703 
2704                 @Override
2705                 public Exports newExports(Set<Exports.Modifier> ms, String source) {
2706                     return new Exports(ms, source, Set.of(), true);
2707                 }
2708 
2709                 @Override
2710                 public Exports newExports(Set<Exports.Modifier> ms,
2711                                           String source,
2712                                           Set<String> targets) {
2713                     return new Exports(ms, source, targets, true);
2714                 }
2715 
2716                 @Override
2717                 public Opens newOpens(Set<Opens.Modifier> ms,
2718                                       String source,
2719                                       Set<String> targets) {
2720                     return new Opens(ms, source, targets, true);
2721                 }
2722 
2723                 @Override
2724                 public Opens newOpens(Set<Opens.Modifier> ms, String source) {
2725                     return new Opens(ms, source, Set.of(), true);
2726                 }
2727 
2728                 @Override
2729                 public Provides newProvides(String service, List<String> providers) {
2730                     return new Provides(service, providers, true);
2731                 }
2732 
2733                 @Override
2734                 public ModuleDescriptor newModuleDescriptor(String name,
2735                                                             Version version,
2736                                                             Set<ModuleDescriptor.Modifier> modifiers,
2737                                                             Set<Requires> requires,
2738                                                             Set<Exports> exports,
2739                                                             Set<Opens> opens,
2740                                                             Set<String> uses,
2741                                                             Set<Provides> provides,
2742                                                             Set<String> packages,
2743                                                             String mainClass,
2744                                                             int hashCode) {
2745                     return new ModuleDescriptor(name,
2746                                                 version,
2747                                                 modifiers,
2748                                                 requires,
2749                                                 exports,
2750                                                 opens,
2751                                                 uses,
2752                                                 provides,
2753                                                 packages,
2754                                                 mainClass,
2755                                                 hashCode,
2756                                                 false);
2757                 }
2758 
2759                 @Override
2760                 public Configuration resolveAndBind(ModuleFinder finder,
2761                                                     Collection<String> roots,
2762                                                     PrintStream traceOutput)
2763                 {
2764                     return Configuration.resolveAndBind(finder, roots, traceOutput);
2765                 }
2766 
2767                 @Override
2768                 public Configuration newConfiguration(ModuleFinder finder,
2769                                                       Map<String, Set<String>> graph) {
2770                     return new Configuration(finder, graph);
2771                 }
2772             });
2773     }
2774 
2775 }