rspyts-cli 0.3.2

The rspyts code generator: emits pydantic models, TypeScript types, and JSON Schema from a bridged Rust crate.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Shared helpers for the three emitters: headers, hashing, casing,
//! and the Python/TypeScript projections of [`Ty`].

use heck::{ToLowerCamelCase, ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
use rspyts_core::ir::{Dtype, Manifest, Ty, TypeDecl};

/// The rspyts version stamped into every generated file header.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Portable provenance stamped into every generated file.
pub struct Provenance<'a> {
    pub manifest_hash: &'a str,
    pub rust_source: &'a str,
}

/// Canonical manifest fingerprint used in every generated file.
pub fn manifest_hash_hex(manifest: &Manifest) -> String {
    rspyts_core::manifest_fingerprint(manifest)
}

/// The generated-code warning and Rust provenance for Python files.
pub fn py_header(provenance: &Provenance<'_>) -> String {
    format!(
        "# =============================================================================\n\
# Code generated by rspyts v{VERSION}. DO NOT EDIT THIS FILE.\n\
# Edit the Rust source tree instead: {}\n\
# Then regenerate these bindings with rspyts.\n\
# rspyts:manifest-hash sha256:{}\n\
# =============================================================================\n",
        provenance.rust_source, provenance.manifest_hash,
    )
}

/// The generated-code warning and Rust provenance for TypeScript files.
pub fn ts_header(provenance: &Provenance<'_>) -> String {
    format!(
        "// ============================================================================\n\
// Code generated by rspyts v{VERSION}. DO NOT EDIT THIS FILE.\n\
// Edit the Rust source tree instead: {}\n\
// Then regenerate these bindings with rspyts.\n\
// rspyts:manifest-hash sha256:{}\n\
// ============================================================================\n",
        provenance.rust_source, provenance.manifest_hash,
    )
}

/// The marker `generate` requires in a file's first line before it will
/// delete it as no-longer-emitted, and `check` uses to spot strays.
pub const GENERATED_MARKER: &str = "Code generated by rspyts";

/// `demo-crate` → `DemoCrate` (for `{PascalCrateName}Client`).
pub fn pascal(name: &str) -> String {
    name.to_upper_camel_case()
}

/// Public Python registry emitted for an application-error enum.
///
/// Kept here rather than in the Python emitter because manifest validation
/// must reserve the exact same synthesized name before any files are written.
pub(crate) fn py_error_registry_name(name: &str) -> String {
    let shouty = name.to_shouty_snake_case();
    let base = shouty.strip_suffix("_ERROR").unwrap_or(&shouty);
    format!("{base}_ERROR_TYPES")
}

/// Public TypeScript registry emitted for an application-error enum.
///
/// `Foo` and `FooError` deliberately project to the same registry name; the
/// validator diagnoses that collision before emission.
pub(crate) fn ts_error_registry_name(name: &str) -> String {
    let base = name.strip_suffix("Error").unwrap_or(name);
    format!("{base}ErrorTypes")
}

/// Arbitrary contract name → a stable Python identifier, with a trailing
/// underscore for keywords. Invalid/empty starts are prefixed because
/// pydantic does not treat leading-underscore names as model fields.
pub fn py_name(name: &str) -> String {
    let source = name.strip_prefix("r#").unwrap_or(name);
    let mut snake: String = source
        .to_snake_case()
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || ch == '_' {
                ch
            } else {
                '_'
            }
        })
        .collect();
    if snake.is_empty() {
        snake.push_str("field");
    }
    if snake.starts_with('_') || snake.starts_with(|ch: char| ch.is_ascii_digit()) {
        snake = format!("field_{snake}");
    }
    if PY_KEYWORDS.contains(&snake.as_str()) {
        format!("{snake}_")
    } else {
        snake
    }
}

/// Would pydantic's `to_camel` alias generator round-trip this Python
/// name back to `wire`? When not, the field needs an explicit alias.
pub fn py_alias_roundtrips(py_name: &str, wire: &str) -> bool {
    py_name.to_lower_camel_case() == wire
}

