bhc-ast 0.2.2

Abstract syntax tree definitions for BHC
Documentation
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
//! Abstract syntax tree definitions for BHC.
//!
//! This crate defines the AST produced by parsing Haskell 2026 source code.
//! The AST preserves source locations and syntactic structure.

#![warn(missing_docs)]

use bhc_index::define_index;
use bhc_intern::{Ident, Symbol};
use bhc_span::Span;

define_index! {
    /// Index into the expression arena.
    pub struct ExprId;

    /// Index into the pattern arena.
    pub struct PatId;

    /// Index into the type arena.
    pub struct TypeId;

    /// Index into the declaration arena.
    pub struct DeclId;
}

// ============================================================
// Documentation Comments
// ============================================================

/// The kind of documentation comment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DocKind {
    /// Preceding documentation: `-- |` or `{- | -}`
    /// Documents the following item.
    Preceding,
    /// Trailing documentation: `-- ^` or `{- ^ -}`
    /// Documents the preceding item.
    Trailing,
}

/// A Haddock-style documentation comment.
#[derive(Clone, Debug)]
pub struct DocComment {
    /// The raw text content of the documentation.
    pub text: String,
    /// The kind of documentation (preceding or trailing).
    pub kind: DocKind,
    /// The span of the comment in source.
    pub span: Span,
}

impl DocComment {
    /// Create a new preceding documentation comment.
    #[must_use]
    pub fn preceding(text: String, span: Span) -> Self {
        Self {
            text,
            kind: DocKind::Preceding,
            span,
        }
    }

    /// Create a new trailing documentation comment.
    #[must_use]
    pub fn trailing(text: String, span: Span) -> Self {
        Self {
            text,
            kind: DocKind::Trailing,
            span,
        }
    }
}

/// A Haskell module.
#[derive(Clone, Debug)]
pub struct Module {
    /// Module documentation comment.
    pub doc: Option<DocComment>,
    /// Module pragmas (LANGUAGE, OPTIONS_GHC, etc.).
    pub pragmas: Vec<Pragma>,
    /// Module name.
    pub name: Option<ModuleName>,
    /// Export list.
    pub exports: Option<Vec<Export>>,
    /// Import declarations.
    pub imports: Vec<ImportDecl>,
    /// Top-level declarations.
    pub decls: Vec<Decl>,
    /// Span of the entire module.
    pub span: Span,
}

// ============================================================
// Pragmas
// ============================================================

/// A pragma in the source code.
#[derive(Clone, Debug)]
pub struct Pragma {
    /// The kind of pragma.
    pub kind: PragmaKind,
    /// The span.
    pub span: Span,
}

/// The kind of pragma.
#[derive(Clone, Debug)]
pub enum PragmaKind {
    /// Language extension: `{-# LANGUAGE GADTs #-}`
    Language(Vec<Symbol>),
    /// GHC options: `{-# OPTIONS_GHC -Wall #-}`
    OptionsGhc(String),
    /// Inline pragma: `{-# INLINE foo #-}`
    Inline(Ident),
    /// No-inline pragma: `{-# NOINLINE foo #-}`
    NoInline(Ident),
    /// Inlinable pragma: `{-# INLINABLE foo #-}`
    Inlinable(Ident),
    /// Specialize pragma: `{-# SPECIALIZE foo :: Int -> Int #-}`
    Specialize(Ident, Type),
    /// Unpack pragma: `{-# UNPACK #-}`
    Unpack,
    /// No-unpack pragma: `{-# NOUNPACK #-}`
    NoUnpack,
    /// Source pragma (for generated code): `{-# SOURCE #-}`
    Source,
    /// Complete pragma: `{-# COMPLETE Pat1, Pat2 #-}`
    Complete(Vec<Ident>),
    /// Minimal pragma: `{-# MINIMAL foo | bar #-}`
    Minimal(String),
    /// Deprecated pragma: `{-# DEPRECATED foo "message" #-}`
    Deprecated(Option<Vec<Ident>>, String),
    /// Warning pragma: `{-# WARNING foo "message" #-}`
    Warning(Option<Vec<Ident>>, String),
    /// Unknown/unsupported pragma (preserved for compatibility)
    Other(String),
}

