mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 08:44:50 +00:00
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.
This commit is contained in:
1 parent
93c755ffe4
commit
3465f8d390
19 files changed
+1302
-6
No files matched your search
@@ -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<String, TypeDrafts.TypeDraft> types;
|
||||
private final Set<Object> converting = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
|
||||
DefaultValues(Map<String, TypeDrafts.TypeDraft> types) {
|
||||
this.types = types;
|
||||
}
|
||||
|
||||
Optional<Object> 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<Object> 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<Object> list(List<?> elements, ListKind kind) {
|
||||
var converted = new ArrayList<Object>();
|
||||
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<Object> sortedSet(List<Object> 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<Object> map(Map<?, ?> entries, ValueKind valueKind) {
|
||||
var converted = new TreeMap<String, Object>();
|
||||
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(Object value, TypeDrafts.TypeDraft type) {
|
||||
if (!converting.add(value)) return Optional.empty();
|
||||
var converted = new TreeMap<String, Object>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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<DiscoveredModule> modules;
|
||||
private final TypeDrafts drafts = new TypeDrafts();
|
||||
|
||||
private PackSchemaBuilder(List<DiscoveredModule> modules) {
|
||||
this.modules = modules;
|
||||
}
|
||||
|
||||
static PackSchema describe(FeatureCatalog catalog, List<DiscoveredModule> 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<String, ObjectType> 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> 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<String, TypeDrafts.TypeDraft>();
|
||||
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/<name>/, 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<TypeDrafts.TypeDraft> sortedDrafts() {
|
||||
return drafts.drafts().stream().sorted(Comparator.comparing(draft -> draft.type().getName())).toList();
|
||||
}
|
||||
|
||||
private Map<String, ObjectType> completeTypes() {
|
||||
var byName = new HashMap<String, TypeDrafts.TypeDraft>();
|
||||
drafts.drafts().forEach(draft -> byName.put(draft.type().getName(), draft));
|
||||
var defaults = new DefaultValues(byName);
|
||||
var types = new TreeMap<String, ObjectType>();
|
||||
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.<String>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);
|
||||
}
|
||||
}
|
||||
@@ -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 + ")";
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<Class<?>, TypeDraft> drafts = new LinkedHashMap<>();
|
||||
private final Set<Class<?>> describing = new HashSet<>();
|
||||
private final Map<String, Class<?>> 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<OptionDraft> 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<TypeDraft> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Class<?>> BOOLEANS = Set.of(boolean.class, Boolean.class);
|
||||
private static final Set<Class<?>> INTEGERS = Set.of(byte.class, short.class, int.class, long.class,
|
||||
Byte.class, Short.class, Integer.class, Long.class);
|
||||
private static final Set<Class<?>> DECIMALS = Set.of(float.class, double.class, Float.class, Double.class);
|
||||
private static final String DECLARE_COLLECTION = "declare it as List<...>, Set<...> or Map<String, ...>";
|
||||
|
||||
private final Function<Class<?>, ObjectKind> objects;
|
||||
|
||||
ValueKinds(Function<Class<?>, 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<String>");
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<FeatureAttachment.Target> 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));
|
||||
}
|
||||
}
|
||||
@@ -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/<name>/} 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<String> snippet, List<SchemaOption> options) {
|
||||
public ObjectType {
|
||||
Objects.requireNonNull(name, "name");
|
||||
Objects.requireNonNull(description, "description");
|
||||
Objects.requireNonNull(snippet, "snippet");
|
||||
options = List.copyOf(options);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <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 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<FeatureSchema> features, List<ObjectType> 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<FeatureSchema> 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<FeatureSchema> 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<ObjectType> snippets() {
|
||||
return types.stream()
|
||||
.filter(type -> type.snippet().isPresent())
|
||||
.sorted(Comparator.comparing(type -> type.snippet().orElseThrow()))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>{@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<Object>} for list kinds (sets sorted) and {@code Map<String, Object>} 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<Object> 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");
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<EnumConstant> 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<String, V>} 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user