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
//! V1 AST representation for declarations.

use std::fmt;

use super::Expr;
use crate::support;
use crate::support::child;
use crate::token;
use crate::AstNode;
use crate::AstToken;
use crate::Ident;
use crate::SyntaxKind;
use crate::SyntaxNode;
use crate::WorkflowDescriptionLanguage;

/// Represents a `Map` type.
#[derive(Clone, Debug, Eq)]
pub struct MapType(SyntaxNode);

impl MapType {
    /// Gets the key and value types of the `Map`.
    pub fn types(&self) -> (PrimitiveType, Type) {
        let mut children = self.0.children().filter_map(Type::cast);
        let key = children
            .next()
            .expect("map should have a key type")
            .unwrap_primitive_type();
        let value = children.next().expect("map should have a value type");
        (key, value)
    }

    /// Determines if the type is optional.
    pub fn is_optional(&self) -> bool {
        matches!(
            self.0.last_token().map(|t| t.kind()),
            Some(SyntaxKind::QuestionMark)
        )
    }
}

impl PartialEq for MapType {
    fn eq(&self, other: &Self) -> bool {
        self.is_optional() == other.is_optional() && self.types() == other.types()
    }
}

impl AstNode for MapType {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == SyntaxKind::MapTypeNode
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::MapTypeNode => Some(Self(syntax)),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl fmt::Display for MapType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (key, value) = self.types();
        write!(
            f,
            "Map[{key}, {value}]{o}",
            o = if self.is_optional() { "?" } else { "" }
        )
    }
}

/// Represents an `Array` type.
#[derive(Clone, Debug, Eq)]
pub struct ArrayType(SyntaxNode);

impl ArrayType {
    /// Gets the element type of the array.
    pub fn element_type(&self) -> Type {
        child(&self.0).expect("array should have an element type")
    }

    /// Determines if the type has the "non-empty" qualifier.
    pub fn is_non_empty(&self) -> bool {
        support::token(&self.0, SyntaxKind::Plus).is_some()
    }

    /// Determines if the type is optional.
    pub fn is_optional(&self) -> bool {
        matches!(
            self.0.last_token().map(|t| t.kind()),
            Some(SyntaxKind::QuestionMark)
        )
    }
}

impl PartialEq for ArrayType {
    fn eq(&self, other: &Self) -> bool {
        self.is_optional() == other.is_optional()
            && self.is_non_empty() == other.is_non_empty()
            && self.element_type() == other.element_type()
    }
}

impl AstNode for ArrayType {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == SyntaxKind::ArrayTypeNode
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::ArrayTypeNode => Some(Self(syntax)),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl fmt::Display for ArrayType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Array[{ty}]{p}{o}",
            ty = self.element_type(),
            p = if self.is_non_empty() { "+" } else { "" },
            o = if self.is_optional() { "?" } else { "" }
        )
    }
}

/// Represents a `Pair` type.
#[derive(Clone, Debug, Eq)]
pub struct PairType(SyntaxNode);

impl PairType {
    /// Gets the first and second types of the `Pair`.
    pub fn types(&self) -> (Type, Type) {
        let mut children = self.0.children().filter_map(Type::cast);
        let first = children.next().expect("pair should have a first type");
        let second = children.next().expect("pair should have a second type");
        (first, second)
    }

    /// Determines if the type is optional.
    pub fn is_optional(&self) -> bool {
        matches!(
            self.0.last_token().map(|t| t.kind()),
            Some(SyntaxKind::QuestionMark)
        )
    }
}

impl PartialEq for PairType {
    fn eq(&self, other: &Self) -> bool {
        self.is_optional() == other.is_optional() && self.types() == other.types()
    }
}

impl AstNode for PairType {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == SyntaxKind::PairTypeNode
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::PairTypeNode => Some(Self(syntax)),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl fmt::Display for PairType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (first, second) = self.types();
        write!(
            f,
            "Pair[{first}, {second}]{o}",
            o = if self.is_optional() { "?" } else { "" }
        )
    }
}

/// Represents a `Object` type.
#[derive(Clone, Debug, Eq)]
pub struct ObjectType(SyntaxNode);

