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