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
use crate::ast::*;
use std::mem;
use wast::{Error, Index};

#[derive(Default)]
pub struct Expander<'a> {
    to_append: Vec<Adapter<'a>>,
    funcs: u32,
}

impl<'a> Expander<'a> {
    pub fn process(
        &mut self,
        fields: &mut Vec<Adapter<'a>>,
        mut f: impl FnMut(&mut Self, &mut Adapter<'a>) -> Result<(), Error>,
    ) -> Result<(), Error> {
        let mut cur = 0;
        while cur < fields.len() {
            f(self, &mut fields[cur])?;
            for new in self.to_append.drain(..) {
                fields.insert(cur, new);
                cur += 1;
            }
            cur += 1;
        }
        Ok(())
    }

    pub fn deinline_import(&mut self, item: &mut Adapter<'a>) -> Result<(), Error> {
        match item {
            Adapter::Func(f) => {
                let (module, name) = match f.kind {
                    FuncKind::Import { module, name } => (module, name),
                    _ => return Ok(()),
                };
                if let Some(name) = f.export.take() {
                    self.to_append.push(Adapter::Export(Export {
                        name,
                        func: Index::Num(self.funcs),
                    }));
                }
                *item = Adapter::Import(Import {
                    span: f.span,
                    module,
                    name,
                    id: f.name,
                    ty: f.ty.clone(),
                });
                self.funcs += 1;
            }

            Adapter::Import(_) => self.funcs += 1,

            _ => {}
        }
        Ok(())
    }

    pub fn deinline_non_import(
        &mut self,
        item: &mut Adapter<'a>,
        core: &[wast::ModuleField<'a>],
    ) -> Result<(), Error> {
        match item {
            Adapter::Func(f) => {
                if let Some(name) = f.export.take() {
                    self.to_append.push(Adapter::Export(Export {
                        name,
                        func: Index::Num(self.funcs),
                    }));
                }
                self.funcs += 1;
            }

            Adapter::Implement(i) => {
                // If this `implement` directive is listed by a name then we
                // need to find the corresponding import in the core module and
                // switch it to `ByIndex`.
                if let Implemented::ByName { module, name } = i.implemented {
                    let idx = self.find_func_index(i.span, core, module, name)?;
                    i.implemented = Implemented::ByIndex(wast::Index::Num(idx));
                }

                // If we have an inline function declaration, then move this
                // function declaration into its own item.
                let tmp = Implementation::ByIndex(wast::Index::Num(self.funcs));
                match mem::replace(&mut i.implementation, tmp) {
                    Implementation::Inline { ty, instrs } => {
                        self.to_append.push(Adapter::Func(Func {
                            span: i.span,
                            name: None,
                            export: None,
                            ty,
                            kind: FuncKind::Inline { instrs },
                        }));

                        self.funcs += 1;
                    }
                    Implementation::ByIndex(idx) => {
                        i.implementation = Implementation::ByIndex(idx);
                    }
                }
            }

            _ => {}
        }

        Ok(())
    }

    fn find_func_index(
        &self,
        span: wast::Span,
        core: &[wast::ModuleField<'_>],
        module: &str,
        field: &str,
    ) -> Result<u32, Error> {
        let mut idx = 0;
        let mut ret = None;
        for entry in core {
            let i = match entry {
                wast::ModuleField::Import(i) => i,
                _ => continue,
            };
            match i.kind {
                wast::ImportKind::Func(_) => {}
                _ => continue,
            }
            idx += 1;
            if i.module != module || i.field != field {
                continue;
            }
            if ret.is_some() {
                let msg = format!(
                    "import of `{}` from `{}` is ambiguous since \
                     it's listed twice in the core module",
                    module, field
                );
                return Err(Error::new(span, msg));
            }
            ret = Some(idx - 1);
        }

        match ret {
            Some(i) => Ok(i),
            None => {
                let msg = format!(
                    "import of `{}` from `{}` not found in core module",
                    module, field
                );
                Err(Error::new(span, msg))
            }
        }
    }
}