impl ObjectType {
    /// Determines if the type is optional.
    pub fn is_optional(&self) -> bool {
        matches!(
            self.0.last_token().map(|t| t.kind()),
            Some(SyntaxKind::QuestionMark)
        )
    }
}

impl PartialEq for ObjectType {
    fn eq(&self, other: &Self) -> bool {
        self.is_optional() == other.is_optional()
    }
}

impl AstNode for ObjectType {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == SyntaxKind::ObjectTypeNode
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::ObjectTypeNode => Some(Self(syntax)),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl fmt::Display for ObjectType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Object{o}",
            o = if self.is_optional() { "?" } else { "" }
        )
    }
}

/// Represents a reference to a type.
#[derive(Clone, Debug, Eq)]
pub struct TypeRef(SyntaxNode);

impl TypeRef {
    /// Gets the name of the type reference.
    pub fn name(&self) -> Ident {
        token(&self.0).expect("type reference should have a name")
    }

    /// Determines if the type is optional.
    pub fn is_optional(&self) -> bool {
        matches!(
            self.0.last_token().map(|t| t.kind()),
            Some(SyntaxKind::QuestionMark)
        )
    }
}

impl PartialEq for TypeRef {
    fn eq(&self, other: &Self) -> bool {
        self.is_optional() == other.is_optional() && self.name().as_str() == other.name().as_str()
    }
}

impl AstNode for TypeRef {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == SyntaxKind::TypeRefNode
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::TypeRefNode => Some(Self(syntax)),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl fmt::Display for TypeRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{n}{o}",
            n = self.name().as_str(),
            o = if self.is_optional() { "?" } else { "" }
        )
    }
}

/// Represents a kind of primitive type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PrimitiveTypeKind {
    /// The primitive is a `Boolean`.
    Boolean,
    /// The primitive is an `Int`.
    Integer,
    /// The primitive is a `Float`.
    Float,
    /// The primitive is a `String`.
    String,
    /// The primitive is a `File`.
    File,
    /// The primitive is a `Directory`
    Directory,
}

/// Represents a primitive type.
#[derive(Clone, Debug, Eq)]
pub struct PrimitiveType(SyntaxNode);

impl PrimitiveType {
    /// Gets the kind of the primitive type.
    pub fn kind(&self) -> PrimitiveTypeKind {
        self.0
            .children_with_tokens()
            .find_map(|t| match t.kind() {
                SyntaxKind::BooleanTypeKeyword => Some(PrimitiveTypeKind::Boolean),
                SyntaxKind::IntTypeKeyword => Some(PrimitiveTypeKind::Integer),
                SyntaxKind::FloatTypeKeyword => Some(PrimitiveTypeKind::Float),
                SyntaxKind::StringTypeKeyword => Some(PrimitiveTypeKind::String),
                SyntaxKind::FileTypeKeyword => Some(PrimitiveTypeKind::File),
                SyntaxKind::DirectoryTypeKeyword => Some(PrimitiveTypeKind::Directory),
                _ => None,
            })
            .expect("type should have a kind")
    }

    /// Determines if the type is optional.
    pub fn is_optional(&self) -> bool {
        matches!(
            self.0.last_token().map(|t| t.kind()),
            Some(SyntaxKind::QuestionMark)
        )
    }
}

impl PartialEq for PrimitiveType {
    fn eq(&self, other: &Self) -> bool {
        self.kind() == other.kind()
    }
}

impl AstNode for PrimitiveType {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == SyntaxKind::PrimitiveTypeNode
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::PrimitiveTypeNode => Some(Self(syntax)),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl fmt::Display for PrimitiveType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind() {
            PrimitiveTypeKind::Boolean => write!(f, "Boolean")?,
            PrimitiveTypeKind::Integer => write!(f, "Int")?,
            PrimitiveTypeKind::Float => write!(f, "Float")?,
            PrimitiveTypeKind::String => write!(f, "String")?,
            PrimitiveTypeKind::File => write!(f, "File")?,
            PrimitiveTypeKind::Directory => write!(f, "Directory")?,
        }

