Delete the composite constructor heuristic from the inspector

Operator ruling: the heuristic that rebuilt unkeyed structs through a
guessed constructor is removed, not guarded. Gone: the Composite value
kind, CultInspectorShape.Composer, CultInspectorModel.Compose and
Composite, the composite-component flag on CultInspectorMember, the IMGUI
composite rebuild path, and the README text about it.

An unkeyed struct is now edited in place through its public fields. A
struct holding state it cannot write in place (a public readonly field or
a get-only auto-property) is Unsupported with a reason naming the member,
until a drawer claims it. Computed get-only properties are not state and
do not lock a struct.

The composite-rejection test goes with the heuristic; the replacement
test pins both lock rules and fails with either removed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-14 14:05:30 +02:00
commit d03e376411
4 changed files with 53 additions and 117 deletions

View file

@ -19,8 +19,6 @@ namespace GameCult.Caching
Float,
Bool,
Enum,
// An unkeyed value type rebuilt through its constructor (CultMath vectors, rect, Color32).
Composite,
RecordRef,
List,
Dictionary,
@ -62,14 +60,14 @@ namespace GameCult.Caching
public sealed class CultInspectorMember
{
internal CultInspectorMember(MemberInfo member, Type valueType, int slot, bool assignable, bool component, CultInspectorMetadata metadata)
internal CultInspectorMember(MemberInfo member, Type valueType, int slot, bool assignable, CultInspectorMetadata metadata)
{
Member = member;
ValueType = valueType;
Slot = slot;
IsAssignable = assignable;
Metadata = metadata;
IsReadOnly = metadata.ReadOnly || !assignable && !component;
IsReadOnly = metadata.ReadOnly || !assignable;
}
public MemberInfo Member { get; }
@ -79,10 +77,10 @@ namespace GameCult.Caching
public CultInspectorMetadata Metadata { get; }
// SetValue works: MessagePack's own rule, the one the registry persists by (a public setter or non-readonly field, or
// any setter or readonly field under AllowPrivate). A composite component is never assignable; its owner is composed.
// any setter or readonly field under AllowPrivate).
public bool IsAssignable { get; }
// The lowering offers no edit: declared [CultInspectorReadOnly], or a member that can be neither assigned nor composed.
// The lowering offers no edit: declared [CultInspectorReadOnly], or not assignable.
public bool IsReadOnly { get; }
public object? GetValue(object target) =>
@ -121,14 +119,13 @@ namespace GameCult.Caching
// Union: the declared [Union] subtypes in key order, and nothing else.
public IReadOnlyList<Type> UnionChoices { get; internal set; } = Array.Empty<Type>();
// Nested: the members in inspection order. Composite: the components in constructor order.
// Nested: the members in inspection order.
public IReadOnlyList<CultInspectorMember> Members { get; internal set; } = Array.Empty<CultInspectorMember>();
// Unsupported: why.
public string? Reason { get; internal set; }
internal Type? BuildType { get; set; }
internal ConstructorInfo? Composer { get; set; }
}
public readonly struct CultInspectorClaim
@ -365,13 +362,6 @@ namespace GameCult.Caching
return Activator.CreateInstance(subtype)!;
}
public object Compose(CultInspectorShape composite, IReadOnlyList<object?> components)
{
if (composite?.Composer == null)
throw new ArgumentException("Only a composite shape is composed.", nameof(composite));
return composite.Composer.Invoke(components.ToArray());
}
// A new collection holding items; the value it replaces is never mutated.
public object BuildList(Type listType, IReadOnlyList<object?> items)
{
@ -522,14 +512,18 @@ namespace GameCult.Caching
var keyed = KeyedMembers(type);
if (keyed.Length > 0)
return new CultInspectorShape(type, CultInspectorValueKind.Nested) { Members = keyed };
// An unkeyed struct is edited in place through its public fields. State it cannot write in place (a readonly field,
// a get-only auto-property) makes it unsupported until a drawer claims it.
if (type.IsValueType)
{
var composite = Composite(type);
if (composite != null)
return composite;
var fields = type.GetFields(Public).Where(field => !field.IsLiteral)
var locked = type.GetFields(Public).FirstOrDefault(field => field.IsInitOnly)?.Name
?? type.GetProperties(Public).FirstOrDefault(property => property.GetSetMethod() == null &&
type.GetField($"<{property.Name}>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance) != null)?.Name;
if (locked != null)
return Unsupported(type, $"{type.Name}.{locked} is readonly or get-only, so {type.Name} cannot be edited in place; it needs a drawer.");
var fields = type.GetFields(Public)
.OrderBy(field => field.MetadataToken)
.Select((field, slot) => new CultInspectorMember(field, field.FieldType, slot, !field.IsInitOnly, false, MetadataOf(field)))
.Select((field, slot) => new CultInspectorMember(field, field.FieldType, slot, true, MetadataOf(field)))
.ToArray();
if (fields.Length > 0)
return new CultInspectorShape(type, CultInspectorValueKind.Nested) { Members = fields };
@ -564,42 +558,12 @@ namespace GameCult.Caching
}
return slotted
.Select(entry => new CultInspectorMember(entry.Member, TypeOf(entry.Member), entry.Slot, Assignable(entry.Member, allowPrivate), false, MetadataOf(entry.Member)))
.Select(entry => new CultInspectorMember(entry.Member, TypeOf(entry.Member), entry.Slot, Assignable(entry.Member, allowPrivate), MetadataOf(entry.Member)))
.OrderBy(member => member.Metadata.Order ?? member.Slot)
.ThenBy(member => member.Slot)
.ToArray();
}
// The longest public constructor whose every parameter takes a readable member of the same name and type. Public
// fields it does not take are state a rebuild would drop, so such a type is not composite.
private CultInspectorShape? Composite(Type type)
{
var readable = type.GetFields(Public).Where(field => !field.IsLiteral).Cast<MemberInfo>()
.Concat(type.GetProperties(Public).Where(property => property.GetGetMethod() != null && property.GetIndexParameters().Length == 0))
.ToArray();
foreach (var constructor in type.GetConstructors().OrderByDescending(constructor => constructor.GetParameters().Length))
{
var parameters = constructor.GetParameters();
if (parameters.Length == 0)
break;
var components = parameters
.Select(parameter => readable.FirstOrDefault(member =>
string.Equals(member.Name, parameter.Name, StringComparison.OrdinalIgnoreCase) && TypeOf(member) == parameter.ParameterType))
.ToArray();
if (components.Any(component => component == null) || components.Distinct().Count() != components.Length)
continue;
if (readable.OfType<FieldInfo>().Any(field => !components.Contains(field)))
continue;
return new CultInspectorShape(type, CultInspectorValueKind.Composite)
{
Members = components.Select((component, slot) => new CultInspectorMember(component!, TypeOf(component!), slot, false, true, MetadataOf(component))).ToArray(),
Composer = constructor
};
}
return null;
}
private static CultInspectorShape Unsupported(Type type, string reason) =>
new CultInspectorShape(type, CultInspectorValueKind.Unsupported) { Reason = reason };

View file

@ -84,8 +84,6 @@ namespace GameCult.Unity.Caching.Editor
case CultInspectorValueKind.Enum:
var current = value as Enum ?? (Enum)Enum.ToObject(type, 0);
return type.IsDefined(typeof(FlagsAttribute), false) ? EditorGUILayout.EnumFlagsField(label, current) : EditorGUILayout.EnumPopup(label, current);
case CultInspectorValueKind.Composite:
return DrawComposite(label, shape, value);
case CultInspectorValueKind.RecordRef:
return DrawRecordRef(label, type, value);
case CultInspectorValueKind.List:
@ -189,55 +187,6 @@ namespace GameCult.Unity.Caching.Editor
}
}
// Scalar components draw on one row; anything else folds out. A change composes a new value.
private object DrawComposite(string label, CultInspectorShape shape, object value)
{
var path = _path;
value = value ?? Model.CreateDefault(shape.Type);
var components = shape.Members;
var values = components.Select(component => component.GetValue(value)).ToArray();
var changed = false;
if (components.All(component => Model.ShapeOf(component.ValueType).Kind is CultInspectorValueKind.Float or CultInspectorValueKind.Integer or CultInspectorValueKind.Bool))
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel(label);
var indent = EditorGUI.indentLevel;
var labelWidth = EditorGUIUtility.labelWidth;
EditorGUI.indentLevel = 0;
EditorGUIUtility.labelWidth = 8 + 7 * components.Max(component => component.Name.Length);
for (var i = 0; i < components.Count; i++)
{
EditorGUI.BeginChangeCheck();
var next = DrawDefault(components[i].Name, components[i].ValueType, values[i], null);
if (!EditorGUI.EndChangeCheck()) continue;
values[i] = next;
changed = true;
}
EditorGUIUtility.labelWidth = labelWidth;
EditorGUI.indentLevel = indent;
}
}
else
{
if (!Foldout(path, label)) return value;
EditorGUI.indentLevel++;
for (var i = 0; i < components.Count; i++)
{
EditorGUI.BeginChangeCheck();
var next = DrawValue(LabelOf(components[i]), components[i].ValueType, values[i], components[i].Member, path + "." + components[i].Name);
if (!EditorGUI.EndChangeCheck()) continue;
values[i] = next;
changed = true;
}
EditorGUI.indentLevel--;
}
return changed ? Model.Compose(shape, values) : value;
}
private object DrawRecordRef(string label, Type type, object value)
{
var key = CultInspectorModel.RecordKey(value);

View file

@ -42,10 +42,10 @@ reloading scripts drops unsaved edits.
in `GameCult.Caching`. Given a registry and the store's document codec it gives
the member list of a type (registry catalog slots, `CultInspector*` metadata,
whether a member is assignable), the shape of any value (string, integer,
float, bool, enum, composite value rebuilt through its constructor,
`CultRecordRef<T>` with its candidate records, rank-1 list or array,
dictionary, `[Union]` with only its declared subtypes, nested keyed object, or
unsupported with a reason), drawer claim resolution
float, bool, enum, `CultRecordRef<T>` with its candidate records, rank-1 list
or array, dictionary, `[Union]` with only its declared subtypes, nested keyed
object, struct edited in place through its public fields, or unsupported with
a reason), drawer claim resolution
(`CultInspectorDrawerClaims`), dictionary key identity and refusal (null keys,
empty record references and duplicates), and edits that work on a copy
(`CultInspectorEdit`): a refused upsert leaves the cached object unchanged. The
@ -55,11 +55,12 @@ the same documents under the same rules.
## Drawers
Built in: every model shape above. Composite values of scalars (`float2/3/4`,
`int2`, `double2/3`, `bool2`, `quaternion`, `Color32`) draw as one row;
`rect` folds out to its corners. Unity object references draw as object
fields. A value no drawer claims and no shape covers shows a red error row, as
does a multi-dimensional array.
Built in: every model shape above. A struct without `[Key]` members folds out
to its public fields and is edited in place; a struct with a readonly field or
a get-only auto-property is unsupported until a drawer claims it. Unity object
references draw as object fields. A value no drawer claims and no shape covers
shows a red error row with the model's reason, as does a multi-dimensional
array.
A project adds or overrides a drawer with an editor class. `Claimed` is either
a value type (an open generic definition claims every closed form) or an