/// Known language extensions.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Extension {
    // Type system
    /// GADTs
    GADTs,
    /// Type families
    TypeFamilies,
    /// Data kinds
    DataKinds,
    /// Kind signatures
    KindSignatures,
    /// Rank-N types
    RankNTypes,
    /// Existential quantification
    ExistentialQuantification,
    /// Scoped type variables
    ScopedTypeVariables,
    /// Type applications
    TypeApplications,
    /// Flexible instances
    FlexibleInstances,
    /// Flexible contexts
    FlexibleContexts,
    /// Multi-param type classes
    MultiParamTypeClasses,
    /// Functional dependencies
    FunctionalDependencies,
    /// Undecidable instances
    UndecidableInstances,
    /// Overlapping instances
    OverlappingInstances,
    /// Constraint kinds
    ConstraintKinds,

    // Syntax
    /// Lambda case
    LambdaCase,
    /// Multi-way if
    MultiWayIf,
    /// Block arguments
    BlockArguments,
    /// Pattern guards
    PatternGuards,
    /// View patterns
    ViewPatterns,
    /// Pattern synonyms
    PatternSynonyms,
    /// Record wild cards
    RecordWildCards,
    /// Named field puns
    NamedFieldPuns,
    /// Overloaded strings
    OverloadedStrings,
    /// Overloaded lists
    OverloadedLists,
    /// Numeric underscores
    NumericUnderscores,
    /// Hex float literals
    HexFloatLiterals,
    /// Binary literals
    BinaryLiterals,
    /// Negative literals
    NegativeLiterals,

    // Strictness
    /// Bang patterns
    BangPatterns,
    /// Strict data
    StrictData,
    /// Strict
    Strict,

    // Deriving
    /// Derive functor
    DeriveFunctor,
    /// Derive foldable
    DeriveFoldable,
    /// Derive traversable
    DeriveTraversable,
    /// Derive generic
    DeriveGeneric,
    /// Derive data typeable
    DeriveDataTypeable,
    /// Derive lift
    DeriveLift,
    /// Deriving via
    DerivingVia,
    /// Deriving strategies
    DerivingStrategies,
    /// Generalized newtype deriving
    GeneralizedNewtypeDeriving,
    /// Standalone deriving
    StandaloneDeriving,

    // FFI
    /// Foreign function interface
    ForeignFunctionInterface,
    /// C API FFI
    CApiFFI,
    /// Unsafe FFI
    UnliftedFFITypes,

    // Other
    /// Template Haskell
    TemplateHaskell,
    /// Template Haskell quotes
    TemplateHaskellQuotes,
    /// Quasi quotes
    QuasiQuotes,
    /// Type operators
    TypeOperators,
    /// Explicit forall
    ExplicitForAll,
    /// Explicit namespaces
    ExplicitNamespaces,
    /// Empty data declarations
    EmptyDataDecls,
    /// Empty case
    EmptyCase,
    /// Instance sigs
    InstanceSigs,
    /// Default signatures
    DefaultSignatures,
    /// Named defaults
    NamedDefaults,

    /// Unknown extension (preserved)
    Unknown(Symbol),
}

