diff --git a/src/main/java/com/volmit/ModuleInfo.java b/src/main/java/com/volmit/ModuleInfo.java index 3a1ed26f0..7a6d3a84a 100644 --- a/src/main/java/com/volmit/ModuleInfo.java +++ b/src/main/java/com/volmit/ModuleInfo.java @@ -1,23 +1,46 @@ package com.volmit; import com.volmit.resource.ResourceId; +import java.util.Arrays; +import java.util.List; import java.util.Objects; /** Module identity. Stages a module defines must use the namespace of its id. The name is for * people, for example in load logs; the id is what the host and other modules match on. Name and * version must fit on one log line, so they reject control characters such as line breaks. + * + *

Optional packages are packages, with their subpackages, whose classes the module's jar uses + * but expects may be absent at runtime, typically optional integrations of a library it bundles. + * The pack load does not warn about missing classes in them. They never excuse a class that Iris + * hides from modules or one missing from a package Iris exposes; those still fail the load. */ -public record ModuleInfo(ResourceId id, String name, String version) { +public record ModuleInfo(ResourceId id, String name, String version, List optionalPackages) { public ModuleInfo { Objects.requireNonNull(id, "id"); Objects.requireNonNull(name, "name"); Objects.requireNonNull(version, "version"); requireOneLineText(id, "name", name); requireOneLineText(id, "version", version); + optionalPackages = List.copyOf(optionalPackages); } public static ModuleInfo of(String id, String name, String version) { - return new ModuleInfo(ResourceId.parse(id), name, version); + return new ModuleInfo(ResourceId.parse(id), name, version, List.of()); + } + + /** This identity with {@code packages} as its optional packages, replacing any declared before. + * A trailing dot is accepted; anything that is not a package name, such as a wildcard, is rejected. + */ + public ModuleInfo withOptionalPackages(String... packages) { + var parsed = Arrays.stream(packages).map(this::requireOptionalPackage).toList(); + return new ModuleInfo(id, name, version, parsed); + } + + private PackageName requireOptionalPackage(String packageName) { + Objects.requireNonNull(packageName, "optional package"); + return PackageName.tryParse(packageName).orElseThrow(() -> new IllegalArgumentException("Optional package '" + + packageName + "' of module " + id + " is not a package name; name a package such as org.slf4j," + + " which covers that package and its subpackages")); } private static void requireOneLineText(ResourceId id, String field, String value) { diff --git a/src/main/java/com/volmit/PackageName.java b/src/main/java/com/volmit/PackageName.java new file mode 100644 index 000000000..2fcce8b0c --- /dev/null +++ b/src/main/java/com/volmit/PackageName.java @@ -0,0 +1,51 @@ +package com.volmit; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; + +/** A Java package name that stands for the package and all its subpackages. Only whole package + * names match: {@code com.volmit} contains {@code com.volmit.stage.Stage} but not + * {@code com.volmitx.Fake}. + */ +public record PackageName(String name) implements Comparable { + private static final char SEPARATOR = '.'; + private static final String SEPARATOR_PATTERN = "\\."; + + public PackageName { + Objects.requireNonNull(name, "name"); + if (!isPackageName(name)) throw new IllegalArgumentException("'" + name + "' is not a package name"); + } + + /** The package {@code name} denotes, if it is a package name. A trailing dot is accepted; blank + * names, wildcards and anything else that is not a package name give an empty result. + */ + public static Optional tryParse(String name) { + Objects.requireNonNull(name, "name"); + var withoutTrailingDot = name.endsWith(String.valueOf(SEPARATOR)) ? name.substring(0, name.length() - 1) : name; + return isPackageName(withoutTrailingDot) ? Optional.of(new PackageName(withoutTrailingDot)) : Optional.empty(); + } + + /** Whether the class with this binary name is in this package or one of its subpackages. */ + public boolean contains(String binaryName) { + return binaryName.startsWith(name) + && binaryName.length() > name.length() + && binaryName.charAt(name.length()) == SEPARATOR; + } + + @Override + public String toString() { return name; } + + @Override + public int compareTo(PackageName other) { return name.compareTo(other.name); } + + private static boolean isPackageName(String name) { + return Arrays.stream(name.split(SEPARATOR_PATTERN, -1)).allMatch(PackageName::isIdentifier); + } + + private static boolean isIdentifier(String segment) { + return !segment.isEmpty() + && Character.isJavaIdentifierStart(segment.codePointAt(0)) + && segment.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart); + } +} diff --git a/src/main/java/com/volmit/host/ExposedPackages.java b/src/main/java/com/volmit/host/ExposedPackages.java index cda1329a8..8c9162bca 100644 --- a/src/main/java/com/volmit/host/ExposedPackages.java +++ b/src/main/java/com/volmit/host/ExposedPackages.java @@ -1,7 +1,7 @@ package com.volmit.host; import com.volmit.IrisModule; -import java.util.Arrays; +import com.volmit.PackageName; import java.util.Collection; import java.util.Comparator; import java.util.List; @@ -16,13 +16,13 @@ import java.util.TreeSet; final class ExposedPackages { /** The root package of the Iris API. Module classes must not use it. */ static final String API_PACKAGE = IrisModule.class.getPackageName(); + private static final PackageName API = new PackageName(API_PACKAGE); private static final char PACKAGE_SEPARATOR = '.'; private static final char PATH_SEPARATOR = '/'; - private static final String PACKAGE_SEPARATOR_PATTERN = "\\."; - private final List packages; + private final List packages; - private ExposedPackages(List packages) { + private ExposedPackages(List packages) { this.packages = List.copyOf(packages); } @@ -35,18 +35,18 @@ final class ExposedPackages { */ static ExposedPackages apiAnd(Collection hostPackages) { Objects.requireNonNull(hostPackages, "hostPackages"); - var packages = new TreeSet(); - packages.add(API_PACKAGE); + var packages = new TreeSet(); + packages.add(API); hostPackages.forEach(name -> packages.add(requirePackageName(name))); return new ExposedPackages(List.copyOf(packages)); } static boolean isApiClass(String binaryName) { - return isInPackage(binaryName, API_PACKAGE); + return API.contains(binaryName); } boolean exposes(String binaryName) { - return packages.stream().anyMatch(name -> isInPackage(binaryName, name)); + return packages.stream().anyMatch(name -> name.contains(binaryName)); } /** Whether a resource path, such as {@code com/volmit/IrisModule.class}, lies in an exposed package. */ @@ -57,32 +57,16 @@ final class ExposedPackages { /** The exposed package a class is in; the most specific one when exposed packages nest. */ String packageOf(String binaryName) { return packages.stream() - .filter(name -> isInPackage(binaryName, name)) + .filter(name -> name.contains(binaryName)) + .map(PackageName::name) .max(Comparator.comparingInt(String::length)) .orElseThrow(() -> new IllegalArgumentException(binaryName + " is not in an exposed package")); } - private static boolean isInPackage(String binaryName, String packageName) { - return binaryName.startsWith(packageName) - && binaryName.length() > packageName.length() - && binaryName.charAt(packageName.length()) == PACKAGE_SEPARATOR; - } - - private static String requirePackageName(String name) { + private static PackageName requirePackageName(String name) { Objects.requireNonNull(name, "exposed package"); - var withoutTrailingDot = name.endsWith(String.valueOf(PACKAGE_SEPARATOR)) ? name.substring(0, name.length() - 1) : name; - if (isPackageName(withoutTrailingDot)) return withoutTrailingDot; - throw new IllegalArgumentException("Exposed package '" + name + "' is not a package name; name a package" - + " such as art.arcane.iris.engine, which exposes that package and its subpackages"); - } - - private static boolean isPackageName(String name) { - return Arrays.stream(name.split(PACKAGE_SEPARATOR_PATTERN, -1)).allMatch(ExposedPackages::isIdentifier); - } - - private static boolean isIdentifier(String segment) { - return !segment.isEmpty() - && Character.isJavaIdentifierStart(segment.codePointAt(0)) - && segment.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart); + return PackageName.tryParse(name).orElseThrow(() -> new IllegalArgumentException("Exposed package '" + name + + "' is not a package name; name a package such as art.arcane.iris.engine, which exposes that package" + + " and its subpackages")); } } diff --git a/src/main/java/com/volmit/host/MissingClasses.java b/src/main/java/com/volmit/host/MissingClasses.java index 9e977f8c7..69ad8060f 100644 --- a/src/main/java/com/volmit/host/MissingClasses.java +++ b/src/main/java/com/volmit/host/MissingClasses.java @@ -1,11 +1,14 @@ package com.volmit.host; +import com.volmit.ModuleInfo; +import com.volmit.PackageName; import java.util.List; import java.util.Objects; /** Classes a module jar uses that neither its pack, Iris nor the JDK has, usually optional - * dependencies of a library the jar bundles. The jar still loads; code that needs one of these - * classes throws {@link NoClassDefFoundError} when it runs. + * dependencies of a library the jar bundles, and that the jar's module does not declare + * {@linkplain ModuleInfo#optionalPackages() optional}. The jar still loads; code that needs one of + * these classes throws {@link NoClassDefFoundError} when it runs. * * @param origin the jar path relative to its pack * @param classNames the missing classes as sorted binary names @@ -15,4 +18,16 @@ public record MissingClasses(String origin, List classNames) { Objects.requireNonNull(origin, "origin"); classNames = List.copyOf(classNames); } + + /** These classes without those in any of {@code packages}. */ + MissingClasses outside(List packages) { + var remaining = classNames.stream() + .filter(className -> packages.stream().noneMatch(name -> name.contains(className))) + .toList(); + return new MissingClasses(origin, remaining); + } + + boolean isEmpty() { + return classNames.isEmpty(); + } } diff --git a/src/main/java/com/volmit/host/PackModules.java b/src/main/java/com/volmit/host/PackModules.java index 1f2a4c358..588187401 100644 --- a/src/main/java/com/volmit/host/PackModules.java +++ b/src/main/java/com/volmit/host/PackModules.java @@ -12,6 +12,8 @@ import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Objects; +import java.util.function.Predicate; +import java.util.stream.Collectors; /** The module jars of one pack: every {@code /modules/*.jar}, one module per jar, ordered * by file name so the result never depends on directory listing order. @@ -24,7 +26,8 @@ import java.util.Objects; * fails if a jar holds classes of an exposed package, if a class is in two jars, or if a class uses * a class that Iris hides from modules or that is missing from an exposed package. * Classes that nobody has are not an error, because the JVM only needs them when code that uses - * them runs; they are reported as {@link #missingClasses()}. + * them runs; they are reported as {@link #missingClasses()}, except those in the optional packages + * the jar's module declares in its {@link com.volmit.ModuleInfo}. * *

A successful load logs one INFO summary of the pack's modules through {@link System.Logger}, * which the host can route to its own logging, and one WARNING listing the missing classes, if any. @@ -78,7 +81,8 @@ public final class PackModules implements AutoCloseable { } /** Per jar that uses any, in jar file name order, the classes that neither the pack, Iris nor the - * JDK has. Empty when every class the jars use exists. + * JDK has and that are outside the optional packages the jar's module declares. Empty when every + * class the jars use exists or is declared optional. */ public List missingClasses() { return missingClasses; @@ -114,7 +118,8 @@ public final class PackModules implements AutoCloseable { Path packRoot, List jars, List missingClasses, ClassLoader host) { var loader = newPackClassLoader(packRoot, jars, host); try { - return new PackModules(createModules(jars, loader), missingClasses, loader); + var modules = createModules(jars, loader); + return new PackModules(modules, withoutDeclaredOptional(missingClasses, modules), loader); } catch (RuntimeException | Error failure) { closeAfterFailure(loader, failure); throw failure; @@ -141,6 +146,19 @@ public final class PackModules implements AutoCloseable { return jars.stream().map(jar -> jar.createModule(loader)).toList(); } + /** A module's optional packages excuse only its own jar's missing classes. They are read from + * {@code info()}, so this runs after the entry classes exist; errors were decided before that and + * never depend on them. + */ + private static List withoutDeclaredOptional(List missingClasses, List modules) { + var optionalPackages = modules.stream() + .collect(Collectors.toMap(DiscoveredModule::origin, found -> found.module().info().optionalPackages())); + return missingClasses.stream() + .map(jar -> jar.outside(optionalPackages.get(jar.origin()))) + .filter(Predicate.not(MissingClasses::isEmpty)) + .toList(); + } + private static void closeAfterFailure(URLClassLoader loader, Throwable failure) { try { loader.close(); diff --git a/src/test/java/com/volmit/ApiValuesTest.java b/src/test/java/com/volmit/ApiValuesTest.java index 146207462..a2bd47bb7 100644 --- a/src/test/java/com/volmit/ApiValuesTest.java +++ b/src/test/java/com/volmit/ApiValuesTest.java @@ -41,6 +41,23 @@ class ApiValuesTest { assertThrows(NullPointerException.class, () -> ModuleInfo.of("example:moss", null, "1.0.0")); } + @Test + void moduleInfoDeclaresOptionalPackagesWithTheirSubpackages() { + var plain = ModuleInfo.of("example:moss", "Moss", "1.0.0"); + var info = plain.withOptionalPackages("org.slf4j", "org.apache.logging."); + + assertEquals(List.of(), plain.optionalPackages()); + assertEquals(List.of(new PackageName("org.slf4j"), new PackageName("org.apache.logging")), info.optionalPackages()); + assertEquals(List.of(), info.withOptionalPackages().optionalPackages()); + assertTrue(info.optionalPackages().getFirst().contains("org.slf4j.spi.LocationAwareLogger")); + assertFalse(info.optionalPackages().getFirst().contains("org.slf4jx.Logger")); + for (var invalid : List.of("", "org.*", "org..slf4j", "1org")) { + var failure = assertThrows(IllegalArgumentException.class, () -> plain.withOptionalPackages(invalid)); + assertTrue(failure.getMessage().startsWith("Optional package '" + invalid + "' of module example:moss is not a package name"), + failure.getMessage()); + } + } + @Test void moduleInfoTextFitsOnOneLogLine() { for (var broken : List.of("Moss\nINFO forged line", "Moss\r", "Moss\tTabbed", "Moss\u2028Next")) { diff --git a/src/test/java/com/volmit/host/PackModulesTest.java b/src/test/java/com/volmit/host/PackModulesTest.java index c865c688e..85f77355d 100644 --- a/src/test/java/com/volmit/host/PackModulesTest.java +++ b/src/test/java/com/volmit/host/PackModulesTest.java @@ -49,6 +49,21 @@ class PackModulesTest { return TestModuleJar.compileClass(pack, SHARED_CLASS, SHARED_SOURCE); } + /** A jar of empty public classes, for modules to compile against without shipping it. */ + private static Path library(Path build, String jarName, String... classNames) { + var library = new TestModuleJar(); + for (var className : classNames) { + int dot = className.lastIndexOf('.'); + library.source(className, "package %s; public final class %s {}".formatted(className.substring(0, dot), className.substring(dot + 1))); + } + return library.writeInto(build, jarName); + } + + /** Module members that use each class, so its class file references them. */ + private static String using(String... classNames) { + return "static Object[] used() { return new Object[] {" + String.join(".class, ", classNames) + ".class}; }"; + } + private static String failure(Executable load) { return assertThrows(IllegalArgumentException.class, load).getMessage(); } @@ -294,6 +309,70 @@ class PackModulesTest { assertFalse(message.contains(OPTIONAL_CLASS), message); } + @Test + void missingClassesInDeclaredOptionalPackagesDoNotWarn(@TempDir Path build) { + module("pack.user.User", "user:core", List.of("org.optional", "org.other."), using(OPTIONAL_CLASS, "org.other.deep.Thing"), NO_STAGES) + .compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS, "org.other.deep.Thing")) + .writeInto(pack, "user.jar"); + + try (var packModules = PackModules.load(pack)) { + assertEquals(List.of(), packModules.missingClasses()); + } + } + + @Test + void missingClassesOutsideDeclaredOptionalPackagesStillWarn(@TempDir Path build) { + module("pack.user.User", "user:core", List.of("org.optional"), using(OPTIONAL_CLASS, "org.optionalx.Other", "org.slf4j.Logger"), NO_STAGES) + .compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS, "org.optionalx.Other", "org.slf4j.Logger")) + .writeInto(pack, "user.jar"); + + try (var packModules = PackModules.load(pack)) { + assertEquals(List.of(new MissingClasses(origin("user.jar"), List.of("org.optionalx.Other", "org.slf4j.Logger"))), + packModules.missingClasses()); + } + } + + @Test + void optionalPackagesExcuseOnlyTheirOwnJar(@TempDir Path build) { + var optionalLibrary = library(build, "optional.jar", OPTIONAL_CLASS); + module("pack.alpha.Alpha", "alpha:core", List.of("org.optional"), using(OPTIONAL_CLASS), NO_STAGES) + .compileAgainst(optionalLibrary) + .writeInto(pack, "alpha.jar"); + module("pack.beta.Beta", "beta:core", using(OPTIONAL_CLASS), NO_STAGES) + .compileAgainst(optionalLibrary) + .writeInto(pack, "beta.jar"); + + try (var packModules = PackModules.load(pack)) { + assertEquals(List.of(new MissingClasses(origin("beta.jar"), List.of(OPTIONAL_CLASS))), packModules.missingClasses()); + } + } + + @Test + void optionalPackagesNeverExcuseALoadError(@TempDir Path build) { + var hidden = pack.resolve("hidden"); + module("pack.user.User", "user:core", List.of("org.junit"), using("org.junit.jupiter.api.Test"), NO_STAGES) + .compileAgainstHostOf(Test.class) + .writeInto(hidden, "user.jar"); + assertMentions(failure(() -> PackModules.load(hidden)), + "uses classes that exist in Iris but are hidden from modules:\n pack.user.User -> org.junit.jupiter.api.Test"); + + var newerApi = pack.resolve("newer-api"); + module("pack.user.User", "user:core", List.of("com.volmit"), using("com.volmit.Newer"), NO_STAGES) + .compileAgainst(library(build, "newer-api.jar", "com.volmit.Newer")) + .writeInto(newerApi, "user.jar"); + assertMentions(failure(() -> PackModules.load(newerApi)), + "uses classes that this Iris does not have, in packages Iris provides to modules:\n pack.user.User -> com.volmit.Newer"); + } + + @Test + void invalidOptionalPackageFailsNamingTheJar() { + module("pack.user.User", "user:core", List.of("org.*"), NO_MEMBERS, NO_STAGES).writeInto(pack, "user.jar"); + + assertMentions(failure(() -> PackModules.load(pack)), + "Module jar " + origin("user.jar") + " has a broken entry point pack.user.User: info() failed", + "Optional package 'org.*' of module user:core is not a package name"); + } + @Test void referenceToAMissingApiClassPointsAtADifferentApiBuild(@TempDir Path build) { var newerApi = new TestModuleJar() diff --git a/src/test/java/com/volmit/support/TestModuleJar.java b/src/test/java/com/volmit/support/TestModuleJar.java index 1c6d0eb45..bbc3d89df 100644 --- a/src/test/java/com/volmit/support/TestModuleJar.java +++ b/src/test/java/com/volmit/support/TestModuleJar.java @@ -39,7 +39,13 @@ public final class TestModuleJar { /** An entry class with the given module id whose install body may use {@code graph}. */ public static TestModuleJar module(String className, String moduleId, String members, String install) { - return new TestModuleJar().source(className, moduleSource(className, moduleId, members, install)).entryPoint(className); + return module(className, moduleId, List.of(), members, install); + } + + /** Like {@link #module(String, String, String, String)}, with {@code info()} declaring {@code optionalPackages}. */ + public static TestModuleJar module(String className, String moduleId, List optionalPackages, String members, String install) { + var info = moduleInfo(moduleId, optionalPackages); + return new TestModuleJar().source(className, moduleSource(className, info, members, install)).entryPoint(className); } /** Compiles one class on its own and returns its class file, for raw entries such as versioned classes. */ @@ -147,7 +153,14 @@ public final class TestModuleJar { output.closeEntry(); } - private static String moduleSource(String className, String moduleId, String members, String install) { + private static String moduleInfo(String moduleId, List optionalPackages) { + var info = "ModuleInfo.of(\"%s\", \"%s\", \"1.0.0\")".formatted(moduleId, displayName(moduleId)); + if (optionalPackages.isEmpty()) return info; + var packages = optionalPackages.stream().map(name -> '"' + name + '"').collect(Collectors.joining(", ")); + return info + ".withOptionalPackages(" + packages + ")"; + } + + private static String moduleSource(String className, String info, String members, String install) { int dot = className.lastIndexOf('.'); return """ package %s; @@ -159,11 +172,11 @@ public final class TestModuleJar { public final class %s implements IrisModule { %s - public ModuleInfo info() { return ModuleInfo.of("%s", "%s", "1.0.0"); } + public ModuleInfo info() { return %s; } public void install(StageGraph graph) { %s } } - """.formatted(className.substring(0, dot), className.substring(dot + 1), members, moduleId, displayName(moduleId), install); + """.formatted(className.substring(0, dot), className.substring(dot + 1), members, info, install); } /** The display name test modules get, so assertions can predict it from the id. */