1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
use crate::component::*;
use crate::core;
use crate::kw;
use crate::parser::Lookahead1;
use crate::parser::Peek;
use crate::parser::{Parse, Parser, Result};
use crate::token::Index;
use crate::token::LParen;
use crate::token::{Id, NameAnnotation, Span};

/// A core type declaration.
#[derive(Debug)]
pub struct CoreType<'a> {
    /// Where this type was defined.
    pub span: Span,
    /// An optional identifier to refer to this `core type` by as part of name
    /// resolution.
    pub id: Option<Id<'a>>,
    /// An optional name for this type stored in the custom `name` section.
    pub name: Option<NameAnnotation<'a>>,
    /// The core type's definition.
    pub def: CoreTypeDef<'a>,
}

impl<'a> Parse<'a> for CoreType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let span = parser.parse::<kw::core>()?.0;
        parser.parse::<kw::r#type>()?;
        let id = parser.parse()?;
        let name = parser.parse()?;
        let def = parser.parens(|p| p.parse())?;

        Ok(Self {
            span,
            id,
            name,
            def,
        })
    }
}

/// Represents a core type definition.
///
/// In the future this may be removed when module types are a part of
/// a core module.
#[derive(Debug)]
pub enum CoreTypeDef<'a> {
    /// The type definition is one of the core types.
    Def(core::TypeDef<'a>),
    /// The type definition is a module type.
    Module(ModuleType<'a>),
}

impl<'a> Parse<'a> for CoreTypeDef<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        if parser.peek::<kw::module>() {
            parser.parse::<kw::module>()?;
            Ok(Self::Module(parser.parse()?))
        } else {
            Ok(Self::Def(parser.parse()?))
        }
    }
}

/// A type definition for a core module.
#[derive(Debug)]
pub struct ModuleType<'a> {
    /// The declarations of the module type.
    pub decls: Vec<ModuleTypeDecl<'a>>,
}

impl<'a> Parse<'a> for ModuleType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.depth_check()?;
        Ok(Self {
            decls: parser.parse()?,
        })
    }
}

/// The declarations of a [`ModuleType`].
#[derive(Debug)]
pub enum ModuleTypeDecl<'a> {
    /// A core type.
    Type(core::Type<'a>),
    /// An alias local to the component type.
    Alias(Alias<'a>),
    /// An import.
    Import(core::Import<'a>),
    /// An export.
    Export(&'a str, core::ItemSig<'a>),
}

impl<'a> Parse<'a> for ModuleTypeDecl<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let mut l = parser.lookahead1();
        if l.peek::<kw::r#type>() {
            Ok(Self::Type(parser.parse()?))
        } else if l.peek::<kw::alias>() {
            Ok(Self::Alias(Alias::parse_outer_type_alias(parser, true)?))
        } else if l.peek::<kw::import>() {
            Ok(Self::Import(parser.parse()?))
        } else if l.peek::<kw::export>() {
            parser.parse::<kw::export>()?;
            let name = parser.parse()?;
            let et = parser.parens(|parser| parser.parse())?;
            Ok(Self::Export(name, et))
        } else {
            Err(l.error())
        }
    }
}

impl<'a> Parse<'a> for Vec<ModuleTypeDecl<'a>> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let mut decls = Vec::new();
        while !parser.is_empty() {
            decls.push(parser.parens(|parser| parser.parse())?);
        }
        Ok(decls)
    }
}

/// A type declaration in a component.
#[derive(Debug)]
pub struct Type<'a> {
    /// Where this type was defined.
    pub span: Span,
    /// An optional identifier to refer to this `type` by as part of name
    /// resolution.
    pub id: Option<Id<'a>>,
    /// An optional name for this type stored in the custom `name` section.
    pub name: Option<NameAnnotation<'a>>,
    /// If present, inline export annotations which indicate names this
    /// definition should be exported under.
    pub exports: core::InlineExport<'a>,
    /// The type definition.
    pub def: TypeDef<'a>,
}

impl<'a> Parse<'a> for Type<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let span = parser.parse::<kw::r#type>()?.0;
        let id = parser.parse()?;
        let name = parser.parse()?;
        let exports = parser.parse()?;
        let def = parser.parse()?;

        Ok(Self {
            span,
            id,
            name,
            exports,
            def,
        })
    }
}

