feat(reflect): generic value tree + Reflect.serialize/apply + JSON bridge (#44)
All checks were successful
bootstrap / cfree-fixpoint (push) Successful in 17s
ci / build-and-test (push) Successful in 1m15s
commit-lint / conventional-commits (push) Successful in 3s
docs / build-and-deploy (push) Successful in 19s

A self-describing Value node (null/int/fixed/bool/str/list/object) with
constructors, builders (Value.add/put) and accessors (get/at/count/kind/
as_int/as_str/…). Reflect.serialize(entity) walks an entity's whole component
set into a value tree — one member per component, each a sub-object of its
fields — and Reflect.apply(entity, value) writes one back; a fixed field
becomes a fixed node, everything else an int node, so the round-trip is
bit-exact, with the model id under "@kind". Json.encode/parse bridge the tree
to and from compact, stable, diffable text, with fixed written as an exact
terminating decimal that parses back bit-for-bit (verified across the raw
Q16.16 range). Together: a one-call, bit-exact save/load for entities.

Written in Ludic and spliced on demand (runtime/native/value.ludic +
reflect_io.ludic, like Query/Light), so a program that doesn't touch
Value.*/Json.*/Reflect.serialize compiles byte-identically and the C-free
bootstrap fixpoint holds (verified). The general tagged-union/any language type
stays tracked in #1; this ships the concrete value tree the serializer needs.

Adds 21 namespace-method docs pages + Value/Json sections,
examples/library/serialize.ludic, and a regression case. Whole CI set green:
x test 72/72, x test-tools 30/30, check-impl/vocabulary/docs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Orkun ÇAKILKAYA 2026-08-31 15:19:21 +03:00
parent 0d1b09e4f0
commit 9452557f3c
31 changed files with 16753 additions and 14898 deletions

3
changes/value-tree.md Normal file
View file

@ -0,0 +1,3 @@
bump: minor
type: feat
Generic value tree + reflection serialize/deserialize + JSON bridge (#44) — a self-describing `Value` node (null/int/fixed/bool/str/list/object) with constructors, builders (`Value.add`/`Value.put`) and accessors (`Value.get`/`Value.at`/`Value.count`/`Value.kind`/`Value.as_int`/`Value.as_str`/…). `Reflect.serialize(entity)` walks an entity's whole component set into a value tree (one member per component, each a sub-object of its fields) and `Reflect.apply(entity, value)` writes one back — a `fixed` field becomes a `fixed` node, everything else an `int` node, so the round-trip is bit-exact; the model id rides along under `"@kind"`. `Json.encode`/`Json.parse` bridge the tree to and from compact, stable, diffable JSON text, with `fixed` written as an exact terminating decimal that parses back bit-for-bit. Together they are a one-call save/load for entities and the backbone of data-driven tooling. Written in Ludic and spliced on demand (like Query/Light), so a program that doesn't touch `Value.*`/`Json.*`/`Reflect.serialize` compiles byte-identically and the C-free bootstrap fixpoint is untouched. The general tagged-union/`any` language type remains tracked in #1; this delivers the concrete value tree the serializer needs.

View file

@ -0,0 +1,7 @@
---
id: json
title: Json
order: 36
---
The text bridge over the <a href="value"><code>Value</code></a> tree: <a href="json-encode"><code>Json.encode</code></a> turns a value tree into compact, stable JSON text and <a href="json-parse"><code>Json.parse</code></a> reads it back. Together with <a href="reflect-serialize"><code>Reflect.serialize</code></a>/<a href="reflect-apply"><code>Reflect.apply</code></a> this is a one-call, bit-exact save/load for entities, and a diffable on-disk format for tooling. Determinism holds: the same tree always encodes to the same bytes.

View file

@ -0,0 +1,14 @@
---
id: json-encode
name: Json.encode
category: json
kind: namespace-method
tokens: Json.encode
sig: Json.encode(value) -> string
tip: Serialize a value tree to compact JSON text.
order: 1
ns: Json
member: encode
---
Walks a value tree and returns compact JSON text. <code>int</code> nodes become integers, <code>fixed</code> nodes an exact decimal, <code>bool</code> <code>true</code>/<code>false</code>, <code>str</code> a quoted (escaped) string, and lists/objects the usual <code>[…]</code>/<code>{…}</code> — object members keep insertion order, so the output is stable and diffable. The inverse is <a href="json-parse"><code>Json.parse</code></a>; together with <a href="reflect-serialize"><code>Reflect.serialize</code></a> this is a one-call save.

View file

@ -0,0 +1,14 @@
---
id: json-parse
name: Json.parse
category: json
kind: namespace-method
tokens: Json.parse
sig: Json.parse(text: string) -> value
tip: Parse JSON text into a value tree.
order: 2
ns: Json
member: parse
---
Parses JSON <code>text</code> into a value tree — the inverse of <a href="json-encode"><code>Json.encode</code></a>. Numbers with a decimal point become <code>fixed</code> nodes (recovered bit-for-bit from a value written by <code>Json.encode</code>), whole numbers <code>int</code> nodes. It is a lean, best-effort reader for trusted saves, not a validating parser; feed a parsed object to <a href="reflect-apply"><code>Reflect.apply</code></a> to load it into an entity.

View file

@ -0,0 +1,14 @@
---
id: reflect-apply
name: Reflect.apply
category: reflect
kind: namespace-method
tokens: Reflect.apply
sig: Reflect.apply(entity, value) -> int
tip: Write a value tree's fields back into an entity.
order: 14
ns: Reflect
member: apply
---
The inverse of <a href="reflect-serialize"><code>Reflect.serialize</code></a>: writes the fields of a value-tree <code>value</code> back into a live <code>entity</code>, and returns how many were set. Only components the entity already has and fields the schema knows are applied; reserved <code>"@"</code>-keys (like <code>"@kind"</code>) and unknown names are skipped, so a partial or older save loads cleanly. Feed it the output of <a href="json-parse"><code>Json.parse</code></a> to load a save.

View file

@ -0,0 +1,14 @@
---
id: reflect-serialize
name: Reflect.serialize
category: reflect
kind: namespace-method
tokens: Reflect.serialize
sig: Reflect.serialize(entity) -> value
tip: Walk an entity's components into a value tree.
order: 13
ns: Reflect
member: serialize
---
Walks every component the <code>entity</code> carries and every field of each into a generic <a href="value-object"><code>object</code></a> value tree: one member per component, each a sub-object of its fields. A <code>fixed</code> field becomes a <a href="value-fixed"><code>fixed</code></a> node, everything else an <a href="value-int"><code>int</code></a> node, so a <code>serialize</code> → <a href="reflect-apply"><code>apply</code></a> round-trip is bit-exact; the model id rides along under the reserved <code>"@kind"</code> key. Pair it with <a href="json-encode"><code>Json.encode</code></a> for a one-call save. It names no component or field, so it works over any schema — the pattern auto-save and debug inspectors use.

View file

@ -0,0 +1,7 @@
---
id: value
title: Value
order: 35
---
A generic, self-describing value tree — the node type reflection serializes into and JSON round-trips through. A node is one of null, <code>int</code>, <code>fixed</code>, <code>bool</code>, <code>str</code>, <code>list</code>, or <code>object</code> (see <a href="value-kind"><code>Value.kind</code></a>). Build one with the constructors (<a href="value-int"><code>Value.int</code></a>, <a href="value-object"><code>Value.object</code></a>, …) and the builders <a href="value-add"><code>Value.add</code></a>/<a href="value-put"><code>Value.put</code></a>; read it with <a href="value-get"><code>Value.get</code></a>/<a href="value-at"><code>Value.at</code></a>/<a href="value-count"><code>Value.count</code></a> and the <code>as_*</code> accessors. Related: <a href="json"><code>Json</code></a>, <a href="reflect"><code>Reflect</code></a>.

View file

@ -0,0 +1,14 @@
---
id: value-add
name: Value.add
category: value
kind: namespace-method
tokens: Value.add
sig: Value.add(list, item) -> value
tip: Append an item to a list; returns the list.
order: 8
ns: Value
member: add
---
Appends <code>item</code> to the <code>list</code> node and returns the list, so calls chain. Order is preserved.

View file

@ -0,0 +1,14 @@
---
id: value-as_int
name: Value.as_int
category: value
kind: namespace-method
tokens: Value.as_int
sig: Value.as_int(value) -> int
tip: Read a scalar node as an int.
order: 16
ns: Value
member: as_int
---
Returns the raw scalar an int/fixed/bool node carries (a <code>fixed</code> comes back as its Q16.16 bits). Non-scalar nodes return <code>0</code>.

View file

@ -0,0 +1,14 @@
---
id: value-as_str
name: Value.as_str
category: value
kind: namespace-method
tokens: Value.as_str
sig: Value.as_str(value) -> string
tip: Read a str node's text.
order: 17
ns: Value
member: as_str
---
Returns the text a <code>str</code> node holds, or an empty string for any other kind.

View file

@ -0,0 +1,14 @@
---
id: value-at
name: Value.at
category: value
kind: namespace-method
tokens: Value.at
sig: Value.at(list, index: int) -> value
tip: Read a list item by index.
order: 12
ns: Value
member: at
---
Returns the item at <code>index</code> in a <code>list</code> (or object) node, or a <a href="value-null"><code>null</code></a> node if the index is out of range.

View file

@ -0,0 +1,14 @@
---
id: value-bool
name: Value.bool
category: value
kind: namespace-method
tokens: Value.bool
sig: Value.bool(b: bool) -> value
tip: Wrap a bool in a value node.
order: 4
ns: Value
member: bool
---
Builds a <code>bool</code> node (kind <code>3</code>). It encodes to JSON <code>true</code>/<code>false</code>. Read it with <a href="value-as_int"><code>Value.as_int</code></a> (0 or 1).

View file

@ -0,0 +1,14 @@
---
id: value-count
name: Value.count
category: value
kind: namespace-method
tokens: Value.count
sig: Value.count(value) -> int
tip: Number of items/members in a list or object.
order: 14
ns: Value
member: count
---
Returns how many items a <code>list</code> holds, or how many members an <code>object</code> holds. Zero for a scalar node.

View file

@ -0,0 +1,14 @@
---
id: value-fixed
name: Value.fixed
category: value
kind: namespace-method
tokens: Value.fixed
sig: Value.fixed(f: fixed) -> value
tip: Wrap a fixed in a value node.
order: 3
ns: Value
member: fixed
---
Builds a <code>fixed</code> node (kind <code>2</code>) carrying the raw Q16.16 value <code>f</code>. <a href="json-encode"><code>Json.encode</code></a> writes it as an exact decimal (e.g. <code>0.5</code>) that <a href="json-parse"><code>Json.parse</code></a> reads back bit-for-bit.

View file

@ -0,0 +1,14 @@
---
id: value-get
name: Value.get
category: value
kind: namespace-method
tokens: Value.get
sig: Value.get(obj, key: string) -> value
tip: Read a member of an object by key.
order: 10
ns: Value
member: get
---
Returns the value stored under <code>key</code> in the <code>obj</code> node, or a <a href="value-null"><code>null</code></a> node if there is no such member.

View file

@ -0,0 +1,14 @@
---
id: value-has
name: Value.has
category: value
kind: namespace-method
tokens: Value.has
sig: Value.has(obj, key: string) -> bool
tip: Whether an object has a member.
order: 11
ns: Value
member: has
---
Returns whether the <code>obj</code> node has a member named <code>key</code> — the way to tell an explicit <a href="value-null"><code>null</code></a> from an absent key.

View file

@ -0,0 +1,14 @@
---
id: value-int
name: Value.int
category: value
kind: namespace-method
tokens: Value.int
sig: Value.int(n: int) -> value
tip: Wrap an int in a value node.
order: 2
ns: Value
member: int
---
Builds an <code>int</code> node (kind <code>1</code>) carrying <code>n</code>. Read it back with <a href="value-as_int"><code>Value.as_int</code></a>. This is the node <a href="reflect-serialize"><code>Reflect.serialize</code></a> uses for every non-<code>fixed</code> field.

View file

@ -0,0 +1,14 @@
---
id: value-key_at
name: Value.key_at
category: value
kind: namespace-method
tokens: Value.key_at
sig: Value.key_at(obj, index: int) -> string
tip: The key of an object member by position.
order: 13
ns: Value
member: key_at
---
Returns the key of the member at position <code>index</code> in an <code>object</code> node — pair it with <a href="value-at"><code>Value.at</code></a> and <a href="value-count"><code>Value.count</code></a> to walk every member in order.

View file

@ -0,0 +1,14 @@
---
id: value-kind
name: Value.kind
category: value
kind: namespace-method
tokens: Value.kind
sig: Value.kind(value) -> int
tip: The node's kind tag.
order: 15
ns: Value
member: kind
---
Returns the node's kind: <code>0</code> null, <code>1</code> int, <code>2</code> fixed, <code>3</code> bool, <code>4</code> str, <code>5</code> list, <code>6</code> object — so a generic reader can branch before unwrapping.

View file

@ -0,0 +1,14 @@
---
id: value-list
name: Value.list
category: value
kind: namespace-method
tokens: Value.list
sig: Value.list() -> value
tip: An empty list node.
order: 6
ns: Value
member: list
---
Builds an empty <code>list</code> node (kind <code>5</code>). Append items with <a href="value-add"><code>Value.add</code></a>, read them with <a href="value-at"><code>Value.at</code></a> and <a href="value-count"><code>Value.count</code></a>.

View file

@ -0,0 +1,14 @@
---
id: value-null
name: Value.null
category: value
kind: namespace-method
tokens: Value.null
sig: Value.null() -> value
tip: An empty null node.
order: 1
ns: Value
member: null
---
Builds a <code>null</code> node — the absent value. <a href="value-get"><code>Value.get</code></a> and <a href="value-at"><code>Value.at</code></a> return one for a missing key or out-of-range index, so a reader never faults on absent data. Its <a href="value-kind"><code>Value.kind</code></a> is <code>0</code>.

View file

@ -0,0 +1,14 @@
---
id: value-object
name: Value.object
category: value
kind: namespace-method
tokens: Value.object
sig: Value.object() -> value
tip: An empty object node.
order: 7
ns: Value
member: object
---
Builds an empty <code>object</code> node (kind <code>6</code>) — an ordered set of key/value members. Set members with <a href="value-put"><code>Value.put</code></a>; read them with <a href="value-get"><code>Value.get</code></a>, <a href="value-key_at"><code>Value.key_at</code></a>, and <a href="value-count"><code>Value.count</code></a>. This is the shape <a href="reflect-serialize"><code>Reflect.serialize</code></a> produces.

View file

@ -0,0 +1,14 @@
---
id: value-put
name: Value.put
category: value
kind: namespace-method
tokens: Value.put
sig: Value.put(obj, key: string, item) -> value
tip: Set a key on an object; returns the object.
order: 9
ns: Value
member: put
---
Sets member <code>key</code> of the <code>obj</code> node to <code>item</code> (replacing an existing member with the same key) and returns the object. Insertion order is preserved for a stable <a href="json-encode"><code>Json.encode</code></a>.

View file

@ -0,0 +1,14 @@
---
id: value-str
name: Value.str
category: value
kind: namespace-method
tokens: Value.str
sig: Value.str(s: string) -> value
tip: Wrap a string in a value node.
order: 5
ns: Value
member: str
---
Builds a <code>str</code> node (kind <code>4</code>) holding <code>s</code>. <a href="json-encode"><code>Json.encode</code></a> quotes and escapes it; read it back with <a href="value-as_str"><code>Value.as_str</code></a>.

View file

@ -0,0 +1,56 @@
# serialize.ludic — the generic value tree (Value.*), its JSON bridge (Json.*),
# and reflection-driven save/load (Reflect.serialize / Reflect.apply, issue #44).
# One call walks an entity's whole component set into a self-describing value
# tree; Json.encode turns it into text and Json.parse reads it back; Reflect.apply
# writes a parsed tree into a live entity — a one-call save/load, bit-exact.
#
# Each assertion that holds prints its number, so a full run prints:
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
program Serialize {
property Health { hp: int = 0, max: int = 0 }
property Velocity { dx: fixed = 0.0, dy: fixed = 0.0 }
model Unit { Health, Velocity }
entry {
spawn Unit { Health { hp: 7, max: 10 }, Velocity { dx: fixed(2), dy: fixed(3) } }
let e = 0
# --- serialize an entity to a value tree ---
let tree = Reflect.serialize(e)
if Value.kind(tree) == 6 { print(1) } # object
if Value.has(tree, "Health") == 1 { print(2) }
let h = Value.get(tree, "Health")
if Value.as_int(Value.get(h, "hp")) == 7 { print(3) }
if Value.as_int(Value.get(h, "max")) == 10 { print(4) }
let vv = Value.get(tree, "Velocity")
if Value.kind(Value.get(vv, "dx")) == 2 { print(5) } # a fixed node
if Value.as_int(Value.get(vv, "dx")) == 131072 { print(6) } # raw Q16.16 = fixed(2)
# --- JSON bridge: encode, then parse straight back ---
let text = Json.encode(tree)
if text == "{\"@kind\":1,\"Health\":{\"hp\":7,\"max\":10},\"Velocity\":{\"dx\":2.0,\"dy\":3.0}}" { print(7) }
let back = Json.parse(text)
if Value.as_int(Value.get(Value.get(back, "Health"), "hp")) == 7 { print(8) }
# --- apply a parsed tree into a second, zeroed entity: a one-call load ---
spawn Unit { Health { hp: 0, max: 0 }, Velocity { dx: 0.0, dy: 0.0 } }
let e2 = 1
let applied = Reflect.apply(e2, back)
if applied == 4 { print(9) } # four fields written
let H = Reflect.prop("Health")
let V = Reflect.prop("Velocity")
if Reflect.get(e2, H, 0) == 7 { print(10) } # hp round-tripped
if Reflect.get(e2, H, 1) == 10 { print(11) } # max round-tripped
if Reflect.get(e2, V, 0) == 131072 { print(12) } # dx (fixed) bit-exact
# --- build a value tree by hand + inspect a list ---
let list = Value.list()
Value.add(list, Value.int(3))
Value.add(list, Value.str("hi"))
Value.add(list, Value.bool(1))
if Value.count(list) == 3 { print(13) }
if Value.as_int(Value.at(list, 0)) == 3 { print(14) }
if Value.as_str(Value.at(list, 1)) == "hi" { print(15) }
if Json.encode(list) == "[3,\"hi\",true]" { print(16) }
}
}

View file

@ -0,0 +1,71 @@
# ============================================================================
# reflect_io.ludic — Reflect.serialize / Reflect.apply, in Ludic. One call walks
# an entity's whole component set into a generic value tree (value.ludic), and
# its inverse writes a value tree's fields back into a live entity. Together with
# Json.* this is a one-call save/load and the backbone of tooling (debug
# inspectors, network snapshots as text).
#
# It stands on the reflection ABI (world_* builtins — the EV2/EV8 world table)
# and the value tree, so ludicc force-emits the world table and splices value.ludic
# whenever Reflect.serialize/apply appear (parse.ludic + emit_decl.ludic).
#
# Serialize captures each field's raw stored value: a `fixed` field becomes a
# `fixed` node (its Q16.16 value), everything else an `int` node — so a
# serialize -> apply round-trip is bit-exact. The entity's model id rides along
# under the reserved "@kind" key; apply skips any "@"-prefixed key.
# ============================================================================
# entity -> a value-tree object: { "@kind": <model id>, "<Comp>": { "<field>": v, … }, … }
function reflect_serialize(e: int) -> Val {
let obj = value_object()
value_put(obj, "@kind", value_int(world_kind(e)))
let pc = world_prop_count()
var p = 0
while p < pc {
if world_has(e, p) != 0 {
let comp = value_object()
let fc = world_field_count(p)
var f = 0
while f < fc {
let fname = world_field_name(p, f)
let raw = world_get(e, p, f)
var node = value_int(raw)
if world_field_type(p, f) == "fixed" { node = value_fixed(raw) }
value_put(comp, fname, node)
f = f + 1
}
value_put(obj, world_prop_name(p), comp)
}
p = p + 1
}
return obj
}
# write a value-tree object's fields back into entity `e`. Only components the
# entity already has and fields the schema knows are applied; reserved "@"-keys
# (e.g. "@kind") and unknown names are skipped. Returns the number of fields set.
function reflect_apply(e: int, v: Val) -> int {
var set = 0
var i = 0
while i < value_count(v) {
let pname = value_key_at(v, i)
if pname[0] != 64 { # skip reserved "@…" keys
let p = world_prop_id(pname)
if p >= 0 and world_has(e, p) != 0 {
let comp = value_at(v, i)
var j = 0
while j < value_count(comp) {
let fname = value_key_at(comp, j)
let f = world_field_id(p, fname)
if f >= 0 {
world_set(e, p, f, value_as_int(value_at(comp, j)))
set = set + 1
}
j = j + 1
}
}
}
i = i + 1
}
return set
}

266
runtime/native/value.ludic Normal file
View file

@ -0,0 +1,266 @@
# ============================================================================
# value.ludic — a generic value tree (`Value.*`) and its JSON bridge (`Json.*`),
# in Ludic. The value tree is the tagged, self-describing node the reflection
# serializer (runtime/native/reflect_io.ludic) walks an entity into, and the
# shape a JSON save round-trips through. A node is one of:
#
# kind 0 null kind 1 int kind 2 fixed kind 3 bool
# kind 4 str kind 5 list kind 6 object
#
# ludicc splices this file when it sees Value.* / Json.* / Reflect.serialize /
# Reflect.apply (parse.ludic). Everything is plain Ludic over heap records — no
# new runtime primitive — so the whole tree is deterministic and allocation is
# the only cost.
# ============================================================================
# one node of the tree. A list uses `kids`; an object uses `keys` + `kids` in
# parallel (keys[i] labels kids[i]). Scalars use `num` (int/bool/fixed-raw) or
# `txt` (str).
property Val {
tag: int = 0
num: int = 0
txt: pointer = null
keys: []pointer
kids: []Val
}
function value_new(tag: int) -> Val {
let v = new Val
v.tag = tag
v.keys = new []pointer
v.kids = new []Val
return v
}
# --- constructors -----------------------------------------------------------
function value_null() -> Val { return value_new(0) }
function value_int(n: int) -> Val { let v = value_new(1); v.num = n; return v }
function value_fixed(f: int) -> Val { let v = value_new(2); v.num = f; return v } # f = raw Q16.16
function value_bool(b: int) -> Val { let v = value_new(3); if b != 0 { v.num = 1 }; return v }
function value_str(s: pointer) -> Val { let v = value_new(4); v.txt = s; return v }
function value_list() -> Val { return value_new(5) }
function value_object() -> Val { return value_new(6) }
# --- builders (return the container, so calls chain) ------------------------
function value_add(list: Val, item: Val) -> Val { push(list.kids, item); return list }
function value_put(obj: Val, key: pointer, item: Val) -> Val {
var i = 0
while i < len(obj.keys) { if obj.keys[i] == key { obj.kids[i] = item; return obj }; i = i + 1 }
push(obj.keys, key); push(obj.kids, item)
return obj
}
# --- accessors --------------------------------------------------------------
function value_kind(v: Val) -> int { return v.tag }
function value_count(v: Val) -> int { return len(v.kids) }
function value_as_int(v: Val) -> int { return v.num }
function value_as_str(v: Val) -> pointer { if v.txt == null { return "" }; return v.txt }
function value_at(list: Val, i: int) -> Val {
if i < 0 or i >= len(list.kids) { return value_null() }
return list.kids[i]
}
function value_key_at(obj: Val, i: int) -> pointer {
if i < 0 or i >= len(obj.keys) { return "" }
return obj.keys[i]
}
function value_get(obj: Val, key: pointer) -> Val {
var i = 0
while i < len(obj.keys) { if obj.keys[i] == key { return obj.kids[i] }; i = i + 1 }
return value_null()
}
function value_has(obj: Val, key: pointer) -> int {
var i = 0
while i < len(obj.keys) { if obj.keys[i] == key { return 1 }; i = i + 1 }
return 0
}
# --- JSON encode ------------------------------------------------------------
# escape a string's `"` `\` and newline, wrapping it in quotes.
function json_quote(s: pointer) -> pointer {
var out = "\""
var i = 0
let n = len(s)
while i < n {
let c = s[i]
if c == 34 { out = out + "\\\"" }
else { if c == 92 { out = out + "\\\\" }
else { if c == 10 { out = out + "\\n" }
else { out = out + s[i..i + 1] } } }
i = i + 1
}
return out + "\""
}
# a raw Q16.16 fixed -> its EXACT decimal string. The denominator is 2^16, so the
# decimal always terminates (in <=16 fractional digits): emit digits until the
# remainder hits zero. This is the exact inverse of jp_number's fixed decode, so
# a value_fixed round-trips through JSON bit-for-bit; short values (0.5, 2.0) stay
# short. Each step keeps frac < 655360, well within i32.
function json_fixed_str(raw: int) -> pointer {
var a = raw
var sign = ""
if a < 0 { sign = "-"; a = 0 - a }
let ip = a / 65536
var frac = a % 65536
if frac == 0 { return sign + string(ip) + ".0" }
var fs = ""
while frac != 0 {
frac = frac * 10
fs = fs + string(frac / 65536)
frac = frac % 65536
}
return sign + string(ip) + "." + fs
}
function json_encode(v: Val) -> pointer {
if v.tag == 0 { return "null" }
if v.tag == 1 { return string(v.num) }
if v.tag == 2 { return json_fixed_str(v.num) }
if v.tag == 3 { if v.num != 0 { return "true" }; return "false" }
if v.tag == 4 { return json_quote(v.txt) }
if v.tag == 5 {
var out = "["
var i = 0
while i < len(v.kids) {
if i > 0 { out = out + "," }
out = out + json_encode(v.kids[i])
i = i + 1
}
return out + "]"
}
var out = "{"
var i = 0
while i < len(v.keys) {
if i > 0 { out = out + "," }
out = out + json_quote(v.keys[i]) + ":" + json_encode(v.kids[i])
i = i + 1
}
return out + "}"
}
# --- JSON parse -------------------------------------------------------------
# a tiny recursive-descent parser over a byte string. `JP` carries the cursor so
# the recursion threads position without a global. Malformed input yields a null
# node and leaves the cursor where it stopped (best-effort, not a validator).
property JP { s: pointer = null, i: int = 0, n: int = 0 }
function jp_skip_ws(p: JP) -> void {
while p.i < p.n {
let c = p.s[p.i]
if c == 32 or c == 9 or c == 10 or c == 13 { p.i = p.i + 1 }
else { return }
}
}
function json_parse(s: pointer) -> Val {
let p = new JP
p.s = s; p.i = 0; p.n = len(s)
return jp_value(p)
}
function jp_value(p: JP) -> Val {
jp_skip_ws(p)
if p.i >= p.n { return value_null() }
let c = p.s[p.i]
if c == 123 { return jp_object(p) } # '{'
if c == 91 { return jp_list(p) } # '['
if c == 34 { return value_str(jp_string(p)) } # '"'
if c == 116 { p.i = p.i + 4; return value_bool(1) } # true
if c == 102 { p.i = p.i + 5; return value_bool(0) } # false
if c == 110 { p.i = p.i + 4; return value_null() } # null
return jp_number(p)
}
# read a quoted string (cursor on the opening quote) -> the unescaped contents.
function jp_string(p: JP) -> pointer {
p.i = p.i + 1 # skip opening quote
var out = ""
while p.i < p.n {
let c = p.s[p.i]
if c == 34 { p.i = p.i + 1; return out } # closing quote
if c == 92 { # escape
p.i = p.i + 1
if p.i < p.n {
let e = p.s[p.i]
if e == 110 { out = out + "\n" }
else { out = out + p.s[p.i..p.i + 1] } # \" \\ \/ -> the literal char
p.i = p.i + 1
}
} else {
out = out + p.s[p.i..p.i + 1]
p.i = p.i + 1
}
}
return out
}
# read a number; a '.' makes it a fixed node, otherwise an int node.
function jp_number(p: JP) -> Val {
var neg = 0
if p.i < p.n and p.s[p.i] == 45 { neg = 1; p.i = p.i + 1 } # '-'
var ip = 0
while p.i < p.n and p.s[p.i] >= 48 and p.s[p.i] <= 57 {
ip = ip * 10 + (p.s[p.i] - 48)
p.i = p.i + 1
}
if p.i < p.n and p.s[p.i] == 46 { # '.', a fixed
p.i = p.i + 1
let digits = new []int
while p.i < p.n and p.s[p.i] >= 48 and p.s[p.i] <= 57 {
push(digits, p.s[p.i] - 48)
p.i = p.i + 1
}
# exact inverse of json_fixed_str's generation: fold the digits back from the
# last, frac_{i-1} = (d_i*65536 + frac_i)/10. Every intermediate stays < 2^16*10,
# so this is overflow-free and reproduces the raw Q16.16 for a generated decimal
# (an arbitrary hand-written decimal lands within one raw unit).
var frac = 0
var di = len(digits) - 1
while di >= 0 {
frac = (digits[di] * 65536 + frac) / 10
di = di - 1
}
var raw = ip * 65536 + frac
if neg != 0 { raw = 0 - raw }
return value_fixed(raw)
}
if neg != 0 { ip = 0 - ip }
return value_int(ip)
}
function jp_list(p: JP) -> Val {
let out = value_list()
p.i = p.i + 1 # '['
jp_skip_ws(p)
if p.i < p.n and p.s[p.i] == 93 { p.i = p.i + 1; return out } # empty ']'
while p.i < p.n {
push(out.kids, jp_value(p))
jp_skip_ws(p)
if p.i < p.n and p.s[p.i] == 44 { p.i = p.i + 1; continue } # ','
break
}
jp_skip_ws(p)
if p.i < p.n and p.s[p.i] == 93 { p.i = p.i + 1 }
return out
}
function jp_object(p: JP) -> Val {
let out = value_object()
p.i = p.i + 1 # '{'
jp_skip_ws(p)
if p.i < p.n and p.s[p.i] == 125 { p.i = p.i + 1; return out } # empty '}'
while p.i < p.n {
jp_skip_ws(p)
let key = jp_string(p)
jp_skip_ws(p)
if p.i < p.n and p.s[p.i] == 58 { p.i = p.i + 1 } # ':'
push(out.keys, key)
push(out.kids, jp_value(p))
jp_skip_ws(p)
if p.i < p.n and p.s[p.i] == 44 { p.i = p.i + 1; continue } # ','
break
}
jp_skip_ws(p)
if p.i < p.n and p.s[p.i] == 125 { p.i = p.i + 1 }
return out
}

View file

@ -295,6 +295,36 @@ function emit_ns_call(ns: pointer, meth: pointer, e: Node) -> Val {
if (meth == "has") { bare = "world_has"; push(labels, "entity"); push(labels, "prop") }
if (meth == "kind") { bare = "world_kind"; push(labels, "entity") }
if (meth == "model") { bare = "world_model_id"; push(labels, "name") }
# #44 — serialize an entity to a value tree and apply one back (reflect_io.ludic)
if (meth == "serialize") { bare = "reflect_serialize"; push(labels, "entity") }
if (meth == "apply") { bare = "reflect_apply"; push(labels, "entity"); push(labels, "value") }
}
# Value.* — the generic value tree (runtime/native/value.ludic, spliced on
# demand). Nodes are int/fixed/bool/str/list/object; the methods map straight
# to the spliced value_* functions, whose signatures carry the return types.
if (ns == "Value") {
if (meth == "null") { bare = "value_null" }
if (meth == "int") { bare = "value_int"; push(labels, "n") }
if (meth == "fixed") { bare = "value_fixed"; push(labels, "f") }
if (meth == "bool") { bare = "value_bool"; push(labels, "b") }
if (meth == "str") { bare = "value_str"; push(labels, "s") }
if (meth == "list") { bare = "value_list" }
if (meth == "object") { bare = "value_object" }
if (meth == "add") { bare = "value_add"; push(labels, "list"); push(labels, "item") }
if (meth == "put") { bare = "value_put"; push(labels, "obj"); push(labels, "key"); push(labels, "item") }
if (meth == "get") { bare = "value_get"; push(labels, "obj"); push(labels, "key") }
if (meth == "has") { bare = "value_has"; push(labels, "obj"); push(labels, "key") }
if (meth == "at") { bare = "value_at"; push(labels, "list"); push(labels, "index") }
if (meth == "key_at") { bare = "value_key_at"; push(labels, "obj"); push(labels, "index") }
if (meth == "count") { bare = "value_count"; push(labels, "value") }
if (meth == "kind") { bare = "value_kind"; push(labels, "value") }
if (meth == "as_int") { bare = "value_as_int"; push(labels, "value") }
if (meth == "as_str") { bare = "value_as_str"; push(labels, "value") }
}
# Json.* — the text bridge over the value tree (runtime/native/value.ludic).
if (ns == "Json") {
if (meth == "encode") { bare = "json_encode"; push(labels, "value") }
if (meth == "parse") { bare = "json_parse"; push(labels, "text") }
}
if (bare == null) { perr(`unknown builtin {ns}.{meth}`) }
reorder_named(e, labels)

View file

@ -178,6 +178,8 @@ function p_postfix() -> Node {
if e.a.kind == E_ID and e.a.s == "Query" { g_uses_query = true } # splice the ECS spatial-query runtime on demand
if e.a.kind == E_ID and e.a.s == "Reflect" { g_uses_reflect = true } # force-emit the reflection ABI (Reflect.* reads the world schema)
if e.a.kind == E_ID and e.a.s == "Light" { g_uses_light = true } # splice the 2D light-accumulation pass on demand
if e.a.kind == E_ID and (e.a.s == "Value" or e.a.s == "Json") { g_uses_value = true } # splice the value tree + JSON on demand (#44)
if e.a.kind == E_ID and e.a.s == "Reflect" and (e.s == "serialize" or e.s == "apply") { g_uses_value = true; g_uses_reflect_io = true } # Reflect.serialize/apply -> value tree + world table
}
else { if is_op("[") { pi = pi + 1; let lo = expr()
if is_op("..") { pi = pi + 1; let sl = node(E_SLICE); sl.a = e; sl.b = lo; sl.c = expr(); eat_op("]"); e = sl } # s[a..b] substring
@ -403,6 +405,8 @@ var g_uses_regex: bool = false # a program mentioned Regex.* -> splice the re
var g_uses_query: bool = false # a program mentioned Query.* -> splice the query runtime + reflection ABI
var g_uses_reflect: bool = false # a program mentioned Reflect.* -> force-emit the reflection ABI
var g_uses_light: bool = false # a program mentioned Light.* -> splice the 2D light pass
var g_uses_value: bool = false # Value.*/Json.*/Reflect.serialize -> splice the value tree + JSON (#44)
var g_uses_reflect_io: bool = false # Reflect.serialize/apply -> splice the reflection serializer
function already_loaded(full: pointer) -> bool {
var i = 0
@ -585,6 +589,20 @@ function maybe_splice_runtime() -> void {
do_import("runtime/native/light.ludic")
cur_dir = saved
}
# Value.*/Json.* (#44) get the generic value tree + JSON bridge spliced in; it
# is self-contained (only string/slice ops), so it works in a plain tool too.
if g_uses_value {
cur_dir = ""
do_import("runtime/native/value.ludic")
cur_dir = saved
}
# Reflect.serialize/apply add the reflection serializer, which stands on both
# the value tree (above) and the world table (force-emitted for Reflect.*).
if g_uses_reflect_io {
cur_dir = ""
do_import("runtime/native/reflect_io.ludic")
cur_dir = saved
}
}
function parse_program() -> void {
@ -606,6 +624,8 @@ function parse_program() -> void {
g_uses_query = false
g_uses_reflect = false
g_uses_light = false
g_uses_value = false
g_uses_reflect_io = false
g_tests = new []Node
loaded_paths = new []pointer
skipnl()

File diff suppressed because it is too large Load diff

View file

@ -198,6 +198,7 @@ function cmd_test() -> int {
feat_case("library/anim", "", "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34", "anim.ludic (Anim frame/once/pingpong/cell + Tween progress/loop/yoyo/ease/number/round/point/tint)")
feat_case("library/query", "", "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18", "query.ludic (Query count/first/nearest/within — ECS spatial queries over the reflection ABI)")
feat_case("library/reflect", "", "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20", "reflect.ludic (Reflect prop/field enumeration + type + get/set/has/kind — runtime reflection over the world schema)")
feat_case("library/serialize", "", "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16", "serialize.ludic (Value tree + Json encode/parse + Reflect.serialize/apply — bit-exact save/load; issue #44)")
feat_case("library/render", "", "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18", "render.ludic (Screen pixel/oval/camera/clip/blend_mode/measure_text + Camera set/follow/shake, verified by pixel readback)")
feat_case("library/lighting", "", "1 2 3 4 5 6 7 8 9 10 11 12 13 14", "lighting.ludic (Light ambient/point radial falloff + occluder hard shadows — 2D light accumulation, verified by pixel readback)")
spec_case("library/testing", "== 6 passed, 0 failed ==")