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