/// A definition of a component type.
#[derive(Debug)]
pub enum TypeDef<'a> {
    /// A defined value type.
    Defined(ComponentDefinedType<'a>),
    /// A component function type.
    Func(ComponentFunctionType<'a>),
    /// A component type.
    Component(ComponentType<'a>),
    /// An instance type.
    Instance(InstanceType<'a>),
}

impl<'a> Parse<'a> for TypeDef<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        if parser.peek::<LParen>() {
            parser.parens(|parser| {
                let mut l = parser.lookahead1();
                if l.peek::<kw::func>() {
                    parser.parse::<kw::func>()?;
                    Ok(Self::Func(parser.parse()?))
                } else if l.peek::<kw::component>() {
                    parser.parse::<kw::component>()?;
                    Ok(Self::Component(parser.parse()?))
                } else if l.peek::<kw::instance>() {
                    parser.parse::<kw::instance>()?;
                    Ok(Self::Instance(parser.parse()?))
                } else {
                    Ok(Self::Defined(ComponentDefinedType::parse_non_primitive(
                        parser, l,
                    )?))
                }
            })
        } else {
            // Only primitive types have no parens
            Ok(Self::Defined(ComponentDefinedType::Primitive(
                parser.parse()?,
            )))
        }
    }
}

/// A primitive value type.
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrimitiveValType {
    Bool,
    S8,
    U8,
    S16,
    U16,
    S32,
    U32,
    S64,
    U64,
    Float32,
    Float64,
    Char,
    String,
}

impl<'a> Parse<'a> for PrimitiveValType {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let mut l = parser.lookahead1();
        if l.peek::<kw::bool_>() {
            parser.parse::<kw::bool_>()?;
            Ok(Self::Bool)
        } else if l.peek::<kw::s8>() {
            parser.parse::<kw::s8>()?;
            Ok(Self::S8)
        } else if l.peek::<kw::u8>() {
            parser.parse::<kw::u8>()?;
            Ok(Self::U8)
        } else if l.peek::<kw::s16>() {
            parser.parse::<kw::s16>()?;
            Ok(Self::S16)
        } else if l.peek::<kw::u16>() {
            parser.parse::<kw::u16>()?;
            Ok(Self::U16)
        } else if l.peek::<kw::s32>() {
            parser.parse::<kw::s32>()?;
            Ok(Self::S32)
        } else if l.peek::<kw::u32>() {
            parser.parse::<kw::u32>()?;
            Ok(Self::U32)
        } else if l.peek::<kw::s64>() {
            parser.parse::<kw::s64>()?;
            Ok(Self::S64)
        } else if l.peek::<kw::u64>() {
            parser.parse::<kw::u64>()?;
            Ok(Self::U64)
        } else if l.peek::<kw::float32>() {
            parser.parse::<kw::float32>()?;
            Ok(Self::Float32)
        } else if l.peek::<kw::float64>() {
            parser.parse::<kw::float64>()?;
            Ok(Self::Float64)
        } else if l.peek::<kw::char>() {
            parser.parse::<kw::char>()?;
            Ok(Self::Char)
        } else if l.peek::<kw::string>() {
            parser.parse::<kw::string>()?;
            Ok(Self::String)
        } else {
            Err(l.error())
        }
    }
}

impl Peek for PrimitiveValType {
    fn peek(cursor: crate::parser::Cursor<'_>) -> bool {
        matches!(
            cursor.keyword(),
            Some(("bool", _))
                | Some(("s8", _))
                | Some(("u8", _))
                | Some(("s16", _))
                | Some(("u16", _))
                | Some(("s32", _))
                | Some(("u32", _))
                | Some(("s64", _))
                | Some(("u64", _))
                | Some(("float32", _))
                | Some(("float64", _))
                | Some(("char", _))
                | Some(("string", _))
        )
    }

    fn display() -> &'static str {
        "primitive value type"
    }
}

/// A component value type.
#[allow(missing_docs)]
#[derive(Debug)]
pub enum ComponentValType<'a> {
    /// The value type is an inline defined type.
    Inline(ComponentDefinedType<'a>),
    /// The value type is an index reference to a defined type.
    Ref(Index<'a>),
}

impl<'a> Parse<'a> for ComponentValType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        if parser.peek::<Index<'_>>() {
            Ok(Self::Ref(parser.parse()?))
        } else {
            Ok(Self::Inline(InlineComponentValType::parse(parser)?.0))
        }
    }
}