impl Extension {
    /// Parse an extension name.
    #[must_use]
    pub fn from_name(name: &str) -> Self {
        match name {
            // Type system
            "GADTs" => Self::GADTs,
            "TypeFamilies" => Self::TypeFamilies,
            "DataKinds" => Self::DataKinds,
            "KindSignatures" => Self::KindSignatures,
            "RankNTypes" | "Rank2Types" | "PolymorphicComponents" => Self::RankNTypes,
            "ExistentialQuantification" => Self::ExistentialQuantification,
            "ScopedTypeVariables" => Self::ScopedTypeVariables,
            "TypeApplications" => Self::TypeApplications,
            "FlexibleInstances" => Self::FlexibleInstances,
            "FlexibleContexts" => Self::FlexibleContexts,
            "MultiParamTypeClasses" => Self::MultiParamTypeClasses,
            "FunctionalDependencies" => Self::FunctionalDependencies,
            "UndecidableInstances" => Self::UndecidableInstances,
            "OverlappingInstances" | "IncoherentInstances" => Self::OverlappingInstances,
            "ConstraintKinds" => Self::ConstraintKinds,

            // Syntax
            "LambdaCase" => Self::LambdaCase,
            "MultiWayIf" => Self::MultiWayIf,
            "BlockArguments" => Self::BlockArguments,
            "PatternGuards" => Self::PatternGuards,
            "ViewPatterns" => Self::ViewPatterns,
            "PatternSynonyms" => Self::PatternSynonyms,
            "RecordWildCards" => Self::RecordWildCards,
            "NamedFieldPuns" => Self::NamedFieldPuns,
            "OverloadedStrings" => Self::OverloadedStrings,
            "OverloadedLists" => Self::OverloadedLists,
            "NumericUnderscores" => Self::NumericUnderscores,
            "HexFloatLiterals" => Self::HexFloatLiterals,
            "BinaryLiterals" => Self::BinaryLiterals,
            "NegativeLiterals" => Self::NegativeLiterals,

            // Strictness
            "BangPatterns" => Self::BangPatterns,
            "StrictData" => Self::StrictData,
            "Strict" => Self::Strict,

            // Deriving
            "DeriveFunctor" => Self::DeriveFunctor,
            "DeriveFoldable" => Self::DeriveFoldable,
            "DeriveTraversable" => Self::DeriveTraversable,
            "DeriveGeneric" => Self::DeriveGeneric,
            "DeriveDataTypeable" => Self::DeriveDataTypeable,
            "DeriveLift" => Self::DeriveLift,
            "DerivingVia" => Self::DerivingVia,
            "DerivingStrategies" => Self::DerivingStrategies,
            "GeneralizedNewtypeDeriving" | "GeneralisedNewtypeDeriving" => {
                Self::GeneralizedNewtypeDeriving
            }
            "StandaloneDeriving" => Self::StandaloneDeriving,

            // FFI
            "ForeignFunctionInterface" | "FFI" => Self::ForeignFunctionInterface,
            "CApiFFI" => Self::CApiFFI,
            "UnliftedFFITypes" => Self::UnliftedFFITypes,

            // Other
            "TemplateHaskell" => Self::TemplateHaskell,
            "TemplateHaskellQuotes" => Self::TemplateHaskellQuotes,
            "QuasiQuotes" => Self::QuasiQuotes,
            "TypeOperators" => Self::TypeOperators,
            "ExplicitForAll" => Self::ExplicitForAll,
            "ExplicitNamespaces" => Self::ExplicitNamespaces,
            "EmptyDataDecls" => Self::EmptyDataDecls,
            "EmptyCase" => Self::EmptyCase,
            "InstanceSigs" => Self::InstanceSigs,
            "DefaultSignatures" => Self::DefaultSignatures,
            "NamedDefaults" => Self::NamedDefaults,

            _ => Self::Unknown(Symbol::intern(name)),
        }
    }
}

/// A qualified module name like `Data.List`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ModuleName {
    /// The components of the name.
    pub parts: Vec<Symbol>,
    /// The span.
    pub span: Span,
}

impl ModuleName {
    /// Get the fully qualified name as a string.
    #[must_use]
    pub fn to_string(&self) -> String {
        self.parts
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(".")
    }
}

/// An export specification.
#[derive(Clone, Debug)]
pub enum Export {
    /// Export a value: `foo`
    Var(Ident, Span),
    /// Export a type with optional constructors: `Foo(..)` or `Foo(A, B)`
    Type(Ident, Option<Vec<Ident>>, Span),
    /// Export a module: `module Data.List`
    Module(ModuleName, Span),
}

/// An import declaration.
#[derive(Clone, Debug)]
pub struct ImportDecl {
    /// The module being imported.
    pub module: ModuleName,
    /// Whether this is a qualified import.
    pub qualified: bool,
    /// The alias for qualified imports.
    pub alias: Option<ModuleName>,
    /// The import specification (hiding or explicit).
    pub spec: Option<ImportSpec>,
    /// The span.
    pub span: Span,
}

/// Import specification.
#[derive(Clone, Debug)]
pub enum ImportSpec {
    /// Import only the listed items.
    Only(Vec<Import>),
    /// Import everything except the listed items.
    Hiding(Vec<Import>),
}

/// A single import item.
#[derive(Clone, Debug)]
pub enum Import {
    /// Import a value.
    Var(Ident, Span),
    /// Import a type with optional constructors.
    Type(Ident, Option<Vec<Ident>>, Span),
}

