Skip to main content

pit_go_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 GoOpts {
9    pub rewrites: BTreeMap<[u8; 32], String>,
10}
11impl GoOpts {
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!("float32"),
17            Arg::F64 => format!("float64"),
18            Arg::Resource {
19                ty,
20                nullable,
21                take,
22                ann,
23            } => match ty {
24                pit_core::ResTy::None => format!("interface{{}}"),
25                pit_core::ResTy::Of(a) => format!(
26                    "{}.P{}",
27                    match self.rewrites.get(a) {
28                        None => format!("pit{}", hex::encode(a)),
29                        Some(b) => b.clone(),
30                    },
31                    hex::encode(a)
32                ),
33                pit_core::ResTy::This => format!("P{}", hex::encode(this)),
34                _ => todo!(),
35            },
36            _ => todo!(),
37        }
38    }
39    pub fn meth(&self, s: &Sig, this: [u8; 32]) -> String {
40        format!(
41            "({}) ({})",
42            s.params
43                .iter()
44                .enumerate()
45                .map(|(a, b)| format!("p{a} {}", self.ty(b, this)))
46                .collect::<Vec<_>>()
47                .join(","),
48            s.rets
49                .iter()
50                .map(|x| self.ty(x, this))
51                .collect::<Vec<_>>()
52                .join(",")
53        )
54    }
55    pub fn interface(&self, i: &Interface) -> String {
56        let this = i.rid();
57        format!(
58            "type P{} interface{{{}}}",
59            hex::encode(this),
60            i.methods
61                .iter()
62                .map(|(a, b)| format!("P{}_{a} {}", hex::encode(this), self.meth(b, this)))
63                .collect::<Vec<_>>()
64                .join("")
65        )
66    }
67}