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

use crate::{Atom, Expr, FunctionSectionEntry, SExpr};

/// https://webassembly.github.io/spec/core/text/modules.html#text-global-abbrev
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InlineExport {
    name: String,
}

impl InlineExport {
    pub fn new(name: String) -> Self {
        Self { name }
    }
}

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

    fn cdr(&self) -> Vec<Expr> {
        vec![Expr::Atom(Atom::new(format!(r#""{}""#, self.name)))]
    }
}

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

        let name = parser.parse::<String>()?;

        Ok(Self { name })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Export {
    name: String,
    desc: ExportDesc,
}

impl Export {
    pub fn new(name: String, desc: ExportDesc) -> Self {
        Self { name, desc }
    }
}

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

    fn cdr(&self) -> Vec<Expr> {
        vec![
            Expr::Atom(Atom::new(format!(r#""{}""#, self.name))),
            Expr::SExpr(Box::new(self.desc.clone())),
        ]
    }
}

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

        let name = parser.parse::<String>()?;
        let desc = parser.parse::<ExportDesc>()?;

        Ok(Self { name, desc })
    }
}

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

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

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExportDesc {
    Func(Box<FunctionSectionEntry>),
}

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

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

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

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