/// A top-level declaration.
#[derive(Clone, Debug)]
pub enum Decl {
    /// Type signature: `foo :: Int -> Int`
    TypeSig(TypeSig),
    /// Function/value binding: `foo x = x + 1`
    FunBind(FunBind),
    /// Data type: `data Foo = A | B Int`
    DataDecl(DataDecl),
    /// Type alias: `type Foo = Bar`
    TypeAlias(TypeAlias),
    /// Newtype: `newtype Foo = Foo Bar`
    Newtype(NewtypeDecl),
    /// Class definition: `class Eq a where ...`
    ClassDecl(ClassDecl),
    /// Instance definition: `instance Eq Int where ...`
    InstanceDecl(InstanceDecl),
    /// Foreign import/export
    Foreign(ForeignDecl),
    /// Fixity declaration: `infixl 6 +`
    Fixity(FixityDecl),
    /// Pragma declaration: `{-# MINIMAL ... #-}`
    PragmaDecl(Pragma),
    /// Standalone deriving: `deriving instance Show Foo`
    StandaloneDeriving(StandaloneDeriving),
    /// Pattern synonym: `pattern Zero = Lit 0`
    PatternSynonym(PatternSynonymDecl),
}

/// A standalone deriving declaration: `deriving instance Show Foo`
#[derive(Clone, Debug)]
pub struct StandaloneDeriving {
    /// The class to derive (e.g., Show, Eq).
    pub class: Ident,
    /// The type to derive for (e.g., Foo).
    pub ty: Type,
    /// Source span.
    pub span: Span,
}

/// A pattern synonym declaration: `pattern Zero = Lit 0`
#[derive(Clone, Debug)]
pub struct PatternSynonymDecl {
    /// The pattern synonym name (e.g., Zero).
    pub name: Ident,
    /// Pattern variables.
    pub args: Vec<Ident>,
    /// Direction: bidirectional (`=`) or unidirectional (`<-`).
    pub direction: PatSynDir,
    /// The RHS pattern.
    pub pattern: Pat,
    /// Source span.
    pub span: Span,
}

/// Direction of a pattern synonym.
#[derive(Clone, Debug)]
pub enum PatSynDir {
    /// `pattern Foo x = Con x 0` — usable in both patterns and expressions.
    Bidirectional,
    /// `pattern Foo x <- Con x _` — usable only in patterns.
    Unidirectional,
}

/// A type signature.
#[derive(Clone, Debug)]
pub struct TypeSig {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// The names being typed.
    pub names: Vec<Ident>,
    /// The type.
    pub ty: Type,
    /// The span.
    pub span: Span,
}

/// A function binding.
#[derive(Clone, Debug)]
pub struct FunBind {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// The function name.
    pub name: Ident,
    /// The clauses (pattern matches).
    pub clauses: Vec<Clause>,
    /// The span.
    pub span: Span,
}

/// A clause in a function binding.
#[derive(Clone, Debug)]
pub struct Clause {
    /// The patterns for arguments.
    pub pats: Vec<Pat>,
    /// The right-hand side.
    pub rhs: Rhs,
    /// Local bindings.
    pub wheres: Vec<Decl>,
    /// The span.
    pub span: Span,
}

/// The right-hand side of a binding.
#[derive(Clone, Debug)]
pub enum Rhs {
    /// Simple: `= expr`
    Simple(Expr, Span),
    /// Guarded: `| guard = expr`
    Guarded(Vec<GuardedRhs>, Span),
}

/// A guarded right-hand side.
#[derive(Clone, Debug)]
pub struct GuardedRhs {
    /// The guards (can be multiple, e.g., `| pat <- expr, cond`).
    pub guards: Vec<Guard>,
    /// The body expression.
    pub body: Expr,
    /// The span.
    pub span: Span,
}

/// A guard in a guarded RHS.
#[derive(Clone, Debug)]
pub enum Guard {
    /// A pattern guard: `pat <- expr`
    Pattern(Pat, Expr, Span),
    /// A boolean guard: `expr`
    Expr(Expr, Span),
}

