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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use anyhow::{anyhow, bail, Context, Result};
use id_arena::{Arena, Id};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};

pub mod abi;
mod ast;
mod sizealign;
pub use sizealign::*;

pub struct Interface {
    pub name: String,
    pub types: Arena<TypeDef>,
    pub type_lookup: HashMap<String, TypeId>,
    pub resources: Arena<Resource>,
    pub resource_lookup: HashMap<String, ResourceId>,
    pub interfaces: Arena<Interface>,
    pub interface_lookup: HashMap<String, InterfaceId>,
    pub functions: Vec<Function>,
    pub globals: Vec<Global>,
}

pub type TypeId = Id<TypeDef>;
pub type ResourceId = Id<Resource>;
pub type InterfaceId = Id<Interface>;

pub struct TypeDef {
    pub docs: Docs,
    pub kind: TypeDefKind,
    pub name: Option<String>,
    /// `None` if this type is originally declared in this instance or
    /// otherwise `Some` if it was originally defined in a different module.
    pub foreign_module: Option<String>,
}

pub enum TypeDefKind {
    Record(Record),
    Variant(Variant),
    List(Type),
    Pointer(Type),
    ConstPointer(Type),
    PushBuffer(Type),
    PullBuffer(Type),
    Type(Type),
}

#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum Type {
    U8,
    U16,
    U32,
    U64,
    S8,
    S16,
    S32,
    S64,
    F32,
    F64,
    Char,
    CChar,
    Usize,
    Handle(ResourceId),
    Id(TypeId),
}

#[derive(PartialEq, Debug, Copy, Clone)]
pub enum Int {
    U8,
    U16,
    U32,
    U64,
}

#[derive(Debug)]
pub struct Record {
    pub fields: Vec<Field>,
    pub kind: RecordKind,
}

#[derive(Copy, Clone, Debug)]
pub enum RecordKind {
    Other,
    Flags(Option<Int>),
    Tuple,
}

#[derive(Debug)]
pub struct Field {
    pub docs: Docs,
    pub name: String,
    pub ty: Type,
}

impl Record {
    pub fn is_tuple(&self) -> bool {
        match self.kind {
            RecordKind::Tuple => true,
            _ => false,
        }
    }

    pub fn is_flags(&self) -> bool {
        match self.kind {
            RecordKind::Flags(_) => true,
            _ => false,
        }
    }

    pub fn num_i32s(&self) -> usize {
        (self.fields.len() + 31) / 32
    }
}

impl RecordKind {
    fn infer(types: &Arena<TypeDef>, fields: &[Field]) -> RecordKind {
        if fields.len() == 0 {
            return RecordKind::Other;
        }

        // Structs-of-bools are classified to get represented as bitflags.
        if fields.iter().all(|t| is_bool(&t.ty, types)) {
            return RecordKind::Flags(None);
        }

        // fields with consecutive integer names get represented as tuples.
        if fields
            .iter()
            .enumerate()
            .all(|(i, m)| m.name.as_str().parse().ok() == Some(i))
        {
            return RecordKind::Tuple;
        }

        return RecordKind::Other;

        fn is_bool(t: &Type, types: &Arena<TypeDef>) -> bool {
            match t {
                Type::Id(v) => match &types[*v].kind {
                    TypeDefKind::Variant(v) => v.is_bool(),
                    TypeDefKind::Type(t) => is_bool(t, types),
                    _ => false,
                },
                _ => false,
            }
        }
    }
}

#[derive(Debug)]
pub struct Variant {
    pub cases: Vec<Case>,
    /// The bit representation of the width of this variant's tag when the
    /// variant is stored in memory.
    pub tag: Int,
}

#[derive(Debug)]
pub struct Case {
    pub docs: Docs,
    pub name: String,
    pub ty: Option<Type>,
}

impl Variant {
    pub fn infer_tag(cases: usize) -> Int {
        match cases {
            n if n <= u8::max_value() as usize => Int::U8,
            n if n <= u16::max_value() as usize => Int::U16,
            n if n <= u32::max_value() as usize => Int::U32,
            n if n <= u64::max_value() as usize => Int::U64,
            _ => panic!("too many cases to fit in a repr"),
        }
    }

