tabnas_path/lib.rs
1/* Copyright (c) 2022-2026 Richard Rodger and other contributors, MIT License */
2
3//! Property-path tracking for the `tabnas` parsing engine.
4//!
5//! This is a behaviour plugin, not a grammar plugin. It tracks the
6//! **property path**, the chain of map keys and array indices leading to
7//! each value as it is parsed, and records it in the parser's per-rule
8//! `k` bag, where other rule actions can read it. It computes nothing
9//! visible on its own: install it on a grammar that defines the
10//! conventional `val` / `map` / `pair` / `list` / `elem` rules, then read
11//! the path from a rule action of your own.
12//!
13//! This is the Rust port of the canonical TypeScript implementation in
14//! `ts/src/path.ts`; the Go port is `go/path.go`.
15//!
16//! ```
17//! use tabnas::{Tabnas, Value};
18//!
19//! let mut parser = Tabnas::new();
20//! tabnas_json::json(&mut parser)?; // any grammar with val/map/pair/list/elem
21//! tabnas_path::path(&mut parser)?; // the grammar first, then Path
22//!
23//! // A key or scalar as text: keys as themselves, numbers without a
24//! // fractional part, anything else as JSON.
25//! fn text(value: &Value) -> String {
26//! match value {
27//! Value::String(text) => text.clone(),
28//! Value::Number(number) => format!("{number}"),
29//! other => other.to_json().to_string(),
30//! }
31//! }
32//!
33//! // Read the path from a rule action: tag every scalar `<value:path>`.
34//! parser.define_rule("val", |spec| {
35//! spec.add_ac(|rule, _ctx| {
36//! let scalar = match &*rule.node.borrow() {
37//! Value::Object(_) | Value::Array(_) => None,
38//! other => Some(text(other)),
39//! };
40//! if let Some(value) = scalar {
41//! let segments: Vec<String> =
42//! tabnas_path::path_of(rule).iter().map(text).collect();
43//! let tagged = format!("<{value}:{}>", segments.join(","));
44//! rule.node = std::rc::Rc::new(std::cell::RefCell::new(Value::String(tagged)));
45//! }
46//! });
47//! });
48//!
49//! let out = parser.parse(r#"{"a":[1,2]}"#)?;
50//! assert_eq!(
51//! out.to_json(),
52//! serde_json::json!({"a": ["<1:a,0>", "<2:a,1>"]})
53//! );
54//! # Ok::<(), Box<dyn std::error::Error>>(())
55//! ```
56//!
57//! # What it writes
58//!
59//! Only these `k` entries, on the rules of the host grammar:
60//!
61//! | key | value |
62//! |---|---|
63//! | [`PATH`] | a [`Value::Array`] of segments: map keys as strings, array indices as numbers |
64//! | [`PATH_DEPTH`] | the number of segments |
65//! | [`KEY`] | the last segment |
66//! | [`INDEX`] | the current element index inside a list, `-1` before the first element |
67//!
68//! The `k` bag propagates from a rule to the rules it pushes and to the
69//! rule that replaces it, so a value deep in the tree sees the whole
70//! path above it. The root value has an empty path unless the parse meta
71//! seeds one: `parser.parse_with_meta(src, meta)` with
72//! `meta.path.base` set to an array of segments.
73//!
74//! Each level's path is a fresh [`Value::Array`], as in the Go port. The
75//! TypeScript implementation pools and mutates one array per depth, so
76//! its callers must copy a path they keep; here a path read from the
77//! bag is an owned value.
78//!
79//! # How the child's path is set
80//!
81//! The canonical implementation sets the child's path from the parent's
82//! `@pair-ao` / `@elem-ao` hooks (`r.child.k.path = ...`). This engine
83//! hands a parent's after-open hook the child only as an immutable
84//! snapshot, and the child's `k` bag is cloned from the parent's before
85//! that hook runs, so a parent cannot write the child's bag. The port
86//! therefore does the same work one step later, in the child's own
87//! `@val-bo` hook, reading the parent rule's snapshot (which the engine
88//! refreshes after the parent's `ao` phase). The observable `k` values
89//! are the same for the conventional rule set, where `pair` and `elem`
90//! push `val`. See the crate README for what that means for a host
91//! grammar whose `pair` or `elem` pushes a rule of another name.
92
93use tabnas::{
94 Context, GrammarError, GrammarSpec, Plugin, PluginError, Rule, RuleSnapshot, Tabnas, Value,
95};
96
97/// This crate's version. It MUST equal `ts/package.json` "version": the
98/// release orchestrator rewrites both, and `tests/version_test.rs` fails
99/// the build if they drift. Mirrors `VERSION` in `ts/src/path.ts` and
100/// `const VERSION` in `go/path.go`.
101pub const VERSION: &str = "0.3.10";
102
103/// The README's Rust examples run as doctests, so a stale one fails the
104/// gate rather than misleading the reader. Its `toml` and `bash` fences
105/// are skipped; rustdoc runs only the `rust` ones.
106#[cfg(doctest)]
107#[doc = include_str!("../README.md")]
108mod readme_examples {}
109
110/// The error a failed parse produces, re-exported so callers need not
111/// depend on the engine crate directly. The plugin itself raises no
112/// errors and declares no error codes: it contributes only lifecycle
113/// hooks, never alternates, so any error a parse raises comes from the
114/// engine or the host grammar.
115pub use tabnas::TabnasError as PathError;
116
117/// The host-grammar rules the plugin hooks. The engine ships no grammar
118/// of its own, so these names must match the rules supplied by whatever
119/// grammar plugin the consumer installs; the standard
120/// value/map/pair/list/elem rule set uses these names.
121pub const HOOKED_RULES: [&str; 5] = ["val", "map", "pair", "list", "elem"];
122
123/// The `k` key holding the path: a [`Value::Array`] of segments.
124pub const PATH: &str = "path";
125/// The `k` key holding the number of segments in [`PATH`].
126pub const PATH_DEPTH: &str = "pathDepth";
127/// The `k` key holding the last segment: the map key or array index of
128/// the current value.
129pub const KEY: &str = "key";
130/// The `k` key holding the current element index inside a list.
131pub const INDEX: &str = "index";
132
133/// The lifecycle references the plugin registers. They carry the
134/// engine's `/prepend` suffix rather than the bare `@<rule>-<phase>`
135/// name, for reasons that are all specific to this engine:
136///
137/// - Function references are one instance-wide namespace here, looked
138/// up by name at parse time, where the TypeScript engine resolves each
139/// `grammar()` call's `ref` map on its own. A name a host grammar also
140/// registers is overwritten, and the engine wires each name once, so
141/// one of the two hooks is lost. The bare names collide with a host
142/// that registers them; the `/append` names collide with the jsonic
143/// port, which registers `@map-bo/append` and `@list-bo/append`.
144/// - `@val-bo`, `@map-bo` and `@list-bo` are also the names of engine
145/// builtins, which a named action resolves to before any reference
146/// registered through `state_action_ref`.
147/// - The engine wires a `/prepend` reference on its own, without
148/// touching the phase's base or `/append` slot, so a host grammar
149/// installed before or after Path keeps its own hook either way.
150///
151/// The hooks run first in their phase where TypeScript's run last. That
152/// is closer to the canonical order for `val`: there the parent set the
153/// child's path before the child's `bo` ran, so a host `val-bo` sees the
154/// path, as it does here. The other three hooks touch only `k`, which no
155/// host hook of the same phase reads.
156const VAL_BO: &str = "@val-bo/prepend";
157const MAP_BO: &str = "@map-bo/prepend";
158const LIST_BO: &str = "@list-bo/prepend";
159const ELEM_AO: &str = "@elem-ao/prepend";
160
161/// The grammar document: the hooked rules, declared empty. An empty
162/// entry extends an existing rule with nothing, and re-installing it is
163/// what makes the engine wire any registered `@<rule>-<phase>` reference
164/// as a state action, without touching the host grammar's alternates.
165const GRAMMAR: &str = r#"{
166 "rule": { "val": {}, "map": {}, "pair": {}, "list": {}, "elem": {} }
167}"#;
168
169/// The tracked path of a rule, as a slice of segments: map keys as
170/// [`Value::String`], array indices as [`Value::Number`]. Empty for a rule
171/// carrying no path (the root, or a rule reached before the plugin ran).
172///
173/// Takes a snapshot so it reads a parent's path as readily as the current
174/// rule's; a `&Rule` coerces to one.
175pub fn path_of(rule: &RuleSnapshot) -> &[Value] {
176 match rule.k.get(PATH) {
177 Some(Value::Array(segments)) => segments,
178 _ => &[],
179 }
180}
181
182/// Install the plugin: register the lifecycle hooks and declare the
183/// hooked rules so the engine wires them.
184///
185/// Install the host grammar first, then Path, so the hooks land on rules
186/// that already exist. Installed on a bare engine it creates the five
187/// rules empty, and a grammar installed afterwards extends them.
188///
189/// ```
190/// let mut parser = tabnas::Tabnas::new();
191/// tabnas_json::json(&mut parser).unwrap();
192/// tabnas_path::path(&mut parser).unwrap();
193/// // The plugin adds no alternates, so the grammar parses as before.
194/// assert_eq!(
195/// parser.parse(r#"{"a":[1,2]}"#).unwrap().to_json(),
196/// serde_json::json!({"a": [1.0, 2.0]})
197/// );
198/// ```
199pub fn path(parser: &mut Tabnas) -> Result<(), GrammarError> {
200 parser.state_action_ref(VAL_BO, val_before_open);
201 parser.state_action_ref(MAP_BO, map_before_open);
202 parser.state_action_ref(LIST_BO, list_before_open);
203 parser.state_action_ref(ELEM_AO, elem_after_open);
204
205 let spec = GrammarSpec::from_json(GRAMMAR)?;
206 parser.grammar(&spec)?;
207 Ok(())
208}
209
210/// The plugin as a [`Plugin`], for `Tabnas::use_plugin`. Named `Path`,
211/// as the TypeScript export is; it takes no options.
212///
213/// ```
214/// let mut parser = tabnas::Tabnas::new();
215/// tabnas_json::json(&mut parser).unwrap();
216/// parser.use_plugin(tabnas_path::plugin(), None).unwrap();
217/// ```
218pub fn plugin() -> Plugin {
219 Plugin::new("Path", |parser, _options| {
220 path(parser).map_err(|error| PluginError(error.to_string()))
221 })
222}
223
224/// `@val-bo`. At the top level, seed the path: empty, or the base path
225/// the parse meta carries at `meta.path.base`. Below the top level,
226/// adopt the path the pushing `pair` or `elem` rule has for this value.
227fn val_before_open(rule: &mut Rule, context: &mut Context) -> Result<(), tabnas::ActionError> {
228 if rule.d == 0 {
229 let base = base_path(&context.meta);
230 let depth = base.len();
231 let bag = rule.k_mut();
232 bag.insert(PATH.to_string(), Value::array(base));
233 bag.insert(PATH_DEPTH.to_string(), Value::Number(depth as f64));
234 return Ok(());
235 }
236
237 // The parent rule's snapshot, taken after its `ao` phase ran, so an
238 // index `@elem-ao` just advanced is the one read here.
239 let Some(parent) = rule.parent_rule.clone() else {
240 return Ok(());
241 };
242 // Mirrors the canonical `0 < r.d` guard on the pair and elem rules:
243 // the path only starts once the top-level implicit is set up.
244 if parent.d == 0 {
245 return Ok(());
246 }
247
248 match parent.name.as_str() {
249 "pair" if truthy(parent.u.get("pair")) => {
250 let key = parent.u.get(KEY).cloned().unwrap_or(Value::Undefined);
251 adopt(rule, &parent, key.clone(), key, None);
252 }
253 "elem" => {
254 let index = parent.k.get(INDEX).cloned().unwrap_or(Value::Undefined);
255 adopt(rule, &parent, index.clone(), index.clone(), Some(index));
256 }
257 _ => {}
258 }
259 Ok(())
260}
261
262/// `@map-bo`. Not in an array, so no element index to track.
263fn map_before_open(rule: &mut Rule, _context: &mut Context) -> Result<(), tabnas::ActionError> {
264 if rule.k.contains_key(INDEX) {
265 rule.k_mut().remove(INDEX);
266 }
267 Ok(())
268}
269
270/// `@list-bo`. In an array, the path property is the element index,
271/// which starts before the first element.
272fn list_before_open(rule: &mut Rule, _context: &mut Context) -> Result<(), tabnas::ActionError> {
273 rule.k_mut().insert(INDEX.to_string(), Value::Number(-1.0));
274 Ok(())
275}
276
277/// `@elem-ao`. Advance the element index. The pushed `val` reads it from
278/// this rule's snapshot in its own `@val-bo`.
279fn elem_after_open(rule: &mut Rule, _context: &mut Context) -> Result<(), tabnas::ActionError> {
280 if rule.d == 0 {
281 return Ok(());
282 }
283 let next = match rule.k.get(INDEX) {
284 Some(Value::Number(index)) => index + 1.0,
285 _ => 0.0,
286 };
287 rule.k_mut().insert(INDEX.to_string(), Value::Number(next));
288 Ok(())
289}
290
291/// Write the child's entries: the parent's path plus one segment, its
292/// depth, the key, and (inside a list) the index.
293fn adopt(rule: &mut Rule, parent: &RuleSnapshot, segment: Value, key: Value, index: Option<Value>) {
294 let mut segments = path_of(parent).to_vec();
295 segments.push(segment);
296 let depth = segments.len();
297 let bag = rule.k_mut();
298 bag.insert(PATH.to_string(), Value::array(segments));
299 bag.insert(PATH_DEPTH.to_string(), Value::Number(depth as f64));
300 bag.insert(KEY.to_string(), key);
301 if let Some(index) = index {
302 bag.insert(INDEX.to_string(), index);
303 }
304}
305
306/// `meta.path.base` as segments, or none.
307fn base_path(meta: &Value) -> Vec<Value> {
308 let Value::Object(meta) = meta else {
309 return Vec::new();
310 };
311 let Some(Value::Object(path)) = meta.get("path") else {
312 return Vec::new();
313 };
314 match path.get("base") {
315 Some(Value::Array(segments)) => segments.to_vec(),
316 _ => Vec::new(),
317 }
318}
319
320/// JavaScript truthiness, for the `r.u.pair` guard.
321fn truthy(value: Option<&Value>) -> bool {
322 match value {
323 None | Some(Value::Undefined) | Some(Value::Null) => false,
324 Some(Value::Bool(flag)) => *flag,
325 Some(Value::Number(number)) => *number != 0.0 && !number.is_nan(),
326 Some(Value::String(text)) => !text.is_empty(),
327 Some(_) => true,
328 }
329}