Skip to main content

pit_swift_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!("UInt32"),
15            Arg::I64 => format!("UInt64"),
16            Arg::F32 => format!("Float"),
17            Arg::F64 => format!("Double"),
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                    "any P{}",
27                    hex::encode(a)
28                ),
29                pit_core::ResTy::This => format!("any 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              .enumerate()
47                .map(|(a, b)| format!("r{a} _: {}", self.ty(b, this)))
48                .collect::<Vec<_>>()
49                .join(",")
50        )
51    }
52    pub fn interface(&self, i: &Interface) -> String {
53        let this = i.rid();
54        format!(
55            "protocol P{} {{{}}}",
56            hex::encode(this),
57            i.methods
58                .iter()
59                .map(|(a, b)| format!("P{}_{a} {}", hex::encode(this), self.meth(b, this)))
60                .collect::<Vec<_>>()
61                .join("")
62        )
63    }
64}