impl Guard {
    /// Get the span of this guard.
    #[must_use]
    pub fn span(&self) -> Span {
        match self {
            Self::Pattern(_, _, s) | Self::Expr(_, s) => *s,
        }
    }
}

/// A data type declaration.
#[derive(Clone, Debug)]
pub struct DataDecl {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// The type name.
    pub name: Ident,
    /// Type parameters.
    pub params: Vec<TyVar>,
    /// Constructors (H98 syntax).
    pub constrs: Vec<ConDecl>,
    /// GADT constructors (where syntax).
    pub gadt_constrs: Vec<GadtConDecl>,
    /// Deriving clause.
    pub deriving: Vec<Ident>,
    /// The span.
    pub span: Span,
}

/// A GADT constructor declaration: `ConName :: Type`.
#[derive(Clone, Debug)]
pub struct GadtConDecl {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// Constructor name.
    pub name: Ident,
    /// The full constructor type, e.g. `Int -> Expr Int`.
    pub ty: Type,
    /// The span.
    pub span: Span,
}

/// A data constructor declaration.
#[derive(Clone, Debug)]
pub struct ConDecl {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// Constructor name.
    pub name: Ident,
    /// Constructor fields.
    pub fields: ConFields,
    /// The span.
    pub span: Span,
}

/// Constructor fields.
#[derive(Clone, Debug)]
pub enum ConFields {
    /// Positional: `Foo Int String`
    Positional(Vec<Type>),
    /// Record: `Foo { bar :: Int, baz :: String }`
    Record(Vec<FieldDecl>),
}

/// A record field declaration.
#[derive(Clone, Debug)]
pub struct FieldDecl {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// Field name.
    pub name: Ident,
    /// Field type.
    pub ty: Type,
    /// The span.
    pub span: Span,
}

/// A type alias declaration.
#[derive(Clone, Debug)]
pub struct TypeAlias {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// The alias name.
    pub name: Ident,
    /// Type parameters.
    pub params: Vec<TyVar>,
    /// The aliased type.
    pub ty: Type,
    /// The span.
    pub span: Span,
}

/// A newtype declaration.
#[derive(Clone, Debug)]
pub struct NewtypeDecl {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// The type name.
    pub name: Ident,
    /// Type parameters.
    pub params: Vec<TyVar>,
    /// The constructor.
    pub constr: ConDecl,
    /// Deriving clause.
    pub deriving: Vec<Ident>,
    /// The span.
    pub span: Span,
}

/// A type class declaration.
#[derive(Clone, Debug)]
pub struct ClassDecl {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// Superclass constraints.
    pub context: Vec<Constraint>,
    /// Class name.
    pub name: Ident,
    /// Type parameters (multi-param type classes).
    pub params: Vec<TyVar>,
    /// Functional dependencies.
    pub fundeps: Vec<FunDep>,
    /// Associated type declarations.
    pub assoc_types: Vec<AssocType>,
    /// Method signatures and default implementations.
    pub methods: Vec<Decl>,
    /// The span.
    pub span: Span,
}

/// An associated type declaration within a type class.
///
/// Example: `type Elem c` in `class Collection c where type Elem c`
#[derive(Clone, Debug)]
pub struct AssocType {
    /// The name of the associated type.
    pub name: Ident,
    /// Type parameters (in addition to class params).
    pub params: Vec<TyVar>,
    /// Optional kind signature.
    pub kind: Option<Kind>,
    /// Optional default type.
    pub default: Option<Type>,
    /// The span.
    pub span: Span,
}

/// A kind (for kind signatures).
#[derive(Clone, Debug)]
pub enum Kind {
    /// The kind of types: `*` or `Type`.
    Star,
    /// Function kind: `k1 -> k2`.
    Arrow(Box<Kind>, Box<Kind>),
    /// Named kind variable.
    Var(Ident),
}

/// A functional dependency in a type class.
#[derive(Clone, Debug)]
pub struct FunDep {
    /// Variables that determine others.
    pub from: Vec<Ident>,
    /// Variables that are determined.
    pub to: Vec<Ident>,
    /// The span.
    pub span: Span,
}

