Debian Codegraph @

crates/wast/src/wat.rs

raw
1 use crate::component::Component;
2 use crate::core::{Module, ModuleField, ModuleKind};
3 use crate::kw;
4 use crate::parser::{Parse, Parser, Result};
5 use crate::token::Span;
6
7 /// A `*.wat` file parser, or a parser for one parenthesized module.
8 ///
9 /// This is the top-level type which you'll frequently parse when working with
10 /// this crate. A `*.wat` file is either one `module` s-expression or a sequence
11 /// of s-expressions that are module fields.
12 #[derive(Debug)]
13 #[allow(missing_docs)]
14 pub enum Wat<'a> {
15 Module(Module<'a>),
16 Component(Component<'a>),
17 }
18
19 impl Wat<'_> {
20 /// Encodes this `Wat` to binary form. This calls either [`Module::encode`]
21 /// or [`Component::encode`].
22 pub fn encode(&mut self) -> std::result::Result<Vec<u8>, crate::Error> {
23 crate::core::EncodeOptions::default().encode_wat(self)
24 }
25
26 /// Returns the defining span of this file.
27 pub fn span(&self) -> Span {
28 match self {
29 Wat::Module(m) => m.span,
30 Wat::Component(c) => c.span,
31 }
32 }
33 }
34
35 impl<'a> Parse<'a> for Wat<'a> {
36 fn parse(parser: Parser<'a>) -> Result<Self> {
37 if !parser.has_meaningful_tokens() {
38 return Err(parser.error("expected at least one module field"));
39 }
40
41 parser.with_standard_annotations_registered(|parser| {
42 let wat = if parser.peek2::<kw::module>()? {
43 Wat::Module(parser.parens(|parser| parser.parse())?)
44 } else if parser.peek2::<kw::component>()? {
45 Wat::Component(parser.parens(|parser| parser.parse())?)
46 } else {
47 let fields = ModuleField::parse_remaining(parser)?;
48 Wat::Module(Module {
49 span: Span { offset: 0 },
50 id: None,
51 name: None,
52 kind: ModuleKind::Text(fields),
53 })
54 };
55 Ok(wat)
56 })
57 }
58 }