1use std::fmt::Write as _;
9
10use crate::bridge::Manifest;
11use crate::codegen::{PortApi, PortFn, Wire, wire};
12use crate::ts::exports::{ExportedFn, LocalType};
13use crate::ts::shape::{self, Shape};
14use crate::wire::{Ty, rust_read_args, rust_write, schema_expr};
15
16fn shape_ty(s: &Shape, types: &[LocalType], depth: usize) -> Ty {
18 if depth > 6 {
19 return Ty::Dyn;
20 }
21 let str_like = |s: &Shape| matches!(s, Shape::Str | Shape::LitStr(_));
22 let num_like = |s: &Shape| matches!(s, Shape::Num | Shape::Int | Shape::LitNum(_));
23 let bool_like = |s: &Shape| matches!(s, Shape::Bool | Shape::LitBool(_));
24 match s {
25 Shape::Str | Shape::LitStr(_) => Ty::Str16,
26 Shape::Num | Shape::Int | Shape::LitNum(_) => Ty::Num,
27 Shape::Bool | Shape::LitBool(_) => Ty::Bool,
28 Shape::Null | Shape::Undefined | Shape::Any | Shape::Tuple(_) => Ty::Dyn,
29 Shape::Array(item) => Ty::List {
30 item: Box::new(shape_ty(item, types, depth + 1)),
31 native: "ts".into(),
32 array: false,
33 },
34 Shape::Object(props, None) if props.len() <= usize::from(u8::MAX) => Ty::Obj(
35 props
36 .iter()
37 .map(|(name, optional, s)| {
38 let t = shape_ty(s, types, depth + 1);
39 let t = match t {
40 Ty::OptJs {
41 inner, nullable, ..
42 } if *optional => Ty::OptJs {
43 inner,
44 nullable,
45 undefinable: true,
46 },
47 t if *optional && t != Ty::Dyn => Ty::OptJs {
48 inner: Box::new(t),
49 nullable: false,
50 undefinable: true,
51 },
52 t => t,
53 };
54 (name.clone(), t)
55 })
56 .collect(),
57 ),
58 Shape::Object(props, Some(value)) if props.is_empty() => {
59 Ty::Map16(Box::new(shape_ty(value, types, depth + 1)))
60 }
61 Shape::Object(..) => Ty::Dyn,
62 Shape::Union(members) => {
63 let nullable = members.iter().any(|m| matches!(m, Shape::Null));
64 let undefinable = members.iter().any(|m| matches!(m, Shape::Undefined));
65 let rest: Vec<&Shape> = members
66 .iter()
67 .filter(|m| !matches!(m, Shape::Null | Shape::Undefined))
68 .collect();
69 let base = if rest.is_empty() {
70 Ty::Dyn
71 } else if rest.iter().all(|m| str_like(m)) {
72 Ty::Str16
73 } else if rest.iter().all(|m| num_like(m)) {
74 Ty::Num
75 } else if rest.iter().all(|m| bool_like(m)) {
76 Ty::Bool
77 } else if rest.len() == 1 {
78 shape_ty(rest[0], types, depth + 1)
79 } else {
80 Ty::Dyn
81 };
82 if (nullable || undefinable) && base != Ty::Dyn {
83 Ty::OptJs {
84 inner: Box::new(base),
85 nullable,
86 undefinable,
87 }
88 } else {
89 base
90 }
91 }
92 Shape::Ref(name, args) => {
93 let resolved = shape::resolve(name, args, types);
94 if matches!(resolved, Shape::Ref(..)) {
95 Ty::Dyn
96 } else {
97 shape_ty(&resolved, types, depth + 1)
98 }
99 }
100 }
101}
102
103fn js_key(k: &str) -> String {
104 serde_json::to_string(k).unwrap_or_else(|_| "\"\"".into())
105}
106
107fn js_enc(x: &str, t: &Ty, d: usize) -> String {
109 match t {
110 Ty::Num => format!("if (typeof {x} !== 'number') return false\nwF64({x})\n"),
111 Ty::Bool => format!("if (typeof {x} !== 'boolean') return false\nwU8({x} ? 1 : 0)\n"),
112 Ty::Str16 => format!("if (typeof {x} !== 'string') return false\nwStr({x})\n"),
113 Ty::Dyn => format!("if (!wDyn({x})) return false\n"),
114 Ty::OptJs {
115 inner,
116 nullable,
117 undefinable,
118 } => format!(
119 "if ({x} === undefined) {{\n{}wU8(0)\n}} else if ({x} === null) {{\n{}wU8(2)\n}} else {{\nwU8(1)\n{}}}\n",
120 if *undefinable { "" } else { "return false\n" },
121 if *nullable { "" } else { "return false\n" },
122 js_enc(x, inner, d)
123 ),
124 Ty::List { item, .. } => format!(
125 "if (!Array.isArray({x})) return false\nwU8(1)\nwU32({x}.length)\nfor (let i{d} = 0; i{d} < {x}.length; i{d}++) {{\nconst v{d} = {x}[i{d}]\n{}}}\n",
126 js_enc(&format!("v{d}"), item, d + 1)
127 ),
128 Ty::Map16(value) => format!(
129 "if ({x} === null || typeof {x} !== 'object' || Array.isArray({x})) return false\n{{\nconst k{d} = Object.keys({x})\nwU8(1)\nwU32(k{d}.length)\nfor (const key{d} of k{d}) {{\nwStr(key{d})\nconst v{d} = {x}[key{d}]\n{}}}\n}}\n",
130 js_enc(&format!("v{d}"), value, d + 1)
131 ),
132 Ty::Obj(fields) => {
133 let required = fields
136 .iter()
137 .filter(|(_, ft)| {
138 !(matches!(
139 ft,
140 Ty::OptJs {
141 undefinable: true,
142 ..
143 }
144 ) || *ft == Ty::Dyn)
145 })
146 .count();
147 let mut cases = String::new();
148 for (i, (key, ft)) in fields.iter().enumerate() {
149 let optional = matches!(
150 ft,
151 Ty::OptJs {
152 undefinable: true,
153 ..
154 }
155 ) || *ft == Ty::Dyn;
156 let _ = write!(
157 cases,
158 "case {}: {{\nwU8({i})\n{}const f{d} = {x}[k{d}]\n{}break\n}}\n",
159 js_key(key),
160 if optional {
161 String::new()
162 } else {
163 format!("r{d}++\n")
164 },
165 js_enc(&format!("f{d}"), ft, d + 1)
166 );
167 }
168 format!(
169 "if ({x} === null || typeof {x} !== 'object' || Array.isArray({x})) return false\n{{\n\
170 const at{d} = at\nwU8(0)\nlet n{d} = 0, r{d} = 0\nfor (const k{d} in {x}) {{\nswitch (k{d}) {{\n{cases}default: return false\n}}\n\
171 if (++n{d} > 255) return false\n}}\nif (r{d} !== {required}) return false\niv.setUint8(at{d}, n{d})\n}}\n"
172 )
173 }
174 _ => "return false\n".into(),
175 }
176}
177
178fn js_dec(target: &str, t: &Ty, d: usize) -> String {
180 match t {
181 Ty::Num => format!("{target} = rF64()\n"),
182 Ty::Bool => format!("{target} = rU8() === 1\n"),
183 Ty::Str16 => format!("{target} = rStr()\n"),
184 Ty::Dyn => format!("{target} = rDyn()\n"),
185 Ty::OptJs { inner, .. } => format!(
186 "{{\nconst g{d} = rU8()\nif (g{d} === 0) {target} = undefined\nelse if (g{d} === 2) {target} = null\nelse {{\n{}}}\n}}\n",
187 js_dec(target, inner, d + 1)
188 ),
189 Ty::List { item, .. } => format!(
190 "if (rU8() === 0) {target} = null\nelse {{\nconst n{d} = rU32()\nconst a{d} = new Array(n{d})\nfor (let i{d} = 0; i{d} < n{d}; i{d}++) {{\nlet v{d}\n{}a{d}[i{d}] = v{d}\n}}\n{target} = a{d}\n}}\n",
191 js_dec(&format!("v{d}"), item, d + 1)
192 ),
193 Ty::Map16(value) => format!(
194 "if (rU8() === 0) {target} = null\nelse {{\nconst n{d} = rU32()\nconst o{d} = {{}}\nfor (let i{d} = 0; i{d} < n{d}; i{d}++) {{\nconst k{d} = rStr()\nlet v{d}\n{}o{d}[k{d}] = v{d}\n}}\n{target} = o{d}\n}}\n",
195 js_dec(&format!("v{d}"), value, d + 1)
196 ),
197 Ty::Obj(fields) => {
198 let mut cases = String::new();
199 for (i, (key, ft)) in fields.iter().enumerate() {
200 let _ = write!(
201 cases,
202 "case {i}: {{\nlet v{d}\n{}o{d}[{}] = v{d}\nbreak\n}}\n",
203 js_dec(&format!("v{d}"), ft, d + 1),
204 js_key(key)
205 );
206 }
207 format!(
208 "{{\nconst o{d} = {{}}\nconst n{d} = rU8()\nfor (let j{d} = 0; j{d} < n{d}; j{d}++) {{\nswitch (rU8()) {{\n{cases}default: {{\nconst k{d} = rStr()\no{d}[k{d}] = rDyn()\n}}\n}}\n}}\n{target} = o{d}\n}}\n"
209 )
210 }
211 _ => format!("{target} = undefined\n"),
212 }
213}
214
215const WIRE_NAPI_CJS: &str = r#"
217// The binary wire (see rust-anything's `wire.rs`): arguments are written into `wIn`, results read
218// from `wOut`; both are registered with the native module once.
219let wIn = new Uint8Array(1 << 16), wOut = new Uint8Array(1 << 16)
220const wLen = new Uint32Array(1)
221let iv = new DataView(wIn.buffer), ov = new DataView(wOut.buffer), at = 0, p = 0
222native.rustAnythingWireInit(wIn, wOut, wLen)
223const regrow = () => native.rustAnythingWireInit(wIn, wOut, wLen)
224// Runs a wire function; a result larger than `wOut` is fetched once `wOut` has grown.
225const wireCall = fn => {
226 wLen[0] = at
227 const n = fn()
228 if (Number.isNaN(n)) return false
229 if (n === Infinity) {
230 p = 0
231 throw new Error(rStr())
232 }
233 if (n < 0) {
234 wOut = new Uint8Array(Math.max(wOut.length * 2, -n))
235 ov = new DataView(wOut.buffer)
236 native.rustAnythingWireInit(wIn, wOut, wLen)
237 native.rustAnythingWireFlush()
238 }
239 p = 0
240 return true
241}
242"#;
243
244const WIRE_WASM_CJS: &str = r#"
245// The binary wire (see rust-anything's `wire.rs`): arguments are written into `wIn` and copied into
246// wasm memory in one step; results are read where the Rust side left them.
247let wIn = new Uint8Array(1 << 16), iv = new DataView(wIn.buffer), at = 0, p = 0
248const mem = native.rustAnythingWireMemory()
249let wOut = new Uint8Array(mem.buffer), ov = new DataView(mem.buffer)
250const regrow = () => {}
251// Growing wasm memory replaces its buffer: views are made again when that happened.
252const views = () => {
253 if (wOut.buffer !== mem.buffer) {
254 wOut = new Uint8Array(mem.buffer)
255 ov = new DataView(mem.buffer)
256 }
257}
258const wireCall = fn => {
259 const ptr = native.rustAnythingWireIn(at)
260 views()
261 wOut.set(wIn.subarray(0, at), ptr)
262 if (fn(at) === 0xFFFFFFFF) return false
263 views()
264 p = native.rustAnythingWireOut()
265 return true
266}
267"#;
268
269const WIRE_CJS: &str = r#"
270const need = n => {
271 if (at + n <= wIn.length) return
272 const grown = new Uint8Array(Math.max(wIn.length * 2, at + n))
273 grown.set(wIn)
274 wIn = grown
275 iv = new DataView(wIn.buffer)
276 regrow()
277}
278const wU8 = v => { need(1); iv.setUint8(at++, v) }
279const wU32 = v => { need(4); iv.setUint32(at, v, true); at += 4 }
280const wF64 = v => { need(8); iv.setFloat64(at, v, true); at += 8 }
281const wUnits = s => {
282 need(4 + 2 * s.length)
283 iv.setUint32(at, s.length, true)
284 at += 4
285 for (let i = 0; i < s.length; i++) { iv.setUint16(at, s.charCodeAt(i), true); at += 2 }
286}
287const wStr = s => { wU8(4); wUnits(s) }
288const wDyn = v => {
289 switch (typeof v) {
290 case 'undefined': wU8(0); return true
291 case 'boolean': wU8(v ? 3 : 2); return true
292 case 'number': wU8(4); wF64(v); return true
293 case 'string': wU8(5); wUnits(v); return true
294 case 'object':
295 if (v === null) { wU8(1); return true }
296 if (Array.isArray(v)) {
297 wU8(6); wU32(v.length)
298 for (let i = 0; i < v.length; i++) if (!wDyn(v[i])) return false
299 return true
300 }
301 if (Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) return false
302 {
303 const keys = Object.keys(v)
304 wU8(7); wU32(keys.length)
305 for (const k of keys) { wUnits(k); if (!wDyn(v[k])) return false }
306 return true
307 }
308 }
309 return false
310}
311const rU8 = () => ov.getUint8(p++)
312const rU32 = () => { const v = ov.getUint32(p, true); p += 4; return v }
313const rF64 = () => { const v = ov.getFloat64(p, true); p += 8; return v }
314// ignoreBOM: a leading U+FEFF is part of the string, not a byte-order mark.
315const utf16 = new TextDecoder('utf-16le', { ignoreBOM: true })
316const rUnits = (wellFormed) => {
317 const n = rU32()
318 let s
319 if (n > 24 && wellFormed) s = utf16.decode(wOut.subarray(p, p + 2 * n))
320 else {
321 s = ''
322 for (let i = 0; i < n; i++) s += String.fromCharCode(ov.getUint16(p + 2 * i, true))
323 }
324 p += 2 * n
325 return s
326}
327// Tag 1: a string from Rust (well-formed); 4: raw code units, lone surrogates included.
328const rStr = () => rUnits(rU8() === 1)
329const rDyn = () => {
330 switch (rU8()) {
331 case 0: return undefined
332 case 1: return null
333 case 2: return false
334 case 3: return true
335 case 4: return rF64()
336 case 5: return rUnits(false)
337 case 6: { const n = rU32(); const a = new Array(n); for (let i = 0; i < n; i++) a[i] = rDyn(); return a }
338 case 7: { const n = rU32(); const o = {}; for (let i = 0; i < n; i++) { const k = rUnits(false); o[k] = rDyn() } return o }
339 }
340}
341"#;
342
343const WIRE_NAPI_RS: &str = r#"
345// ---- the binary wire ------------------------------------------------------------------------
346
347type WireBuffers = (
348 napi::bindgen_prelude::Uint8Array,
349 napi::bindgen_prelude::Uint8Array,
350 napi::bindgen_prelude::Uint32Array,
351);
352
353thread_local! {
354 static WIRE: std::cell::RefCell<Option<WireBuffers>> = const { std::cell::RefCell::new(None) };
355 static PENDING: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
356 static SCRATCH: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
357}
358
359/// Registers the argument, result and argument-length buffers `index.cjs` uses.
360#[napi(js_name = "rustAnythingWireInit")]
361pub fn rust_anything_wire_init(
362 input: napi::bindgen_prelude::Uint8Array,
363 output: napi::bindgen_prelude::Uint8Array,
364 len: napi::bindgen_prelude::Uint32Array,
365) {
366 WIRE.with(|w| *w.borrow_mut() = Some((input, output, len)));
367}
368
369/// Copies a result that did not fit into the (now larger) result buffer.
370#[napi(js_name = "rustAnythingWireFlush")]
371pub fn rust_anything_wire_flush() -> f64 {
372 let bytes = PENDING.with(|p| std::mem::take(&mut *p.borrow_mut()));
373 WIRE.with(|w| {
374 let mut w = w.borrow_mut();
375 let Some((_, output, _)) = w.as_mut() else {
376 return -1.0;
377 };
378 // SAFETY: the call is synchronous; JS does not touch `output` until it returns.
379 let out = unsafe { output.as_mut() };
380 let n = bytes.len().min(out.len());
381 out[..n].copy_from_slice(&bytes[..n]);
382 n as f64
383 })
384}
385
386/// Reads the argument bytes (`wLen[0]` of them), runs `f`, and writes its result; a negative
387/// return is the size of a result that did not fit, kept for `rustAnythingWireFlush`.
388fn wire_io(f: impl FnOnce(&mut wire::Reader, &mut wire::Writer) -> Result<(), String>) -> napi::Result<f64> {
389 WIRE.with(|cell| {
390 let mut guard = cell.borrow_mut();
391 let Some((input, output, len)) = guard.as_mut() else {
392 return Err(napi::Error::from_reason("rust-anything: the wire buffers are not registered"));
393 };
394 let len = (len.first().copied().unwrap_or(0) as usize).min(input.len());
395 let mut w = wire::Writer(SCRATCH.with(|s| std::mem::take(&mut *s.borrow_mut())));
396 w.0.clear();
397 let result = run(|| f(&mut wire::Reader::new(&input[..len]), &mut w));
398 let keep = |w: wire::Writer| SCRATCH.with(|s| *s.borrow_mut() = w.0);
399 match result {
400 // A result of another shape than the TS type: JS runs the call through JSON.
401 Err(e) if e.reason.starts_with(wire::MISMATCH) => {
402 keep(w);
403 return Ok(f64::NAN);
404 }
405 Err(e) => {
406 keep(w);
407 let mut m = wire::Writer::default();
408 m.string16(&e.reason);
409 // SAFETY: the call is synchronous; JS does not touch `output` until it returns.
410 let out = unsafe { output.as_mut() };
411 if m.0.len() > out.len() {
412 return Err(e);
413 }
414 out[..m.0.len()].copy_from_slice(&m.0);
415 return Ok(f64::INFINITY);
416 }
417 Ok(()) => {}
418 }
419 // SAFETY: the call is synchronous; JS does not touch `output` until it returns.
420 let out = unsafe { output.as_mut() };
421 let n = w.0.len();
422 if n > out.len() {
423 PENDING.with(|p| *p.borrow_mut() = w.0);
424 return Ok(-(n as f64));
425 }
426 out[..n].copy_from_slice(&w.0);
427 keep(w);
428 Ok(n as f64)
429 })
430}
431"#;
432
433const WIRE_WASM_RS: &str = r#"
435// ---- the binary wire ------------------------------------------------------------------------
436
437thread_local! {
438 static WIRE_IN: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
439 static WIRE_OUT: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
440}
441
442/// This module's memory, where `index.cjs` reads and writes the wire buffers.
443#[wasm_bindgen(js_name = "rustAnythingWireMemory")]
444pub fn rust_anything_wire_memory() -> JsValue {
445 wasm_bindgen::memory()
446}
447
448/// The address of an argument buffer of `len` bytes.
449#[wasm_bindgen(js_name = "rustAnythingWireIn")]
450pub fn rust_anything_wire_in(len: u32) -> u32 {
451 WIRE_IN.with(|b| {
452 let mut b = b.borrow_mut();
453 b.resize(len as usize, 0);
454 b.as_mut_ptr() as usize as u32
455 })
456}
457
458/// The address of the last result.
459#[wasm_bindgen(js_name = "rustAnythingWireOut")]
460pub fn rust_anything_wire_out() -> u32 {
461 WIRE_OUT.with(|b| b.borrow().as_ptr() as usize as u32)
462}
463
464/// Reads `len` argument bytes, runs `f`, and keeps its result for `rustAnythingWireOut`.
465fn wire_io(len: u32, f: impl FnOnce(&mut wire::Reader, &mut wire::Writer) -> Result<(), String>) -> Result<u32, JsError> {
466 let input = WIRE_IN.with(|b| std::mem::take(&mut *b.borrow_mut()));
467 let mut w = wire::Writer::default();
468 let result = f(&mut wire::Reader::new(&input[..(len as usize).min(input.len())]), &mut w);
469 WIRE_IN.with(|b| *b.borrow_mut() = input);
470 match result {
471 // A result of another shape than the TS type: JS runs the call through JSON.
472 Err(e) if e.starts_with(wire::MISMATCH) => return Ok(u32::MAX),
473 other => other.map_err(|e| JsError::new(&e))?,
474 }
475 let n = w.0.len();
476 WIRE_OUT.with(|b| *b.borrow_mut() = w.0);
477 Ok(u32::try_from(n).unwrap_or(u32::MAX))
478}
479"#;
480
481struct WireFn<'m> {
483 export: &'m ExportedFn,
484 port: &'m PortFn,
485 params: Vec<Ty>,
486 result: Option<Ty>,
487 rust: String,
488}
489
490fn types_for(m: &Manifest, file: &str) -> Vec<LocalType> {
491 let text = std::fs::read_to_string(m.root.join(file)).unwrap_or_default();
492 crate::bridge::types_in_scope(&m.root, file, &text)
493}
494
495fn wire_fns<'m>(m: &'m Manifest, api: &'m PortApi) -> Vec<WireFn<'m>> {
498 let mut out = Vec::new();
499 let mut scopes: std::collections::HashMap<&str, Vec<LocalType>> =
500 std::collections::HashMap::new();
501 for f in &api.functions {
502 if f.is_async {
503 continue;
504 }
505 let structured =
506 f.params.iter().any(|(_, t)| wire(t) == Wire::Json) || wire(&f.ret) == Wire::Json;
507 let napi = m.kind == crate::bridge::Kind::Napi;
508 if !structured && !napi {
509 continue;
510 }
511 let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
512 continue;
513 };
514 if e.params.len() != f.params.len() || e.params.iter().any(|p| p.rest) {
515 continue;
516 }
517 let types = scopes
518 .entry(e.file.as_str())
519 .or_insert_with(|| types_for(m, &e.file));
520 let params: Vec<Ty> = e
521 .params
522 .iter()
523 .map(|p| {
524 let t = shape_ty(&shape::parse(&p.ts_type), types, 0);
525 if p.optional || p.default.is_some() {
526 match t {
527 Ty::OptJs {
528 inner, nullable, ..
529 } => Ty::OptJs {
530 inner,
531 nullable,
532 undefinable: true,
533 },
534 Ty::Dyn => Ty::Dyn,
535 t => Ty::OptJs {
536 inner: Box::new(t),
537 nullable: false,
538 undefinable: true,
539 },
540 }
541 } else {
542 t
543 }
544 })
545 .collect();
546 let params: Vec<Ty> = params
547 .into_iter()
548 .zip(&f.params)
549 .map(|(t, (_, rust))| {
550 let rust: String = rust.chars().filter(|c| !c.is_whitespace()).collect();
551 let value = rust
552 .strip_prefix("Option<")
553 .and_then(|r| r.strip_suffix('>'))
554 .unwrap_or(&rust);
555 if matches!(value, "Value" | "serde_json::Value") {
556 Ty::Dyn
557 } else {
558 t
559 }
560 })
561 .collect();
562 let result = (f.ret != "()").then(|| shape_ty(&shape::parse(&e.returns), types, 0));
563 let named: Vec<(String, Ty)> = f
564 .params
565 .iter()
566 .map(|(n, _)| n.clone())
567 .zip(params.iter().cloned())
568 .collect();
569 let mut statics = String::new();
570 let prefix = format!("S_{}", crate::bridge::snake_case(&f.js_name).to_uppercase());
571 let Some(reads) = rust_read_args(&named, &f.params, &prefix, &mut statics) else {
572 continue;
573 };
574 let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
575 let call = format!("port::{}({})", f.rust_name, args.join(", "));
576 let call = if f.fallible { format!("{call}?") } else { call };
577 let write = match &result {
578 None => format!(" let () = {call};\n"),
579 Some(t) => {
580 let schema = format!("{prefix}_OUT");
581 let Some(w) = rust_write(t, &f.ret, "out", &schema, 0) else {
582 continue;
583 };
584 if w.contains(&schema) {
585 let _ = writeln!(
586 statics,
587 "static {schema}: wire::Schema = {};",
588 schema_expr(t)
589 );
590 }
591 format!(" let out = &{call};\n {w}\n")
592 }
593 };
594 let (attr, ret, len, len_arg) = if napi {
595 ("napi", "napi::Result<f64>", "", "")
596 } else {
597 ("wasm_bindgen", "Result<u32, JsError>", "len: u32", "len, ")
598 };
599 let rust = format!(
600 "\n{statics}\n/// `{js}` over the binary wire.\n#[{attr}(js_name = \"{js}Wire\")]\npub fn {name}_wire({len}) -> {ret} {{\n \
601 wire_io({len_arg}|r, w| {{\n{reads}{write} Ok(())\n }})\n}}\n",
602 js = f.js_name,
603 name = f.rust_name.trim_start_matches("r#"),
604 );
605 out.push(WireFn {
606 export: e,
607 port: f,
608 params,
609 result,
610 rust,
611 });
612 }
613 out
614}
615
616pub fn napi_rs(m: &Manifest, api: &PortApi) -> String {
619 let fns = wire_fns(m, api);
620 if fns.is_empty() {
621 return String::new();
622 }
623 let mut out = String::from(if m.kind == crate::bridge::Kind::Wasm {
624 WIRE_WASM_RS
625 } else {
626 WIRE_NAPI_RS
627 });
628 for f in fns {
629 out.push_str(&f.rust);
630 }
631 out
632}
633
634pub fn wired(m: &Manifest, api: &PortApi) -> Vec<String> {
637 if !matches!(
638 m.kind,
639 crate::bridge::Kind::Napi | crate::bridge::Kind::Wasm
640 ) {
641 return Vec::new();
642 }
643 wire_fns(m, api)
644 .iter()
645 .map(|f| f.port.js_name.clone())
646 .collect()
647}
648
649pub fn uses_wire(m: &Manifest, api: &PortApi) -> bool {
651 matches!(
652 m.kind,
653 crate::bridge::Kind::Napi | crate::bridge::Kind::Wasm
654 ) && !wire_fns(m, api).is_empty()
655}
656
657pub fn index_cjs(m: &Manifest, api: &PortApi) -> String {
660 let fns = wire_fns(m, api);
661 if fns.is_empty() {
662 return String::new();
663 }
664 let mut out = String::from(if m.kind == crate::bridge::Kind::Wasm {
665 WIRE_WASM_CJS
666 } else {
667 WIRE_NAPI_CJS
668 });
669 out.push_str(WIRE_CJS);
670 for f in &fns {
671 let n = f.params.len();
672 let names: Vec<String> = (0..n).map(|i| format!("a{i}")).collect();
673 let mut enc = String::new();
674 for (i, t) in f.params.iter().enumerate() {
675 enc.push_str(&js_enc(&format!("a{i}"), t, 0));
676 }
677 let dec = f
678 .result
679 .as_ref()
680 .map_or_else(String::new, |t| js_dec("t", t, 0));
681 let js = &f.port.js_name;
682 let checks: String = crate::codegen::string_params(f.port)
683 .iter()
684 .map(|i| {
685 format!(
686 " if (illFormed(a{i})) throw new TypeError('argument {} of {js} has a lone surrogate, which a Rust String cannot hold')\n",
687 i + 1
688 )
689 })
690 .collect();
691 let _ = write!(
692 out,
693 "\n// `{js}`: binary wire; the JSON version handles inputs of other shapes.\n{{\n\
694 const json = module.exports.{js}\nconst call = native.{js}Wire\n\
695 const encode = ({args}) => {{\nat = 0\n{enc}return true\n}}\n\
696 const decode = () => {{\nlet t\n{dec}return t\n}}\n\
697 module.exports.{js} = function {js} ({args}) {{\n{checks} try {{\n \
698 if (arguments.length <= {n} && encode({args}) && wireCall(call)) return decode()\n \
699 return json(...arguments)\n }} catch (e) {{\n throw jsError(e)\n }}\n}}\n}}\n",
700 args = names.join(", "),
701 );
702 let _ = f.export;
703 }
704 out
705}
706
707#[cfg(test)]
708mod tests {
709 use super::*;
710
711 #[test]
712 fn wide_objects_use_dynamic_keys_instead_of_truncating_field_indexes() {
713 let shape = |n| {
714 Shape::Object(
715 (0..n)
716 .map(|i| (format!("p{i}"), true, Shape::Num))
717 .collect(),
718 None,
719 )
720 };
721 assert!(matches!(shape_ty(&shape(255), &[], 0), Ty::Obj(fields) if fields.len() == 255));
722 assert_eq!(shape_ty(&shape(256), &[], 0), Ty::Dyn);
723 assert_eq!(shape_ty(&shape(257), &[], 0), Ty::Dyn);
724 }
725
726 #[test]
727 fn maps_ts_shapes() {
728 let none: Vec<LocalType> = Vec::new();
729 let t = shape_ty(
730 &shape::parse("{ start: number; end: number; label?: string | null }"),
731 &none,
732 0,
733 );
734 let Ty::Obj(fields) = &t else { panic!("{t:?}") };
735 assert_eq!(fields[0], ("start".into(), Ty::Num));
736 assert_eq!(
737 fields[2].1,
738 Ty::OptJs {
739 inner: Box::new(Ty::Str16),
740 nullable: true,
741 undefinable: true
742 }
743 );
744 assert_eq!(shape_ty(&shape::parse("'a' | 'b'"), &none, 0), Ty::Str16);
745 assert_eq!(shape_ty(&shape::parse("unknown"), &none, 0), Ty::Dyn);
746 assert!(matches!(
747 shape_ty(&shape::parse("Record<string, number>"), &none, 0),
748 Ty::Map16(_)
749 ));
750 }
751}