ffi_gen/
abi.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use crate::parser::{Interface, Type};
use std::collections::HashSet;

pub mod export;
pub mod import;

#[derive(Clone, Copy, Debug)]
pub enum NumType {
    U8,
    U16,
    U32,
    U64,
    I8,
    I16,
    I32,
    I64,
    F32,
    F64,
    IPtr,
    UPtr,
}

#[derive(Clone, Debug)]
pub enum AbiType {
    Num(NumType),
    Usize,
    Isize,
    Bool,
    RefStr,
    String,
    RefSlice(NumType),
    Vec(NumType),
    RefObject(String),
    Object(String),
    Option(Box<AbiType>),
    Result(Box<AbiType>),
    RefIter(Box<AbiType>),
    Iter(Box<AbiType>),
    RefFuture(Box<AbiType>),
    Future(Box<AbiType>),
    RefStream(Box<AbiType>),
    Stream(Box<AbiType>),
    Tuple(Vec<AbiType>),
    Buffer(NumType),
    List(String),
    RefEnum(String),
}

impl AbiType {
    pub fn num(&self) -> NumType {
        match self {
            Self::Num(num) => *num,
            _ => todo!("{self:?} still missing"),
        }
    }
}

#[derive(Clone, Debug)]
pub enum FunctionType {
    Constructor(String),
    Method(String),
    Function,
    NextIter(String, AbiType),
    PollFuture(String, AbiType),
    PollStream(String, AbiType),
}

#[derive(Clone, Debug)]
pub struct AbiFunction {
    pub doc: Vec<String>,
    pub ty: FunctionType,
    pub name: String,
    pub args: Vec<(String, AbiType)>,
    pub ret: Option<AbiType>,
}

impl AbiFunction {
    pub fn symbol(&self) -> String {
        match &self.ty {
            FunctionType::Constructor(object) | FunctionType::Method(object) => {
                format!("__{}_{}", object, &self.name)
            }
            FunctionType::Function => format!("__{}", &self.name),
            FunctionType::NextIter(symbol, _) => format!("{}_iter_{}", symbol, &self.name),
            FunctionType::PollFuture(symbol, _) => format!("{}_future_{}", symbol, &self.name),
            FunctionType::PollStream(symbol, _) => format!("{}_stream_{}", symbol, &self.name),
        }
    }

    pub fn ret(&self, rets: Vec<Var>) -> Return {
        match rets.len() {
            0 => Return::Void,
            1 => Return::Num(rets[0].clone()),
            _ => Return::Struct(rets, format!("{}Return", self.symbol())),
        }
    }
}

#[derive(Clone, Debug)]
pub struct AbiObject {
    pub doc: Vec<String>,
    pub name: String,
    pub methods: Vec<AbiFunction>,
    pub destructor: String,
}

#[derive(Clone, Debug)]
pub struct AbiIter {
    pub ty: AbiType,
    pub symbol: String,
}

impl AbiIter {
    pub fn next(&self) -> AbiFunction {
        AbiFunction {
            ty: FunctionType::NextIter(self.symbol.clone(), self.ty.clone()),
            doc: vec![],
            name: "next".to_string(),
            args: vec![],
            ret: Some(AbiType::Option(Box::new(self.ty.clone()))),
        }
    }
}

#[derive(Clone, Debug)]
pub struct AbiFuture {
    pub ty: AbiType,
    pub symbol: String,
}

impl AbiFuture {
    pub fn poll(&self) -> AbiFunction {
        AbiFunction {
            ty: FunctionType::PollFuture(self.symbol.clone(), self.ty.clone()),
            doc: vec![],
            name: "poll".to_string(),
            args: vec![
                ("post_cobject".to_string(), AbiType::Isize),
                ("port".to_string(), AbiType::Num(NumType::I64)),
            ],
            ret: Some(AbiType::Option(Box::new(self.ty.clone()))),
        }
    }
}

#[derive(Clone, Debug)]
pub struct AbiStream {
    pub ty: AbiType,
    pub symbol: String,
}

impl AbiStream {
    pub fn poll(&self) -> AbiFunction {
        AbiFunction {
            ty: FunctionType::PollStream(self.symbol.clone(), self.ty.clone()),
            doc: vec![],
            name: "poll".to_string(),
            args: vec![
                ("post_cobject".to_string(), AbiType::Isize),
                ("port".to_string(), AbiType::Num(NumType::I64)),
                ("done".to_string(), AbiType::Num(NumType::I64)),
            ],
            ret: Some(AbiType::Option(Box::new(self.ty.clone()))),
        }
    }
}

#[derive(Clone, Debug)]
pub enum Return {
    Void,
    Num(Var),
    Struct(Vec<Var>, String),
}

#[derive(Default)]
struct VarGen {
    counter: u32,
}

impl VarGen {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn gen_num(&mut self, num: NumType) -> Var {
        self.gen(AbiType::Num(num))
    }

    pub fn gen(&mut self, ty: AbiType) -> Var {
        let binding = self.counter;
        self.counter += 1;
        Var { binding, ty }
    }
}

