Skip to main content

mlua_swarm_dsl/
lib.rs

1//! Lua internal DSL for Blueprint authoring (`flow_dsl` + `bp_dsl`).
2//!
3//! Raw AST (JSON) authoring cost is high at real Blueprint scale (hundreds
4//! of lines and deep nesting for a multi-stage flow) — that cost motivated
5//! this module. `flow_dsl.lua` (flow.ir vocabulary) and `bp_dsl.lua`
6//! (Blueprint vocabulary, depends on `flow_dsl`) are baked into this
7//! binary via `include_str!` and preloaded into a fresh `mlua::Lua` VM so
8//! `require("flow_dsl")` / `require("bp_dsl")` resolve without touching
9//! the filesystem. The `flow-ir` / `mlua-swarm-schema` crates are not
10//! touched by this module — canonical JSON stays the wire format; the DSL
11//! is purely an authoring-time convenience that emits it.
12//!
13//! # Crate positioning
14//!
15//! This crate is the DSL frontend only (`.bp.lua` → `serde_json::Value`).
16//! The compile pipeline (linker → shape lint → BPReady) lives in the
17//! sibling `mlua-swarm-compile` crate, which consumes the JSON this crate
18//! produces. `mlua-swarm-schema` (types) stays free of the `mlua` runtime
19//! dep so that consumers who only need type surfaces (e.g. the server's
20//! wire codec) do not transitively pull the Lua interpreter.
21
22const FLOW_DSL_SRC: &str = include_str!("flow_dsl.lua");
23const BP_DSL_SRC: &str = include_str!("bp_dsl.lua");
24
25/// The wire-level key `F.obj()` (`flow_dsl.lua`) emits — must match the
26/// Lua-side `M.EMPTY_OBJECT_MARKER_KEY` literal exactly.
27const EMPTY_OBJECT_MARKER_KEY: &str = "__mse_empty_object__";
28
29/// Walk `value` in place and replace every JSON object shaped exactly
30/// like `{ "<EMPTY_OBJECT_MARKER_KEY>": true }` (the wire shape `F.obj()`
31/// emits) with a genuine empty JSON object (`{}`). Limited to that exact
32/// single-key shape so an ordinary data field that happens to carry a key
33/// with the same name is left untouched.
34fn replace_empty_object_markers(value: &mut serde_json::Value) {
35    match value {
36        serde_json::Value::Object(map) => {
37            let is_marker = map.len() == 1
38                && map.get(EMPTY_OBJECT_MARKER_KEY) == Some(&serde_json::Value::Bool(true));
39            if is_marker {
40                *value = serde_json::Value::Object(serde_json::Map::new());
41                return;
42            }
43            for v in map.values_mut() {
44                replace_empty_object_markers(v);
45            }
46        }
47        serde_json::Value::Array(arr) => {
48            for v in arr.iter_mut() {
49                replace_empty_object_markers(v);
50            }
51        }
52        _ => {}
53    }
54}
55
56/// Register `flow_dsl` and `bp_dsl` in `lua`'s `package.preload` table so
57/// `require("flow_dsl")` / `require("bp_dsl")` resolve to the baked-in Lua
58/// source. Idempotent to call more than once on the same `Lua` (each call
59/// simply re-sets the same two `preload` entries).
60pub fn preload(lua: &mlua::Lua) -> mlua::Result<()> {
61    let package: mlua::Table = lua.globals().get("package")?;
62    let preload: mlua::Table = package.get("preload")?;
63
64    preload.set(
65        "flow_dsl",
66        lua.create_function(|lua, ()| {
67            lua.load(FLOW_DSL_SRC)
68                .set_name("flow_dsl.lua")
69                .eval::<mlua::Value>()
70        })?,
71    )?;
72    preload.set(
73        "bp_dsl",
74        lua.create_function(|lua, ()| {
75            lua.load(BP_DSL_SRC)
76                .set_name("bp_dsl.lua")
77                .eval::<mlua::Value>()
78        })?,
79    )?;
80    Ok(())
81}
82
83/// Run a `.bp.lua` DSL script (source text, not a file path) in a fresh
84/// `mlua::Lua` VM and return its result as `serde_json::Value`.
85///
86/// The script is expected to `require("flow_dsl")` and/or
87/// `require("bp_dsl")` and `return` a Blueprint-shaped (or Expr/Node
88/// -shaped, for narrower scripts) Lua table as its last expression.
89///
90/// Empty Lua tables are treated as empty JSON arrays rather than empty
91/// objects (`encode_empty_tables_as_array`) — every plain empty table this
92/// DSL can emit is a `Node`/`Expr` list field (`seq.children`, `and.args`,
93/// `or.args`), never a legitimately-empty JSON object. A field that must
94/// serialize as an empty JSON object uses the `F.obj()` marker
95/// (`flow_dsl.lua`) instead of a bare `{}` table literal; this function
96/// replaces every occurrence of that marker with a genuine empty JSON
97/// object as a post-pass (`replace_empty_object_markers`) over the
98/// converted value.
99pub fn build_bp_from_script(script: &str) -> anyhow::Result<serde_json::Value> {
100    use mlua::LuaSerdeExt;
101
102    // `mlua::Error` wraps a boxed `dyn std::error::Error` without a
103    // `Send + Sync` bound, so it does not satisfy anyhow's blanket `From`
104    // impl (`?` cannot convert it directly) — stringify explicitly instead.
105    let lua = mlua::Lua::new();
106    preload(&lua).map_err(|e| anyhow::anyhow!("dsl preload failed: {e}"))?;
107    let result: mlua::Value = lua
108        .load(script)
109        .set_name("<bp-script>")
110        .eval()
111        .map_err(|e| anyhow::anyhow!("bp-script eval failed: {e}"))?;
112    let options = mlua::serde::de::Options::new().encode_empty_tables_as_array(true);
113    let mut value: serde_json::Value = lua
114        .from_value_with(result, options)
115        .map_err(|e| anyhow::anyhow!("lua value -> json conversion failed: {e}"))?;
116    replace_empty_object_markers(&mut value);
117    Ok(value)
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn preload_exposes_flow_dsl_and_bp_dsl() {
126        let lua = mlua::Lua::new();
127        preload(&lua).expect("preload must succeed");
128        let ok: bool = lua
129            .load(
130                r#"
131                local F = require("flow_dsl")
132                local B = require("bp_dsl")
133                return F ~= nil and B ~= nil
134                "#,
135            )
136            .eval()
137            .expect("require must succeed for both modules");
138        assert!(ok, "flow_dsl / bp_dsl must both resolve via require()");
139    }
140
141    #[test]
142    fn build_bp_from_script_returns_json_value() {
143        let out = build_bp_from_script(
144            r#"
145            local F = require("flow_dsl")
146            return { id = "t", flow = F.assign{ at = F.p("$.x"), value = F.lit(1) } }
147            "#,
148        )
149        .expect("script must build");
150        assert_eq!(out["id"], serde_json::json!("t"));
151        assert_eq!(out["flow"]["kind"], serde_json::json!("assign"));
152        assert_eq!(
153            out["flow"]["at"],
154            serde_json::json!({"op": "path", "at": "$.x"})
155        );
156    }
157
158    #[test]
159    fn build_bp_from_script_surfaces_lua_errors() {
160        let err = build_bp_from_script("error(\"boom\")").expect_err("must propagate the error");
161        assert!(err.to_string().contains("boom"));
162    }
163
164    #[test]
165    fn f_obj_marker_becomes_a_genuine_empty_json_object() {
166        let out = build_bp_from_script(
167            r#"
168            local F = require("flow_dsl")
169            return { spec = F.obj(), other = {} }
170            "#,
171        )
172        .expect("script must build");
173        assert_eq!(out["spec"], serde_json::json!({}));
174        assert!(
175            out["spec"].is_object(),
176            "F.obj() must become an object, not an array"
177        );
178        // A plain empty Lua table is still converted to an empty JSON
179        // array (the pre-existing `encode_empty_tables_as_array` rule),
180        // proving the marker replacement is scoped to `F.obj()`'s exact
181        // one-key shape and does not affect ordinary empty tables.
182        assert_eq!(out["other"], serde_json::json!([]));
183    }
184
185    #[test]
186    fn empty_object_marker_replacement_does_not_misfire_on_ordinary_data() {
187        // A field that legitimately reuses the marker key name for
188        // something other than `true` (or carries sibling keys) must not
189        // be collapsed to `{}`.
190        let out = build_bp_from_script(
191            r#"
192            return {
193              a = { __mse_empty_object__ = false },
194              b = { __mse_empty_object__ = true, extra = 1 },
195            }
196            "#,
197        )
198        .expect("script must build");
199        assert_eq!(out["a"], serde_json::json!({"__mse_empty_object__": false}));
200        assert_eq!(
201            out["b"],
202            serde_json::json!({"__mse_empty_object__": true, "extra": 1})
203        );
204    }
205}