/// An instance declaration.
#[derive(Clone, Debug)]
pub struct InstanceDecl {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// Instance constraints.
    pub context: Vec<Constraint>,
    /// Class name.
    pub class: Ident,
    /// Instance type.
    pub ty: Type,
    /// Associated type definitions.
    pub assoc_type_defs: Vec<AssocTypeDef>,
    /// Method implementations.
    pub methods: Vec<Decl>,
    /// The span.
    pub span: Span,
}

/// An associated type definition within an instance.
///
/// Example: `type Elem [a] = a` in `instance Collection [a] where type Elem [a] = a`
#[derive(Clone, Debug)]
pub struct AssocTypeDef {
    /// The name of the associated type.
    pub name: Ident,
    /// Type arguments (patterns for the associated type).
    pub args: Vec<Type>,
    /// The definition (right-hand side).
    pub rhs: Type,
    /// The span.
    pub span: Span,
}

/// A foreign declaration.
#[derive(Clone, Debug)]
pub struct ForeignDecl {
    /// Documentation comment.
    pub doc: Option<DocComment>,
    /// Import or export.
    pub kind: ForeignKind,
    /// Calling convention.
    pub convention: Symbol,
    /// External name.
    pub external_name: Option<String>,
    /// Haskell name.
    pub name: Ident,
    /// Type signature.
    pub ty: Type,
    /// The span.
    pub span: Span,
}

/// Foreign declaration kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ForeignKind {
    /// Foreign import.
    Import,
    /// Foreign export.
    Export,
}

/// A fixity declaration.
#[derive(Clone, Debug)]
pub struct FixityDecl {
    /// The fixity.
    pub fixity: Fixity,
    /// Precedence level (0-9).
    pub prec: u8,
    /// The operators.
    pub ops: Vec<Ident>,
    /// The span.
    pub span: Span,
}

/// Operator fixity.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Fixity {
    /// Left associative.
    Left,
    /// Right associative.
    Right,
    /// Non-associative.
    None,
}

/// An expression.
#[derive(Clone, Debug)]
pub enum Expr {
    /// Variable: `x`
    Var(Ident, Span),
    /// Qualified variable: `M.foo`, `Data.List.sort`
    QualVar(ModuleName, Ident, Span),
    /// Constructor: `Just`
    Con(Ident, Span),
    /// Qualified constructor: `M.Just`, `Data.Maybe.Nothing`
    QualCon(ModuleName, Ident, Span),
    /// Literal: `42`, `"hello"`
    Lit(Lit, Span),
    /// Application: `f x`
    App(Box<Expr>, Box<Expr>, Span),
    /// Lambda: `\x -> x`
    Lam(Vec<Pat>, Box<Expr>, Span),
    /// Let: `let x = 1 in x`
    Let(Vec<Decl>, Box<Expr>, Span),
    /// If: `if c then t else e`
    If(Box<Expr>, Box<Expr>, Box<Expr>, Span),
    /// Case: `case x of { ... }`
    Case(Box<Expr>, Vec<Alt>, Span),
    /// Do block: `do { ... }`
    Do(Vec<Stmt>, Span),
    /// Tuple: `(a, b, c)`
    Tuple(Vec<Expr>, Span),
    /// List: `[1, 2, 3]`
    List(Vec<Expr>, Span),
    /// Arithmetic sequence: `[1..10]`, `[1,3..10]`
    ArithSeq(ArithSeq, Span),
    /// List comprehension: `[x | x <- xs, x > 0]`
    ListComp(Box<Expr>, Vec<Stmt>, Span),
    /// Record construction: `Foo { bar = 1 }` or `Foo { bar = 1, .. }` (RecordWildCards)
    RecordCon(Ident, Vec<FieldBind>, bool, Span),
    /// Record update: `foo { bar = 1 }`
    RecordUpd(Box<Expr>, Vec<FieldBind>, Span),
    /// Infix operator: `a + b`
    Infix(Box<Expr>, Ident, Box<Expr>, Span),
    /// Negation: `-x`
    Neg(Box<Expr>, Span),
    /// Parenthesized expression
    Paren(Box<Expr>, Span),
    /// Type annotation: `x :: Int`
    Ann(Box<Expr>, Type, Span),
    /// Lazy block (H26): `lazy { ... }`
    Lazy(Box<Expr>, Span),
    /// Wildcard/hole: `_` (used in patterns parsed as expressions)
    Wildcard(Span),
}

