From 98bd9a9c12d8d5c55cc59230119218925d7781a2 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 5 Oct 2026 20:27:24 +0200 Subject: [PATCH] Let pack jars use classes nobody has, as optional dependencies The class check was stricter than the JVM: a bundled library that references optional integrations failed the whole pack, although that code only runs when the classes exist. Each missing reference is now classified: - the host has the class but hides it (Iris internals, Iris's copy of a library): load error, saying modules cannot use Iris's classes; - missing from the API: load error, as before (different Iris build); - nobody has it: the pack loads. PackModules.missingClasses() lists the classes per jar and the load logs one capped WARNING per pack, formatted by MissingClassesWarning. Reference resolution moves from PackClassCheck to PackReferenceCheck. --- .../com/volmit/host/ApiAndJdkClassLoader.java | 13 +- .../java/com/volmit/host/MissingClasses.java | 18 +++ .../volmit/host/MissingClassesWarning.java | 31 ++++ .../java/com/volmit/host/PackClassCheck.java | 82 +--------- .../java/com/volmit/host/PackModules.java | 34 ++++- .../com/volmit/host/PackReferenceCheck.java | 141 ++++++++++++++++++ .../volmit/host/ApiAndJdkClassLoaderTest.java | 7 + .../host/MissingClassesWarningTest.java | 44 ++++++ .../java/com/volmit/host/PackModulesTest.java | 47 +++++- 9 files changed, 326 insertions(+), 91 deletions(-) create mode 100644 src/main/java/com/volmit/host/MissingClasses.java create mode 100644 src/main/java/com/volmit/host/MissingClassesWarning.java create mode 100644 src/main/java/com/volmit/host/PackReferenceCheck.java create mode 100644 src/test/java/com/volmit/host/MissingClassesWarningTest.java diff --git a/src/main/java/com/volmit/host/ApiAndJdkClassLoader.java b/src/main/java/com/volmit/host/ApiAndJdkClassLoader.java index 94fac97d8..40af12f60 100644 --- a/src/main/java/com/volmit/host/ApiAndJdkClassLoader.java +++ b/src/main/java/com/volmit/host/ApiAndJdkClassLoader.java @@ -40,7 +40,14 @@ final class ApiAndJdkClassLoader extends ClassLoader { /** Whether this loader can load the class, judged by its class file so that nothing is loaded. */ boolean hasClass(String binaryName) { - return getResource(binaryName.replace('.', '/') + CLASS_FILE_SUFFIX) != null; + return getResource(classFile(binaryName)) != null; + } + + /** Whether the API's loader has the class, whether or not this loader shows it to packs. In + * production that loader also holds Iris internals and the libraries Iris bundles. + */ + boolean hostHasClass(String binaryName) { + return apiLoader.getResource(classFile(binaryName)) != null; } @Override @@ -61,6 +68,10 @@ final class ApiAndJdkClassLoader extends ClassLoader { return super.getResources(name); } + private static String classFile(String binaryName) { + return binaryName.replace('.', '/') + CLASS_FILE_SUFFIX; + } + private static boolean isApiResource(String name) { return name.startsWith(API_RESOURCE_PREFIX); } diff --git a/src/main/java/com/volmit/host/MissingClasses.java b/src/main/java/com/volmit/host/MissingClasses.java new file mode 100644 index 000000000..9e977f8c7 --- /dev/null +++ b/src/main/java/com/volmit/host/MissingClasses.java @@ -0,0 +1,18 @@ +package com.volmit.host; + +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. + * + * @param origin the jar path relative to its pack + * @param classNames the missing classes as sorted binary names + */ +public record MissingClasses(String origin, List classNames) { + public MissingClasses { + Objects.requireNonNull(origin, "origin"); + classNames = List.copyOf(classNames); + } +} diff --git a/src/main/java/com/volmit/host/MissingClassesWarning.java b/src/main/java/com/volmit/host/MissingClassesWarning.java new file mode 100644 index 000000000..410a63caa --- /dev/null +++ b/src/main/java/com/volmit/host/MissingClassesWarning.java @@ -0,0 +1,31 @@ +package com.volmit.host; + +import java.util.List; + +/** The one warning a pack load writes when its jars use classes nobody has. One line per jar, + * with a capped list of classes, so a large bundled library cannot flood the log. + */ +final class MissingClassesWarning { + static final int MAX_LISTED_CLASSES_PER_JAR = 5; + private static final String INDENT = " "; + + private MissingClassesWarning() {} + + /** Expects at least one jar; a pack without missing classes logs no warning. */ + static String describe(String packName, List jars) { + var text = new StringBuilder("Pack ").append(packName) + .append(": module jars use classes that neither the pack, Iris nor the JDK has, usually optional" + + " dependencies of a bundled library. The jars load, but code that needs these classes throws" + + " NoClassDefFoundError when it runs:"); + for (var jar : jars) { + text.append('\n').append(INDENT).append(jar.origin()).append(": ").append(listClasses(jar.classNames())); + } + return text.toString(); + } + + private static String listClasses(List classNames) { + var listed = String.join(", ", classNames.subList(0, Math.min(classNames.size(), MAX_LISTED_CLASSES_PER_JAR))); + int unlisted = classNames.size() - MAX_LISTED_CLASSES_PER_JAR; + return unlisted > 0 ? listed + " and " + unlisted + " more" : listed; + } +} diff --git a/src/main/java/com/volmit/host/PackClassCheck.java b/src/main/java/com/volmit/host/PackClassCheck.java index 79d090ac1..53ef87c73 100644 --- a/src/main/java/com/volmit/host/PackClassCheck.java +++ b/src/main/java/com/volmit/host/PackClassCheck.java @@ -1,27 +1,22 @@ package com.volmit.host; import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; /** Checks the classes of all jars of one pack before its class loader exists, so a pack that * cannot link fails at load with the jar to fix, not later with a {@link NoClassDefFoundError} * during install or generation. */ final class PackClassCheck { - private static final int MAX_REPORTED_REFERENCES_PER_JAR = 10; - private static final String INDENT = " "; - private PackClassCheck() {} - /** Fails when a class is in two jars, or when a class uses a class that is neither in the API, - * the JDK nor a jar of the pack. + /** Fails when a class is in two jars, or when a class uses a class that Iris hides from modules + * or that is missing from the API. Returns the classes that nobody has, per jar; they fail only + * when code that needs them runs. */ - static void requireLinkable(List jars, ApiAndJdkClassLoader apiAndJdk) { + static List requireLinkable(List jars, ApiAndJdkClassLoader apiAndJdk) { requireDistinctClasses(jars); - requireResolvableReferences(jars, apiAndJdk); + return PackReferenceCheck.requireResolvable(jars, apiAndJdk); } /** The shared pack loader would otherwise silently use whichever copy comes first in file name order. */ @@ -40,71 +35,4 @@ final class PackClassCheck { + " and " + second.origin() + "; every class of a pack must come from one jar, so relocate" + " shaded libraries or keep shared classes in one module"); } - - private static void requireResolvableReferences(List jars, ApiAndJdkClassLoader apiAndJdk) { - var resolver = new ReferenceResolver(jars, apiAndJdk); - var unresolved = jars.stream() - .map(jar -> new UnresolvedReferences(jar, resolver.unresolvedIn(jar))) - .filter(UnresolvedReferences::any) - .toList(); - if (!unresolved.isEmpty()) throw unresolvedReferences(unresolved); - } - - private static IllegalArgumentException unresolvedReferences(List jars) { - var text = new StringBuilder(); - for (var jar : jars) jar.describeTo(text); - text.append("A module can use only the Iris API, the JDK and the classes in its pack's module jars;" - + " ship any library it needs inside a module jar of the pack."); - if (jars.stream().anyMatch(UnresolvedReferences::missesApiClasses)) { - text.append(" A missing ").append(ApiAndJdkClassLoader.API_PACKAGE_PREFIX) - .append("* class means the jar was built against a different Iris API."); - } - return new IllegalArgumentException(text.toString()); - } - - /** Decides per referenced class whether the pack loader will find it. Classes outside the pack - * are looked up once per pack. - */ - private static final class ReferenceResolver { - private final Set packClasses = new HashSet<>(); - private final Map outsidePack = new HashMap<>(); - private final ApiAndJdkClassLoader apiAndJdk; - - ReferenceResolver(List jars, ApiAndJdkClassLoader apiAndJdk) { - this.apiAndJdk = apiAndJdk; - jars.forEach(jar -> packClasses.addAll(jar.classNames())); - } - - List unresolvedIn(ModuleJar jar) { - return jar.classes().stream() - .flatMap(type -> type.references().stream().map(target -> new Reference(type.name(), target))) - .filter(reference -> !resolves(reference.target())) - .toList(); - } - - private boolean resolves(String className) { - return packClasses.contains(className) || outsidePack.computeIfAbsent(className, apiAndJdk::hasClass); - } - } - - private record Reference(String source, String target) {} - - private record UnresolvedReferences(ModuleJar jar, List references) { - boolean any() { - return !references.isEmpty(); - } - - boolean missesApiClasses() { - return references.stream().anyMatch(reference -> ApiAndJdkClassLoader.isApiClass(reference.target())); - } - - void describeTo(StringBuilder text) { - text.append("Module jar ").append(jar.origin()) - .append(" uses classes that are not in the Iris API, the JDK or the pack's module jars:\n"); - references.stream().limit(MAX_REPORTED_REFERENCES_PER_JAR).forEach(reference -> text.append(INDENT) - .append(reference.source()).append(" -> ").append(reference.target()).append('\n')); - int hidden = references.size() - MAX_REPORTED_REFERENCES_PER_JAR; - if (hidden > 0) text.append(INDENT).append("and ").append(hidden).append(" more\n"); - } - } } diff --git a/src/main/java/com/volmit/host/PackModules.java b/src/main/java/com/volmit/host/PackModules.java index 9ffeb253f..734e5bfec 100644 --- a/src/main/java/com/volmit/host/PackModules.java +++ b/src/main/java/com/volmit/host/PackModules.java @@ -19,10 +19,12 @@ import java.util.Objects; * stage constants in {@code requires(...)}. Besides the pack's own classes, that loader sees only * the Iris API and the JDK ({@link ApiAndJdkClassLoader}); packs do not see each other or Iris * internals. Before the loader exists, the load fails if a jar holds API classes, if a class is in - * two jars, or if a class uses a class the loader would not find. + * two jars, or if a class uses a class that Iris hides from modules or that is missing from the API. + * 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()}. * *

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. + * which the host can route to its own logging, and one WARNING listing the missing classes, if any. * *

Close this when the pack unloads, after dropping everything built from its modules, such as * {@link LoadedModules}. Classes not loaded before then can no longer be loaded. @@ -33,10 +35,12 @@ public final class PackModules implements AutoCloseable { private static final System.Logger LOGGER = System.getLogger(PackModules.class.getName()); private final List modules; + private final List missingClasses; private final URLClassLoader loader; - private PackModules(List modules, URLClassLoader loader) { + private PackModules(List modules, List missingClasses, URLClassLoader loader) { this.modules = List.copyOf(modules); + this.missingClasses = List.copyOf(missingClasses); this.loader = loader; } @@ -49,9 +53,9 @@ public final class PackModules implements AutoCloseable { .map(jar -> ModuleJar.read(packRoot, jar)) .toList(); var apiAndJdk = new ApiAndJdkClassLoader(IrisModule.class.getClassLoader()); - PackClassCheck.requireLinkable(jars, apiAndJdk); - var packModules = defineModules(packRoot, jars, apiAndJdk); - LOGGER.log(Level.INFO, () -> PackModulesSummary.describe(packName(packRoot), packModules.modules())); + var missingClasses = PackClassCheck.requireLinkable(jars, apiAndJdk); + var packModules = defineModules(packRoot, jars, missingClasses, apiAndJdk); + logLoad(packName(packRoot), packModules); return packModules; } @@ -60,6 +64,13 @@ public final class PackModules implements AutoCloseable { return modules; } + /** 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. + */ + public List missingClasses() { + return missingClasses; + } + @Override public void close() { try { @@ -86,10 +97,11 @@ public final class PackModules implements AutoCloseable { return Files.isRegularFile(path) && path.getFileName().toString().endsWith(JAR_EXTENSION); } - private static PackModules defineModules(Path packRoot, List jars, ClassLoader apiAndJdk) { + private static PackModules defineModules( + Path packRoot, List jars, List missingClasses, ClassLoader apiAndJdk) { var loader = newPackClassLoader(packRoot, jars, apiAndJdk); try { - return new PackModules(createModules(jars, loader), loader); + return new PackModules(createModules(jars, loader), missingClasses, loader); } catch (RuntimeException | Error failure) { closeAfterFailure(loader, failure); throw failure; @@ -101,6 +113,12 @@ public final class PackModules implements AutoCloseable { return new URLClassLoader("pack:" + packName(packRoot), urls, apiAndJdk); } + private static void logLoad(String packName, PackModules packModules) { + LOGGER.log(Level.INFO, () -> PackModulesSummary.describe(packName, packModules.modules())); + if (packModules.missingClasses().isEmpty()) return; + LOGGER.log(Level.WARNING, () -> MissingClassesWarning.describe(packName, packModules.missingClasses())); + } + private static String packName(Path packRoot) { var name = packRoot.getFileName(); return name == null ? packRoot.toString() : name.toString(); diff --git a/src/main/java/com/volmit/host/PackReferenceCheck.java b/src/main/java/com/volmit/host/PackReferenceCheck.java new file mode 100644 index 000000000..11298c979 --- /dev/null +++ b/src/main/java/com/volmit/host/PackReferenceCheck.java @@ -0,0 +1,141 @@ +package com.volmit.host; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Predicate; + +/** Decides for every class a pack's jars use whether the pack loader will find it, and why not + * when it won't. Nothing is loaded: the host's classes are judged by their class files. + * + *

The JVM resolves a class only when code first needs it, so a class nobody has is not an + * error: bundled libraries reference optional dependencies they only use when present. A class + * that Iris has but hides, or that is missing from a package Iris exposes, always fails the load. + */ +final class PackReferenceCheck { + private static final int MAX_REPORTED_REFERENCES_PER_JAR = 10; + private static final String INDENT = " "; + + /** Where the pack loader would find a referenced class. */ + private enum Resolution { + /** In the pack, a package the host exposes, or the JDK. */ + PROVIDED, + /** Nowhere: an optional dependency, which only fails when code that needs it runs. */ + ABSENT, + HIDDEN_HOST_CLASS( + "uses classes that exist in Iris but are hidden from modules:", + "Modules cannot use Iris's own classes or its copies of libraries; ship the library in a module jar" + + " of the pack, or use the Iris API."), + MISSING_HOST_CLASS( + "uses classes that this Iris does not have, in packages Iris provides to modules:", + "The jar was built against a different Iris API or Iris version."); + + private final String header; + private final String advice; + + Resolution() { + this(null, null); + } + + Resolution(String header, String advice) { + this.header = header; + this.advice = advice; + } + + boolean failsLoad() { + return header != null; + } + } + + private final Set packClasses = new HashSet<>(); + private final Map outsidePack = new HashMap<>(); + private final ApiAndJdkClassLoader host; + + private PackReferenceCheck(List jars, ApiAndJdkClassLoader host) { + this.host = host; + jars.forEach(jar -> packClasses.addAll(jar.classNames())); + } + + /** Fails when a jar uses a class Iris hides or a class missing from a package Iris exposes. + * Returns the classes nobody has, per jar, for jars that use any. + */ + static List requireResolvable(List jars, ApiAndJdkClassLoader host) { + var check = new PackReferenceCheck(jars, host); + var references = jars.stream().map(check::resolve).toList(); + requireNoFailures(references); + return references.stream() + .filter(JarReferences::missesClasses) + .map(JarReferences::missingClasses) + .toList(); + } + + private JarReferences resolve(ModuleJar jar) { + var references = jar.classes().stream() + .flatMap(type -> type.references().stream().map(target -> new Reference(type.name(), target, resolve(target)))) + .filter(reference -> reference.resolution() != Resolution.PROVIDED) + .toList(); + return new JarReferences(jar, references); + } + + private Resolution resolve(String className) { + if (packClasses.contains(className)) return Resolution.PROVIDED; + return outsidePack.computeIfAbsent(className, this::resolveOutsidePack); + } + + private Resolution resolveOutsidePack(String className) { + if (host.hasClass(className)) return Resolution.PROVIDED; + if (ApiAndJdkClassLoader.isApiClass(className)) return Resolution.MISSING_HOST_CLASS; + if (host.hostHasClass(className)) return Resolution.HIDDEN_HOST_CLASS; + return Resolution.ABSENT; + } + + private static void requireNoFailures(List jars) { + var failures = Arrays.stream(Resolution.values()) + .filter(Resolution::failsLoad) + .map(failure -> describeFailure(failure, jars)) + .filter(Predicate.not(String::isEmpty)) + .toList(); + if (failures.isEmpty()) return; + throw new IllegalArgumentException(String.join("\n", failures)); + } + + private static String describeFailure(Resolution failure, List jars) { + var text = new StringBuilder(); + for (var jar : jars) jar.describeTo(failure, text); + if (text.isEmpty()) return ""; + return text.append(failure.advice).toString(); + } + + private record Reference(String source, String target, Resolution resolution) {} + + /** The references of one jar the pack loader would not resolve. */ + private record JarReferences(ModuleJar jar, List unresolved) { + boolean missesClasses() { + return unresolved.stream().anyMatch(reference -> reference.resolution() == Resolution.ABSENT); + } + + MissingClasses missingClasses() { + var classNames = new TreeSet(); + with(Resolution.ABSENT).forEach(reference -> classNames.add(reference.target())); + return new MissingClasses(jar.origin(), List.copyOf(classNames)); + } + + void describeTo(Resolution failure, StringBuilder text) { + var references = with(failure); + if (references.isEmpty()) return; + text.append("Module jar ").append(jar.origin()).append(' ').append(failure.header).append('\n'); + references.stream().limit(MAX_REPORTED_REFERENCES_PER_JAR).forEach(reference -> text.append(INDENT) + .append(reference.source()).append(" -> ").append(reference.target()).append('\n')); + int hidden = references.size() - MAX_REPORTED_REFERENCES_PER_JAR; + if (hidden > 0) text.append(INDENT).append("and ").append(hidden).append(" more\n"); + } + + private List with(Resolution resolution) { + return unresolved.stream().filter(reference -> reference.resolution() == resolution).toList(); + } + } +} diff --git a/src/test/java/com/volmit/host/ApiAndJdkClassLoaderTest.java b/src/test/java/com/volmit/host/ApiAndJdkClassLoaderTest.java index cd16561a1..546c61fa8 100644 --- a/src/test/java/com/volmit/host/ApiAndJdkClassLoaderTest.java +++ b/src/test/java/com/volmit/host/ApiAndJdkClassLoaderTest.java @@ -45,4 +45,11 @@ class ApiAndJdkClassLoaderTest { assertFalse(loader.hasClass(Test.class.getName())); assertFalse(loader.hasClass("com.volmit.DoesNotExist")); } + + @Test + void knowsWhichClassesTheHostHasEvenWhenItHidesThem() { + assertTrue(loader.hostHasClass(Test.class.getName())); + assertTrue(loader.hostHasClass(IrisModule.class.getName())); + assertFalse(loader.hostHasClass("org.nowhere.Missing")); + } } diff --git a/src/test/java/com/volmit/host/MissingClassesWarningTest.java b/src/test/java/com/volmit/host/MissingClassesWarningTest.java new file mode 100644 index 000000000..cf07ee892 --- /dev/null +++ b/src/test/java/com/volmit/host/MissingClassesWarningTest.java @@ -0,0 +1,44 @@ +package com.volmit.host; + +import org.junit.jupiter.api.Test; +import java.util.List; +import java.util.stream.IntStream; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MissingClassesWarningTest { + private static final String HEADER = "Pack overworld: module jars use classes that neither the pack, Iris nor the JDK" + + " has, usually optional dependencies of a bundled library. The jars load, but code that needs these" + + " classes throws NoClassDefFoundError when it runs:"; + + @Test + void listsTheMissingClassesOfEveryJarOnOneLine() { + var jars = List.of( + new MissingClasses("modules/moss.jar", List.of("org.slf4j.Logger", "org.slf4j.LoggerFactory")), + new MissingClasses("modules/snow.jar", List.of("com.google.gson.Gson"))); + + assertEquals(HEADER + + "\n modules/moss.jar: org.slf4j.Logger, org.slf4j.LoggerFactory" + + "\n modules/snow.jar: com.google.gson.Gson", + MissingClassesWarning.describe("overworld", jars)); + } + + @Test + void capsLongListsPerJar() { + var classNames = IntStream.rangeClosed(1, 214).mapToObj(index -> "lib.Missing%03d".formatted(index)).toList(); + var jars = List.of(new MissingClasses("modules/big.jar", classNames)); + + assertEquals(HEADER + + "\n modules/big.jar: lib.Missing001, lib.Missing002, lib.Missing003, lib.Missing004, lib.Missing005 and 209 more", + MissingClassesWarning.describe("overworld", jars)); + } + + @Test + void listAtTheCapHasNoRemainder() { + var classNames = IntStream.rangeClosed(1, MissingClassesWarning.MAX_LISTED_CLASSES_PER_JAR) + .mapToObj(index -> "lib.Missing" + index).toList(); + var jars = List.of(new MissingClasses("modules/big.jar", classNames)); + + assertEquals(HEADER + "\n modules/big.jar: lib.Missing1, lib.Missing2, lib.Missing3, lib.Missing4, lib.Missing5", + MissingClassesWarning.describe("overworld", jars)); + } +} diff --git a/src/test/java/com/volmit/host/PackModulesTest.java b/src/test/java/com/volmit/host/PackModulesTest.java index eaf413393..1cd68f555 100644 --- a/src/test/java/com/volmit/host/PackModulesTest.java +++ b/src/test/java/com/volmit/host/PackModulesTest.java @@ -25,6 +25,7 @@ class PackModulesTest { private static final byte[] UNUSED_CLASS_BYTES = {(byte) 0xCA, (byte) 0xFE}; private static final String VERSIONED_SHARED_CLASS = "META-INF/versions/9/pack/shared/Util.class"; private static final String DEFINED_PROPERTY = "irisapi.test.packModuleConstructed"; + private static final String OPTIONAL_CLASS = "org.optional.Feature"; @TempDir Path pack; @@ -78,6 +79,7 @@ class PackModulesTest { assertEquals(List.of("alpha:core", "beta:core"), packModules.modules().stream().map(found -> found.module().info().id().toString()).toList()); assertNotSame(PackModules.class.getClassLoader(), packModules.modules().getFirst().module().getClass().getClassLoader()); + assertTrue(packModules.missingClasses().isEmpty()); var order = loadWithBuiltIns(packModules).placement().stages().stream() .map(stage -> stage.stage().id().toString()).toList(); @@ -247,13 +249,47 @@ class PackModulesTest { .compileAgainstHostOf(Test.class) .writeInto(pack, "user.jar"); - assertEquals("Module jar " + origin("user.jar") + " uses classes that are not in the Iris API, the JDK or the" - + " pack's module jars:\n pack.user.User -> org.junit.jupiter.api.Test\n" - + "A module can use only the Iris API, the JDK and the classes in its pack's module jars;" - + " ship any library it needs inside a module jar of the pack.", + assertEquals("Module jar " + origin("user.jar") + " uses classes that exist in Iris but are hidden from modules:\n" + + " pack.user.User -> org.junit.jupiter.api.Test\n" + + "Modules cannot use Iris's own classes or its copies of libraries; ship the library in a module" + + " jar of the pack, or use the Iris API.", failure(() -> PackModules.load(pack))); } + @Test + void classesNobodyHasAreReportedWithoutFailingTheLoad(@TempDir Path build) { + var optionalLibrary = new TestModuleJar() + .source(OPTIONAL_CLASS, "package org.optional; public final class Feature { public static void use() {} }") + .writeInto(build, "optional.jar"); + module("pack.user.User", "user:core", "static void useWhenPresent() { org.optional.Feature.use(); }", + "graph.define(Stage.placement(\"user:core/work\")).run(context -> {});") + .compileAgainst(optionalLibrary) + .writeInto(pack, "user.jar"); + + try (var packModules = PackModules.load(pack)) { + assertEquals(List.of(new MissingClasses(origin("user.jar"), List.of(OPTIONAL_CLASS))), packModules.missingClasses()); + assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of())); + } + } + + @Test + void hiddenHostClassFailsEvenWhenOtherMissingClassesAreOptional(@TempDir Path build) { + var optionalLibrary = new TestModuleJar() + .source(OPTIONAL_CLASS, "package org.optional; public final class Feature {}") + .writeInto(build, "optional.jar"); + module("pack.user.User", "user:core", """ + static Object optional() { return org.optional.Feature.class; } + static Object hidden() { return org.junit.jupiter.api.Test.class; } + """, NO_STAGES) + .compileAgainst(optionalLibrary) + .compileAgainstHostOf(Test.class) + .writeInto(pack, "user.jar"); + + var message = failure(() -> PackModules.load(pack)); + assertMentions(message, "pack.user.User -> org.junit.jupiter.api.Test"); + assertFalse(message.contains(OPTIONAL_CLASS), message); + } + @Test void referenceToAMissingApiClassPointsAtADifferentApiBuild(@TempDir Path build) { var newerApi = new TestModuleJar() @@ -264,7 +300,8 @@ class PackModulesTest { .writeInto(pack, "user.jar"); assertMentions(failure(() -> PackModules.load(pack)), - "pack.user.User -> com.volmit.Newer", "the jar was built against a different Iris API"); + "uses classes that this Iris does not have, in packages Iris provides to modules:\n pack.user.User -> com.volmit.Newer", + "The jar was built against a different Iris API or Iris version."); } @Test