const PY_KEYWORDS: &[&str] = &[
    "false", "none", "true", "and", "as", "assert", "async", "await", "break", "class", "continue",
    "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import",
    "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while",
    "with", "yield",
];

/// Inclusive integer bounds for bounded scalar kinds.
pub fn int_bounds(ty: &Ty) -> Option<(i64, u64)> {
    match ty {
        Ty::U8 => Some((0, u8::MAX as u64)),
        Ty::U16 => Some((0, u16::MAX as u64)),
        Ty::U32 => Some((0, u32::MAX as u64)),
        Ty::I8 => Some((i8::MIN as i64, i8::MAX as u64)),
        Ty::I16 => Some((i16::MIN as i64, i16::MAX as u64)),
        Ty::I32 => Some((i32::MIN as i64, i32::MAX as u64)),
        _ => None,
    }
}

/// The TypeScript typed-array class for a dtype.
pub fn ts_typed_array(dt: Dtype) -> &'static str {
    match dt {
        Dtype::U8 => "Uint8Array",
        Dtype::I8 => "Int8Array",
        Dtype::U16 => "Uint16Array",
        Dtype::I16 => "Int16Array",
        Dtype::U32 => "Uint32Array",
        Dtype::I32 => "Int32Array",
        Dtype::U64 => "BigUint64Array",
        Dtype::I64 => "BigInt64Array",
        Dtype::F32 => "Float32Array",
        Dtype::F64 => "Float64Array",
    }
}

/// Look up a named type declaration.
pub fn find_type<'m>(m: &'m Manifest, name: &str) -> Option<&'m TypeDecl> {
    m.types.iter().find(|t| t.name() == name)
}

/// Python annotation for `ty`.
///
/// `bounds`: emit `typing.Annotated[int, pydantic.Field(ge=…, le=…)]` for bounded
/// integers (model fields) instead of plain `int` (signatures).
/// `quote`: names that must be forward-referenced as `"Name"` because
/// they are not yet defined at this point in `models.py`.
pub fn py_type(ty: &Ty, bounds: bool, quote: &dyn Fn(&str) -> bool) -> String {
    match ty {
        Ty::Bool => "bool".into(),
        Ty::U8 | Ty::U16 | Ty::U32 | Ty::I8 | Ty::I16 | Ty::I32 => {
            if bounds {
                let (lo, hi) = int_bounds(ty).expect("bounded integer kind");
                format!("typing.Annotated[int, pydantic.Field(ge={lo}, le={hi})]")
            } else {
                "int".into()
            }
        }
        Ty::I64 | Ty::U64 => "int".into(),
        Ty::F32 | Ty::F64 => "float".into(),
        Ty::String => "str".into(),
        Ty::Bytes => "bytes".into(),
        Ty::Unit => "None".into(),
        Ty::Null => "None".into(),
        Ty::Option { inner } => {
            let inner = py_type(inner, bounds, quote);
            // `Null`, `Unit`, and a nested option-like type already include
            // Python's null member. Repeating it produces invalid/counterfeit
            // annotations such as `None | None` without adding information.
            if inner == "None" || inner.ends_with(" | None") {
                inner
            } else {
                format!("{inner} | None")
            }
        }
        Ty::List { inner } => format!("list[{}]", py_type(inner, bounds, quote)),
        Ty::Map { value } => format!("dict[str, {}]", py_type(value, bounds, quote)),
        Ty::Tuple { items } => format!(
            "tuple[{}]",
            items
                .iter()
                .map(|item| py_type(item, bounds, quote))
                .collect::<Vec<_>>()
                .join(", ")
        ),
        Ty::Ref { name } => {
            if quote(name) {
                format!("\"{name}\"")
            } else {
                name.clone()
            }
        }
        Ty::Json => "typing.Any".into(),
        Ty::Buf { .. } | Ty::Slice { .. } => "np.ndarray".into(),
    }
}

