dsl_kit_parse/dump.rs
1//! Typed AST → [`ParseTree`] reverse walk (`DslDump`).
2//!
3//! [`DslBuild`](crate::DslBuild) turns a validated [`ParseTree`] into a
4//! typed AST value; this module is its inverse. A type deriving
5//! `#[derive(DslDump)]` (in `dsl-kit-macros`) re-emits the tree shape
6//! its own `DslBuild` derive accepts, so the two derives stay a
7//! round-trip pair by construction:
8//!
9//! ```text
10//! from_parse_tree(&ast.to_parse_tree()?, &ids) ≙ ast (modulo NodeId)
11//! ```
12//!
13//! Chaining the emitted tree through
14//! [`to_canonical_json`](crate::serde_bridge::to_canonical_json) yields
15//! the serde-bridge JSON serializer downstream consumers want — see
16//! [`dump_canonical_json`]. Because `to_canonical_json` runs
17//! [`check_conformance`](crate::check_conformance) on the way down, a
18//! derive bug that emitted a non-conforming shape surfaces as loud
19//! diagnostics rather than silently wrong JSON.
20//!
21//! ## Emission rules (the duals of the build defaults)
22//!
23//! - `id: NodeId` is **not** serialized — re-parsing mints fresh ids,
24//! which is the same contract every front-end already has. The id is
25//! only used to look up the node's `$allow` annotation in the
26//! caller-supplied [`AllowTable`].
27//! - An absent `Option<T>` payload / child omits its key entirely
28//! (never `null`), matching the canonical-JSON spelling and
29//! [`build_field_optional`](crate::build_field_optional)'s absent →
30//! `None` rule.
31//! - `Vec<T>` payloads always emit, including as `[]` when empty —
32//! one unambiguous spelling. ([`build_field_vec`](crate::build_field_vec)
33//! accepts the omitted spelling too, so both round-trip; the emit
34//! side just never produces it.)
35//! - `Vec<Self>` child slots always emit the slot, including empty.
36//! A slot declared `non_empty` fails conformance downstream in that
37//! case, which is the declared-constraint violation surfacing — not
38//! something to paper over here.
39//! - Keyed slots (`BTreeMap`) emit in map iteration order, which is
40//! already ascending by key — the sortedness
41//! [`check_conformance`](crate::check_conformance) demands. Empty
42//! maps omit the slot (the PEG front-end's "nothing to record"
43//! spelling; both spellings are accepted everywhere it matters).
44//! - Spans are `None`: a synthesized tree has no source text.
45//!
46//! One known asymmetry, inherited rather than introduced: nested
47//! `Option<Option<T>>` payloads cannot distinguish `Some(None)` from
48//! `None` in JSON (both spell as an absent key / `null`), exactly as on
49//! the build side.
50
51use std::collections::BTreeMap;
52
53use dsl_kit_core::AllowTable;
54use serde_json::Value;
55
56use crate::serde_bridge::{serde_codes, to_canonical_json};
57use crate::{BuildError, Diagnostic, ParseTree, RawValue};
58
59// ---------------------------------------------------------------------------
60// DslDump
61// ---------------------------------------------------------------------------
62
63/// Contract for re-emitting a typed AST value as the [`ParseTree`] its
64/// [`DslBuild`](crate::DslBuild) impl accepts.
65///
66/// Implemented via `#[derive(DslDump)]` in `dsl-kit-macros`;
67/// hand-written impls are fine for shapes the derive cannot express,
68/// as long as they uphold the round-trip contract in the module docs.
69pub trait DslDump {
70 /// Emits the tree, attaching each node's `$allow` annotation looked
71 /// up by its `NodeId` in `allows` (the table
72 /// [`IdGen::take_allows`](dsl_kit_core::IdGen::take_allows)
73 /// produced when the AST was built).
74 ///
75 /// `$allow` participates in canonical-JSON content hashes, so a
76 /// caller that carried an [`AllowTable`] alongside the AST should
77 /// hand it back here rather than calling [`DslDump::to_parse_tree`]
78 /// and silently dropping the suppressions.
79 fn to_parse_tree_with(&self, allows: &AllowTable) -> Result<ParseTree, BuildError>;
80
81 /// Emits the tree with no `$allow` annotations (an empty
82 /// [`AllowTable`]).
83 fn to_parse_tree(&self) -> Result<ParseTree, BuildError> {
84 self.to_parse_tree_with(&AllowTable::default())
85 }
86}
87
88// ---------------------------------------------------------------------------
89// Canonical-JSON convenience
90// ---------------------------------------------------------------------------
91
92/// Serializes a typed AST straight to canonical serde-bridge JSON:
93/// [`DslDump::to_parse_tree`] chained through
94/// [`to_canonical_json`](crate::serde_bridge::to_canonical_json)
95/// against the type's own derived schema.
96///
97/// The output is what the JSON front-end
98/// ([`from_json_value`](crate::serde_bridge::from_json_value)) parses
99/// back into an equivalent AST — the wire form for caching, transport,
100/// and content hashing of an AST a program built or transformed in
101/// memory.
102pub fn dump_canonical_json<T>(ast: &T) -> Result<Value, BuildError>
103where
104 T: DslDump + dsl_kit_schema::DslSchema,
105{
106 dump_canonical_json_with(ast, &AllowTable::default())
107}
108
109/// [`dump_canonical_json`] with an [`AllowTable`] so `$allow`
110/// annotations survive into the JSON (and therefore into content
111/// hashes computed over it).
112pub fn dump_canonical_json_with<T>(ast: &T, allows: &AllowTable) -> Result<Value, BuildError>
113where
114 T: DslDump + dsl_kit_schema::DslSchema,
115{
116 to_canonical_json(&ast.to_parse_tree_with(allows)?, &T::schema())
117}
118
119// ---------------------------------------------------------------------------
120// Field helpers (payload side)
121// ---------------------------------------------------------------------------
122
123fn dump_value_error(context: String, err: serde_json::Error) -> BuildError {
124 BuildError::single(Diagnostic::error(
125 serde_codes::DUMP_FIELD,
126 format!("{context}: {err}"),
127 ))
128}
129
130/// Serializes one payload field into the tree as
131/// [`RawValue::Json`].
132///
133/// Dual of [`build_field`](crate::build_field): the emitted value is
134/// what `serde_json::from_value` on the build side deserializes back.
135/// Serialization failure (a map with non-string keys, a non-finite
136/// float, a failing custom `Serialize`) reports
137/// [`serde_codes::DUMP_FIELD`].
138pub fn dump_field<T: serde::Serialize>(
139 tree: &mut ParseTree,
140 name: &str,
141 value: &T,
142) -> Result<(), BuildError> {
143 let v =
144 serde_json::to_value(value).map_err(|e| dump_value_error(format!("field `{name}`"), e))?;
145 tree.fields.push((name.to_string(), RawValue::Json(v)));
146 Ok(())
147}
148
149/// Serializes an optional payload field, omitting the key when `None`.
150///
151/// Dual of [`build_field_optional`](crate::build_field_optional): the
152/// absent key is the canonical spelling of `None`, so `Some(x)` emits
153/// `x`'s value (never a JSON `null`).
154pub fn dump_field_optional<T: serde::Serialize>(
155 tree: &mut ParseTree,
156 name: &str,
157 value: &Option<T>,
158) -> Result<(), BuildError> {
159 match value {
160 Some(v) => dump_field(tree, name, v),
161 None => Ok(()),
162 }
163}
164
165// ---------------------------------------------------------------------------
166// Child helpers (recursive side)
167// ---------------------------------------------------------------------------
168
169/// Emits a [`Multiplicity::One`](dsl_kit_schema::Multiplicity::One)
170/// child slot. Dual of [`build_child_one`](crate::build_child_one).
171pub fn dump_child_one<T: DslDump>(
172 tree: &mut ParseTree,
173 name: &str,
174 child: &T,
175 allows: &AllowTable,
176) -> Result<(), BuildError> {
177 let sub = child.to_parse_tree_with(allows)?;
178 tree.children.push((name.to_string(), vec![sub]));
179 Ok(())
180}
181
182/// Emits a
183/// [`Multiplicity::Optional`](dsl_kit_schema::Multiplicity::Optional)
184/// child slot, omitting the slot entirely when `None`. Dual of
185/// [`build_child_optional`](crate::build_child_optional).
186///
187/// Takes `Option<&T>` rather than `&Option<T>` so `Option<Box<T>>`
188/// fields flatten in via `as_deref()`.
189pub fn dump_child_optional<T: DslDump>(
190 tree: &mut ParseTree,
191 name: &str,
192 child: Option<&T>,
193 allows: &AllowTable,
194) -> Result<(), BuildError> {
195 match child {
196 Some(c) => dump_child_one(tree, name, c, allows),
197 None => Ok(()),
198 }
199}
200
201/// Emits a [`Multiplicity::Many`](dsl_kit_schema::Multiplicity::Many)
202/// child slot — always, including as an empty slot, so the emitted
203/// spelling is unambiguous. Dual of
204/// [`build_child_many`](crate::build_child_many).
205///
206/// Takes an iterator of `&T` so `Vec<T>` and `Vec<Box<T>>` fields both
207/// feed in without an intermediate collect.
208pub fn dump_child_many<'a, T, I>(
209 tree: &mut ParseTree,
210 name: &str,
211 children: I,
212 allows: &AllowTable,
213) -> Result<(), BuildError>
214where
215 T: DslDump + 'a,
216 I: IntoIterator<Item = &'a T>,
217{
218 let mut subs = Vec::new();
219 for child in children {
220 subs.push(child.to_parse_tree_with(allows)?);
221 }
222 tree.children.push((name.to_string(), subs));
223 Ok(())
224}
225
226/// Emits a [`Multiplicity::Map`](dsl_kit_schema::Multiplicity::Map)
227/// child slot from `(key, node)` entries, omitting the slot when
228/// empty. Dual of [`build_child_map`](crate::build_child_map).
229///
230/// The entries must arrive in ascending key order —
231/// [`BTreeMap::iter`] order, which is where the derive reads them
232/// from — so the emitted tree passes the
233/// [`KEYED_SLOT_UNSORTED`](crate::codes::KEYED_SLOT_UNSORTED)
234/// conformance gate.
235pub fn dump_child_map<'a, T, I>(
236 tree: &mut ParseTree,
237 name: &str,
238 entries: I,
239 allows: &AllowTable,
240) -> Result<(), BuildError>
241where
242 T: DslDump + 'a,
243 I: IntoIterator<Item = (&'a String, &'a T)>,
244{
245 let mut out = Vec::new();
246 for (key, child) in entries {
247 out.push((key.clone(), child.to_parse_tree_with(allows)?));
248 }
249 if !out.is_empty() {
250 tree.keyed_children.push((name.to_string(), out));
251 }
252 Ok(())
253}
254
255/// Emits a scalar-valued keyed slot (`BTreeMap<String, V>` where `V`
256/// is a payload type) as keyed entries each carrying a single `value`
257/// field — the exact shape the JSON front-end builds on ingest and
258/// [`build_scalar_map`](crate::build_scalar_map) reads back. Omits the
259/// slot when the map is empty.
260pub fn dump_scalar_map<V: serde::Serialize>(
261 tree: &mut ParseTree,
262 name: &str,
263 entries: &BTreeMap<String, V>,
264) -> Result<(), BuildError> {
265 if entries.is_empty() {
266 return Ok(());
267 }
268 let mut out = Vec::with_capacity(entries.len());
269 for (key, value) in entries {
270 let v = serde_json::to_value(value)
271 .map_err(|e| dump_value_error(format!("keyed slot `{name}` entry `{key}`"), e))?;
272 let mut leaf = ParseTree::new("");
273 leaf.fields.push(("value".to_string(), RawValue::Json(v)));
274 out.push((key.clone(), leaf));
275 }
276 tree.keyed_children.push((name.to_string(), out));
277 Ok(())
278}