impl Peek for ComponentValType<'_> {
    fn peek(cursor: crate::parser::Cursor<'_>) -> bool {
        Index::peek(cursor) || ComponentDefinedType::peek(cursor)
    }

    fn display() -> &'static str {
        "component value type"
    }
}

/// An inline-only component value type.
///
/// This variation does not parse type indexes.
#[allow(missing_docs)]
#[derive(Debug)]
pub struct InlineComponentValType<'a>(ComponentDefinedType<'a>);

impl<'a> Parse<'a> for InlineComponentValType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        if parser.peek::<LParen>() {
            parser.parens(|parser| {
                Ok(Self(ComponentDefinedType::parse_non_primitive(
                    parser,
                    parser.lookahead1(),
                )?))
            })
        } else {
            Ok(Self(ComponentDefinedType::Primitive(parser.parse()?)))
        }
    }
}

// A component defined type.
#[allow(missing_docs)]
#[derive(Debug)]
pub enum ComponentDefinedType<'a> {
    Primitive(PrimitiveValType),
    Record(Record<'a>),
    Variant(Variant<'a>),
    List(List<'a>),
    Tuple(Tuple<'a>),
    Flags(Flags<'a>),
    Enum(Enum<'a>),
    Union(Union<'a>),
    Option(OptionType<'a>),
    Result(ResultType<'a>),
}

impl<'a> ComponentDefinedType<'a> {
    fn parse_non_primitive(parser: Parser<'a>, mut l: Lookahead1<'a>) -> Result<Self> {
        parser.depth_check()?;
        if l.peek::<kw::record>() {
            Ok(Self::Record(parser.parse()?))
        } else if l.peek::<kw::variant>() {
            Ok(Self::Variant(parser.parse()?))
        } else if l.peek::<kw::list>() {
            Ok(Self::List(parser.parse()?))
        } else if l.peek::<kw::tuple>() {
            Ok(Self::Tuple(parser.parse()?))
        } else if l.peek::<kw::flags>() {
            Ok(Self::Flags(parser.parse()?))
        } else if l.peek::<kw::enum_>() {
            Ok(Self::Enum(parser.parse()?))
        } else if l.peek::<kw::union>() {
            Ok(Self::Union(parser.parse()?))
        } else if l.peek::<kw::option>() {
            Ok(Self::Option(parser.parse()?))
        } else if l.peek::<kw::result>() {
            Ok(Self::Result(parser.parse()?))
        } else {
            Err(l.error())
        }
    }
}

impl Default for ComponentDefinedType<'_> {
    fn default() -> Self {
        Self::Primitive(PrimitiveValType::Bool)
    }
}

impl Peek for ComponentDefinedType<'_> {
    fn peek(cursor: crate::parser::Cursor<'_>) -> bool {
        if PrimitiveValType::peek(cursor) {
            return true;
        }

        match cursor.lparen() {
            Some(cursor) => matches!(
                cursor.keyword(),
                Some(("record", _))
                    | Some(("variant", _))
                    | Some(("list", _))
                    | Some(("tuple", _))
                    | Some(("flags", _))
                    | Some(("enum", _))
                    | Some(("union", _))
                    | Some(("option", _))
                    | Some(("result", _))
            ),
            None => false,
        }
    }

    fn display() -> &'static str {
        "component defined type"
    }
}

/// A record defined type.
#[derive(Debug)]
pub struct Record<'a> {
    /// The fields of the record.
    pub fields: Vec<RecordField<'a>>,
}

impl<'a> Parse<'a> for Record<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::record>()?;
        let mut fields = Vec::new();
        while !parser.is_empty() {
            fields.push(parser.parens(|p| p.parse())?);
        }
        Ok(Self { fields })
    }
}

/// A record type field.
#[derive(Debug)]
pub struct RecordField<'a> {
    /// The name of the field.
    pub name: &'a str,
    /// The type of the field.
    pub ty: ComponentValType<'a>,
}

impl<'a> Parse<'a> for RecordField<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::field>()?;
        Ok(Self {
            name: parser.parse()?,
            ty: parser.parse()?,
        })
    }
}

/// A variant defined type.
#[derive(Debug)]
pub struct Variant<'a> {
    /// The cases of the variant type.
    pub cases: Vec<VariantCase<'a>>,
}

