inf_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::Import<'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    Tuple(Tuple<'a>),
390    Flags(Flags<'a>),
391    Enum(Enum<'a>),
392    Option(OptionType<'a>),
393    Result(ResultType<'a>),
394    Own(Index<'a>),
395    Borrow(Index<'a>),
396    Stream(Stream<'a>),
397    Future(Future<'a>),
398}
399
400impl<'a> ComponentDefinedType<'a> {
401    fn parse_non_primitive(parser: Parser<'a>, mut l: Lookahead1<'a>) -> Result<Self> {
402        parser.depth_check()?;
403        if l.peek::<kw::record>()? {
404            Ok(Self::Record(parser.parse()?))
405        } else if l.peek::<kw::variant>()? {
406            Ok(Self::Variant(parser.parse()?))
407        } else if l.peek::<kw::list>()? {
408            Ok(Self::List(parser.parse()?))
409        } else if l.peek::<kw::tuple>()? {
410            Ok(Self::Tuple(parser.parse()?))
411        } else if l.peek::<kw::flags>()? {
412            Ok(Self::Flags(parser.parse()?))
413        } else if l.peek::<kw::enum_>()? {
414            Ok(Self::Enum(parser.parse()?))
415        } else if l.peek::<kw::option>()? {
416            Ok(Self::Option(parser.parse()?))
417        } else if l.peek::<kw::result>()? {
418            Ok(Self::Result(parser.parse()?))
419        } else if l.peek::<kw::own>()? {
420            parser.parse::<kw::own>()?;
421            Ok(Self::Own(parser.parse()?))
422        } else if l.peek::<kw::borrow>()? {
423            parser.parse::<kw::borrow>()?;
424            Ok(Self::Borrow(parser.parse()?))
425        } else if l.peek::<kw::stream>()? {
426            Ok(Self::Stream(parser.parse()?))
427        } else if l.peek::<kw::future>()? {
428            Ok(Self::Future(parser.parse()?))
429        } else {
430            Err(l.error())
431        }
432    }
433}
434
435impl Default for ComponentDefinedType<'_> {
436    fn default() -> Self {
437        Self::Primitive(PrimitiveValType::Bool)
438    }
439}
440
441impl Peek for ComponentDefinedType<'_> {
442    fn peek(cursor: crate::parser::Cursor<'_>) -> Result<bool> {
443        if PrimitiveValType::peek(cursor)? {
444            return Ok(true);
445        }
446
447        Ok(match cursor.lparen()? {
448            Some(cursor) => matches!(
449                cursor.keyword()?,
450                Some(("record", _))
451                    | Some(("variant", _))
452                    | Some(("list", _))
453                    | Some(("tuple", _))
454                    | Some(("flags", _))
455                    | Some(("enum", _))
456                    | Some(("option", _))
457                    | Some(("result", _))
458                    | Some(("own", _))
459                    | Some(("borrow", _))
460            ),
461            None => false,
462        })
463    }
464
465    fn display() -> &'static str {
466        "component defined type"
467    }
468}
469
470/// A record defined type.
471#[derive(Debug)]
472pub struct Record<'a> {
473    /// The fields of the record.
474    pub fields: Vec<RecordField<'a>>,
475}
476
477impl<'a> Parse<'a> for Record<'a> {
478    fn parse(parser: Parser<'a>) -> Result<Self> {
479        parser.parse::<kw::record>()?;
480        let mut fields = Vec::new();
481        while !parser.is_empty() {
482            fields.push(parser.parens(|p| p.parse())?);
483        }
484        Ok(Self { fields })
485    }
486}
487
488/// A record type field.
489#[derive(Debug)]
490pub struct RecordField<'a> {
491    /// The name of the field.
492    pub name: &'a str,
493    /// The type of the field.
494    pub ty: ComponentValType<'a>,
495}
496
497impl<'a> Parse<'a> for RecordField<'a> {
498    fn parse(parser: Parser<'a>) -> Result<Self> {
499        parser.parse::<kw::field>()?;
500        Ok(Self {
501            name: parser.parse()?,
502            ty: parser.parse()?,
503        })
504    }
505}
506
507/// A variant defined type.
508#[derive(Debug)]
509pub struct Variant<'a> {
510    /// The cases of the variant type.
511    pub cases: Vec<VariantCase<'a>>,
512}
513
514impl<'a> Parse<'a> for Variant<'a> {
515    fn parse(parser: Parser<'a>) -> Result<Self> {
516        parser.parse::<kw::variant>()?;
517        let mut cases = Vec::new();
518        while !parser.is_empty() {
519            cases.push(parser.parens(|p| p.parse())?);
520        }
521        Ok(Self { cases })
522    }
523}
524
525/// A case of a variant type.
526#[derive(Debug)]
527pub struct VariantCase<'a> {
528    /// Where this `case` was defined
529    pub span: Span,
530    /// An optional identifier to refer to this case by as part of name
531    /// resolution.
532    pub id: Option<Id<'a>>,
533    /// The name of the case.
534    pub name: &'a str,
535    /// The optional type of the case.
536    pub ty: Option<ComponentValType<'a>>,
537    /// The optional refinement.
538    pub refines: Option<Refinement<'a>>,
539}
540
541impl<'a> Parse<'a> for VariantCase<'a> {
542    fn parse(parser: Parser<'a>) -> Result<Self> {
543        let span = parser.parse::<kw::case>()?.0;
544        let id = parser.parse()?;
545        let name = parser.parse()?;
546        let ty = parser.parse()?;
547        let refines = if !parser.is_empty() {
548            Some(parser.parse()?)
549        } else {
550            None
551        };
552        Ok(Self {
553            span,
554            id,
555            name,
556            ty,
557            refines,
558        })
559    }
560}
561
562/// A refinement for a variant case.
563#[derive(Debug)]
564pub enum Refinement<'a> {
565    /// The refinement is referenced by index.
566    Index(Span, Index<'a>),
567    /// The refinement has been resolved to an index into
568    /// the cases of the variant.
569    Resolved(u32),
570}
571
572impl<'a> Parse<'a> for Refinement<'a> {
573    fn parse(parser: Parser<'a>) -> Result<Self> {
574        parser.parens(|parser| {
575            let span = parser.parse::<kw::refines>()?.0;
576            let id = parser.parse()?;
577            Ok(Self::Index(span, id))
578        })
579    }
580}
581
582/// A list type.
583#[derive(Debug)]
584pub struct List<'a> {
585    /// The element type of the array.
586    pub element: Box<ComponentValType<'a>>,
587}
588
589impl<'a> Parse<'a> for List<'a> {
590    fn parse(parser: Parser<'a>) -> Result<Self> {
591        parser.parse::<kw::list>()?;
592        Ok(Self {
593            element: Box::new(parser.parse()?),
594        })
595    }
596}
597
598/// A tuple type.
599#[derive(Debug)]
600pub struct Tuple<'a> {
601    /// The types of the fields of the tuple.
602    pub fields: Vec<ComponentValType<'a>>,
603}
604
605impl<'a> Parse<'a> for Tuple<'a> {
606    fn parse(parser: Parser<'a>) -> Result<Self> {
607        parser.parse::<kw::tuple>()?;
608        let mut fields = Vec::new();
609        while !parser.is_empty() {
610            fields.push(parser.parse()?);
611        }
612        Ok(Self { fields })
613    }
614}
615
616/// A flags type.
617#[derive(Debug)]
618pub struct Flags<'a> {
619    /// The names of the individual flags.
620    pub names: Vec<&'a str>,
621}
622
623impl<'a> Parse<'a> for Flags<'a> {
624    fn parse(parser: Parser<'a>) -> Result<Self> {
625        parser.parse::<kw::flags>()?;
626        let mut names = Vec::new();
627        while !parser.is_empty() {
628            names.push(parser.parse()?);
629        }
630        Ok(Self { names })
631    }
632}
633
634/// An enum type.
635#[derive(Debug)]
636pub struct Enum<'a> {
637    /// The tag names of the enum.
638    pub names: Vec<&'a str>,
639}
640
641impl<'a> Parse<'a> for Enum<'a> {
642    fn parse(parser: Parser<'a>) -> Result<Self> {
643        parser.parse::<kw::enum_>()?;
644        let mut names = Vec::new();
645        while !parser.is_empty() {
646            names.push(parser.parse()?);
647        }
648        Ok(Self { names })
649    }
650}
651
652/// An optional type.
653#[derive(Debug)]
654pub struct OptionType<'a> {
655    /// The type of the value, when a value is present.
656    pub element: Box<ComponentValType<'a>>,
657}
658
659impl<'a> Parse<'a> for OptionType<'a> {
660    fn parse(parser: Parser<'a>) -> Result<Self> {
661        parser.parse::<kw::option>()?;
662        Ok(Self {
663            element: Box::new(parser.parse()?),
664        })
665    }
666}
667
668/// A result type.
669#[derive(Debug)]
670pub struct ResultType<'a> {
671    /// The type on success.
672    pub ok: Option<Box<ComponentValType<'a>>>,
673    /// The type on failure.
674    pub err: Option<Box<ComponentValType<'a>>>,
675}
676
677impl<'a> Parse<'a> for ResultType<'a> {
678    fn parse(parser: Parser<'a>) -> Result<Self> {
679        parser.parse::<kw::result>()?;
680
681        let ok: Option<ComponentValType> = parser.parse()?;
682        let err: Option<ComponentValType> = if parser.peek::<LParen>()? {
683            Some(parser.parens(|parser| {
684                parser.parse::<kw::error>()?;
685                parser.parse()
686            })?)
687        } else {
688            None
689        };
690
691        Ok(Self {
692            ok: ok.map(Box::new),
693            err: err.map(Box::new),
694        })
695    }
696}
697
698/// A stream type.
699#[derive(Debug)]
700pub struct Stream<'a> {
701    /// The element type of the stream.
702    pub element: Option<Box<ComponentValType<'a>>>,
703}
704
705impl<'a> Parse<'a> for Stream<'a> {
706    fn parse(parser: Parser<'a>) -> Result<Self> {
707        parser.parse::<kw::stream>()?;
708        Ok(Self {
709            element: parser.parse::<Option<ComponentValType>>()?.map(Box::new),
710        })
711    }
712}
713
714/// A future type.
715#[derive(Debug)]
716pub struct Future<'a> {
717    /// The element type of the future, if any.
718    pub element: Option<Box<ComponentValType<'a>>>,
719}
720
721impl<'a> Parse<'a> for Future<'a> {
722    fn parse(parser: Parser<'a>) -> Result<Self> {
723        parser.parse::<kw::future>()?;
724        Ok(Self {
725            element: parser.parse::<Option<ComponentValType>>()?.map(Box::new),
726        })
727    }
728}
729
730/// A component function type with parameters and result.
731#[derive(Debug)]
732pub struct ComponentFunctionType<'a> {
733    /// The parameters of a function, optionally each having an identifier for
734    /// name resolution and a name for the custom `name` section.
735    pub params: Box<[ComponentFunctionParam<'a>]>,
736    /// The result of a function.
737    pub result: Option<ComponentValType<'a>>,
738}
739
740impl<'a> Parse<'a> for ComponentFunctionType<'a> {
741    fn parse(parser: Parser<'a>) -> Result<Self> {
742        let mut params: Vec<ComponentFunctionParam> = Vec::new();
743        while parser.peek2::<kw::param>()? {
744            params.push(parser.parens(|p| p.parse())?);
745        }
746
747        let result = if parser.peek2::<kw::result>()? {
748            Some(parser.parens(|p| {
749                p.parse::<kw::result>()?;
750                p.parse()
751            })?)
752        } else {
753            None
754        };
755
756        Ok(Self {
757            params: params.into(),
758            result,
759        })
760    }
761}
762
763/// A parameter of a [`ComponentFunctionType`].
764#[derive(Debug)]
765pub struct ComponentFunctionParam<'a> {
766    /// The name of the parameter
767    pub name: &'a str,
768    /// The type of the parameter.
769    pub ty: ComponentValType<'a>,
770}
771
772impl<'a> Parse<'a> for ComponentFunctionParam<'a> {
773    fn parse(parser: Parser<'a>) -> Result<Self> {
774        parser.parse::<kw::param>()?;
775        Ok(Self {
776            name: parser.parse()?,
777            ty: parser.parse()?,
778        })
779    }
780}
781
782/// A result of a [`ComponentFunctionType`].
783#[derive(Debug)]
784pub struct ComponentFunctionResult<'a> {
785    /// An optionally-specified name of this result
786    pub name: Option<&'a str>,
787    /// The type of the result.
788    pub ty: ComponentValType<'a>,
789}
790
791impl<'a> Parse<'a> for ComponentFunctionResult<'a> {
792    fn parse(parser: Parser<'a>) -> Result<Self> {
793        parser.parse::<kw::result>()?;
794        Ok(Self {
795            name: parser.parse()?,
796            ty: parser.parse()?,
797        })
798    }
799}
800
801/// The type of an exported item from an component or instance type.
802#[derive(Debug)]
803pub struct ComponentExportType<'a> {
804    /// Where this export was defined.
805    pub span: Span,
806    /// The name of this export.
807    pub name: ComponentExternName<'a>,
808    /// The signature of the item.
809    pub item: ItemSig<'a>,
810}
811
812impl<'a> Parse<'a> for ComponentExportType<'a> {
813    fn parse(parser: Parser<'a>) -> Result<Self> {
814        let span = parser.parse::<kw::export>()?.0;
815        let id = parser.parse()?;
816        let debug_name = parser.parse()?;
817        let name = parser.parse()?;
818        let item = parser.parens(|p| {
819            let mut item = p.parse::<ItemSigNoName<'_>>()?.0;
820            item.id = id;
821            item.name = debug_name;
822            Ok(item)
823        })?;
824        Ok(Self { span, name, item })
825    }
826}
827
828/// A type definition for a component type.
829#[derive(Debug, Default)]
830pub struct ComponentType<'a> {
831    /// The declarations of the component type.
832    pub decls: Vec<ComponentTypeDecl<'a>>,
833}
834
835impl<'a> Parse<'a> for ComponentType<'a> {
836    fn parse(parser: Parser<'a>) -> Result<Self> {
837        parser.depth_check()?;
838        Ok(Self {
839            decls: parser.parse()?,
840        })
841    }
842}
843
844/// A declaration of a component type.
845#[derive(Debug)]
846pub enum ComponentTypeDecl<'a> {
847    /// A core type definition local to the component type.
848    CoreType(CoreType<'a>),
849    /// A type definition local to the component type.
850    Type(Type<'a>),
851    /// An alias local to the component type.
852    Alias(Alias<'a>),
853    /// An import of the component type.
854    Import(ComponentImport<'a>),
855    /// An export of the component type.
856    Export(ComponentExportType<'a>),
857}
858
859impl<'a> Parse<'a> for ComponentTypeDecl<'a> {
860    fn parse(parser: Parser<'a>) -> Result<Self> {
861        let mut l = parser.lookahead1();
862        if l.peek::<kw::core>()? {
863            Ok(Self::CoreType(parser.parse()?))
864        } else if l.peek::<kw::r#type>()? {
865            Ok(Self::Type(Type::parse_no_inline_exports(parser)?))
866        } else if l.peek::<kw::alias>()? {
867            Ok(Self::Alias(parser.parse()?))
868        } else if l.peek::<kw::import>()? {
869            Ok(Self::Import(parser.parse()?))
870        } else if l.peek::<kw::export>()? {
871            Ok(Self::Export(parser.parse()?))
872        } else {
873            Err(l.error())
874        }
875    }
876}
877
878impl<'a> Parse<'a> for Vec<ComponentTypeDecl<'a>> {
879    fn parse(parser: Parser<'a>) -> Result<Self> {
880        let mut decls = Vec::new();
881        while !parser.is_empty() {
882            decls.push(parser.parens(|parser| parser.parse())?);
883        }
884        Ok(decls)
885    }
886}
887
888/// A type definition for an instance type.
889#[derive(Debug)]
890pub struct InstanceType<'a> {
891    /// The declarations of the instance type.
892    pub decls: Vec<InstanceTypeDecl<'a>>,
893}
894
895impl<'a> Parse<'a> for InstanceType<'a> {
896    fn parse(parser: Parser<'a>) -> Result<Self> {
897        parser.depth_check()?;
898        Ok(Self {
899            decls: parser.parse()?,
900        })
901    }
902}
903
904/// A declaration of an instance type.
905#[derive(Debug)]
906pub enum InstanceTypeDecl<'a> {
907    /// A core type definition local to the component type.
908    CoreType(CoreType<'a>),
909    /// A type definition local to the instance type.
910    Type(Type<'a>),
911    /// An alias local to the instance type.
912    Alias(Alias<'a>),
913    /// An export of the instance type.
914    Export(ComponentExportType<'a>),
915}
916
917impl<'a> Parse<'a> for InstanceTypeDecl<'a> {
918    fn parse(parser: Parser<'a>) -> Result<Self> {
919        let mut l = parser.lookahead1();
920        if l.peek::<kw::core>()? {
921            Ok(Self::CoreType(parser.parse()?))
922        } else if l.peek::<kw::r#type>()? {
923            Ok(Self::Type(Type::parse_no_inline_exports(parser)?))
924        } else if l.peek::<kw::alias>()? {
925            Ok(Self::Alias(parser.parse()?))
926        } else if l.peek::<kw::export>()? {
927            Ok(Self::Export(parser.parse()?))
928        } else {
929            Err(l.error())
930        }
931    }
932}
933
934impl<'a> Parse<'a> for Vec<InstanceTypeDecl<'a>> {
935    fn parse(parser: Parser<'a>) -> Result<Self> {
936        let mut decls = Vec::new();
937        while !parser.is_empty() {
938            decls.push(parser.parens(|parser| parser.parse())?);
939        }
940        Ok(decls)
941    }
942}
943
944/// A type definition for an instance type.
945#[derive(Debug)]
946pub struct ResourceType<'a> {
947    /// Representation, in core WebAssembly, of this resource.
948    pub rep: core::ValType<'a>,
949    /// The declarations of the instance type.
950    pub dtor: Option<CoreItemRef<'a, kw::func>>,
951}
952
953impl<'a> Parse<'a> for ResourceType<'a> {
954    fn parse(parser: Parser<'a>) -> Result<Self> {
955        let rep = parser.parens(|p| {
956            p.parse::<kw::rep>()?;
957            p.parse()
958        })?;
959        let dtor = if parser.is_empty() {
960            None
961        } else {
962            Some(parser.parens(|p| {
963                p.parse::<kw::dtor>()?;
964                p.parens(|p| p.parse())
965            })?)
966        };
967        Ok(Self { rep, dtor })
968    }
969}
970
971/// A value type declaration used for values in import signatures.
972#[derive(Debug)]
973pub struct ComponentValTypeUse<'a>(pub ComponentValType<'a>);
974
975impl<'a> Parse<'a> for ComponentValTypeUse<'a> {
976    fn parse(parser: Parser<'a>) -> Result<Self> {
977        match ComponentTypeUse::<'a, InlineComponentValType<'a>>::parse(parser)? {
978            ComponentTypeUse::Ref(i) => Ok(Self(ComponentValType::Ref(i.idx))),
979            ComponentTypeUse::Inline(t) => Ok(Self(ComponentValType::Inline(t.0))),
980        }
981    }
982}
983
984/// A reference to a core type defined in this component.
985///
986/// This is the same as `TypeUse`, but accepts `$T` as shorthand for
987/// `(type $T)`.
988#[derive(Debug, Clone)]
989pub enum CoreTypeUse<'a, T> {
990    /// The type that we're referencing.
991    Ref(CoreItemRef<'a, kw::r#type>),
992    /// The inline type.
993    Inline(T),
994}
995
996impl<'a, T: Parse<'a>> Parse<'a> for CoreTypeUse<'a, T> {
997    fn parse(parser: Parser<'a>) -> Result<Self> {
998        // Here the core context is assumed, so no core prefix is expected
999        if parser.peek::<LParen>()? && parser.peek2::<CoreItemRef<'a, kw::r#type>>()? {
1000            Ok(Self::Ref(parser.parens(|parser| parser.parse())?))
1001        } else {
1002            Ok(Self::Inline(parser.parse()?))
1003        }
1004    }
1005}
1006
1007impl<T> Default for CoreTypeUse<'_, T> {
1008    fn default() -> Self {
1009        let span = Span::from_offset(0);
1010        Self::Ref(CoreItemRef {
1011            idx: Index::Num(0, span),
1012            kind: kw::r#type(span),
1013            export_name: None,
1014        })
1015    }
1016}
1017
1018/// A reference to a type defined in this component.
1019///
1020/// This is the same as `TypeUse`, but accepts `$T` as shorthand for
1021/// `(type $T)`.
1022#[derive(Debug, Clone)]
1023pub enum ComponentTypeUse<'a, T> {
1024    /// The type that we're referencing.
1025    Ref(ItemRef<'a, kw::r#type>),
1026    /// The inline type.
1027    Inline(T),
1028}
1029
1030impl<'a, T: Parse<'a>> Parse<'a> for ComponentTypeUse<'a, T> {
1031    fn parse(parser: Parser<'a>) -> Result<Self> {
1032        if parser.peek::<LParen>()? && parser.peek2::<ItemRef<'a, kw::r#type>>()? {
1033            Ok(Self::Ref(parser.parens(|parser| parser.parse())?))
1034        } else {
1035            Ok(Self::Inline(parser.parse()?))
1036        }
1037    }
1038}
1039
1040impl<T> Default for ComponentTypeUse<'_, T> {
1041    fn default() -> Self {
1042        let span = Span::from_offset(0);
1043        Self::Ref(ItemRef {
1044            idx: Index::Num(0, span),
1045            kind: kw::r#type(span),
1046            export_names: Vec::new(),
1047        })
1048    }
1049}