impl Expr {
    /// Get the span of this expression.
    #[must_use]
    pub fn span(&self) -> Span {
        match self {
            Self::Var(_, s)
            | Self::QualVar(_, _, s)
            | Self::Con(_, s)
            | Self::QualCon(_, _, s)
            | Self::Lit(_, s)
            | Self::App(_, _, s)
            | Self::Lam(_, _, s)
            | Self::Let(_, _, s)
            | Self::If(_, _, _, s)
            | Self::Case(_, _, s)
            | Self::Do(_, s)
            | Self::Tuple(_, s)
            | Self::List(_, s)
            | Self::ArithSeq(_, s)
            | Self::ListComp(_, _, s)
            | Self::RecordCon(_, _, _, s)
            | Self::RecordUpd(_, _, s)
            | Self::Infix(_, _, _, s)
            | Self::Neg(_, s)
            | Self::Paren(_, s)
            | Self::Ann(_, _, s)
            | Self::Lazy(_, s)
            | Self::Wildcard(s) => *s,
        }
    }
}

/// A literal value.
#[derive(Clone, Debug, PartialEq)]
pub enum Lit {
    /// Integer literal.
    Int(i64),
    /// Floating-point literal.
    Float(f64),
    /// Character literal.
    Char(char),
    /// String literal.
    String(String),
}

/// An arithmetic sequence.
#[derive(Clone, Debug)]
pub enum ArithSeq {
    /// `[from..]`
    From(Box<Expr>),
    /// `[from, then..]`
    FromThen(Box<Expr>, Box<Expr>),
    /// `[from..to]`
    FromTo(Box<Expr>, Box<Expr>),
    /// `[from, then..to]`
    FromThenTo(Box<Expr>, Box<Expr>, Box<Expr>),
}

/// A case alternative.
#[derive(Clone, Debug)]
pub struct Alt {
    /// The pattern.
    pub pat: Pat,
    /// The right-hand side.
    pub rhs: Rhs,
    /// Local bindings.
    pub wheres: Vec<Decl>,
    /// The span.
    pub span: Span,
}

/// A statement in a do block or list comprehension.
#[derive(Clone, Debug)]
pub enum Stmt {
    /// Generator: `x <- xs`
    Generator(Pat, Expr, Span),
    /// Qualifier/guard: `x > 0`
    Qualifier(Expr, Span),
    /// Let binding: `let x = 1`
    LetStmt(Vec<Decl>, Span),
}

/// A field binding in a record.
#[derive(Clone, Debug)]
pub struct FieldBind {
    /// Optional module qualifier for disambiguated record fields (e.g., `XMonad.borderWidth`).
    pub qualifier: Option<ModuleName>,
    /// Field name.
    pub name: Ident,
    /// Field value (None for punning: `Foo { bar }` means `Foo { bar = bar }`)
    pub value: Option<Expr>,
    /// The span.
    pub span: Span,
}

/// A pattern.
#[derive(Clone, Debug)]
pub enum Pat {
    /// Wildcard: `_`
    Wildcard(Span),
    /// Variable: `x`
    Var(Ident, Span),
    /// Literal: `42`
    Lit(Lit, Span),
    /// Constructor: `Just x`
    Con(Ident, Vec<Pat>, Span),
    /// Qualified constructor: `M.Just x`, `Data.Maybe.Nothing`
    QualCon(ModuleName, Ident, Vec<Pat>, Span),
    /// Infix constructor: `x : xs`
    Infix(Box<Pat>, Ident, Box<Pat>, Span),
    /// Tuple: `(a, b)`
    Tuple(Vec<Pat>, Span),
    /// List: `[a, b, c]`
    List(Vec<Pat>, Span),
    /// Record: `Foo { bar = x }` or `Foo { bar = x, .. }` (RecordWildCards)
    Record(Ident, Vec<FieldPat>, bool, Span),
    /// Qualified record: `M.Foo { bar = x }` or `M.Foo { .. }` (RecordWildCards)
    QualRecord(ModuleName, Ident, Vec<FieldPat>, bool, Span),
    /// As-pattern: `xs@(x:_)`
    As(Ident, Box<Pat>, Span),
    /// Lazy pattern: `~pat`
    Lazy(Box<Pat>, Span),
    /// Bang pattern: `!pat`
    Bang(Box<Pat>, Span),
    /// Parenthesized pattern
    Paren(Box<Pat>, Span),
    /// Type annotation: `x :: Int`
    Ann(Box<Pat>, Type, Span),
    /// View pattern: `(expr -> pat)` (ViewPatterns extension)
    View(Box<Expr>, Box<Pat>, Span),
}