impl<'a> Parse<'a> for Variant<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::variant>()?;
        let mut cases = Vec::new();
        while !parser.is_empty() {
            cases.push(parser.parens(|p| p.parse())?);
        }
        Ok(Self { cases })
    }
}

/// A case of a variant type.
#[derive(Debug)]
pub struct VariantCase<'a> {
    /// Where this `case` was defined
    pub span: Span,
    /// An optional identifier to refer to this case by as part of name
    /// resolution.
    pub id: Option<Id<'a>>,
    /// The name of the case.
    pub name: &'a str,
    /// The optional type of the case.
    pub ty: Option<ComponentValType<'a>>,
    /// The optional refinement.
    pub refines: Option<Refinement<'a>>,
}

impl<'a> Parse<'a> for VariantCase<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let span = parser.parse::<kw::case>()?.0;
        let id = parser.parse()?;
        let name = parser.parse()?;
        let ty = parser.parse()?;
        let refines = if !parser.is_empty() {
            Some(parser.parse()?)
        } else {
            None
        };
        Ok(Self {
            span,
            id,
            name,
            ty,
            refines,
        })
    }
}

/// A refinement for a variant case.
#[derive(Debug)]
pub enum Refinement<'a> {
    /// The refinement is referenced by index.
    Index(Span, Index<'a>),
    /// The refinement has been resolved to an index into
    /// the cases of the variant.
    Resolved(u32),
}

impl<'a> Parse<'a> for Refinement<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parens(|parser| {
            let span = parser.parse::<kw::refines>()?.0;
            let id = parser.parse()?;
            Ok(Self::Index(span, id))
        })
    }
}

/// A list type.
#[derive(Debug)]
pub struct List<'a> {
    /// The element type of the array.
    pub element: Box<ComponentValType<'a>>,
}

impl<'a> Parse<'a> for List<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::list>()?;
        Ok(Self {
            element: Box::new(parser.parse()?),
        })
    }
}

/// A tuple type.
#[derive(Debug)]
pub struct Tuple<'a> {
    /// The types of the fields of the tuple.
    pub fields: Vec<ComponentValType<'a>>,
}

impl<'a> Parse<'a> for Tuple<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::tuple>()?;
        let mut fields = Vec::new();
        while !parser.is_empty() {
            fields.push(parser.parse()?);
        }
        Ok(Self { fields })
    }
}

/// A flags type.
#[derive(Debug)]
pub struct Flags<'a> {
    /// The names of the individual flags.
    pub names: Vec<&'a str>,
}

impl<'a> Parse<'a> for Flags<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::flags>()?;
        let mut names = Vec::new();
        while !parser.is_empty() {
            names.push(parser.parse()?);
        }
        Ok(Self { names })
    }
}

/// An enum type.
#[derive(Debug)]
pub struct Enum<'a> {
    /// The tag names of the enum.
    pub names: Vec<&'a str>,
}

impl<'a> Parse<'a> for Enum<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::enum_>()?;
        let mut names = Vec::new();
        while !parser.is_empty() {
            names.push(parser.parse()?);
        }
        Ok(Self { names })
    }
}

/// A union type.
#[derive(Debug)]
pub struct Union<'a> {
    /// The types of the union.
    pub types: Vec<ComponentValType<'a>>,
}

impl<'a> Parse<'a> for Union<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::union>()?;
        let mut types = Vec::new();
        while !parser.is_empty() {
            types.push(parser.parse()?);
        }
        Ok(Self { types })
    }
}

/// An optional type.
#[derive(Debug)]
pub struct OptionType<'a> {
    /// The type of the value, when a value is present.
    pub element: Box<ComponentValType<'a>>,
}

impl<'a> Parse<'a> for OptionType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::option>()?;
        Ok(Self {
            element: Box::new(parser.parse()?),
        })
    }
}

/// A result type.
#[derive(Debug)]
pub struct ResultType<'a> {
    /// The type on success.
    pub ok: Option<Box<ComponentValType<'a>>>,
    /// The type on failure.
    pub err: Option<Box<ComponentValType<'a>>>,
}

impl<'a> Parse<'a> for ResultType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::result>()?;

        let ok: Option<ComponentValType> = parser.parse()?;
        let err: Option<ComponentValType> = if parser.peek::<LParen>() {
            Some(parser.parens(|parser| {
                parser.parse::<kw::error>()?;
                parser.parse()
            })?)
        } else {
            None
        };

        Ok(Self {
            ok: ok.map(Box::new),
            err: err.map(Box::new),
        })
    }
}

