wast/component/
types.rs

1use crate::component::*;
2use crate::core;
3use crate::kw;
4use crate::parser::Lookahead1;
5use crate::parser::Peek;
6use crate::parser::{Parse, Parser, Result};
7use crate::token::Index;
8use crate::token::LParen;
9use crate::token::{Id, NameAnnotation, Span};
10
11/// A core type declaration.
12#[derive(Debug)]
13pub struct CoreType<'a> {
14    /// Where this type was defined.
15    pub span: Span,
16    /// An optional identifier to refer to this `core type` by as part of name
17    /// resolution.
18    pub id: Option<Id<'a>>,
19    /// An optional name for this type stored in the custom `name` section.
20    pub name: Option<NameAnnotation<'a>>,
21    /// The core type's definition.
22    pub def: CoreTypeDef<'a>,
23}
24
25impl<'a> Parse<'a> for CoreType<'a> {
26    fn parse(parser: Parser<'a>) -> Result<Self> {
27        let span = parser.parse::<kw::core>()?.0;
28        parser.parse::<kw::r#type>()?;
29        let id = parser.parse()?;
30        let name = parser.parse()?;
31        let def = parser.parens(|p| p.parse())?;
32
33        Ok(Self {
34            span,
35            id,
36            name,
37            def,
38        })
39    }
40}
41
42/// Represents a core type definition.
43///
44/// In the future this may be removed when module types are a part of
45/// a core module.
46#[derive(Debug)]
47pub enum CoreTypeDef<'a> {
48    /// The type definition is one of the core types.
49    Def(core::TypeDef<'a>),
50    /// The type definition is a module type.
51    Module(ModuleType<'a>),
52}
53
54impl<'a> Parse<'a> for CoreTypeDef<'a> {
55    fn parse(parser: Parser<'a>) -> Result<Self> {
56        if parser.peek::<kw::module>()? {
57            parser.parse::<kw::module>()?;
58            Ok(Self::Module(parser.parse()?))
59        } else {
60            Ok(Self::Def(parser.parse()?))
61        }
62    }
63}
64
65/// A type definition for a core module.
66#[derive(Debug)]
67pub struct ModuleType<'a> {
68    /// The declarations of the module type.
69    pub decls: Vec<ModuleTypeDecl<'a>>,
70}
71
72impl<'a> Parse<'a> for ModuleType<'a> {
73    fn parse(parser: Parser<'a>) -> Result<Self> {
74        parser.depth_check()?;
75        Ok(Self {
76            decls: parser.parse()?,
77        })
78    }
79}
80
81/// The declarations of a [`ModuleType`].
82#[derive(Debug)]
83pub enum ModuleTypeDecl<'a> {
84    /// A core type.
85    Type(core::Type<'a>),
86    /// A core recursion group.
87    Rec(core::Rec<'a>),
88    /// An alias local to the component type.
89    Alias(Alias<'a>),
90    /// An import.
91    Import(core::Imports<'a>),
92    /// An export.
93    Export(&'a str, core::ItemSig<'a>),
94}
95
96impl<'a> Parse<'a> for ModuleTypeDecl<'a> {
97    fn parse(parser: Parser<'a>) -> Result<Self> {
98        let mut l = parser.lookahead1();
99        if l.peek::<kw::r#type>()? {
100            Ok(Self::Type(parser.parse()?))
101        } else if l.peek::<kw::rec>()? {
102            Ok(Self::Rec(parser.parse()?))
103        } else if l.peek::<kw::alias>()? {
104            Ok(Self::Alias(Alias::parse_outer_core_type_alias(parser)?))
105        } else if l.peek::<kw::import>()? {
106            Ok(Self::Import(parser.parse()?))
107        } else if l.peek::<kw::export>()? {
108            parser.parse::<kw::export>()?;
109            let name = parser.parse()?;
110            let et = parser.parens(|parser| parser.parse())?;
111            Ok(Self::Export(name, et))
112        } else {
113            Err(l.error())
114        }
115    }
116}
117
118impl<'a> Parse<'a> for Vec<ModuleTypeDecl<'a>> {
119    fn parse(parser: Parser<'a>) -> Result<Self> {
120        let mut decls = Vec::new();
121        while !parser.is_empty() {
122            decls.push(parser.parens(|parser| parser.parse())?);
123        }
124        Ok(decls)
125    }
126}
127
128/// A type declaration in a component.
129#[derive(Debug)]
130pub struct Type<'a> {
131    /// Where this type was defined.
132    pub span: Span,
133    /// An optional identifier to refer to this `type` by as part of name
134    /// resolution.
135    pub id: Option<Id<'a>>,
136    /// An optional name for this type stored in the custom `name` section.
137    pub name: Option<NameAnnotation<'a>>,
138    /// If present, inline export annotations which indicate names this
139    /// definition should be exported under.
140    pub exports: InlineExport<'a>,
141    /// The type definition.
142    pub def: TypeDef<'a>,
143}
144
145impl<'a> Type<'a> {
146    /// Parses a `Type` while allowing inline `(export "...")` names to be
147    /// defined.
148    pub fn parse_maybe_with_inline_exports(parser: Parser<'a>) -> Result<Self> {
149        Type::parse(parser, true)
150    }
151
152    fn parse_no_inline_exports(parser: Parser<'a>) -> Result<Self> {
153        Type::parse(parser, false)
154    }
155
156    fn parse(parser: Parser<'a>, allow_inline_exports: bool) -> Result<Self> {
157        let span = parser.parse::<kw::r#type>()?.0;
158        let id = parser.parse()?;
159        let name = parser.parse()?;
160        let exports = if allow_inline_exports {
161            parser.parse()?
162        } else {
163            Default::default()
164        };
165        let def = parser.parse()?;
166
167        Ok(Self {
168            span,
169            id,
170            name,
171            exports,
172            def,
173        })
174    }
175}
176
177/// A definition of a component type.
178#[derive(Debug)]
179pub enum TypeDef<'a> {
180    /// A defined value type.
181    Defined(ComponentDefinedType<'a>),
182    /// A component function type.
183    Func(ComponentFunctionType<'a>),
184    /// A component type.
185    Component(ComponentType<'a>),
186    /// An instance type.
187    Instance(InstanceType<'a>),
188    /// A resource type.
189    Resource(ResourceType<'a>),
190}
191
192impl<'a> Parse<'a> for TypeDef<'a> {
193    fn parse(parser: Parser<'a>) -> Result<Self> {
194        if parser.peek::<LParen>()? {
195            parser.parens(|parser| {
196                let mut l = parser.lookahead1();
197                if l.peek::<kw::func>()? {
198                    parser.parse::<kw::func>()?;
199                    Ok(Self::Func(parser.parse()?))
200                } else if l.peek::<kw::component>()? {
201                    parser.parse::<kw::component>()?;
202                    Ok(Self::Component(parser.parse()?))
203                } else if l.peek::<kw::instance>()? {
204                    parser.parse::<kw::instance>()?;
205                    Ok(Self::Instance(parser.parse()?))
206                } else if l.peek::<kw::resource>()? {
207                    parser.parse::<kw::resource>()?;
208                    Ok(Self::Resource(parser.parse()?))
209                } else {
210                    Ok(Self::Defined(ComponentDefinedType::parse_non_primitive(
211                        parser, l,
212                    )?))
213                }
214            })
215        } else {
216            // Only primitive types have no parens
217            Ok(Self::Defined(ComponentDefinedType::Primitive(
218                parser.parse()?,
219            )))
220        }
221    }
222}
223
224/// A primitive value type.
225#[allow(missing_docs)]
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum PrimitiveValType {
228    Bool,
229    S8,
230    U8,
231    S16,
232    U16,
233    S32,
234    U32,
235    S64,
236    U64,
237    F32,
238    F64,
239    Char,
240    String,
241    ErrorContext,
242}
243
244impl<'a> Parse<'a> for PrimitiveValType {
245    fn parse(parser: Parser<'a>) -> Result<Self> {
246        let mut l = parser.lookahead1();
247        if l.peek::<kw::bool_>()? {
248            parser.parse::<kw::bool_>()?;
249            Ok(Self::Bool)
250        } else if l.peek::<kw::s8>()? {
251            parser.parse::<kw::s8>()?;
252            Ok(Self::S8)
253        } else if l.peek::<kw::u8>()? {
254            parser.parse::<kw::u8>()?;
255            Ok(Self::U8)
256        } else if l.peek::<kw::s16>()? {
257            parser.parse::<kw::s16>()?;
258            Ok(Self::S16)
259        } else if l.peek::<kw::u16>()? {
260            parser.parse::<kw::u16>()?;
261            Ok(Self::U16)
262        } else if l.peek::<kw::s32>()? {
263            parser.parse::<kw::s32>()?;
264            Ok(Self::S32)
265        } else if l.peek::<kw::u32>()? {
266            parser.parse::<kw::u32>()?;
267            Ok(Self::U32)
268        } else if l.peek::<kw::s64>()? {
269            parser.parse::<kw::s64>()?;
270            Ok(Self::S64)
271        } else if l.peek::<kw::u64>()? {
272            parser.parse::<kw::u64>()?;
273            Ok(Self::U64)
274        } else if l.peek::<kw::f32>()? {
275            parser.parse::<kw::f32>()?;
276            Ok(Self::F32)
277        } else if l.peek::<kw::f64>()? {
278            parser.parse::<kw::f64>()?;
279            Ok(Self::F64)
280        } else if l.peek::<kw::float32>()? {
281            parser.parse::<kw::float32>()?;
282            Ok(Self::F32)
283        } else if l.peek::<kw::float64>()? {
284            parser.parse::<kw::float64>()?;
285            Ok(Self::F64)
286        } else if l.peek::<kw::char>()? {
287            parser.parse::<kw::char>()?;
288            Ok(Self::Char)
289        } else if l.peek::<kw::string>()? {
290            parser.parse::<kw::string>()?;
291            Ok(Self::String)
292        } else if l.peek::<kw::error_context>()? {
293            parser.parse::<kw::error_context>()?;
294            Ok(Self::ErrorContext)
295        } else {
296            Err(l.error())
297        }
298    }
299}
300
301impl Peek for PrimitiveValType {
302    fn peek(cursor: crate::parser::Cursor<'_>) -> Result<bool> {
303        Ok(matches!(
304            cursor.keyword()?,
305            Some(("bool", _))
306                | Some(("s8", _))
307                | Some(("u8", _))
308                | Some(("s16", _))
309                | Some(("u16", _))
310                | Some(("s32", _))
311                | Some(("u32", _))
312                | Some(("s64", _))
313                | Some(("u64", _))
314                | Some(("f32", _))
315                | Some(("f64", _))
316                | Some(("float32", _))
317                | Some(("float64", _))
318                | Some(("char", _))
319                | Some(("string", _))
320                | Some(("error-context", _))
321        ))
322    }
323
324    fn display() -> &'static str {
325        "primitive value type"
326    }
327}
328
329/// A component value type.
330#[allow(missing_docs)]
331#[derive(Debug)]
332pub enum ComponentValType<'a> {
333    /// The value type is an inline defined type.
334    Inline(ComponentDefinedType<'a>),
335    /// The value type is an index reference to a defined type.
336    Ref(Index<'a>),
337}
338
339impl<'a> Parse<'a> for ComponentValType<'a> {
340    fn parse(parser: Parser<'a>) -> Result<Self> {
341        if parser.peek::<Index<'_>>()? {
342            Ok(Self::Ref(parser.parse()?))
343        } else {
344            Ok(Self::Inline(InlineComponentValType::parse(parser)?.0))
345        }
346    }
347}
348
349impl Peek for ComponentValType<'_> {
350    fn peek(cursor: crate::parser::Cursor<'_>) -> Result<bool> {
351        Ok(Index::peek(cursor)? || ComponentDefinedType::peek(cursor)?)
352    }
353
354    fn display() -> &'static str {
355        "component value type"
356    }
357}
358
359/// An inline-only component value type.
360///
361/// This variation does not parse type indexes.
362#[allow(missing_docs)]
363#[derive(Debug)]
364pub struct InlineComponentValType<'a>(ComponentDefinedType<'a>);
365
366impl<'a> Parse<'a> for InlineComponentValType<'a> {
367    fn parse(parser: Parser<'a>) -> Result<Self> {
368        if parser.peek::<LParen>()? {
369            parser.parens(|parser| {
370                Ok(Self(ComponentDefinedType::parse_non_primitive(
371                    parser,
372                    parser.lookahead1(),
373                )?))
374            })
375        } else {
376            Ok(Self(ComponentDefinedType::Primitive(parser.parse()?)))
377        }
378    }
379}
380
381// A component defined type.
382#[allow(missing_docs)]
383#[derive(Debug)]
384pub enum ComponentDefinedType<'a> {
385    Primitive(PrimitiveValType),
386    Record(Record<'a>),
387    Variant(Variant<'a>),
388    List(List<'a>),
389    Map(Map<'a>),
390    FixedSizeList(FixedSizeList<'a>),
391    Tuple(Tuple<'a>),
392    Flags(Flags<'a>),
393    Enum(Enum<'a>),
394    Option(OptionType<'a>),
395    Result(ResultType<'a>),
396    Own(Index<'a>),
397    Borrow(Index<'a>),
398    Stream(Stream<'a>),
399    Future(Future<'a>),
400}
401
402impl<'a> ComponentDefinedType<'a> {
403    fn parse_non_primitive(parser: Parser<'a>, mut l: Lookahead1<'a>) -> Result<Self> {
404        parser.depth_check()?;
405        if l.peek::<kw::record>()? {
406            Ok(Self::Record(parser.parse()?))
407        } else if l.peek::<kw::variant>()? {
408            Ok(Self::Variant(parser.parse()?))
409        } else if l.peek::<kw::list>()? {
410            parse_list(parser)
411        } else if l.peek::<kw::map>()? {
412            Ok(Self::Map(parser.parse()?))
413        } else if l.peek::<kw::tuple>()? {
414            Ok(Self::Tuple(parser.parse()?))
415        } else if l.peek::<kw::flags>()? {
416            Ok(Self::Flags(parser.parse()?))
417        } else if l.peek::<kw::enum_>()? {
418            Ok(Self::Enum(parser.parse()?))
419        } else if l.peek::<kw::option>()? {
420            Ok(Self::Option(parser.parse()?))
421        } else if l.peek::<kw::result>()? {
422            Ok(Self::Result(parser.parse()?))
423        } else if l.peek::<kw::own>()? {
424            parser.parse::<kw::own>()?;
425            Ok(Self::Own(parser.parse()?))
426        } else if l.peek::<kw::borrow>()? {
427            parser.parse::<kw::borrow>()?;
428            Ok(Self::Borrow(parser.parse()?))
429        } else if l.peek::<kw::stream>()? {
430            Ok(Self::Stream(parser.parse()?))
431        } else if l.peek::<kw::future>()? {
432            Ok(Self::Future(parser.parse()?))
433        } else {
434            Err(l.error())
435        }
436    }
437}
438
439impl Default for ComponentDefinedType<'_> {
440    fn default() -> Self {
441        Self::Primitive(PrimitiveValType::Bool)
442    }
443}
444
445impl Peek for ComponentDefinedType<'_> {
446    fn peek(cursor: crate::parser::Cursor<'_>) -> Result<bool> {
447        if PrimitiveValType::peek(cursor)? {
448            return Ok(true);
449        }
450
451        Ok(match cursor.lparen()? {
452            Some(cursor) => matches!(
453                cursor.keyword()?,
454                Some(("record", _))
455                    | Some(("variant", _))
456                    | Some(("list", _))
457                    | Some(("map", _))
458                    | Some(("tuple", _))
459                    | Some(("flags", _))
460                    | Some(("enum", _))
461                    | Some(("option", _))
462                    | Some(("result", _))
463                    | Some(("own", _))
464                    | Some(("borrow", _))
465            ),
466            None => false,
467        })
468    }
469
470    fn display() -> &'static str {
471        "component defined type"
472    }
473}
474
475/// A record defined type.
476#[derive(Debug)]
477pub struct Record<'a> {
478    /// The fields of the record.
479    pub fields: Vec<RecordField<'a>>,
480}
481
482impl<'a> Parse<'a> for Record<'a> {
483    fn parse(parser: Parser<'a>) -> Result<Self> {
484        parser.parse::<kw::record>()?;
485        let mut fields = Vec::new();
486        while !parser.is_empty() {
487            fields.push(parser.parens(|p| p.parse())?);
488        }
489        Ok(Self { fields })
490    }
491}
492
493/// A record type field.
494#[derive(Debug)]
495pub struct RecordField<'a> {
496    /// The name of the field.
497    pub name: &'a str,
498    /// The type of the field.
499    pub ty: ComponentValType<'a>,
500}
501
502impl<'a> Parse<'a> for RecordField<'a> {
503    fn parse(parser: Parser<'a>) -> Result<Self> {
504        parser.parse::<kw::field>()?;
505        Ok(Self {
506            name: parser.parse()?,
507            ty: parser.parse()?,
508        })
509    }
510}
511
512/// A variant defined type.
513#[derive(Debug)]
514pub struct Variant<'a> {
515    /// The cases of the variant type.
516    pub cases: Vec<VariantCase<'a>>,
517}
518
519impl<'a> Parse<'a> for Variant<'a> {
520    fn parse(parser: Parser<'a>) -> Result<Self> {
521        parser.parse::<kw::variant>()?;
522        let mut cases = Vec::new();
523        while !parser.is_empty() {
524            cases.push(parser.parens(|p| p.parse())?);
525        }
526        Ok(Self { cases })
527    }
528}
529
530/// A case of a variant type.
531#[derive(Debug)]
532pub struct VariantCase<'a> {
533    /// Where this `case` was defined
534    pub span: Span,
535    /// An optional identifier to refer to this case by as part of name
536    /// resolution.
537    pub id: Option<Id<'a>>,
538    /// The name of the case.
539    pub name: &'a str,
540    /// The optional type of the case.
541    pub ty: Option<ComponentValType<'a>>,
542    /// The optional refinement.
543    pub refines: Option<Refinement<'a>>,
544}
545
546impl<'a> Parse<'a> for VariantCase<'a> {
547    fn parse(parser: Parser<'a>) -> Result<Self> {
548        let span = parser.parse::<kw::case>()?.0;
549        let id = parser.parse()?;
550        let name = parser.parse()?;
551        let ty = parser.parse()?;
552        let refines = if !parser.is_empty() {
553            Some(parser.parse()?)
554        } else {
555            None
556        };
557        Ok(Self {
558            span,
559            id,
560            name,
561            ty,
562            refines,
563        })
564    }
565}
566
567/// A refinement for a variant case.
568#[derive(Debug)]
569pub enum Refinement<'a> {
570    /// The refinement is referenced by index.
571    Index(Span, Index<'a>),
572    /// The refinement has been resolved to an index into
573    /// the cases of the variant.
574    Resolved(u32),
575}
576
577impl<'a> Parse<'a> for Refinement<'a> {
578    fn parse(parser: Parser<'a>) -> Result<Self> {
579        parser.parens(|parser| {
580            let span = parser.parse::<kw::refines>()?.0;
581            let id = parser.parse()?;
582            Ok(Self::Index(span, id))
583        })
584    }
585}
586
587/// A list type.
588#[derive(Debug)]
589pub struct List<'a> {
590    /// The element type of the array.
591    pub element: Box<ComponentValType<'a>>,
592}
593
594/// A map type.
595#[derive(Debug)]
596pub struct Map<'a> {
597    /// The key type of the map.
598    pub key: Box<ComponentValType<'a>>,
599    /// The value type of the map.
600    pub value: Box<ComponentValType<'a>>,
601}
602
603/// A fixed size list type.
604#[derive(Debug)]
605pub struct FixedSizeList<'a> {
606    /// The element type of the array.
607    pub element: Box<ComponentValType<'a>>,
608    /// Number of Elements
609    pub elements: u32,
610}
611
612fn parse_list<'a>(parser: Parser<'a>) -> Result<ComponentDefinedType<'a>> {
613    parser.parse::<kw::list>()?;
614    let tp = parser.parse()?;
615    let elements = parser.parse::<Option<u32>>()?;
616    if let Some(elements) = elements {
617        Ok(ComponentDefinedType::FixedSizeList(FixedSizeList {
618            element: Box::new(tp),
619            elements,
620        }))
621    } else {
622        Ok(ComponentDefinedType::List(List {
623            element: Box::new(tp),
624        }))
625    }
626}
627
628impl<'a> Parse<'a> for Map<'a> {
629    fn parse(parser: Parser<'a>) -> Result<Self> {
630        parser.parse::<kw::map>()?;
631        let key = parser.parse()?;
632        let value = parser.parse()?;
633        Ok(Self {
634            key: Box::new(key),
635            value: Box::new(value),
636        })
637    }
638}
639
640/// A tuple type.
641#[derive(Debug)]
642pub struct Tuple<'a> {
643    /// The types of the fields of the tuple.
644    pub fields: Vec<ComponentValType<'a>>,
645}
646
647impl<'a> Parse<'a> for Tuple<'a> {
648    fn parse(parser: Parser<'a>) -> Result<Self> {
649        parser.parse::<kw::tuple>()?;
650        let mut fields = Vec::new();
651        while !parser.is_empty() {
652            fields.push(parser.parse()?);
653        }
654        Ok(Self { fields })
655    }
656}
657
658/// A flags type.
659#[derive(Debug)]
660pub struct Flags<'a> {
661    /// The names of the individual flags.
662    pub names: Vec<&'a str>,
663}
664
665impl<'a> Parse<'a> for Flags<'a> {
666    fn parse(parser: Parser<'a>) -> Result<Self> {
667        parser.parse::<kw::flags>()?;
668        let mut names = Vec::new();
669        while !parser.is_empty() {
670            names.push(parser.parse()?);
671        }
672        Ok(Self { names })
673    }
674}
675
676/// An enum type.
677#[derive(Debug)]
678pub struct Enum<'a> {
679    /// The tag names of the enum.
680    pub names: Vec<&'a str>,
681}
682
683impl<'a> Parse<'a> for Enum<'a> {
684    fn parse(parser: Parser<'a>) -> Result<Self> {
685        parser.parse::<kw::enum_>()?;
686        let mut names = Vec::new();
687        while !parser.is_empty() {
688            names.push(parser.parse()?);
689        }
690        Ok(Self { names })
691    }
692}
693
694/// An optional type.
695#[derive(Debug)]
696pub struct OptionType<'a> {
697    /// The type of the value, when a value is present.
698    pub element: Box<ComponentValType<'a>>,
699}
700
701impl<'a> Parse<'a> for OptionType<'a> {
702    fn parse(parser: Parser<'a>) -> Result<Self> {
703        parser.parse::<kw::option>()?;
704        Ok(Self {
705            element: Box::new(parser.parse()?),
706        })
707    }
708}
709
710/// A result type.
711#[derive(Debug)]
712pub struct ResultType<'a> {
713    /// The type on success.
714    pub ok: Option<Box<ComponentValType<'a>>>,
715    /// The type on failure.
716    pub err: Option<Box<ComponentValType<'a>>>,
717}
718
719impl<'a> Parse<'a> for ResultType<'a> {
720    fn parse(parser: Parser<'a>) -> Result<Self> {
721        parser.parse::<kw::result>()?;
722
723        let ok: Option<ComponentValType> = parser.parse()?;
724        let err: Option<ComponentValType> = if parser.peek::<LParen>()? {
725            Some(parser.parens(|parser| {
726                parser.parse::<kw::error>()?;
727                parser.parse()
728            })?)
729        } else {
730            None
731        };
732
733        Ok(Self {
734            ok: ok.map(Box::new),
735            err: err.map(Box::new),
736        })
737    }
738}
739
740/// A stream type.
741#[derive(Debug)]
742pub struct Stream<'a> {
743    /// The element type of the stream.
744    pub element: Option<Box<ComponentValType<'a>>>,
745}
746
747impl<'a> Parse<'a> for Stream<'a> {
748    fn parse(parser: Parser<'a>) -> Result<Self> {
749        parser.parse::<kw::stream>()?;
750        Ok(Self {
751            element: parser.parse::<Option<ComponentValType>>()?.map(Box::new),
752        })
753    }
754}
755
756/// A future type.
757#[derive(Debug)]
758pub struct Future<'a> {
759    /// The element type of the future, if any.
760    pub element: Option<Box<ComponentValType<'a>>>,
761}
762
763impl<'a> Parse<'a> for Future<'a> {
764    fn parse(parser: Parser<'a>) -> Result<Self> {
765        parser.parse::<kw::future>()?;
766        Ok(Self {
767            element: parser.parse::<Option<ComponentValType>>()?.map(Box::new),
768        })
769    }
770}
771
772/// A component function type with parameters and result.
773#[derive(Debug)]
774pub struct ComponentFunctionType<'a> {
775    /// Whether or not this is an `async` fnction.
776    pub async_: bool,
777    /// The parameters of a function, optionally each having an identifier for
778    /// name resolution and a name for the custom `name` section.
779    pub params: Box<[ComponentFunctionParam<'a>]>,
780    /// The result of a function.
781    pub result: Option<ComponentValType<'a>>,
782}
783
784impl<'a> Parse<'a> for ComponentFunctionType<'a> {
785    fn parse(parser: Parser<'a>) -> Result<Self> {
786        let async_ = parser.parse::<Option<kw::r#async>>()?.is_some();
787        let mut params: Vec<ComponentFunctionParam> = Vec::new();
788        while parser.peek2::<kw::param>()? {
789            params.push(parser.parens(|p| p.parse())?);
790        }
791
792        let result = if parser.peek2::<kw::result>()? {
793            Some(parser.parens(|p| {
794                p.parse::<kw::result>()?;
795                p.parse()
796            })?)
797        } else {
798            None
799        };
800
801        Ok(Self {
802            async_,
803            params: params.into(),
804            result,
805        })
806    }
807}
808
809/// A parameter of a [`ComponentFunctionType`].
810#[derive(Debug)]
811pub struct ComponentFunctionParam<'a> {
812    /// The name of the parameter
813    pub name: &'a str,
814    /// The type of the parameter.
815    pub ty: ComponentValType<'a>,
816}
817
818impl<'a> Parse<'a> for ComponentFunctionParam<'a> {
819    fn parse(parser: Parser<'a>) -> Result<Self> {
820        parser.parse::<kw::param>()?;
821        Ok(Self {
822            name: parser.parse()?,
823            ty: parser.parse()?,
824        })
825    }
826}
827
828/// A result of a [`ComponentFunctionType`].
829#[derive(Debug)]
830pub struct ComponentFunctionResult<'a> {
831    /// An optionally-specified name of this result
832    pub name: Option<&'a str>,
833    /// The type of the result.
834    pub ty: ComponentValType<'a>,
835}
836
837impl<'a> Parse<'a> for ComponentFunctionResult<'a> {
838    fn parse(parser: Parser<'a>) -> Result<Self> {
839        parser.parse::<kw::result>()?;
840        Ok(Self {
841            name: parser.parse()?,
842            ty: parser.parse()?,
843        })
844    }
845}
846
847/// The type of an exported item from an component or instance type.
848#[derive(Debug)]
849pub struct ComponentExportType<'a> {
850    /// Where this export was defined.
851    pub span: Span,
852    /// The name of this export.
853    pub name: ComponentExternName<'a>,
854    /// The signature of the item.
855    pub item: ItemSig<'a>,
856}
857
858impl<'a> Parse<'a> for ComponentExportType<'a> {
859    fn parse(parser: Parser<'a>) -> Result<Self> {
860        let span = parser.parse::<kw::export>()?.0;
861        let name = parser.parse()?;
862        let item = parser.parens(|p| p.parse())?;
863        Ok(Self { span, name, item })
864    }
865}
866
867/// A type definition for a component type.
868#[derive(Debug, Default)]
869pub struct ComponentType<'a> {
870    /// The declarations of the component type.
871    pub decls: Vec<ComponentTypeDecl<'a>>,
872}
873
874impl<'a> Parse<'a> for ComponentType<'a> {
875    fn parse(parser: Parser<'a>) -> Result<Self> {
876        parser.depth_check()?;
877        Ok(Self {
878            decls: parser.parse()?,
879        })
880    }
881}
882
883/// A declaration of a component type.
884#[derive(Debug)]
885pub enum ComponentTypeDecl<'a> {
886    /// A core type definition local to the component type.
887    CoreType(CoreType<'a>),
888    /// A type definition local to the component type.
889    Type(Type<'a>),
890    /// An alias local to the component type.
891    Alias(Alias<'a>),
892    /// An import of the component type.
893    Import(ComponentImport<'a>),
894    /// An export of the component type.
895    Export(ComponentExportType<'a>),
896}
897
898impl<'a> Parse<'a> for ComponentTypeDecl<'a> {
899    fn parse(parser: Parser<'a>) -> Result<Self> {
900        let mut l = parser.lookahead1();
901        if l.peek::<kw::core>()? {
902            Ok(Self::CoreType(parser.parse()?))
903        } else if l.peek::<kw::r#type>()? {
904            Ok(Self::Type(Type::parse_no_inline_exports(parser)?))
905        } else if l.peek::<kw::alias>()? {
906            Ok(Self::Alias(parser.parse()?))
907        } else if l.peek::<kw::import>()? {
908            Ok(Self::Import(parser.parse()?))
909        } else if l.peek::<kw::export>()? {
910            Ok(Self::Export(parser.parse()?))
911        } else {
912            Err(l.error())
913        }
914    }
915}
916
917impl<'a> Parse<'a> for Vec<ComponentTypeDecl<'a>> {
918    fn parse(parser: Parser<'a>) -> Result<Self> {
919        let mut decls = Vec::new();
920        while !parser.is_empty() {
921            decls.push(parser.parens(|parser| parser.parse())?);
922        }
923        Ok(decls)
924    }
925}
926
927/// A type definition for an instance type.
928#[derive(Debug)]
929pub struct InstanceType<'a> {
930    /// The declarations of the instance type.
931    pub decls: Vec<InstanceTypeDecl<'a>>,
932}
933
934impl<'a> Parse<'a> for InstanceType<'a> {
935    fn parse(parser: Parser<'a>) -> Result<Self> {
936        parser.depth_check()?;
937        Ok(Self {
938            decls: parser.parse()?,
939        })
940    }
941}
942
943/// A declaration of an instance type.
944#[derive(Debug)]
945pub enum InstanceTypeDecl<'a> {
946    /// A core type definition local to the component type.
947    CoreType(CoreType<'a>),
948    /// A type definition local to the instance type.
949    Type(Type<'a>),
950    /// An alias local to the instance type.
951    Alias(Alias<'a>),
952    /// An export of the instance type.
953    Export(ComponentExportType<'a>),
954}
955
956impl<'a> Parse<'a> for InstanceTypeDecl<'a> {
957    fn parse(parser: Parser<'a>) -> Result<Self> {
958        let mut l = parser.lookahead1();
959        if l.peek::<kw::core>()? {
960            Ok(Self::CoreType(parser.parse()?))
961        } else if l.peek::<kw::r#type>()? {
962            Ok(Self::Type(Type::parse_no_inline_exports(parser)?))
963        } else if l.peek::<kw::alias>()? {
964            Ok(Self::Alias(parser.parse()?))
965        } else if l.peek::<kw::export>()? {
966            Ok(Self::Export(parser.parse()?))
967        } else {
968            Err(l.error())
969        }
970    }
971}
972
973impl<'a> Parse<'a> for Vec<InstanceTypeDecl<'a>> {
974    fn parse(parser: Parser<'a>) -> Result<Self> {
975        let mut decls = Vec::new();
976        while !parser.is_empty() {
977            decls.push(parser.parens(|parser| parser.parse())?);
978        }
979        Ok(decls)
980    }
981}
982
983/// A type definition for an instance type.
984#[derive(Debug)]
985pub struct ResourceType<'a> {
986    /// Representation, in core WebAssembly, of this resource.
987    pub rep: core::ValType<'a>,
988    /// The declarations of the instance type.
989    pub dtor: Option<CoreItemRef<'a, kw::func>>,
990}
991
992impl<'a> Parse<'a> for ResourceType<'a> {
993    fn parse(parser: Parser<'a>) -> Result<Self> {
994        let rep = parser.parens(|p| {
995            p.parse::<kw::rep>()?;
996            p.parse()
997        })?;
998        let dtor = if parser.is_empty() {
999            None
1000        } else {
1001            Some(parser.parens(|p| {
1002                p.parse::<kw::dtor>()?;
1003                p.parens(|p| p.parse())
1004            })?)
1005        };
1006        Ok(Self { rep, dtor })
1007    }
1008}
1009
1010/// A value type declaration used for values in import signatures.
1011#[derive(Debug)]
1012pub struct ComponentValTypeUse<'a>(pub ComponentValType<'a>);
1013
1014impl<'a> Parse<'a> for ComponentValTypeUse<'a> {
1015    fn parse(parser: Parser<'a>) -> Result<Self> {
1016        match ComponentTypeUse::<'a, InlineComponentValType<'a>>::parse(parser)? {
1017            ComponentTypeUse::Ref(i) => Ok(Self(ComponentValType::Ref(i.idx))),
1018            ComponentTypeUse::Inline(t) => Ok(Self(ComponentValType::Inline(t.0))),
1019        }
1020    }
1021}
1022
1023/// A reference to a core type defined in this component.
1024///
1025/// This is the same as `TypeUse`, but accepts `$T` as shorthand for
1026/// `(type $T)`.
1027#[derive(Debug, Clone)]
1028pub enum CoreTypeUse<'a, T> {
1029    /// The type that we're referencing.
1030    Ref(CoreItemRef<'a, kw::r#type>),
1031    /// The inline type.
1032    Inline(T),
1033}
1034
1035impl<'a, T: Parse<'a>> Parse<'a> for CoreTypeUse<'a, T> {
1036    fn parse(parser: Parser<'a>) -> Result<Self> {
1037        // Here the core context is assumed, so no core prefix is expected
1038        if parser.peek::<LParen>()? && parser.peek2::<CoreItemRef<'a, kw::r#type>>()? {
1039            Ok(Self::Ref(parser.parens(|parser| parser.parse())?))
1040        } else {
1041            Ok(Self::Inline(parser.parse()?))
1042        }
1043    }
1044}
1045
1046impl<T> Default for CoreTypeUse<'_, T> {
1047    fn default() -> Self {
1048        let span = Span::from_offset(0);
1049        Self::Ref(CoreItemRef {
1050            idx: Index::Num(0, span),
1051            kind: kw::r#type(span),
1052            export_name: None,
1053        })
1054    }
1055}
1056
1057/// A reference to a type defined in this component.
1058///
1059/// This is the same as `TypeUse`, but accepts `$T` as shorthand for
1060/// `(type $T)`.
1061#[derive(Debug, Clone)]
1062pub enum ComponentTypeUse<'a, T> {
1063    /// The type that we're referencing.
1064    Ref(ItemRef<'a, kw::r#type>),
1065    /// The inline type.
1066    Inline(T),
1067}
1068
1069impl<'a, T: Parse<'a>> Parse<'a> for ComponentTypeUse<'a, T> {
1070    fn parse(parser: Parser<'a>) -> Result<Self> {
1071        if parser.peek::<LParen>()? && parser.peek2::<ItemRef<'a, kw::r#type>>()? {
1072            Ok(Self::Ref(parser.parens(|parser| parser.parse())?))
1073        } else {
1074            Ok(Self::Inline(parser.parse()?))
1075        }
1076    }
1077}
1078
1079impl<T> Default for ComponentTypeUse<'_, T> {
1080    fn default() -> Self {
1081        let span = Span::from_offset(0);
1082        Self::Ref(ItemRef {
1083            idx: Index::Num(0, span),
1084            kind: kw::r#type(span),
1085            export_names: Vec::new(),
1086        })
1087    }
1088}