View file

@ -195,7 +195,7 @@ namespace GameCult.Caching.Tests
}
[Test]
public void ShapesClassifyCollectionsCompositesAndMultiDimensionalArrays()
public void ShapesClassifyCollectionsStructsAndMultiDimensionalArrays()
{
var model = Model();
@ -204,10 +204,15 @@ namespace GameCult.Caching.Tests
Assert.That(model.ShapeOf(typeof(List<int>)).ElementType, Is.EqualTo(typeof(int)));
Assert.That(model.BuildList(typeof(float[]), new object?[] { 1f, 2f }), Is.EqualTo(new[] { 1f, 2f }));
var pair = model.ShapeOf(typeof(InspectPair));
Assert.That(pair.Kind, Is.EqualTo(CultInspectorValueKind.Composite));
Assert.That(pair.Members.Select(member => member.Name), Is.EqualTo(new[] { "x", "y" }));
Assert.That(model.Compose(pair, new object?[] { 1f, 2f }), Is.EqualTo(new InspectPair(1f, 2f)));
var open = model.ShapeOf(typeof(InspectOpenStruct));
Assert.That(open.Kind, Is.EqualTo(CultInspectorValueKind.Nested));
Assert.That(open.Members.Select(member => member.Name), Is.EqualTo(new[] { "x", "y" }));
Assert.That(open.Members.All(member => member.IsAssignable), Is.True);
foreach (var (locked, member) in new[] { (typeof(InspectReadonlyField), "y"), (typeof(InspectGetOnly), "Id") })
{
Assert.That(model.ShapeOf(locked).Kind, Is.EqualTo(CultInspectorValueKind.Unsupported), locked.Name);
Assert.That(model.ShapeOf(locked).Reason, Does.Contain(locked.Name + "." + member).And.Contain("readonly or get-only"));
}
Assert.That(model.ShapeOf(typeof(IDictionary<string, int>)).Kind, Is.EqualTo(CultInspectorValueKind.Dictionary));
Assert.That(model.BuildDictionary(typeof(IDictionary<string, int>), new[] { new KeyValuePair<object?, object?>("a", 1) }),
@ -295,7 +300,24 @@ namespace GameCult.Caching.Tests
public new string Value = string.Empty;
}
public readonly record struct InspectPair(float x, float y);
public struct InspectOpenStruct
{
public float x;
public float y;
public float Length => x + y;
}
public struct InspectReadonlyField
{
public float x;
public readonly float y;
}
public struct InspectGetOnly
{
public float x;
public int Id { get; }
}
[MessagePackObject]
public readonly record struct InspectKey([property: Key(0)] int Value)