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);
}