daml-parser 0.10.1

Lossless lexer, layout resolver, and parser for the Daml smart-contract language
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
//! Typed, lossless parse tree produced by the recursive-descent parser
//! (src/parse.rs).
//!
//! Declarations, expressions, patterns, and most parser DTOs carry both a
//! 1-based source `Pos` for their first token and a byte `Span` for their
//! full source extent. `Type` nodes carry spans only because downstream
//! consumers slice type source text but do not currently need line/column
//! anchors per type fragment. Downstream crates consume this tree directly:
//! daml-fmt re-prints layout from the spans, and daml-lint lowers it onto its
//! own rule-facing IR.
//!
//! Parser-created trees are the supported construction path. Public fields are
//! exposed so tools can match the tree directly; vectors preserve source order,
//! `pos` is the first token's position, and `span` is the half-open byte range
//! covering the node's real source tokens.

pub use crate::lexer::{ByteOffset, Identifier, ModuleName, Operator, Pos};

/// Byte span of an AST node.
///
/// `[start, end)` into the original source, same basis as `Token::start`/
/// `Token::end`. Covers every (non-virtual) token that belongs to the node —
/// first token's `start` to last token's `end`.
///
/// Invariants the parser maintains (checked over the corpus by
/// `render_from_ast`): a child's span is contained in its parent's span, and
/// sibling spans are ordered and non-overlapping. Trivia (comments, blank
/// lines) live *between* sibling spans.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct Span {
    /// Inclusive byte offset at which the node starts.
    pub start: ByteOffset,
    /// Exclusive byte offset at which the node ends.
    pub end: ByteOffset,
}

impl Span {
    /// Create a span from already-typed byte offsets.
    ///
    /// Use [`Self::from_usize`] only at parser/source-slicing boundaries where
    /// raw byte offsets are being converted deliberately.
    ///
    /// ```compile_fail
    /// use daml_parser::ast::Span;
    ///
    /// let _ = Span::new(1usize, 2usize);
    /// ```
    #[must_use]
    pub const fn new(start: ByteOffset, end: ByteOffset) -> Self {
        Self { start, end }
    }

    /// Convert raw byte offsets into a typed parser span.
    #[must_use]
    pub const fn from_usize(start: usize, end: usize) -> Self {
        Self {
            start: ByteOffset::new(start),
            end: ByteOffset::new(end),
        }
    }

    /// Raw start byte offset for source slicing and external interop.
    #[must_use]
    pub const fn start_usize(self) -> usize {
        self.start.get()
    }

    /// Raw exclusive end byte offset for source slicing and external interop.
    #[must_use]
    pub const fn end_usize(self) -> usize {
        self.end.get()
    }

    /// True when the span is well-formed (`start <= end`).
    #[must_use]
    pub const fn is_valid(&self) -> bool {
        self.start.get() <= self.end.get()
    }

    /// True for a zero-width but still valid span.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.start.get() == self.end.get()
    }

    #[must_use]
    pub const fn range(&self) -> std::ops::Range<usize> {
        self.start.get()..self.end.get()
    }

    #[must_use]
    pub fn get<'a>(&self, source: &'a str) -> Option<&'a str> {
        let start = self.start.get();
        let end = self.end.get();
        if start <= end
            && end <= source.len()
            && source.is_char_boundary(start)
            && source.is_char_boundary(end)
        {
            Some(&source[start..end])
        } else {
            None
        }
    }

    /// `self` fully contains `other`.
    #[must_use]
    pub const fn contains(&self, other: &Self) -> bool {
        self.is_valid()
            && other.is_valid()
            && self.start.get() <= other.start.get()
            && other.end.get() <= self.end.get()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LitKind {
    /// Integer literal.
    Int,
    /// Decimal literal.
    Decimal,
    /// Text/string literal.
    Text,
    /// Character literal.
    Char,
}

/// Import syntax style.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ImportStyle {
    /// Qualified import (`import qualified Foo.Bar`, `import Foo.Bar qualified`).
    Qualified,
    /// Unqualified import (`import Foo.Bar`, `import Foo.Bar as Baz`).
    Unqualified,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FieldAssign {
    /// Explicit record assignment: `field = expression`.
    Assign {
        /// Field being assigned.
        name: Identifier,
        /// Right-hand-side expression after `=`.
        value: Expr,
        /// Position of the field name.
        pos: Pos,
        /// Span of the whole `field = expression` assignment.
        span: Span,
    },
    /// Record pun: `field`, meaning `field = field`.
    Pun {
        /// Punned field name.
        name: Identifier,
        /// Position of the field name.
        pos: Pos,
        /// Span of the field name.
        span: Span,
    },
    /// Record wildcard: `..`.
    Wildcard {
        /// Position of the `..` token.
        pos: Pos,
        /// Span of the `..` token.
        span: Span,
    },
}

impl FieldAssign {
    #[must_use]
    pub const fn pos(&self) -> Pos {
        match self {
            Self::Assign { pos, .. } | Self::Pun { pos, .. } | Self::Wildcard { pos, .. } => *pos,
        }
    }

    #[must_use]
    pub const fn span(&self) -> Span {
        match self {
            Self::Assign { span, .. } | Self::Pun { span, .. } | Self::Wildcard { span, .. } => {
                *span
            }
        }
    }

    #[must_use]
    pub const fn name(&self) -> Option<&Identifier> {
        match self {
            Self::Assign { name, .. } | Self::Pun { name, .. } => Some(name),
            Self::Wildcard { .. } => None,
        }
    }
}

/// Boolean or pattern guard qualifier in a guarded case alternative branch.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum GuardQualifier {
    /// Boolean guard expression.
    Bool {
        /// Guard expression.
        expr: Expr,
        /// Position of the guard's first token.
        pos: Pos,
        /// Span of the guard qualifier.
        span: Span,
    },
    /// Pattern guard `pat <- expr`.
    Pattern {
        /// Pattern bound by the guard.
        pat: Pat,
        /// Source expression on the right of `<-`.
        expr: Expr,
        /// Position of the pattern guard's first token.
        pos: Pos,
        /// Span of the pattern guard qualifier.
        span: Span,
    },
}

impl GuardQualifier {
    #[must_use]
    pub const fn span(&self) -> Span {
        match self {
            Self::Bool { span, .. } | Self::Pattern { span, .. } => *span,
        }
    }

    #[must_use]
    pub const fn pos(&self) -> Pos {
        match self {
            Self::Bool { pos, .. } | Self::Pattern { pos, .. } => *pos,
        }
    }
}