        if self.is_optional() {
            write!(f, "?")
        } else {
            Ok(())
        }
    }
}

/// Represents a type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Type {
    /// The type is a map.
    Map(MapType),
    /// The type is an array.
    Array(ArrayType),
    /// The type is a pair.
    Pair(PairType),
    /// The type is an object.
    Object(ObjectType),
    /// The type is a reference to custom type.
    Ref(TypeRef),
    /// The type is a primitive.
    Primitive(PrimitiveType),
}

impl Type {
    /// Determines if the type is optional.
    pub fn is_optional(&self) -> bool {
        match self {
            Self::Map(m) => m.is_optional(),
            Self::Array(a) => a.is_optional(),
            Self::Pair(p) => p.is_optional(),
            Self::Object(o) => o.is_optional(),
            Self::Ref(r) => r.is_optional(),
            Self::Primitive(p) => p.is_optional(),
        }
    }

    /// Unwraps the type into a map type.
    ///
    /// # Panics
    ///
    /// Panics if the type is not a map type.
    pub fn unwrap_map_type(self) -> MapType {
        match self {
            Self::Map(ty) => ty,
            _ => panic!("not a map type"),
        }
    }

    /// Unwraps the type into an array type.
    ///
    /// # Panics
    ///
    /// Panics if the type is not an array type.
    pub fn unwrap_array_type(self) -> ArrayType {
        match self {
            Self::Array(ty) => ty,
            _ => panic!("not an array type"),
        }
    }

    /// Unwraps the type into a pair type.
    ///
    /// # Panics
    ///
    /// Panics if the type is not a pair type.
    pub fn unwrap_pair_type(self) -> PairType {
        match self {
            Self::Pair(ty) => ty,
            _ => panic!("not a pair type"),
        }
    }

    /// Unwraps the type into an object type.
    ///
    /// # Panics
    ///
    /// Panics if the type is not an object type.
    pub fn unwrap_object_type(self) -> ObjectType {
        match self {
            Self::Object(ty) => ty,
            _ => panic!("not an object type"),
        }
    }

    /// Unwraps the type into a type reference.
    ///
    /// # Panics
    ///
    /// Panics if the type is not a type reference.
    pub fn unwrap_type_ref(self) -> TypeRef {
        match self {
            Self::Ref(r) => r,
            _ => panic!("not a type reference"),
        }
    }

    /// Unwraps the type into a primitive type.
    ///
    /// # Panics
    ///
    /// Panics if the type is not a primitive type.
    pub fn unwrap_primitive_type(self) -> PrimitiveType {
        match self {
            Self::Primitive(ty) => ty,
            _ => panic!("not a primitive type"),
        }
    }
}

impl AstNode for Type {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        matches!(
            kind,
            SyntaxKind::MapTypeNode
                | SyntaxKind::ArrayTypeNode
                | SyntaxKind::PairTypeNode
                | SyntaxKind::ObjectTypeNode
                | SyntaxKind::TypeRefNode
                | SyntaxKind::PrimitiveTypeNode
        )
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::MapTypeNode => Some(Self::Map(MapType(syntax))),
            SyntaxKind::ArrayTypeNode => Some(Self::Array(ArrayType(syntax))),
            SyntaxKind::PairTypeNode => Some(Self::Pair(PairType(syntax))),
            SyntaxKind::ObjectTypeNode => Some(Self::Object(ObjectType(syntax))),
            SyntaxKind::TypeRefNode => Some(Self::Ref(TypeRef(syntax))),
            SyntaxKind::PrimitiveTypeNode => Some(Self::Primitive(PrimitiveType(syntax))),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        match self {
            Type::Map(m) => &m.0,
            Type::Array(a) => &a.0,
            Type::Pair(p) => &p.0,
            Type::Object(o) => &o.0,
            Type::Ref(r) => &r.0,
            Type::Primitive(t) => &t.0,
        }
    }
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Type::Map(m) => m.fmt(f),
            Type::Array(a) => a.fmt(f),
            Type::Pair(p) => p.fmt(f),
            Type::Object(o) => o.fmt(f),
            Type::Ref(r) => r.fmt(f),
            Type::Primitive(p) => p.fmt(f),
        }
    }
}