/// A component function type with parameters and result.
#[derive(Debug)]
pub struct ComponentFunctionType<'a> {
    /// The parameters of a function, optionally each having an identifier for
    /// name resolution and a name for the custom `name` section.
    pub params: Box<[ComponentFunctionParam<'a>]>,
    /// The result of a function, optionally each having an identifier for
    /// name resolution and a name for the custom `name` section.
    pub results: Box<[ComponentFunctionResult<'a>]>,
}

impl<'a> Parse<'a> for ComponentFunctionType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let mut params: Vec<ComponentFunctionParam> = Vec::new();
        while parser.peek2::<kw::param>() {
            params.push(parser.parens(|p| p.parse())?);
        }

        let mut results: Vec<ComponentFunctionResult> = Vec::new();
        while parser.peek2::<kw::result>() {
            results.push(parser.parens(|p| p.parse())?);
        }

        Ok(Self {
            params: params.into(),
            results: results.into(),
        })
    }
}

/// A parameter of a [`ComponentFunctionType`].
#[derive(Debug)]
pub struct ComponentFunctionParam<'a> {
    /// The name of the parameter
    pub name: &'a str,
    /// The type of the parameter.
    pub ty: ComponentValType<'a>,
}

impl<'a> Parse<'a> for ComponentFunctionParam<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::param>()?;
        Ok(Self {
            name: parser.parse()?,
            ty: parser.parse()?,
        })
    }
}

/// A result of a [`ComponentFunctionType`].
#[derive(Debug)]
pub struct ComponentFunctionResult<'a> {
    /// An optionally-specified name of this result
    pub name: Option<&'a str>,
    /// The type of the result.
    pub ty: ComponentValType<'a>,
}

impl<'a> Parse<'a> for ComponentFunctionResult<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.parse::<kw::result>()?;
        Ok(Self {
            name: parser.parse()?,
            ty: parser.parse()?,
        })
    }
}

/// The type of an exported item from an component or instance type.
#[derive(Debug)]
pub struct ComponentExportType<'a> {
    /// Where this export was defined.
    pub span: Span,
    /// The name of this export.
    pub name: &'a str,
    /// The signature of the item.
    pub item: ItemSig<'a>,
}

impl<'a> Parse<'a> for ComponentExportType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let span = parser.parse::<kw::export>()?.0;
        let name = parser.parse()?;
        let item = parser.parens(|p| p.parse())?;
        Ok(Self { span, name, item })
    }
}

/// A type definition for a component type.
#[derive(Debug, Default)]
pub struct ComponentType<'a> {
    /// The declarations of the component type.
    pub decls: Vec<ComponentTypeDecl<'a>>,
}

impl<'a> Parse<'a> for ComponentType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.depth_check()?;
        Ok(Self {
            decls: parser.parse()?,
        })
    }
}

/// A declaration of a component type.
#[derive(Debug)]
pub enum ComponentTypeDecl<'a> {
    /// A core type definition local to the component type.
    CoreType(CoreType<'a>),
    /// A type definition local to the component type.
    Type(Type<'a>),
    /// An alias local to the component type.
    Alias(Alias<'a>),
    /// An import of the component type.
    Import(ComponentImport<'a>),
    /// An export of the component type.
    Export(ComponentExportType<'a>),
}

impl<'a> Parse<'a> for ComponentTypeDecl<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let mut l = parser.lookahead1();
        if l.peek::<kw::core>() {
            Ok(Self::CoreType(parser.parse()?))
        } else if l.peek::<kw::r#type>() {
            Ok(Self::Type(parser.parse()?))
        } else if l.peek::<kw::alias>() {
            Ok(Self::Alias(Alias::parse_outer_type_alias(parser, false)?))
        } else if l.peek::<kw::import>() {
            Ok(Self::Import(parser.parse()?))
        } else if l.peek::<kw::export>() {
            Ok(Self::Export(parser.parse()?))
        } else {
            Err(l.error())
        }
    }
}

impl<'a> Parse<'a> for Vec<ComponentTypeDecl<'a>> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let mut decls = Vec::new();
        while !parser.is_empty() {
            decls.push(parser.parens(|parser| parser.parse())?);
        }
        Ok(decls)
    }
}