    pub fn is_bool(&self) -> bool {
        self.cases.len() == 2
            && self.cases[0].name == "false"
            && self.cases[1].name == "true"
            && self.cases[0].ty.is_none()
            && self.cases[1].ty.is_none()
    }

    pub fn is_enum(&self) -> bool {
        self.cases.iter().all(|c| c.ty.is_none())
    }

    pub fn as_option(&self) -> Option<&Type> {
        if self.cases.len() != 2 {
            return None;
        }
        if self.cases[0].name != "none" || self.cases[0].ty.is_some() {
            return None;
        }
        if self.cases[1].name != "some" {
            return None;
        }
        self.cases[1].ty.as_ref()
    }

    pub fn as_expected(&self) -> Option<(Option<&Type>, Option<&Type>)> {
        if self.cases.len() != 2 {
            return None;
        }
        if self.cases[0].name != "ok" {
            return None;
        }
        if self.cases[1].name != "err" {
            return None;
        }
        Some((self.cases[0].ty.as_ref(), self.cases[1].ty.as_ref()))
    }
}

#[derive(Clone, Default, Debug)]
pub struct Docs {
    pub contents: Option<String>,
}

pub struct Resource {
    pub docs: Docs,
    pub name: String,
    /// `None` if this resource is defined within the containing instance,
    /// otherwise `Some` if it's defined in an instance named here.
    pub foreign_module: Option<String>,
}

pub struct Global {
    pub docs: Docs,
    pub name: String,
    pub ty: Type,
}

#[derive(Debug)]
pub struct Function {
    pub abi: abi::Abi,
    pub docs: Docs,
    pub name: String,
    pub kind: FunctionKind,
    pub params: Vec<(String, Type)>,
    pub results: Vec<(String, Type)>,
}

#[derive(Debug)]
pub enum FunctionKind {
    Freestanding,
    Static { resource: ResourceId, name: String },
    Method { resource: ResourceId, name: String },
}

impl Function {
    pub fn item_name(&self) -> &str {
        match &self.kind {
            FunctionKind::Freestanding => &self.name,
            FunctionKind::Static { name, .. } => name,
            FunctionKind::Method { name, .. } => name,
        }
    }
}

impl Interface {
    pub fn parse(name: &str, input: &str) -> Result<Interface> {
        Interface::parse_with(name, input, |f| {
            Err(anyhow!("cannot load submodule `{}`", f))
        })
    }

    pub fn parse_file(path: impl AsRef<Path>) -> Result<Interface> {
        let path = path.as_ref();
        let parent = path.parent().unwrap();
        let contents = std::fs::read_to_string(&path)
            .with_context(|| format!("failed to read: {}", path.display()))?;
        Interface::parse_with(path, &contents, |path| load_fs(parent, path))
    }

    pub fn parse_with(
        filename: impl AsRef<Path>,
        contents: &str,
        mut load: impl FnMut(&str) -> Result<(PathBuf, String)>,
    ) -> Result<Interface> {
        Interface::_parse_with(
            filename.as_ref(),
            contents,
            &mut load,
            &mut HashSet::new(),
            &mut HashMap::new(),
        )
    }

    fn _parse_with(
        filename: &Path,
        contents: &str,
        load: &mut dyn FnMut(&str) -> Result<(PathBuf, String)>,
        visiting: &mut HashSet<PathBuf>,
        map: &mut HashMap<String, Interface>,
    ) -> Result<Interface> {
        // Parse the `contents `into an AST
        let ast = match ast::Ast::parse(&contents) {
            Ok(ast) => ast,
            Err(mut e) => {
                let file = filename.display().to_string();
                ast::rewrite_error(&mut e, &file, contents);
                return Err(e);
            }
        };

        // Load up any modules into our `map` that have not yet been parsed.
        if !visiting.insert(filename.to_path_buf()) {
            bail!("file `{}` recursively imports itself", filename.display())
        }
        for item in ast.items.iter() {
            let u = match item {
                ast::Item::Use(u) => u,
                _ => continue,
            };
            if map.contains_key(&*u.from[0].name) {
                continue;
            }
            let (filename, contents) = load(&u.from[0].name)
                // TODO: insert context here about `u.name.span` and `filename`
                ?;
            let instance = Interface::_parse_with(&filename, &contents, load, visiting, map)?;
            map.insert(u.from[0].name.to_string(), instance);
        }
        visiting.remove(filename);

        // and finally resolve everything into our final instance
        let name = filename.file_stem().unwrap().to_str().unwrap();
        match ast.resolve(name, map) {
            Ok(i) => Ok(i),
            Err(mut e) => {
                let file = filename.display().to_string();
                ast::rewrite_error(&mut e, &file, contents);
                Err(e)
            }
        }
    }

