diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index d969f4c..8e4e854 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -186,6 +186,25 @@ Methods of `Mod`, usable from the constructor on, and in field initializers: | `commands()` | `Commands` | admin commands for chat, the server console, and RCON | | `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods | +## Settings + +`config().bind(Settings.class)` reads `config.toml` into a record. Keys are the component names +in `snake_case` (`maxBalance` reads `max_balance`); defaults come from the jar's +`META-INF/zomboidforge/config.toml`. + +```java +record Settings( + @Key("max_hp_regen") int healthRegenPerHour, // keeps its key after a rename + @Min(1) @Max(100) int maxPlayers, // bounds for numbers, also inside List, Map, Optional + String greeting +) {} +``` + +A missing, mistyped, or out-of-bounds value stops the server, and the log lists every problem +with its key (`'max_players' must be at most 100, found 250.`). `@Key` names are `snake_case` +and differ within a record; `@Min`/`@Max` only fit numeric components and may be fractions +(`@Max(0.5) double ratio`). + ## Threads Game objects belong to the server's main thread. Everything else should stay off it, because @@ -289,9 +308,14 @@ public class HelloCommand extends CommandBase public void onLoad() { this.commands().register(HelloCommand.class); } ``` +Or `@RegisterCommand` on the class (`dev.overlord.zomboidforge.api.annotations`), without the +call: ZomboidForge registers the annotated classes of the mod's own jar (not of `lib/`) by name, +before `onLoad()`. + - **Registration** happens in the entry point's constructor or `onLoad()`; later calls throw. `register` checks the class and throws `IllegalArgumentException` listing every problem, - which stops the server like any other exception in `onLoad()`. + which stops the server like any other exception in `onLoad()`; an annotated class that breaks + the rules stops it the same way. - **The class** is public and not abstract, with one public constructor `(String, Role, String, UdpConnection)`. - **Names** (`@CommandName`, repeatable for aliases) consist of letters, digits, and `_` and @@ -400,7 +424,9 @@ this.storage().transaction(() -> { // all or nothin | `Instant` | ISO-8601 text | | `byte[]` | blob | -Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`. +Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`. `@Key("paid_at")` +on a component sets the column name instead, so a renamed component keeps its column and data. +`@Min`/`@Max` are for settings; storage ignores them. When the record changes between versions of the mod: diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java index 2ef17a8..85123eb 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import dev.overlord.zomboidforge.api.annotations.RegisterCommand; + import org.jetbrains.annotations.ApiStatus; /** @@ -28,7 +30,8 @@ public interface Commands { /** * Registers {@code command}. Only on the main thread while the mod loads: in the entry point's - * constructor or {@link Mod#onLoad()}. + * constructor or {@link Mod#onLoad()}. Classes annotated with {@link RegisterCommand} are + * registered without this call. * * @throws IllegalArgumentException when {@code command} does not meet the rules above, or is * registered already diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java b/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java index 0cfdf88..42c6f19 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModConfig.java @@ -1,5 +1,9 @@ package dev.overlord.zomboidforge.api; +import dev.overlord.zomboidforge.api.annotations.Key; +import dev.overlord.zomboidforge.api.annotations.Max; +import dev.overlord.zomboidforge.api.annotations.Min; + import org.jetbrains.annotations.ApiStatus; import java.util.Optional; @@ -10,7 +14,8 @@ import java.util.Optional; * default. The table {@code [forge]} belongs to ZomboidForge and is not part of these settings. * *

Keys are {@code snake_case}; record components and paths use the same names converted - * from {@code camelCase} ({@code maxBalance} reads {@code max_balance}). + * from {@code camelCase} ({@code maxBalance} reads {@code max_balance}), or the name of the + * component's {@link Key}. */ @ApiStatus.NonExtendable public interface ModConfig @@ -21,9 +26,13 @@ public interface ModConfig * wrappers), enums (by constant name), records (TOML tables), {@code List}, * {@code Map} (tables with free keys), and {@code Optional} for values that * may be missing. Every other component must have a value. Keys without a component are - * logged as warnings. + * logged as warnings. {@link Min} and {@link Max} bound numeric components. * - * @throws IllegalStateException listing every missing or mistyped value + * @throws IllegalStateException listing every missing, mistyped, or out-of-bounds value + * @throws IllegalArgumentException when {@code type} has a component that configuration + * values cannot have, an invalid or repeated {@link Key}, + * or {@link Min}/{@link Max} on a component that is not + * numeric or with the minimum above the maximum */ T bind(Class type); diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Key.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Key.java new file mode 100644 index 0000000..c5b8b3d --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Key.java @@ -0,0 +1,32 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.ModConfig; +import dev.overlord.zomboidforge.api.storage.ModStorage; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The key of a record component, instead of the one converted from its name ({@code maxBalance} + * to {@code max_balance}): the {@code config.toml} key for {@link ModConfig#bind}, the column + * name for {@link ModStorage} tables. A component keeps its key when it is renamed: + * + *

{@code
+ * record Settings(@Key("max_hp_regen") int healthRegenPerHour) {}
+ * }
+ * + * The key is {@code snake_case}: lowercase letters, digits, and single underscores, starting with + * a letter. Two components of a record cannot have the same key. For a storage record, giving an + * existing component another key renames its column, which the table treats as a removed and a + * new column, as when the component is renamed without {@code @Key}. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.RECORD_COMPONENT) +public @interface Key +{ + String value(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Max.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Max.java new file mode 100644 index 0000000..c1b1835 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Max.java @@ -0,0 +1,21 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.ModConfig; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The largest value a numeric component of a configuration record accepts; see {@link Min}. + * {@link ModConfig#bind} reports a larger value in {@code config.toml} with its key. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.RECORD_COMPONENT) +public @interface Max +{ + double value(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Min.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Min.java new file mode 100644 index 0000000..2e228ac --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/Min.java @@ -0,0 +1,28 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.ModConfig; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The smallest value a numeric component of a configuration record accepts. {@link ModConfig#bind} + * reports a smaller value in {@code config.toml} with its key, together with every other + * problem. On a {@code List}, {@code Map}, or {@code Optional} component, it applies to each + * value. The bound may be a fraction ({@code @Min(0.1)}); it is not {@code NaN}. Values are + * compared as {@code double}. Storage records ignore it. + * + *
{@code
+ * record Settings(@Min(1) @Max(100) int maxPlayers) {}
+ * }
+ */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.RECORD_COMPONENT) +public @interface Min +{ + double value(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/annotations/RegisterCommand.java b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/RegisterCommand.java new file mode 100644 index 0000000..8dc9d30 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/annotations/RegisterCommand.java @@ -0,0 +1,28 @@ +package dev.overlord.zomboidforge.api.annotations; + +import dev.overlord.zomboidforge.api.Commands; +import dev.overlord.zomboidforge.api.Mod; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Registers the class as an admin command, as {@link Commands#register} does, while the mod + * loads: after the entry point's listener methods and before {@link Mod#onLoad()}. Only classes + * in the mod's own jar are found, not those of its libraries; several are registered in the + * order of their names. The class follows the rules of {@link Commands}. + * + *
{@code
+ * @RegisterCommand
+ * @CommandName(name = "zfhello")
+ * @RequiredCapability(requiredCapability = Capability.LoginOnServer)
+ * public class HelloCommand extends CommandBase { ... }
+ * }
+ */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface RegisterCommand {} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java index c8b26c7..d44e6a0 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java @@ -33,6 +33,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -152,11 +153,11 @@ public final class Forge try (GameClasses gameClasses = GameClasses.open(gameJar)) { - ModVerifier.verify(ordered, gameClasses, game); + Map> annotatedCommands = ModVerifier.verify(ordered, gameClasses, game); for (ModDiscovery.Candidate candidate : ordered) ModTables.adoptPreviousIds(storage, candidate.id(), candidate.descriptor().previousIds(), installed); - this.mods = ModLoader.load(ordered, game, parent, gameClasses, this::services); + this.mods = ModLoader.load(ordered, game, parent, gameClasses, this::services, annotatedCommands); } catch (IOException e) { diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java b/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java index 46677c4..25657e8 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java @@ -1,5 +1,9 @@ package dev.overlord.zomboidforge.core.config; +import dev.overlord.zomboidforge.api.annotations.Key; +import dev.overlord.zomboidforge.api.annotations.Max; +import dev.overlord.zomboidforge.api.annotations.Min; + import org.jetbrains.annotations.Nullable; import java.lang.reflect.Constructor; @@ -16,14 +20,26 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; +import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Converts {@link TomlTree} values to records and other Java types. Collects every problem - * instead of stopping at the first one, and records the keys no component reads. + * instead of stopping at the first one, and records the keys no component reads. Record + * components are read by their {@link Key} or converted name, and checked against their + * {@link Min} and {@link Max}. */ public final class RecordBinder { + /** Bounds of a numeric component from {@link Min} and {@link Max}; {@code null} when absent. */ + private record Bounds(@Nullable Double min, @Nullable Double max) + { + static final Bounds NONE = new Bounds(null, null); + } + + private static final Pattern KEY = Pattern.compile("[a-z][a-z0-9]*(_[a-z0-9]+)*"); + private static final Set> NUMBERS = Set.of(long.class, Long.class, int.class, Integer.class, double.class, Double.class, float.class, Float.class); + private final List problems = new ArrayList<>(); private final Set unknownKeys = new TreeSet<>(); @@ -51,20 +67,49 @@ public final class RecordBinder return key.toString(); } + /** + * The keys of the components of {@code type}, in component order: each component's + * {@link Key}, or its name converted by {@link #key(String)}. + * + * @throws IllegalArgumentException when a {@link Key} is not {@code snake_case}, or two + * components have the same key + */ + public static List keys(Class type) + { + List keys = new ArrayList<>(); + + for (RecordComponent component : type.getRecordComponents()) + { + Key annotation = component.getAnnotation(Key.class); + String key = annotation == null ? RecordBinder.key(component.getName()) : annotation.value(); + + if (annotation != null && !RecordBinder.KEY.matcher(key).matches()) + throw new IllegalArgumentException("'" + type.getName() + "." + component.getName() + "' has @Key(\"" + key + "\"); keys are lowercase letters, digits, and single underscores, starting with a letter."); + + if (keys.contains(key)) + throw new IllegalArgumentException("'" + type.getName() + "' has two components with the key '" + key + "'."); + + keys.add(key); + } + + return keys; + } + /** A record of {@code type} from {@code table}, or {@code null} when a problem was found. */ public @Nullable T record(Map table, Class type, String path) { RecordComponent[] components = type.getRecordComponents(); + List names = RecordBinder.keys(type); @Nullable Object[] arguments = new Object[components.length]; Set keys = new TreeSet<>(table.keySet()); int before = this.problems.size(); for (int i = 0; i < components.length; i++) { - String key = RecordBinder.key(components[i].getName()); + String key = names.get(i); keys.remove(key); - arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key)); + arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key), RecordBinder.bounds(components[i])); } for (String key : keys) this.unknownKeys.add(RecordBinder.join(path, key)); @@ -94,7 +139,10 @@ public final class RecordBinder * {@code raw} converted to {@code target}, or {@code null} after recording a problem. * {@code raw == null} means the key is missing. */ - public @Nullable Object value(@Nullable Object raw, Type target, String path) + public @Nullable Object value(@Nullable Object raw, Type target, String path) { return this.value(raw, target, path, Bounds.NONE); } + + /** Like {@link #value(Object, Type, String)}; numbers, also inside an {@code Optional}, {@code List}, or {@code Map}, are checked against {@code bounds}. */ + private @Nullable Object value(@Nullable Object raw, Type target, String path, Bounds bounds) { Class type = RecordBinder.rawType(target); @@ -102,7 +150,7 @@ public final class RecordBinder { if (raw == null) return Optional.empty(); - Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path); + Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path, bounds); return element == null ? null : Optional.of(element); } @@ -110,14 +158,14 @@ public final class RecordBinder if (type == String.class) return raw instanceof String ? raw : this.mistyped(path, "a string", raw); if (type == boolean.class || type == Boolean.class) return raw instanceof Boolean ? raw : this.mistyped(path, "true or false", raw); - if (type == long.class || type == Long.class) return raw instanceof Long ? raw : this.mistyped(path, "an integer", raw); - if (type == int.class || type == Integer.class) return this.integer(raw, path); - if (type == double.class || type == Double.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).doubleValue() : this.mistyped(path, "a number", raw); - if (type == float.class || type == Float.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).floatValue() : this.mistyped(path, "a number", raw); + if (type == long.class || type == Long.class) return this.bounded(raw instanceof Long ? raw : this.mistyped(path, "an integer", raw), path, bounds); + if (type == int.class || type == Integer.class) return this.bounded(this.integer(raw, path), path, bounds); + if (type == double.class || type == Double.class) return this.bounded(raw instanceof Long || raw instanceof Double ? ((Number) raw).doubleValue() : this.mistyped(path, "a number", raw), path, bounds); + if (type == float.class || type == Float.class) return this.bounded(raw instanceof Long || raw instanceof Double ? ((Number) raw).floatValue() : this.mistyped(path, "a number", raw), path, bounds); if (type.isEnum()) return this.constant(raw, type, path); if (type.isRecord()) return raw instanceof Map table ? this.record(TomlTree.cast(table), type.asSubclass(Record.class), path) : this.mistyped(path, "a table", raw); - if (type == List.class) return this.list(raw, RecordBinder.typeArgument(target, 0), path); - if (type == Map.class) return this.map(raw, target, path); + if (type == List.class) return this.list(raw, RecordBinder.typeArgument(target, 0), path, bounds); + if (type == Map.class) return this.map(raw, target, path, bounds); throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "', which configuration values cannot have."); } @@ -144,7 +192,23 @@ public final class RecordBinder return this.mistyped(path, "one of " + allowed, raw); } - private @Nullable Object list(Object raw, Type element, String path) + /** {@code value} when it is within {@code bounds}; {@code null} after recording a problem, or when {@code value} is {@code null} already. */ + private @Nullable Object bounded(@Nullable Object value, String path, Bounds bounds) + { + if (value == null || bounds == Bounds.NONE) return value; + + // Integers above 2^53 lose precision as doubles; configuration values do not get there. + double number = ((Number) value).doubleValue(); + Double min = bounds.min(); + Double max = bounds.max(); + + if (min != null && number < min) return this.problem(path, "must be at least " + RecordBinder.bound(min) + ", found " + value); + if (max != null && number > max) return this.problem(path, "must be at most " + RecordBinder.bound(max) + ", found " + value); + + return value; + } + + private @Nullable Object list(Object raw, Type element, String path, Bounds bounds) { if (!(raw instanceof List list)) return this.mistyped(path, "a list", raw); @@ -153,14 +217,14 @@ public final class RecordBinder for (int i = 0; i < list.size(); i++) { - Object value = this.value(list.get(i), element, path + "[" + i + "]"); + Object value = this.value(list.get(i), element, path + "[" + i + "]", bounds); if (value != null) values.add(value); } return this.problems.size() > before ? null : List.copyOf(values); } - private @Nullable Object map(Object raw, Type target, String path) + private @Nullable Object map(Object raw, Type target, String path, Bounds bounds) { if (RecordBinder.typeArgument(target, 0) != String.class) throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "'; configuration maps need String keys."); @@ -172,7 +236,7 @@ public final class RecordBinder for (Map.Entry entry : TomlTree.cast(table).entrySet()) { - Object value = this.value(entry.getValue(), RecordBinder.typeArgument(target, 1), RecordBinder.join(path, entry.getKey())); + Object value = this.value(entry.getValue(), RecordBinder.typeArgument(target, 1), RecordBinder.join(path, entry.getKey()), bounds); if (value != null) values.put(entry.getKey(), value); } @@ -191,6 +255,44 @@ public final class RecordBinder return null; } + /** + * The bounds of {@code component} from its {@link Min} and {@link Max}. + * + * @throws IllegalArgumentException when the component's values are not numbers, a bound is + * {@code NaN}, or the minimum is above the maximum + */ + private static Bounds bounds(RecordComponent component) + { + Min min = component.getAnnotation(Min.class); + Max max = component.getAnnotation(Max.class); + + if (min == null && max == null) return Bounds.NONE; + + String where = "'" + component.getDeclaringRecord().getName() + "." + component.getName() + "'"; + + if (!RecordBinder.isNumeric(component.getGenericType())) + throw new IllegalArgumentException(where + " has @Min or @Max, but its values are not numbers."); + + if ((min != null && Double.isNaN(min.value())) || (max != null && Double.isNaN(max.value()))) + throw new IllegalArgumentException(where + " has a @Min or @Max that is not a number."); + + if (min != null && max != null && min.value() > max.value()) + throw new IllegalArgumentException(where + " has @Min(" + RecordBinder.bound(min.value()) + ") above @Max(" + RecordBinder.bound(max.value()) + ")."); + + return new Bounds(min == null ? null : min.value(), max == null ? null : max.value()); + } + + /** Whether values of {@code type} are numbers, also as the values of an {@code Optional}, {@code List}, or {@code Map}. */ + private static boolean isNumeric(Type type) + { + Class raw = RecordBinder.rawType(type); + + if (raw == Optional.class || raw == List.class) return RecordBinder.isNumeric(RecordBinder.typeArgument(type, 0)); + if (raw == Map.class) return RecordBinder.isNumeric(RecordBinder.typeArgument(type, 1)); + + return RecordBinder.NUMBERS.contains(raw); + } + private static Class rawType(Type type) { return switch (type) @@ -208,5 +310,12 @@ public final class RecordBinder throw new IllegalArgumentException("'" + type.getTypeName() + "' needs type arguments in configuration records."); } + /** + * {@code value} for messages: whole numbers without a decimal point ({@code 100}), others as + * they are ({@code 0.5}). Beyond 10^15 the {@code double} form stays, as a {@code long} would + * not hold every such value. + */ + private static String bound(double value) { return value == Math.rint(value) && Math.abs(value) < 1e15 ? String.valueOf((long) value) : String.valueOf(value); } + private static String join(String path, String key) { return path.isEmpty() ? key : path + "." + key; } } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java index c28719b..40fa209 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java @@ -30,7 +30,8 @@ import java.util.Objects; /** * Creates the class loaders and entry points of resolved mods, in order, registers each entry - * point's listener methods, and calls {@link Mod#onLoad()}. Stops at the first mod that fails. + * point's listener methods and the mod's {@code @RegisterCommand} classes, and calls + * {@link Mod#onLoad()}. Stops at the first mod that fails. */ public final class ModLoader { @@ -62,9 +63,11 @@ public final class ModLoader * @param gameClasses classes of the Project Zomboid jar, visible to mods that declare * {@code game} versions * @param services creates each mod's threads and event registration + * @param commands mod id to its classes annotated with {@code @RegisterCommand}, as + * returned by {@link ModVerifier#verify} * @throws ModLoadException naming the mod that failed and why */ - public static List load(List ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses, ModServices.Factory services) throws ModLoadException + public static List load(List ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses, ModServices.Factory services, Map> commands) throws ModLoadException { Map loaders = new HashMap<>(); List loaded = new ArrayList<>(); @@ -102,7 +105,7 @@ public final class ModLoader provided.clientCommands() ); - loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context))); + loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context, commands.getOrDefault(descriptor.id(), List.of())))); } return List.copyOf(loaded); @@ -114,7 +117,8 @@ public final class ModLoader } } - private static Mod create(ModDescriptor descriptor, ClassLoader loader, ModContext context) throws ModLoadException + /** @param commands binary names of the mod's classes annotated with {@code @RegisterCommand} */ + private static Mod create(ModDescriptor descriptor, ClassLoader loader, ModContext context, List commands) throws ModLoadException { String id = descriptor.id(); @@ -139,6 +143,8 @@ public final class ModLoader try { context.events().register(mod); } catch (IllegalArgumentException e) { throw new ModLoadException("'" + id + "': " + e.getMessage(), e); } + for (String command : commands) ModLoader.registerCommand(descriptor, loader, context, command); + try { mod.onLoad(); } catch (Exception e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() threw " + e), e); } catch (LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() failed with " + e), e); } @@ -146,6 +152,19 @@ public final class ModLoader return mod; } + /** Registers the class {@code command}, annotated with {@code @RegisterCommand}. */ + private static void registerCommand(ModDescriptor descriptor, ClassLoader loader, ModContext context, String command) throws ModLoadException + { + String id = descriptor.id(); + Class type; + + try { type = Class.forName(command, false, loader); } + catch (ClassNotFoundException | LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': the command '" + command + "' cannot be loaded: " + e), e); } + + try { context.commands().register(type); } + catch (IllegalArgumentException e) { throw new ModLoadException("'" + id + "': " + e.getMessage(), e); } + } + private static Constructor constructor(ModDescriptor descriptor, ClassLoader loader) throws ModLoadException { String id = descriptor.id(); diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java index 84f1c63..d3c3a40 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java @@ -4,6 +4,7 @@ import dev.overlord.zomboidforge.api.GameVersion; import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; @@ -20,6 +21,7 @@ import java.io.UncheckedIOException; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; @@ -45,6 +47,8 @@ import java.util.stream.Collectors; * * * Annotations are not checked: the JVM does not load annotation types a class only carries. + * The classes of a mod's own jar annotated with {@code @RegisterCommand} are collected for the + * loader. */ public final class ModVerifier { @@ -53,6 +57,8 @@ public final class ModVerifier private static final String API_INTERNAL = "dev/overlord/zomboidforge/api/internal/"; private static final int EXAMPLES = 5; + private static final String REGISTER_COMMAND = "Ldev/overlord/zomboidforge/api/annotations/RegisterCommand;"; + /** A field or method that a mod's code uses. */ private record Member(boolean method, String owner, String name, String desc) implements Comparable { @@ -68,13 +74,16 @@ public final class ModVerifier /** * @param ordered mods in load order, as returned by {@link ModResolver#resolve} * @param version the version of {@code game}, for messages; {@code null} with {@link GameClasses#none()} + * @return mod id to the binary names of the classes in its own jar annotated with + * {@code @RegisterCommand}, sorted * @throws ModLoadException listing every problem of every mod */ - public static void verify(List ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException + public static Map> verify(List ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException { - Hierarchy hierarchy = new Hierarchy(game); - Map> ownByMod = new HashMap<>(); - List problems = new ArrayList<>(); + Hierarchy hierarchy = new Hierarchy(game); + Map> ownByMod = new HashMap<>(); + Map> commands = new HashMap<>(); + List problems = new ArrayList<>(); for (ModDiscovery.Candidate candidate : ordered) { @@ -85,6 +94,7 @@ public final class ModVerifier for (Path library : candidate.libraries()) libraries.putAll(ModVerifier.classes(library)); ownByMod.put(id, own.keySet()); + commands.put(id, ModVerifier.registeredCommands(own.values())); Set provided = new HashSet<>(own.keySet()); provided.addAll(libraries.keySet()); @@ -144,6 +154,25 @@ public final class ModVerifier } if (!problems.isEmpty()) throw new ModLoadException(problems); + + return Map.copyOf(commands); + } + + /** Binary names of the classes annotated with {@code @RegisterCommand}, sorted. */ + private static List registeredCommands(Collection classes) + { + List names = new ArrayList<>(); + + for (byte[] bytes : classes) + { + CommandAnnotation annotation = new CommandAnnotation(); + new ClassReader(bytes).accept(annotation, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); + + if (annotation.name != null) names.add(ModVerifier.dotted(annotation.name)); + } + + names.sort(null); + return List.copyOf(names); } /** Internal class name to class file, for every class in {@code jar} outside {@code META-INF/}. */ @@ -178,6 +207,27 @@ public final class ModVerifier private static String dotted(String internalName) { return internalName.replace('/', '.'); } + /** Reads whether a class carries {@code @RegisterCommand}. */ + private static final class CommandAnnotation extends ClassVisitor + { + /** The internal name of the class when it carries the annotation. */ + private @Nullable String name; + + private @Nullable String visited; + + private CommandAnnotation() { super(Opcodes.ASM9); } + + @Override + public void visit(int version, int access, String name, @Nullable String signature, @Nullable String superName, String @Nullable [] interfaces) { this.visited = name; } + + @Override + public @Nullable AnnotationVisitor visitAnnotation(String descriptor, boolean visible) + { + if (ModVerifier.REGISTER_COMMAND.equals(descriptor)) this.name = this.visited; + return null; + } + } + /** Collects the classes and members that code uses; skips annotations and debug information. */ private static final class References extends ClassVisitor { diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java index 1902866..d80b4e5 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java @@ -21,7 +21,8 @@ import java.util.regex.Pattern; /** * Converts records of one type to table rows and back. Components become columns named in - * {@code snake_case}; accessors and the canonical constructor are resolved once. + * {@code snake_case}, or by their {@code @Key}; accessors and the canonical constructor are + * resolved once. {@code @Min} and {@code @Max} are for configuration records and ignored here. * *

Stored forms: integers and booleans as {@code INTEGER}, other numbers as {@code REAL}, * texts, UUIDs, instants (ISO-8601), and enum constants (by name) as {@code TEXT}, bytes as @@ -51,10 +52,14 @@ final class RecordCodec static RecordCodec of(Class type) { RecordComponent[] components = type.getRecordComponents(); + List names; List columns = new ArrayList<>(); Class[] types = new Class[components.length]; MethodHandle[] accessors = new MethodHandle[components.length]; + try { names = RecordBinder.keys(type); } + catch (IllegalArgumentException e) { throw new StorageException(e.getMessage(), e); } + try { MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(type, MethodHandles.lookup()); @@ -62,7 +67,7 @@ final class RecordCodec for (int i = 0; i < components.length; i++) { RecordComponent component = components[i]; - String name = RecordBinder.key(component.getName()); + String name = names.get(i); String where = "'" + type.getSimpleName() + "." + component.getName() + "'"; if (!RecordCodec.NAME.matcher(name).matches()) throw new StorageException(where + " gives the column name '" + name + "'; column names are lowercase letters, digits, and single underscores."); diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java index f917e1b..5b60495 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import testmods.AnnotatedCommandMod; import testmods.CommandMod; import testmods.ContextMod; import testmods.ErrorMod; @@ -403,6 +404,47 @@ class ForgeTest forge.stopping(); } + /** {@link AnnotatedCommandMod} and its command classes, packaged as the mod {@code commands}. */ + private void annotatedCommandMod() throws IOException + { + TestMods.folder(this.mods, "commands", TestMods.toml("commands", AnnotatedCommandMod.class.getName(), ""), Map.of( + "testmods/AnnotatedCommandMod", TestMods.classFile(AnnotatedCommandMod.class), + "testmods/AnnotatedCommandMod$Hello", TestMods.classFile(AnnotatedCommandMod.Hello.class), + "testmods/AnnotatedCommandMod$Bye", TestMods.classFile(AnnotatedCommandMod.Bye.class), + "testmods/AnnotatedCommandMod$Manual", TestMods.classFile(AnnotatedCommandMod.Manual.class) + )); + } + + @Test + void registersAnnotatedCommandsByNameBeforeOnLoad() throws Exception + { + this.annotatedCommandMod(); + + Forge forge = this.load(); + String mod = AnnotatedCommandMod.class.getName(); + + assertEquals(List.of(mod + "$Bye after 0", mod + "$Hello after 1", mod + "$Manual after 2"), this.checkedCommands); + assertEquals(3, forge.commands().size()); + } + + @Test + void failsWhenAnAnnotatedCommandBreaksTheRules() throws IOException + { + this.annotatedCommandMod(); + + Forge forge = new Forge( + this.directory, + ModVersion.parse("0.3.0"), + (command, registered) -> { throw new IllegalArgumentException("'" + command.getName() + "' has no @CommandName."); }, + (player, module, command, args) -> () -> {} + ); + + ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader(), this.storageFile)); + + assertEquals(1, e.problems().size()); + ForgeTest.assertContainsAll(e.problems().getFirst(), "'commands'", "AnnotatedCommandMod$Bye"); + } + private static void assertContainsAll(String message, String... parts) { for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message); diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java index 24787dd..c5319aa 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java @@ -1,5 +1,8 @@ package dev.overlord.zomboidforge.core.config; +import dev.overlord.zomboidforge.api.annotations.Key; +import dev.overlord.zomboidforge.api.annotations.Max; +import dev.overlord.zomboidforge.api.annotations.Min; import dev.overlord.zomboidforge.core.ConsoleLogger; import org.junit.jupiter.api.Test; @@ -9,7 +12,9 @@ import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class TomlModConfigTest { @@ -30,6 +35,28 @@ class TomlModConfigTest Optional httpPort ) {} + private record Renamed(@Key("max_hp_regen") int healthRegenPerHour, String name) {} + + private record InvalidKey(@Key("Max HP") int maxHp) {} + + private record RepeatedKey(@Key("value") int amount, int value) {} + + private record Bounded( + @Min(1) @Max(100) int maxPlayers, + @Min(0) double ratio, + @Max(10) List levels, + @Min(1) Optional port, + @Min(1) Map prices + ) {} + + private record FractionalBounds(@Min(0.1) @Max(0.5) double ratio) {} + + private record BoundedText(@Min(1) String name) {} + + private record NotANumberBound(@Min(Double.NaN) double ratio) {} + + private record InvertedBounds(@Min(5) @Max(1) int amount) {} + private static TomlModConfig config(String defaults, String settings) { return new TomlModConfig(TomlTree.merge(TomlTree.parse(defaults), TomlTree.parse(settings)), new ConsoleLogger("test")); @@ -133,4 +160,88 @@ class TomlModConfigTest assertEquals(Map.of("a", 1L, "b", 2.5, "t", Map.of("x", 1L, "y", 3L)), merged); } + + @Test + void readsComponentsByTheirKeyAnnotation() + { + Renamed renamed = TomlModConfigTest.config("max_hp_regen = 5\nname = \"a\"\n", "").bind(Renamed.class); + + assertEquals(new Renamed(5, "a"), renamed); + } + + @Test + void rejectsInvalidAndRepeatedKeys() + { + TomlModConfig config = TomlModConfigTest.config("value = 1\n", ""); + + IllegalArgumentException invalid = assertThrows(IllegalArgumentException.class, () -> config.bind(InvalidKey.class)); + IllegalArgumentException repeated = assertThrows(IllegalArgumentException.class, () -> config.bind(RepeatedKey.class)); + + TomlModConfigTest.assertContainsAll(invalid.getMessage(), InvalidKey.class.getName() + ".maxHp", "Max HP"); + TomlModConfigTest.assertContainsAll(repeated.getMessage(), RepeatedKey.class.getName(), "'value'"); + } + + @Test + void reportsValuesOutsideTheirBoundsWithEveryOtherProblem() + { + String valid = """ + max_players = 100 + ratio = 0.0 + levels = [10] + port = 1 + + [prices] + apple = 1 + """; + + assertEquals(new Bounded(100, 0.0, List.of(10L), Optional.of(1), Map.of("apple", 1L)), TomlModConfigTest.config(valid, "").bind(Bounded.class)); + + TomlModConfig invalid = TomlModConfigTest.config(""" + max_players = 250 + ratio = -0.5 + levels = [1, 11] + port = 0 + + [prices] + apple = 0 + """, ""); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> invalid.bind(Bounded.class)); + + TomlModConfigTest.assertContainsAll(e.getMessage(), "'max_players'", "100", "250", "'ratio'", "-0.5", "'levels[1]'", "11", "'port'", "'prices.apple'"); + assertFalse(e.getMessage().contains("100.0"), "whole bounds without a decimal point: " + e.getMessage()); + assertFalse(e.getMessage().contains("levels[0]"), e.getMessage()); + } + + @Test + void rejectsBoundsOnNonNumbersAndInvertedBounds() + { + TomlModConfig config = TomlModConfigTest.config("name = \"a\"\namount = 3\n", ""); + + IllegalArgumentException text = assertThrows(IllegalArgumentException.class, () -> config.bind(BoundedText.class)); + IllegalArgumentException inverted = assertThrows(IllegalArgumentException.class, () -> config.bind(InvertedBounds.class)); + + TomlModConfigTest.assertContainsAll(text.getMessage(), BoundedText.class.getName() + ".name"); + TomlModConfigTest.assertContainsAll(inverted.getMessage(), InvertedBounds.class.getName() + ".amount", "5", "1"); + + IllegalArgumentException notANumber = assertThrows(IllegalArgumentException.class, () -> TomlModConfigTest.config("ratio = 0.5\n", "").bind(NotANumberBound.class)); + TomlModConfigTest.assertContainsAll(notANumber.getMessage(), NotANumberBound.class.getName() + ".ratio"); + } + + @Test + void acceptsFractionalBounds() + { + assertEquals(new FractionalBounds(0.5), TomlModConfigTest.config("ratio = 0.5\n", "").bind(FractionalBounds.class)); + + IllegalStateException above = assertThrows(IllegalStateException.class, () -> TomlModConfigTest.config("ratio = 0.75\n", "").bind(FractionalBounds.class)); + IllegalStateException below = assertThrows(IllegalStateException.class, () -> TomlModConfigTest.config("ratio = 0.05\n", "").bind(FractionalBounds.class)); + + TomlModConfigTest.assertContainsAll(above.getMessage(), "'ratio'", "0.5", "0.75"); + TomlModConfigTest.assertContainsAll(below.getMessage(), "'ratio'", "0.1", "0.05"); + } + + private static void assertContainsAll(String message, String... parts) + { + for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message); + } } diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java index ff4febd..8fab22e 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java @@ -53,6 +53,22 @@ class ModVerifierTest return e.problems(); } + @Test + void collectsTheRegisteredCommandsOfEachModsOwnJar() throws Exception + { + String annotation = "Ldev/overlord/zomboidforge/api/annotations/RegisterCommand;"; + + ModDiscovery.Candidate mod = this.mod("commands", "", Map.of( + "a/Zeta", TestMods.type("a/Zeta", "java/lang/Object", annotation), + "a/Alpha", TestMods.type("a/Alpha", "java/lang/Object", annotation), + "a/Plain", TestMods.type("a/Plain", "java/lang/Object", null) + ), Map.of("lib/Bundled", TestMods.type("lib/Bundled", "java/lang/Object", annotation))); + + Map> commands = assertDoesNotThrow(() -> ModVerifier.verify(List.of(mod), this.game, ModVerifierTest.GAME)); + + assertEquals(Map.of("commands", List.of("a.Alpha", "a.Zeta")), commands, "sorted, own jar only"); + } + @Test void acceptsGameUseWithDeclaredVersionsThatLinks() throws Exception { diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java index bd57c51..fd7aaff 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java @@ -1,6 +1,8 @@ package dev.overlord.zomboidforge.core.storage; +import dev.overlord.zomboidforge.api.annotations.Key; import dev.overlord.zomboidforge.api.annotations.Migrate; +import dev.overlord.zomboidforge.api.annotations.Min; import dev.overlord.zomboidforge.api.annotations.Schema; import dev.overlord.zomboidforge.api.storage.ModStorage; import dev.overlord.zomboidforge.api.storage.Row; @@ -57,6 +59,11 @@ class ModTablesTest private record RenamedDifficulty(RenamedMode mode) {} + /** {@link Balance} with the component renamed; {@code @Min} only applies to configuration. */ + private record RenamedBalance(@Key("coins") @Min(100) long amount) {} + + private record RepeatedColumn(@Key("coins") long amount, long coins) {} + @Schema(version = 2) private record AnnotatedLevel(long coins, int level) { @@ -490,6 +497,20 @@ class ModTablesTest assertThrows(StorageException.class, () -> empty.contains("a")); } + @Test + void keyAnnotationsKeepTheColumnOfARenamedComponent() + { + this.storage("shop").table("balances", Balance.class).set("a", new Balance(5)); + + Table renamed = this.storage("shop").table("balances", RenamedBalance.class); + + assertEquals(Optional.of(new RenamedBalance(5)), renamed.get("a"), "the column is the same, and @Min does not apply"); + assertTrue(this.logger.messages.isEmpty(), "no column is reported as removed: " + this.logger.messages); + + StorageException repeated = assertThrows(StorageException.class, () -> this.storage("shop").table("repeated", RepeatedColumn.class)); + ModTablesTest.assertContainsAll(repeated.getMessage(), RepeatedColumn.class.getName(), "'coins'"); + } + private static void assertContainsAll(String message, String... parts) { for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message); diff --git a/core/src/test/java/testmods/AnnotatedCommandMod.java b/core/src/test/java/testmods/AnnotatedCommandMod.java new file mode 100644 index 0000000..9d97d5a --- /dev/null +++ b/core/src/test/java/testmods/AnnotatedCommandMod.java @@ -0,0 +1,23 @@ +package testmods; + +import dev.overlord.zomboidforge.api.Mod; +import dev.overlord.zomboidforge.api.annotations.RegisterCommand; + +/** + * Entry point that tests package into a mod jar. Two command classes carry + * {@link RegisterCommand}; {@code onLoad()} registers a third. + */ +public final class AnnotatedCommandMod extends Mod +{ + /** Stands in for a command class; the tests' validator accepts any class. */ + @RegisterCommand + public static final class Hello {} + + @RegisterCommand + public static final class Bye {} + + public static final class Manual {} + + @Override + public void onLoad() { this.commands().register(AnnotatedCommandMod.Manual.class); } +}