wars_pit_plugin/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use std::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet},
    convert::Infallible,
    f32::consts::E,
    iter::once,
    sync::{Arc, Mutex, OnceLock},
};
use wars::*;

use pit_core::{Arg, Interface};
use proc_macro2::{Span, TokenStream};
use quasiquote::quasiquote;
use quote::{format_ident, quote, ToTokens};
use relooper::{reloop, BranchMode, ShapedBlock};
use sha3::Digest;
use syn::{Ident, Lifetime};
use waffle::{
    cfg::CFGInfo, entity::EntityRef, Block, BlockTarget, Export, ExportKind, Func, ImportKind,
    Memory, Module, Operator, Signature, SignatureData, Type, Value,
};
#[derive(Default)]
pub struct PitPlugin {
    pub tpit: OnceLock<BTreeSet<pit_core::Interface>>,
    pub extra: Vec<Arc<dyn PitPluginPlugin>>,
}

pub trait PitPluginPlugin {
    fn choose_type(&self, opts: &Opts<Module<'static>>) -> anyhow::Result<Option<TokenStream>>;
    fn emit_method(
        &self,
        opts: &Opts<Module<'static>>,
        i: &Interface,
        s: &str,
        value: TokenStream,
        params: &[TokenStream],
    ) -> anyhow::Result<TokenStream>;
    fn post(&self, parent: &PitPlugin, opts: &Opts<Module<'static>>)
        -> anyhow::Result<TokenStream>;
}

impl PitPlugin {
    pub fn tpit(&self, opts: &Opts<Module<'static>>) -> &BTreeSet<Interface> {
        return self.tpit.get_or_init(|| {
            pit_patch::get_interfaces(&opts.module)
                .unwrap()
                .into_iter()
                .collect()
        });
    }
    pub fn host_tpit(&self, opts: &Opts<Module<'static>>) -> anyhow::Result<TokenStream> {
        let mut a = opts.host_tpit();
        let root = &opts.crate_path;
        for e in self.extra.iter() {
            if let Some(c) = e.choose_type(opts)? {
                a = quote! {
                    #root::Either<#c,#a>
                };
            }
        }
        return Ok(a);
    }
    pub fn apply_host(
        &self,
        mut x: TokenStream,
        opts: &Opts<Module<'static>>,
        i: &Interface,
        s: &str,
        params: &[TokenStream],
    ) -> anyhow::Result<TokenStream> {
        let root = &opts.crate_path;
        for e in self.extra.iter() {
            if let Some(c) = e.choose_type(opts)? {
                x = quasiquote! {
                    match host{
                        #root::Either::Right(host) => #x,
                        #root::Either::Left(host) => #{e.emit_method(opts, i, s, quote! {host}, params)?},
                    }
                };
            }
        }
        return Ok(x);
    }
    pub fn wrap(
        &self,
        opts: &Opts<Module<'static>>,
        mut x: TokenStream,
    ) -> anyhow::Result<TokenStream> {
        let root = &opts.crate_path;
        for e in self.extra.iter() {
            if let Some(c) = e.choose_type(opts)? {
                x = quasiquote! {
                    #root::Either::Right(#x)
                };
            }
        }
        return Ok(x);
    }
}
impl Plugin for PitPlugin {
    fn exref_bounds(&self, opts: &Opts<Module<'static>>) -> anyhow::Result<Option<TokenStream>> {
        let root = &opts.crate_path;
        Ok(Some(
            quasiquote! {From<#root::Pit<Vec<#{opts.fp()}::Value<Self>>,#{self.host_tpit(opts)?}>> + TryInto<#root::Pit<Vec<#{opts.fp()}::Value<Self>>,#{self.host_tpit(opts)?}>>},
        ))
    }
    fn pre(&self, module: &mut Module<'static>) -> anyhow::Result<()> {
        Ok(())
    }

    fn import(
        &self,
        opts: &Opts<Module<'static>>,
        module: &str,
        name: &str,
        params: Vec<TokenStream>,
    ) -> anyhow::Result<Option<TokenStream>> {
        let root = &opts.crate_path;
        let mut params = params.into_iter();
        if let Some(i) = module.strip_prefix("pit/") {
            let x: [u8; 32] = hex::decode(i).unwrap().try_into().unwrap();
            if let Some(s) = name.strip_prefix("~") {
                let s = {
                    let mut h = sha3::Sha3_256::default();
                    h.update(s);
                    h.finalize()
                };
                return Ok(Some(quasiquote! {
                    #{opts.fp()}::ret(Ok(#{opts.fp()}::Value::<C>::ExternRef(#root::Pit::Guest{
                        id: [#(#x),*],
                        x: #{opts.fp()}::CoeVec::coe(#root::tuple_list::tuple_list!(#(#params),*)),
                        s: [#(#s),*],
                    }.into())))
                }));
            }

            let mut f = params.next().unwrap();
            // let id = format_ident!("{}", bindname(&format!("pit/{i}/~{PIT_NS}/{name}")));
            // ctx.#id(x.x,#(#params),*)
            let params = params.collect::<Vec<_>>();
            let cases = opts
                .module
                .exports
                .iter()
                .filter_map(|x| x.name.strip_prefix(&format!("pit/{i}/~")))
                .filter_map(|x| x.strip_suffix(&format!("/{name}")))
                .map(|s| {
                    let id = format_ident!("{}", bindname(&format!("pit/{i}/~{s}/{name}")));
                    let s = {
                        let mut h = sha3::Sha3_256::default();
                        h.update(s);
                        h.finalize()
                    };
                    quasiquote! {
                        [#(#s),*] => {
                            let mut y = #{opts.fp()}::CoeVec::coe(#root::tuple_list::tuple_list!(#(#params),*));
                            y.extend(&mut x.clone());
                            ctx.#id(#{opts.fp()}::CoeVec::uncoe(y))
                        }
                    }
                });
            let interface = self.tpit(opts).iter().find(|a| a.rid() == x);
            let meth = interface.and_then(|a| a.methods.get(name));
            return Ok(Some(quasiquote! {
                'a: {
                    let x = #f;
                    let #{opts.fp()}::Value::<C>::ExternRef(x) = x else{
                        break 'a #{opts.fp()}::ret(Err(#root::_rexport::anyhow::anyhow!("not an externref")))
                    };
                    let Ok(x) = x.try_into() else{
                        break 'a #{opts.fp()}::ret(Err(#root::_rexport::anyhow::anyhow!("not a pit externref")))
                    };
                    match x{
                        #root::Pit::Guest{s,x,id} => match s{
                            #(#cases),*,
                            _ => break 'a #{opts.fp()}::ret(Err(#root::_rexport::anyhow::anyhow!("invalid target")))
                        },
                        #root::Pit::Host{host} => #{let t = match opts.roots.get("tpit_rt"){
                            None => quote!{
                                match host{

                                }
                            },
                            Some(r) => quasiquote!{
                                let casted = unsafe{
                                    host.cast::<Box<dyn #{format_ident!("R{}",i)}>>()
                                };
                                let a = casted.#{format_ident!("{name}")}(#{
                                    let p = params.iter().zip(meth.unwrap().params.iter()).map(|(x,y)|match y{
                                        Arg::Resource { ty, nullable, take, ann } => quasiquote!{
                                            Box::new(Shim{wrapped: ctx, x: #x}).into()
                                        },
                                        _ => quote!{
                                            #x
                                        }
                                    });

                                    quote!{
                                        #(#p),*
                                    }
                                });
                                break 'a #{opts.fp()}::ret(Ok(#root::tuple_list::tuple_list!(#{
                                    let r = meth.unwrap().rets.iter().enumerate().map(|(i,r)|{
                                        let i = syn::Index{index: i as u32, span: Span::call_site()};
                                        let i = quote!{
                                            a.#i
                                        };
                                        match r{
                                            Arg::Resource { ty, nullable, take, ann } => quote!{
                                                #{opts.fp()}::Value::<C>::ExternRef(#root::Pit::Host{host: unsafe{i.cast()}})
                                            },
                                            _ => i
                                        }
                                    });

                                    quote!{
                                        #(#r),*
                                    }
                                })));
                            }
                        };self.apply_host(t,opts,interface.unwrap(),name,&params)?}
            _ => todo!()
                    }
                }
            }));
        }
        if module == "pit" && name == "drop" {
            let mut f = params.next().unwrap();
            let cases = opts
                .module
                .exports
                .iter()
                .filter_map(|x| {
                    let x = x.name.as_str();
                    let x = x.strip_prefix("pit/")?;
                    let (a, x) = x.split_once("/~")?;
                    let s = x.strip_suffix(".drop")?;
                    return Some((a, s));
                })
                .map(|(a, s)| {
                    let x = hex::decode(a).unwrap();
                    let id = format_ident!("{}", bindname(&format!("pit/{a}/~{s}.drop")));
                    let s = {
                        let mut h = sha3::Sha3_256::default();
                        h.update(s);
                        h.finalize()
                    };
                    // let id = format_ident!(
                    //     "{}",
                    //     bindname(&format!("pit/{}/~{PIT_NS}.drop", i.rid_str()))
                    // ); ctx.#id(x.x)
                    quasiquote!(
                        ([#(#x),*],[#(#s),*]) => ctx.#id(#{opts.fp()}::CoeVec::uncoe(x))
                    )
                });
            return Ok(Some(quasiquote! {
                'a: {
                    let x = #f;
                    let #{opts.fp()}::Value::<C>::ExternRef(x) = x else{
                        break 'a #{opts.fp()}::ret(Ok(()));
                    };
                    if let Ok(x) = x.try_into(){
                        match x{
                            #root::Pit::Guest{s,x,id} => => break 'a match (id,s){
                                #(#cases),*,
                                _ => #{opts.fp()}::ret(Ok(()))
                            },
                            #root::Pit::Host{host} => break 'a #{opts.fp()}::ret(Ok(()))
                        }
                    }else{
                        break 'a #{opts.fp()}::ret(Ok(()))
                    }
                }
            }));
        };
        return Ok(None);
    }

    fn post(&self, opts: &Opts<Module<'static>>) -> anyhow::Result<TokenStream> {
        let root = &opts.crate_path;
        let name = opts.name.clone();
        let a = match opts.roots.get("tpit_rt") {
            None => quote! {},
            Some(tpit_rt) => quasiquote! {
                impl<T: #name + ?Sized> Into<#tpit_rt::Tpit<()>> for Box<Shim<T>>{
                    fn into(self) -> #tpit_rt::Tpit<()>{
                        if let #{opts.fp()}::Value::<T>::ExternRef(e) = *self{
                            if let Ok(a) = e.try_into(){
                                if let #root::Pit::Host{host} = a{
                                    return host;
                                }
                            }
                        }
                        Default::default()
                    }
                }
                impl<T: #name + ?Sized> Drop for Shim<T>{
                    fn drop(&mut self){
                        let ctx = unsafe{
                            &mut *self.wrapped
                        };
                        #root::rexport::tramp::tramp(#{opts.import("pit","drop",once(quote!{
                            self.x.clone()
                        }))?})
                    }
                }
                #{
                    let a = self.tpit(opts).iter().map(|i|{
                        let tname = format_ident!("R{}",i.rid_str());
                        let meths = i.methods.iter().map(|(a,b)|
                            Ok(quasiquote!{
                                fn #{format_ident!("{a}")}#{pit_rust_guest::render_sig(&pit_rust_guest::Opts { root: tpit_rt.clone(), salt: vec![], tpit: true },&tpit_rt.clone(),i,b,&quote! {&mut self},false)}{
                                    let ctx = unsafe{
                                        &mut *self.wrapped
                                    };
                                    let res = #{opts.import(&format!("pit/{}",i.rid_str()),&format!("{a}"),once(Ok(quote!{self.x.clone()})).chain(b.params.iter().enumerate().map(|(i,p)|{
                                        let i = format_ident!("p{i}");
                                        Ok(match p{
                                            Arg::Resource{ty,nullable,take,ann} => {
                                                quote!{
                                                    #{opts.fp()}::Value::<C>::ExternRef(Pit::Host{host:#{self.wrap(opts,quasiquote!{
                                                        unsafe{
                                                            #i.cast()
                                                        }
                                                    })?}}.into())
                                                }
                                            }
                                            _ => quote!{
                                                #i
                                            }
                                        })
                                    })).collect::<anyhow::Result<Vec<_>>>()?.into_iter())?};
                                    let res = #root::rexport::tramp::tramp(res).unwrap().into_tuple()
                                    ;
                                    #{                                        let r = b.rets.iter().enumerate().map(|(i,r)|{
                                        let i = syn::Index{index: i as u32, span: Span::call_site()};
                                        let i = quote!{
                                            res.#i
                                        };
                                        match r{
                                            Arg::Resource { ty, nullable, take, ann } => quote!{
                                                Box::new(Shim{wrapped:self.wrapped,x: #i}).into()
                                            },
                                            _ => i
                                        }
                                    });

                                    quote!{
                                        #(#r),*
                                    }}
                                }
                        })).collect::<anyhow::Result<Vec<_>>>()?;
                        Ok(quote!{
                            impl<C: #name + ?Sized> #tname for Shim<C>{
                                #(#meths),*
                            }
                        })
                    }).collect::<anyhow::Result<Vec<_>>>()?;
                    quote!{
                        #(#a)*
                    }
                }
            },
        };
        let bs = self
            .extra
            .iter()
            .map(|x| x.post(self, opts))
            .collect::<anyhow::Result<Vec<_>>>()?;
        return Ok(quote! {
            #a
            #(#bs)*
        });
    }
}