From 3465f8d390192b3508a0c4af199dd6f3fd5f1a08 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 6 Oct 2026 12:14:34 +0200 Subject: [PATCH] Describe module settings for studio as LoadedPack.schema() PackSchema (com.volmit.host.schema) is a JSON-free description of every catalogued settings type: features with their module, JSON field and targets, every reachable class once by name (cycles end at the name), options with value kind, description, required, bounds, defaults read from a no-argument instance and @Ref references, plus object generator settings and snippets. Everything is in a fixed order. The pack load fails, naming class, field and module, on unsupported field types, @Ref on fields that are not text, classes without a working no-argument constructor and snippet names that are not folder names or are used twice. GrassSettings.block becomes a BlockState, a block reference without @Ref. --- .../java/com/volmit/host/DefaultValues.java | 119 +++++ .../java/com/volmit/host/LoadedModules.java | 11 +- src/main/java/com/volmit/host/LoadedPack.java | 8 + .../com/volmit/host/PackSchemaBuilder.java | 130 +++++ .../java/com/volmit/host/SchemaSource.java | 9 + .../com/volmit/host/SettingsTypeProblem.java | 10 + src/main/java/com/volmit/host/TypeDrafts.java | 165 +++++++ src/main/java/com/volmit/host/ValueKinds.java | 143 ++++++ .../com/volmit/host/schema/FeatureRole.java | 9 + .../com/volmit/host/schema/FeatureSchema.java | 37 ++ .../com/volmit/host/schema/ObjectType.java | 22 + .../com/volmit/host/schema/PackSchema.java | 54 ++ .../com/volmit/host/schema/SchemaOption.java | 34 ++ .../com/volmit/host/schema/TextFormat.java | 11 + .../com/volmit/host/schema/ValueKind.java | 73 +++ .../com/volmit/example/chunk/GrassModule.java | 2 +- .../volmit/example/chunk/GrassSettings.java | 8 +- .../example/placement/StiltSettings.java | 1 + .../java/com/volmit/host/PackSchemaTest.java | 462 ++++++++++++++++++ 19 files changed, 1302 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/volmit/host/DefaultValues.java create mode 100644 src/main/java/com/volmit/host/PackSchemaBuilder.java create mode 100644 src/main/java/com/volmit/host/SchemaSource.java create mode 100644 src/main/java/com/volmit/host/SettingsTypeProblem.java create mode 100644 src/main/java/com/volmit/host/TypeDrafts.java create mode 100644 src/main/java/com/volmit/host/ValueKinds.java create mode 100644 src/main/java/com/volmit/host/schema/FeatureRole.java create mode 100644 src/main/java/com/volmit/host/schema/FeatureSchema.java create mode 100644 src/main/java/com/volmit/host/schema/ObjectType.java create mode 100644 src/main/java/com/volmit/host/schema/PackSchema.java create mode 100644 src/main/java/com/volmit/host/schema/SchemaOption.java create mode 100644 src/main/java/com/volmit/host/schema/TextFormat.java create mode 100644 src/main/java/com/volmit/host/schema/ValueKind.java create mode 100644 src/test/java/com/volmit/host/PackSchemaTest.java diff --git a/src/main/java/com/volmit/host/DefaultValues.java b/src/main/java/com/volmit/host/DefaultValues.java new file mode 100644 index 000000000..8944bd522 --- /dev/null +++ b/src/main/java/com/volmit/host/DefaultValues.java @@ -0,0 +1,119 @@ +package com.volmit.host; + +import com.volmit.block.BlockState; +import com.volmit.host.schema.ValueKind; +import com.volmit.host.schema.ValueKind.BooleanKind; +import com.volmit.host.schema.ValueKind.DecimalKind; +import com.volmit.host.schema.ValueKind.EnumKind; +import com.volmit.host.schema.ValueKind.IntegerKind; +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.TextKind; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; + +/** Turns a field's default value into the JSON-shaped value {@link com.volmit.host.schema.SchemaOption} + * documents, or empty when it has none. Objects are read through the options of their described + * class, so a subclass instance shows only the declared class's options. + */ +final class DefaultValues { + private final Map types; + private final Set converting = Collections.newSetFromMap(new IdentityHashMap<>()); + + DefaultValues(Map types) { + this.types = types; + } + + Optional of(Object value, ValueKind kind) { + if (value == null) return Optional.empty(); + return switch (kind) { + 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 EnumKind _ -> Optional.of(((Enum) value).name()); + case ListKind list -> list(elements(value), list); + case MapKind map -> map((Map) value, map.value()); + case ObjectKind object -> object(value, types.get(object.type())); + }; + } + + /** A float keeps its own shortest decimal form: 0.1f is 0.1, not 0.10000000149011612. */ + private static Optional decimal(Number value) { + double converted = value instanceof Float single ? Double.parseDouble(Float.toString(single)) : value.doubleValue(); + if (!Double.isFinite(converted)) return Optional.empty(); + return Optional.of(converted); + } + + private static String text(Object value) { + if (value instanceof BlockState state) return state.key(); + return value.toString(); + } + + private static List elements(Object value) { + if (value instanceof Collection collection) return new ArrayList<>(collection); + var elements = new ArrayList<>(); + for (int index = 0; index < Array.getLength(value); index++) { + elements.add(Array.get(value, index)); + } + return elements; + } + + private Optional list(List elements, ListKind kind) { + var converted = new ArrayList(); + for (var element : elements) { + var value = of(element, kind.element()); + if (value.isEmpty()) return Optional.empty(); + converted.add(value.get()); + } + if (kind.unique()) return sortedSet(converted); + return Optional.of(List.copyOf(converted)); + } + + /** Set elements are all of one kind; only scalar ones have a natural order to sort by. */ + @SuppressWarnings({"unchecked", "rawtypes"}) + private static Optional sortedSet(List elements) { + if (!elements.stream().allMatch(element -> element instanceof Comparable)) return Optional.empty(); + elements.sort((left, right) -> ((Comparable) left).compareTo(right)); + return Optional.of(List.copyOf(elements)); + } + + private Optional map(Map entries, ValueKind valueKind) { + var converted = new TreeMap(); + for (var entry : entries.entrySet()) { + var value = of(entry.getValue(), valueKind); + if (entry.getKey() == null || value.isEmpty()) return Optional.empty(); + converted.put((String) entry.getKey(), value.get()); + } + return Optional.of(Collections.unmodifiableMap(converted)); + } + + private Optional object(Object value, TypeDrafts.TypeDraft type) { + if (!converting.add(value)) return Optional.empty(); + var converted = new TreeMap(); + for (var option : type.options()) { + of(read(option, value), option.kind()).ifPresent(field -> converted.put(option.option().name(), field)); + } + converting.remove(value); + return Optional.of(Collections.unmodifiableMap(converted)); + } + + /** {@link TypeDrafts} made every option field accessible while reading the class's own defaults. */ + private static Object read(TypeDrafts.OptionDraft option, Object instance) { + try { + return option.option().field().get(instance); + } catch (IllegalAccessException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/src/main/java/com/volmit/host/LoadedModules.java b/src/main/java/com/volmit/host/LoadedModules.java index a8efde51b..b2bb736bb 100644 --- a/src/main/java/com/volmit/host/LoadedModules.java +++ b/src/main/java/com/volmit/host/LoadedModules.java @@ -1,6 +1,7 @@ package com.volmit.host; import com.volmit.FeatureAttachment; +import com.volmit.host.schema.PackSchema; import com.volmit.stage.Pipeline; import java.util.Collection; import java.util.List; @@ -9,11 +10,13 @@ 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) and one resolved graph per pipeline. + * settings types stages are conditioned on), its description for studio and one resolved graph per + * pipeline. */ -public record LoadedModules(FeatureCatalog catalog, ResolvedGraph placement, ResolvedGraph chunk) { +public record LoadedModules(FeatureCatalog catalog, PackSchema schema, ResolvedGraph placement, ResolvedGraph chunk) { public LoadedModules { Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(schema, "schema"); Objects.requireNonNull(placement, "placement"); Objects.requireNonNull(chunk, "chunk"); } @@ -36,7 +39,9 @@ public record LoadedModules(FeatureCatalog catalog, ResolvedGraph placement, Res installModule(discovered, stages, registry); } stages.settingsTypes(registry::registeredByOwner).forEach(registry::registerStageSettings); - return new LoadedModules(registry.freeze(), stages.resolve(Pipeline.PLACEMENT), stages.resolve(Pipeline.CHUNK)); + var catalog = registry.freeze(); + var schema = PackSchemaBuilder.describe(catalog, modules); + return new LoadedModules(catalog, schema, stages.resolve(Pipeline.PLACEMENT), stages.resolve(Pipeline.CHUNK)); } /** The pack load checks that every class a module uses exists, not that every method or field diff --git a/src/main/java/com/volmit/host/LoadedPack.java b/src/main/java/com/volmit/host/LoadedPack.java index 1b309c465..d57cd9cba 100644 --- a/src/main/java/com/volmit/host/LoadedPack.java +++ b/src/main/java/com/volmit/host/LoadedPack.java @@ -1,5 +1,6 @@ package com.volmit.host; +import com.volmit.host.schema.PackSchema; import java.nio.file.Path; import java.util.List; import java.util.Objects; @@ -58,6 +59,13 @@ public final class LoadedPack implements AutoCloseable { return loaded.catalog(); } + /** What the pack's modules, built-in ones included, add to the pack's JSON, for studio's schema + * and completion. Built with the pack, so a load that returns has a complete description. + */ + public PackSchema schema() { + return loaded.schema(); + } + public ResolvedGraph placement() { return loaded.placement(); } diff --git a/src/main/java/com/volmit/host/PackSchemaBuilder.java b/src/main/java/com/volmit/host/PackSchemaBuilder.java new file mode 100644 index 000000000..971888610 --- /dev/null +++ b/src/main/java/com/volmit/host/PackSchemaBuilder.java @@ -0,0 +1,130 @@ +package com.volmit.host; + +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.SchemaOption; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalDouble; +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 or a snippet name used twice. + */ +final class PackSchemaBuilder { + private static final Pattern SNIPPET_NAME = Pattern.compile("[a-z0-9_-]+"); + + private final List modules; + private final TypeDrafts drafts = new TypeDrafts(); + + private PackSchemaBuilder(List modules) { + this.modules = modules; + } + + static PackSchema describe(FeatureCatalog catalog, List modules) { + return new PackSchemaBuilder(modules).describe(catalog); + } + + private PackSchema describe(FeatureCatalog catalog) { + var features = catalogued(catalog).map(this::draft).toList(); + requireUniqueSnippets(); + var types = completeTypes(); + return new PackSchema(features.stream().map(feature -> feature.complete(types)).toList(), List.copyOf(types.values())); + } + + /** One catalogued settings type and why it is in the catalog. */ + private record Catalogued(FeatureDescriptor descriptor, FeatureRole role) {} + + /** A feature whose settings class is drafted but whose defaults are not converted yet. */ + private record FeatureDraft(Catalogued catalogued, DiscoveredModule owner) { + FeatureSchema complete(Map types) { + var descriptor = catalogued.descriptor(); + return new FeatureSchema(descriptor.id(), descriptor.name(), catalogued.role(), owner.info(), + descriptor.attachment().field(), descriptor.attachment().targets(), types.get(descriptor.type().getName())); + } + } + + /** Ordered by feature id, so which settings an error names first never depends on discovery. */ + private static Stream catalogued(FeatureCatalog catalog) { + var settings = catalog.settings().stream().map(descriptor -> new Catalogued(descriptor, FeatureRole.SETTINGS)); + var objects = catalog.objects().stream() + .map(registration -> new Catalogued(registration.descriptor(), FeatureRole.OBJECT_GENERATOR)); + return Stream.concat(settings, objects).sorted(Comparator.comparing(catalogued -> catalogued.descriptor().id())); + } + + private FeatureDraft draft(Catalogued catalogued) { + var owner = ownerOf(catalogued.descriptor()); + drafts.settings(new SchemaSource(catalogued.descriptor(), owner)); + return new FeatureDraft(catalogued, owner); + } + + /** Registration checked that a module owns every catalogued id; module ids are unique and have no '/', so only one can. */ + private DiscoveredModule ownerOf(FeatureDescriptor descriptor) { + return modules.stream() + .filter(module -> module.info().ownsId(descriptor.id())) + .findFirst() + .orElseThrow(() -> new IllegalStateException("No loaded module owns feature id " + descriptor.id())); + } + + private void requireUniqueSnippets() { + var owners = new HashMap(); + for (var draft : sortedDrafts()) { + var snippet = draft.metadata().snippet(); + if (snippet.isEmpty()) continue; + requireSnippetName(snippet, draft); + var previous = owners.putIfAbsent(snippet, draft); + if (previous != null) throw snippetCollision(snippet, previous, draft); + } + } + + private static void requireSnippetName(String snippet, TypeDrafts.TypeDraft draft) { + if (SNIPPET_NAME.matcher(snippet).matches()) return; + throw new IllegalArgumentException("Snippet name '" + snippet + "' of " + draft.type().getName() + " of " + + draft.source() + " is not a folder name; packs write snippets under snippet//, so use lowercase" + + " letters, digits, '-' and '_'"); + } + + private static IllegalArgumentException snippetCollision(String snippet, TypeDrafts.TypeDraft first, TypeDrafts.TypeDraft second) { + return new IllegalArgumentException("Snippet name '" + snippet + "' is used by " + first.type().getName() + " of " + + first.source() + " and by " + second.type().getName() + " of " + second.source() + + "; studio describes snippet/" + snippet + "/ by one class, so give each its own name"); + } + + private List sortedDrafts() { + return drafts.drafts().stream().sorted(Comparator.comparing(draft -> draft.type().getName())).toList(); + } + + private Map completeTypes() { + var byName = new HashMap(); + drafts.drafts().forEach(draft -> byName.put(draft.type().getName(), draft)); + var defaults = new DefaultValues(byName); + var types = new TreeMap(); + byName.forEach((name, draft) -> types.put(name, objectType(draft, defaults))); + return types; + } + + private static ObjectType objectType(TypeDrafts.TypeDraft draft, DefaultValues defaults) { + var metadata = draft.metadata(); + var options = draft.options().stream().map(option -> schemaOption(option, defaults)).toList(); + var snippet = metadata.snippet().isEmpty() ? Optional.empty() : Optional.of(metadata.snippet()); + return new ObjectType(draft.type().getName(), metadata.description(), snippet, options); + } + + private static SchemaOption schemaOption(TypeDrafts.OptionDraft draft, DefaultValues defaults) { + var option = draft.option(); + return new SchemaOption(option.name(), draft.kind(), option.description(), option.required(), + bound(option.minimum()), bound(option.maximum()), defaults.of(draft.defaultValue(), draft.kind())); + } + + private static OptionalDouble bound(Double value) { + return value == null ? OptionalDouble.empty() : OptionalDouble.of(value); + } +} diff --git a/src/main/java/com/volmit/host/SchemaSource.java b/src/main/java/com/volmit/host/SchemaSource.java new file mode 100644 index 000000000..55067ec02 --- /dev/null +++ b/src/main/java/com/volmit/host/SchemaSource.java @@ -0,0 +1,9 @@ +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) { + @Override + public String toString() { + return "settings " + feature.id() + " (module " + module + ")"; + } +} diff --git a/src/main/java/com/volmit/host/SettingsTypeProblem.java b/src/main/java/com/volmit/host/SettingsTypeProblem.java new file mode 100644 index 000000000..5c9a99934 --- /dev/null +++ b/src/main/java/com/volmit/host/SettingsTypeProblem.java @@ -0,0 +1,10 @@ +package com.volmit.host; + +/** Why a settings field's type cannot be described, phrased to follow the field's name, such as + * "uses java.util.UUID, a JDK class, ...". {@link TypeDrafts} adds the field and its settings. + */ +final class SettingsTypeProblem extends RuntimeException { + SettingsTypeProblem(String problem) { + super(problem, null, false, false); + } +} diff --git a/src/main/java/com/volmit/host/TypeDrafts.java b/src/main/java/com/volmit/host/TypeDrafts.java new file mode 100644 index 000000000..b47420f62 --- /dev/null +++ b/src/main/java/com/volmit/host/TypeDrafts.java @@ -0,0 +1,165 @@ +package com.volmit.host; + +import com.volmit.config.OptionsMetadata; +import com.volmit.host.schema.ValueKind; +import com.volmit.host.schema.ValueKind.ObjectKind; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InaccessibleObjectException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.MalformedParameterizedTypeException; +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Describes every class reachable from the settings of a pack, each once. 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. + */ +final class TypeDrafts { + private final Map, TypeDraft> drafts = new LinkedHashMap<>(); + private final Set> describing = new HashSet<>(); + private final Map> names = new HashMap<>(); + + /** One described class: its metadata and its options with their kinds and raw default values. */ + record TypeDraft(Class type, SchemaSource source, OptionsMetadata metadata, List options) {} + + /** {@code defaultValue} is the field's value in a new instance, or null. */ + record OptionDraft(OptionsMetadata.Option option, ValueKind kind, Object defaultValue) {} + + /** Describes a catalogued settings type and everything it reaches. */ + ObjectKind settings(SchemaSource source) { + var type = source.feature().type(); + try { + return object(type, source); + } catch (SettingsTypeProblem problem) { + throw new IllegalArgumentException("Settings type " + type.getName() + " of " + source + " " + + problem.getMessage()); + } + } + + Collection drafts() { + return drafts.values(); + } + + private ObjectKind object(Class type, SchemaSource source) { + claimName(type, source); + if (drafts.containsKey(type) || describing.contains(type)) { + return new ObjectKind(type.getName()); + } + requireDescribable(type); + describing.add(type); + drafts.put(type, draft(type, source)); + describing.remove(type); + return new ObjectKind(type.getName()); + } + + 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)); + var options = metadata.options().stream() + .sorted(Comparator.comparing(OptionsMetadata.Option::name)) + .map(option -> new OptionDraft(option, kind(option, kinds, source), defaultValue(option.field(), instance, source))) + .toList(); + return new TypeDraft(type, source, metadata, options); + } + + private void claimName(Class type, SchemaSource source) { + var previous = names.putIfAbsent(type.getName(), type); + if (previous == null || previous == type) return; + throw new IllegalArgumentException("Two different classes named " + type.getName() + " are used by settings," + + " the second by " + source + "; studio describes classes by name, so rename one"); + } + + private static void requireDescribable(Class type) { + if (type.isPrimitive()) throw unsupported(type, "which settings cannot use; " + ValueKinds.SUPPORTED_TYPES); + if (isJdkClass(type)) throw unsupported(type, "a JDK class settings cannot use; " + ValueKinds.SUPPORTED_TYPES); + if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) { + throw unsupported(type, "which is abstract; settings fields need a concrete class"); + } + if (type.isAnonymousClass() || type.isLocalClass()) { + throw unsupported(type, "which is a local or anonymous class; declare it as a top-level or static nested class"); + } + if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers())) { + throw unsupported(type, "which is an inner class; declare it static"); + } + } + + /** JDK classes live in named modules of the boot layer; module classes, built-in or from packs, do not. */ + private static boolean isJdkClass(Class type) { + var module = type.getModule(); + return module.isNamed() && module.getLayer() == ModuleLayer.boot(); + } + + private static OptionsMetadata inspect(Class type, SchemaSource source) { + try { + return OptionsMetadata.inspect(type); + } catch (IllegalArgumentException | LinkageError failure) { + throw new IllegalArgumentException("Class " + type.getName() + " of " + source + + " cannot be described: " + failure.getMessage(), failure); + } + } + + private static Object instantiate(Class type, SchemaSource source) { + var constructor = noArgumentConstructor(type, source); + try { + constructor.setAccessible(true); + return constructor.newInstance(); + } catch (InvocationTargetException failure) { + throw new IllegalArgumentException("The no-argument constructor of " + type.getName() + " of " + source + + " threw " + failure.getCause() + "; the host creates settings with it, so it must not fail", + failure.getCause()); + } catch (ReflectiveOperationException | RuntimeException | LinkageError failure) { + throw new IllegalArgumentException("Class " + type.getName() + " of " + source + + " cannot be created with its no-argument constructor: " + failure, failure); + } + } + + private static Constructor noArgumentConstructor(Class type, SchemaSource source) { + try { + return type.getDeclaredConstructor(); + } catch (NoSuchMethodException missing) { + throw new IllegalArgumentException("Class " + type.getName() + " of " + source + " has no no-argument" + + " constructor; the host creates settings with it and reads their defaults from it, so declare one," + + " private if nothing else should use it"); + } + } + + private static ValueKind kind(OptionsMetadata.Option option, ValueKinds kinds, SchemaSource source) { + try { + return kinds.of(option); + } catch (SettingsTypeProblem problem) { + throw new IllegalArgumentException("Field " + fieldName(option.field()) + " of " + source + " " + + problem.getMessage()); + } catch (TypeNotPresentException | MalformedParameterizedTypeException | LinkageError failure) { + throw new IllegalArgumentException("Field " + fieldName(option.field()) + " of " + source + + " uses a type that cannot be loaded: " + failure, failure); + } + } + + private static Object defaultValue(Field field, Object instance, SchemaSource source) { + try { + field.setAccessible(true); + return field.get(instance); + } catch (IllegalAccessException | InaccessibleObjectException failure) { + throw new IllegalArgumentException("Field " + fieldName(field) + " of " + source + + " cannot be read for its default: " + failure, failure); + } + } + + private static String fieldName(Field field) { + return field.getDeclaringClass().getName() + "." + field.getName(); + } + + private static SettingsTypeProblem unsupported(Class type, String why) { + return new SettingsTypeProblem("uses " + type.getName() + ", " + why); + } +} diff --git a/src/main/java/com/volmit/host/ValueKinds.java b/src/main/java/com/volmit/host/ValueKinds.java new file mode 100644 index 000000000..9b2c65b82 --- /dev/null +++ b/src/main/java/com/volmit/host/ValueKinds.java @@ -0,0 +1,143 @@ +package com.volmit.host; + +import com.volmit.block.BlockState; +import com.volmit.config.Desc; +import com.volmit.config.OptionsMetadata; +import com.volmit.config.Reference; +import com.volmit.host.schema.TextFormat; +import com.volmit.host.schema.ValueKind; +import com.volmit.host.schema.ValueKind.BooleanKind; +import com.volmit.host.schema.ValueKind.DecimalKind; +import com.volmit.host.schema.ValueKind.EnumConstant; +import com.volmit.host.schema.ValueKind.EnumKind; +import com.volmit.host.schema.ValueKind.IntegerKind; +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.TextKind; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKey; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +/** Maps a settings field's declared type and {@code @Ref} to the JSON it takes. 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 { + static final String SUPPORTED_TYPES = "settings fields can be booleans, numbers, String, ResourceId, BlockState, enums, " + + "lists, sets and arrays of these, Map with String keys and classes with a no-argument constructor"; + private static final Set> BOOLEANS = Set.of(boolean.class, Boolean.class); + private static final Set> INTEGERS = Set.of(byte.class, short.class, int.class, long.class, + Byte.class, Short.class, Integer.class, Long.class); + private static final Set> DECIMALS = Set.of(float.class, double.class, Float.class, Double.class); + private static final String DECLARE_COLLECTION = "declare it as List<...>, Set<...> or Map"; + + private final Function, ObjectKind> objects; + + ValueKinds(Function, ObjectKind> objects) { + this.objects = objects; + } + + ValueKind of(OptionsMetadata.Option option) { + return kind(option.type(), option.reference()); + } + + /** {@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) { + 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); + default -> throw unsupported(type, ", which is not a concrete type; name the type, such as List"); + }; + } + + private ValueKind classKind(Class type, Reference 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); + if (isCollection(type)) throw unsupported(type, " without type arguments; " + DECLARE_COLLECTION); + if (type == ResourceKey.class) throw resourceKey(type); + requireNoReference(type, reference); + if (BOOLEANS.contains(type)) return new BooleanKind(); + if (INTEGERS.contains(type)) return new IntegerKind(); + if (DECIMALS.contains(type)) return new DecimalKind(); + if (type.isEnum()) return enumKind(type); + return objects.apply(type); + } + + private ValueKind genericKind(ParameterizedType generic, Reference reference) { + var raw = (Class) generic.getRawType(); + 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 (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); + if (arguments[0] != String.class) throw unsupported(generic, "; map keys must be String"); + return new MapKind(kind(arguments[1], null)); + } + + private static ValueKind text(TextFormat format, Reference reference) { + if (reference == null) return new TextKind(format); + return new ReferenceKind(reference, format); + } + + private static ValueKind blockState(Reference reference) { + if (reference == null || reference == Reference.BLOCK) return new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE); + throw new SettingsTypeProblem("has @Ref(" + reference + ") on BlockState, which always names a block;" + + " remove the @Ref or use String or ResourceId"); + } + + private static EnumKind enumKind(Class type) { + var constants = Arrays.stream(type.getEnumConstants()) + .map(constant -> ((Enum) constant).name()) + .map(name -> new EnumConstant(name, constantDescription(type, name))) + .toList(); + return new EnumKind(type.getName(), constants); + } + + private static String constantDescription(Class type, String constant) { + try { + var desc = type.getField(constant).getAnnotation(Desc.class); + return desc == null ? "" : desc.value(); + } catch (NoSuchFieldException impossible) { + throw new IllegalStateException("Enum constant without field: " + type.getName() + "." + constant, impossible); + } + } + + 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"); + } + + /** ResourceKey's type argument is the Java class a resource loads as, which tells studio nothing to list. */ + private static SettingsTypeProblem resourceKey(Type type) { + return unsupported(type, ", which names a Java type, not something studio can list; use ResourceId," + + " with @Ref when it names a block, biome or other listed entry"); + } + + private static boolean isCollection(Class type) { + return Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type); + } + + /** {@code why} starts with its own separator, such as ", which ..." or "; ...". */ + private static SettingsTypeProblem unsupported(Type type, String why) { + return new SettingsTypeProblem("uses " + type.getTypeName() + why); + } +} diff --git a/src/main/java/com/volmit/host/schema/FeatureRole.java b/src/main/java/com/volmit/host/schema/FeatureRole.java new file mode 100644 index 000000000..88bed4aa8 --- /dev/null +++ b/src/main/java/com/volmit/host/schema/FeatureRole.java @@ -0,0 +1,9 @@ +package com.volmit.host.schema; + +/** Why a module catalogued a settings type. */ +public enum FeatureRole { + /** Settings that stages read: named in {@code when(...)} or registered with {@code registerSettings}. */ + SETTINGS, + /** Settings of an object generator, registered with {@code registerObject}. */ + OBJECT_GENERATOR +} diff --git a/src/main/java/com/volmit/host/schema/FeatureSchema.java b/src/main/java/com/volmit/host/schema/FeatureSchema.java new file mode 100644 index 000000000..2b7c4c8e9 --- /dev/null +++ b/src/main/java/com/volmit/host/schema/FeatureSchema.java @@ -0,0 +1,37 @@ +package com.volmit.host.schema; + +import com.volmit.FeatureAttachment; +import com.volmit.ModuleInfo; +import com.volmit.resource.ResourceId; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Objects; +import java.util.Set; + +/** A module's settings type and the JSON field it is attached to at each of its targets. + * + * @param id the feature id from {@code @Feature} + * @param name the feature's display name from {@code @Feature} + * @param module the module that owns the feature id + * @param field the JSON field the settings are written under, the same at every target + * @param targets where the field appears, in {@link FeatureAttachment.Target} order + * @param settings the settings class; its description describes the field + */ +public record FeatureSchema( + ResourceId id, + String name, + FeatureRole role, + ModuleInfo module, + String field, + Set targets, + ObjectType settings) { + public FeatureSchema { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(role, "role"); + Objects.requireNonNull(module, "module"); + Objects.requireNonNull(field, "field"); + Objects.requireNonNull(settings, "settings"); + targets = Collections.unmodifiableSet(EnumSet.copyOf(targets)); + } +} diff --git a/src/main/java/com/volmit/host/schema/ObjectType.java b/src/main/java/com/volmit/host/schema/ObjectType.java new file mode 100644 index 000000000..df62ec763 --- /dev/null +++ b/src/main/java/com/volmit/host/schema/ObjectType.java @@ -0,0 +1,22 @@ +package com.volmit.host.schema; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** A settings class, described once per pack however many options use it. + * + * @param name the class's binary name, such as {@code com.example.moss.MossSettings}; unique in a pack + * @param description the class's {@code @Desc}, or empty + * @param snippet the class's {@code @Snippet} name: a pack may then write the object in its own file + * under {@code snippet//} and refer to it by path + * @param options the class's fields, including inherited ones, in name order + */ +public record ObjectType(String name, String description, Optional snippet, List options) { + public ObjectType { + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(description, "description"); + Objects.requireNonNull(snippet, "snippet"); + options = List.copyOf(options); + } +} diff --git a/src/main/java/com/volmit/host/schema/PackSchema.java b/src/main/java/com/volmit/host/schema/PackSchema.java new file mode 100644 index 000000000..82b6b7676 --- /dev/null +++ b/src/main/java/com/volmit/host/schema/PackSchema.java @@ -0,0 +1,54 @@ +package com.volmit.host.schema; + +import com.volmit.FeatureAttachment; +import java.util.Comparator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Objects; + +/** What the modules of a loaded pack add to the pack's JSON, for the host to render as JSON Schema and + * studio completion. It holds module-provided entries only: the host describes its own fields. + * + *

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 field, types by name, snippets by snippet name, options by + * name 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 + */ +public record PackSchema(List features, List types) { + public PackSchema { + features = features.stream().sorted(Comparator.comparing(FeatureSchema::id)).toList(); + types = types.stream().sorted(Comparator.comparing(ObjectType::name)).toList(); + } + + /** The module fields of one attachment target, by JSON field name. */ + public List fields(FeatureAttachment.Target target) { + Objects.requireNonNull(target, "target"); + return features.stream() + .filter(feature -> feature.targets().contains(target)) + .sorted(Comparator.comparing(FeatureSchema::field)) + .toList(); + } + + /** The settings of object generators, by feature id. */ + public List objectGenerators() { + return features.stream().filter(feature -> feature.role() == FeatureRole.OBJECT_GENERATOR).toList(); + } + + /** The type an {@link ValueKind.ObjectKind} names. */ + public ObjectType type(String name) { + return types.stream() + .filter(type -> type.name().equals(name)) + .findFirst() + .orElseThrow(() -> new NoSuchElementException("No settings type: " + name)); + } + + /** The types a pack may write as snippet files, by snippet name; each name belongs to one type. */ + public List snippets() { + return types.stream() + .filter(type -> type.snippet().isPresent()) + .sorted(Comparator.comparing(type -> type.snippet().orElseThrow())) + .toList(); + } +} diff --git a/src/main/java/com/volmit/host/schema/SchemaOption.java b/src/main/java/com/volmit/host/schema/SchemaOption.java new file mode 100644 index 000000000..636c0c424 --- /dev/null +++ b/src/main/java/com/volmit/host/schema/SchemaOption.java @@ -0,0 +1,34 @@ +package com.volmit.host.schema; + +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalDouble; + +/** One option of an {@link ObjectType}: a field of a settings class. + * + *

{@code defaultValue} is the field's value in an instance made by the class's no-argument + * constructor, as plain JSON-shaped Java values: {@code Boolean}, {@code Long} for integer kinds, + * {@code Double} for decimal kinds, {@code String} for text, references and enum constants, + * {@code List} for list kinds (sets sorted) and {@code Map} with sorted keys + * for maps and objects, where an object holds its options that have defaults. It is empty when the + * field is null, when a float or double is not finite, when a list or map holds a value without a + * default and when a set holds objects, lists or maps. An object inside itself, such as a field + * holding {@code this}, is left out of the outer object. + */ +public record SchemaOption( + String name, + ValueKind kind, + String description, + boolean required, + OptionalDouble minimum, + OptionalDouble maximum, + Optional defaultValue) { + public SchemaOption { + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(kind, "kind"); + Objects.requireNonNull(description, "description"); + Objects.requireNonNull(minimum, "minimum"); + Objects.requireNonNull(maximum, "maximum"); + Objects.requireNonNull(defaultValue, "defaultValue"); + } +} diff --git a/src/main/java/com/volmit/host/schema/TextFormat.java b/src/main/java/com/volmit/host/schema/TextFormat.java new file mode 100644 index 000000000..aa42d4a29 --- /dev/null +++ b/src/main/java/com/volmit/host/schema/TextFormat.java @@ -0,0 +1,11 @@ +package com.volmit.host.schema; + +/** How a string option is written. */ +public enum TextFormat { + /** Any string: {@code String} fields. */ + PLAIN, + /** {@code namespace:path}, as {@link com.volmit.resource.ResourceId} parses it. */ + RESOURCE_ID, + /** {@code namespace:path}, optionally followed by {@code [name=value,...]}, as {@link com.volmit.block.BlockState#key()} writes it. */ + BLOCK_STATE +} diff --git a/src/main/java/com/volmit/host/schema/ValueKind.java b/src/main/java/com/volmit/host/schema/ValueKind.java new file mode 100644 index 000000000..a13a805fb --- /dev/null +++ b/src/main/java/com/volmit/host/schema/ValueKind.java @@ -0,0 +1,73 @@ +package com.volmit.host.schema; + +import com.volmit.config.Reference; +import java.util.List; +import java.util.Objects; + +/** The JSON an option takes. Every settings field maps to exactly one kind; a field of any other type + * fails the pack load, so the host never sees an untyped option. + */ +public sealed interface ValueKind { + /** {@code true} or {@code false}: {@code boolean} and {@code Boolean} fields. */ + record BooleanKind() implements ValueKind {} + + /** A whole number: {@code byte}, {@code short}, {@code int} and {@code long} fields and their boxes. */ + record IntegerKind() implements ValueKind {} + + /** Any number: {@code float} and {@code double} fields and their boxes. */ + record DecimalKind() implements ValueKind {} + + /** A string in {@code format} that names nothing in particular. */ + record TextKind(TextFormat format) implements ValueKind { + public TextKind { + Objects.requireNonNull(format, "format"); + } + } + + /** A string in {@code format} that names an entry of {@code reference}, such as a block. */ + record ReferenceKind(Reference reference, TextFormat format) implements ValueKind { + public ReferenceKind { + Objects.requireNonNull(reference, "reference"); + Objects.requireNonNull(format, "format"); + } + } + + /** One of the constant names of the enum class named {@code type}, in declaration order. */ + record EnumKind(String type, List constants) implements ValueKind { + public EnumKind { + Objects.requireNonNull(type, "type"); + constants = List.copyOf(constants); + } + } + + /** A JSON array of {@code element} values: lists, arrays and, with {@code unique}, sets. */ + record ListKind(ValueKind element, boolean unique) implements ValueKind { + public ListKind { + Objects.requireNonNull(element, "element"); + } + } + + /** A JSON object with any string keys and {@code value} values: {@code Map} fields. */ + record MapKind(ValueKind value) implements ValueKind { + public MapKind { + Objects.requireNonNull(value, "value"); + } + } + + /** A JSON object described by the {@link ObjectType} named {@code type} in {@link PackSchema#types()}. + * Types are referenced by name, so a type that contains itself is described once. + */ + record ObjectKind(String type) implements ValueKind { + public ObjectKind { + Objects.requireNonNull(type, "type"); + } + } + + /** An enum constant and its {@code @Desc}, or an empty description. */ + record EnumConstant(String name, String description) { + public EnumConstant { + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(description, "description"); + } + } +} diff --git a/src/test/java/com/volmit/example/chunk/GrassModule.java b/src/test/java/com/volmit/example/chunk/GrassModule.java index 9a5e4ac86..7b20b826c 100644 --- a/src/test/java/com/volmit/example/chunk/GrassModule.java +++ b/src/test/java/com/volmit/example/chunk/GrassModule.java @@ -26,7 +26,7 @@ public final class GrassModule implements IrisModule { } private static void cover(ChunkStageContext context, GrassSettings grass) { - var top = new BlockState(grass.block()); + var top = grass.block(); var heights = context.output(TerrainModule.SURFACE); var blocks = context.hunk(BlockState.class); for (int x = 0; x < blocks.getWidth(); x++) { diff --git a/src/test/java/com/volmit/example/chunk/GrassSettings.java b/src/test/java/com/volmit/example/chunk/GrassSettings.java index cdc448634..b84f542ca 100644 --- a/src/test/java/com/volmit/example/chunk/GrassSettings.java +++ b/src/test/java/com/volmit/example/chunk/GrassSettings.java @@ -2,13 +2,17 @@ package com.volmit.example.chunk; import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; +import com.volmit.block.BlockState; +import com.volmit.config.Desc; import com.volmit.config.Feature; +@Desc("Covers the top of every terrain column") @Feature(id = "example:grass", name = "Grass", field = "grass", targets = FeatureAttachment.Target.BIOME) public final class GrassSettings implements IrisFeature { - private String block = "minecraft:grass_block"; + @Desc("Block placed on top of each column") + private BlockState block = new BlockState("minecraft:grass_block"); - public String block() { + public BlockState block() { return block; } } diff --git a/src/test/java/com/volmit/example/placement/StiltSettings.java b/src/test/java/com/volmit/example/placement/StiltSettings.java index 32cd225c2..2d0202b32 100644 --- a/src/test/java/com/volmit/example/placement/StiltSettings.java +++ b/src/test/java/com/volmit/example/placement/StiltSettings.java @@ -6,6 +6,7 @@ import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.MinNumber; +@Desc("Fills the space below an object down to the ground") @Feature(id = "iris:stilt", name = "Stilt", field = "stilt", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) public final class StiltSettings implements IrisFeature { @Desc("Maximum blocks filled below each lowest object block") diff --git a/src/test/java/com/volmit/host/PackSchemaTest.java b/src/test/java/com/volmit/host/PackSchemaTest.java new file mode 100644 index 000000000..f53b8c53a --- /dev/null +++ b/src/test/java/com/volmit/host/PackSchemaTest.java @@ -0,0 +1,462 @@ +package com.volmit.host; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Reference; +import com.volmit.example.chunk.GrassModule; +import com.volmit.example.chunk.TerrainModule; +import com.volmit.example.placement.PlacementModules; +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.SchemaOption; +import com.volmit.host.schema.TextFormat; +import com.volmit.host.schema.ValueKind.BooleanKind; +import com.volmit.host.schema.ValueKind.DecimalKind; +import com.volmit.host.schema.ValueKind.EnumConstant; +import com.volmit.host.schema.ValueKind.EnumKind; +import com.volmit.host.schema.ValueKind.IntegerKind; +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.TextKind; +import com.volmit.support.TestModuleJar; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.function.Function; +import static com.volmit.support.TestModuleJar.displayName; +import static com.volmit.support.TestModuleJar.module; +import static org.junit.jupiter.api.Assertions.*; + +/** Loads real module jars and checks what the pack tells studio about their settings. */ +class PackSchemaTest { + private static final ModuleHost NO_BUILT_INS = ModuleHost.of(List.of()); + private static final String FLORA = "example:flora"; + private static final String FLORA_SOURCE = "settings example:flora (module example:flora from modules/flora.jar)"; + private static final String NO_STAGES = ""; + + @TempDir + Path packs; + private int brokenPacks; + + private static final String FLORA_MODULE_MEMBERS = """ + public void register(com.volmit.FeatureRegistry registry) { + registry.registerSettings(WindSettings.class); + registry.registerSettings(FloraSettings.class); + registry.registerObject(BushSettings.class, bush -> context -> null); + } + """; + + private static final String FLORA_INSTALL = + "graph.define(Stage.chunk(\"example:flora/plant\")).when(FloraSettings.class).run((context, flora) -> {});"; + + private static final String FLORA_SETTINGS = """ + package pack.flora; + + import com.volmit.FeatureAttachment.Target; + import com.volmit.IrisFeature; + import com.volmit.block.BlockState; + import com.volmit.config.*; + import com.volmit.resource.ResourceId; + import java.util.*; + + @Desc("Plants flowers and bushes") + @Feature(id = "example:flora", name = "Flora", field = "flora", targets = {Target.REGION, Target.BIOME}) + public final class FloraSettings implements IrisFeature { + @Desc("Plants per chunk") @Required @MinNumber(0) @MaxNumber(64) + private int density = 4; + private double chance = 0.25; + private float spread = 0.1f; + private Long seedOffset; + private boolean enabled = true; + private String label = "flora"; + private ResourceId palette = ResourceId.parse("example:flora/default"); + @Ref(Reference.BLOCK) + private String ground = "minecraft:grass_block"; + @Ref(Reference.PACK_BIOME) + private List biomes = List.of("plains", "forest"); + @Ref(Reference.ITEM) + private ResourceId[] drops = {}; + private BlockState flower = new BlockState("minecraft:poppy"); + private Season season = Season.SPRING; + private Set seasons = new HashSet<>(Set.of(Season.SUMMER, Season.AUTUMN)); + private Map weights = Map.of("rose", 2, "daisy", 1); + private Patch patch = new Patch(); + private List extra = List.of(); + private transient int cache; + private static int counter; + } + """; + + private static final String SEASON = """ + package pack.flora; + + import com.volmit.config.Desc; + + public enum Season { + @Desc("Early in the year") SPRING, + SUMMER, + AUTUMN + } + """; + + private static final String PATCH = """ + package pack.flora; + + import com.volmit.config.*; + + @Desc("A patch of plants") + @Snippet("flora-patch") + final class Patch { + @MinNumber(1) + private int radius = 3; + private Season bloom = Season.SUMMER; + @Desc("A smaller patch inside this one") + private Patch child; + } + """; + + private static final String WIND_SETTINGS = """ + package pack.flora; + + import com.volmit.FeatureAttachment.Target; + import com.volmit.IrisFeature; + import com.volmit.config.*; + + @Feature(id = "example:flora/wind", name = "Wind", field = "wind", targets = Target.DIMENSION) + public final class WindSettings implements IrisFeature { + @Desc("How far plants sway") + private double strength = 1.5; + } + """; + + private static final String BUSH_SETTINGS = """ + package pack.flora; + + import com.volmit.FeatureAttachment.Target; + import com.volmit.IrisFeature; + import com.volmit.config.*; + + @Snippet("bush") + @Feature(id = "example:flora/bush", name = "Bush", field = "bush", targets = Target.OBJECT_PLACEMENT) + public final class BushSettings implements IrisFeature { + private int height = 2; + } + """; + + private static TestModuleJar flora() { + return module("pack.flora.FloraModule", FLORA, FLORA_MODULE_MEMBERS, FLORA_INSTALL) + .source("pack.flora.FloraSettings", FLORA_SETTINGS) + .source("pack.flora.Season", SEASON) + .source("pack.flora.Patch", PATCH) + .source("pack.flora.WindSettings", WIND_SETTINGS) + .source("pack.flora.BushSettings", BUSH_SETTINGS); + } + + private Path pack(String name) { + try { + return Files.createDirectories(packs.resolve(name)); + } catch (java.io.IOException exception) { + throw new java.io.UncheckedIOException(exception); + } + } + + private static PackSchema schemaOf(Path pack, ModuleHost host) { + try (var loaded = LoadedPack.load(pack, host)) { + return loaded.schema(); + } + } + + private PackSchema floraSchema() { + var pack = pack("flora"); + flora().writeInto(pack, "flora.jar"); + return schemaOf(pack, NO_BUILT_INS); + } + + private static SchemaOption option(ObjectType type, String name) { + return type.options().stream().filter(option -> option.name().equals(name)).findFirst().orElseThrow(); + } + + private static List names(List features, Function name) { + return features.stream().map(name).map(Object::toString).toList(); + } + + @Test + void attachesEveryModuleFieldToItsTargets() { + var schema = floraSchema(); + + assertEquals(List.of("flora"), names(schema.fields(Target.BIOME), FeatureSchema::field)); + assertEquals(List.of("flora"), names(schema.fields(Target.REGION), FeatureSchema::field)); + assertEquals(List.of("wind"), names(schema.fields(Target.DIMENSION), FeatureSchema::field)); + assertEquals(List.of("bush"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::field)); + assertEquals(List.of("example:flora", "example:flora/bush", "example:flora/wind"), names(schema.features(), FeatureSchema::id)); + + var flora = schema.features().getFirst(); + assertEquals("Flora", flora.name()); + assertEquals(FeatureRole.SETTINGS, flora.role()); + assertEquals(FLORA, flora.module().id().toString()); + assertEquals(displayName(FLORA), flora.module().name()); + assertEquals(List.of(Target.REGION, Target.BIOME), List.copyOf(flora.targets())); + assertEquals("pack.flora.FloraSettings", flora.settings().name()); + assertEquals("Plants flowers and bushes", flora.settings().description()); + assertEquals(Optional.empty(), flora.settings().snippet()); + } + + @Test + void describesOptionsInNameOrderWithChecksAndDefaults() { + var settings = floraSchema().type("pack.flora.FloraSettings"); + + assertEquals(List.of("biomes", "chance", "density", "drops", "enabled", "extra", "flower", "ground", "label", + "palette", "patch", "season", "seasons", "seedOffset", "spread", "weights"), + settings.options().stream().map(SchemaOption::name).toList()); + assertEquals(new SchemaOption("density", new IntegerKind(), "Plants per chunk", true, + OptionalDouble.of(0), OptionalDouble.of(64), Optional.of(4L)), option(settings, "density")); + assertEquals(new SchemaOption("chance", new DecimalKind(), "", false, + OptionalDouble.empty(), OptionalDouble.empty(), Optional.of(0.25)), option(settings, "chance")); + assertEquals(Optional.of(0.1), option(settings, "spread").defaultValue(), "floats keep their own decimal form"); + assertEquals(new IntegerKind(), option(settings, "seedOffset").kind()); + assertEquals(Optional.empty(), option(settings, "seedOffset").defaultValue(), "a null field has no default"); + assertEquals(new BooleanKind(), option(settings, "enabled").kind()); + assertEquals(Optional.of(true), option(settings, "enabled").defaultValue()); + assertEquals(new TextKind(TextFormat.PLAIN), option(settings, "label").kind()); + assertEquals(new TextKind(TextFormat.RESOURCE_ID), option(settings, "palette").kind()); + assertEquals(Optional.of("example:flora/default"), option(settings, "palette").defaultValue()); + } + + @Test + void describesEnumsCollectionsAndMaps() { + var settings = floraSchema().type("pack.flora.FloraSettings"); + + var season = new EnumKind("pack.flora.Season", List.of(new EnumConstant("SPRING", "Early in the year"), + new EnumConstant("SUMMER", ""), new EnumConstant("AUTUMN", ""))); + assertEquals(season, option(settings, "season").kind()); + assertEquals(Optional.of("SPRING"), option(settings, "season").defaultValue()); + assertEquals(new ListKind(season, true), option(settings, "seasons").kind()); + assertEquals(Optional.of(List.of("AUTUMN", "SUMMER")), option(settings, "seasons").defaultValue(), "sets are sorted"); + assertEquals(new MapKind(new IntegerKind()), option(settings, "weights").kind()); + assertEquals(Optional.of(Map.of("daisy", 1L, "rose", 2L)), option(settings, "weights").defaultValue()); + assertEquals(List.of("daisy", "rose"), List.copyOf(((Map) option(settings, "weights").defaultValue().orElseThrow()).keySet())); + assertEquals(new ListKind(new ObjectKind("pack.flora.Patch"), false), option(settings, "extra").kind()); + assertEquals(Optional.of(List.of()), option(settings, "extra").defaultValue()); + } + + @Test + void describesReferencesOnTextCollectionsArraysAndBlockStates() { + var settings = floraSchema().type("pack.flora.FloraSettings"); + + assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.PLAIN), option(settings, "ground").kind()); + assertEquals(new ListKind(new ReferenceKind(Reference.PACK_BIOME, TextFormat.PLAIN), false), option(settings, "biomes").kind()); + assertEquals(Optional.of(List.of("plains", "forest")), option(settings, "biomes").defaultValue()); + assertEquals(new ListKind(new ReferenceKind(Reference.ITEM, TextFormat.RESOURCE_ID), false), option(settings, "drops").kind()); + assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE), option(settings, "flower").kind(), + "BlockState names a block without @Ref"); + assertEquals(Optional.of("minecraft:poppy"), option(settings, "flower").defaultValue()); + } + + @Test + void describesNestedTypesOnceAndEndsCyclesAtTheTypesName() { + var schema = floraSchema(); + var settings = schema.type("pack.flora.FloraSettings"); + var patch = schema.type("pack.flora.Patch"); + + assertEquals(List.of("pack.flora.BushSettings", "pack.flora.FloraSettings", "pack.flora.Patch", "pack.flora.WindSettings"), + schema.types().stream().map(ObjectType::name).toList()); + assertEquals(new ObjectKind("pack.flora.Patch"), option(settings, "patch").kind()); + assertEquals(Optional.of(Map.of("bloom", "SUMMER", "radius", 3L)), option(settings, "patch").defaultValue(), + "an object default holds the options that have one"); + assertEquals("A patch of plants", patch.description()); + assertEquals(List.of("bloom", "child", "radius"), patch.options().stream().map(SchemaOption::name).toList()); + assertEquals(new ObjectKind("pack.flora.Patch"), option(patch, "child").kind()); + assertEquals("A smaller patch inside this one", option(patch, "child").description()); + assertEquals(OptionalDouble.of(1), option(patch, "radius").minimum()); + } + + @Test + void listsSnippetsObjectGeneratorsAndExplicitlyRegisteredSettings() { + var schema = floraSchema(); + + assertEquals(List.of("bush", "flora-patch"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList()); + assertEquals(List.of("pack.flora.BushSettings", "pack.flora.Patch"), schema.snippets().stream().map(ObjectType::name).toList()); + + var bush = schema.objectGenerators().getFirst(); + assertEquals(1, schema.objectGenerators().size()); + assertEquals(FeatureRole.OBJECT_GENERATOR, bush.role()); + assertEquals(Optional.of(2L), option(bush.settings(), "height").defaultValue()); + + var wind = schema.fields(Target.DIMENSION).getFirst(); + assertEquals(FeatureRole.SETTINGS, wind.role()); + assertEquals("example:flora/wind", wind.id().toString()); + assertEquals(new SchemaOption("strength", new DecimalKind(), "How far plants sway", false, + OptionalDouble.empty(), OptionalDouble.empty(), Optional.of(1.5)), option(wind.settings(), "strength")); + } + + @Test + void sameModulesGiveTheSameDescriptionWhateverTheJarOrder() { + var other = module("pack.other.OtherModule", "example:other", NO_STAGES, NO_STAGES); + var first = pack("first"); + flora().writeInto(first, "a.jar"); + other.writeInto(first, "b.jar"); + var second = pack("second"); + other.writeInto(second, "a.jar"); + flora().writeInto(second, "b.jar"); + + var schema = schemaOf(first, NO_BUILT_INS); + + assertEquals(schema, schemaOf(first, NO_BUILT_INS)); + assertEquals(schema, schemaOf(second, NO_BUILT_INS)); + } + + @Test + void describesBuiltInModulesWithThePack() { + var builtIns = new ArrayList<>(PlacementModules.all()); + builtIns.add(new TerrainModule()); + builtIns.add(new GrassModule()); + var schema = schemaOf(pack("empty"), ModuleHost.of(builtIns)); + + assertEquals(List.of("example:grass", "example:moss", "iris:snow", "iris:stilt"), names(schema.features(), FeatureSchema::id)); + assertEquals(List.of("moss", "snow", "stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::field)); + + var stilt = schema.fields(Target.OBJECT_PLACEMENT).get(2); + assertEquals("Stilts", stilt.module().name()); + assertEquals(new ObjectType("com.volmit.example.placement.StiltSettings", "Fills the space below an object down to the ground", + Optional.empty(), List.of(new SchemaOption("maxDepth", new IntegerKind(), "Maximum blocks filled below each lowest object block", + false, OptionalDouble.of(1), OptionalDouble.empty(), Optional.of(16L)))), stilt.settings()); + + var grass = schema.fields(Target.BIOME).getFirst(); + assertEquals(new SchemaOption("block", new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE), "Block placed on top of each column", + false, OptionalDouble.empty(), OptionalDouble.empty(), Optional.of("minecraft:grass_block")), grass.settings().options().getFirst()); + } + + /** A pack whose module example:flora registers pack.flora.FloraSettings with {@code body} as its class body. */ + private IllegalArgumentException loadFailure(String body, String... otherSources) { + var jar = module("pack.flora.FloraModule", FLORA, + "public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) + .source("pack.flora.FloraSettings", """ + package pack.flora; + + import com.volmit.FeatureAttachment.Target; + import com.volmit.IrisFeature; + import com.volmit.block.BlockState; + import com.volmit.config.*; + import com.volmit.resource.*; + import java.util.*; + + @Feature(id = "example:flora", name = "Flora", field = "flora", targets = Target.BIOME) + public final class FloraSettings implements IrisFeature { + %s + } + """.formatted(body)); + for (int index = 0; index < otherSources.length; index += 2) { + jar.source(otherSources[index], otherSources[index + 1]); + } + var pack = pack("broken-" + ++brokenPacks); + jar.writeInto(pack, "flora.jar"); + return assertThrows(IllegalArgumentException.class, () -> LoadedPack.load(pack, NO_BUILT_INS)); + } + + private void assertLoadFails(String expected, String body, String... otherSources) { + assertEquals(expected, loadFailure(body, otherSources).getMessage()); + } + + @Test + void defaultsLeaveOutWhatJsonCannotHold() { + var pack = pack("defaults"); + module("pack.flora.FloraModule", FLORA, + "public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) + .source("pack.flora.FloraSettings", """ + package pack.flora; + + import com.volmit.FeatureAttachment.Target; + import com.volmit.IrisFeature; + import com.volmit.config.Feature; + import java.util.*; + + @Feature(id = "example:flora", name = "Flora", field = "flora", targets = Target.BIOME) + public final class FloraSettings implements IrisFeature { + private Node node = new Node(); + private double ratio = Double.NaN; + private List names = Arrays.asList("a", null); + private Set nodes = Set.of(new Node()); + } + """) + .source("pack.flora.Node", "package pack.flora; final class Node { private Node self = this; private int size = 1; }") + .writeInto(pack, "flora.jar"); + var settings = schemaOf(pack, NO_BUILT_INS).type("pack.flora.FloraSettings"); + + assertEquals(Optional.of(Map.of("size", 1L)), option(settings, "node").defaultValue(), "a reference back to itself is left out"); + assertEquals(Optional.empty(), option(settings, "ratio").defaultValue()); + assertEquals(Optional.empty(), option(settings, "names").defaultValue()); + assertEquals(Optional.empty(), option(settings, "nodes").defaultValue(), "a set of objects has no order to write"); + } + + @Test + void unsupportedFieldTypesFailTheLoadNamingClassFieldAndModule() { + assertLoadFails("Field pack.flora.FloraSettings.id of " + FLORA_SOURCE + " uses java.util.UUID, a JDK class settings cannot use; " + + ValueKinds.SUPPORTED_TYPES, "private UUID id;"); + assertLoadFails("Field pack.flora.FloraSettings.name of " + FLORA_SOURCE + " uses java.util.Optional;" + + " only List, Set and Map may have type arguments", "private Optional name;"); + assertLoadFails("Field pack.flora.FloraSettings.names of " + FLORA_SOURCE + " uses java.util.List without type arguments;" + + " declare it as List<...>, Set<...> or Map", "@SuppressWarnings(\"rawtypes\") private List names;"); + assertLoadFails("Field pack.flora.FloraSettings.names of " + FLORA_SOURCE + " uses java.util.ArrayList;" + + " declare it as List<...>, Set<...> or Map", "private ArrayList names;"); + assertLoadFails("Field pack.flora.FloraSettings.weights of " + FLORA_SOURCE + " uses java.util.Map;" + + " map keys must be String", "private Map weights;"); + assertLoadFails("Field pack.flora.FloraSettings.letter of " + FLORA_SOURCE + " uses char, which settings cannot use; " + + ValueKinds.SUPPORTED_TYPES, "private char letter;"); + assertLoadFails("Field pack.flora.FloraSettings.palette of " + FLORA_SOURCE + " uses com.volmit.resource.ResourceKey, which names" + + " a Java type, not something studio can list; use ResourceId, with @Ref when it names a block, biome or other listed entry", + "private ResourceKey palette;"); + assertLoadFails("Field pack.flora.FloraSettings.names of " + FLORA_SOURCE + " uses ? extends java.lang.String, which is not a" + + " concrete type; name the type, such as List", "private List names;"); + } + + @Test + void nestedClassesMustBeConcreteStaticAndConstructible() { + assertLoadFails("Field pack.flora.FloraSettings.shape of " + FLORA_SOURCE + " uses pack.flora.Shape, which is abstract;" + + " settings fields need a concrete class", "private Shape shape;", "pack.flora.Shape", "package pack.flora; interface Shape {}"); + assertLoadFails("Field pack.flora.FloraSettings.inner of " + FLORA_SOURCE + " uses pack.flora.FloraSettings$Inner, which is an" + + " inner class; declare it static", "private Inner inner; class Inner {}"); + assertLoadFails("Class pack.flora.Shape of " + FLORA_SOURCE + " has no no-argument constructor; the host creates settings with it" + + " and reads their defaults from it, so declare one, private if nothing else should use it", + "private Shape shape;", "pack.flora.Shape", "package pack.flora; record Shape(int size) {}"); + + var throwing = loadFailure("private Shape shape;", "pack.flora.Shape", + "package pack.flora; final class Shape { Shape() { throw new IllegalStateException(\"no shapes today\"); } }"); + assertEquals("The no-argument constructor of pack.flora.Shape of " + FLORA_SOURCE + " threw java.lang.IllegalStateException:" + + " no shapes today; the host creates settings with it, so it must not fail", throwing.getMessage()); + assertEquals("no shapes today", throwing.getCause().getMessage()); + } + + @Test + void referencesOnIncompatibleFieldsFailTheLoad() { + assertLoadFails("Field pack.flora.FloraSettings.count of " + FLORA_SOURCE + " has @Ref(BLOCK) on int, but @Ref fits only String" + + " and ResourceId and lists, sets and arrays of them", "@Ref(Reference.BLOCK) private int count;"); + assertLoadFails("Field pack.flora.FloraSettings.flower of " + FLORA_SOURCE + " has @Ref(BIOME) on BlockState, which always names" + + " a block; remove the @Ref or use String or ResourceId", "@Ref(Reference.BIOME) private BlockState flower;"); + assertLoadFails("Field pack.flora.FloraSettings.blocks of " + FLORA_SOURCE + " has @Ref(BLOCK) on java.util.Map, but @Ref fits only String and ResourceId and lists, sets and arrays of them", + "@Ref(Reference.BLOCK) private Map blocks;"); + assertTrue(loadFailure("@Ref(Reference.ENTITY) private List counts;").getMessage() + .contains("has @Ref(ENTITY) on java.lang.Integer")); + } + + @Test + void snippetNamesAreFolderNamesThatBelongToOneClass() { + assertLoadFails("Snippet name 'Big Patch' of pack.flora.Patch of " + FLORA_SOURCE + " is not a folder name; packs write snippets under" + + " snippet//, so use lowercase letters, digits, '-' and '_'", + "private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"Big Patch\") final class Patch {}"); + assertLoadFails("Snippet name 'patch' is used by pack.flora.Patch of " + FLORA_SOURCE + " and by pack.flora.Plot of " + FLORA_SOURCE + + "; studio describes snippet/patch/ by one class, so give each its own name", + "private Patch patch; private Plot plot;", + "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"patch\") final class Patch {}", + "pack.flora.Plot", "package pack.flora; @com.volmit.config.Snippet(\"patch\") final class Plot {}"); + } +}