Skip to main content

rust_anything/
codegen.rs

1//! Code generation for a bridge crate: port stubs from TS signatures, and the binding layer
2//! (`lib.rs`, `index.cjs`) from the port's Rust signatures.
3//!
4//! The binding layer follows `port.rs`, not the TS: change a port's types, run
5//! `rust-anything refresh`, and the bindings and loader follow. Values cross three ways:
6//!
7//! - native: strings, numbers, booleans and lists or options of those, with no extra cost;
8//! - JSON text: anything structured, as one string each way (`JSON.parse` is fast in V8), with
9//!   markers for what JSON lacks (`undefined`, NaN, lone surrogates; see `js.rs`);
10//! - UTF-16 units: a `Vec<u16>` return, for strings that may hold lone surrogates.
11
12use std::fmt::Write as _;
13
14use crate::bridge::{Kind, Manifest, RType, param_type, snake_case};
15use crate::ts::exports::ExportedFn;
16
17/// A port function, as declared in `port.rs`.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct PortFn {
20    pub js_name: String,
21    pub rust_name: String,
22    pub params: Vec<(String, String)>,
23    /// The success type, `()` for none.
24    pub ret: String,
25    /// Returns `Result<T, String>`; an `Err` becomes a thrown JS error.
26    pub fallible: bool,
27    pub is_async: bool,
28}
29
30/// A port class: a struct with `new` and methods taking `&self` or `&mut self`.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct PortClass {
33    pub js_name: String,
34    pub rust_name: String,
35    pub constructor: PortFn,
36    pub methods: Vec<(PortFn, bool)>,
37}
38
39/// What `port.rs` offers to JS. `methods` pairs each method with whether it takes `&mut self`.
40#[derive(Clone, Debug, Default, PartialEq, Eq)]
41pub struct PortApi {
42    pub functions: Vec<PortFn>,
43    pub classes: Vec<PortClass>,
44    /// Every `pub struct` of `port.rs` (a batch uses `<Name>Index` when the port defines one).
45    pub structs: Vec<String>,
46    /// The structs whose `impl` has a `pub fn rank` (an index that ranks by itself).
47    pub ranked: Vec<String>,
48}
49
50impl PortApi {
51    /// Every function and method, for dependency and wire checks.
52    pub fn all(&self) -> impl Iterator<Item = &PortFn> {
53        self.functions.iter().chain(
54            self.classes.iter().flat_map(|c| {
55                std::iter::once(&c.constructor).chain(c.methods.iter().map(|(m, _)| m))
56            }),
57        )
58    }
59
60    pub fn needs_json(&self) -> bool {
61        self.all().any(|f| {
62            wire(&f.ret) == Wire::Json || f.params.iter().any(|(_, t)| wire(t) == Wire::Json)
63        })
64    }
65}
66
67/// How a Rust type crosses the bridge.
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub enum Wire {
70    Native,
71    Json,
72    Units,
73}
74
75pub fn wire(ty: &str) -> Wire {
76    let ty: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
77    match ty.as_str() {
78        "String" | "f64" | "i64" | "bool" | "()" | "Vec<String>" | "Vec<f64>" | "Vec<i64>"
79        | "Option<String>" | "Option<f64>" | "Option<i64>" | "Option<bool>" => Wire::Native,
80        "Vec<u16>" => Wire::Units,
81        _ => Wire::Json,
82    }
83}
84
85// ---- port.rs stubs ---------------------------------------------------------------------------
86
87/// `port.rs` with one stub per export, typed from the TS signature.
88pub fn port_rs(m: &Manifest) -> String {
89    let mut out = format!(
90        "//! The Rust port of `{}`.\n//!\n\
91         //! Replace each `unimplemented!` with the port of the source function. Return `Err` where\n\
92         //! the source throws or raises: the caller gets an error there too. After changing a\n\
93         //! signature, run `rust-anything refresh` to regenerate the bindings. `rust-anything diff` checks\n\
94         //! behavior against what the source recorded.\n\n\
95         #![forbid(unsafe_code)]\n",
96        m.unit
97    );
98    for f in &m.exports {
99        let params = f
100            .params
101            .iter()
102            .map(|p| format!("{}: {}", snake_case(&p.name), port_param_type(m, p).rust()))
103            .collect::<Vec<_>>()
104            .join(", ");
105        let ret = match RType::from_ts(&f.returns) {
106            RType::Unit => "()".to_string(),
107            t => t.rust(),
108        };
109        let names: Vec<String> = f.params.iter().map(|p| snake_case(&p.name)).collect();
110        let asyncness = if is_async(f) { "async " } else { "" };
111        out.push('\n');
112        let _ = writeln!(out, "/// Port of `{}` (`{}:{}`).", f.name, f.file, f.line);
113        for p in f.params.iter().filter(|p| p.default.is_some()) {
114            let _ = writeln!(
115                out,
116                "///\n/// `{}` defaults to `{}` in the source.",
117                snake_case(&p.name),
118                p.default.as_deref().unwrap_or_default()
119            );
120        }
121        let _ = writeln!(
122            out,
123            "pub {asyncness}fn {}({params}) -> Result<{ret}, String> {{",
124            snake_case(&f.name)
125        );
126        match names.len() {
127            0 => {}
128            1 => {
129                let _ = writeln!(out, "    let _ = &{};", names[0]);
130            }
131            _ => {
132                let refs: Vec<String> = names.iter().map(|n| format!("&{n}")).collect();
133                let _ = writeln!(out, "    let _ = ({});", refs.join(", "));
134            }
135        }
136        let _ = writeln!(
137            out,
138            "    unimplemented!(\"port `{}` from {}\")",
139            f.name, f.file
140        );
141        out.push_str("}\n");
142    }
143    for c in &m.classes {
144        let _ = writeln!(
145            out,
146            "\n/// Port of class `{}` (`{}:{}`): holds the instance state.",
147            c.name, c.file, c.line
148        );
149        let _ = writeln!(out, "pub struct {} {{}}\n", c.name);
150        let _ = writeln!(out, "impl {} {{", c.name);
151        let ctor = stub_params(m, &c.constructor);
152        let _ = writeln!(
153            out,
154            "    /// Port of `{}` constructor (`{}:{}`).",
155            c.name, c.file, c.line
156        );
157        let _ = writeln!(out, "    pub fn new({}) -> Result<Self, String> {{", ctor.0);
158        let _ = write!(out, "{}", ctor.1);
159        let _ = writeln!(
160            out,
161            "        unimplemented!(\"port the `{}` constructor\")\n    }}",
162            c.name
163        );
164        for f in &c.methods {
165            let (params, unused) = stub_params(m, &f.params);
166            let ret = match RType::from_ts(&f.returns) {
167                RType::Unit => "()".to_string(),
168                t => t.rust(),
169            };
170            let receiver = if params.is_empty() {
171                "&mut self".to_string()
172            } else {
173                format!("&mut self, {params}")
174            };
175            let _ = writeln!(
176                out,
177                "\n    /// Port of `{}.{}` (`{}:{}`).",
178                c.name, f.name, f.file, f.line
179            );
180            let _ = writeln!(
181                out,
182                "    pub fn {}({receiver}) -> Result<{ret}, String> {{",
183                snake_case(&f.name)
184            );
185            let _ = write!(out, "{unused}");
186            let _ = writeln!(
187                out,
188                "        unimplemented!(\"port `{}.{}`\")\n    }}",
189                c.name, f.name
190            );
191        }
192        out.push_str("}\n");
193    }
194    out
195}
196
197/// A parameter's type in the port. Python parameters with a literal default (`sep="-"`) are
198/// plain values: PyO3 fills in the default, and an explicit `None` stays an error, as in Python.
199fn port_param_type(m: &Manifest, p: &crate::ts::exports::Param) -> RType {
200    if matches!(
201        m.language,
202        crate::lang::Lang::Python | crate::lang::Lang::Ruby
203    ) && crate::codegen_py::has_literal_default(p)
204    {
205        RType::from_ts(&p.ts_type)
206    } else {
207        param_type(p)
208    }
209}
210
211/// Parameters of a method stub, and a line marking them used.
212fn stub_params(m: &Manifest, params: &[crate::ts::exports::Param]) -> (String, String) {
213    let list = params
214        .iter()
215        .map(|p| format!("{}: {}", snake_case(&p.name), port_param_type(m, p).rust()))
216        .collect::<Vec<_>>()
217        .join(", ");
218    let names: Vec<String> = params
219        .iter()
220        .map(|p| format!("&{}", snake_case(&p.name)))
221        .collect();
222    let unused = match names.len() {
223        0 => String::new(),
224        1 => format!("        let _ = {};\n", names[0]),
225        _ => format!("        let _ = ({});\n", names.join(", ")),
226    };
227    (list, unused)
228}
229
230pub fn is_async(f: &ExportedFn) -> bool {
231    f.is_async || f.returns.trim().starts_with("Promise<")
232}
233
234// ---- reading port.rs -------------------------------------------------------------------------
235
236/// The functions and classes `port.rs` offers. A function's JS name comes from its
237/// `/// Port of `name`` doc line (else its Rust name in camelCase); a class is a `pub struct`
238/// documented `/// Port of class `Name``, with an `impl` holding `new` and its methods.
239pub fn parse_port(source: &str) -> PortApi {
240    let lines: Vec<&str> = source.lines().collect();
241    let mut api = PortApi {
242        functions: functions_in(&lines, ""),
243        classes: Vec::new(),
244        structs: lines
245            .iter()
246            .filter_map(|l| l.trim_start().strip_prefix("pub struct "))
247            .map(|r| {
248                r.chars()
249                    .take_while(|c| c.is_alphanumeric() || *c == '_')
250                    .collect()
251            })
252            .collect(),
253        ranked: Vec::new(),
254    };
255    // `impl Name {` ... `}` at column 0: does it define `pub fn rank`?
256    for (i, line) in lines.iter().enumerate() {
257        let Some(rest) = line.strip_prefix("impl ") else {
258            continue;
259        };
260        let name: String = rest
261            .chars()
262            .take_while(|c| c.is_alphanumeric() || *c == '_')
263            .collect();
264        let body = lines[i + 1..].iter().take_while(|l| !l.starts_with('}'));
265        if body
266            .into_iter()
267            .any(|l| l.trim_start().starts_with("pub fn rank("))
268        {
269            api.ranked.push(name);
270        }
271    }
272    for (i, line) in lines.iter().enumerate() {
273        let Some(rest) = line.strip_prefix("pub struct ") else {
274            continue;
275        };
276        let rust_name: String = rest
277            .chars()
278            .take_while(|c| c.is_alphanumeric() || *c == '_')
279            .collect();
280        let Some(js_name) = doc_name(&lines[..i], "Port of class `") else {
281            continue;
282        };
283        // The `impl Name {` block, up to its closing `}` at column 0.
284        let Some(start) = lines
285            .iter()
286            .position(|l| l.trim_end() == format!("impl {rust_name} {{"))
287        else {
288            continue;
289        };
290        let end = lines[start..]
291            .iter()
292            .position(|l| *l == "}")
293            .map_or(lines.len(), |e| start + e);
294        let block = &lines[start + 1..end];
295        let mut constructor = None;
296        let mut methods = Vec::new();
297        for f in functions_in(block, "    ") {
298            if f.rust_name == "new" {
299                constructor = Some(f);
300            } else {
301                let signature_line = block
302                    .iter()
303                    .find(|l| l.contains(&format!("fn {}(", f.rust_name)))
304                    .copied()
305                    .unwrap_or("");
306                let block_text = block.join("\n");
307                let mutable = signature_line.contains("&mut self") || {
308                    let at = block_text
309                        .find(&format!("fn {}(", f.rust_name))
310                        .unwrap_or(0);
311                    block_text[at..]
312                        .split('{')
313                        .next()
314                        .unwrap_or("")
315                        .contains("&mut self")
316                };
317                methods.push((f, mutable));
318            }
319        }
320        if let Some(constructor) = constructor {
321            api.classes.push(PortClass {
322                js_name,
323                rust_name,
324                constructor,
325                methods,
326            });
327        }
328    }
329    api
330}
331
332fn doc_name(before: &[&str], prefix: &str) -> Option<String> {
333    before
334        .iter()
335        .rev()
336        .take_while(|l| l.trim_start().starts_with("///") || l.trim_start().starts_with("#["))
337        .find_map(|l| {
338            let doc = l.trim_start().strip_prefix("///")?.trim();
339            let rest = doc.strip_prefix(prefix)?;
340            Some(rest.split('`').next()?.to_string())
341        })
342}
343
344/// `pub fn` items at one indentation level. In an `impl`, `Port of `Class.method`` names the
345/// method `method`.
346fn functions_in(lines: &[&str], indent: &str) -> Vec<PortFn> {
347    let mut out = Vec::new();
348    let mut i = 0;
349    while i < lines.len() {
350        let line = lines[i].strip_prefix(indent).unwrap_or("");
351        let (is_async, rest) = if let Some(rest) = line.strip_prefix("pub async fn ") {
352            (true, rest)
353        } else if let Some(rest) = line.strip_prefix("pub fn ") {
354            (false, rest)
355        } else {
356            i += 1;
357            continue;
358        };
359        // The signature runs to the `{` that opens the body, possibly over several lines.
360        let mut signature = rest.to_string();
361        let mut j = i;
362        while !balanced_open_brace(&signature) && j + 1 < lines.len() {
363            j += 1;
364            signature.push(' ');
365            signature.push_str(lines[j].trim());
366        }
367        let js_name = doc_name(&lines[..i], "Port of `")
368            .map(|n| n.rsplit('.').next().unwrap_or(&n).to_string());
369        if let Some(f) = parse_signature(&signature, is_async, js_name) {
370            out.push(f);
371        }
372        i = j + 1;
373    }
374    out
375}
376
377/// Whether the text reaches the body's `{` outside parentheses and angle brackets.
378fn balanced_open_brace(text: &str) -> bool {
379    let mut depth = 0i32;
380    let mut previous = ' ';
381    for c in text.chars() {
382        let arrow = c == '>' && previous == '-';
383        previous = c;
384        match c {
385            '(' | '<' | '[' => depth += 1,
386            // `->` is not a closing bracket.
387            '>' if arrow => {}
388            ')' | '>' | ']' => depth -= 1,
389            '{' if depth == 0 => return true,
390            _ => {}
391        }
392    }
393    false
394}
395
396fn parse_signature(signature: &str, is_async: bool, js_name: Option<String>) -> Option<PortFn> {
397    let open = signature.find('(')?;
398    let rust_name = signature[..open].trim().to_string();
399    let mut depth = 0i32;
400    let mut close = None;
401    for (i, c) in signature.char_indices().skip(open) {
402        match c {
403            '(' | '<' | '[' => depth += 1,
404            ')' | '>' | ']' => {
405                depth -= 1;
406                if depth == 0 && c == ')' {
407                    close = Some(i);
408                    break;
409                }
410            }
411            _ => {}
412        }
413    }
414    let close = close?;
415    let params = split_top(&signature[open + 1..close])
416        .into_iter()
417        .filter(|p| !p.trim().is_empty())
418        .filter_map(|p| {
419            let (name, ty) = p.split_once(':')?;
420            Some((
421                name.trim().trim_start_matches("mut ").to_string(),
422                ty.trim().to_string(),
423            ))
424        })
425        .collect();
426    let after = &signature[close + 1..];
427    let body = after.find('{').unwrap_or(after.len());
428    let ret_text = after[..body].trim();
429    let ret_text = ret_text.strip_prefix("->").map_or("()", str::trim);
430    let (ret, fallible) = match ret_text
431        .strip_prefix("Result<")
432        .and_then(|r| r.strip_suffix('>'))
433    {
434        Some(inner) => (
435            split_top(inner)
436                .first()
437                .map_or("()", |t| t.trim())
438                .to_string(),
439            true,
440        ),
441        None => (ret_text.to_string(), false),
442    };
443    Some(PortFn {
444        js_name: js_name.unwrap_or_else(|| camel_case(&rust_name)),
445        rust_name,
446        params,
447        ret,
448        fallible,
449        is_async,
450    })
451}
452
453fn split_top(text: &str) -> Vec<&str> {
454    let mut out = Vec::new();
455    let mut depth = 0i32;
456    let mut start = 0;
457    for (i, c) in text.char_indices() {
458        match c {
459            '(' | '<' | '[' => depth += 1,
460            ')' | '>' | ']' => depth -= 1,
461            ',' if depth == 0 => {
462                out.push(&text[start..i]);
463                start = i + 1;
464            }
465            _ => {}
466        }
467    }
468    out.push(&text[start..]);
469    out
470}
471
472fn camel_case(name: &str) -> String {
473    let name = name.trim_start_matches("r#");
474    let mut out = String::new();
475    let mut upper = false;
476    for c in name.chars() {
477        if c == '_' {
478            upper = true;
479        } else if upper {
480            out.extend(c.to_uppercase());
481            upper = false;
482        } else {
483            out.push(c);
484        }
485    }
486    out
487}
488
489// ---- lib.rs ----------------------------------------------------------------------------------
490
491pub struct Modules {
492    pub utf16: bool,
493    pub js: bool,
494}
495
496pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {
497    if m.kind == Kind::Pyo3 {
498        return crate::codegen_py::lib_rs(m, api, modules);
499    }
500    let mut out = format!(
501        "//! JS bindings for `{}`: generated from the signatures in `port.rs` by rust-anything.\n\
502         //! Regenerate with `rust-anything refresh` after changing them.\n\n",
503        m.unit
504    );
505    out.push_str(match m.kind {
506        Kind::Wasm => "use wasm_bindgen::prelude::*;\n\n",
507        _ => "use napi_derive::napi;\n\n",
508    });
509    if modules.js {
510        out.push_str("pub mod js;\n");
511    }
512    out.push_str("pub mod port;\n");
513    if modules.utf16 {
514        out.push_str("pub mod utf16;\n");
515    }
516    if m.kind == Kind::Napi {
517        out.push_str(NAPI_RUN);
518        if api.all().any(|f| f.is_async) {
519            out.push_str(NAPI_RUN_ASYNC);
520        }
521    }
522    for f in &api.functions {
523        out.push('\n');
524        let _ = writeln!(out, "/// `{}`.", f.js_name);
525        bind(&mut out, m.kind, f);
526    }
527    for c in &api.classes {
528        bind_class(&mut out, m.kind, c);
529    }
530    out
531}
532
533/// The body of a binding: decode structured arguments, call, encode the result.
534fn body(f: &PortFn, target: &str, kind: Kind, constructor: bool) -> String {
535    let mut body = String::new();
536    for (n, t) in &f.params {
537        // The port's own type names may only resolve inside `port.rs`: let inference pick the type.
538        if wire(t) == Wire::Json {
539            let _ = writeln!(body, "        let {n} = crate::js::from_json(&{n})?;");
540        }
541    }
542    let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
543    let call = format!(
544        "{target}({}){}{}",
545        args.join(", "),
546        if f.is_async { ".await" } else { "" },
547        if f.fallible { "?" } else { "" }
548    );
549    // A unit result: call it, then return `()` (`let out = ()` is a clippy error).
550    if !constructor && f.ret.trim() == "()" {
551        let _ = writeln!(body, "        {call};\n        Ok(())");
552        return body;
553    }
554    let _ = writeln!(body, "        let out = {call};");
555    let result = match (constructor, wire(&f.ret), kind) {
556        (true, _, Kind::Napi) => "Ok(Self { inner: out })",
557        (true, _, Kind::Wasm) => "Ok(out)",
558        (false, Wire::Json, _) => "crate::js::to_json(&out)",
559        (false, Wire::Units, Kind::Napi) => "Ok(napi::bindgen_prelude::Uint16Array::new(out))",
560        (false, Wire::Native, Kind::Napi) if option_inner(&f.ret).is_some() => {
561            "Ok(out.map_or(napi::bindgen_prelude::Either::B(()), napi::bindgen_prelude::Either::A))"
562        }
563        _ => "Ok(out)",
564    };
565    let _ = writeln!(body, "        {result}");
566    body
567}
568
569fn binding_params(f: &PortFn) -> Vec<String> {
570    f.params
571        .iter()
572        .map(|(n, t)| match wire(t) {
573            Wire::Json => format!("{n}: String"),
574            _ => format!("{n}: {t}"),
575        })
576        .collect()
577}
578
579fn binding_ret(f: &PortFn, kind: Kind) -> String {
580    match (wire(&f.ret), kind) {
581        (Wire::Json, _) => "String".to_string(),
582        (Wire::Units, Kind::Napi) => "napi::bindgen_prelude::Uint16Array".to_string(),
583        // napi turns `None` into `null`; JS code returning nothing gives `undefined`.
584        (Wire::Native, Kind::Napi) if option_inner(&f.ret).is_some() => {
585            format!(
586                "napi::bindgen_prelude::Either<{}, ()>",
587                option_inner(&f.ret).unwrap_or_default()
588            )
589        }
590        _ => f.ret.clone(),
591    }
592}
593
594/// `T` of `Option<T>`.
595fn option_inner(ty: &str) -> Option<String> {
596    let ty: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
597    ty.strip_prefix("Option<")?
598        .strip_suffix('>')
599        .map(str::to_string)
600}
601
602fn bind_class(out: &mut String, kind: Kind, c: &PortClass) {
603    let (name, js) = (&c.rust_name, &c.js_name);
604    let snake = snake_case(name);
605    let ctor_params = binding_params(&c.constructor).join(", ");
606    let ctor_args: Vec<&str> = c
607        .constructor
608        .params
609        .iter()
610        .map(|(n, _)| n.as_str())
611        .collect();
612    match kind {
613        Kind::Napi => {
614            let _ = writeln!(
615                out,
616                "\n/// Class `{js}`.\n#[napi(js_name = \"{js}\")]\npub struct {name} {{\n    inner: port::{name},\n}}\n"
617            );
618            let _ = writeln!(out, "#[napi]\nimpl {name} {{");
619            let _ = writeln!(
620                out,
621                "    #[napi(constructor)]\n    pub fn new({ctor_params}) -> napi::Result<Self> {{"
622            );
623            let _ = writeln!(
624                out,
625                "        run(move || {{\n{}        }})\n    }}",
626                indent(&body(
627                    &c.constructor,
628                    &format!("port::{name}::new"),
629                    kind,
630                    true
631                ))
632            );
633            for (m, mutable) in &c.methods {
634                let receiver = if *mutable { "&mut self" } else { "&self" };
635                let params = binding_params(m);
636                let sig = if params.is_empty() {
637                    receiver.to_string()
638                } else {
639                    format!("{receiver}, {}", params.join(", "))
640                };
641                let _ = writeln!(out, "\n    #[napi(js_name = \"{}\")]", m.js_name);
642                let _ = writeln!(
643                    out,
644                    "    pub fn {}({sig}) -> napi::Result<{}> {{",
645                    m.rust_name,
646                    binding_ret(m, kind)
647                );
648                let borrow = if *mutable {
649                    "&mut self.inner"
650                } else {
651                    "&self.inner"
652                };
653                let _ = writeln!(out, "        let inner = {borrow};");
654                let _ = writeln!(
655                    out,
656                    "        run(move || {{\n{}        }})\n    }}",
657                    indent(&body(m, &format!("inner.{}", m.rust_name), kind, false))
658                );
659            }
660            out.push_str("}\n");
661        }
662        // PyO3 bindings come from `codegen_py`.
663        Kind::Wasm | Kind::Pyo3 | Kind::CAbi | Kind::Ffi => {
664            let _ = writeln!(
665                out,
666                "\nfn {snake}_new_inner({ctor_params}) -> Result<port::{name}, String> {{\n{}}}",
667                dedent(&body(
668                    &c.constructor,
669                    &format!("port::{name}::new"),
670                    kind,
671                    true
672                ))
673            );
674            for (m, mutable) in &c.methods {
675                let params = binding_params(m);
676                let receiver = if *mutable {
677                    format!("inner: &mut port::{name}")
678                } else {
679                    format!("inner: &port::{name}")
680                };
681                let sig = std::iter::once(receiver)
682                    .chain(params)
683                    .collect::<Vec<_>>()
684                    .join(", ");
685                let _ = writeln!(
686                    out,
687                    "\nfn {snake}_{}_inner({sig}) -> Result<{}, String> {{\n{}}}",
688                    m.rust_name.trim_start_matches("r#"),
689                    binding_ret(m, kind),
690                    dedent(&body(m, &format!("inner.{}", m.rust_name), kind, false))
691                );
692            }
693            let _ = writeln!(
694                out,
695                "\n/// Class `{js}`.\n#[wasm_bindgen(js_name = \"{js}\")]\npub struct {name} {{\n    inner: port::{name},\n}}\n"
696            );
697            let _ = writeln!(out, "#[wasm_bindgen(js_class = \"{js}\")]\nimpl {name} {{");
698            let _ = writeln!(
699                out,
700                "    #[wasm_bindgen(constructor)]\n    pub fn new({ctor_params}) -> Result<{name}, JsError> {{"
701            );
702            let _ = writeln!(
703                out,
704                "        let inner = {snake}_new_inner({}).map_err(|e| JsError::new(&e))?;\n        Ok(Self {{ inner }})\n    }}",
705                ctor_args.join(", ")
706            );
707            for (m, mutable) in &c.methods {
708                let receiver = if *mutable { "&mut self" } else { "&self" };
709                let params = binding_params(m);
710                let sig = if params.is_empty() {
711                    receiver.to_string()
712                } else {
713                    format!("{receiver}, {}", params.join(", "))
714                };
715                let args: Vec<&str> = m.params.iter().map(|(n, _)| n.as_str()).collect();
716                let borrow = if *mutable {
717                    "&mut self.inner"
718                } else {
719                    "&self.inner"
720                };
721                let call_args = std::iter::once(borrow)
722                    .chain(args)
723                    .collect::<Vec<_>>()
724                    .join(", ");
725                let _ = writeln!(out, "\n    #[wasm_bindgen(js_name = \"{}\")]", m.js_name);
726                let _ = writeln!(
727                    out,
728                    "    pub fn {}({sig}) -> Result<{}, JsError> {{",
729                    m.rust_name,
730                    binding_ret(m, kind)
731                );
732                let _ = writeln!(
733                    out,
734                    "        {snake}_{}_inner({call_args}).map_err(|e| JsError::new(&e))\n    }}",
735                    m.rust_name.trim_start_matches("r#")
736                );
737            }
738            out.push_str("}\n");
739        }
740    }
741}
742
743fn indent(text: &str) -> String {
744    text.lines().map(|l| format!("    {l}\n")).collect()
745}
746
747fn dedent(text: &str) -> String {
748    text.lines()
749        .map(|l| format!("{}\n", l.strip_prefix("    ").unwrap_or(l)))
750        .collect()
751}
752
753fn bind(out: &mut String, kind: Kind, f: &PortFn) {
754    let params = binding_params(f).join(", ");
755    let ret = binding_ret(f, kind);
756    let body = body(f, &format!("port::{}", f.rust_name), kind, false);
757    let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
758    let asyncness = if f.is_async { "async " } else { "" };
759    match kind {
760        Kind::Napi => {
761            let _ = writeln!(out, "#[napi(js_name = \"{}\")]", f.js_name);
762            let _ = writeln!(
763                out,
764                "pub {asyncness}fn {}({params}) -> napi::Result<{ret}> {{",
765                f.rust_name
766            );
767            if f.is_async {
768                let _ = writeln!(
769                    out,
770                    "    run_async(async move {{\n{body}    }})\n    .await"
771                );
772            } else {
773                let _ = writeln!(out, "    run(move || {{\n{body}    }})");
774            }
775            out.push_str("}\n");
776        }
777        // PyO3 bindings come from `codegen_py`.
778        Kind::Wasm | Kind::Pyo3 | Kind::CAbi | Kind::Ffi => {
779            // `?` needs a function boundary: the body lives in a private helper.
780            let inner = format!("{}_inner", f.rust_name.trim_start_matches("r#"));
781            let _ = writeln!(
782                out,
783                "{asyncness}fn {inner}({params}) -> Result<{ret}, String> {{\n{}}}\n",
784                dedent(&body)
785            );
786            let _ = writeln!(out, "#[wasm_bindgen(js_name = \"{}\")]", f.js_name);
787            let _ = writeln!(
788                out,
789                "pub {asyncness}fn {}({params}) -> Result<{ret}, JsError> {{",
790                f.rust_name
791            );
792            let _ = writeln!(
793                out,
794                "    {inner}({}){}.map_err(|e| JsError::new(&e))",
795                args.join(", "),
796                if f.is_async { ".await" } else { "" }
797            );
798            out.push_str("}\n");
799        }
800    }
801}
802
803/// napi: a panic must not unwind into Node (it aborts the process, and in shadow mode the
804/// app), and `Err` becomes a JS error.
805const NAPI_RUN: &str = r#"
806fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
807    payload
808        .downcast_ref::<&str>()
809        .map(|s| (*s).to_string())
810        .or_else(|| payload.downcast_ref::<String>().cloned())
811        .unwrap_or_else(|| "unknown panic".into())
812}
813
814#[allow(dead_code)]
815fn run<T>(f: impl FnOnce() -> Result<T, String>) -> napi::Result<T> {
816    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
817        Ok(result) => result.map_err(napi::Error::from_reason),
818        Err(payload) => Err(napi::Error::from_reason(format!("Rust panic: {}", panic_message(&*payload)))),
819    }
820}
821
822"#;
823
824const NAPI_RUN_ASYNC: &str = r#"
825#[allow(dead_code)]
826async fn run_async<T>(f: impl std::future::Future<Output = Result<T, String>>) -> napi::Result<T> {
827    use futures::FutureExt as _;
828    match std::panic::AssertUnwindSafe(f).catch_unwind().await {
829        Ok(result) => result.map_err(napi::Error::from_reason),
830        Err(payload) => Err(napi::Error::from_reason(format!("Rust panic: {}", panic_message(&*payload)))),
831    }
832}
833"#;
834
835// ---- index.cjs -------------------------------------------------------------------------------
836
837fn spec(f: &PortFn) -> (String, &'static str) {
838    let args: Vec<&str> = f
839        .params
840        .iter()
841        .map(|(_, t)| if wire(t) == Wire::Json { "1" } else { "0" })
842        .collect();
843    let ret = match wire(&f.ret) {
844        Wire::Json => "'json'",
845        Wire::Units => "'units'",
846        Wire::Native => "'raw'",
847    };
848    (format!("[{}]", args.join(", ")), ret)
849}
850
851fn needs_wrap(f: &PortFn) -> bool {
852    wire(&f.ret) != Wire::Native || f.params.iter().any(|(_, t)| wire(t) == Wire::Json)
853}
854
855pub fn index_cjs(m: &Manifest, api: &PortApi) -> String {
856    let load = match m.kind {
857        Kind::Napi => format!(
858            "// Loads the native module built by `rust-anything build`.\nconst native = require('./{}.node')\n",
859            m.lib_name()
860        ),
861        Kind::Wasm | Kind::Pyo3 | Kind::CAbi | Kind::Ffi => format!(
862            "// Loads the wasm-bindgen (nodejs target) output built by `rust-anything build`.\nconst native = require('./pkg/{}.js')\n",
863            m.lib_name()
864        ),
865    };
866    let functions: Vec<String> = api
867        .functions
868        .iter()
869        .filter(|f| needs_wrap(f))
870        .map(|f| {
871            let (args, ret) = spec(f);
872            format!("  {}: [{args}, {ret}, {}],", f.js_name, f.is_async)
873        })
874        .collect();
875    let classes: Vec<String> = api
876        .classes
877        .iter()
878        .filter(|c| needs_wrap(&c.constructor) || c.methods.iter().any(|(m, _)| needs_wrap(m)))
879        .map(|c| {
880            let methods: Vec<String> = c
881                .methods
882                .iter()
883                .map(|(m, _)| {
884                    let (args, ret) = spec(m);
885                    format!("{}: [{args}, {ret}]", m.js_name)
886                })
887                .collect();
888            format!(
889                "  {}: [{}, {{ {} }}],",
890                c.js_name,
891                spec(&c.constructor).0,
892                methods.join(", ")
893            )
894        })
895        .collect();
896    if functions.is_empty() && classes.is_empty() {
897        return format!("{load}module.exports = native\n");
898    }
899    format!(
900        "{load}{CODEC_CJS}\nmodule.exports = {{ ...native }}\nconst specs = {{\n{}\n}}\nconst classes = {{\n{}\n}}\n{WRAP_CJS}",
901        functions.join("\n"),
902        classes.join("\n")
903    )
904}
905
906const CODEC_CJS: &str = r#"
907// Structured values cross as JSON text. JSON has no `undefined`, NaN or -0, and Rust strings no
908// lone surrogates: those travel as `{"$undefined": true}`, `{"$num": "NaN"}` and
909// `{"$utf16": [...]}` (see `js.rs`), so `{ a: undefined }`, `null` and half an emoji survive.
910const replacer = (_, v) => v === undefined ? { $undefined: true }
911  : typeof v === 'number' ? (Number.isFinite(v) && !Object.is(v, -0) ? v : { $num: Object.is(v, -0) ? '-0' : String(v) })
912  : typeof v === 'string' && !v.isWellFormed() ? { $utf16: Array.from({ length: v.length }, (_, i) => v.charCodeAt(i)) }
913  : v
914const encode = v => JSON.stringify(v, replacer)
915const single = (v, key) => Object.keys(v).length === 1 && key in v
916const revive = v => Array.isArray(v) ? v.map(revive)
917  : v !== null && typeof v === 'object'
918    ? (single(v, '$undefined') ? undefined
919      : single(v, '$utf16') ? String.fromCharCode(...v.$utf16)
920      : single(v, '$num') ? Number(v.$num)
921      : Object.fromEntries(Object.entries(v).map(([k, x]) => [k, revive(x)])))
922    : v
923// Most results carry no marker: skip the walk unless the text has one.
924const decode = text => {
925  const value = JSON.parse(text)
926  return text.includes('"$') ? revive(value) : value
927}
928const fromUnits = (units) => {
929  let out = ''
930  for (let i = 0; i < units.length; i += 8192)
931    out += String.fromCharCode.apply(null, Array.prototype.slice.call(units, i, i + 8192))
932  return out
933}
934"#;
935
936const WRAP_CJS: &str = r#"const convert = result => result === 'json' ? decode : result === 'units' ? fromUnits : x => x
937// An omitted structured argument is `undefined`, not a missing value.
938const prepare = (a, structured) => Array.from({ length: Math.max(a.length, structured.length) }, (_, i) => structured[i] ? encode(a[i]) : a[i])
939// Functions: [structured arguments, result kind, async].
940for (const [name, [structured, result, isAsync]] of Object.entries(specs)) {
941  const call = native[name]
942  const out = convert(result)
943  module.exports[name] = isAsync
944    ? async (...a) => out(await call(...prepare(a, structured)))
945    : (...a) => out(call(...prepare(a, structured)))
946}
947// Classes: a JS class around the native one, converting arguments and results.
948const INNER = Symbol('native')
949for (const [name, [ctor, methods]] of Object.entries(classes)) {
950  const Native = native[name]
951  const Wrapped = { [name]: class { constructor(...a) { this[INNER] = new Native(...prepare(a, ctor)) } } }[name]
952  for (const [method, [structured, result]] of Object.entries(methods)) {
953    const out = convert(result)
954    Wrapped.prototype[method] = function (...a) { return out(this[INNER][method](...prepare(a, structured))) }
955  }
956  module.exports[name] = Wrapped
957}
958"#;
959
960// ---- js.rs -----------------------------------------------------------------------------------
961
962pub const JS_RS: &str = r#"//! JS values that JSON cannot express, and the JSON transport of the bindings.
963
964#![forbid(unsafe_code)]
965
966/// Reads a structured argument sent by `index.cjs`.
967pub fn from_json<T: serde::de::DeserializeOwned>(text: &str) -> Result<T, String> {
968    serde_json::from_str(text).map_err(|e| format!("TypeError: {e}"))
969}
970
971/// Writes a structured result for `index.cjs`.
972pub fn to_json<T: serde::Serialize>(value: &T) -> Result<String, String> {
973    serde_json::to_string(value).map_err(|e| e.to_string())
974}
975
976/// JS `undefined` inside a structured value: `{ a: undefined }` is not `{ a: null }`.
977pub fn undefined() -> serde_json::Value {
978    serde_json::json!({ "$undefined": true })
979}
980
981/// Whether a structured value received from JS was `undefined`.
982pub fn is_undefined(value: &serde_json::Value) -> bool {
983    value.as_object().is_some_and(|o| {
984        o.len() == 1 && o.get("$undefined") == Some(&serde_json::Value::Bool(true))
985    })
986}
987
988/// A JS string from UTF-16 code units: a plain string when well-formed, else a marker that
989/// `index.cjs` turns into the exact JS string, lone surrogates included.
990pub fn utf16_string(units: &[u16]) -> serde_json::Value {
991    match String::from_utf16(units) {
992        Ok(s) => serde_json::Value::String(s),
993        Err(_) => serde_json::json!({ "$utf16": units }),
994    }
995}
996
997/// The UTF-16 code units of a string received from JS, plain or marked.
998pub fn string_units(value: &serde_json::Value) -> Option<Vec<u16>> {
999    match value {
1000        serde_json::Value::String(s) => Some(s.encode_utf16().collect()),
1001        serde_json::Value::Object(o) if o.len() == 1 => o
1002            .get("$utf16")?
1003            .as_array()?
1004            .iter()
1005            .map(|u| u.as_u64().and_then(|u| u16::try_from(u).ok()))
1006            .collect(),
1007        _ => None,
1008    }
1009}
1010
1011/// A JS number inside a structured value. JSON has no NaN, Infinity or -0: those cross as
1012/// `{"$num": "NaN"}` and friends, which `index.cjs` turns back into numbers.
1013pub fn number(n: f64) -> serde_json::Value {
1014    if n.is_nan() {
1015        serde_json::json!({ "$num": "NaN" })
1016    } else if n.is_infinite() {
1017        serde_json::json!({ "$num": if n > 0.0 { "Infinity" } else { "-Infinity" } })
1018    } else if n == 0.0 && n.is_sign_negative() {
1019        serde_json::json!({ "$num": "-0" })
1020    } else if n.fract() == 0.0 && n.abs() < 9_007_199_254_740_992.0 {
1021        serde_json::Value::from(n as i64)
1022    } else {
1023        serde_json::Value::from(n)
1024    }
1025}
1026
1027/// JS `Array.prototype.sort(compare)`, as V8 runs it.
1028///
1029/// With a consistent comparator any stable sort agrees with JS. With one that returns NaN or
1030/// contradicts itself, the order depends on the algorithm: under 64 elements this reproduces
1031/// V8's TimSort exactly (one run, then binary insertion); longer arrays use Rust's stable sort.
1032pub fn sort<T>(items: &mut [T], mut compare: impl FnMut(&T, &T) -> f64) {
1033    let n = items.len();
1034    if n < 2 {
1035        return;
1036    }
1037    if n >= 64 {
1038        items.sort_by(|a, b| compare(a, b).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal));
1039        return;
1040    }
1041    // CountAndMakeRun: the leading ascending run, or strictly descending run (reversed).
1042    let mut run = 2;
1043    let descending = compare(&items[1], &items[0]) < 0.0;
1044    while run < n {
1045        let order = compare(&items[run], &items[run - 1]);
1046        if (descending && order >= 0.0) || (!descending && order < 0.0) {
1047            break;
1048        }
1049        run += 1;
1050    }
1051    if descending {
1052        items[..run].reverse();
1053    }
1054    // BinaryInsertionSort of the rest.
1055    for start in run..n {
1056        let (mut left, mut right) = (0, start);
1057        while left < right {
1058            let mid = left + ((right - left) >> 1);
1059            if compare(&items[start], &items[mid]) < 0.0 {
1060                right = mid;
1061            } else {
1062                left = mid + 1;
1063            }
1064        }
1065        items[left..=start].rotate_right(1);
1066    }
1067}
1068
1069/// A number received from JS inside a structured value, plain or marked.
1070pub fn as_number(value: &serde_json::Value) -> Option<f64> {
1071    match value {
1072        serde_json::Value::Number(n) => n.as_f64(),
1073        serde_json::Value::Object(o) if o.len() == 1 => match o.get("$num")?.as_str()? {
1074            "NaN" => Some(f64::NAN),
1075            "Infinity" => Some(f64::INFINITY),
1076            "-Infinity" => Some(f64::NEG_INFINITY),
1077            "-0" => Some(-0.0),
1078            _ => None,
1079        },
1080        _ => None,
1081    }
1082}
1083"#;
1084
1085// ---- Cargo.toml ------------------------------------------------------------------------------
1086
1087/// Dependencies the bindings need, as `(name, TOML value)`.
1088pub fn required_deps(kind: Kind, api: &PortApi) -> Vec<(&'static str, String)> {
1089    let json = api.needs_json();
1090    let any_async = api.all().any(|f| f.is_async);
1091    let mut deps = Vec::new();
1092    match kind {
1093        Kind::Napi => {
1094            deps.push((
1095                "napi",
1096                if any_async {
1097                    r#"{ version = "3", features = ["async"] }"#.into()
1098                } else {
1099                    r#""3""#.into()
1100                },
1101            ));
1102            deps.push(("napi-derive", r#""3""#.into()));
1103            if any_async {
1104                deps.push(("futures", r#""0.3""#.into()));
1105            }
1106        }
1107        Kind::Pyo3 => {
1108            // abi3: one build for every Python from 3.9 on.
1109            deps.push((
1110                "pyo3",
1111                r#"{ version = "0.30", features = ["extension-module", "abi3-py39"] }"#.into(),
1112            ));
1113        }
1114        // The C ABI needs no binding crate.
1115        Kind::CAbi | Kind::Ffi => {}
1116        Kind::Wasm => {
1117            deps.push(("wasm-bindgen", r#""0.2""#.into()));
1118            if any_async {
1119                deps.push(("wasm-bindgen-futures", r#""0.4""#.into()));
1120            }
1121        }
1122    }
1123    if json {
1124        deps.push(("serde", r#""1""#.into()));
1125        // JS objects keep insertion order; serde_json sorts keys unless told otherwise. Its
1126        // default float parser can be off by one ULP; `float_roundtrip` makes it exact.
1127        deps.push((
1128            "serde_json",
1129            r#"{ version = "1", features = ["preserve_order", "float_roundtrip"] }"#.into(),
1130        ));
1131    }
1132    deps
1133}
1134
1135pub fn cargo_toml(m: &Manifest, api: &PortApi) -> String {
1136    let deps: String = required_deps(m.kind, api)
1137        .iter()
1138        .map(|(name, value)| format!("{name} = {value}\n"))
1139        .collect();
1140    let build = if m.kind == Kind::Napi {
1141        "\n[build-dependencies]\nnapi-build = \"2\"\n"
1142    } else {
1143        ""
1144    };
1145    format!(
1146        "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\ndescription = \"Rust port of `{}`, generated by rust-anything\"\n\n\
1147         [lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[dependencies]\n{deps}{build}\n\
1148         [profile.release]\nlto = true\n\n[lints.clippy]\nall = {{ level = \"warn\", priority = -1 }}\n",
1149        m.crate_name, m.unit
1150    )
1151}
1152
1153/// Adds missing required dependencies to an existing Cargo.toml, keeping everything else.
1154pub fn ensure_deps(cargo: &str, kind: Kind, api: &PortApi) -> Result<String, String> {
1155    let mut doc: toml_edit::DocumentMut = cargo.parse().map_err(|e| format!("Cargo.toml: {e}"))?;
1156    let deps = doc
1157        .entry("dependencies")
1158        .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()))
1159        .as_table_mut()
1160        .ok_or("Cargo.toml: [dependencies] is not a table")?;
1161    for (name, value) in required_deps(kind, api) {
1162        let wanted: toml_edit::Item = format!("x = {value}")
1163            .parse::<toml_edit::DocumentMut>()
1164            .map_err(|e| e.to_string())?["x"]
1165            .clone();
1166        match deps.get(name) {
1167            None => {
1168                deps.insert(name, wanted);
1169            }
1170            // napi needs the `async` feature once an async function appears.
1171            Some(_) if name == "napi" && value.contains("async") => {
1172                deps.insert(name, wanted);
1173            }
1174            Some(_) => {}
1175        }
1176    }
1177    Ok(doc.to_string())
1178}
1179
1180#[cfg(test)]
1181mod tests {
1182    use super::*;
1183
1184    #[test]
1185    fn reads_port_signatures() {
1186        let source = "//! doc\n\n#![forbid(unsafe_code)]\n\n/// Port of `fuzzyScore` (`a.ts:1`).\n\
1187            pub fn fuzzy_score(query: String, text: String) -> Result<f64, String> {\n    Ok(1.0)\n}\n\n\
1188            /// Port of `load` (`a.ts:9`).\npub async fn load(\n    path: Option<String>,\n    data: Vec<serde_json::Value>,\n) -> Result<serde_json::Value, String> {\n    todo!()\n}\n\n\
1189            fn helper(x: Vec<u8>) -> u8 { 0 }\n\npub fn plain_name(a: f64) -> Vec<u16> {\n    vec![]\n}\n";
1190        let fns = parse_port(source).functions;
1191        assert_eq!(fns.len(), 3);
1192        assert_eq!(fns[0].js_name, "fuzzyScore");
1193        assert_eq!(
1194            fns[0].params,
1195            [
1196                ("query".into(), "String".into()),
1197                ("text".into(), "String".into())
1198            ]
1199        );
1200        assert_eq!(
1201            (fns[0].ret.as_str(), fns[0].fallible, fns[0].is_async),
1202            ("f64", true, false)
1203        );
1204        assert_eq!(fns[1].params[1].1, "Vec<serde_json::Value>");
1205        assert_eq!(
1206            (fns[1].ret.as_str(), fns[1].is_async),
1207            ("serde_json::Value", true)
1208        );
1209        assert_eq!(
1210            (
1211                fns[2].js_name.as_str(),
1212                fns[2].ret.as_str(),
1213                fns[2].fallible
1214            ),
1215            ("plainName", "Vec<u16>", false)
1216        );
1217    }
1218
1219    #[test]
1220    fn picks_wires() {
1221        assert_eq!(wire("Vec<String>"), Wire::Native);
1222        assert_eq!(wire("Option < f64 >"), Wire::Native);
1223        assert_eq!(wire("Vec<serde_json::Value>"), Wire::Json);
1224        assert_eq!(wire("Vec<bool>"), Wire::Json);
1225        assert_eq!(wire("Vec<u16>"), Wire::Units);
1226    }
1227
1228    #[test]
1229    fn adds_missing_deps_only() {
1230        let fns = parse_port(
1231            "/// Port of `a`.\npub async fn a(x: serde_json::Value) -> Result<(), String> {\n}\n",
1232        );
1233        let cargo =
1234            "[package]\nname = \"x\"\n\n[dependencies]\nnapi = \"3\"\nindexmap = \"2\" # mine\n";
1235        let out = ensure_deps(cargo, Kind::Napi, &fns).unwrap();
1236        assert!(out.contains("indexmap = \"2\" # mine"));
1237        assert!(out.contains("features = [\"async\"]"));
1238        assert!(out.contains("futures") && out.contains("preserve_order"));
1239    }
1240}