/// TypeScript type for `ty`. `Unit` renders as `void` (return-only).
pub fn ts_type(ty: &Ty) -> String {
    match ty {
        Ty::Bool => "boolean".into(),
        Ty::U8 | Ty::U16 | Ty::U32 | Ty::I8 | Ty::I16 | Ty::I32 | Ty::F32 | Ty::F64 => {
            "number".into()
        }
        Ty::I64 | Ty::U64 => "bigint".into(),
        Ty::String => "string".into(),
        Ty::Bytes => "Uint8Array".into(),
        Ty::Unit => "void".into(),
        Ty::Null => "null".into(),
        Ty::Option { inner } => {
            let inner = ts_type(inner);
            if inner == "null" || inner.ends_with(" | null") {
                inner
            } else {
                format!("{inner} | null")
            }
        }
        Ty::List { inner } => {
            let inner = ts_type(inner);
            if inner.contains(' ') {
                format!("({inner})[]")
            } else {
                format!("{inner}[]")
            }
        }
        Ty::Map { value } => format!("Record<string, {}>", ts_type(value)),
        Ty::Tuple { items } => format!(
            "[{}]",
            items.iter().map(ts_type).collect::<Vec<_>>().join(", ")
        ),
        Ty::Ref { name } => name.clone(),
        Ty::Json => "unknown".into(),
        Ty::Buf { dt } | Ty::Slice { dt } => ts_typed_array(*dt).into(),
    }
}

/// Collect the names of every `Ty::Ref` in `ty` into `out` (recursive).
pub fn collect_refs(ty: &Ty, out: &mut std::collections::BTreeSet<String>) {
    match ty {
        Ty::Ref { name } => {
            out.insert(name.clone());
        }
        Ty::Option { inner } | Ty::List { inner } => collect_refs(inner, out),
        Ty::Map { value } => collect_refs(value, out),
        Ty::Tuple { items } => {
            for item in items {
                collect_refs(item, out);
            }
        }
        _ => {}
    }
}

/// Split docs into trimmed lines, dropping leading/trailing empties.
pub fn doc_lines(docs: &str) -> Vec<&str> {
    let lines: Vec<&str> = docs.lines().map(str::trim_end).collect();
    let start = lines.iter().position(|l| !l.trim().is_empty());
    let Some(start) = start else {
        return Vec::new();
    };
    let end = lines
        .iter()
        .rposition(|l| !l.trim().is_empty())
        .expect("start exists");
    lines[start..=end].to_vec()
}

/// A Python docstring block at `indent`, or empty when no docs. Always
/// multiline: the quotes sit on their own lines, never around the text.
pub fn py_docstring(docs: &str, indent: &str) -> String {
    let lines = doc_lines(docs);
    if lines.is_empty() {
        return String::new();
    }
    let escape = |s: &str| s.replace('\\', "\\\\").replace("\"\"\"", "\\\"\\\"\\\"");
    let mut out = format!("{indent}\"\"\"\n");
    for line in &lines {
        if line.trim().is_empty() {
            out.push('\n');
        } else {
            out.push_str(indent);
            out.push_str(&escape(line));
            out.push('\n');
        }
    }
    out.push_str(indent);
    out.push_str("\"\"\"\n");
    out
}

/// A TypeScript `/** … */` doc comment at `indent` from raw lines, or
/// empty when there are none.
pub fn ts_doc_from_lines(lines: &[String], indent: &str) -> String {
    if lines.is_empty() {
        return String::new();
    }
    let escape = |s: &str| s.replace("*/", "*\\/");
    if lines.len() == 1 {
        return format!("{indent}/** {} */\n", escape(&lines[0]));
    }
    let mut out = format!("{indent}/**\n");
    for line in lines {
        if line.trim().is_empty() {
            out.push_str(indent);
            out.push_str(" *\n");
        } else {
            out.push_str(indent);
            out.push_str(" * ");
            out.push_str(&escape(line));
            out.push('\n');
        }
    }
    out.push_str(indent);
    out.push_str(" */\n");
    out
}