/// One guarded or unguarded branch of a case/`try` alternative.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AltBranch {
    /// Comma-separated guard qualifiers before `->`; empty for unguarded branches.
    pub guards: Vec<GuardQualifier>,
    /// Branch body after `->`.
    pub body: Expr,
    /// Position of the branch's first token (`|` or `->`).
    pub pos: Pos,
    /// Span of the whole branch.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Alt {
    /// Pattern to match before `->` or the first `|`.
    pub pat: Pat,
    /// First branch body for convenience; mirrors `branches[0].body`.
    pub body: Expr,
    /// Source-ordered guarded/unguarded branches for this alternative.
    pub branches: Vec<AltBranch>,
    /// `where` helper bindings attached to this alternative.
    pub where_bindings: Vec<Binding>,
    /// Position of the alternative's first token.
    pub pos: Pos,
    /// Span of the whole alternative.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding {
    /// Left-hand side: a variable with parameters, or a destructuring pattern.
    pub pat: Pat,
    /// Parameter patterns when the LHS is a function binding (`f x y = ...`).
    pub params: Vec<Pat>,
    /// Right-hand-side expression.
    pub expr: Expr,
    /// Position of the binding's first token.
    pub pos: Pos,
    /// Span of the whole binding.
    pub span: Span,
}

/// Record-pattern field syntax: explicit braces or layout `with`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecordPatternSyntax {
    /// `Foo { field = pat; .. }`.
    Braces,
    /// `Foo with field; nested = pat`.
    With,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PatFieldAssign {
    /// Explicit record-pattern assignment: `field = pattern`.
    Assign {
        /// Field being matched.
        name: Identifier,
        /// Pattern bound to the field.
        pat: Pat,
        /// Position of the field name.
        pos: Pos,
        /// Span of the whole `field = pattern` assignment.
        span: Span,
    },
    /// Record-pattern pun: `field`, meaning `field = field`.
    Pun {
        /// Punned field name.
        name: Identifier,
        /// Position of the field name.
        pos: Pos,
        /// Span of the field name.
        span: Span,
    },
    /// Record-pattern wildcard: `..`.
    Wildcard {
        /// Position of the `..` token.
        pos: Pos,
        /// Span of the `..` token.
        span: Span,
    },
}

impl PatFieldAssign {
    #[must_use]
    pub const fn pos(&self) -> Pos {
        match self {
            Self::Assign { pos, .. } | Self::Pun { pos, .. } | Self::Wildcard { pos, .. } => *pos,
        }
    }

    #[must_use]
    pub const fn span(&self) -> Span {
        match self {
            Self::Assign { span, .. } | Self::Pun { span, .. } | Self::Wildcard { span, .. } => {
                *span
            }
        }
    }

