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