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