#[derive(Clone, Debug)]
pub struct Var {
    pub binding: u32,
    pub ty: AbiType,
}

/// Abi type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Abi {
    /// Native 32bit
    Native32,
    /// Native 64bit
    Native64,
    /// Wasm 32bit
    Wasm32,
    /// Wasm 64bit
    Wasm64,
}

impl Abi {
    pub(crate) fn native() -> Self {
        #[cfg(target_pointer_width = "32")]
        return Abi::Native32;
        #[cfg(target_pointer_width = "64")]
        return Abi::Native64;
    }

    /// Returns the size and alignment of a primitive type.
    pub(crate) fn layout(self, ty: NumType) -> (usize, usize) {
        let size = match ty {
            NumType::U8 | NumType::I8 => 1,
            NumType::U16 | NumType::I16 => 2,
            NumType::U32 | NumType::I32 | NumType::F32 => 4,
            NumType::U64 | NumType::I64 | NumType::F64 => 8,
            NumType::IPtr => todo!(),
            NumType::UPtr => todo!(),
        };
        let size = match self {
            Self::Native32 | Self::Native64 => size,
            Self::Wasm32 | Self::Wasm64 => core::cmp::max(4, size),
        };
        (size, size)
    }
}

impl Interface {
    pub fn objects(&self) -> Vec<AbiObject> {
        let mut objs = vec![];
        for object in &self.objects {
            let mut methods = vec![];
            for method in &object.methods {
                let obj = object.ident.clone();
                let func = AbiFunction {
                    doc: method.doc.clone(),
                    name: method.ident.clone(),
                    ty: if method.is_static {
                        FunctionType::Constructor(obj)
                    } else {
                        FunctionType::Method(obj)
                    },
                    args: method
                        .args
                        .iter()
                        .map(|(n, ty)| (n.clone(), self.to_type(ty)))
                        .collect(),
                    ret: method.ret.as_ref().map(|ty| self.to_type(ty)),
                };
                methods.push(func);
            }
            objs.push(AbiObject {
                doc: object.doc.clone(),
                name: object.ident.clone(),
                methods,
                destructor: format!("drop_box_{}", &object.ident),
            });
        }
        objs
    }

    pub fn functions(&self) -> Vec<AbiFunction> {
        let mut funcs = vec![];
        for func in &self.functions {
            assert!(!func.is_static);
            let args = func
                .args
                .iter()
                .map(|(n, ty)| (n.clone(), self.to_type(ty)))
                .collect();
            let ret = func.ret.as_ref().map(|ty| self.to_type(ty));
            let func = AbiFunction {
                doc: func.doc.clone(),
                name: func.ident.clone(),
                ty: FunctionType::Function,
                args,
                ret,
            };
            funcs.push(func);
        }
        funcs
    }

    pub fn iterators(&self) -> Vec<AbiIter> {
        let mut iterators = vec![];
        let mut functions = self.functions();
        for obj in self.objects() {
            functions.extend(obj.methods);
        }
        for func in functions {
            if let Some(ty) = func.ret.as_ref() {
                let mut p = ty;
                let mut symbol = func.symbol();
                loop {
                    match p {
                        AbiType::Option(ty) | AbiType::Result(ty) => p = &**ty,
                        AbiType::Future(ty) => {
                            symbol.push_str("_future_poll");
                            p = &**ty
                        }
                        AbiType::Stream(ty) => {
                            symbol.push_str("_stream_poll");
                            p = &**ty
                        }
                        AbiType::Iter(ty) => {
                            iterators.push(AbiIter {
                                ty: (**ty).clone(),
                                symbol,
                            });
                            break;
                        }
                        _ => break,
                    }
                }
            }
        }
        iterators
    }

    pub fn futures(&self) -> Vec<AbiFuture> {
        let mut futures = vec![];
        let mut functions = self.functions();
        for obj in self.objects() {
            functions.extend(obj.methods);
        }
        for func in functions {
            if let Some(ty) = func.ret.as_ref() {
                let mut p = ty;
                loop {
                    match p {
                        AbiType::Option(ty) | AbiType::Result(ty) => p = &**ty,
                        AbiType::Future(ty) => {
                            let symbol = func.symbol();
                            futures.push(AbiFuture {
                                ty: (**ty).clone(),
                                symbol,
                            });
                            break;
                        }
                        _ => break,
                    }
                }
            }
        }
        futures
    }

    pub fn streams(&self) -> Vec<AbiStream> {
        let mut streams = vec![];
        let mut functions = self.functions();
        for obj in self.objects() {
            functions.extend(obj.methods);
        }
        for func in functions {
            if let Some(ty) = func.ret.as_ref() {
                let mut p = ty;
                loop {
                    match p {
                        AbiType::Option(ty) | AbiType::Result(ty) => p = &**ty,
                        AbiType::Stream(ty) => {
                            let symbol = func.symbol();
                            streams.push(AbiStream {
                                ty: (**ty).clone(),
                                symbol,
                            });
                            break;
                        }
                        _ => break,
                    }
                }
            }
        }
        streams
    }

