Skip to main content

rust_anything/
wire.rs

1//! The binary wire for Go and Java: values cross as compact bytes whose encoders and decoders
2//! are generated per type on both sides, without JSON text or reflection.
3//!
4//! Layout, little endian: `I64` and `F64` as 8 bytes, `Bool` as 1 byte. `Str`, `List`, `Map`
5//! and `Struct` start with a presence byte (0 for null/nil, 1 otherwise); strings then carry a
6//! u32 length and UTF-8 bytes, lists and maps a u32 count and their items (maps as string key,
7//! value). `Opt` is a presence byte and the value. `Tuple` (several results) is its items in order.
8
9use std::fmt::Write as _;
10
11/// A source-language type the wire carries. `native` is the type as the source spells it.
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub enum Ty {
14    I64(String),
15    F64(String),
16    Bool,
17    Str,
18    /// `array` marks a Java array (`int[]`) rather than a list.
19    List {
20        item: Box<Ty>,
21        native: String,
22        array: bool,
23    },
24    Map {
25        value: Box<Ty>,
26        native: String,
27    },
28    /// Fields: (source field name, JSON key, type).
29    Struct {
30        name: String,
31        fields: Vec<(String, String, Ty)>,
32    },
33    Opt {
34        inner: Box<Ty>,
35        native: String,
36    },
37    Tuple(Vec<Ty>),
38    // JS (TS) values: a JS number; a string as UTF-16 code units (lone surrogates survive);
39    // `undefined`/`null`/value; an object whose fields travel by index in the writer's key
40    // order (unknown keys by name); a string-keyed record; and any value, tagged by kind.
41    Num,
42    Str16,
43    OptJs {
44        inner: Box<Ty>,
45        nullable: bool,
46        undefinable: bool,
47    },
48    Obj(Vec<(String, Ty)>),
49    Map16(Box<Ty>),
50    Dyn,
51}
52
53/// The `wire::Schema` constant expression for a type, for `read_value`/`write_value`.
54pub fn schema_expr(t: &Ty) -> String {
55    match t {
56        Ty::I64(_) => "wire::Schema::I64".into(),
57        Ty::F64(_) => "wire::Schema::F64".into(),
58        Ty::Bool => "wire::Schema::Bool".into(),
59        Ty::Str => "wire::Schema::Str".into(),
60        Ty::List { item, .. } => format!("wire::Schema::List(&{})", schema_expr(item)),
61        Ty::Map { value, .. } => format!("wire::Schema::Map(&{})", schema_expr(value)),
62        Ty::Opt { inner, .. } => format!("wire::Schema::Opt(&{})", schema_expr(inner)),
63        Ty::Struct { fields, .. } => format!(
64            "wire::Schema::Struct(&[{}])",
65            fields
66                .iter()
67                .map(|(_, key, t)| format!("({key:?}, {})", schema_expr(t)))
68                .collect::<Vec<_>>()
69                .join(", ")
70        ),
71        Ty::Tuple(items) => format!(
72            "wire::Schema::Tuple(&[{}])",
73            items.iter().map(schema_expr).collect::<Vec<_>>().join(", ")
74        ),
75        Ty::Num => "wire::Schema::Num".into(),
76        Ty::Str16 => "wire::Schema::Str16".into(),
77        Ty::OptJs { inner, .. } => format!("wire::Schema::OptJs(&{})", schema_expr(inner)),
78        Ty::Obj(fields) => format!(
79            "wire::Schema::Obj(&[{}])",
80            fields
81                .iter()
82                .map(|(key, t)| format!("({key:?}, {})", schema_expr(t)))
83                .collect::<Vec<_>>()
84                .join(", ")
85        ),
86        Ty::Map16(value) => format!("wire::Schema::Map16(&{})", schema_expr(value)),
87        Ty::Dyn => "wire::Schema::Dyn".into(),
88    }
89}
90
91fn generic_arg<'a>(rust: &'a str, head: &str) -> Option<&'a str> {
92    let rust = rust.trim();
93    let rest = rust
94        .strip_prefix(head)
95        .or_else(|| rust.strip_prefix(&format!("std::collections::{head}")))?;
96    rest.strip_prefix('<')?.strip_suffix('>').map(str::trim)
97}
98
99fn map_value(rust: &str) -> Option<&str> {
100    for head in ["HashMap", "BTreeMap", "IndexMap"] {
101        if let Some(args) = generic_arg(rust, head) {
102            let (key, value) = args.split_once(',')?;
103            return (key.trim() == "String").then_some(value.trim());
104        }
105    }
106    None
107}
108
109fn is_value(rust: &str) -> bool {
110    matches!(rust.trim(), "serde_json::Value" | "Value")
111}
112
113/// A closure body: `r.f64()` stays as is, anything else is wrapped in `Ok(...)`.
114fn body(read: &str) -> String {
115    match read.strip_suffix('?') {
116        Some(call) if !call.contains('?') => call.to_string(),
117        _ => format!("Ok({read})"),
118    }
119}
120
121/// A schema as an argument: `&S` for a static, `S.inner()` (already a reference) as is.
122fn schema_ref(schema: &str) -> String {
123    if schema.ends_with(')') {
124        schema.to_string()
125    } else {
126        format!("&{schema}")
127    }
128}
129
130/// Rust code reading a value of `t` into the port type `rust` from reader `r`; `None` when the
131/// port type does not fit the wire type (the function then keeps the JSON bridge).
132pub fn rust_read(t: &Ty, rust: &str, schema: &str) -> Option<String> {
133    if is_value(rust) {
134        return Some(format!("wire::read_value(r, {})?", schema_ref(schema)));
135    }
136    let rust = rust.trim();
137    if *t == Ty::Dyn
138        && matches!(
139            rust.split_whitespace().collect::<String>().as_str(),
140            "Option<Value>" | "Option<serde_json::Value>"
141        )
142    {
143        return Some("wire::read_dyn_opt(r)?".into());
144    }
145    if *t == Ty::Dyn {
146        // Any JS value into a typed port parameter: through a tagged value and serde.
147        return Some(
148            "serde_json::from_value(wire::read_dyn(r)?).map_err(|e| format!(\"TypeError: {e}\"))?"
149                .into(),
150        );
151    }
152    let structural = rust_read_structural(t, rust, schema);
153    if structural.is_none() && rust.contains("Value") {
154        return Some(format!(
155            "serde_json::from_value(wire::read_value(r, {})?).map_err(|e| format!(\"TypeError: {{e}}\"))?",
156            schema_ref(schema)
157        ));
158    }
159    structural
160}
161
162fn rust_read_structural(t: &Ty, rust: &str, schema: &str) -> Option<String> {
163    Some(match t {
164        Ty::I64(_) if rust == "i64" => "r.i64()?".into(),
165        Ty::F64(_) if rust == "f64" => "r.f64()?".into(),
166        Ty::Bool if rust == "bool" => "r.bool()?".into(),
167        Ty::Str if rust == "String" => "r.string()?".into(),
168        Ty::Opt { inner, .. } => match generic_arg(rust, "Option") {
169            Some(inner_rust) => format!(
170                "r.opt(|r| {})?",
171                body(&rust_read(inner, inner_rust, &format!("{schema}.inner()"))?)
172            ),
173            None => format!(
174                "r.required(|r| {})?",
175                body(&rust_read(inner, rust, &format!("{schema}.inner()"))?)
176            ),
177        },
178        Ty::List { item, .. } => format!(
179            "r.list(|r| {})?",
180            body(&rust_read(
181                item,
182                generic_arg(rust, "Vec")?,
183                &format!("{schema}.inner()")
184            )?)
185        ),
186        Ty::Map { value, .. } => format!(
187            "r.map(|r| {})?.into_iter().collect()",
188            body(&rust_read(
189                value,
190                map_value(rust)?,
191                &format!("{schema}.inner()")
192            )?)
193        ),
194        Ty::Num if rust == "f64" => "r.f64()?".into(),
195        Ty::Str16 if rust == "String" => "r.string16()?".into(),
196        Ty::Str16 if rust == "Vec<u16>" => "r.units()?".into(),
197        Ty::OptJs { inner, .. } => match generic_arg(rust, "Option") {
198            Some(inner_rust) => format!(
199                "r.opt_js(|r| {})?",
200                body(&rust_read(inner, inner_rust, &format!("{schema}.inner()"))?)
201            ),
202            None => format!(
203                "r.required_js(|r| {})?",
204                body(&rust_read(inner, rust, &format!("{schema}.inner()"))?)
205            ),
206        },
207        Ty::Map16(value) => format!(
208            "r.map16(|r| {})?.into_iter().collect()",
209            body(&rust_read(
210                value,
211                map_value(rust)?,
212                &format!("{schema}.inner()")
213            )?)
214        ),
215        _ => return None,
216    })
217}
218
219/// Rust statements writing `expr` (a reference to the port type `rust`) as `t` into writer `w`.
220pub fn rust_write(t: &Ty, rust: &str, expr: &str, schema: &str, depth: usize) -> Option<String> {
221    if is_value(rust) {
222        return Some(format!(
223            "wire::write_value(w, {expr}, {})?;",
224            schema_ref(schema)
225        ));
226    }
227    if *t == Ty::Dyn {
228        // `serde_json::to_value` turns NaN and the infinities into `Value::Null`, so a scalar
229        // float whose declaration is only `unknown` goes over the wire as a number: JS then sees
230        // NaN and ±Infinity, instead of `null` that `diff` blames on the port.
231        let spelled = rust.trim();
232        let scalar = spelled.rsplit("::").next().unwrap_or(spelled);
233        if matches!(scalar, "f64" | "f32") {
234            return Some(format!("w.tag(4); w.f64(f64::from(*{expr}));"));
235        }
236        return Some(format!(
237            "wire::write_dyn(w, &serde_json::to_value({expr}).map_err(|e| e.to_string())?);"
238        ));
239    }
240    if rust.contains("Value") {
241        if let Some(code) = rust_write_structural(t, rust, expr, schema, depth) {
242            return Some(code);
243        }
244        return Some(format!(
245            "wire::write_value(w, &serde_json::to_value({expr}).map_err(|e| e.to_string())?, {})?;",
246            schema_ref(schema)
247        ));
248    }
249    rust_write_structural(t, rust, expr, schema, depth)
250}
251
252fn rust_write_structural(
253    t: &Ty,
254    rust: &str,
255    expr: &str,
256    schema: &str,
257    depth: usize,
258) -> Option<String> {
259    let rust = rust.trim();
260    let x = format!("x{depth}");
261    // A method receiver: `out` as is, `&out` in parentheses.
262    let r = if expr.starts_with('&') {
263        format!("({expr})")
264    } else {
265        expr.to_string()
266    };
267    Some(match t {
268        Ty::I64(_) if rust == "i64" => format!("w.i64(*{expr});"),
269        Ty::F64(_) if rust == "f64" => format!("w.f64(*{expr});"),
270        Ty::Bool if rust == "bool" => format!("w.bool(*{expr});"),
271        Ty::Str if rust == "String" => format!("w.string({expr});"),
272        Ty::Opt { inner, .. } => {
273            let inner_schema = format!("{schema}.inner()");
274            match generic_arg(rust, "Option") {
275                Some(inner_rust) => format!(
276                    "match {expr} {{ Some({x}) => {{ w.tag(1); {} }} None => w.tag(0) }}",
277                    rust_write(inner, inner_rust, &x, &inner_schema, depth + 1)?
278                ),
279                None => format!(
280                    "w.tag(1); {}",
281                    rust_write(inner, rust, expr, &inner_schema, depth + 1)?
282                ),
283            }
284        }
285        Ty::List { item, .. } => format!(
286            "w.tag(1); w.count({r}.len()); for {x} in {r}.iter() {{ {} }}",
287            rust_write(
288                item,
289                generic_arg(rust, "Vec")?,
290                &x,
291                &format!("{schema}.inner()"),
292                depth + 1
293            )?
294        ),
295        Ty::Map { value, .. } => format!(
296            "w.tag(1); w.count({r}.len()); for (k{depth}, {x}) in {r}.iter() {{ w.string(k{depth}); {} }}",
297            rust_write(
298                value,
299                map_value(rust)?,
300                &x,
301                &format!("{schema}.inner()"),
302                depth + 1
303            )?
304        ),
305        Ty::Num if rust == "f64" => format!("w.f64(*{expr});"),
306        Ty::Str16 if rust == "String" => format!("w.string16({expr});"),
307        Ty::Str16 if rust == "Vec<u16>" => format!("w.units({expr});"),
308        Ty::OptJs {
309            inner, undefinable, ..
310        } => {
311            let inner_schema = format!("{schema}.inner()");
312            // `None` is `undefined`, or `null` for a `T | null` that cannot be undefined.
313            let none = if *undefinable { 0 } else { 2 };
314            match generic_arg(rust, "Option") {
315                Some(inner_rust) => format!(
316                    "match {expr} {{ Some({x}) => {{ w.tag(1); {} }} None => w.tag({none}) }}",
317                    rust_write(inner, inner_rust, &x, &inner_schema, depth + 1)?
318                ),
319                None => format!(
320                    "w.tag(1); {}",
321                    rust_write(inner, rust, expr, &inner_schema, depth + 1)?
322                ),
323            }
324        }
325        Ty::Map16(value) => format!(
326            "w.tag(1); w.count({r}.len()); for (k{depth}, {x}) in {r}.iter() {{ w.string16(k{depth}); {} }}",
327            rust_write(
328                value,
329                map_value(rust)?,
330                &x,
331                &format!("{schema}.inner()"),
332                depth + 1
333            )?
334        ),
335        _ => return None,
336    })
337}
338
339/// `src/wire.rs` of a generated crate: the reader, the writer, and schema-driven conversion of
340/// `serde_json::Value` (for ports that keep structured values as JSON values).
341pub const WIRE_RS: &str = r#"//! The binary wire between the source language and the port. Generated by rust-anything.
342
343#![forbid(unsafe_code)]
344#![allow(dead_code)]
345
346use serde_json::{Map, Value, json};
347
348/// A wire type, for converting `serde_json::Value`s.
349pub enum Schema {
350    I64,
351    F64,
352    Bool,
353    Str,
354    List(&'static Schema),
355    Map(&'static Schema),
356    Opt(&'static Schema),
357    Struct(&'static [(&'static str, Schema)]),
358    Tuple(&'static [Schema]),
359    Num,
360    Str16,
361    OptJs(&'static Schema),
362    Obj(&'static [(&'static str, Schema)]),
363    Map16(&'static Schema),
364    Dyn,
365}
366
367impl Schema {
368    /// The item type of a list, map or option.
369    pub const fn inner(&self) -> &Schema {
370        match self {
371            Self::List(s) | Self::Map(s) | Self::Opt(s) | Self::OptJs(s) | Self::Map16(s) => s,
372            _ => self,
373        }
374    }
375}
376
377pub struct Reader<'a> {
378    bytes: &'a [u8],
379    at: usize,
380}
381
382const SHORT: &str = "TypeError: wire data ended early";
383
384impl<'a> Reader<'a> {
385    pub fn new(bytes: &'a [u8]) -> Self {
386        Self { bytes, at: 0 }
387    }
388
389    fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
390        let end = self.at.checked_add(n).filter(|&e| e <= self.bytes.len()).ok_or(SHORT)?;
391        let out = &self.bytes[self.at..end];
392        self.at = end;
393        Ok(out)
394    }
395
396    pub fn tag(&mut self) -> Result<u8, String> {
397        Ok(self.take(1)?[0])
398    }
399
400    pub fn count(&mut self) -> Result<usize, String> {
401        let b = self.take(4)?;
402        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize)
403    }
404
405    pub fn i64(&mut self) -> Result<i64, String> {
406        let b = self.take(8)?;
407        Ok(i64::from_le_bytes(b.try_into().map_err(|_| SHORT)?))
408    }
409
410    pub fn f64(&mut self) -> Result<f64, String> {
411        let b = self.take(8)?;
412        Ok(f64::from_le_bytes(b.try_into().map_err(|_| SHORT)?))
413    }
414
415    pub fn bool(&mut self) -> Result<bool, String> {
416        Ok(self.tag()? != 0)
417    }
418
419    /// A string; `None` for null.
420    pub fn opt_string(&mut self) -> Result<Option<String>, String> {
421        if self.tag()? == 0 {
422            return Ok(None);
423        }
424        let n = self.count()?;
425        Ok(Some(String::from_utf8_lossy(self.take(n)?).into_owned()))
426    }
427
428    pub fn string(&mut self) -> Result<String, String> {
429        self.opt_string()?
430            .ok_or_else(|| "NullPointerException: null string".to_string())
431    }
432
433    pub fn opt<T>(&mut self, item: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<Option<T>, String> {
434        if self.tag()? == 0 { Ok(None) } else { item(self).map(Some) }
435    }
436
437    pub fn required<T>(&mut self, item: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
438        self.opt(item)?
439            .ok_or_else(|| "NullPointerException: null value".to_string())
440    }
441
442    /// A JS string as UTF-16 code units.
443    pub fn units(&mut self) -> Result<Vec<u16>, String> {
444        if self.tag()? == 0 {
445            return Err("TypeError: expected a string".into());
446        }
447        let n = self.count()?;
448        let bytes = self.take(n.checked_mul(2).ok_or(SHORT)?)?;
449        Ok(bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect())
450    }
451
452    /// A JS string; lone surrogates become U+FFFD, as napi's own conversion does.
453    pub fn string16(&mut self) -> Result<String, String> {
454        Ok(String::from_utf16_lossy(&self.units()?))
455    }
456
457    /// A JS optional value: 0 `undefined`, 1 a value, 2 `null`.
458    pub fn opt_js<T>(&mut self, item: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<Option<T>, String> {
459        if self.tag()? == 1 { item(self).map(Some) } else { Ok(None) }
460    }
461
462    pub fn required_js<T>(&mut self, item: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
463        self.opt_js(item)?
464            .ok_or_else(|| "TypeError: expected a value, got undefined or null".to_string())
465    }
466
467    /// A string-keyed record (keys as JS strings).
468    pub fn map16<T>(&mut self, mut item: impl FnMut(&mut Self) -> Result<T, String>) -> Result<Vec<(String, T)>, String> {
469        if self.tag()? == 0 {
470            return Ok(Vec::new());
471        }
472        let n = self.count()?;
473        let mut out = Vec::with_capacity(n.min(1 << 16));
474        for _ in 0..n {
475            let key = self.string16()?;
476            out.push((key, item(self)?));
477        }
478        Ok(out)
479    }
480
481    /// A list; nil reads as empty.
482    pub fn list<T>(&mut self, mut item: impl FnMut(&mut Self) -> Result<T, String>) -> Result<Vec<T>, String> {
483        if self.tag()? == 0 {
484            return Ok(Vec::new());
485        }
486        let n = self.count()?;
487        let mut out = Vec::with_capacity(n.min(1 << 16));
488        for _ in 0..n {
489            out.push(item(self)?);
490        }
491        Ok(out)
492    }
493
494    /// A map's entries; nil reads as empty.
495    pub fn map<T>(&mut self, mut item: impl FnMut(&mut Self) -> Result<T, String>) -> Result<Vec<(String, T)>, String> {
496        if self.tag()? == 0 {
497            return Ok(Vec::new());
498        }
499        let n = self.count()?;
500        let mut out = Vec::with_capacity(n.min(1 << 16));
501        for _ in 0..n {
502            let key = self.string()?;
503            out.push((key, item(self)?));
504        }
505        Ok(out)
506    }
507}
508
509#[derive(Default)]
510pub struct Writer(pub Vec<u8>);
511
512impl Writer {
513    pub fn tag(&mut self, t: u8) {
514        self.0.push(t);
515    }
516
517    pub fn count(&mut self, n: usize) {
518        self.0.extend_from_slice(&u32::try_from(n).unwrap_or(u32::MAX).to_le_bytes());
519    }
520
521    pub fn i64(&mut self, v: i64) {
522        self.0.extend_from_slice(&v.to_le_bytes());
523    }
524
525    pub fn f64(&mut self, v: f64) {
526        self.0.extend_from_slice(&v.to_le_bytes());
527    }
528
529    pub fn bool(&mut self, v: bool) {
530        self.0.push(u8::from(v));
531    }
532
533    pub fn string(&mut self, s: &str) {
534        self.tag(1);
535        self.count(s.len());
536        self.0.extend_from_slice(s.as_bytes());
537    }
538
539    /// A JS string from a Rust one (well-formed: tag 1).
540    pub fn string16(&mut self, s: &str) {
541        self.tag(1);
542        let at = self.0.len();
543        self.count(0);
544        let mut n = 0usize;
545        for u in s.encode_utf16() {
546            self.0.extend_from_slice(&u.to_le_bytes());
547            n += 1;
548        }
549        self.0[at..at + 4].copy_from_slice(&u32::try_from(n).unwrap_or(u32::MAX).to_le_bytes());
550    }
551
552    /// A JS string from code units, lone surrogates included (tag 4).
553    pub fn units(&mut self, units: &[u16]) {
554        self.tag(4);
555        self.count(units.len());
556        for u in units {
557            self.0.extend_from_slice(&u.to_le_bytes());
558        }
559    }
560}
561
562fn float_value(x: f64) -> Value {
563    if x.is_nan() {
564        json!({"$num": "NaN"})
565    } else if x.is_infinite() {
566        json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
567    } else if x == 0.0 && x.is_sign_negative() {
568        json!({"$num": "-0"})
569    } else {
570        json!(x)
571    }
572}
573
574fn value_float(v: &Value) -> Option<f64> {
575    match v {
576        Value::Number(n) => n.as_f64(),
577        Value::Object(o) => match o.get("$num")?.as_str()? {
578            "NaN" => Some(f64::NAN),
579            "Infinity" => Some(f64::INFINITY),
580            "-Infinity" => Some(f64::NEG_INFINITY),
581            "-0" => Some(-0.0),
582            _ => None,
583        },
584        _ => None,
585    }
586}
587
588/// Reads a value of `schema` as JSON: null for nil, `{"$num": ...}` for NaN and infinities.
589pub fn read_value(r: &mut Reader, schema: &Schema) -> Result<Value, String> {
590    Ok(match schema {
591        Schema::I64 => json!(r.i64()?),
592        Schema::F64 => float_value(r.f64()?),
593        Schema::Bool => Value::Bool(r.bool()?),
594        Schema::Str => r.opt_string()?.map_or(Value::Null, Value::String),
595        Schema::Opt(inner) => r.opt(|r| read_value(r, inner))?.unwrap_or(Value::Null),
596        Schema::List(item) => {
597            if r.tag()? == 0 {
598                Value::Null
599            } else {
600                let n = r.count()?;
601                let mut out = Vec::with_capacity(n.min(1 << 16));
602                for _ in 0..n {
603                    out.push(read_value(r, item)?);
604                }
605                Value::Array(out)
606            }
607        }
608        Schema::Map(item) => {
609            if r.tag()? == 0 {
610                Value::Null
611            } else {
612                let n = r.count()?;
613                let mut out = Map::new();
614                for _ in 0..n {
615                    let key = r.string()?;
616                    out.insert(key, read_value(r, item)?);
617                }
618                Value::Object(out)
619            }
620        }
621        Schema::Struct(fields) => {
622            if r.tag()? == 0 {
623                Value::Null
624            } else {
625                let mut out = Map::new();
626                for (key, field) in *fields {
627                    out.insert((*key).to_string(), read_value(r, field)?);
628                }
629                Value::Object(out)
630            }
631        }
632        Schema::Tuple(items) => Value::Array(items.iter().map(|s| read_value(r, s)).collect::<Result<_, _>>()?),
633        Schema::Num => js_number(r.f64()?),
634        Schema::Str16 => js_string(r.units()?),
635        Schema::OptJs(inner) => match r.tag()? {
636            1 => read_value(r, inner)?,
637            2 => Value::Null,
638            _ => json!({"$undefined": true}),
639        },
640        Schema::Obj(fields) => {
641            let n = r.tag()?;
642            let mut out = Map::new();
643            for _ in 0..n {
644                let index = usize::from(r.tag()?);
645                match fields.get(index) {
646                    Some((key, field)) => {
647                        out.insert((*key).to_string(), read_value(r, field)?);
648                    }
649                    None => {
650                        let key = r.string16()?;
651                        out.insert(key, read_dyn(r)?);
652                    }
653                }
654            }
655            Value::Object(out)
656        }
657        Schema::Map16(item) => {
658            if r.tag()? == 0 {
659                Value::Null
660            } else {
661                let n = r.count()?;
662                let mut out = Map::new();
663                for _ in 0..n {
664                    let key = r.string16()?;
665                    out.insert(key, read_value(r, item)?);
666                }
667                Value::Object(out)
668            }
669        }
670        Schema::Dyn => read_dyn(r)?,
671    })
672}
673
674/// A JS number as JSON, as the JSON bridge reads it: integers as integers, markers for the rest.
675fn js_number(x: f64) -> Value {
676    if x.is_finite() && !(x == 0.0 && x.is_sign_negative()) && x.fract() == 0.0 && x.abs() < 9_007_199_254_740_992.0 {
677        json!(x as i64)
678    } else {
679        float_value(x)
680    }
681}
682
683/// A JS string as JSON: lone surrogates as `{"$utf16": [...]}`.
684fn js_string(units: Vec<u16>) -> Value {
685    match String::from_utf16(&units) {
686        Ok(s) => Value::String(s),
687        Err(_) => json!({"$utf16": units}),
688    }
689}
690
691/// Any JS value, tagged: 0 undefined, 1 null, 2 false, 3 true, 4 number, 5 string, 6 array,
692/// 7 object.
693/// An optional JS value: `undefined` and `null` are `None`, as JSON gives for an `Option`.
694pub fn read_dyn_opt(r: &mut Reader) -> Result<Option<Value>, String> {
695    if matches!(r.bytes.get(r.at), Some(0 | 1)) {
696        r.at += 1;
697        return Ok(None);
698    }
699    read_dyn(r).map(Some)
700}
701
702pub fn read_dyn(r: &mut Reader) -> Result<Value, String> {
703    let units = |r: &mut Reader| -> Result<Vec<u16>, String> {
704        let n = r.count()?;
705        let bytes = r.take(n.checked_mul(2).ok_or(SHORT)?)?;
706        Ok(bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect())
707    };
708    Ok(match r.tag()? {
709        0 => json!({"$undefined": true}),
710        1 => Value::Null,
711        2 => Value::Bool(false),
712        3 => Value::Bool(true),
713        4 => js_number(r.f64()?),
714        5 => js_string(units(r)?),
715        6 => {
716            let n = r.count()?;
717            let mut out = Vec::with_capacity(n.min(1 << 16));
718            for _ in 0..n {
719                out.push(read_dyn(r)?);
720            }
721            Value::Array(out)
722        }
723        7 => {
724            let n = r.count()?;
725            let mut out = Map::new();
726            for _ in 0..n {
727                let key = String::from_utf16_lossy(&units(r)?);
728                out.insert(key, read_dyn(r)?);
729            }
730            Value::Object(out)
731        }
732        t => return Err(format!("TypeError: unknown value tag {t}")),
733    })
734}
735
736fn marker<'v>(v: &'v Value, key: &str) -> Option<&'v Value> {
737    v.as_object().filter(|o| o.len() == 1).and_then(|o| o.get(key))
738}
739
740fn write_units16(w: &mut Writer, v: &Value) -> Option<()> {
741    if let Value::String(s) = v {
742        w.string16(s);
743        return Some(());
744    }
745    let units: Vec<u16> = marker(v, "$utf16")?
746        .as_array()?
747        .iter()
748        .map(|u| u.as_u64().and_then(|u| u16::try_from(u).ok()))
749        .collect::<Option<_>>()?;
750    w.units(&units);
751    Some(())
752}
753
754/// Writes any JSON value as a tagged JS value; markers become what they stand for.
755pub fn write_dyn(w: &mut Writer, v: &Value) {
756    match v {
757        Value::Null => w.tag(1),
758        Value::Bool(b) => w.tag(if *b { 3 } else { 2 }),
759        Value::Number(n) => {
760            w.tag(4);
761            w.f64(n.as_f64().unwrap_or(f64::NAN));
762        }
763        Value::String(s) => {
764            w.tag(5);
765            let units: Vec<u16> = s.encode_utf16().collect();
766            w.count(units.len());
767            for u in units {
768                w.0.extend_from_slice(&u.to_le_bytes());
769            }
770        }
771        Value::Array(items) => {
772            w.tag(6);
773            w.count(items.len());
774            for x in items {
775                write_dyn(w, x);
776            }
777        }
778        Value::Object(o) => {
779            if marker(v, "$undefined").is_some() {
780                w.tag(0);
781            } else if let Some(x) = value_float(v).filter(|_| marker(v, "$num").is_some()) {
782                w.tag(4);
783                w.f64(x);
784            } else if let Some(units) = marker(v, "$utf16").and_then(Value::as_array) {
785                w.tag(5);
786                w.count(units.len());
787                for u in units {
788                    w.0.extend_from_slice(&u16::try_from(u.as_u64().unwrap_or(0xFFFD)).unwrap_or(0xFFFD).to_le_bytes());
789                }
790            } else {
791                w.tag(7);
792                w.count(o.len());
793                for (k, x) in o {
794                    let units: Vec<u16> = k.encode_utf16().collect();
795                    w.count(units.len());
796                    for u in units {
797                        w.0.extend_from_slice(&u.to_le_bytes());
798                    }
799                    write_dyn(w, x);
800                }
801            }
802        }
803    }
804}
805
806/// The start of the error a result of the wrong shape raises; JS bridges answer it by running
807/// the call through JSON instead.
808pub const MISMATCH: &str = "TypeError: the port returned ";
809
810fn mismatch(schema: &str, v: &Value) -> String {
811    format!("{MISMATCH}{v} where the original returns {schema}")
812}
813
814/// Writes a JSON value as `schema`; the port's value must fit the original's type.
815pub fn write_value(w: &mut Writer, v: &Value, schema: &Schema) -> Result<(), String> {
816    match schema {
817        Schema::I64 => w.i64(v.as_i64().or_else(|| v.as_f64().filter(|f| f.fract() == 0.0).map(|f| f as i64)).ok_or_else(|| mismatch("an integer", v))?),
818        Schema::F64 => w.f64(value_float(v).ok_or_else(|| mismatch("a float", v))?),
819        Schema::Bool => w.bool(v.as_bool().ok_or_else(|| mismatch("a bool", v))?),
820        Schema::Str => match v {
821            Value::Null => w.tag(0),
822            Value::String(s) => w.string(s),
823            _ => return Err(mismatch("a string", v)),
824        },
825        Schema::Opt(inner) => {
826            if v.is_null() {
827                w.tag(0);
828            } else {
829                w.tag(1);
830                write_value(w, v, inner)?;
831            }
832        }
833        Schema::List(item) => match v {
834            Value::Null => w.tag(0),
835            Value::Array(items) => {
836                w.tag(1);
837                w.count(items.len());
838                for x in items {
839                    write_value(w, x, item)?;
840                }
841            }
842            _ => return Err(mismatch("a list", v)),
843        },
844        Schema::Map(item) => match v {
845            Value::Null => w.tag(0),
846            Value::Object(o) => {
847                w.tag(1);
848                w.count(o.len());
849                for (k, x) in o {
850                    w.string(k);
851                    write_value(w, x, item)?;
852                }
853            }
854            _ => return Err(mismatch("a map", v)),
855        },
856        Schema::Struct(fields) => match v {
857            Value::Null => w.tag(0),
858            Value::Object(o) => {
859                w.tag(1);
860                for (key, field) in *fields {
861                    write_value(w, o.get(*key).unwrap_or(&Value::Null), field)?;
862                }
863            }
864            _ => return Err(mismatch("a struct", v)),
865        },
866        Schema::Tuple(items) => match v {
867            Value::Array(values) if values.len() == items.len() => {
868                for (x, s) in values.iter().zip(*items) {
869                    write_value(w, x, s)?;
870                }
871            }
872            _ => return Err(mismatch("several results", v)),
873        },
874        Schema::Num => w.f64(value_float(v).ok_or_else(|| mismatch("a number", v))?),
875        Schema::Str16 => write_units16(w, v).ok_or_else(|| mismatch("a string", v))?,
876        Schema::OptJs(inner) => {
877            if marker(v, "$undefined").is_some() {
878                w.tag(0);
879            } else if v.is_null() {
880                w.tag(2);
881            } else {
882                w.tag(1);
883                write_value(w, v, inner)?;
884            }
885        }
886        Schema::Obj(fields) => {
887            let o = v.as_object().ok_or_else(|| mismatch("an object", v))?;
888            w.tag(u8::try_from(o.len()).map_err(|_| mismatch("an object of at most 255 keys", v))?);
889            for (k, x) in o {
890                match fields.iter().position(|(key, _)| key == k) {
891                    Some(i) if i < 255 => {
892                        w.tag(i as u8);
893                        write_value(w, x, &fields[i].1)?;
894                    }
895                    _ => {
896                        w.tag(255);
897                        w.string16(k);
898                        write_dyn(w, x);
899                    }
900                }
901            }
902        }
903        Schema::Map16(item) => match v {
904            Value::Null => w.tag(0),
905            Value::Object(o) => {
906                w.tag(1);
907                w.count(o.len());
908                for (k, x) in o {
909                    w.string16(k);
910                    write_value(w, x, item)?;
911                }
912            }
913            _ => return Err(mismatch("a record", v)),
914        },
915        Schema::Dyn => write_dyn(w, v),
916    }
917    Ok(())
918}
919"#;
920
921/// Rust statements that read every argument of a port function from `r`; `None` when one does
922/// not fit.
923pub fn rust_read_args(
924    params: &[(String, Ty)],
925    port_params: &[(String, String)],
926    schema_prefix: &str,
927    statics: &mut String,
928) -> Option<String> {
929    let mut out = String::new();
930    for (i, ((_, ty), (name, rust))) in params.iter().zip(port_params).enumerate() {
931        let schema = format!("{schema_prefix}_{i}");
932        let read = rust_read(ty, rust, &schema)?;
933        if read.contains(&schema) {
934            let _ = writeln!(
935                statics,
936                "static {schema}: wire::Schema = {};",
937                schema_expr(ty)
938            );
939        }
940        let _ = writeln!(out, "        let {name}: {rust} = {read};");
941    }
942    Some(out)
943}
944
945#[cfg(test)]
946mod tests {
947    use super::*;
948
949    fn list(item: Ty) -> Ty {
950        Ty::List {
951            item: Box::new(item),
952            native: String::new(),
953            array: false,
954        }
955    }
956
957    #[test]
958    fn reads_fit_the_port_types() {
959        let strings = list(Ty::Str);
960        assert_eq!(
961            rust_read(&strings, "Vec<String>", "S").unwrap(),
962            "r.list(|r| r.string())?"
963        );
964        let boxed = Ty::Opt {
965            inner: Box::new(Ty::I64("int".into())),
966            native: "Integer".into(),
967        };
968        assert_eq!(
969            rust_read(&boxed, "i64", "S").unwrap(),
970            "r.required(|r| r.i64())?"
971        );
972        assert_eq!(
973            rust_read(&boxed, "Option<i64>", "S").unwrap(),
974            "r.opt(|r| r.i64())?"
975        );
976        assert_eq!(
977            rust_read(&strings, "serde_json::Value", "S").unwrap(),
978            "wire::read_value(r, &S)?"
979        );
980        // A port type that does not fit the wire type keeps the JSON bridge.
981        assert!(rust_read(&strings, "Vec<i64>", "S").is_none());
982    }
983
984    #[test]
985    fn a_scalar_float_under_an_untyped_declaration_keeps_nan_and_infinities() {
986        // `serde_json::to_value(NaN)` is `Value::Null`, so a port typed `f64` whose declaration
987        // says only `unknown` reached JS as `null`: `diff` then blamed the port for a binding bug.
988        let code = rust_write(&Ty::Dyn, "f64", "out", "S", 0).unwrap();
989        assert!(code.contains("w.f64("), "{code}");
990        assert!(!code.contains("to_value"), "{code}");
991        let single = rust_write(&Ty::Dyn, "f32", "out", "S", 0).unwrap();
992        assert!(single.contains("w.f64("), "{single}");
993        // A qualified spelling is the same type.
994        for spelled in ["std::primitive::f64", "core::primitive::f32"] {
995            let qualified = rust_write(&Ty::Dyn, spelled, "out", "S", 0).unwrap();
996            assert!(qualified.contains("w.f64("), "{spelled}: {qualified}");
997            assert!(!qualified.contains("to_value"), "{spelled}: {qualified}");
998        }
999    }
1000
1001    #[test]
1002    fn writes_fit_the_port_types() {
1003        let floats = list(Ty::F64("double".into()));
1004        assert_eq!(
1005            rust_write(&floats, "Vec<f64>", "out", "S", 0).unwrap(),
1006            "w.tag(1); w.count(out.len()); for x0 in out.iter() { w.f64(*x0); }"
1007        );
1008        assert_eq!(
1009            schema_expr(&floats),
1010            "wire::Schema::List(&wire::Schema::F64)"
1011        );
1012    }
1013}