Let modules declare pack resource kinds and validators: ResourceKind, PackResources.ids, @ResourceRef, the validation API and folders the host reserves

This commit is contained in:
piexel committed 2026-10-08 20:36:10 +02:00
1 parent 09afee8ae3
commit ef4b640867
37 files changed
+990 -128

No files matched your search

+14 -2
View File
@@ -4,12 +4,14 @@ import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.resource.ResourceKind;
import com.volmit.stage.StageGraph;
import com.volmit.validation.Validator;
/** 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
* settings types stages name in {@code when(...)}. Feature IDs and mantle keys a module registers
* are its module id or start with it and {@code /}, such as {@code iris:snow} or {@code iris:snow/depth}.
* settings types stages name in {@code when(...)}. Feature IDs, mantle keys and resource kind ids a module
* registers are its module id or start with it and {@code /}, such as {@code iris:snow} or {@code iris:snow/depth}.
*/
public interface FeatureRegistry {
/** Registers a layer before pack loading. Null arguments throw NullPointerException;
@@ -30,4 +32,14 @@ public interface FeatureRegistry {
* {@link StageGraph}).
*/
void registerSettings(Class<? extends IrisFeature> settingsType);
/** Declares a kind of pack resource this module reads: the JSON files under the kind's folder, served through
* {@link com.volmit.resource.PackResources} by the kind's type and described for studio from its class like
* settings. The pack load fails when another kind has the same id, type or folder, or the folder is one the
* host reads itself; the error names both owners.
*/
<T> void registerResourceKind(ResourceKind<T> kind);
/** Adds a check the host runs over the whole pack wherever it validates packs. */
void registerValidator(Validator validator);
}
+3 -1
View File
@@ -16,6 +16,8 @@ public interface IrisModule {
*/
void install(StageGraph graph);
/** Registers non-stage contributions: geometry generators and mantle layers. */
/** Registers non-stage contributions: geometry generators, mantle layers, settings no stage names, pack
* resource kinds and validators.
*/
default void register(FeatureRegistry registry) {}
}
@@ -13,9 +13,11 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
options = List.copyOf(options);
}
/** One field of a settings type. {@code minimum}, {@code maximum} and {@code reference} are null when not declared. */
/** One field of a settings type. {@code minimum}, {@code maximum}, {@code reference} and {@code resource} are null
* when not declared; {@code resource} is the class of {@link ResourceRef}.
*/
public record Option(Field field, String description, boolean required,
Double minimum, Double maximum, Reference reference) {
Double minimum, Double maximum, Reference reference, Class<?> resource) {
public String name() {
return field.getName();
}
@@ -45,6 +47,7 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
var min = field.getAnnotation(MinNumber.class);
var max = field.getAnnotation(MaxNumber.class);
var ref = field.getAnnotation(Ref.class);
var resourceRef = field.getAnnotation(ResourceRef.class);
if ((min != null || max != null) && !isNumeric(field.getType())) {
throw new IllegalArgumentException("Numeric bounds on nonnumeric option: " + field.getName());
}
@@ -55,7 +58,7 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
}
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()));
ref == null ? null : ref.value(), resourceRef == null ? null : resourceRef.value()));
}
}
var desc = type.getAnnotation(Desc.class);
@@ -0,0 +1,14 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Says that an option names a resource of the module resource kind read into {@code value}, by its key in the
* pack, such as {@code @ResourceRef(Pool.class) String startPool = "castle/start"}. Studio then offers the keys
* of that kind's files. Allowed on {@code String} options and lists, sets and arrays of them; the class must be
* the type of a resource kind some module of the pack registers. Anywhere else it fails the pack load.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ResourceRef {
Class<?> value();
}
@@ -11,6 +11,7 @@ import com.volmit.host.schema.ValueKind.ListKind;
import com.volmit.host.schema.ValueKind.MapKind;
import com.volmit.host.schema.ValueKind.ObjectKind;
import com.volmit.host.schema.ValueKind.ReferenceKind;
import com.volmit.host.schema.ValueKind.ResourceReferenceKind;
import com.volmit.host.schema.ValueKind.TextKind;
import java.lang.reflect.Array;
import java.util.ArrayList;
@@ -41,7 +42,7 @@ final class DefaultValues {
case BooleanKind _ -> Optional.of(value);
case IntegerKind _ -> Optional.of(((Number) value).longValue());
case DecimalKind _ -> decimal((Number) value);
case TextKind _, ReferenceKind _ -> Optional.of(text(value));
case TextKind _, ReferenceKind _, ResourceReferenceKind _ -> Optional.of(text(value));
case EnumKind _ -> Optional.of(((Enum<?>) value).name());
case ListKind list -> list(elements(value), list);
case MapKind map -> map((Map<?, ?>) value, map.value());
@@ -8,21 +8,30 @@ import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Function;
/** Frozen registrations. Lists use lexical feature/layer ID order, independent of discovery.
* Factory and codec implementations must themselves obey their concurrency contracts.
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators are in module id order,
* so nothing depends on discovery. Factory, codec and validator implementations must themselves obey their
* concurrency contracts.
*/
public final class FeatureCatalog {
private final Map<Class<?>, FeatureDescriptor<?>> settings;
private final Map<Class<?>, ObjectRegistration<?>> objects;
private final Map<String, MantleRegistration<?>> mantle;
private final List<ResourceKindRegistration> resourceKinds;
private final List<ValidatorRegistration> validators;
FeatureCatalog(
Map<Class<?>, FeatureDescriptor<?>> settings,
Map<Class<?>, ObjectRegistration<?>> objects,
Map<String, MantleRegistration<?>> mantle) {
Map<String, MantleRegistration<?>> mantle,
Collection<ResourceKindRegistration> resourceKinds,
List<ValidatorRegistration> validators) {
this.settings = Map.copyOf(settings);
this.objects = Map.copyOf(objects);
this.mantle = Map.copyOf(mantle);
this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id());
this.validators = validators.stream()
.sorted(Comparator.comparing(registration -> registration.module().info().id()))
.toList();
}
/** Settings types that activate stages; the host decodes them from pack JSON. */
@@ -38,6 +47,16 @@ public final class FeatureCatalog {
return sorted(mantle.values(), registration -> registration.key().id());
}
/** The pack resource kinds modules read, by kind id. */
public List<ResourceKindRegistration> resourceKinds() {
return resourceKinds;
}
/** The validators modules registered, by module id, each module's in the order it registered them. */
public List<ValidatorRegistration> validators() {
return validators;
}
private static <T, K extends Comparable<? super K>> List<T> sorted(
Collection<T> registrations,
Function<? super T, ? extends K> key) {
@@ -10,8 +10,8 @@ import java.util.Objects;
import java.util.Set;
/** Everything one pack load derives from its modules: the frozen feature catalog (including the
* settings types stages are conditioned on), its description for studio and one resolved graph per
* pipeline.
* settings types stages are conditioned on, resource kinds and validators), its description for studio and one
* resolved graph per pipeline.
*/
public record LoadedModules(
FeatureCatalog catalog, PackSchema schema, ResolvedGraph placement, ResolvedGraph chunk, ResolvedGraph mantle) {
@@ -30,15 +30,18 @@ public record LoadedModules(
* pack module whose id uses one fails the load
* @param hostTypePackages packages whose classes the host describes itself, each with its
* subpackages; only built-in modules' settings may use them (see {@link ModuleHost#describingHostTypesIn})
* @param reservedFolders pack folders the host reads itself, which no resource kind may read (see
* {@link ModuleHost#reservingFolders})
*/
public static LoadedModules load(
List<DiscoveredModule> modules,
Map<FeatureAttachment.Target, Set<String>> reservedHostFields,
Collection<String> reservedNamespaces,
Collection<String> hostTypePackages) {
Collection<String> hostTypePackages,
Collection<String> reservedFolders) {
var reserved = ReservedNamespaces.of(reservedNamespaces);
modules.forEach(reserved::requireAllowed);
var registry = new ModuleRegistry(reservedHostFields);
var registry = new ModuleRegistry(reservedHostFields, Set.copyOf(reservedFolders));
var stages = new StageGraphBuilder();
for (var discovered : modules) {
installModule(discovered, stages, registry);
@@ -37,7 +37,7 @@ public final class LoadedPack implements AutoCloseable {
var packModules = PackModules.load(packRoot, host.exposedHostPackages(), host.jarCopyRoot(), host.logger());
try {
var loaded = LoadedModules.load(host.withPackModules(packModules.modules()),
host.reservedHostFields(), host.reservedNamespaces(), host.hostTypePackages());
host.reservedHostFields(), host.reservedNamespaces(), host.hostTypePackages(), host.reservedFolders());
return new LoadedPack(packModules, loaded);
} catch (RuntimeException | Error failure) {
closeAfterFailure(packModules, failure);
+31 -10
View File
@@ -2,6 +2,7 @@ package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.IrisModule;
import com.volmit.resource.ResourceKind;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
@@ -14,8 +15,8 @@ import java.util.TreeSet;
/** The host's side of every pack load, the same for all packs: its built-in modules, the host
* packages pack modules may use besides the Iris API, the JSON fields the host itself uses (which no
* built-in alias may take), the namespaces only built-in modules may use and the packages of the
* classes the host describes itself. Build it once and pass it to every
* built-in alias may take), the namespaces only built-in modules may use, the packages of the
* classes the host describes itself and the pack folders it reads itself (which no resource kind may read). Build it once and pass it to every
* {@link LoadedPack#load(java.nio.file.Path, ModuleHost)}.
*
* <pre>{@code
@@ -27,7 +28,7 @@ import java.util.TreeSet;
*
* Every method adds to what earlier calls configured, so a host can build the configuration in steps.
* Built-in modules' {@code info()} is read here, once. Exposed package names, reserved namespaces,
* host type packages and reserved field names are checked here, so a mistake fails when the host starts rather than at the
* host type packages, reserved folders and reserved field names are checked here, so a mistake fails when the host starts rather than at the
* first pack load.
*/
public record ModuleHost(
@@ -36,6 +37,7 @@ public record ModuleHost(
Map<FeatureAttachment.Target, Set<String>> reservedHostFields,
Set<String> reservedNamespaces,
Set<String> hostTypePackages,
Set<String> reservedFolders,
Path jarCopyRoot,
System.Logger logger) {
private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir";
@@ -46,12 +48,14 @@ public record ModuleHost(
reservedHostFields = copyOf(reservedHostFields);
reservedNamespaces = Set.copyOf(reservedNamespaces);
hostTypePackages = Set.copyOf(hostTypePackages);
reservedFolders = Set.copyOf(reservedFolders);
Objects.requireNonNull(jarCopyRoot, "jarCopyRoot");
Objects.requireNonNull(logger, "logger");
ExposedPackages.apiAnd(exposedHostPackages);
ReservedNamespaces.of(reservedNamespaces);
HostTypes.of(hostTypePackages);
requireFieldNames(reservedHostFields);
requireFolderNames(reservedFolders);
}
/** The given built-in modules, exposing only the Iris API and reserving nothing. Jar copies go to
@@ -59,7 +63,7 @@ public record ModuleHost(
*/
public static ModuleHost of(List<? extends IrisModule> builtInModules) {
var builtIns = builtInModules.stream().map(DiscoveredModule::builtIn).toList();
return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), Set.of(), systemTemporaryDirectory(),
return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), Set.of(), Set.of(), systemTemporaryDirectory(),
System.getLogger(PackModules.class.getName()));
}
@@ -68,13 +72,13 @@ public record ModuleHost(
*/
public ModuleHost exposing(String... packages) {
return new ModuleHost(builtIns, union(exposedHostPackages, packages), reservedHostFields, reservedNamespaces,
hostTypePackages, jarCopyRoot, logger);
hostTypePackages, reservedFolders, jarCopyRoot, logger);
}
/** This configuration with {@code namespaces} reserved for built-in modules. */
public ModuleHost reservingNamespaces(String... namespaces) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, union(reservedNamespaces, namespaces),
hostTypePackages, jarCopyRoot, logger);
hostTypePackages, reservedFolders, jarCopyRoot, logger);
}
/** This configuration with {@code fields} also reserved as JSON fields the host itself uses,
@@ -82,7 +86,7 @@ public record ModuleHost(
*/
public ModuleHost reservingFields(Map<FeatureAttachment.Target, Set<String>> fields) {
return new ModuleHost(builtIns, exposedHostPackages, merge(reservedHostFields, fields), reservedNamespaces,
hostTypePackages, jarCopyRoot, logger);
hostTypePackages, reservedFolders, jarCopyRoot, logger);
}
/** This configuration with the classes in {@code packages}, each with its subpackages, described by
@@ -92,7 +96,15 @@ public record ModuleHost(
*/
public ModuleHost describingHostTypesIn(String... packages) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces,
union(hostTypePackages, packages), jarCopyRoot, logger);
union(hostTypePackages, packages), reservedFolders, jarCopyRoot, logger);
}
/** This configuration with {@code folders}, folder names directly below a pack's root, also read by the host
* itself, such as its biome and object folders. A module resource kind that reads one fails the pack load.
*/
public ModuleHost reservingFolders(String... folders) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, hostTypePackages,
union(reservedFolders, folders), jarCopyRoot, logger);
}
/** This configuration copying module jars into new directories below {@code directory}, such as a
@@ -100,7 +112,7 @@ public record ModuleHost(
*/
public ModuleHost copyingJarsTo(Path directory) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, hostTypePackages,
directory, logger);
reservedFolders, directory, logger);
}
/** This configuration logging each pack load's module summary and missing-classes warning to
@@ -108,7 +120,7 @@ public record ModuleHost(
*/
public ModuleHost loggingTo(System.Logger logger) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, hostTypePackages,
jarCopyRoot, logger);
reservedFolders, jarCopyRoot, logger);
}
/** The built-in modules followed by a pack's modules, in the order {@link LoadedModules} installs them. */
@@ -133,6 +145,15 @@ public record ModuleHost(
fields.values().forEach(names -> names.forEach(FeatureAttachment::requireFieldName));
}
private static void requireFolderNames(Set<String> folders) {
for (var folder : folders) {
if (!ResourceKind.isFolderName(folder)) {
throw new IllegalArgumentException("Reserved folder '" + folder + "' is not a folder name directly below the"
+ " pack root, such as biomes");
}
}
}
private static Map<FeatureAttachment.Target, Set<String>> merge(
Map<FeatureAttachment.Target, Set<String>> existing,
Map<FeatureAttachment.Target, Set<String>> added) {
@@ -9,6 +9,8 @@ import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import com.volmit.validation.Validator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -21,8 +23,10 @@ import java.util.Set;
* immutable. IDs are unique across feature kinds, and every feature id is its JSON key. Aliases,
* which only built-in modules may set, are unique per attachment target and may not equal the
* host JSON fields passed in to reserve them. Modules register through
* {@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
* {@link #register(DiscoveredModule)}; object feature ids, mantle keys, resource kind ids and explicitly registered
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}).
* Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own
* files. 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.
*/
@@ -34,6 +38,9 @@ public final class ModuleRegistry implements FeatureRegistry {
private final Set<Class<?>> featureTypes = new HashSet<>();
private final Set<Class<?>> registeredByOwner = new HashSet<>();
private final Map<Field, String> fields = new HashMap<>();
private final Map<ResourceId, ResourceKindRegistration> resourceKinds = new HashMap<>();
private final List<ValidatorRegistration> validators = new ArrayList<>();
private final Set<String> reservedFolders;
private final List<DiscoveredModule> registered = new ArrayList<>();
private FeatureCatalog catalog;
private DiscoveredModule registering;
@@ -43,7 +50,13 @@ public final class ModuleRegistry implements FeatureRegistry {
}
public ModuleRegistry(Map<FeatureAttachment.Target, Set<String>> reservedFields) {
this(reservedFields, Set.of());
}
/** @param reservedFolders folders below the pack root that the host reads itself, which no resource kind may read */
public ModuleRegistry(Map<FeatureAttachment.Target, Set<String>> reservedFields, Set<String> reservedFolders) {
reserveHostFields(reservedFields);
this.reservedFolders = Set.copyOf(reservedFolders);
}
/** Lets the module register its contributions through {@link IrisModule#register}. */
@@ -96,6 +109,26 @@ public final class ModuleRegistry implements FeatureRegistry {
registeredByOwner.add(settingsType);
}
@Override
public <T> void registerResourceKind(ResourceKind<T> kind) {
checkOpen();
Objects.requireNonNull(kind, "kind");
requireOwnedId("Resource kind", kind.id());
var registration = new ResourceKindRegistration(kind, registering);
requireUnclaimedKind(registration);
resourceKinds.put(kind.id(), registration);
}
@Override
public void registerValidator(Validator validator) {
checkOpen();
Objects.requireNonNull(validator, "validator");
if (registering == null) {
throw new IllegalStateException("Validator " + validator + " registered outside IrisModule.register");
}
validators.add(new ValidatorRegistration(validator, registering));
}
/** 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. Call
* it after every module has registered, so the owner is known.
@@ -116,7 +149,7 @@ public final class ModuleRegistry implements FeatureRegistry {
public FeatureCatalog freeze() {
if (catalog == null) {
catalog = new FeatureCatalog(settings, objects, mantle);
catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators);
}
return catalog;
}
@@ -146,6 +179,28 @@ public final class ModuleRegistry implements FeatureRegistry {
+ info.idPrefix() + ", the id of its registering module " + registering);
}
/** One id, one type and one folder per kind: the host finds resources by type and reads each folder as one kind. */
private void requireUnclaimedKind(ResourceKindRegistration added) {
var kind = added.kind();
if (resourceKinds.containsKey(kind.id())) {
throw new IllegalArgumentException("Duplicate resource kind: " + kind.id() + " of module " + added.module());
}
if (reservedFolders.contains(kind.folder())) {
throw new IllegalArgumentException("Resource kind " + kind.id() + " of module " + added.module() + " reads folder '"
+ kind.folder() + "', which the host reads itself; give the kind a folder of its own");
}
for (var existing : resourceKinds.values()) {
if (existing.kind().type() == kind.type()) {
throw new IllegalArgumentException(added + " reads into " + kind.type().getName() + ", which " + existing
+ " reads into already; resources are found by their type, so each kind needs a class of its own");
}
if (existing.kind().folder().equals(kind.folder())) {
throw new IllegalArgumentException(added + " reads folder '" + kind.folder() + "', which " + existing
+ " reads already; a folder holds one kind, so give one of them a folder of its own");
}
}
}
private void reserveHostFields(Map<FeatureAttachment.Target, Set<String>> reservedFields) {
for (var entry : reservedFields.entrySet()) {
for (var name : entry.getValue()) {
@@ -4,7 +4,10 @@ import com.volmit.host.schema.FeatureRole;
import com.volmit.host.schema.FeatureSchema;
import com.volmit.host.schema.ObjectType;
import com.volmit.host.schema.PackSchema;
import com.volmit.host.schema.ResourceKindSchema;
import com.volmit.host.schema.SchemaOption;
import com.volmit.host.schema.ValueKind;
import com.volmit.resource.ResourceId;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
@@ -15,10 +18,10 @@ import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/** Describes a loaded pack's catalogued settings for studio. Fails the load, naming the class, field
* and module, on settings the host could not render: an unsupported field type, a misplaced
* {@code @Ref}, a class without a usable no-argument constructor, a snippet name used twice or a pack
* class's snippet name outside its module's path.
/** Describes a loaded pack's catalogued settings and resource kinds for studio. Fails the load, naming the class,
* field and module, on what the host could not render: an unsupported field type, a misplaced {@code @Ref} or
* {@code @ResourceRef}, a class without a usable no-argument constructor, a snippet name used twice, a pack
* class's snippet name outside its module's path, or a pack module's resource kind read into a host type.
*/
final class PackSchemaBuilder {
private static final Pattern SNIPPET_NAME = Pattern.compile("[a-z0-9_.-]+(/[a-z0-9_.-]+)*");
@@ -28,20 +31,49 @@ final class PackSchemaBuilder {
private final List<DiscoveredModule> modules;
private final TypeDrafts drafts;
private PackSchemaBuilder(List<DiscoveredModule> modules, HostTypes hostTypes) {
private final HostTypes hostTypes;
private PackSchemaBuilder(FeatureCatalog catalog, List<DiscoveredModule> modules, HostTypes hostTypes) {
this.modules = modules;
this.drafts = new TypeDrafts(hostTypes);
this.hostTypes = hostTypes;
this.drafts = new TypeDrafts(hostTypes, type -> resourceKindOf(catalog, type));
}
static PackSchema describe(FeatureCatalog catalog, List<DiscoveredModule> modules, HostTypes hostTypes) {
return new PackSchemaBuilder(modules, hostTypes).describe(catalog);
return new PackSchemaBuilder(catalog, modules, hostTypes).describe(catalog);
}
private PackSchema describe(FeatureCatalog catalog) {
var features = catalogued(catalog).map(this::draft).toList();
var resources = catalog.resourceKinds().stream().map(this::describe).toList();
requireUniqueSnippets();
var types = completeTypes();
return new PackSchema(features.stream().map(feature -> feature.complete(types)).toList(), List.copyOf(types.values()));
return new PackSchema(features.stream().map(feature -> feature.complete(types)).toList(), resources,
List.copyOf(types.values()));
}
private static Optional<ResourceId> resourceKindOf(FeatureCatalog catalog, Class<?> type) {
return catalog.resourceKinds().stream()
.map(ResourceKindRegistration::kind)
.filter(kind -> kind.type() == type)
.map(com.volmit.resource.ResourceKind::id)
.findFirst();
}
/** A built-in kind may read into a class the host describes itself, as built-in settings may hold one. */
private ResourceKindSchema describe(ResourceKindRegistration registration) {
var kind = registration.kind();
var module = registration.module();
return new ResourceKindSchema(kind.id(), module.info(), kind.folder(), fileType(registration));
}
private ValueKind fileType(ResourceKindRegistration registration) {
var type = registration.kind().type();
if (!hostTypes.contains(type)) return drafts.resourceKind(SchemaSource.resourceKind(registration.kind(), registration.module()));
if (registration.module().source() == DiscoveredModule.Source.HOST) return new ValueKind.HostKind(type.getName());
throw new IllegalArgumentException("Resource kind " + registration.kind().id() + " of module " + registration.module()
+ " reads into " + type.getName() + ", a class the host describes itself, which only modules that ship with"
+ " the host may use; read the files into a class of the module");
}
/** One catalogued settings type and why it is in the catalog. */
@@ -66,7 +98,7 @@ final class PackSchemaBuilder {
private FeatureDraft draft(Catalogued catalogued) {
var owner = ownerOf(catalogued.descriptor());
drafts.settings(new SchemaSource(catalogued.descriptor(), owner));
drafts.settings(SchemaSource.settings(catalogued.descriptor(), owner));
return new FeatureDraft(catalogued, owner);
}
@@ -0,0 +1,17 @@
package com.volmit.host;
import com.volmit.resource.ResourceKind;
import java.util.Objects;
/** A resource kind and the module that registered it, which owns its id. */
public record ResourceKindRegistration(ResourceKind<?> kind, DiscoveredModule module) {
public ResourceKindRegistration {
Objects.requireNonNull(kind, "kind");
Objects.requireNonNull(module, "module");
}
@Override
public String toString() {
return "resource kind " + kind.id() + " of module " + module;
}
}
@@ -1,9 +1,23 @@
package com.volmit.host;
/** The settings, and their module, that first reached a class while describing a pack; load errors name them. */
record SchemaSource(FeatureDescriptor<?> feature, DiscoveredModule module) {
import com.volmit.resource.ResourceKind;
/** The settings or resource kind, and its module, that first reached a class while describing a pack; load errors name them.
*
* @param subject what reached the class, such as {@code settings example:flora}
* @param type the class the subject is read into
*/
record SchemaSource(String subject, Class<?> type, DiscoveredModule module) {
static SchemaSource settings(FeatureDescriptor<?> feature, DiscoveredModule module) {
return new SchemaSource("settings " + feature.id(), feature.type(), module);
}
static SchemaSource resourceKind(ResourceKind<?> kind, DiscoveredModule module) {
return new SchemaSource("resource kind " + kind.id(), kind.type(), module);
}
@Override
public String toString() {
return "settings " + feature.id() + " (module " + module + ")";
return subject + " (module " + module + ")";
}
}
+21 -7
View File
@@ -3,6 +3,7 @@ package com.volmit.host;
import com.volmit.config.OptionsMetadata;
import com.volmit.host.schema.ValueKind;
import com.volmit.host.schema.ValueKind.ObjectKind;
import com.volmit.resource.ResourceId;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InaccessibleObjectException;
@@ -15,10 +16,12 @@ import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
/** Describes every class reachable from the settings of a pack, each once, except host types, which the
* host describes itself. A class is recorded before
/** Describes every class reachable from the settings and resource kinds of a pack, each once, except host types,
* which the host describes itself. A class is recorded before
* its fields are described, so a class that contains itself, directly or through others, ends the
* walk at its own name. Each class is instantiated once with its no-argument constructor, the way the
* host creates settings before decoding JSON into them, and its fields' values there are the defaults.
@@ -28,9 +31,12 @@ final class TypeDrafts {
private final Set<Class<?>> describing = new HashSet<>();
private final Map<String, Class<?>> names = new HashMap<>();
private final HostTypes hostTypes;
private final Function<Class<?>, Optional<ResourceId>> resourceKinds;
TypeDrafts(HostTypes hostTypes) {
/** @param resourceKinds the id of the resource kind read into a class, which {@code @ResourceRef} options name */
TypeDrafts(HostTypes hostTypes, Function<Class<?>, Optional<ResourceId>> resourceKinds) {
this.hostTypes = hostTypes;
this.resourceKinds = resourceKinds;
}
/** One described class: its metadata and its options with their kinds and raw default values. */
@@ -41,12 +47,20 @@ final class TypeDrafts {
/** Describes a catalogued settings type and everything it reaches. */
ObjectKind settings(SchemaSource source) {
var type = source.feature().type();
return root("Settings type", source);
}
/** Describes the class a resource kind reads its files into and everything it reaches. */
ObjectKind resourceKind(SchemaSource source) {
return root("Resource type", source);
}
private ObjectKind root(String label, SchemaSource source) {
var type = source.type();
try {
return object(type, source);
} catch (SettingsTypeProblem problem) {
throw new IllegalArgumentException("Settings type " + type.getName() + " of " + source + " "
+ problem.getMessage());
throw new IllegalArgumentException(label + " " + type.getName() + " of " + source + " " + problem.getMessage());
}
}
@@ -69,7 +83,7 @@ final class TypeDrafts {
private TypeDraft draft(Class<?> type, SchemaSource source) {
var metadata = inspect(type, source);
var instance = instantiate(type, source);
var kinds = new ValueKinds(nested -> object(nested, source), hostTypes,
var kinds = new ValueKinds(nested -> object(nested, source), hostTypes, resourceKinds,
source.module().source() == DiscoveredModule.Source.HOST);
var options = metadata.options().stream()
.map(option -> new OptionDraft(option, kind(option, kinds, source), defaultValue(option.field(), instance, source)))
@@ -0,0 +1,12 @@
package com.volmit.host;
import com.volmit.validation.Validator;
import java.util.Objects;
/** A validator and the module that registered it, which the host names when the validator fails. */
public record ValidatorRegistration(Validator validator, DiscoveredModule module) {
public ValidatorRegistration {
Objects.requireNonNull(validator, "validator");
Objects.requireNonNull(module, "module");
}
}
+79 -34
View File
@@ -16,6 +16,7 @@ import com.volmit.host.schema.ValueKind.ListKind;
import com.volmit.host.schema.ValueKind.MapKind;
import com.volmit.host.schema.ValueKind.ObjectKind;
import com.volmit.host.schema.ValueKind.ReferenceKind;
import com.volmit.host.schema.ValueKind.ResourceReferenceKind;
import com.volmit.host.schema.ValueKind.TextKind;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKey;
@@ -27,12 +28,13 @@ import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
/** Maps a settings field's declared type and {@code @Ref} to the JSON it takes. Host types become host
* kinds where the settings may use them; other classes that are none of the built-in kinds become object
* kinds through the given function. Throws {@link SettingsTypeProblem} for a type or reference that does
/** Maps a settings field's declared type, {@code @Ref} and {@code @ResourceRef} to the JSON it takes. Host types
* become host kinds where the settings may use them; other classes that are none of the built-in kinds become
* object kinds through the given function. Throws {@link SettingsTypeProblem} for a type or reference that does
* not fit.
*/
final class ValueKinds {
@@ -47,38 +49,52 @@ final class ValueKinds {
private final Function<Class<?>, ObjectKind> objects;
private final HostTypes hostTypes;
private final Function<Class<?>, Optional<ResourceId>> resourceKinds;
private final boolean hostTypesAllowed;
/** {@code hostTypesAllowed} is whether the settings belong to a module that ships with the host. */
ValueKinds(Function<Class<?>, ObjectKind> objects, HostTypes hostTypes, boolean hostTypesAllowed) {
/** {@code resourceKinds} gives the id of the resource kind read into a class; {@code hostTypesAllowed} is
* whether the settings belong to a module that ships with the host.
*/
ValueKinds(Function<Class<?>, ObjectKind> objects, HostTypes hostTypes, Function<Class<?>, Optional<ResourceId>> resourceKinds,
boolean hostTypesAllowed) {
this.objects = objects;
this.hostTypes = hostTypes;
this.resourceKinds = resourceKinds;
this.hostTypesAllowed = hostTypesAllowed;
}
ValueKind of(OptionsMetadata.Option option) {
return kind(option.type(), option.reference());
return kind(option.type(), new Naming(option.reference(), option.resource()));
}
/** {@code reference} is the field's {@code @Ref}, or null; lists, sets and arrays pass it to their elements. */
private ValueKind kind(Type type, Reference reference) {
/** What a text option names: the field's {@code @Ref} and the class of its {@code @ResourceRef}, each null when absent. */
private record Naming(Reference reference, Class<?> resource) {
static final Naming NONE = new Naming(null, null);
boolean isEmpty() {
return reference == null && resource == null;
}
}
/** Lists, sets and arrays pass {@code naming} on to their elements. */
private ValueKind kind(Type type, Naming naming) {
return switch (type) {
case Class<?> plain -> classKind(plain, reference);
case ParameterizedType generic -> genericKind(generic, reference);
case GenericArrayType array -> new ListKind(kind(array.getGenericComponentType(), reference), false);
case Class<?> plain -> classKind(plain, naming);
case ParameterizedType generic -> genericKind(generic, naming);
case GenericArrayType array -> new ListKind(kind(array.getGenericComponentType(), naming), false);
default -> throw unsupported(type, ", which is not a concrete type; name the type, such as List<String>");
};
}
private ValueKind classKind(Class<?> type, Reference reference) {
if (hostTypes.contains(type)) return hostKind(type, reference);
if (type == String.class) return text(TextFormat.PLAIN, reference);
if (type == ResourceId.class) return text(TextFormat.RESOURCE_ID, reference);
if (type == BlockState.class) return blockState(reference);
if (type.isArray()) return new ListKind(kind(type.getComponentType(), reference), false);
private ValueKind classKind(Class<?> type, Naming naming) {
if (hostTypes.contains(type)) return hostKind(type, naming);
if (type == String.class) return text(TextFormat.PLAIN, naming);
if (type == ResourceId.class) return text(TextFormat.RESOURCE_ID, naming);
if (type == BlockState.class) return blockState(naming);
if (type.isArray()) return new ListKind(kind(type.getComponentType(), naming), false);
if (isCollection(type)) throw unsupported(type, " without type arguments; " + DECLARE_COLLECTION);
if (type == ResourceKey.class) throw resourceKey(type);
requireNoReference(type, reference);
requireNoNaming(type, naming);
if (BOOLEANS.contains(type)) return new BooleanKind();
if (INTEGERS.contains(type)) return new IntegerKind();
if (DECIMALS.contains(type)) return new DecimalKind();
@@ -86,44 +102,69 @@ final class ValueKinds {
return objects.apply(type);
}
private ValueKind genericKind(ParameterizedType generic, Reference reference) {
private ValueKind genericKind(ParameterizedType generic, Naming naming) {
var raw = (Class<?>) generic.getRawType();
if (hostTypes.contains(raw)) return hostKind(raw, reference);
if (hostTypes.contains(raw)) return hostKind(raw, naming);
var arguments = generic.getActualTypeArguments();
if (raw == List.class || raw == Set.class) return new ListKind(kind(arguments[0], reference), raw == Set.class);
if (raw == Map.class) return mapKind(generic, arguments, reference);
if (raw == List.class || raw == Set.class) return new ListKind(kind(arguments[0], naming), raw == Set.class);
if (raw == Map.class) return mapKind(generic, arguments, naming);
if (isCollection(raw)) throw unsupported(generic, "; " + DECLARE_COLLECTION);
if (raw == ResourceKey.class) throw resourceKey(generic);
throw unsupported(generic, "; only List, Set and Map may have type arguments");
}
private ValueKind mapKind(ParameterizedType generic, Type[] arguments, Reference reference) {
requireNoReference(generic, reference);
private ValueKind mapKind(ParameterizedType generic, Type[] arguments, Naming naming) {
requireNoNaming(generic, naming);
if (arguments[0] != String.class) throw unsupported(generic, "; map keys must be String");
return new MapKind(kind(arguments[1], null));
return new MapKind(kind(arguments[1], Naming.NONE));
}
private HostKind hostKind(Class<?> type, Reference reference) {
requireNoReference(type, reference);
private HostKind hostKind(Class<?> type, Naming naming) {
requireNoNaming(type, naming);
if (hostTypesAllowed) return new HostKind(type.getName());
throw new SettingsTypeProblem("uses " + type.getName() + ", a class the host describes itself, which only settings of"
+ " modules that ship with the host may use; " + SUPPORTED_TYPES);
}
private static ValueKind text(TextFormat format, Reference reference) {
private ValueKind text(TextFormat format, Naming naming) {
if (naming.resource() != null) return resourceReference(format, naming);
var reference = naming.reference();
if (reference == null) return new TextKind(format);
if (format == TextFormat.RESOURCE_ID && PACK_REFERENCES.contains(reference)) throw packReferenceOnResourceId(reference);
return new ReferenceKind(reference, format);
}
/** Packs name a kind's resources by key without a namespace, as they name their biomes, so only plain text holds one. */
private ValueKind resourceReference(TextFormat format, Naming naming) {
var resource = naming.resource();
if (naming.reference() != null) {
throw new SettingsTypeProblem("has both @Ref(" + naming.reference() + ") and @ResourceRef(" + resource.getName()
+ "); an option names one kind of thing, so keep one");
}
if (format != TextFormat.PLAIN) {
throw new SettingsTypeProblem("has @ResourceRef(" + resource.getName() + ") on ResourceId, but packs name a kind's"
+ " resources by key without a namespace, such as castle/start; use String");
}
return resourceKinds.apply(resource).map(ResourceReferenceKind::new).orElseThrow(() -> new SettingsTypeProblem(
"has @ResourceRef(" + resource.getName() + "), but no module of the pack registers a resource kind read into"
+ " that class; name the class of a kind registered with FeatureRegistry.registerResourceKind"));
}
/** Packs name their biomes, regions and objects by path without a namespace, so a ResourceId could not hold one. */
private static SettingsTypeProblem packReferenceOnResourceId(Reference reference) {
return new SettingsTypeProblem("has @Ref(" + reference + ") on ResourceId, but packs name their biomes,"
+ " regions and objects by path without a namespace, such as desert/dunes; use String");
}
private static ValueKind blockState(Reference reference) {
if (reference == null || reference == Reference.BLOCK) return new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE);
private static ValueKind blockState(Naming naming) {
var reference = naming.reference();
if (naming.resource() == null && (reference == null || reference == Reference.BLOCK)) {
return new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE);
}
if (naming.resource() != null) {
throw new SettingsTypeProblem("has @ResourceRef(" + naming.resource().getName() + ") on BlockState, which always"
+ " names a block; remove the @ResourceRef or use String");
}
throw new SettingsTypeProblem("has @Ref(" + reference + ") on BlockState, which always names a block;"
+ " remove the @Ref or use String or ResourceId");
}
@@ -145,10 +186,14 @@ final class ValueKinds {
}
}
private static void requireNoReference(Type type, Reference reference) {
if (reference == null) return;
throw new SettingsTypeProblem("has @Ref(" + reference + ") on " + type.getTypeName()
+ ", but @Ref fits only String and ResourceId and lists, sets and arrays of them");
private static void requireNoNaming(Type type, Naming naming) {
if (naming.isEmpty()) return;
if (naming.reference() != null) {
throw new SettingsTypeProblem("has @Ref(" + naming.reference() + ") on " + type.getTypeName()
+ ", but @Ref fits only String and ResourceId and lists, sets and arrays of them");
}
throw new SettingsTypeProblem("has @ResourceRef(" + naming.resource().getName() + ") on " + type.getTypeName()
+ ", but @ResourceRef fits only String and lists, sets and arrays of it");
}
/** ResourceKey's type argument is the Java class a resource loads as, which tells studio nothing to list. */
@@ -1,6 +1,7 @@
package com.volmit.host.schema;
import com.volmit.FeatureAttachment;
import com.volmit.resource.ResourceId;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
@@ -10,18 +11,29 @@ import java.util.Objects;
* studio completion. It holds module-provided entries only: the host describes its own fields.
*
* <p>Everything is in a fixed order, so the same modules always give the same description: features
* by id, the features of a target by JSON key, types by name, snippets by snippet name, options and
* enum constants in declaration order.
* and resource kinds by id, the features of a target by JSON key, types by name, snippets by snippet name,
* options and enum constants in declaration order.
*
* @param features every catalogued settings type of the pack's modules, built-in ones included
* @param types every class reachable from those settings, each once
* @param resources every resource kind of the pack's modules, built-in ones included
* @param types every class reachable from those settings and resource kinds, each once
*/
public record PackSchema(List<FeatureSchema> features, List<ObjectType> types) {
public record PackSchema(List<FeatureSchema> features, List<ResourceKindSchema> resources, List<ObjectType> types) {
public PackSchema {
features = features.stream().sorted(Comparator.comparing(FeatureSchema::id)).toList();
resources = resources.stream().sorted(Comparator.comparing(ResourceKindSchema::id)).toList();
types = types.stream().sorted(Comparator.comparing(ObjectType::name)).toList();
}
/** The resource kind {@code id}, such as the one a {@link ValueKind.ResourceReferenceKind} names. */
public ResourceKindSchema resource(ResourceId id) {
Objects.requireNonNull(id, "id");
return resources.stream()
.filter(kind -> kind.id().equals(id))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("No resource kind: " + id));
}
/** The module features of one attachment target, by JSON key. */
public List<FeatureSchema> fields(FeatureAttachment.Target target) {
Objects.requireNonNull(target, "target");
@@ -0,0 +1,26 @@
package com.volmit.host.schema;
import com.volmit.ModuleInfo;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** A module resource kind and what its files hold, for the host to give studio a schema for every JSON file below
* the kind's folder.
*
* @param id the kind's id
* @param module the module that registered the kind
* @param folder the folder below the pack root that holds the kind's files
* @param type what each file holds: an {@link ValueKind.ObjectKind} naming an entry of {@link PackSchema#types()}, or
* a {@link ValueKind.HostKind} for a built-in kind whose class the host describes itself
*/
public record ResourceKindSchema(ResourceId id, ModuleInfo module, String folder, ValueKind type) {
public ResourceKindSchema {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(module, "module");
Objects.requireNonNull(folder, "folder");
Objects.requireNonNull(type, "type");
if (!(type instanceof ValueKind.ObjectKind) && !(type instanceof ValueKind.HostKind)) {
throw new IllegalArgumentException("Resource kind " + id + " files hold an object, not " + type);
}
}
}
@@ -1,6 +1,7 @@
package com.volmit.host.schema;
import com.volmit.config.Reference;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Objects;
@@ -32,6 +33,15 @@ public sealed interface ValueKind {
}
}
/** A string naming a resource of the module resource kind {@code kind} by its key in the pack, such as
* {@code castle/start}; see {@link PackSchema#resource}.
*/
record ResourceReferenceKind(ResourceId kind) implements ValueKind {
public ResourceReferenceKind {
Objects.requireNonNull(kind, "kind");
}
}
/** One of the constant names of the enum class named {@code type}, in declaration order. */
record EnumKind(String type, List<EnumConstant> constants) implements ValueKind {
public EnumKind {
@@ -1,6 +1,7 @@
package com.volmit.resource;
import com.volmit.block.BlockRegistry;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.UUID;
@@ -9,9 +10,9 @@ import java.util.UUID;
* Reload produces a different snapshotId, even for the same pack. Resources must be immutable
* or explicitly thread-safe. The requested type selects the kind of resource, so one ID can name
* both a biome and a region. Hosts serve {@code GeneratedObject} (pack objects),
* {@code PackBiome} and {@code PackRegion}; an ID the pack lacks for that kind returns empty, and a
* type the host does not serve throws IllegalArgumentException. Broken resources fail loading
* rather than appearing absent.
* {@code PackBiome}, {@code PackRegion} and the type of every {@link ResourceKind} the pack's modules
* register; an ID the pack lacks for that kind returns empty, and a type the host does not serve throws
* IllegalArgumentException. Broken resources fail loading rather than appearing absent.
* The host owns resolution, imports, native handles and caches; no filesystem paths escape.
*/
public interface PackResources {
@@ -20,6 +21,11 @@ public interface PackResources {
BlockRegistry blocks();
<T> Optional<T> find(ResourceKey<T> key);
/** The ids of every resource of the kind {@code type} selects, in id order. A type the host does not serve
* throws IllegalArgumentException, as in {@link #find}.
*/
List<ResourceId> ids(Class<?> type);
default <T> T require(ResourceKey<T> key) {
return find(key).orElseThrow(() -> new NoSuchElementException("Missing resource: " + key.id()));
}
@@ -0,0 +1,59 @@
package com.volmit.resource;
import java.lang.reflect.Modifier;
import java.util.Objects;
import java.util.regex.Pattern;
/** A kind of resource a module reads from the pack: every JSON file below {@code <pack>/<folder>/}, each read
* into a new instance of {@code type}. A file's key is its path below the folder without {@code .json}, such as
* {@code castle/keep}, and its id is {@code <pack namespace>:<key>}, the form {@link PackResources} uses for
* every pack resource. The host serves resources of the kind through {@link PackResources#find} by
* {@code type}, so each kind has a class of its own.
*
* <p>Modules register kinds with {@link com.volmit.FeatureRegistry#registerResourceKind}. The id names the kind
* in errors and studio and follows the module id like every other id the module owns: {@code iris:structure}
* owns {@code iris:structure/pool}. The folder is one folder name directly below the pack root, chosen by the
* module; one folder holds one kind, and the host's own folders belong to the host.
*
* <p>The host creates each resource with the type's no-argument constructor and reads the file's JSON into it,
* the way it reads settings, so an omitted field keeps its default. Resources are values: the host reads each
* once per pack load and hands every caller the same instance, so nobody may change one after it is read.
*/
public record ResourceKind<T>(ResourceId id, String folder, Class<T> type) {
private static final Pattern FOLDER = Pattern.compile("[a-z0-9_.-]+");
public ResourceKind {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(folder, "folder");
Objects.requireNonNull(type, "type");
requireFolderName(id, folder);
requireConcreteClass(id, type);
}
public static <T> ResourceKind<T> of(String id, String folder, Class<T> type) {
return new ResourceKind<>(ResourceId.parse(id), folder, type);
}
/** Whether {@code name} may name a kind's folder: one folder name of lowercase letters, digits, '-', '_' and '.'. */
public static boolean isFolderName(String name) {
return FOLDER.matcher(name).matches() && !name.equals(".") && !name.equals("..");
}
/** The key {@link PackResources#find} takes for the resource {@code resource} of this kind. */
public ResourceKey<T> key(ResourceId resource) {
return new ResourceKey<>(resource, type);
}
private static void requireFolderName(ResourceId id, String folder) {
if (isFolderName(folder)) return;
throw new IllegalArgumentException("Folder '" + folder + "' of resource kind " + id + " is not a folder name;"
+ " a kind reads one folder directly below the pack root, named with lowercase letters, digits, '-', '_' and '.'");
}
private static void requireConcreteClass(ResourceId id, Class<?> type) {
if (type.isPrimitive() || type.isArray() || type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
throw new IllegalArgumentException("Resource kind " + id + " reads into " + type.getName()
+ ", which the host cannot create; use a concrete class with a no-argument constructor");
}
}
}
@@ -0,0 +1,25 @@
package com.volmit.validation;
import java.util.Objects;
/** Something wrong with a pack that a {@link Validator} found: how much it matters, what it concerns and what it is.
* The message is a sentence for the pack's author; the host shows it with its subject.
*/
public record Problem(Severity severity, Subject subject, String message) {
public Problem {
Objects.requireNonNull(severity, "severity");
Objects.requireNonNull(subject, "subject");
Objects.requireNonNull(message, "message");
if (message.isBlank()) throw new IllegalArgumentException("Blank problem message about " + subject);
}
/** A problem that stops the pack from loading. */
public static Problem error(Subject subject, String message) {
return new Problem(Severity.ERROR, subject, message);
}
/** A problem the host logs while the pack still loads. */
public static Problem warning(Subject subject, String message) {
return new Problem(Severity.WARNING, subject, message);
}
}
@@ -0,0 +1,9 @@
package com.volmit.validation;
/** How much a {@link Problem} matters to the pack. */
public enum Severity {
/** The pack cannot be used as it is: the host refuses to load it. */
ERROR,
/** The pack works, but probably not as its author meant: the host logs it and loads the pack. */
WARNING
}
@@ -0,0 +1,49 @@
package com.volmit.validation;
import com.volmit.resource.ResourceId;
import java.util.Objects;
import java.util.regex.Pattern;
/** What a {@link Problem} concerns: a resource of the pack, by id, or a file of the pack, by its path. */
public sealed interface Subject {
/** The resource {@code id}, such as {@code overworld:castle}. */
static Subject resource(ResourceId id) {
return new Resource(id);
}
/** The file at {@code path} below the pack root, with {@code /} between folders, such as {@code structures/castle.json}. */
static Subject file(String path) {
return new PackFile(path);
}
/** A resource of the pack. One id can name resources of several kinds, so a file is clearer where the kind matters. */
record Resource(ResourceId id) implements Subject {
public Resource {
Objects.requireNonNull(id, "id");
}
@Override
public String toString() {
return id.toString();
}
}
/** A file below the pack root. */
record PackFile(String path) implements Subject {
private static final Pattern SEGMENTS = Pattern.compile("[^/\\\\]+(/[^/\\\\]+)*");
private static final Pattern RELATIVE_SEGMENT = Pattern.compile("(^|/)\\.\\.?(/|$)");
public PackFile {
Objects.requireNonNull(path, "path");
if (!SEGMENTS.matcher(path).matches() || RELATIVE_SEGMENT.matcher(path).find()) {
throw new IllegalArgumentException("File '" + path + "' is not a path below the pack root;"
+ " write it relative to the pack with '/' between folders, such as structures/castle.json");
}
}
@Override
public String toString() {
return path;
}
}
}
@@ -0,0 +1,22 @@
package com.volmit.validation;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
/** The pack one {@link Validator} checks, as the host would load it, and where it reports what it finds. Valid
* only while {@link Validator#validate} runs.
*/
public interface ValidationContext {
/** The pack's resources: the ones the host serves (objects, biomes, regions) and every module resource kind.
* {@link PackResources#ids} lists a kind's resources.
*/
PackResources resources();
/** The module settings the pack declares: every entry of every dimension, region and biome of the pack,
* whether or not a dimension reaches it.
*/
PackSettings settings();
/** Records {@code problem}. An {@link Severity#ERROR} stops the pack from loading once every validator has run. */
void report(Problem problem);
}
@@ -0,0 +1,12 @@
package com.volmit.validation;
/** Checks a pack for problems its module cares about, such as a structure that can never assemble. Modules
* register validators with {@link com.volmit.FeatureRegistry#registerValidator}; the host runs every validator of
* the pack wherever it validates packs (when a pack loads, when studio opens it, on request) and reports all
* problems together. A validator reports what it finds and returns; it must not change the pack. One that throws
* fails the validation of the pack, naming its module.
*/
@FunctionalInterface
public interface Validator {
void validate(ValidationContext pack);
}
@@ -6,6 +6,9 @@ import com.volmit.mantle.BlockBox;
import com.volmit.object.*;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.*;
import com.volmit.validation.Problem;
import com.volmit.validation.Severity;
import com.volmit.validation.Subject;
import com.volmit.world.*;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
@@ -168,4 +171,38 @@ class ApiValuesTest {
assertThrows(IllegalArgumentException.class,
() -> new PackRegion(arid.id(), "Arid", 0, land, List.of(), List.of(), List.of()));
}
static final class Keep {}
@Test
void resourceKindsReadOneFolderIntoAConcreteClass() {
var kind = ResourceKind.of("test:castle/keep", "keeps", Keep.class);
var id = ResourceId.parse("overworld:castle/main");
assertEquals(new ResourceKey<>(id, Keep.class), kind.key(id));
assertTrue(ResourceKind.isFolderName("jigsaw-pools"));
for (String folder : List.of("", ".", "..", "a/b", "Keeps", "a b")) {
var failure = assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("test:castle/keep", folder, Keep.class));
assertTrue(failure.getMessage().startsWith("Folder '" + folder + "' of resource kind test:castle/keep is not a folder name"),
failure.getMessage());
}
assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("test:castle/keep", "keeps", Runnable.class));
assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("test:castle/keep", "keeps", int.class));
assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("keep", "keeps", Keep.class));
}
@Test
void problemsConcernAResourceOrAFileBelowThePackRoot() {
var error = Problem.error(Subject.file("structures/castle.json"), "Castle never assembles.");
var warning = Problem.warning(Subject.resource(ResourceId.parse("overworld:castle")), "Castle is large.");
assertEquals(Severity.ERROR, error.severity());
assertEquals("structures/castle.json", error.subject().toString());
assertEquals(Severity.WARNING, warning.severity());
assertEquals("overworld:castle", warning.subject().toString());
for (String path : List.of("", "/structures/castle.json", "../castle.json", "structures/../castle.json", "a//b", "a\\b", "./a")) {
assertThrows(IllegalArgumentException.class, () -> Subject.file(path), path);
}
assertThrows(IllegalArgumentException.class, () -> Problem.error(Subject.file("a.json"), " "));
}
}
@@ -135,7 +135,7 @@ class ChunkPipelineTest {
@Test
void mantleStagesWriteBeyondTheirChunkAndChunkStagesReadTheirOwnPart() {
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Map.of(), Set.of(), Set.of());
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Map.of(), Set.of(), Set.of(), Set.of());
var vein = new Entry<>(Target.BIOME, PLAINS, new VeinSettings(12, 4));
int reach = loaded.mantle().stages().getFirst().reachBlocks(new DeclaredSettings(vein));
assertEquals(3, reach, "a 12 block vein from the centre column runs 3 blocks into the next chunk");
@@ -202,7 +202,7 @@ class PlacementLifecyclePortTest {
@Test
void loadingThePortCatalogsEveryConditioningSettingsType() {
var loaded = LoadedModules.load(PlacementModules.builtIns(), Map.of(), Set.of(), Set.of());
var loaded = LoadedModules.load(PlacementModules.builtIns(), Map.of(), Set.of(), Set.of(), Set.of());
assertEquals(List.of("example:moss", "iris:snow", "iris:stilt"),
loaded.catalog().settings().stream().map(settings -> settings.id().toString()).toList());
@@ -30,7 +30,7 @@ class DiscoveredModuleTest {
var module = new ShiftingIdentity();
var discovered = DiscoveredModule.builtIn(module);
var loaded = LoadedModules.load(List.of(discovered), Map.of(), Set.of(), Set.of());
var loaded = LoadedModules.load(List.of(discovered), Map.of(), Set.of(), Set.of(), Set.of());
assertEquals("first:core", discovered.info().id().toString());
assertEquals(List.of("first:core/mark"),
@@ -3,6 +3,8 @@ package com.volmit.host;
import com.volmit.*;
import com.volmit.config.Feature;
import com.volmit.mantle.*;
import com.volmit.resource.ResourceKind;
import com.volmit.validation.Validator;
import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
@@ -128,14 +130,14 @@ class ModuleRegistryTest {
public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); }
public void register(FeatureRegistry registry) { registry.registerObject(Two.class, ignored -> context -> null); }
};
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of(), Set.of());
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of(), Set.of(), Set.of());
assertEquals(List.of("test:core/one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList());
assertEquals(1, loaded.catalog().objects().size());
assertEquals(1, loaded.placement().stages().size());
assertTrue(loaded.chunk().stages().isEmpty());
var reserved = Map.of(FeatureAttachment.Target.BIOME, Set.of("shared"));
assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), reserved, Set.of(), Set.of()));
assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), reserved, Set.of(), Set.of(), Set.of()));
}
@Test
@@ -180,14 +182,72 @@ class ModuleRegistryTest {
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(), Set.of());
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.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(), Set.of()));
() -> LoadedModules.load(List.of(DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of(), Set.of()));
assertTrue(unowned.getMessage().contains("which none of the modules naming it in when(...) owns"), unowned.getMessage());
}
static class Castle {}
static class Pool {}
@Test
void resourceKindsHaveOwnedIdsAndOneIdTypeAndFolderEach() {
var registry = new ModuleRegistry(Map.of(), Set.of("biomes"));
var castles = ResourceKind.of("test:core/castle", "castles", Castle.class);
registerAs(registry, "test:core", kinds -> {
kinds.registerResourceKind(castles);
var duplicate = assertThrows(IllegalArgumentException.class, () -> kinds.registerResourceKind(castles));
assertEquals("Duplicate resource kind: test:core/castle of module test:core from host classpath", duplicate.getMessage());
});
var foreign = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:other",
kinds -> kinds.registerResourceKind(ResourceKind.of("test:core/pool", "pools", Pool.class))));
assertEquals("Resource kind test:core/pool must be test:other or start with test:other/, the id of its registering"
+ " module test:other from host classpath", foreign.getMessage());
var sameType = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:other",
kinds -> kinds.registerResourceKind(ResourceKind.of("test:other/castle", "keeps", Castle.class))));
assertEquals("resource kind test:other/castle of module test:other from host classpath reads into " + Castle.class.getName()
+ ", which resource kind test:core/castle of module test:core from host classpath reads into already; resources"
+ " are found by their type, so each kind needs a class of its own", sameType.getMessage());
var sameFolder = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:other",
kinds -> kinds.registerResourceKind(ResourceKind.of("test:other/pool", "castles", Pool.class))));
assertEquals("resource kind test:other/pool of module test:other from host classpath reads folder 'castles', which"
+ " resource kind test:core/castle of module test:core from host classpath reads already; a folder holds one kind,"
+ " so give one of them a folder of its own", sameFolder.getMessage());
var hostFolder = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:other",
kinds -> kinds.registerResourceKind(ResourceKind.of("test:other/pool", "biomes", Pool.class))));
assertEquals("Resource kind test:other/pool of module test:other from host classpath reads folder 'biomes', which the"
+ " host reads itself; give the kind a folder of its own", hostFolder.getMessage());
assertThrows(IllegalStateException.class, () -> registry.registerResourceKind(ResourceKind.of("test:core/pool", "pools", Pool.class)));
assertEquals(List.of(castles), registry.freeze().resourceKinds().stream().map(ResourceKindRegistration::kind).toList());
assertEquals("test:core", registry.freeze().resourceKinds().getFirst().module().info().id().toString());
}
@Test
void validatorsAreCataloguedByModuleIdInTheOrderEachModuleRegisteredThem() {
var registry = new ModuleRegistry();
Validator first = pack -> {};
Validator second = pack -> {};
Validator other = pack -> {};
registerAs(registry, "test:zeta", validators -> validators.registerValidator(other));
registerAs(registry, "test:alpha", validators -> {
validators.registerValidator(first);
validators.registerValidator(second);
});
assertThrows(IllegalStateException.class, () -> registry.registerValidator(pack -> {}));
assertEquals(List.of(first, second, other), registry.freeze().validators().stream().map(ValidatorRegistration::validator).toList());
assertEquals("test:alpha", registry.freeze().validators().getFirst().module().info().id().toString());
assertThrows(IllegalStateException.class, () -> registry.registerValidator(pack -> {}), "registration has ended");
}
private static MantleCodec<String> codec(int version) {
return new MantleCodec<>() {
public int version() { return version; }
@@ -44,7 +44,7 @@ class PackModulesTest {
private static LoadedModules loadWithBuiltIns(PackModules packModules) {
var modules = new ArrayList<>(PlacementModules.builtIns());
modules.addAll(packModules.modules());
return LoadedModules.load(modules, Map.of(), Set.of(), Set.of());
return LoadedModules.load(modules, Map.of(), Set.of(), Set.of(), Set.of());
}
/** Versioned entries of a multi-release jar are read like any class, so they must be real class files. */
@@ -343,7 +343,7 @@ class PackModulesTest {
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(), Set.of(), Set.of()));
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of()));
}
}
@@ -477,7 +477,7 @@ class PackModulesTest {
.writeInto(pack, "beta.jar");
try (var packModules = PackModules.load(pack)) {
var loaded = LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of());
var loaded = LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of());
assertTrue(loaded.placement().stages().stream().anyMatch(stage -> stage.stage().id().toString().equals("beta:core/size")));
var beta = packModules.modules().getLast().module().getClass();
assertEquals(0, beta.getDeclaredField("SHARED").getAnnotations().length,
@@ -494,7 +494,7 @@ class PackModulesTest {
try (var packModules = PackModules.load(pack, List.of(BUILT_IN_PACKAGE))) {
var modules = new ArrayList<>(List.of(DiscoveredModule.builtIn(new CarveModule())));
modules.addAll(packModules.modules());
var order = LoadedModules.load(modules, Map.of(), Set.of(), Set.of()).placement().stages().stream()
var order = LoadedModules.load(modules, Map.of(), Set.of(), Set.of(), Set.of()).placement().stages().stream()
.map(stage -> stage.stage().id().toString()).toList();
assertEquals(List.of("iris:carve/clear", "user:core/carved"), order);
}
@@ -572,7 +572,7 @@ class PackModulesTest {
.writeInto(pack, "once.jar");
try (var packModules = PackModules.load(pack)) {
var loaded = assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
var loaded = assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of()));
assertEquals("once:core", packModules.modules().getFirst().info().id().toString());
assertEquals(1, loaded.placement().stages().size());
}
@@ -591,7 +591,7 @@ class PackModulesTest {
.writeInto(pack, "beta.jar");
try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of())),
"Module beta:core from " + origin("beta.jar") + " failed to link or initialize a class while installing",
"java.lang.NoSuchMethodError", "pack.lib.Lib.added()");
}
@@ -603,7 +603,7 @@ class PackModulesTest {
module("pack.two.Duplicate", "dup:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "two.jar");
try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of())),
"Duplicate module dup:core from " + origin("two.jar") + "; already loaded from " + origin("one.jar"));
}
}
@@ -625,7 +625,7 @@ class PackModulesTest {
.writeInto(pack, "foreign.jar");
try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of())),
"Stage mine:other/work must start with mine:core/, the id of its defining module mine:core from " + origin("foreign.jar"));
}
}
@@ -640,8 +640,8 @@ class PackModulesTest {
assertEquals("Module iris:stilt from " + origin("stilt.jar") + " uses reserved namespace 'iris', which only "
+ "modules that ship with the host may use; give the module a namespace of its own, which its stages, "
+ "settings ids and mantle keys then use too",
failure(() -> LoadedModules.load(packModules.modules(), Map.of(), RESERVED_NAMESPACES, Set.of())));
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
failure(() -> LoadedModules.load(packModules.modules(), Map.of(), RESERVED_NAMESPACES, Set.of(), Set.of())));
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of(), Set.of()));
}
}
@@ -654,13 +654,13 @@ class PackModulesTest {
try (var packModules = PackModules.load(pack, List.of(BUILT_IN_PACKAGE))) {
var modules = new ArrayList<>(List.of(DiscoveredModule.builtIn(new CarveModule())));
modules.addAll(packModules.modules());
assertDoesNotThrow(() -> LoadedModules.load(modules, Map.of(), RESERVED_NAMESPACES, Set.of()));
assertDoesNotThrow(() -> LoadedModules.load(modules, Map.of(), RESERVED_NAMESPACES, Set.of(), Set.of()));
}
}
@Test
void invalidReservedNamespaceFails() {
assertEquals("Reserved namespace 'iris:core' is not a namespace; name one such as iris, without ':' or a path",
failure(() -> LoadedModules.load(List.of(), Map.of(), Set.of("iris:core"), Set.of())));
failure(() -> LoadedModules.load(List.of(), Map.of(), Set.of("iris:core"), Set.of(), Set.of())));
}
}
@@ -11,6 +11,7 @@ import com.volmit.host.schema.FeatureRole;
import com.volmit.host.schema.FeatureSchema;
import com.volmit.host.schema.ObjectType;
import com.volmit.host.schema.PackSchema;
import com.volmit.host.schema.ResourceKindSchema;
import com.volmit.host.schema.SchemaOption;
import com.volmit.host.schema.TextFormat;
import com.volmit.host.schema.ValueKind.BooleanKind;
@@ -23,7 +24,10 @@ import com.volmit.host.schema.ValueKind.ListKind;
import com.volmit.host.schema.ValueKind.MapKind;
import com.volmit.host.schema.ValueKind.ObjectKind;
import com.volmit.host.schema.ValueKind.ReferenceKind;
import com.volmit.host.schema.ValueKind.ResourceReferenceKind;
import com.volmit.host.schema.ValueKind.TextKind;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import com.volmit.support.TestModuleJar;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -581,4 +585,133 @@ class PackSchemaTest {
assertEquals(List.of("zeta", "alpha", "omega", "beta"), settings.options().stream().map(SchemaOption::name).toList());
}
private static final String CASTLE = "example:castle";
private static final String CASTLE_MEMBERS = """
public void register(com.volmit.FeatureRegistry registry) {
registry.registerResourceKind(com.volmit.resource.ResourceKind.of("example:castle/keep", "keeps", Keep.class));
registry.registerSettings(CastleSettings.class);
}
""";
private static TestModuleJar castle() {
return module("pack.castle.CastleModule", CASTLE, CASTLE_MEMBERS, NO_STAGES)
.source("pack.castle.Keep", """
package pack.castle;
import com.volmit.config.*;
@Desc("A keep of a castle")
public final class Keep {
@Desc("Towers on the walls") @MinNumber(1)
private int towers = 4;
@ResourceRef(Keep.class)
private String next = "";
}
""")
.source("pack.castle.CastleSettings", """
package pack.castle;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.config.*;
import java.util.List;
@Feature(id = "example:castle", name = "Castle", targets = Target.BIOME)
public final class CastleSettings implements IrisFeature {
@ResourceRef(Keep.class)
private List<String> keeps = List.of("main");
}
""");
}
private PackSchema castleSchema(ModuleHost host) {
var pack = pack("castle-" + ++brokenPacks);
castle().writeInto(pack, "castle.jar");
return schemaOf(pack, host);
}
@Test
void describesResourceKindsLikeSettingsAndReferencesToThem() {
var schema = castleSchema(NO_BUILT_INS);
var keepKind = ResourceId.parse("example:castle/keep");
var kind = schema.resources().getFirst();
assertEquals(new ResourceKindSchema(keepKind, kind.module(), "keeps", new ObjectKind("pack.castle.Keep")), kind);
assertEquals(CASTLE, kind.module().id().toString());
assertSame(kind, schema.resource(keepKind));
var keep = schema.type("pack.castle.Keep");
assertEquals("A keep of a castle", keep.description());
assertEquals(new SchemaOption("towers", new IntegerKind(), "Towers on the walls", false, OptionalDouble.of(1),
OptionalDouble.empty(), Optional.of(4L)), keep.options().getFirst());
assertEquals(new ResourceReferenceKind(keepKind), keep.options().get(1).kind(), "a resource may name others of its kind");
var keeps = schema.fields(Target.BIOME).getFirst().settings().options().getFirst();
assertEquals(new ListKind(new ResourceReferenceKind(keepKind), false), keeps.kind());
assertEquals(Optional.of(List.of("main")), keeps.defaultValue());
}
@Test
void builtInKindsMayReadIntoHostTypesWhichTheHostDescribesItself() {
var builtIn = registering("iris:palettes", ResourceKind.of("iris:palettes/palette", "palettes", Palette.class));
var schema = schemaOf(pack("palettes"), ModuleHost.of(List.of(builtIn)).describingHostTypesIn(HOST_TYPES));
assertEquals(new HostKind(Palette.class.getName()), schema.resources().getFirst().type());
assertTrue(schema.types().isEmpty(), "the host describes its own types");
}
@Test
void kindFoldersBelongToOneKindAndNeverToTheHost() {
var builtIn = registering("iris:keeps", ResourceKind.of("iris:keeps/keep", "keeps", Palette.class));
var shared = assertThrows(IllegalArgumentException.class, () -> castleSchema(ModuleHost.of(List.of(builtIn))));
assertEquals("resource kind example:castle/keep of module example:castle from modules/castle.jar reads folder 'keeps',"
+ " which resource kind iris:keeps/keep of module iris:keeps from host classpath reads already; a folder holds"
+ " one kind, so give one of them a folder of its own", shared.getMessage());
var reserved = assertThrows(IllegalArgumentException.class, () -> castleSchema(NO_BUILT_INS.reservingFolders("keeps")));
assertEquals("Resource kind example:castle/keep of module example:castle from modules/castle.jar reads folder 'keeps',"
+ " which the host reads itself; give the kind a folder of its own", reserved.getMessage());
assertThrows(IllegalArgumentException.class, () -> NO_BUILT_INS.reservingFolders("not/a/folder"));
}
@Test
void packKindsCannotReadIntoHostTypes() {
var jar = module("pack.castle.CastleModule", CASTLE, """
public void register(com.volmit.FeatureRegistry registry) {
registry.registerResourceKind(com.volmit.resource.ResourceKind.of("example:castle/palette", "palettes",
%s.class));
}
""".formatted(Palette.class.getName()), NO_STAGES).compileAgainstHostOf(Palette.class);
var pack = pack("castle-host-type");
jar.writeInto(pack, "castle.jar");
var host = NO_BUILT_INS.exposing(HOST_TYPES).describingHostTypesIn(HOST_TYPES);
var failure = assertThrows(IllegalArgumentException.class, () -> LoadedPack.load(pack, host));
assertEquals("Resource kind example:castle/palette of module example:castle from modules/castle.jar reads into "
+ Palette.class.getName() + ", a class the host describes itself, which only modules that ship with the host"
+ " may use; read the files into a class of the module", failure.getMessage());
}
@Test
void resourceReferencesNameARegisteredKindOnPlainText() {
assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer), but no"
+ " module of the pack registers a resource kind read into that class; name the class of a kind registered with"
+ " FeatureRegistry.registerResourceKind", "@ResourceRef(Integer.class) private String keep;");
assertLoadFails("Field pack.flora.FloraSettings.count of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer) on int,"
+ " but @ResourceRef fits only String and lists, sets and arrays of it", "@ResourceRef(Integer.class) private int count;");
assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer) on"
+ " ResourceId, but packs name a kind's resources by key without a namespace, such as castle/start; use String",
"@ResourceRef(Integer.class) private ResourceId keep;");
assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has both @Ref(BLOCK) and"
+ " @ResourceRef(java.lang.Integer); an option names one kind of thing, so keep one",
"@Ref(Reference.BLOCK) @ResourceRef(Integer.class) private String keep;");
}
/** A built-in module {@code id} that registers {@code kind}. */
private static com.volmit.IrisModule registering(String id, ResourceKind<?> kind) {
return new com.volmit.IrisModule() {
public com.volmit.ModuleInfo info() { return com.volmit.ModuleInfo.of(id, "Kinds", "test"); }
public void install(com.volmit.stage.StageGraph graph) {}
public void register(com.volmit.FeatureRegistry registry) { registry.registerResourceKind(kind); }
};
}
}
@@ -478,7 +478,7 @@ class StageGraphTest {
stages.define(plain).run(context -> {});
stages.define(paint).reach(2).run(context -> {});
});
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Map.of(), Set.of(), Set.of());
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Map.of(), Set.of(), Set.of(), Set.of());
assertEquals(new StageReach(24, List.of(depth)), loaded.mantle().stages().getFirst().reach());
assertEquals(StageReach.NONE, loaded.mantle().stages().get(2).reach(), "an undeclared reach is 0 with no layers");
@@ -496,7 +496,7 @@ class StageGraphTest {
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages -> {
stages.define(carve).reach(settings -> settings.declared(Toggle.class).isEmpty() ? 4 : 40).run(context -> {});
stages.define(mark).reach(2).run(context -> {});
}))), Map.of(), Set.of(), Set.of());
}))), Map.of(), Set.of(), Set.of(), Set.of());
var computed = loaded.mantle().stages().getFirst();
var toggled = new DeclaredSettings(new Entry<>(FeatureAttachment.Target.DIMENSION, ResourceId.parse("pack:dimension/main"), new Toggle()));
@@ -512,7 +512,7 @@ class StageGraphTest {
@Test
void onlyMantleStagesWorkOutTheirReachAndNeverANegativeOne() {
var negative = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages ->
stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Map.of(), Set.of(), Set.of());
stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Map.of(), Set.of(), Set.of(), Set.of());
var failure = assertThrows(IllegalStateException.class, () -> negative.mantle().stages().getFirst().reachBlocks(DeclaredSettings.NONE));
assertEquals("Stage test:reach/carve of module test:reach worked out a negative reach of -1 blocks for this pack", failure.getMessage());
@@ -567,13 +567,13 @@ class StageGraphTest {
module("test:reach", stages -> stages.define(carve).writesMantle(depth, depth).run(context -> {}))));
var unregistered = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(
module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))), Map.of(), Set.of(), Set.of()));
module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))), Map.of(), Set.of(), Set.of(), Set.of()));
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth, which no module registers;"
+ " its owner registers it with FeatureRegistry.registerMantle", unregistered.getMessage());
var asText = new MantleKey<>("test:reach/depth", String.class);
var mismatch = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(
module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of(), Set.of()));
module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of(), Set.of(), Set.of()));
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth as java.lang.String,"
+ " but it is registered as java.lang.Integer", mismatch.getMessage());
}