Skip to main content

wat_ast/
document.rs

1use std::fmt;
2
3use wast::parser::{Parse, Parser, Result};
4
5use crate::{Expr, Module, ToWat, ToWatParams};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct Document {
9    module: Module,
10}
11
12impl Document {
13    pub fn new(module: Module) -> Self {
14        Self { module }
15    }
16}
17
18impl fmt::Display for Document {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        write!(
21            f,
22            "{}",
23            Expr::SExpr(Box::new(self.module.clone())).to_wat(&ToWatParams {
24                indent_size:  2,
25                indent_level: 0,
26            })
27        )
28    }
29}
30
31impl Parse<'_> for Document {
32    fn parse(parser: Parser<'_>) -> Result<Self> {
33        let module = parser.parens(|p| p.parse::<Module>())?;
34
35        Ok(Self { module })
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use crate::*;
42
43    #[test]
44    fn empty_module() {
45        assert_eq!(
46            wast::parser::parse::<Document>(
47                &wast::parser::ParseBuffer::new("(module)").unwrap()
48            )
49            .unwrap(),
50            Document {
51                module: Module::with_sections(Vec::new()),
52            },
53        )
54    }
55
56    #[test]
57    fn output_empty_module() {
58        assert_eq!(
59            Document {
60                module: Module::with_sections(Vec::new()),
61            }
62            .to_string(),
63            "(module)",
64        );
65    }
66}