pit_ts_generic/
lib.rs

1#![no_std]
2
3use alloc::{collections::btree_map::BTreeMap, format, string::String, vec::Vec};
4use pit_core::{Arg, Interface, Sig};
5extern crate alloc;
6#[derive(Default, Clone, Debug)]
7#[non_exhaustive]
8pub struct TsOpts {
9    // pub rewrites: BTreeMap<[u8; 32], String>,
10}
11impl TsOpts {
12    pub fn ty(&self, t: &Arg, this: [u8; 32]) -> String {
13        match t {
14            Arg::I32 => format!("number"),
15            Arg::I64 => format!("bigint"),
16            Arg::F32 => format!("number"),
17            Arg::F64 => format!("number"),
18            Arg::Resource {
19                ty,
20                nullable,
21                take,
22                ann,
23            } => match ty {
24                pit_core::ResTy::None => format!("any"),
25                pit_core::ResTy::Of(a) => format!(
26                    "P{}",
27                    hex::encode(a)
28                ),
29                pit_core::ResTy::This => format!("P{}", hex::encode(this)),
30                _ => todo!(),
31            },
32            _ => todo!(),
33        }
34    }
35    pub fn meth(&self, s: &Sig, this: [u8; 32]) -> String {
36        format!(
37            "({}): [{}]",
38            s.params
39                .iter()
40                .enumerate()
41                .map(|(a, b)| format!("p{a}: {}", self.ty(b, this)))
42                .collect::<Vec<_>>()
43                .join(","),
44            s.rets
45                .iter()
46                .map(|x| self.ty(x, this))
47                .collect::<Vec<_>>()
48                .join(",")
49        )
50    }
51    pub fn interface(&self, i: &Interface) -> String {
52        let this = i.rid();
53        format!(
54            "type P{} = {{{}}}",
55            hex::encode(this),
56            i.methods
57                .iter()
58                .map(|(a, b)| format!("P{}_{a} {}", hex::encode(this), self.meth(b, this)))
59                .collect::<Vec<_>>()
60                .join("")
61        )
62    }
63}