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
use wast::parser::{Parse, Parser, Result};

use crate::{Atom, Expr, Index, SExpr, TypeUse};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportDesc {
    Func(ImportDescFunc),
}

impl SExpr for ImportDesc {
    fn car(&self) -> String {
        match self {
            Self::Func(d) => d.car(),
        }
    }

    fn cdr(&self) -> Vec<Expr> {
        match self {
            Self::Func(d) => d.cdr(),
        }
    }
}

impl Parse<'_> for ImportDesc {
    fn parse(parser: Parser<'_>) -> Result<Self> {
        let mut l = parser.lookahead1();

        if l.peek::<wast::kw::func>() {
            Ok(Self::Func(parser.parse::<ImportDescFunc>()?))
        } else {
            Err(l.error())
        }
    }
}

/// https://webassembly.github.io/spec/core/text/modules.html#text-importdesc
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportDescFunc {
    idx:      Option<Index>,
    type_use: TypeUse,
}

impl ImportDescFunc {
    pub fn new(idx: Option<Index>, type_use: TypeUse) -> Self {
        Self { idx, type_use }
    }
}

impl SExpr for ImportDescFunc {
    fn car(&self) -> String {
        "func".to_owned()
    }

    fn cdr(&self) -> Vec<Expr> {
        let mut v = Vec::new();

        if let Some(ref idx) = self.idx {
            v.push(Expr::Atom(Atom::new(idx.to_string())));
        }

        v.append(&mut self.type_use.exprs());

        v
    }
}

impl Parse<'_> for ImportDescFunc {
    fn parse(parser: Parser<'_>) -> Result<Self> {
        parser.parse::<wast::kw::func>()?;

        let idx = parser.parse::<Option<Index>>()?;
        let type_use = parser.parse::<TypeUse>()?;

        Ok(Self { idx, type_use })
    }
}