    #[must_use]
    pub const fn name(&self) -> Option<&Identifier> {
        match self {
            Self::Assign { name, .. } | Self::Pun { name, .. } => Some(name),
            Self::Wildcard { .. } => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Pat {
    /// Variable pattern.
    Var {
        /// Bound variable name.
        name: Identifier,
        /// Position of the variable token.
        pos: Pos,
        /// Span of the variable token.
        span: Span,
    },
    /// Wildcard pattern (`_`).
    Wild {
        /// Position of the `_` token.
        pos: Pos,
        /// Span of the `_` token.
        span: Span,
    },
    /// Constructor pattern with source-ordered arguments.
    Con {
        /// Optional module qualifier before the constructor name.
        qualifier: Option<ModuleName>,
        /// Constructor name.
        name: Identifier,
        /// Constructor arguments in source order.
        args: Vec<Self>,
        /// Position of the constructor token.
        pos: Pos,
        /// Span of the whole constructor pattern.
        span: Span,
    },
    /// Constructor record pattern with source-ordered fields.
    Record {
        /// Optional module qualifier before the constructor name.
        qualifier: Option<ModuleName>,
        /// Constructor name.
        name: Identifier,
        /// Whether fields used `{..}` or `with`.
        syntax: RecordPatternSyntax,
        /// Field patterns in source order.
        fields: Vec<PatFieldAssign>,
        /// Position of the constructor token.
        pos: Pos,
        /// Span of the whole record pattern.
        span: Span,
    },
    /// Tuple pattern with source-ordered items.
    Tuple {
        /// Tuple items in source order.
        items: Vec<Self>,
        /// Position of the opening parenthesis.
        pos: Pos,
        /// Span from `(` through `)`.
        span: Span,
    },
    /// List pattern with source-ordered items.
    List {
        /// List items in source order.
        items: Vec<Self>,
        /// Position of the opening bracket.
        pos: Pos,
        /// Span from `[` through `]`.
        span: Span,
    },
    /// Literal pattern; `text` is the parser's normalized literal text.
    Lit {
        /// Literal family.
        kind: LitKind,
        /// Normalized literal payload.
        text: String,
        /// Position of the literal token.
        pos: Pos,
        /// Span of the literal token in the source.
        span: Span,
    },
    /// `name@pat`
    As {
        /// Name bound to the whole matched pattern.
        name: Identifier,
        /// Pattern being aliased.
        pat: Box<Self>,
        /// Position of the bound name.
        pos: Pos,
        /// Span of the whole `name@pat` pattern.
        span: Span,
    },
    /// Anything the parser couldn't classify; raw text preserved.
    Other {
        /// Raw source text of the unclassified pattern.
        raw: String,
        /// Position of the raw pattern's first token.
        pos: Pos,
        /// Span of the preserved raw pattern text.
        span: Span,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Expr {
    /// Lowercase variable reference, possibly qualified.
    Var {
        /// Optional module qualifier before the variable name.
        qualifier: Option<ModuleName>,
        /// Variable name.
        name: Identifier,
        /// Position of the variable token.
        pos: Pos,
        /// Span of the variable token.
        span: Span,
    },
    /// Constructor / data-constructor reference, possibly qualified.
    Con {
        /// Optional module qualifier before the constructor name.
        qualifier: Option<ModuleName>,
        /// Constructor name.
        name: Identifier,
        /// Position of the constructor token.
        pos: Pos,
        /// Span of the constructor token.
        span: Span,
    },
    /// Literal expression; `text` is the parser's normalized literal text.
    Lit {
        /// Literal family.
        kind: LitKind,
        /// Normalized literal payload.
        text: String,
        /// Position of the literal token.
        pos: Pos,
        /// Span of the literal token in the source.
        span: Span,
    },
    /// Application, flattened: `f a b c` is one App with three args.
    App {
        /// Function expression being applied.
        func: Box<Self>,
        /// Arguments in source order.
        args: Vec<Self>,
        /// Position of the application's first token.
        pos: Pos,
        /// Span of the whole application.
        span: Span,
    },
    /// Binary operator application with source-level operator text.
    BinOp {
        /// Operator token text.
        op: Operator,
        /// Left operand.
        lhs: Box<Self>,
        /// Right operand.
        rhs: Box<Self>,
        /// Position of the left operand.
        pos: Pos,
        /// Span of the whole infix expression.
        span: Span,
    },
    /// Unary negation.
    Neg {
        /// Negated expression.
        expr: Box<Self>,
        /// Position of the `-` token.
        pos: Pos,
        /// Span of the whole negated expression.
        span: Span,
    },
    /// Lambda expression (`\params -> body`).
    Lambda {
        /// Parameter patterns in source order.
        params: Vec<Pat>,
        /// Lambda body.
        body: Box<Self>,
        /// Position of the lambda token.
        pos: Pos,
        /// Span of the whole lambda expression.
        span: Span,
    },
    /// Conditional expression.
    If {
        /// Condition after `if`.
        cond: Box<Self>,
        /// Expression after `then`.
        then_branch: Box<Self>,
        /// Expression after `else`.
        else_branch: Box<Self>,
        /// Position of the `if` token.
        pos: Pos,
        /// Span of the whole conditional expression.
        span: Span,
    },
    /// Case expression with source-ordered alternatives.
    Case {
        /// Scrutinee after `case`.
        scrutinee: Box<Self>,
        /// Alternatives in source order.
        alts: Vec<Alt>,
        /// Position of the `case` token.
        pos: Pos,
        /// Span of the whole case expression.
        span: Span,
    },
    /// Do block.
    Do {
        /// Statements in source order.
        stmts: Vec<DoStmt>,
        /// Position of the `do` token.
        pos: Pos,
        /// Span of the whole do block.
        span: Span,
    },
    /// Let/in expression.
    LetIn {
        /// Bindings in source order.
        bindings: Vec<Binding>,
        /// Body expression after `in`.
        body: Box<Self>,
        /// Position of the `let` token.
        pos: Pos,
        /// Span of the whole let/in expression.
        span: Span,
    },
    /// `base with f = e, ...` — record construction when base is a Con,
    /// record update otherwise.
    Record {
        /// Constructor or record value being constructed/updated.
        base: Box<Self>,
        /// Field assignments in source order.
        fields: Vec<FieldAssign>,
        /// Position of the base expression.
        pos: Pos,
        /// Span of the whole record expression.
        span: Span,
    },
    /// Tuple expression with source-ordered items.
    Tuple {
        /// Tuple items in source order.
        items: Vec<Self>,
        /// Position of the opening parenthesis.
        pos: Pos,
        /// Span from `(` through `)`.
        span: Span,
    },
    /// List expression with source-ordered items.
    List {
        /// List items in source order.
        items: Vec<Self>,
        /// Position of the opening bracket.
        pos: Pos,
        /// Span from `[` through `]`.
        span: Span,
    },
    /// `try <body> catch <alts>`
    Try {
        /// Body after `try`.
        body: Box<Self>,
        /// Catch handlers in source order.
        handlers: Vec<Alt>,
        /// Position of the `try` token.
        pos: Pos,
        /// Span of the whole try/catch expression.
        span: Span,
    },
    /// Parenthesized operator reference like `(+)`.
    OperatorRef {
        /// Referenced operator.
        op: Operator,
        /// Position of the opening parenthesis.
        pos: Pos,
        /// Span from `(` through `)`.
        span: Span,
    },
    /// Left operator section like `(1 +)`.
    LeftSection {
        /// Section operator.
        op: Operator,
        /// Left operand before the operator.
        operand: Box<Self>,
        /// Position of the opening parenthesis.
        pos: Pos,
        /// Span from `(` through `)`.
        span: Span,
    },
    /// Right operator section like `(+ 1)`.
    RightSection {
        /// Section operator.
        op: Operator,
        /// Right operand after the operator.
        operand: Box<Self>,
        /// Position of the opening parenthesis.
        pos: Pos,
        /// Span from `(` through `)`.
        span: Span,
    },
    /// Expression the parser could not understand; raw text preserved so
    /// a parse failure degrades to the shim's behavior instead of dying.
    Error {
        /// Raw source text preserved for the malformed expression.
        raw: String,
        /// Position of the malformed expression's first token.
        pos: Pos,
        /// Span of the preserved raw expression text.
        span: Span,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DoStmt {
    /// `pat <- expr`
    Bind {
        /// Pattern before `<-`.
        pat: Pat,
        /// Expression after `<-`.
        expr: Expr,
        /// Position of the statement's first token.
        pos: Pos,
        /// Span of the whole bind statement.
        span: Span,
    },
    /// `let x = e` (no `in`) inside a do block.
    Let {
        /// Let bindings in source order.
        bindings: Vec<Binding>,
        /// Position of the `let` token.
        pos: Pos,
        /// Span of the whole let statement.
        span: Span,
    },
    /// Bare expression statement.
    Expr {
        /// Statement expression.
        expr: Expr,
        /// Position of the expression's first token.
        pos: Pos,
        /// Span of the expression statement.
        span: Span,
    },
}

/// Structured Daml type, parsed from the real token stream.
///
/// Scoped to the forms the corpus actually contains; it exists so consumers can
/// tell a type *application* from a *function arrow* from an
/// atomic constructor — a distinction a string matcher structurally cannot make.
/// Every node carries a byte span so consumers can render exact source text from
/// `(source, span)`. Unlike declarations, expressions, and patterns, type nodes
/// do not carry a separate [`Pos`]; use [`Type::span`] and source line mapping
/// when a line/column anchor is required for a type fragment.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Type {
    /// Type constructor, possibly qualified: `Party`, `DA.Map.Map`.
    Con {
        /// Optional module qualifier before the constructor name.
        qualifier: Option<ModuleName>,
        /// Constructor name.
        name: Identifier,
        /// Span of the constructor token in the source.
        span: Span,
    },
    /// Type application, head applied to one or more args: `ContractId Foo`,
    /// `Map Text Int`, `Script ()`. Type-level nat literals (the `10` in
    /// `Numeric 10`) are NOT types, so they are dropped from the arg list — a
    /// `Numeric 10` collapses to the bare head `Con "Numeric"`.
    App(Box<Self>, Vec<Self>, Span),
    /// List type `[T]`.
    List(Box<Self>, Span),
    /// Tuple type `(a, b, ...)`.
    Tuple(Vec<Self>, Span),
    /// Function type `a -> b` (right-associative).
    Fun(Box<Self>, Box<Self>, Span),
    /// Lowercase type variable: `a`, `n`.
    Var(Identifier, Span),
    /// The unit type `()`.
    Unit(Span),
    /// A constrained type `C a => T`: the context is not modeled, the body `T`
    /// is kept.
    Constrained(Box<Self>, Span),
    /// Type-level string or char literal, e.g. the `"observers"` in
    /// `HasField "observers" t PartiesMap`.
    Lit {
        /// Literal family.
        kind: LitKind,
        /// Normalized literal payload.
        text: String,
        /// Span of the literal token in the source.
        span: Span,
    },
}

/// Type equality intentionally ignores source spans.
///
/// Spans describe where equivalent type syntax appeared in a source file; they
/// are not part of structural type identity used by parser consumers.
impl PartialEq for Type {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::Con {
                    qualifier: aq,
                    name: an,
                    ..
                },
                Self::Con {
                    qualifier: bq,
                    name: bn,
                    ..
                },
            ) => aq == bq && an == bn,
            (Self::App(ah, aa, _), Self::App(bh, ba, _)) => ah == bh && aa == ba,
            (Self::List(a, _), Self::List(b, _))
            | (Self::Constrained(a, _), Self::Constrained(b, _)) => a == b,
            (Self::Tuple(a, _), Self::Tuple(b, _)) => a == b,
            (Self::Fun(al, ar, _), Self::Fun(bl, br, _)) => al == bl && ar == br,
            (Self::Var(a, _), Self::Var(b, _)) => a == b,
            (Self::Unit(_), Self::Unit(_)) => true,
            (
                Self::Lit {
                    kind: ak, text: at, ..
                },
                Self::Lit {
                    kind: bk, text: bt, ..
                },
            ) => ak == bk && at == bt,
            _ => false,
        }
    }
}

impl Eq for Type {}

impl Type {
    #[must_use]
    pub const fn span(&self) -> Span {
        match self {
            Self::Con { span, .. }
            | Self::App(_, _, span)
            | Self::List(_, span)
            | Self::Tuple(_, span)
            | Self::Fun(_, _, span)
            | Self::Var(_, span)
            | Self::Unit(span)
            | Self::Constrained(_, span)
            | Self::Lit { span, .. } => *span,
        }
    }

    pub(crate) const fn with_span(mut self, span: Span) -> Self {
        match &mut self {
            Self::Con { span: s, .. }
            | Self::App(_, _, s)
            | Self::List(_, s)
            | Self::Tuple(_, s)
            | Self::Fun(_, _, s)
            | Self::Var(_, s)
            | Self::Unit(s)
            | Self::Constrained(_, s)
            | Self::Lit { span: s, .. } => *s = span,
        }
        self
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TypeAnnotation {
    /// The source construct did not include a type annotation.
    Absent,
    /// The source construct included a type annotation that parsed cleanly.
    Present(Type),
    /// The source construct included a type annotation, but the parser could
    /// not model it as a [`Type`]. Diagnostics carry the detailed message.
    Malformed { span: Span },
}

impl TypeAnnotation {
    #[must_use]
    pub const fn as_type(&self) -> Option<&Type> {
        match self {
            Self::Present(ty) => Some(ty),
            Self::Absent | Self::Malformed { .. } => None,
        }
    }

    #[must_use]
    pub const fn is_absent(&self) -> bool {
        matches!(self, Self::Absent)
    }

    #[must_use]
    pub const fn is_malformed(&self) -> bool {
        matches!(self, Self::Malformed { .. })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldDecl {
    /// Field or method name.
    pub name: Identifier,
    /// Structured field type parse state.
    pub ty: TypeAnnotation,
    /// Position of the field/method name.
    pub pos: Pos,
    /// Span of the full field declaration (`name : Type` when present).
    pub span: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Consuming {
    /// Daml `consuming` choice.
    Consuming,
    /// Daml `nonconsuming` choice.
    NonConsuming,
    /// Legacy/pre-Daml-3 `preconsuming` spelling.
    PreConsuming,
    /// Legacy/pre-Daml-3 `postconsuming` spelling.
    PostConsuming,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChoiceDecl {
    /// Choice name.
    pub name: Identifier,
    /// Consuming mode parsed from the choice header.
    pub consuming: Consuming,
    /// Structured return type parse state.
    pub return_ty: TypeAnnotation,
    /// Choice parameter fields in source order.
    pub params: Vec<FieldDecl>,
    /// Comma-separated controller expressions.
    pub controllers: Vec<Expr>,
    /// Choice observers, if any.
    pub observers: Vec<Expr>,
    /// Choice authority expressions from `authority` metadata clauses.
    pub authority_exprs: Vec<Expr>,
    /// Choice body after `do`; `None` when the parser did not find one.
    pub body: Option<Expr>,
    /// Position of the `choice` token.
    pub pos: Pos,
    /// Span of the whole choice declaration.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TemplateBodyDecl {
    /// `signatory` clause with source-ordered party expressions.
    Signatory {
        /// Party expressions in source order.
        parties: Vec<Expr>,
        /// Position of the `signatory` token.
        pos: Pos,
        /// Span of the whole clause.
        span: Span,
    },
    /// `observer` clause with source-ordered party expressions.
    Observer {
        /// Party expressions in source order.
        parties: Vec<Expr>,
        /// Position of the `observer` token.
        pos: Pos,
        /// Span of the whole clause.
        span: Span,
    },
    /// `ensure` clause.
    Ensure {
        /// Predicate expression after `ensure`.
        expr: Expr,
        /// Position of the `ensure` token.
        pos: Pos,
        /// Span of the whole clause.
        span: Span,
    },
    /// Template `key` declaration.
    Key {
        /// Key expression.
        expr: Expr,
        /// Structured key type parse state.
        ty: TypeAnnotation,
        /// Position of the `key` token.
        pos: Pos,
        /// Span of the whole key declaration.
        span: Span,
    },
    /// `maintainer` clause.
    Maintainer {
        /// Maintainer expression.
        expr: Expr,
        /// Position of the `maintainer` token.
        pos: Pos,
        /// Span of the whole clause.
        span: Span,
    },
    /// `choice` declaration.
    Choice(ChoiceDecl),
    /// `interface instance` declaration nested in a template.
    InterfaceInstance(InterfaceInstanceDecl),
    /// `agreement`, `let` blocks, deprecated `controller ... can`, etc.
    Other {
        /// Raw source text preserved for unsupported/malformed body syntax.
        raw: String,
        /// Position of the raw body's first token.
        pos: Pos,
        /// Span of the preserved raw body text.
        span: Span,
    },
}

/// One item in an `interface instance ... where` body, in source order.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum InterfaceInstanceBodyItem {
    /// `view = <expr>` binding for the interface view implementation.
    View {
        /// View expression.
        expr: Expr,
        /// Position of the `view` token.
        pos: Pos,
        /// Span of the whole `view = ...` item.
        span: Span,
    },
    /// An ordinary interface method implementation.
    Method(Binding),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterfaceInstanceDecl {
    /// Interface being implemented (`Disclosure.I`).
    pub interface_name: ModuleName,
    /// Explicit template from `for Foo`; `None` when omitted (the enclosing
    /// template when declared inside one).
    pub for_template: Option<ModuleName>,
    /// View and method implementations in source order.
    pub items: Vec<InterfaceInstanceBodyItem>,
    /// Position of the `interface instance` clause.
    pub pos: Pos,
    /// Span of the whole interface instance declaration.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateDecl {
    /// Template name.
    pub name: Identifier,
    /// Template fields in source order.
    pub fields: Vec<FieldDecl>,
    /// Template body declarations in source order.
    pub body: Vec<TemplateBodyDecl>,
    /// Position of the `template` token.
    pub pos: Pos,
    /// Span of the whole template declaration.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterfaceDecl {
    /// Interface name.
    pub name: Identifier,
    /// Interfaces this interface requires (`requires Lockable.I, ...`).
    pub requires: Vec<ModuleName>,
    /// Optional view type name from `viewtype`.
    pub viewtype: Option<ModuleName>,
    /// Method signatures in source order.
    pub methods: Vec<FieldDecl>,
    /// Interface choices in source order.
    pub choices: Vec<ChoiceDecl>,
    /// Position of the `interface` token.
    pub pos: Pos,
    /// Span of the whole interface declaration.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Equation {
    /// Parameter patterns in source order.
    pub params: Vec<Pat>,
    /// Unguarded body or first guarded body for convenience.
    pub body: Expr,
    /// Guarded equations keep their guards as (guard, body) pairs; `body`
    /// then holds the first guarded body for convenience.
    pub guards: Vec<(Expr, Expr)>,
    /// `where` helper bindings attached to this equation.
    pub where_bindings: Vec<Binding>,
    /// Position of the equation's first token.
    pub pos: Pos,
    /// Span of this equation only.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FunctionDecl {
    /// Function name.
    pub name: Identifier,
    /// Standalone signature type parse state.
    pub ty: TypeAnnotation,
    /// Equations for this function in source order.
    pub equations: Vec<Equation>,
    /// Position of the function's first appearance.
    pub pos: Pos,
    /// Span of the function's first appearance (signature or first equation).
    /// Convenience anchor; a multi-equation function's precise ranges are the
    /// per-`Equation` spans, since equations need not be contiguous in source.
    pub span: Span,
    /// Span of the standalone type signature `name : Type`, if one was seen.
    pub sig_span: Option<Span>,
}

/// Fixity associativity keyword (`infix`, `infixl`, `infixr`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FixityAssoc {
    Infix,
    InfixL,
    InfixR,
}

/// Operator or backtick-quoted name in a fixity declaration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FixityTarget {
    /// Symbolic operator such as `===` or `>=>`.
    Operator(Operator),
    /// Backtick-quoted identifier such as `` `Pair` ``.
    Backtick(Identifier),
}

/// Top-level fixity declaration (`infix[l|r]? n op [, op ...]`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FixityDecl {
    pub assoc: FixityAssoc,
    pub precedence: u8,
    pub operators: Vec<FixityTarget>,
    pub pos: Pos,
    pub span: Span,
}

/// Source package label on a package-qualified import (`import "pkg" Module`).
///
/// Holds the decoded string literal value and its source span. This is source
/// syntax only; it is not resolved to an LF `PackageId`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportPackageLabel {
    /// Decoded package label text from the string literal.
    pub value: String,
    /// Span of the string literal token, including quotes.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportDecl {
    /// Imported module path.
    pub module_name: ModuleName,
    /// Whether the import is qualified.
    pub style: ImportStyle,
    /// Optional module alias from `as`.
    pub alias: Option<ModuleName>,
    /// Optional package label from `import "pkg" Module` source syntax.
    pub package_label: Option<ImportPackageLabel>,
    /// Position of the `import` token.
    pub pos: Pos,
    /// Span of the whole import declaration.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Decl {
    /// Template declaration.
    Template(TemplateDecl),
    /// Interface declaration.
    Interface(InterfaceDecl),
    /// Function signature/equations grouped by name.
    Function(FunctionDecl),
    /// data/type/class/instance/exception — recorded with name + span.
    TypeDef {
        /// Declaration keyword (`data`, `type`, `class`, ...).
        keyword: String,
        /// Declared type/class/instance name as parsed.
        name: Identifier,
        /// Position of the declaration keyword.
        pos: Pos,
        /// Span of the declaration header/body consumed by the parser.
        span: Span,
    },
    /// Top-level fixity declaration.
    Fixity(FixityDecl),
    /// Top-level syntax the parser recognizes but intentionally does not model.
    UnsupportedSyntax {
        /// Why the declaration is unsupported.
        kind: UnsupportedSyntaxKind,
        /// Raw source text of the declaration.
        raw: String,
        /// Position of the declaration's first token.
        pos: Pos,
        /// Span of the declaration text.
        span: Span,
    },
    /// Anything unparseable at the top level (diagnostic already emitted).
    Unknown {
        /// Raw source text of the skipped declaration.
        raw: String,
        /// Position of the skipped declaration's first token.
        pos: Pos,
        /// Span of the skipped declaration text.
        span: Span,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Module {
    /// Module name from the header, or `Unknown` when the source has no header.
    pub name: ModuleName,
    /// Position of the `module` keyword, or the start of the fallback module.
    pub pos: Pos,
    /// Whole-module extent: `[0, source.len())`. Container for all decls.
    pub span: Span,
    /// Span of the `module M (...) where` header clause; empty when the file
    /// has no module header. Lets the span oracle treat header tokens as
    /// covered without a dedicated header node.
    pub header: Span,
    /// Imports in source order.
    pub imports: Vec<ImportDecl>,
    /// Top-level declarations in source order.
    pub decls: Vec<Decl>,
}

/// Why a [`ParseDiagnostic`] fired.
///
/// Lets a consumer separate syntax the parser deliberately does not model (still
/// safe, just unanalyzed) from a genuine malformation, a recursion-limit
/// degradation, or a lexical error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DiagnosticCategory {
    /// A whole declaration could not be parsed and was skipped to the next item.
    SkippedDecl,
    /// A malformed expression, pattern, or expected-token error inside an
    /// otherwise-recognized construct.
    Malformed,
    /// A construct the parser intentionally does not support, e.g. legacy
    /// `controller ... can` choice syntax.
    UnsupportedSyntax,
    /// Expression/pattern nesting exceeded the recursion bound and was degraded
    /// to raw text.
    RecursionLimit,
    /// A lexical error (unterminated string/comment, stray character).
    Lex,
}

impl DiagnosticCategory {
    /// Stable kebab-case tag for machine-readable output (JSON/SARIF) and logs.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SkippedDecl => "skipped-declaration",
            Self::Malformed => "malformed",
            Self::UnsupportedSyntax => "unsupported-syntax",
            Self::RecursionLimit => "recursion-limit",
            Self::Lex => "lexical-error",
        }
    }
}

impl std::fmt::Display for DiagnosticCategory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Machine-readable reason a [`ParseDiagnostic`] fired.
///
/// Keep [`ParseDiagnostic::message`] for presentation. Match on this enum when
/// downstream code needs stable behavior for recoverable parser failures.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseDiagnosticKind {
    /// The lexer reported malformed source; the original lexical kind is
    /// preserved so callers do not need to parse the human message.
    Lex(crate::lexer::LexErrorKind),
    /// The parser expected a specific token or token class and recovered.
    ExpectedToken(ExpectedToken),
    /// A type annotation was present but could not be parsed as a `Type`.
    MalformedTypeAnnotation(TypeAnnotationContext),
    /// A recognized construct was malformed in a way that is not only an
    /// expected-token miss.
    MalformedSyntax(MalformedSyntaxKind),
    /// A whole declaration could not be parsed and was skipped.
    SkippedDeclaration(SkippedDeclarationReason),
    /// The source used syntax this parser intentionally does not model.
    UnsupportedSyntax(UnsupportedSyntaxKind),
    /// Expression or pattern nesting exceeded the parser recursion bound.
    RecursionLimit { limit: u32 },
}

impl ParseDiagnosticKind {
    /// Coarse diagnostic class retained for stable JSON/SARIF tags.
    #[must_use]
    pub const fn category(&self) -> DiagnosticCategory {
        match self {
            Self::Lex(_) => DiagnosticCategory::Lex,
            Self::ExpectedToken(_)
            | Self::MalformedTypeAnnotation(_)
            | Self::MalformedSyntax(_) => DiagnosticCategory::Malformed,
            Self::SkippedDeclaration(_) => DiagnosticCategory::SkippedDecl,
            Self::UnsupportedSyntax(_) => DiagnosticCategory::UnsupportedSyntax,
            Self::RecursionLimit { .. } => DiagnosticCategory::RecursionLimit,
        }
    }
}

/// Expected token or token class for a recoverable parser diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExpectedToken {
    WhereAfterModuleHeader,
    ModuleNameAfterImport,
    TemplateNameAfterInterfaceInstanceFor,
    FieldNameTypePair,
    EqualsAfterGuard,
    EqualsOrGuardedRightHandSide,
    ProjectionFieldAfterDot,
    ThenKeyword,
    ElseKeyword,
    OfKeywordInCaseExpression,
    ArrowInGuardedCaseAlternative,
    ArrowInCaseAlternative,
}

/// The declaration context whose type annotation was malformed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TypeAnnotationContext {
    Field,
    Key,
    Choice,
    InterfaceMethod,
    Function,
}

impl TypeAnnotationContext {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Field => "field",
            Self::Key => "key",
            Self::Choice => "choice",
            Self::InterfaceMethod => "interface method",
            Self::Function => "function",
        }
    }
}