/// A TypeScript doc comment from a manifest docs string.
pub fn ts_doc(docs: &str, indent: &str) -> String {
    let lines: Vec<String> = doc_lines(docs).into_iter().map(str::to_string).collect();
    ts_doc_from_lines(&lines, indent)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hash_delegates_to_the_core_manifest_fingerprint() {
        let manifest = super::super::test_manifest::manifest();
        assert_eq!(
            manifest_hash_hex(&manifest),
            rspyts_core::manifest_fingerprint(&manifest)
        );
    }

    #[test]
    fn py_name_snake_cases_and_avoids_keywords() {
        assert_eq!(py_name("minimumValue"), "minimum_value");
        assert_eq!(py_name("class"), "class_");
        assert!(py_alias_roundtrips("minimum_value", "minimumValue"));
        // pydantic's to_camel drops the trailing underscore, just like
        // heck: keyword-renamed attributes need no explicit alias.
        assert!(py_alias_roundtrips("class_", "class"));
        assert!(!py_alias_roundtrips("kind", "Type"));
    }

    #[test]
    fn ts_list_of_union_is_parenthesized() {
        let ty = Ty::List {
            inner: Box::new(Ty::Option {
                inner: Box::new(Ty::F64),
            }),
        };
        assert_eq!(ts_type(&ty), "(number | null)[]");
    }

    #[test]
    fn py_nested_bounded_int_uses_annotated() {
        let ty = Ty::List {
            inner: Box::new(Ty::U8),
        };
        assert_eq!(
            py_type(&ty, true, &|_| false),
            "list[typing.Annotated[int, pydantic.Field(ge=0, le=255)]]"
        );
        assert_eq!(py_type(&ty, false, &|_| false), "list[int]");

        let nullable = Ty::Option {
            inner: Box::new(Ty::U8),
        };
        assert_eq!(
            py_type(&nullable, true, &|_| false),
            "typing.Annotated[int, pydantic.Field(ge=0, le=255)] | None"
        );
    }

    #[test]
    fn python_null_wrappers_collapse_to_a_single_none_type() {
        let option_null = Ty::Option {
            inner: Box::new(Ty::Null),
        };
        let nested = Ty::Option {
            inner: Box::new(Ty::Option {
                inner: Box::new(Ty::String),
            }),
        };

        assert_eq!(py_type(&option_null, false, &|_| false), "None");
        assert_eq!(py_type(&nested, false, &|_| false), "str | None");

        assert_eq!(ts_type(&option_null), "null");
        assert_eq!(ts_type(&nested), "string | null");
    }

    #[test]
    fn option_reference_collection_is_recursive() {
        let ty = Ty::Option {
            inner: Box::new(Ty::List {
                inner: Box::new(Ty::Ref {
                    name: "Nested".to_string(),
                }),
            }),
        };
        let mut refs = std::collections::BTreeSet::new();
        collect_refs(&ty, &mut refs);
        assert_eq!(refs.into_iter().collect::<Vec<_>>(), vec!["Nested"]);
    }

    #[test]
    fn python_projects_native_exact_integers_and_json() {
        assert_eq!(py_type(&Ty::I64, false, &|_| false), "int");
        assert_eq!(py_type(&Ty::U64, false, &|_| false), "int");
        assert_eq!(py_type(&Ty::Json, false, &|_| false), "typing.Any");
    }

    #[test]
    fn multiline_docs_render_in_both_languages() {
        let docs = "First line.\n\nSecond paragraph.";
        assert_eq!(
            py_docstring(docs, "    "),
            "    \"\"\"\n    First line.\n\n    Second paragraph.\n    \"\"\"\n"
        );
        assert_eq!(
            ts_doc(docs, ""),
            "/**\n * First line.\n *\n * Second paragraph.\n */\n"
        );
    }
}