    pub fn topological_types(&self) -> Vec<TypeId> {
        let mut ret = Vec::new();
        let mut visited = HashSet::new();
        for (id, _) in self.types.iter() {
            self.topo_visit(id, &mut ret, &mut visited);
        }
        return ret;
    }

    fn topo_visit(&self, id: TypeId, list: &mut Vec<TypeId>, visited: &mut HashSet<TypeId>) {
        if !visited.insert(id) {
            return;
        }
        match &self.types[id].kind {
            TypeDefKind::Type(t)
            | TypeDefKind::List(t)
            | TypeDefKind::PushBuffer(t)
            | TypeDefKind::PullBuffer(t)
            | TypeDefKind::Pointer(t)
            | TypeDefKind::ConstPointer(t) => self.topo_visit_ty(t, list, visited),
            TypeDefKind::Record(r) => {
                for f in r.fields.iter() {
                    self.topo_visit_ty(&f.ty, list, visited);
                }
            }
            TypeDefKind::Variant(v) => {
                for v in v.cases.iter() {
                    if let Some(ty) = &v.ty {
                        self.topo_visit_ty(ty, list, visited);
                    }
                }
            }
        }
        list.push(id);
    }

    fn topo_visit_ty(&self, ty: &Type, list: &mut Vec<TypeId>, visited: &mut HashSet<TypeId>) {
        if let Type::Id(id) = ty {
            self.topo_visit(*id, list, visited);
        }
    }

    pub fn all_bits_valid(&self, ty: &Type) -> bool {
        match ty {
            Type::U8
            | Type::S8
            | Type::U16
            | Type::S16
            | Type::U32
            | Type::S32
            | Type::U64
            | Type::S64
            | Type::F32
            | Type::F64
            | Type::CChar
            | Type::Usize => true,

            Type::Char | Type::Handle(_) => false,

            Type::Id(id) => match &self.types[*id].kind {
                TypeDefKind::List(_)
                | TypeDefKind::Variant(_)
                | TypeDefKind::PushBuffer(_)
                | TypeDefKind::PullBuffer(_) => false,
                TypeDefKind::Type(t) => self.all_bits_valid(t),
                TypeDefKind::Record(r) => r.fields.iter().all(|f| self.all_bits_valid(&f.ty)),
                TypeDefKind::Pointer(_) | TypeDefKind::ConstPointer(_) => true,
            },
        }
    }

    pub fn has_preview1_pointer(&self, ty: &Type) -> bool {
        match ty {
            Type::Id(id) => match &self.types[*id].kind {
                TypeDefKind::List(t) | TypeDefKind::PushBuffer(t) | TypeDefKind::PullBuffer(t) => {
                    self.has_preview1_pointer(t)
                }
                TypeDefKind::Type(t) => self.has_preview1_pointer(t),
                TypeDefKind::Pointer(_) | TypeDefKind::ConstPointer(_) => true,
                TypeDefKind::Record(r) => r.fields.iter().any(|f| self.has_preview1_pointer(&f.ty)),
                TypeDefKind::Variant(v) => v.cases.iter().any(|c| match &c.ty {
                    Some(ty) => self.has_preview1_pointer(ty),
                    None => false,
                }),
            },
            _ => false,
        }
    }
}

fn load_fs(root: &Path, name: &str) -> Result<(PathBuf, String)> {
    let path = root.join(name).with_extension("witx");
    let contents =
        fs::read_to_string(&path).context(format!("failed to read `{}`", path.display()))?;
    Ok((path, contents))
}