/// Recoverable malformed syntax cases that are not just missing one token.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MalformedSyntaxKind {
    FunctionEquation,
    FunctionParameterPattern,
    LambdaParameter,
}

/// Why a whole declaration was skipped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SkippedDeclarationReason {
    TopLevelPatternBinding,
    UnrecognizedDeclaration,
}

/// Unsupported syntax families surfaced by the parser.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnsupportedSyntaxKind {
    LegacyControllerCan,
    PatternSynonym,
}

/// Parse diagnostic — never fatal under tolerant parsing.
///
/// Under [`crate::parse::parse_module`] the scan continues. Strict callers that
/// use [`crate::parse::parse_module_strict`] or
/// [`crate::parse::ParseModuleResult::into_result`] treat any diagnostic as
/// [`crate::parse::ParseModuleError`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseDiagnostic {
    /// Machine-readable reason for the diagnostic.
    pub kind: ParseDiagnosticKind,
    /// Human-readable presentation message. Use [`Self::kind`] for logic.
    pub message: String,
    pub pos: Pos,
    /// Byte span of the offending region. The end is the actionable addition
    /// over `pos`-alone; zero-width when only a point is known (lex errors,
    /// EOF).
    pub span: Span,
    pub category: DiagnosticCategory,
}

impl ParseDiagnostic {
    #[must_use]
    pub fn new(
        kind: ParseDiagnosticKind,
        message: impl Into<String>,
        pos: Pos,
        span: Span,
    ) -> Self {
        let category = kind.category();
        Self {
            kind,
            message: message.into(),
            pos,
            span,
            category,
        }
    }

