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
use crate::lexer::FloatVal;
use crate::parser::{Cursor, Parse, Parser, Peek, Result};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str;

/// A position in the original source stream, used to render errors.
#[derive(Copy, Clone, Debug)]
pub struct Span {
    pub(crate) offset: usize,
}

/// An identifier in a WebAssembly module, prefixed by `$` in the textual
/// format.
///
/// An identifier is used to symbolically refer to items in a a wasm module,
/// typically via the [`Index`] type.
#[derive(Copy, Clone)]
pub struct Id<'a> {
    name: &'a str,
    span: Span,
}

impl<'a> Id<'a> {
    /// Returns the underlying name of this identifier.
    ///
    /// The name returned does not contain the leading `$`.
    pub fn name(&self) -> &'a str {
        self.name
    }

    /// Returns span of this identifier in the original source
    pub fn span(&self) -> Span {
        self.span
    }
}

impl<'a> Hash for Id<'a> {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.name.hash(hasher);
    }
}

impl<'a> PartialEq for Id<'a> {
    fn eq(&self, other: &Id<'a>) -> bool {
        self.name == other.name
    }
}

impl<'a> Eq for Id<'a> {}

impl<'a> Parse<'a> for Id<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.step(|c| {
            if let Some((name, rest)) = c.id() {
                return Ok((
                    Id {
                        name,
                        span: c.cur_span(),
                    },
                    rest,
                ));
            }
            Err(c.error("expected an identifier"))
        })
    }
}

impl fmt::Debug for Id<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.name.fmt(f)
    }
}

impl Peek for Id<'_> {
    fn peek(cursor: Cursor<'_>) -> bool {
        cursor.id().is_some()
    }

    fn display() -> &'static str {
        "an identifier"
    }
}

/// A reference to another item in a wasm module.
///
/// This type is used for items referring to other items (such as `call $foo`
/// referencing function `$foo`). References can be either an index (u32) or an
/// [`Id`] in the textual format.
///
/// The emission phase of a module will ensure that `Index::Id` is never used
/// and switch them all to `Index::Num`.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Index<'a> {
    /// A numerical index that this references. The index space this is
    /// referencing is implicit based on where this [`Index`] is stored.
    Num(u32),
    /// A human-readable identifier this references. Like `Num`, the namespace
    /// this references is based on where this is stored.
    Id(Id<'a>),
}

impl<'a> Parse<'a> for Index<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let mut l = parser.lookahead1();
        if l.peek::<Id>() {
            Ok(Index::Id(parser.parse()?))
        } else if l.peek::<u32>() {
            Ok(Index::Num(parser.parse()?))
        } else {
            Err(l.error())
        }
    }
}

impl Peek for Index<'_> {
    fn peek(cursor: Cursor<'_>) -> bool {
        u32::peek(cursor) || Id::peek(cursor)
    }

    fn display() -> &'static str {
        "an index"
    }
}

macro_rules! integers {
    ($($i:ident($u:ident))*) => ($(
        impl<'a> Parse<'a> for $i {
            fn parse(parser: Parser<'a>) -> Result<Self> {
                parser.step(|c| {
                    if let Some((i, rest)) = c.integer() {
                        let (s, base) = i.val();
                        let val = $i::from_str_radix(s, base)
                            .or_else(|_| {
                                $u::from_str_radix(s, base).map(|i| i as $i)
                            });
                        return match val {
                            Ok(n) => Ok((n, rest)),
                            Err(_) => Err(c.error(concat!(
                                "invalid ",
                                stringify!($i),
                                " number: constant out of range",
                            ))),
                        };
                    }
                    Err(c.error(concat!("expected a ", stringify!($i))))
                })
            }
        }

        impl Peek for $i {
            fn peek(cursor: Cursor<'_>) -> bool {
                cursor.integer().is_some()
            }

            fn display() -> &'static str {
                stringify!($i)
            }
        }
    )*)
}

integers! { u32(u32) i32(u32) i64(u64) }

impl<'a> Parse<'a> for &'a [u8] {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.step(|c| {
            if let Some((i, rest)) = c.string() {
                return Ok((i, rest));
            }
            Err(c.error("expected a string"))
        })
    }
}

impl Peek for &'_ [u8] {
    fn peek(cursor: Cursor<'_>) -> bool {
        cursor.string().is_some()
    }

    fn display() -> &'static str {
        "string"
    }
}

impl<'a> Parse<'a> for &'a str {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        str::from_utf8(parser.parse()?).map_err(|_| parser.error("invalid UTF-8 encoding"))
    }
}