    pub fn listed_types(&self) -> Vec<String> {
        fn find_inner_listed_types<F: FnMut(String)>(ty: &AbiType, cb: &mut F) {
            use AbiType::*;
            match ty {
                List(name) => cb(name.clone()),
                Option(ty) | Result(ty) | Iter(ty) | Future(ty) | Stream(ty) | RefIter(ty)
                | RefFuture(ty) | RefStream(ty) => find_inner_listed_types(ty.as_ref(), cb),
                Tuple(tys) => tys.iter().for_each(|ty| find_inner_listed_types(ty, cb)),
                _ => {}
            }
        }

        let mut res = HashSet::new();
        let mut res_adder = |ty| {
            res.insert(ty);
        };
        let mut func_processor = |f: AbiFunction| {
            if let Some(ty) = &f.ret {
                find_inner_listed_types(ty, &mut res_adder);
            }
            for (_, ty) in f.args.iter() {
                find_inner_listed_types(ty, &mut res_adder);
            }
        };

        for func in self.functions() {
            func_processor(func);
        }
        for obj in self.objects() {
            for func in obj.methods {
                func_processor(func);
            }
        }

        let mut fin: Vec<String> = res.into_iter().collect();
        fin.sort();
        fin
    }

    pub fn imports(&self, abi: &Abi) -> Vec<import::Import> {
        let mut imports = vec![];
        for function in self.functions() {
            imports.push(abi.import(&function));
        }
        for obj in self.objects() {
            for method in &obj.methods {
                imports.push(abi.import(method));
            }
        }
        for iter in self.iterators() {
            imports.push(abi.import(&iter.next()));
        }
        for fut in self.futures() {
            imports.push(abi.import(&fut.poll()));
        }
        for stream in self.streams() {
            imports.push(abi.import(&stream.poll()));
        }
        imports
    }

    pub fn to_type(&self, ty: &Type) -> AbiType {
        match ty {
            Type::U8 => AbiType::Num(NumType::U8),
            Type::U16 => AbiType::Num(NumType::U16),
            Type::U32 => AbiType::Num(NumType::U32),
            Type::U64 => AbiType::Num(NumType::U64),
            Type::Usize => AbiType::Usize,
            Type::I8 => AbiType::Num(NumType::I8),
            Type::I16 => AbiType::Num(NumType::I16),
            Type::I32 => AbiType::Num(NumType::I32),
            Type::I64 => AbiType::Num(NumType::I64),
            Type::Isize => AbiType::Isize,
            Type::F32 => AbiType::Num(NumType::F32),
            Type::F64 => AbiType::Num(NumType::F64),
            Type::Bool => AbiType::Bool,
            Type::Buffer(inner) => match self.to_type(inner) {
                AbiType::Num(ty) => AbiType::Buffer(ty),
                ty => unimplemented!("Vec<{:?}>", ty),
            },
            Type::Ref(inner) => match &**inner {
                Type::String => AbiType::RefStr,
                Type::Slice(inner) => match self.to_type(inner) {
                    AbiType::Num(ty) => AbiType::RefSlice(ty),
                    ty => unimplemented!("&{:?}", ty),
                },
                Type::Ident(ident) => {
                    if self.is_object(ident) {
                        AbiType::RefObject(ident.clone())
                    } else if self.is_enum(ident) {
                        AbiType::RefEnum(ident.clone())
                    } else {
                        panic!("unknown identifier {}", ident)
                    }
                }
                ty => unimplemented!("&{:?}", ty),
            },
            Type::String => AbiType::String,
            Type::Slice(_) => panic!("slice needs to be passed by reference"),
            Type::Vec(inner) => match self.to_type(inner) {
                AbiType::Num(ty) => AbiType::Vec(ty),
                AbiType::Object(ty) => AbiType::List(ty),
                AbiType::RefEnum(ty) => AbiType::List(ty),
                AbiType::String => AbiType::List("FfiString".to_string()),
                ty => unimplemented!("Vec<{:?}>", ty),
            },
            Type::Ident(ident) => {
                if self.is_object(ident) {
                    AbiType::Object(ident.clone())
                } else if self.is_enum(ident) {
                    AbiType::RefEnum(ident.clone())
                } else {
                    panic!("unknown identifier {}", ident)
                }
            }
            Type::Option(ty) => {
                let inner = self.to_type(ty);
                if let AbiType::Option(_) = inner {
                    panic!("nested options are not supported");
                }
                AbiType::Option(Box::new(inner))
            }
            Type::Result(ty) => AbiType::Result(Box::new(self.to_type(ty))),
            Type::Iter(ty) => AbiType::Iter(Box::new(self.to_type(ty))),
            Type::Future(ty) => AbiType::Future(Box::new(self.to_type(ty))),
            Type::Stream(ty) => AbiType::Stream(Box::new(self.to_type(ty))),
            Type::Tuple(ty) => AbiType::Tuple(ty.iter().map(|ty| self.to_type(ty)).collect()),
        }
    }
}