    /// Human-readable presentation message.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Machine-readable diagnostic reason.
    #[must_use]
    pub const fn kind(&self) -> &ParseDiagnosticKind {
        &self.kind
    }

    /// Coarse recovery category.
    #[must_use]
    pub const fn category(&self) -> DiagnosticCategory {
        self.category
    }
}

impl std::fmt::Display for ParseDiagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.message.fmt(f)
    }
}

impl std::error::Error for ParseDiagnostic {}

impl Expr {
    #[must_use]
    pub const fn pos(&self) -> Pos {
        match self {
            Self::Var { pos, .. }
            | Self::Con { pos, .. }
            | Self::Lit { pos, .. }
            | Self::App { pos, .. }
            | Self::BinOp { pos, .. }
            | Self::Neg { pos, .. }
            | Self::Lambda { pos, .. }
            | Self::If { pos, .. }
            | Self::Case { pos, .. }
            | Self::Do { pos, .. }
            | Self::LetIn { pos, .. }
            | Self::Record { pos, .. }
            | Self::Tuple { pos, .. }
            | Self::List { pos, .. }
            | Self::Try { pos, .. }
            | Self::OperatorRef { pos, .. }
            | Self::LeftSection { pos, .. }
            | Self::RightSection { pos, .. }
            | Self::Error { pos, .. } => *pos,
        }
    }