impl Peek for &'_ str {
    fn peek(cursor: Cursor<'_>) -> bool {
        <&[u8]>::peek(cursor)
    }

    fn display() -> &'static str {
        <&[u8]>::display()
    }
}

macro_rules! float {
    ($($name:ident => ($int:ident, $float:ident, $exp_bits:tt, $parse:ident))*) => ($(
        /// A parsed floating-point type
        #[derive(Debug)]
        pub struct $name {
            /// The raw bits that this floating point number represents.
            pub bits: $int,
        }

        impl<'a> Parse<'a> for $name {
            fn parse(parser: Parser<'a>) -> Result<Self> {
                fn handle(val: &FloatVal<'_>) -> Option<$int> {
                    use std::ffi::CString;
                    use std::os::raw::c_char;
                    use std::ptr;

                    let width = std::mem::size_of::<$int>() * 8;
                    let neg_offset = width - 1;
                    let exp_offset = neg_offset - $exp_bits;
                    let signif_bits = width - 1 - $exp_bits;
                    let signif_mask = (1 << exp_offset) - 1;
                    let (hex, integral, decimal, exponent) = match val {
                        FloatVal::Inf { negative } => {
                            let exp_bits = (1 << $exp_bits) - 1;
                            let neg_bit = *negative as $int;
                            return Some(
                                (neg_bit << neg_offset) |
                                (exp_bits << exp_offset)
                            );
                        }

                        FloatVal::Nan { negative, val } => {
                            let exp_bits = (1 << $exp_bits) - 1;
                            let neg_bit = *negative as $int;
                            let signif = val.unwrap_or(1 << (signif_bits - 1)) as $int;
                            return Some(
                                (neg_bit << neg_offset) |
                                (exp_bits << exp_offset) |
                                (signif & signif_mask)
                            );
                        }

                        FloatVal::Val { hex, integral, decimal, exponent } => {
                            (hex, integral, decimal, exponent)
                        }
                    };

                    // Rely on Rust's standard library to parse base 10 floats
                    // correctly.
                    if !*hex {
                        let mut s = integral.to_string();
                        if let Some(decimal) = decimal {
                            s.push_str(".");
                            s.push_str(&decimal);
                        }
                        if let Some(exponent) = exponent {
                            s.push_str("e");
                            s.push_str(&exponent);
                        }
                        return s.parse::<$float>().ok().map(|s| s.to_bits());
                    }

                    // FIXME(#13) shouldn't use C here, we should use something
                    // Rust-based
                    let (sign, num) = if integral.starts_with("-") {
                        ("-", &integral[1..])
                    } else {
                        ("", &integral[..])
                    };
                    let mut s = format!("{}0x{}", sign, num);
                    if let Some(decimal) = decimal {
                        s.push_str(".");
                        s.push_str(&decimal);
                    }
                    if let Some(exponent) = exponent {
                        s.push_str("p");
                        s.push_str(&exponent);
                    }
                    let s = CString::new(s).unwrap();

                    // Match what wabt does for now and use
                    // `strtof` and `strtod` until hex float
                    // parsing in Rust is up to par.
                    extern {
                        fn $parse(input: *const c_char, other: *mut *mut c_char) -> $float;
                    }
                    let ret = unsafe {
                        $parse(
                            s.as_ptr(),
                            ptr::null_mut(),
                        )
                    };
                    Some(ret.to_bits())
                }

                parser.step(|c| {
                    let (val, rest) = if let Some((f, rest)) = c.float() {
                        (handle(f.val()), rest)
                    } else if let Some((i, rest)) = c.integer() {
                        let (s, base) = i.val();
                        (
                            handle(&FloatVal::Val {
                                hex: base == 16,
                                integral: s.into(),
                                decimal: None,
                                exponent: None,
                            }),
                            rest,
                        )
                    } else {
                        return Err(c.error("expected a float"));
                    };
                    match val {
                        Some(bits) => Ok(($name { bits }, rest)),
                        None => Err(c.error("invalid float value")),
                    }
                })
            }
        }
    )*)
}

float! {
    Float32 => (u32, f32, 8, strtof)
    Float64 => (u64, f64, 11, strtod)
}

/// A convenience type to use with [`Parser::peek`](crate::parser::Parser::peek)
/// to see if the next token is an s-expression.
pub struct LParen {
    _priv: (),
}

impl Peek for LParen {
    fn peek(cursor: Cursor<'_>) -> bool {
        cursor.lparen().is_some()
    }

    fn display() -> &'static str {
        "left paren"
    }
}