Skip to main content

schema_bridge_lshape/
lib.rs

1//! lshape exporter for [schema-bridge](https://crates.io/crates/schema-bridge).
2//!
3//! Turns the schema-bridge `Schema` IR into [lshape](https://github.com/ynishi/lshape)
4//! type definitions — a Lua module built from `T.shape` / `T.array_of` /
5//! `T.one_of` combinators that can be loaded and used with `lshape.check.check`.
6//!
7//! ```rust
8//! use schema_bridge_core::{Field, Schema};
9//! use schema_bridge_lshape::generate_lshape_file;
10//!
11//! let user = Schema::Object(vec![
12//!     Field::new("name", Schema::String),
13//!     Field::optional("email", Schema::String),
14//! ]);
15//! let lua_src = generate_lshape_file(&[("User", user)]).unwrap();
16//! assert!(lua_src.contains("M.User = T.shape({"));
17//! ```
18//!
19//! # lshape version requirement
20//!
21//! Generated modules use `T.integer` / `T.tuple` / the bounds combinators
22//! (`:min` / `:max` / `:min_len` / `:max_len`), which require
23//! **lshape 0.3.0+** at load time (vendored by `mlua-lshape 0.3+`).
24//!
25//! Semantic note: lshape's `T.integer` is the portable whole-number check
26//! (`v % 1 == 0`), so `2.0` passes; Rust-side integer *range* (e.g. `u8`)
27//! is not carried into the schema.
28
29use schema_bridge_core::{Field, Schema};
30
31/// Error produced while mapping a `Schema` to lshape source text.
32#[derive(Debug, Clone, PartialEq)]
33pub enum LshapeError {
34    /// `Schema::Null` outside of a `Union` — lshape has no standalone nil
35    /// type. Nullability is expressed by folding `Union([T, Null])` into
36    /// `T:is_optional()`.
37    StandaloneNull { path: String },
38    /// `Schema::Union` whose only variant is `Null` (or which is empty).
39    EmptyUnion { path: String },
40    /// `Schema::Tuple` with no elements — `T.tuple` requires at least one
41    /// item (unreachable via `#[derive(SchemaBridge)]`, which covers 1-6
42    /// element tuples only).
43    EmptyTuple { path: String },
44}
45
46impl std::fmt::Display for LshapeError {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        match self {
49            LshapeError::StandaloneNull { path } => write!(
50                f,
51                "schema at `{path}` is a standalone Null — lshape has no nil type; \
52                 wrap it in Option<T> / a Union with a non-null variant"
53            ),
54            LshapeError::EmptyUnion { path } => write!(
55                f,
56                "union at `{path}` has no non-null variant to map to lshape"
57            ),
58            LshapeError::EmptyTuple { path } => write!(
59                f,
60                "tuple at `{path}` has no elements — lshape T.tuple requires at least one item"
61            ),
62        }
63    }
64}
65
66impl std::error::Error for LshapeError {}
67
68/// Error produced by [`export_to_lua_file`].
69#[derive(Debug)]
70pub enum ExportError {
71    Map(LshapeError),
72    Io(std::io::Error),
73}
74
75impl std::fmt::Display for ExportError {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            ExportError::Map(e) => write!(f, "{e}"),
79            ExportError::Io(e) => write!(f, "{e}"),
80        }
81    }
82}
83
84impl std::error::Error for ExportError {}
85
86impl From<LshapeError> for ExportError {
87    fn from(e: LshapeError) -> Self {
88        ExportError::Map(e)
89    }
90}
91
92impl From<std::io::Error> for ExportError {
93    fn from(e: std::io::Error) -> Self {
94        ExportError::Io(e)
95    }
96}
97
98const INDENT: &str = "    ";
99
100/// Convert a single `Schema` into an lshape expression such as
101/// `T.shape({ name = T.string })`.
102pub fn schema_to_lshape(schema: &Schema) -> Result<String, LshapeError> {
103    expr(schema, 0, "$")
104}
105
106/// Generate a complete Lua module defining one lshape schema per entry.
107///
108/// The module requires `lshape` (works out of the box under
109/// [`mlua-lshape`](https://crates.io/crates/mlua-lshape)'s `install`, or any
110/// Lua environment where `require("lshape")` resolves) and returns a table
111/// with one key per exported type name.
112pub fn generate_lshape_file(types: &[(&str, Schema)]) -> Result<String, LshapeError> {
113    let mut out = String::new();
114    out.push_str("-- This file is auto-generated by schema-bridge-lshape. Do not edit.\n");
115    out.push_str("local T = require(\"lshape\").t\n\nlocal M = {}\n\n");
116    for (name, schema) in types {
117        let body = expr(schema, 0, name)?;
118        out.push_str(&format!("M.{name} = {body}\n\n"));
119    }
120    out.push_str("return M\n");
121    Ok(out)
122}
123
124/// Generate the lshape module for `types` and write it to `path`.
125pub fn export_to_lua_file(types: &[(&str, Schema)], path: &str) -> Result<(), ExportError> {
126    let content = generate_lshape_file(types)?;
127    std::fs::write(path, content)?;
128    Ok(())
129}
130
131/// Export types (anything deriving `SchemaBridge`) to an lshape Lua module.
132///
133/// ```ignore
134/// export_lshape_types!("types.lua", User, Point)?;
135/// ```
136#[macro_export]
137macro_rules! export_lshape_types {
138    ($path:expr, $($name:ident),+ $(,)?) => {{
139        let types = vec![
140            $((stringify!($name), $name::to_schema()),)+
141        ];
142        $crate::export_to_lua_file(&types, $path)
143    }};
144}
145
146fn expr(schema: &Schema, depth: usize, path: &str) -> Result<String, LshapeError> {
147    match schema {
148        Schema::String => Ok("T.string".to_string()),
149        Schema::Number => Ok("T.number".to_string()),
150        Schema::Integer => Ok("T.integer".to_string()),
151        Schema::Boolean => Ok("T.boolean".to_string()),
152        Schema::Any => Ok("T.any".to_string()),
153        Schema::Null => Err(LshapeError::StandaloneNull {
154            path: path.to_string(),
155        }),
156        Schema::Array(inner) => {
157            let inner = expr(inner, depth, &format!("{path}[]"))?;
158            Ok(format!("T.array_of({inner})"))
159        }
160        Schema::Record { key, value } => {
161            let key = expr(key, depth, &format!("{path}<key>"))?;
162            let value = expr(value, depth, &format!("{path}<value>"))?;
163            Ok(format!("T.map_of({key}, {value})"))
164        }
165        Schema::Enum(values) => Ok(one_of_expr(values)),
166        Schema::Union(variants) => union_expr(variants, depth, path),
167        Schema::Tuple(items) => {
168            if items.is_empty() {
169                return Err(LshapeError::EmptyTuple {
170                    path: path.to_string(),
171                });
172            }
173            let exprs = items
174                .iter()
175                .enumerate()
176                .map(|(i, s)| expr(s, depth, &format!("{path}[{i}]")))
177                .collect::<Result<Vec<_>, _>>()?;
178            Ok(format!("T.tuple({{ {} }})", exprs.join(", ")))
179        }
180        Schema::Ref(name) => Ok(format!("T.ref({})", lua_string(name))),
181        Schema::Object(fields) => shape_expr(fields, depth, path),
182    }
183}
184
185/// `Union([T, Null])` folds to `T:is_optional()`; unions of two or more
186/// non-null variants become `T.any_of({...})`.
187fn union_expr(variants: &[Schema], depth: usize, path: &str) -> Result<String, LshapeError> {
188    let non_null: Vec<&Schema> = variants.iter().filter(|v| **v != Schema::Null).collect();
189    let nullable = non_null.len() != variants.len();
190    let base = match non_null.len() {
191        0 => {
192            return Err(LshapeError::EmptyUnion {
193                path: path.to_string(),
194            })
195        }
196        1 => expr(non_null[0], depth, path)?,
197        _ => {
198            let exprs = non_null
199                .iter()
200                .enumerate()
201                .map(|(i, v)| expr(v, depth, &format!("{path}|{i}")))
202                .collect::<Result<Vec<_>, _>>()?;
203            format!("T.any_of({{ {} }})", exprs.join(", "))
204        }
205    };
206    if nullable {
207        Ok(format!("{base}:is_optional()"))
208    } else {
209        Ok(base)
210    }
211}
212
213fn shape_expr(fields: &[Field], depth: usize, path: &str) -> Result<String, LshapeError> {
214    let field_indent = INDENT.repeat(depth + 1);
215    let close_indent = INDENT.repeat(depth);
216    let mut out = String::from("T.shape({\n");
217    for field in fields {
218        let field_path = format!("{path}.{}", field.name);
219        let mut value = if let Some(one_of) = &field.constraints.one_of {
220            one_of_expr(one_of)
221        } else {
222            expr(&field.schema, depth + 1, &field_path)?
223        };
224        value.push_str(&bounds_suffix(field));
225        if !field.required && !value.ends_with(":is_optional()") {
226            value.push_str(":is_optional()");
227        }
228        out.push_str(&format!(
229            "{field_indent}{} = {value},\n",
230            lua_key(&field.name)
231        ));
232    }
233    out.push_str(&format!("{close_indent}}})"));
234    Ok(out)
235}
236
237fn one_of_expr(values: &[String]) -> String {
238    let quoted: Vec<String> = values.iter().map(|v| lua_string(v)).collect();
239    format!("T.one_of({{ {} }})", quoted.join(", "))
240}
241
242/// Numeric / length constraints map to lshape's bounds combinators
243/// (lshape 0.3+): chained calls merge into a single `bounded` wrapper and
244/// are enforced at check time.
245fn bounds_suffix(field: &Field) -> String {
246    let c = &field.constraints;
247    let mut out = String::new();
248    if let Some(min) = c.min {
249        out.push_str(&format!(":min({min})"));
250    }
251    if let Some(max) = c.max {
252        out.push_str(&format!(":max({max})"));
253    }
254    if let Some(min_len) = c.min_len {
255        out.push_str(&format!(":min_len({min_len})"));
256    }
257    if let Some(max_len) = c.max_len {
258        out.push_str(&format!(":max_len({max_len})"));
259    }
260    out
261}
262
263const LUA_RESERVED: &[&str] = &[
264    "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in",
265    "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while",
266];
267
268fn lua_key(name: &str) -> String {
269    let is_identifier = !name.is_empty()
270        && !name.chars().next().unwrap().is_ascii_digit()
271        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
272        && !LUA_RESERVED.contains(&name);
273    if is_identifier {
274        name.to_string()
275    } else {
276        format!("[{}]", lua_string(name))
277    }
278}
279
280fn lua_string(s: &str) -> String {
281    let mut out = String::with_capacity(s.len() + 2);
282    out.push('"');
283    for c in s.chars() {
284        match c {
285            '"' => out.push_str("\\\""),
286            '\\' => out.push_str("\\\\"),
287            '\n' => out.push_str("\\n"),
288            '\r' => out.push_str("\\r"),
289            '\t' => out.push_str("\\t"),
290            c if (c as u32) < 0x20 => out.push_str(&format!("\\{}", c as u32)),
291            c => out.push(c),
292        }
293    }
294    out.push('"');
295    out
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301    use schema_bridge_core::Constraints;
302
303    fn field_with(name: &str, schema: Schema, constraints: Constraints) -> Field {
304        Field {
305            name: name.into(),
306            schema,
307            required: true,
308            constraints,
309        }
310    }
311
312    #[test]
313    fn primitives() {
314        assert_eq!(schema_to_lshape(&Schema::String).unwrap(), "T.string");
315        assert_eq!(schema_to_lshape(&Schema::Number).unwrap(), "T.number");
316        assert_eq!(schema_to_lshape(&Schema::Boolean).unwrap(), "T.boolean");
317        assert_eq!(schema_to_lshape(&Schema::Any).unwrap(), "T.any");
318    }
319
320    #[test]
321    fn integer_maps_to_t_integer() {
322        assert_eq!(schema_to_lshape(&Schema::Integer).unwrap(), "T.integer");
323    }
324
325    #[test]
326    fn standalone_null_is_an_error() {
327        assert_eq!(
328            schema_to_lshape(&Schema::Null),
329            Err(LshapeError::StandaloneNull { path: "$".into() })
330        );
331    }
332
333    #[test]
334    fn array_and_record() {
335        assert_eq!(
336            schema_to_lshape(&Schema::Array(Box::new(Schema::String))).unwrap(),
337            "T.array_of(T.string)"
338        );
339        let record = Schema::Record {
340            key: Box::new(Schema::String),
341            value: Box::new(Schema::Integer),
342        };
343        assert_eq!(
344            schema_to_lshape(&record).unwrap(),
345            "T.map_of(T.string, T.integer)"
346        );
347    }
348
349    #[test]
350    fn enum_maps_to_one_of() {
351        let schema = Schema::Enum(vec!["active".into(), "inactive".into()]);
352        assert_eq!(
353            schema_to_lshape(&schema).unwrap(),
354            r#"T.one_of({ "active", "inactive" })"#
355        );
356    }
357
358    #[test]
359    fn union_with_null_folds_to_optional() {
360        // Option<String>::to_schema() == Union([String, Null])
361        let schema = Schema::Union(vec![Schema::String, Schema::Null]);
362        assert_eq!(schema_to_lshape(&schema).unwrap(), "T.string:is_optional()");
363    }
364
365    #[test]
366    fn union_without_null_maps_to_any_of() {
367        let schema = Schema::Union(vec![Schema::String, Schema::Number]);
368        assert_eq!(
369            schema_to_lshape(&schema).unwrap(),
370            "T.any_of({ T.string, T.number })"
371        );
372    }
373
374    #[test]
375    fn union_with_null_and_two_variants() {
376        let schema = Schema::Union(vec![Schema::String, Schema::Number, Schema::Null]);
377        assert_eq!(
378            schema_to_lshape(&schema).unwrap(),
379            "T.any_of({ T.string, T.number }):is_optional()"
380        );
381    }
382
383    #[test]
384    fn union_of_only_null_is_an_error() {
385        assert_eq!(
386            schema_to_lshape(&Schema::Union(vec![Schema::Null])),
387            Err(LshapeError::EmptyUnion { path: "$".into() })
388        );
389    }
390
391    #[test]
392    fn tuple_maps_to_t_tuple() {
393        let schema = Schema::Tuple(vec![Schema::String, Schema::Integer]);
394        assert_eq!(
395            schema_to_lshape(&schema).unwrap(),
396            "T.tuple({ T.string, T.integer })"
397        );
398    }
399
400    #[test]
401    fn empty_tuple_is_an_error() {
402        assert_eq!(
403            schema_to_lshape(&Schema::Tuple(vec![])),
404            Err(LshapeError::EmptyTuple { path: "$".into() })
405        );
406    }
407
408    #[test]
409    fn ref_maps_to_t_ref() {
410        assert_eq!(
411            schema_to_lshape(&Schema::Ref("Point".into())).unwrap(),
412            r#"T.ref("Point")"#
413        );
414    }
415
416    #[test]
417    fn object_with_optional_field() {
418        let schema = Schema::Object(vec![
419            Field::new("name", Schema::String),
420            Field::optional("email", Schema::String),
421        ]);
422        let expected = "T.shape({\n    name = T.string,\n    email = T.string:is_optional(),\n})";
423        assert_eq!(schema_to_lshape(&schema).unwrap(), expected);
424    }
425
426    #[test]
427    fn optional_field_with_nullable_schema_does_not_double_wrap() {
428        // #[derive] with Option<T> yields required=false AND Union([T, Null]).
429        let schema = Schema::Object(vec![Field {
430            name: "email".into(),
431            schema: Schema::Union(vec![Schema::String, Schema::Null]),
432            required: false,
433            constraints: Constraints::default(),
434        }]);
435        let out = schema_to_lshape(&schema).unwrap();
436        assert_eq!(out.matches(":is_optional()").count(), 1);
437    }
438
439    #[test]
440    fn field_constraints_become_bounds() {
441        let schema = Schema::Object(vec![field_with(
442            "age",
443            Schema::Integer,
444            Constraints {
445                min: Some(0.0),
446                max: Some(150.0),
447                ..Default::default()
448            },
449        )]);
450        let expected = "T.shape({\n    age = T.integer:min(0):max(150),\n})";
451        assert_eq!(schema_to_lshape(&schema).unwrap(), expected);
452    }
453
454    #[test]
455    fn field_length_constraints_become_len_bounds() {
456        let schema = Schema::Object(vec![field_with(
457            "name",
458            Schema::String,
459            Constraints {
460                min_len: Some(1),
461                max_len: Some(64),
462                ..Default::default()
463            },
464        )]);
465        let expected = "T.shape({\n    name = T.string:min_len(1):max_len(64),\n})";
466        assert_eq!(schema_to_lshape(&schema).unwrap(), expected);
467    }
468
469    #[test]
470    fn field_one_of_constraint_overrides_base_type() {
471        let schema = Schema::Object(vec![field_with(
472            "status",
473            Schema::String,
474            Constraints {
475                one_of: Some(vec!["on".into(), "off".into()]),
476                ..Default::default()
477            },
478        )]);
479        let expected = "T.shape({\n    status = T.one_of({ \"on\", \"off\" }),\n})";
480        assert_eq!(schema_to_lshape(&schema).unwrap(), expected);
481    }
482
483    #[test]
484    fn nested_object_indents() {
485        let schema = Schema::Object(vec![Field::new(
486            "point",
487            Schema::Object(vec![Field::new("x", Schema::Number)]),
488        )]);
489        let expected = "T.shape({\n    point = T.shape({\n        x = T.number,\n    }),\n})";
490        assert_eq!(schema_to_lshape(&schema).unwrap(), expected);
491    }
492
493    #[test]
494    fn non_identifier_and_reserved_keys_are_bracketed() {
495        let schema = Schema::Object(vec![
496            Field::new("valid_key", Schema::String),
497            Field::new("kebab-case", Schema::String),
498            Field::new("end", Schema::String),
499        ]);
500        let out = schema_to_lshape(&schema).unwrap();
501        assert!(out.contains("    valid_key = T.string,"));
502        assert!(out.contains("    [\"kebab-case\"] = T.string,"));
503        assert!(out.contains("    [\"end\"] = T.string,"));
504    }
505
506    #[test]
507    fn lua_string_escapes() {
508        assert_eq!(lua_string(r#"a"b\c"#), r#""a\"b\\c""#);
509        assert_eq!(lua_string("a\nb"), r#""a\nb""#);
510    }
511
512    #[test]
513    fn error_path_points_at_field() {
514        let schema = Schema::Object(vec![Field::new("bad", Schema::Null)]);
515        assert_eq!(
516            schema_to_lshape(&schema),
517            Err(LshapeError::StandaloneNull {
518                path: "$.bad".into()
519            })
520        );
521    }
522
523    #[test]
524    fn generate_file_layout() {
525        let types = vec![
526            (
527                "User",
528                Schema::Object(vec![Field::new("name", Schema::String)]),
529            ),
530            ("Id", Schema::String),
531        ];
532        let out = generate_lshape_file(&types).unwrap();
533        assert!(out
534            .starts_with("-- This file is auto-generated by schema-bridge-lshape. Do not edit.\n"));
535        assert!(out.contains("local T = require(\"lshape\").t\n"));
536        assert!(out.contains("M.User = T.shape({\n    name = T.string,\n})\n"));
537        assert!(out.contains("M.Id = T.string\n"));
538        assert!(out.ends_with("return M\n"));
539    }
540}