    /// Byte span covering the whole expression.
    #[must_use]
    pub const fn span(&self) -> Span {
        match self {
            Self::Var { span, .. }
            | Self::Con { span, .. }
            | Self::Lit { span, .. }
            | Self::App { span, .. }
            | Self::BinOp { span, .. }
            | Self::Neg { span, .. }
            | Self::Lambda { span, .. }
            | Self::If { span, .. }
            | Self::Case { span, .. }
            | Self::Do { span, .. }
            | Self::LetIn { span, .. }
            | Self::Record { span, .. }
            | Self::Tuple { span, .. }
            | Self::List { span, .. }
            | Self::Try { span, .. }
            | Self::OperatorRef { span, .. }
            | Self::LeftSection { span, .. }
            | Self::RightSection { span, .. }
            | Self::Error { span, .. } => *span,
        }
    }

    /// Render back to compact, source-*like* text for diagnostics and `raw`
    /// fields.
    ///
    /// This is **lossy and normalizing**, not byte-faithful: original layout is
    /// dropped (e.g. `do`/`let` statements are joined with `; `), operators and
    /// spacing are normalized, and comments/trivia are gone. Use it for a quick
    /// human-readable echo of an expression; for source-exact reconstruction use
    /// the node's [`span`](Self::span) into the original text (that is how
    /// `daml-fmt` and [`crate::ast_span::render_from_ast`] stay lossless).
    #[must_use]
    pub fn render(&self) -> String {
        match self {
            Self::Var {
                qualifier, name, ..
            }
            | Self::Con {
                qualifier, name, ..
            } => qualifier
                .as_ref()
                .map_or_else(|| name.to_string(), |q| format!("{q}.{name}")),
            Self::Lit { kind, text, .. } => match kind {
                LitKind::Text => format!("{text:?}"),
                LitKind::Char => format!("'{text}'"),
                _ => text.clone(),
            },
            Self::App { func, args, .. } => {
                let mut s = func.render_atomic();
                for a in args {
                    s.push(' ');
                    s.push_str(&a.render_atomic());
                }
                s
            }
            Self::BinOp { op, lhs, rhs, .. } => {
                if *op == "." {
                    // Record projection / composition: `account.custodian`.
                    format!("{}.{}", lhs.render_atomic(), rhs.render_atomic())
                } else {
                    format!("{} {} {}", lhs.render_atomic(), op, rhs.render_atomic())
                }
            }
            Self::Neg { expr, .. } => format!("-{}", expr.render_atomic()),
            Self::Lambda { params, body, .. } => {
                let ps: Vec<String> = params.iter().map(|p| p.render()).collect();
                format!("\\{} -> {}", ps.join(" "), body.render())
            }
            Self::If {
                cond,
                then_branch,
                else_branch,
                ..
            } => format!(
                "if {} then {} else {}",
                cond.render(),
                then_branch.render(),
                else_branch.render()
            ),
            Self::Case {
                scrutinee, alts, ..
            } => {
                let arms: Vec<String> = alts.iter().map(render_alt).collect();
                format!("case {} of {}", scrutinee.render(), arms.join("; "))
            }
            Self::Do { stmts, .. } => {
                let body: Vec<String> = stmts.iter().map(render_do_stmt).collect();
                format!("do {}", body.join("; "))
            }
            Self::LetIn { bindings, body, .. } => {
                let bs: Vec<String> = bindings.iter().map(render_binding).collect();
                format!("let {} in {}", bs.join("; "), body.render())
            }
            Self::Record { base, fields, .. } => {
                let fs: Vec<String> = fields
                    .iter()
                    .map(|f| match f {
                        FieldAssign::Assign { name, value, .. } => {
                            format!("{} = {}", name, value.render())
                        }
                        FieldAssign::Pun { name, .. } => name.to_string(),
                        FieldAssign::Wildcard { .. } => "..".to_string(),
                    })
                    .collect();
                format!("{} with {}", base.render_atomic(), fs.join("; "))
            }
            Self::Tuple { items, .. } => {
                let xs: Vec<String> = items.iter().map(|e| e.render()).collect();
                format!("({})", xs.join(", "))
            }
            Self::List { items, .. } => {
                let xs: Vec<String> = items.iter().map(|e| e.render()).collect();
                format!("[{}]", xs.join(", "))
            }
            Self::Try { body, handlers, .. } => {
                let hs: Vec<String> = handlers.iter().map(render_alt).collect();
                format!("try {} catch {}", body.render(), hs.join("; "))
            }
            Self::OperatorRef { op, .. } => format!("({op})"),
            Self::LeftSection { op, operand, .. } => format!("({} {})", operand.render(), op),
            Self::RightSection { op, operand, .. } => format!("({} {})", op, operand.render()),
            Self::Error { raw, .. } => raw.clone(),
        }
    }