/// Represents an unbound declaration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnboundDecl(pub(crate) SyntaxNode);

impl UnboundDecl {
    /// Gets the type of the declaration.
    pub fn ty(&self) -> Type {
        child(&self.0).expect("unbound declaration should have a type")
    }

    /// Gets the name of the declaration.
    pub fn name(&self) -> Ident {
        token(&self.0).expect("unbound declaration should have a name")
    }
}

impl AstNode for UnboundDecl {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == SyntaxKind::UnboundDeclNode
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::UnboundDeclNode => Some(Self(syntax)),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

/// Represents a bound declaration in a task or workflow definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BoundDecl(pub(crate) SyntaxNode);

impl BoundDecl {
    /// Gets the type of the declaration.
    pub fn ty(&self) -> Type {
        child(&self.0).expect("bound declaration should have a type")
    }

    /// Gets the name of the declaration.
    pub fn name(&self) -> Ident {
        token(&self.0).expect("bound declaration should have a name")
    }

    /// Gets the expression the declaration is bound to.
    pub fn expr(&self) -> Expr {
        child(&self.0).expect("bound declaration should have an expression")
    }
}

impl AstNode for BoundDecl {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == SyntaxKind::BoundDeclNode
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::BoundDeclNode => Some(Self(syntax)),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

/// Represents a declaration in an input section.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Decl {
    /// The declaration is bound.
    Bound(BoundDecl),
    /// The declaration is unbound.
    Unbound(UnboundDecl),
}

impl Decl {
    /// Gets the type of the declaration.
    pub fn ty(&self) -> Type {
        match self {
            Self::Bound(d) => d.ty(),
            Self::Unbound(d) => d.ty(),
        }
    }

    /// Gets the name of the declaration.
    pub fn name(&self) -> Ident {
        match self {
            Self::Bound(d) => d.name(),
            Self::Unbound(d) => d.name(),
        }
    }

    /// Gets the expression of the declaration.
    ///
    /// Returns `None` for unbound declarations.
    pub fn expr(&self) -> Option<Expr> {
        match self {
            Self::Bound(d) => Some(d.expr()),
            Self::Unbound(_) => None,
        }
    }

    /// Unwraps the declaration into a bound declaration.
    ///
    /// # Panics
    ///
    /// Panics if the declaration is not a bound declaration.
    pub fn unwrap_bound_decl(self) -> BoundDecl {
        match self {
            Self::Bound(decl) => decl,
            _ => panic!("not a bound declaration"),
        }
    }

    /// Unwraps the declaration into an unbound declaration.
    ///
    /// # Panics
    ///
    /// Panics if the declaration is not an unbound declaration.
    pub fn unwrap_unbound_decl(self) -> UnboundDecl {
        match self {
            Self::Unbound(decl) => decl,
            _ => panic!("not an unbound declaration"),
        }
    }
}

impl AstNode for Decl {
    type Language = WorkflowDescriptionLanguage;

    fn can_cast(kind: SyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == SyntaxKind::BoundDeclNode || kind == SyntaxKind::UnboundDeclNode
    }

