/build/cargo-vendor-dir/wast-231.0.0/src/wat.rs
Line | Count | Source |
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 | 0 | pub fn encode(&mut self) -> std::result::Result<Vec<u8>, crate::Error> { |
23 | 0 | crate::core::EncodeOptions::default().encode_wat(self) |
24 | 0 | } |
25 | | |
26 | | /// Returns the defining span of this file. |
27 | 0 | pub fn span(&self) -> Span { |
28 | 0 | match self { |
29 | 0 | Wat::Module(m) => m.span, |
30 | 0 | Wat::Component(c) => c.span, |
31 | | } |
32 | 0 | } |
33 | | } |
34 | | |
35 | | impl<'a> Parse<'a> for Wat<'a> { |
36 | 495 | fn parse(parser: Parser<'a>) -> Result<Self> { |
37 | 495 | if !parser.has_meaningful_tokens() { |
38 | 0 | return Err(parser.error("expected at least one module field")); |
39 | 495 | } |
40 | 495 | |
41 | 495 | parser.with_standard_annotations_registered(|parser| { |
42 | 495 | let wat = if parser.peek2::<kw::module>()?0 { |
43 | 495 | Wat::Module(parser.parens(|parser| parser.parse())?0 ) |
44 | 0 | } else if parser.peek2::<kw::component>()? { |
45 | 0 | Wat::Component(parser.parens(|parser| parser.parse())?) |
46 | | } else { |
47 | 0 | let fields = ModuleField::parse_remaining(parser)?; |
48 | 0 | Wat::Module(Module { |
49 | 0 | span: Span { offset: 0 }, |
50 | 0 | id: None, |
51 | 0 | name: None, |
52 | 0 | kind: ModuleKind::Text(fields), |
53 | 0 | }) |
54 | | }; |
55 | 495 | Ok(wat) |
56 | 495 | }) |
57 | 495 | } |
58 | | } |