    /// Render with parentheses if this expression wouldn't survive as an
    /// application argument.
    fn render_atomic(&self) -> String {
        match self {
            Self::Var { .. }
            | Self::Con { .. }
            | Self::Lit { .. }
            | Self::Tuple { .. }
            | Self::List { .. }
            | Self::OperatorRef { .. }
            | Self::LeftSection { .. }
            | Self::RightSection { .. }
            | Self::Error { .. } => self.render(),
            _ => format!("({})", self.render()),
        }
    }

    /// The head of an application spine: for `Foo.exercise cid X`, the
    /// `Foo.exercise` Var. For non-apps, the expression itself.
    #[must_use]
    pub fn application_head(&self) -> &Self {
        match self {
            Self::App { func, .. } => func.application_head(),
            _ => self,
        }
    }

    /// Application arguments, empty for non-apps. The `App` spine is flattened
    /// (see the [`App`](Self::App) variant), so for `f a b c` this returns all
    /// three arguments `[a, b, c]`, not a single curried layer.
    #[must_use]
    pub fn application_args(&self) -> &[Self] {
        match self {
            Self::App { args, .. } => args,
            _ => &[],
        }
    }
}

fn render_guard_qualifier(guard: &GuardQualifier) -> String {
    match guard {
        GuardQualifier::Bool { expr, .. } => expr.render(),
        GuardQualifier::Pattern { pat, expr, .. } => {
            format!("{} <- {}", pat.render(), expr.render())
        }
    }
}