    fn cast(syntax: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        match syntax.kind() {
            SyntaxKind::BoundDeclNode => Some(Self::Bound(BoundDecl(syntax))),
            SyntaxKind::UnboundDeclNode => Some(Self::Unbound(UnboundDecl(syntax))),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        match self {
            Self::Bound(b) => &b.0,
            Self::Unbound(u) => &u.0,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::Document;
    use crate::SupportedVersion;
    use crate::VisitReason;
    use crate::Visitor;

    #[test]
    fn decls() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.1

task test {
    input {
        Boolean a
        Int b = 42
        Float? c = None
        String d
        File e = "foo.wdl"
        Map[Int, Int] f
        Array[String] g = []
        Pair[Boolean, Int] h
        Object i = object {}
        MyStruct j
        Directory k = "foo"
    }
}
"#,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].name().as_str(), "test");

        // Inputs
        let input = tasks[0].input().expect("task should have an input section");
        let decls: Vec<_> = input.declarations().collect();
        assert_eq!(decls.len(), 11);

        // First input declaration
        let decl = decls[0].clone().unwrap_unbound_decl();
        assert_eq!(decl.ty().to_string(), "Boolean");
        assert_eq!(decl.name().as_str(), "a");

        // Second input declaration
        let decl = decls[1].clone().unwrap_bound_decl();
        assert_eq!(decl.ty().to_string(), "Int");
        assert_eq!(decl.name().as_str(), "b");
        assert_eq!(
            decl.expr()
                .unwrap_literal()
                .unwrap_integer()
                .value()
                .unwrap(),
            42
        );

        // Third input declaration
        let decl = decls[2].clone().unwrap_bound_decl();
        assert_eq!(decl.ty().to_string(), "Float?");
        assert_eq!(decl.name().as_str(), "c");
        decl.expr().unwrap_literal().unwrap_none();

        // Fourth input declaration
        let decl = decls[3].clone().unwrap_unbound_decl();
        assert_eq!(decl.ty().to_string(), "String");
        assert_eq!(decl.name().as_str(), "d");

        // Fifth input declaration
        let decl = decls[4].clone().unwrap_bound_decl();
        assert_eq!(decl.ty().to_string(), "File");
        assert_eq!(decl.name().as_str(), "e");
        assert_eq!(
            decl.expr()
                .unwrap_literal()
                .unwrap_string()
                .text()
                .unwrap()
                .as_str(),
            "foo.wdl"
        );

        // Sixth input declaration
        let decl = decls[5].clone().unwrap_unbound_decl();
        assert_eq!(decl.ty().to_string(), "Map[Int, Int]");
        assert_eq!(decl.name().as_str(), "f");

        // Seventh input declaration
        let decl = decls[6].clone().unwrap_bound_decl();
        assert_eq!(decl.ty().to_string(), "Array[String]");
        assert_eq!(decl.name().as_str(), "g");
        assert_eq!(
            decl.expr()
                .unwrap_literal()
                .unwrap_array()
                .elements()
                .count(),
            0
        );

        // Eighth input declaration
        let decl = decls[7].clone().unwrap_unbound_decl();
        assert_eq!(decl.ty().to_string(), "Pair[Boolean, Int]");
        assert_eq!(decl.name().as_str(), "h");

        // Ninth input declaration
        let decl = decls[8].clone().unwrap_bound_decl();
        assert_eq!(decl.ty().to_string(), "Object");
        assert_eq!(decl.name().as_str(), "i");
        assert_eq!(
            decl.expr().unwrap_literal().unwrap_object().items().count(),
            0
        );

        // Tenth input declaration
        let decl = decls[9].clone().unwrap_unbound_decl();
        assert_eq!(decl.ty().to_string(), "MyStruct");
        assert_eq!(decl.name().as_str(), "j");

        // Eleventh input declaration
        let decl = decls[10].clone().unwrap_bound_decl();
        assert_eq!(decl.ty().to_string(), "Directory");
        assert_eq!(decl.name().as_str(), "k");
        assert_eq!(
            decl.expr()
                .unwrap_literal()
                .unwrap_string()
                .text()
                .unwrap()
                .as_str(),
            "foo"
        );

        // Use a visitor to count the number of declarations
        #[derive(Default)]
        struct MyVisitor {
            bound: usize,
            unbound: usize,
        }

        impl Visitor for MyVisitor {
            type State = ();

            fn document(
                &mut self,
                _: &mut Self::State,
                _: VisitReason,
                _: &Document,
                _: SupportedVersion,
            ) {
            }

            fn bound_decl(&mut self, _: &mut Self::State, reason: VisitReason, _: &BoundDecl) {
                if reason == VisitReason::Enter {
                    self.bound += 1;
                }
            }

            fn unbound_decl(&mut self, _: &mut Self::State, reason: VisitReason, _: &UnboundDecl) {
                if reason == VisitReason::Enter {
                    self.unbound += 1;
                }
            }
        }

        let mut visitor = MyVisitor::default();
        document.visit(&mut (), &mut visitor);
        assert_eq!(visitor.bound, 6);
        assert_eq!(visitor.unbound, 5);
    }
}