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