fn render_alt(alt: &Alt) -> String {
    let mut rendered = if alt.branches.len() == 1 && alt.branches[0].guards.is_empty() {
        format!("{} -> {}", alt.pat.render(), alt.branches[0].body.render())
    } else {
        let mut parts = vec![alt.pat.render()];
        for branch in &alt.branches {
            let guards: Vec<String> = branch.guards.iter().map(render_guard_qualifier).collect();
            parts.push(format!(
                "| {} -> {}",
                guards.join(", "),
                branch.body.render()
            ));
        }
        parts.join(" ")
    };
    if !alt.where_bindings.is_empty() {
        use std::fmt::Write;
        let bindings: Vec<String> = alt.where_bindings.iter().map(render_binding).collect();
        let _ = write!(rendered, " where {}", bindings.join("; "));
    }
    rendered
}

fn render_do_stmt(s: &DoStmt) -> String {
    match s {
        DoStmt::Bind { pat, expr, .. } => format!("{} <- {}", pat.render(), expr.render()),
        DoStmt::Let { bindings, .. } => {
            let bs: Vec<String> = bindings.iter().map(render_binding).collect();
            format!("let {}", bs.join("; "))
        }
        DoStmt::Expr { expr, .. } => expr.render(),
    }
}

fn render_binding(b: &Binding) -> String {
    let mut s = b.pat.render();
    for p in &b.params {
        s.push(' ');
        s.push_str(&p.render());
    }
    format!("{} = {}", s, b.expr.render())
}

impl Pat {
    #[must_use]
    pub const fn pos(&self) -> Pos {
        match self {
            Self::Var { pos, .. }
            | Self::Wild { pos, .. }
            | Self::Con { pos, .. }
            | Self::Record { pos, .. }
            | Self::Tuple { pos, .. }
            | Self::List { pos, .. }
            | Self::Lit { pos, .. }
            | Self::As { pos, .. }
            | Self::Other { pos, .. } => *pos,
        }
    }

    /// Byte span covering the whole pattern.
    #[must_use]
    pub const fn span(&self) -> Span {
        match self {
            Self::Var { span, .. }
            | Self::Wild { span, .. }
            | Self::Con { span, .. }
            | Self::Record { span, .. }
            | Self::Tuple { span, .. }
            | Self::List { span, .. }
            | Self::Lit { span, .. }
            | Self::As { span, .. }
            | Self::Other { span, .. } => *span,
        }
    }

    /// Render back to compact, source-*like* text. Lossy and normalizing in the
    /// same way as [`Expr::render`]; use the node's [`span`](Self::span) for
    /// byte-faithful text.
    #[must_use]
    pub fn render(&self) -> String {
        match self {
            Self::Var { name, .. } => name.to_string(),
            Self::Wild { .. } => "_".to_string(),
            Self::Con {
                qualifier,
                name,
                args,
                ..
            } => {
                let head = qualifier
                    .as_ref()
                    .map_or_else(|| name.to_string(), |q| format!("{q}.{name}"));
                if args.is_empty() {
                    head
                } else {
                    let parts: Vec<String> = args.iter().map(|p| p.render()).collect();
                    format!("({} {})", head, parts.join(" "))
                }
            }
            Self::Record {
                qualifier,
                name,
                syntax,
                fields,
                ..
            } => {
                let head = qualifier
                    .as_ref()
                    .map_or_else(|| name.to_string(), |q| format!("{q}.{name}"));
                let fs: Vec<String> = fields
                    .iter()
                    .map(|f| match f {
                        PatFieldAssign::Assign { name, pat, .. } => {
                            format!("{} = {}", name, pat.render())
                        }
                        PatFieldAssign::Pun { name, .. } => name.to_string(),
                        PatFieldAssign::Wildcard { .. } => "..".to_string(),
                    })
                    .collect();
                match syntax {
                    RecordPatternSyntax::Braces => format!("{} {{ {} }}", head, fs.join(", ")),
                    RecordPatternSyntax::With => format!("{} with {}", head, fs.join("; ")),
                }
            }
            Self::Tuple { items, .. } => {
                let xs: Vec<String> = items.iter().map(|p| p.render()).collect();
                format!("({})", xs.join(", "))
            }
            Self::List { items, .. } => {
                let xs: Vec<String> = items.iter().map(|p| p.render()).collect();
                format!("[{}]", xs.join(", "))
            }
            Self::Lit { kind, text, .. } => match kind {
                LitKind::Text => format!("{text:?}"),
                LitKind::Char => format!("'{text}'"),
                _ => text.clone(),
            },
            Self::As { name, pat, .. } => format!("{}@{}", name, pat.render()),
            Self::Other { raw, .. } => raw.clone(),
        }
    }
}

impl std::fmt::Display for Expr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.render())
    }
}

impl std::fmt::Display for Pat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.render())
    }
}

// Span invariants for the lossless AST tile layer; render-shape tests live in integration tests.
#[cfg(test)]
mod tests {
    use super::*;

    fn span(start: usize, end: usize) -> Span {
        Span::from_usize(start, end)
    }

    #[test]
    fn span_distinguishes_empty_from_invalid() {
        assert!(span(3, 3).is_valid());
        assert!(span(3, 3).is_empty());

        assert!(!span(4, 3).is_valid());
        assert!(!span(4, 3).is_empty());
    }

    #[test]
    fn contains_rejects_invalid_spans() {
        let parent = span(1, 10);

        assert!(parent.contains(&span(3, 7)));
        assert!(!parent.contains(&span(7, 3)));
        assert!(!span(10, 1).contains(&span(3, 7)));
    }

    #[test]
    fn span_range_and_get_share_source_bytes_safely() {
        let source = "foo: Int";

        assert_eq!(span(0, 3).range(), 0..3);
        assert_eq!(span(0, 3).get(source), Some("foo"));
        assert_eq!(span(3, 7).get(source), Some(": In"));
        assert!(span(3, 100).get(source).is_none());
    }
}