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

use crate::{Index, Integer, ValueType};

enum Paren {
    None,
    Left,
    Right,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Level {
    pub expr: Expression,
    pub subexprs: Vec<Expression>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Expression {
    Unfolded(Instruction),
    Folded(Instruction),
}

impl Expression {
    fn subexprs(&mut self) -> &mut Vec<Expression> {
        match self {
            Self::Unfolded(i) => i.subexprs(),
            Self::Folded(i) => i.subexprs(),
        }
    }
}

#[derive(Default)]
pub struct ExpressionParser {
    exprs: Vec<Expression>,
    stack: Vec<Level>,
}

impl ExpressionParser {
    pub fn parse(mut self, parser: Parser) -> Result<Vec<Expression>> {
        while !parser.is_empty() || !self.stack.is_empty() {
            match self.paren(parser)? {
                Paren::Left => {
                    let instr = parser.parse::<Instruction>()?;
                    self.stack.push(Level {
                        expr: Expression::Folded(instr),
                        subexprs: Vec::new(),
                    });
                }
                Paren::None => {
                    let instr = parser.parse::<Instruction>()?;
                    let expr = Expression::Unfolded(instr);

                    match self.stack.last_mut() {
                        Some(level) => level.subexprs.push(expr),
                        None => self.exprs.push(expr),
                    }
                }
                Paren::Right => match self.stack.pop() {
                    Some(mut level) => {
                        level.expr.subexprs().append(&mut level.subexprs);

                        if let Some(top) = self.stack.last_mut() {
                            top.subexprs.push(level.expr);
                        } else {
                            self.exprs.push(level.expr);
                        }
                    }
                    None => {}
                },
            }
        }

        Ok(self.exprs.clone())
    }

    /// Parses either `(`, `)`, or nothing.
    fn paren(&self, parser: Parser) -> Result<Paren> {
        parser.step(|cursor| {
            Ok(match cursor.lparen() {
                Some(rest) => (Paren::Left, rest),
                None if self.stack.is_empty() => (Paren::None, cursor),
                None => match cursor.rparen() {
                    Some(rest) => (Paren::Right, rest),
                    None => (Paren::None, cursor),
                },
            })
        })
    }
}

#[macro_export]
macro_rules! instructions {
    (pub enum Instruction {
        $(
            $name:ident : $keyword:tt : $instr:tt {
                $($field_name:ident: $field_type:ty),*
            },
        )*
    }) => {
        mod kw {
            $(
                wast::custom_keyword!($keyword = $instr);
            )*
        }

        #[derive(Debug, Clone, PartialEq, Eq)]
        pub enum Instruction {
            $(
                $name($name),
            )*
        }


        impl Instruction {
            pub fn subexprs(&mut self) -> &mut Vec<Expression> {
                match self {
                    $(
                        Self::$name(i) => &mut i.exprs,
                    )*
                }
            }
        }

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

                $(
                    if l.peek::<kw::$keyword>() {
                        return Ok(Self::$name(parser.parse()?));
                    }
                )*

                Err(l.error())
            }
        }

        $(
            #[derive(Debug, Clone, PartialEq, Eq)]
            pub struct $name {
                $(
                    pub $field_name: $field_type,
                )*
                pub exprs: Vec<Expression>,
            }

            impl Parse<'_> for $name {
                fn parse(parser: Parser<'_>) -> Result<Self> {
                    parser.parse::<kw::$keyword>()?;

                    $(
                        let $field_name = parser.parse::<$field_type>()?;
                    )*

                    Ok(Self {
                        $(
                            $field_name,
                        )*
                        exprs: Vec::new(),
                    })
                }
            }
        )*
    };
}

instructions!(
    pub enum Instruction {
        Block     : block      : "block"      { id: Option<Index> },
        Br        : br         : "br"         { id: Index },
        BrIf      : br_if      : "br_if"      { id: Index },
        BrTable   : br_table   : "br_table"   { ids: Index },
        Call      : call       : "call"       { id: Index },
        Drop      : drop       : "drop"       {},
        GlobalGet : global_get : "global.get" { id: Index },
        GlobalSet : global_set : "global.set" { id: Index },
        I32Add    : i32_add    : "i32.add"    {},
        I32Const  : i32_const  : "i32.const"  { integer: Integer },
        I32Eq     : i32_eq     : "i32.eq"     {},
        I32Eqz    : i32_eqz    : "i32.eqz"    {},
        I32GtU    : i32_gt_u   : "i32.gt_u"   {},
        I32Ne     : i32_ne     : "i32.ne"     {},
        I32Sub    : i32_sub    : "i32.sub"    {},
        I64Const  : i64_const  : "i64.const"  { integer: Integer },
        If        : r#if       : "if"         {},
        Local     : local      : "local"      { id: Index, value_type: ValueType },
        LocalGet  : local_get  : "local.get"  { id: Index },
        LocalSet  : local_set  : "local.set"  { id: Index },
        LocalTee  : local_tee  : "local.tee"  { id: Index },
        Loop      : r#loop     : "loop"       { id: Option<Index> },
        Then      : then       : "then"       {},
    }
);