Skip to main content

Crate tabnas_path

Crate tabnas_path 

Source
Expand description

Property-path tracking for the tabnas parsing engine.

This is a behaviour plugin, not a grammar plugin. It tracks the property path, the chain of map keys and array indices leading to each value as it is parsed, and records it in the parser’s per-rule k bag, where other rule actions can read it. It computes nothing visible on its own: install it on a grammar that defines the conventional val / map / pair / list / elem rules, then read the path from a rule action of your own.

This is the Rust port of the canonical TypeScript implementation in ts/src/path.ts; the Go port is go/path.go.

use tabnas::{Tabnas, Value};

let mut parser = Tabnas::new();
tabnas_json::json(&mut parser)?;   // any grammar with val/map/pair/list/elem
tabnas_path::path(&mut parser)?;   // the grammar first, then Path

// A key or scalar as text: keys as themselves, numbers without a
// fractional part, anything else as JSON.
fn text(value: &Value) -> String {
    match value {
        Value::String(text) => text.clone(),
        Value::Number(number) => format!("{number}"),
        other => other.to_json().to_string(),
    }
}

// Read the path from a rule action: tag every scalar `<value:path>`.
parser.define_rule("val", |spec| {
    spec.add_ac(|rule, _ctx| {
        let scalar = match &*rule.node.borrow() {
            Value::Object(_) | Value::Array(_) => None,
            other => Some(text(other)),
        };
        if let Some(value) = scalar {
            let segments: Vec<String> =
                tabnas_path::path_of(rule).iter().map(text).collect();
            let tagged = format!("<{value}:{}>", segments.join(","));
            rule.node = std::rc::Rc::new(std::cell::RefCell::new(Value::String(tagged)));
        }
    });
});

let out = parser.parse(r#"{"a":[1,2]}"#)?;
assert_eq!(
    out.to_json(),
    serde_json::json!({"a": ["<1:a,0>", "<2:a,1>"]})
);

§What it writes

Only these k entries, on the rules of the host grammar:

keyvalue
PATHa Value::Array of segments: map keys as strings, array indices as numbers
PATH_DEPTHthe number of segments
KEYthe last segment
INDEXthe current element index inside a list, -1 before the first element

The k bag propagates from a rule to the rules it pushes and to the rule that replaces it, so a value deep in the tree sees the whole path above it. The root value has an empty path unless the parse meta seeds one: parser.parse_with_meta(src, meta) with meta.path.base set to an array of segments.

Each level’s path is a fresh Value::Array, as in the Go port. The TypeScript implementation pools and mutates one array per depth, so its callers must copy a path they keep; here a path read from the bag is an owned value.

§How the child’s path is set

The canonical implementation sets the child’s path from the parent’s @pair-ao / @elem-ao hooks (r.child.k.path = ...). This engine hands a parent’s after-open hook the child only as an immutable snapshot, and the child’s k bag is cloned from the parent’s before that hook runs, so a parent cannot write the child’s bag. The port therefore does the same work one step later, in the child’s own @val-bo hook, reading the parent rule’s snapshot (which the engine refreshes after the parent’s ao phase). The observable k values are the same for the conventional rule set, where pair and elem push val. See the crate README for what that means for a host grammar whose pair or elem pushes a rule of another name.

Structs§

PathError
The error a failed parse produces, re-exported so callers need not depend on the engine crate directly. The plugin itself raises no errors and declares no error codes: it contributes only lifecycle hooks, never alternates, so any error a parse raises comes from the engine or the host grammar.

Constants§

HOOKED_RULES
The host-grammar rules the plugin hooks. The engine ships no grammar of its own, so these names must match the rules supplied by whatever grammar plugin the consumer installs; the standard value/map/pair/list/elem rule set uses these names.
INDEX
The k key holding the current element index inside a list.
KEY
The k key holding the last segment: the map key or array index of the current value.
PATH
The k key holding the path: a Value::Array of segments.
PATH_DEPTH
The k key holding the number of segments in PATH.
VERSION
This crate’s version. It MUST equal ts/package.json “version”: the release orchestrator rewrites both, and tests/version_test.rs fails the build if they drift. Mirrors VERSION in ts/src/path.ts and const VERSION in go/path.go.

Functions§

path
Install the plugin: register the lifecycle hooks and declare the hooked rules so the engine wires them.
path_of
The tracked path of a rule, as a slice of segments: map keys as Value::String, array indices as Value::Number. Empty for a rule carrying no path (the root, or a rule reached before the plugin ran).
plugin
The plugin as a Plugin, for Tabnas::use_plugin. Named Path, as the TypeScript export is; it takes no options.