impl Pat {
    /// Get the span of this pattern.
    #[must_use]
    pub fn span(&self) -> Span {
        match self {
            Self::Wildcard(s)
            | Self::Var(_, s)
            | Self::Lit(_, s)
            | Self::Con(_, _, s)
            | Self::QualCon(_, _, _, s)
            | Self::Infix(_, _, _, s)
            | Self::Tuple(_, s)
            | Self::List(_, s)
            | Self::Record(_, _, _, s)
            | Self::QualRecord(_, _, _, _, s)
            | Self::As(_, _, s)
            | Self::Lazy(_, s)
            | Self::Bang(_, s)
            | Self::Paren(_, s)
            | Self::Ann(_, _, s)
            | Self::View(_, _, s) => *s,
        }
    }
}

/// A field pattern in a record.
#[derive(Clone, Debug)]
pub struct FieldPat {
    /// Optional module qualifier for disambiguated record fields (e.g., `XMonad.modMask`).
    pub qualifier: Option<ModuleName>,
    /// Field name.
    pub name: Ident,
    /// Pattern (None for punning).
    pub pat: Option<Pat>,
    /// The span.
    pub span: Span,
}

/// A type.
#[derive(Clone, Debug)]
pub enum Type {
    /// Type variable: `a`
    Var(TyVar, Span),
    /// Type constructor: `Int`, `Maybe`
    Con(Ident, Span),
    /// Qualified type constructor: `M.Map`, `Data.List.Sort`
    QualCon(ModuleName, Ident, Span),
    /// Application: `Maybe Int`
    App(Box<Type>, Box<Type>, Span),
    /// Function type: `a -> b`
    Fun(Box<Type>, Box<Type>, Span),
    /// Tuple type: `(a, b)`
    Tuple(Vec<Type>, Span),
    /// List type: `[a]`
    List(Box<Type>, Span),
    /// Parenthesized type
    Paren(Box<Type>, Span),
    /// Forall type: `forall a. a -> a`
    Forall(Vec<TyVar>, Box<Type>, Span),
    /// Constrained type: `Eq a => a -> a -> Bool`
    Constrained(Vec<Constraint>, Box<Type>, Span),

    // === M9 Dependent Types Preview ===
    /// Promoted list: `'[1024, 768]` for tensor shapes
    PromotedList(Vec<Type>, Span),
    /// Type-level natural literal: `1024` in type position
    NatLit(u64, Span),

    /// Strict type annotation: `!Int` in constructor fields
    Bang(Box<Type>, Span),

    /// Lazy type annotation: `~Int` in constructor fields
    Lazy(Box<Type>, Span),

    /// Infix type operator: `a :+: b` (requires TypeOperators)
    InfixOp(Box<Type>, Ident, Box<Type>, Span),
}

impl Type {
    /// Get the span of this type.
    #[must_use]
    pub fn span(&self) -> Span {
        match self {
            Self::Var(_, s)
            | Self::Con(_, s)
            | Self::QualCon(_, _, s)
            | Self::App(_, _, s)
            | Self::Fun(_, _, s)
            | Self::Tuple(_, s)
            | Self::List(_, s)
            | Self::Paren(_, s)
            | Self::Forall(_, _, s)
            | Self::Constrained(_, _, s)
            | Self::PromotedList(_, s)
            | Self::NatLit(_, s)
            | Self::Bang(_, s)
            | Self::Lazy(_, s)
            | Self::InfixOp(_, _, _, s) => *s,
        }
    }
}

/// A type variable.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TyVar {
    /// The name.
    pub name: Ident,
    /// The span.
    pub span: Span,
}

/// A type class constraint.
#[derive(Clone, Debug)]
pub struct Constraint {
    /// The class name.
    pub class: Ident,
    /// The type arguments.
    pub args: Vec<Type>,
    /// The span.
    pub span: Span,
}