/// A type definition for an instance type.
#[derive(Debug)]
pub struct InstanceType<'a> {
    /// The declarations of the instance type.
    pub decls: Vec<InstanceTypeDecl<'a>>,
}

impl<'a> Parse<'a> for InstanceType<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        parser.depth_check()?;
        Ok(Self {
            decls: parser.parse()?,
        })
    }
}

/// A declaration of an instance type.
#[derive(Debug)]
pub enum InstanceTypeDecl<'a> {
    /// A core type definition local to the component type.
    CoreType(CoreType<'a>),
    /// A type definition local to the instance type.
    Type(Type<'a>),
    /// An alias local to the instance type.
    Alias(Alias<'a>),
    /// An export of the instance type.
    Export(ComponentExportType<'a>),
}

impl<'a> Parse<'a> for InstanceTypeDecl<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let mut l = parser.lookahead1();
        if l.peek::<kw::core>() {
            Ok(Self::CoreType(parser.parse()?))
        } else if l.peek::<kw::r#type>() {
            Ok(Self::Type(parser.parse()?))
        } else if l.peek::<kw::alias>() {
            Ok(Self::Alias(Alias::parse_outer_type_alias(parser, false)?))
        } else if l.peek::<kw::export>() {
            Ok(Self::Export(parser.parse()?))
        } else {
            Err(l.error())
        }
    }
}

impl<'a> Parse<'a> for Vec<InstanceTypeDecl<'a>> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        let mut decls = Vec::new();
        while !parser.is_empty() {
            decls.push(parser.parens(|parser| parser.parse())?);
        }
        Ok(decls)
    }
}

/// A value type declaration used for values in import signatures.
#[derive(Debug)]
pub struct ComponentValTypeUse<'a>(pub ComponentValType<'a>);

impl<'a> Parse<'a> for ComponentValTypeUse<'a> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        match ComponentTypeUse::<'a, InlineComponentValType<'a>>::parse(parser)? {
            ComponentTypeUse::Ref(i) => Ok(Self(ComponentValType::Ref(i.idx))),
            ComponentTypeUse::Inline(t) => Ok(Self(ComponentValType::Inline(t.0))),
        }
    }
}

/// A reference to a core type defined in this component.
///
/// This is the same as `TypeUse`, but accepts `$T` as shorthand for
/// `(type $T)`.
#[derive(Debug, Clone)]
pub enum CoreTypeUse<'a, T> {
    /// The type that we're referencing.
    Ref(CoreItemRef<'a, kw::r#type>),
    /// The inline type.
    Inline(T),
}

impl<'a, T: Parse<'a>> Parse<'a> for CoreTypeUse<'a, T> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        // Here the core context is assumed, so no core prefix is expected
        if parser.peek::<LParen>() && parser.peek2::<CoreItemRef<'a, kw::r#type>>() {
            Ok(Self::Ref(parser.parens(|parser| parser.parse())?))
        } else {
            Ok(Self::Inline(parser.parse()?))
        }
    }
}

impl<T> Default for CoreTypeUse<'_, T> {
    fn default() -> Self {
        let span = Span::from_offset(0);
        Self::Ref(CoreItemRef {
            idx: Index::Num(0, span),
            kind: kw::r#type(span),
            export_name: None,
        })
    }
}

/// A reference to a type defined in this component.
///
/// This is the same as `TypeUse`, but accepts `$T` as shorthand for
/// `(type $T)`.
#[derive(Debug, Clone)]
pub enum ComponentTypeUse<'a, T> {
    /// The type that we're referencing.
    Ref(ItemRef<'a, kw::r#type>),
    /// The inline type.
    Inline(T),
}

impl<'a, T: Parse<'a>> Parse<'a> for ComponentTypeUse<'a, T> {
    fn parse(parser: Parser<'a>) -> Result<Self> {
        if parser.peek::<LParen>() && parser.peek2::<ItemRef<'a, kw::r#type>>() {
            Ok(Self::Ref(parser.parens(|parser| parser.parse())?))
        } else {
            Ok(Self::Inline(parser.parse()?))
        }
    }
}

impl<T> Default for ComponentTypeUse<'_, T> {
    fn default() -> Self {
        let span = Span::from_offset(0);
        Self::Ref(ItemRef {
            idx: Index::Num(0, span),
            kind: kw::r#type(span),
            export_names: Vec::new(),
        })
    }
}