Skip to main content

wast/core/
func.rs

1use crate::core::*;
2use crate::kw;
3use crate::parser::{Parse, Parser, Result};
4use crate::token::{Id, NameAnnotation, Span};
5
6/// A WebAssembly function to be inserted into a module.
7///
8/// This is a member of both the function and code sections.
9#[derive(Debug)]
10pub struct Func<'a> {
11    /// Where this `func` was defined.
12    pub span: Span,
13    /// An identifier that this function is resolved with (optionally) for name
14    /// resolution.
15    pub id: Option<Id<'a>>,
16    /// An optional name for this function stored in the custom `name` section.
17    pub name: Option<NameAnnotation<'a>>,
18    /// If present, inline export annotations which indicate names this
19    /// definition should be exported under.
20    pub exports: InlineExport<'a>,
21    /// What kind of function this is, be it an inline-defined or imported
22    /// function.
23    pub kind: FuncKind<'a>,
24    /// The type that this function will have.
25    pub ty: TypeUse<'a, FunctionType<'a>>,
26}
27
28/// Possible ways to define a function in the text format.
29#[derive(Debug)]
30pub enum FuncKind<'a> {
31    /// A function which is actually defined as an import, such as:
32    ///
33    /// ```text
34    /// (func (type 3) (import "foo" "bar"))
35    /// ```
36    ///
37    /// The second element (`bool`) of the tuple means whether the function is _exact_. This concept is part of the custom descriptors proposal.
38    Import(InlineImport<'a>, bool),
39
40    /// Almost all functions, those defined inline in a wasm module.
41    Inline {
42        /// The list of locals, if any, for this function.
43        locals: Box<[Local<'a>]>,
44
45        /// The instructions of the function.
46        expression: Expression<'a>,
47    },
48}
49
50impl<'a> Parse<'a> for Func<'a> {
51    fn parse(parser: Parser<'a>) -> Result<Self> {
52        let span = parser.parse::<kw::func>()?.0;
53        let id = parser.parse()?;
54        let name = parser.parse()?;
55        let exports = parser.parse()?;
56
57        let (ty, kind) = if let Some(import) = parser.parse()? {
58            let (ty, exact) = if parser.peek2::<kw::exact>()? {
59                (
60                    parser.parens(|p| {
61                        p.parse::<kw::exact>()?;
62                        p.parse()
63                    })?,
64                    true,
65                )
66            } else {
67                (parser.parse()?, false)
68            };
69            (ty, FuncKind::Import(import, exact))
70        } else {
71            let ty = parser.parse()?;
72            let locals = Local::parse_remainder(parser)?.into();
73            (
74                ty,
75                FuncKind::Inline {
76                    locals,
77                    expression: parser.parse()?,
78                },
79            )
80        };
81
82        Ok(Func {
83            span,
84            id,
85            name,
86            exports,
87            kind,
88            ty,
89        })
90    }
91}
92
93/// A local for a `func` or `let` instruction.
94///
95/// Each local has an optional identifier for name resolution, an optional name
96/// for the custom `name` section, and a value type.
97#[derive(Debug, Clone)]
98pub struct Local<'a> {
99    /// An identifier that this local is resolved with (optionally) for name
100    /// resolution.
101    pub id: Option<Id<'a>>,
102    /// An optional name for this local stored in the custom `name` section.
103    pub name: Option<NameAnnotation<'a>>,
104    /// The value type of this local.
105    pub ty: ValType<'a>,
106}
107
108/// Parser for `local` instruction.
109///
110/// A single `local` instruction can generate multiple locals, hence this parser
111pub struct LocalParser<'a> {
112    /// All the locals associated with this `local` instruction.
113    pub locals: Vec<Local<'a>>,
114}
115
116impl<'a> Parse<'a> for LocalParser<'a> {
117    fn parse(parser: Parser<'a>) -> Result<Self> {
118        let mut locals = Vec::new();
119        parser.parse::<kw::local>()?;
120        if !parser.is_empty() {
121            let id: Option<_> = parser.parse()?;
122            let name: Option<_> = parser.parse()?;
123            let ty = parser.parse()?;
124            let parse_more = id.is_none() && name.is_none();
125            locals.push(Local { id, name, ty });
126            while parse_more && !parser.is_empty() {
127                locals.push(Local {
128                    id: None,
129                    name: None,
130                    ty: parser.parse()?,
131                });
132            }
133        }
134        Ok(LocalParser { locals })
135    }
136}
137
138impl<'a> Local<'a> {
139    pub(crate) fn parse_remainder(parser: Parser<'a>) -> Result<Vec<Local<'a>>> {
140        let mut locals = Vec::new();
141        while parser.peek2::<kw::local>()? {
142            parser.parens(|p| {
143                locals.extend(p.parse::<LocalParser>()?.locals);
144                Ok(())
145            })?;
146        }
147        Ok(locals)
148    }
149}