Add FeatureRegistry.registerSettings and the @Ref annotation for value references

Modules register settings types that no stage names in when(...) explicitly; the
id must be the module's id or below it, and repeating it or also naming the type
in when(...) changes nothing. A type its owner registered may be named by any
module. OptionsMetadata.Option now carries its field and @Ref reference.
This commit is contained in:
piexel committed 2026-10-06 12:06:46 +02:00
1 parent 8b7accd19d
commit 93c755ffe4
9 files changed
+164 -23

No files matched your search

@@ -4,6 +4,7 @@ import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.stage.StageGraph;
/** Host implementation collects non-stage registrations before loading pack configuration.
* Feature IDs must be unique. JSON fields must be unique per attachment target, including the
@@ -20,4 +21,13 @@ public interface FeatureRegistry {
<T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, MantleCodec<T> codec);
<F extends IrisFeature> void registerObject(Class<F> featureType, ObjectGeneratorFactory<F> factory);
/** Catalogs a settings type that no stage names in {@code when(...)}, such as one read only
* through {@link com.volmit.config.FeatureSettings#at}, so the host decodes it and studio
* describes it. Settings that a stage names are catalogued without this; registering them as
* well changes nothing. The type's feature id must be this module's id or start with it and
* {@code /}. Once registered, other modules may name the type in {@code when(...)} (see
* {@link StageGraph}).
*/
void registerSettings(Class<? extends IrisFeature> settingsType);
}
@@ -1,5 +1,6 @@
package com.volmit.config;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
@@ -12,8 +13,17 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
options = List.copyOf(options);
}
public record Option(String name, Type type, String description,
boolean required, Double minimum, Double maximum) {}
/** One field of a settings type. {@code minimum}, {@code maximum} and {@code reference} are null when not declared. */
public record Option(Field field, String description, boolean required,
Double minimum, Double maximum, Reference reference) {
public String name() {
return field.getName();
}
public Type type() {
return field.getGenericType();
}
}
/** Reads private and inherited fields without constructing settings or accessing values.
* Nested object types are preserved for the schema builder to inspect recursively.
@@ -34,6 +44,7 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
var desc = field.getAnnotation(Desc.class);
var min = field.getAnnotation(MinNumber.class);
var max = field.getAnnotation(MaxNumber.class);
var ref = field.getAnnotation(Ref.class);
if ((min != null || max != null) && !isNumeric(field.getType())) {
throw new IllegalArgumentException("Numeric bounds on nonnumeric option: " + field.getName());
}
@@ -42,9 +53,9 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
|| (min != null && max != null && min.value() > max.value())) {
throw new IllegalArgumentException("Invalid bounds for option: " + field.getName());
}
options.add(new Option(field.getName(), field.getGenericType(),
desc == null ? "" : desc.value(), field.isAnnotationPresent(Required.class),
min == null ? null : min.value(), max == null ? null : max.value()));
options.add(new Option(field, desc == null ? "" : desc.value(), field.isAnnotationPresent(Required.class),
min == null ? null : min.value(), max == null ? null : max.value(),
ref == null ? null : ref.value()));
}
}
var desc = type.getAnnotation(Desc.class);
+13
View File
@@ -0,0 +1,13 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Says what an option's text names, such as {@code @Ref(Reference.BLOCK) String block}. Allowed on
* {@code String} and {@link com.volmit.resource.ResourceId} options and on lists, sets and arrays of
* them, where it applies to every element. Anywhere else it fails the pack load.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Ref {
Reference value();
}
@@ -0,0 +1,29 @@
package com.volmit.config;
/** What a text option names, so studio can offer the matching completion list. Platform kinds name
* entries of the server's registries, such as {@code minecraft:stone}, including those that data
* packs and mods add. Pack kinds name resources of the pack being edited. The set is closed: every
* kind is one the Iris host can list.
*/
public enum Reference {
/** A block type, such as {@code minecraft:stone}. {@link com.volmit.block.BlockState} options are block references without {@link Ref}. */
BLOCK,
/** An item type, such as {@code minecraft:stick}. */
ITEM,
/** An entity type, such as {@code minecraft:zombie}. */
ENTITY,
/** A platform biome, such as {@code minecraft:plains}; not a biome of the pack. */
BIOME,
/** A platform structure, such as {@code minecraft:village_plains}. */
STRUCTURE,
/** A potion effect type, such as {@code minecraft:speed}. */
POTION_EFFECT,
/** An enchantment, such as {@code minecraft:sharpness}. */
ENCHANTMENT,
/** A biome of the pack. */
PACK_BIOME,
/** A region of the pack. */
PACK_REGION,
/** An object of the pack. */
PACK_OBJECT
}
@@ -35,7 +35,7 @@ public record LoadedModules(FeatureCatalog catalog, ResolvedGraph placement, Res
for (var discovered : modules) {
installModule(discovered, stages, registry);
}
stages.settingsTypes().forEach(registry::registerSettings);
stages.settingsTypes(registry::registeredByOwner).forEach(registry::registerStageSettings);
return new LoadedModules(registry.freeze(), stages.resolve(Pipeline.PLACEMENT), stages.resolve(Pipeline.CHUNK));
}
@@ -18,8 +18,8 @@ import java.util.Set;
/** Reference host registry. Single-threaded registration ends with freeze(); the catalog is
* immutable. IDs are unique across feature kinds; JSON fields are unique per attachment target.
* Pass existing host JSON fields to reserve them before modules register. Modules register through
* {@link #register(DiscoveredModule)}; object feature ids and mantle keys must be the registering
* module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}). A failed registration leaves the registry unchanged. A failed module callback
* {@link #register(DiscoveredModule)}; object feature ids, mantle keys and explicitly registered
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}). A failed registration leaves the registry unchanged. A failed module callback
* invalidates the host's whole build. This does not decode JSON, discover modules or instantiate
* settings.
*/
@@ -29,6 +29,7 @@ public final class ModuleRegistry implements FeatureRegistry {
private final Map<String, MantleRegistration<?>> mantle = new HashMap<>();
private final Set<ResourceId> featureIds = new HashSet<>();
private final Set<Class<?>> featureTypes = new HashSet<>();
private final Set<Class<?>> registeredByOwner = new HashSet<>();
private final Map<Field, String> fields = new HashMap<>();
private FeatureCatalog catalog;
private DiscoveredModule registering;
@@ -81,15 +82,29 @@ public final class ModuleRegistry implements FeatureRegistry {
}
}
/** Claims a settings type named by a stage's when(...). Several stages may share one type. */
@Override
public void registerSettings(Class<? extends IrisFeature> settingsType) {
checkOpen();
var descriptor = FeatureDescriptor.of(settingsType);
requireOwnedId("Settings " + settingsType.getName() + " with feature id", descriptor.id());
catalogSettings(descriptor);
registeredByOwner.add(settingsType);
}
/** Catalogs a settings type named by a stage's when(...), whose owner {@link StageGraphBuilder}
* has checked. Several stages, and the owner's {@link #registerSettings}, may name one type.
*/
void registerStageSettings(Class<? extends IrisFeature> settingsType) {
checkOpen();
if (settings.containsKey(settingsType)) {
return;
}
var descriptor = FeatureDescriptor.of(settingsType);
claim(descriptor);
settings.put(settingsType, descriptor);
catalogSettings(FeatureDescriptor.of(settingsType));
}
/** Whether the module owning {@code settingsType} registered it through {@link #registerSettings}. */
boolean registeredByOwner(Class<?> settingsType) {
return registeredByOwner.contains(settingsType);
}
public FeatureCatalog freeze() {
@@ -99,6 +114,14 @@ public final class ModuleRegistry implements FeatureRegistry {
return catalog;
}
private void catalogSettings(FeatureDescriptor<?> descriptor) {
if (settings.containsKey(descriptor.type())) {
return;
}
claim(descriptor);
settings.put(descriptor.type(), descriptor);
}
private void requireOwnedId(String registration, ResourceId id) {
if (registering == null) {
throw new IllegalStateException(registration + " " + id + " registered outside IrisModule.register");
@@ -19,6 +19,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/** Reference host collection of module stages. Install every module, then resolve each pipeline
@@ -27,7 +28,8 @@ import java.util.stream.Collectors;
*
* <p>A module defines only stages whose ids start with its own id and '/', and a settings type
* named in {@code when(...)} must have a feature id that at least one module naming it owns: that
* module's id, or one starting with it and '/'.
* module's id, or one starting with it and '/'. A type its owner registered explicitly may be named
* by any module.
*/
public final class StageGraphBuilder implements StageGraph {
private final Map<ResourceId, StageDeclaration> declarations = new HashMap<>();
@@ -67,11 +69,14 @@ public final class StageGraphBuilder implements StageGraph {
}
/** Settings types named by when(...), ordered by feature id. Fails if no module that names a type
* owns its feature id ({@link com.volmit.ModuleInfo#ownsId}).
* owns its feature id ({@link com.volmit.ModuleInfo#ownsId}), unless {@code registeredByOwner}
* says its owner registered it explicitly.
*/
public List<Class<? extends IrisFeature>> settingsTypes() {
public List<Class<? extends IrisFeature>> settingsTypes(Predicate<Class<?>> registeredByOwner) {
var uses = settingsUses();
uses.forEach(this::requireSettingsOwner);
uses.stream()
.filter(use -> !registeredByOwner.test(use.settings().type()))
.forEach(this::requireSettingsOwner);
return uses.stream()
.<Class<? extends IrisFeature>>map(use -> use.settings().type())
.toList();
@@ -40,8 +40,8 @@ class ModuleRegistryTest {
@Test
void validatesIdsTypesAndFieldsAcrossFeatureKindsWithoutPartialRegistration() {
var registry = new ModuleRegistry();
registry.registerSettings(One.class);
registry.registerSettings(One.class);
registry.registerStageSettings(One.class);
registry.registerStageSettings(One.class);
registerAs(registry, "test:core", objects -> {
assertThrows(IllegalArgumentException.class, () -> objects.registerObject(Collision.class, ignored -> context -> null));
objects.registerObject(Two.class, ignored -> context -> null);
@@ -56,15 +56,15 @@ class ModuleRegistryTest {
@Test
void reservesHostFieldsAndRejectsInvalidFeaturesOrFactories() {
var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.BIOME, Set.of("shared")));
assertThrows(IllegalArgumentException.class, () -> registry.registerSettings(One.class));
assertThrows(IllegalArgumentException.class, () -> registry.registerSettings(MissingAnnotation.class));
assertThrows(IllegalArgumentException.class, () -> registry.registerSettings(AbstractFeature.class));
assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(One.class));
assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(MissingAnnotation.class));
assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(AbstractFeature.class));
registerAs(registry, "test:core", objects -> {
assertThrows(NullPointerException.class, () -> objects.registerObject(Two.class, null));
objects.registerObject(Two.class, ignored -> context -> null);
});
assertSame(registry.freeze(), registry.freeze());
assertThrows(IllegalStateException.class, () -> registry.registerSettings(One.class));
assertThrows(IllegalStateException.class, () -> registry.registerStageSettings(One.class));
}
@Test
@@ -135,6 +135,56 @@ class ModuleRegistryTest {
assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), reserved, Set.of()));
}
@Test
void moduleRegistersItsOwnSettingsExplicitlyAndRepeatingItChangesNothing() {
var registry = new ModuleRegistry();
registerAs(registry, "test:core", settings -> {
settings.registerSettings(One.class);
settings.registerSettings(One.class);
});
registry.registerStageSettings(One.class);
assertEquals(List.of("test:core/one"), registry.freeze().settings().stream().map(value -> value.id().toString()).toList());
assertTrue(registry.registeredByOwner(One.class));
}
@Test
void explicitSettingsFollowTheRegisteringModulesIdAndStillCollide() {
var registry = new ModuleRegistry();
var foreign = assertThrows(IllegalArgumentException.class,
() -> registerAs(registry, "test:other", settings -> settings.registerSettings(One.class)));
assertEquals("Settings " + One.class.getName() + " with feature id test:core/one must be test:other or start with "
+ "test:other/, the id of its registering module test:other from host classpath", foreign.getMessage());
assertThrows(IllegalStateException.class, () -> registry.registerSettings(One.class));
registerAs(registry, "test:core", settings -> settings.registerObject(Two.class, ignored -> context -> null));
var collision = assertThrows(IllegalArgumentException.class,
() -> registerAs(registry, "test:core", settings -> settings.registerSettings(Collision.class)));
assertTrue(collision.getMessage().startsWith("JSON field collision"), collision.getMessage());
assertTrue(registry.freeze().settings().isEmpty());
}
@Test
void settingsTheirOwnerRegisteredMayBeNamedByAnyModule() {
var owner = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:core", "Owner", "1"); }
public void install(StageGraph graph) {}
public void register(FeatureRegistry registry) { registry.registerSettings(One.class); }
};
var user = new IrisModule() {
static final PlacementStage<Void> WORK = Stage.placement("test:user/work");
public ModuleInfo info() { return ModuleInfo.of("test:user", "User", "1"); }
public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); }
};
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of());
assertEquals(List.of("test:core/one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList());
var unowned = assertThrows(IllegalArgumentException.class,
() -> LoadedModules.load(List.of(DiscoveredModule.builtIn(user)), Map.of(), Set.of()));
assertTrue(unowned.getMessage().contains("which none of the modules naming it in when(...) owns"), unowned.getMessage());
}
private static MantleCodec<String> codec(int version) {
return new MantleCodec<>() {
public int version() { return version; }
@@ -57,7 +57,7 @@ class StageGraphTest {
private static List<Class<? extends IrisFeature>> resolveSettings(IrisModule... modules) {
var builder = new StageGraphBuilder();
for (var module : modules) builder.install(DiscoveredModule.builtIn(module));
return builder.settingsTypes();
return builder.settingsTypes(type -> false);
}
private static List<String> order(ResolvedGraph graph) {