daml-parser 0.5.0

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
//! Typed, lossless parse tree produced by the recursive-descent parser
//! (src/parse.rs).
//!
//! Every node carries a source position and byte span. 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.

pub use crate::lexer::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, Default)]
pub struct Span {
    pub start: usize,
    pub end: usize,
}

impl Span {
    pub const fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

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

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

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

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LitKind {
    Int,
    Decimal,
    Text,
    Char,
}

/// Side of an operator section.
///
/// `(+ 1)` stores `SectionSide::Right`, while `(1 +)` stores
/// `SectionSide::Left`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SectionSide {
    /// Right section: operator followed by right operand.
    Right,
    /// Left section: left operand followed by operator.
    Left,
}

/// 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)]
pub struct FieldAssign {
    pub name: String,
    /// None for record puns (`Foo with owner` meaning `owner = owner`)
    /// and `..` wildcards.
    pub value: Option<Expr>,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct Alt {
    pub pat: Pat,
    pub body: Expr,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone)]
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>,
    pub expr: Expr,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Pat {
    Var {
        name: String,
        pos: Pos,
        span: Span,
    },
    Wild {
        pos: Pos,
        span: Span,
    },
    Con {
        qualifier: Option<String>,
        name: String,
        args: Vec<Self>,
        pos: Pos,
        span: Span,
    },
    Tuple {
        items: Vec<Self>,
        pos: Pos,
        span: Span,
    },
    List {
        items: Vec<Self>,
        pos: Pos,
        span: Span,
    },
    Lit {
        kind: LitKind,
        text: String,
        pos: Pos,
        span: Span,
    },
    /// `name@pat`
    As {
        name: String,
        pat: Box<Self>,
        pos: Pos,
        span: Span,
    },
    /// Anything the parser couldn't classify; raw text preserved.
    Other {
        raw: String,
        pos: Pos,
        span: Span,
    },
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Expr {
    /// Lowercase variable reference, possibly qualified.
    Var {
        qualifier: Option<String>,
        name: String,
        pos: Pos,
        span: Span,
    },
    /// Constructor / data-constructor reference, possibly qualified.
    Con {
        qualifier: Option<String>,
        name: String,
        pos: Pos,
        span: Span,
    },
    Lit {
        kind: LitKind,
        text: String,
        pos: Pos,
        span: Span,
    },
    /// Application, flattened: `f a b c` is one App with three args.
    App {
        func: Box<Self>,
        args: Vec<Self>,
        pos: Pos,
        span: Span,
    },
    /// Binary operator application with source-level operator text.
    BinOp {
        op: String,
        lhs: Box<Self>,
        rhs: Box<Self>,
        pos: Pos,
        span: Span,
    },
    /// Unary negation.
    Neg {
        expr: Box<Self>,
        pos: Pos,
        span: Span,
    },
    Lambda {
        params: Vec<Pat>,
        body: Box<Self>,
        pos: Pos,
        span: Span,
    },
    If {
        cond: Box<Self>,
        then_branch: Box<Self>,
        else_branch: Box<Self>,
        pos: Pos,
        span: Span,
    },
    Case {
        scrutinee: Box<Self>,
        alts: Vec<Alt>,
        pos: Pos,
        span: Span,
    },
    Do {
        stmts: Vec<DoStmt>,
        pos: Pos,
        span: Span,
    },
    LetIn {
        bindings: Vec<Binding>,
        body: Box<Self>,
        pos: Pos,
        span: Span,
    },
    /// `base with f = e, ...` — record construction when base is a Con,
    /// record update otherwise.
    Record {
        base: Box<Self>,
        fields: Vec<FieldAssign>,
        pos: Pos,
        span: Span,
    },
    Tuple {
        items: Vec<Self>,
        pos: Pos,
        span: Span,
    },
    List {
        items: Vec<Self>,
        pos: Pos,
        span: Span,
    },
    /// `try <body> catch <alts>`
    Try {
        body: Box<Self>,
        handlers: Vec<Alt>,
        pos: Pos,
        span: Span,
    },
    /// Right operator section like `(+ 1)` / left section `(1 +)`.
    Section {
        op: String,
        operand: Option<Box<Self>>,
        side: SectionSide,
        pos: Pos,
        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: String, pos: Pos, span: Span },
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DoStmt {
    /// `pat <- expr`
    Bind {
        pat: Pat,
        expr: Expr,
        pos: Pos,
        span: Span,
    },
    /// `let x = e` (no `in`) inside a do block.
    Let {
        bindings: Vec<Binding>,
        pos: Pos,
        span: Span,
    },
    /// Bare expression statement.
    Expr { expr: Expr, pos: Pos, 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)`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Type {
    /// Type constructor, possibly qualified: `Party`, `DA.Map.Map`.
    Con {
        qualifier: Option<String>,
        name: String,
        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(String, 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),
}

impl Type {
    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) => *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) => *s = span,
        }
        self
    }
}

/// Type equality intentionally ignores source spans.
///
/// Spans describe where equivalent type syntax appeared in a source file; they
/// are not part of the 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,
            _ => false,
        }
    }
}

impl Eq for Type {}

#[derive(Debug, Clone)]
pub struct FieldDecl {
    pub name: String,
    /// Structured field type parsed from the token stream. `None` when the type
    /// could not be parsed cleanly (analysis treats it as unknown).
    pub ty: Option<Type>,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Consuming {
    Consuming,
    NonConsuming,
    PreConsuming,
    PostConsuming,
}

#[derive(Debug, Clone)]
pub struct ChoiceDecl {
    pub name: String,
    pub consuming: Consuming,
    /// Structured return type. `None` if it could not be parsed cleanly or the
    /// choice declared no return type.
    pub return_ty: Option<Type>,
    pub params: Vec<FieldDecl>,
    /// Comma-separated controller expressions.
    pub controllers: Vec<Expr>,
    /// Choice observers, if any.
    pub observers: Vec<Expr>,
    pub body: Option<Expr>,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub enum TemplateBodyDecl {
    Signatory {
        parties: Vec<Expr>,
        pos: Pos,
        span: Span,
    },
    Observer {
        parties: Vec<Expr>,
        pos: Pos,
        span: Span,
    },
    Ensure {
        expr: Expr,
        pos: Pos,
        span: Span,
    },
    Key {
        expr: Expr,
        /// Structured key type. `None` if absent or not cleanly parseable.
        ty: Option<Type>,
        pos: Pos,
        span: Span,
    },
    Maintainer {
        expr: Expr,
        pos: Pos,
        span: Span,
    },
    Choice(ChoiceDecl),
    InterfaceInstance(InterfaceInstanceDecl),
    /// `agreement`, `let` blocks, deprecated `controller ... can`, etc.
    Other {
        raw: String,
        pos: Pos,
        span: Span,
    },
}

#[derive(Debug, Clone)]
pub struct InterfaceInstanceDecl {
    /// Interface being implemented (`Disclosure.I`).
    pub interface_name: String,
    /// Template it is for (from `for Foo`); the enclosing template when
    /// declared inside one.
    pub for_template: String,
    /// Method implementations: name → bound expression.
    pub methods: Vec<Binding>,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct TemplateDecl {
    pub name: String,
    pub fields: Vec<FieldDecl>,
    pub body: Vec<TemplateBodyDecl>,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct InterfaceDecl {
    pub name: String,
    /// Interfaces this interface requires (`requires Lockable.I, ...`).
    pub requires: Vec<String>,
    pub viewtype: Option<String>,
    /// Method signatures: name and type text.
    pub methods: Vec<FieldDecl>,
    pub choices: Vec<ChoiceDecl>,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct Equation {
    pub params: Vec<Pat>,
    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>,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct FunctionDecl {
    pub name: String,
    pub ty: Option<Type>,
    pub equations: Vec<Equation>,
    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>,
}

#[derive(Debug, Clone)]
pub struct ImportDecl {
    pub module_name: String,
    pub style: ImportStyle,
    pub alias: Option<String>,
    pub pos: Pos,
    pub span: Span,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Decl {
    Template(TemplateDecl),
    Interface(InterfaceDecl),
    Function(FunctionDecl),
    /// data/type/class/instance/exception — recorded with name + span.
    TypeDef {
        keyword: String,
        name: String,
        pos: Pos,
        span: Span,
    },
    /// Anything unparseable at the top level (diagnostic already emitted).
    Unknown {
        raw: String,
        pos: Pos,
        span: Span,
    },
}

#[derive(Debug, Clone)]
pub struct Module {
    pub name: String,
    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,
    pub imports: Vec<ImportDecl>,
    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.
    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",
        }
    }
}

/// Parse diagnostic — never fatal; the scan continues.
#[derive(Debug, Clone)]
pub struct ParseDiagnostic {
    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 Expr {
    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::Section { pos, .. }
            | Self::Error { pos, .. } => *pos,
        }
    }

    /// Byte span covering the whole expression.
    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::Section { 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).
    pub fn render(&self) -> String {
        match self {
            Self::Var {
                qualifier, name, ..
            }
            | Self::Con {
                qualifier, name, ..
            } => qualifier
                .as_ref()
                .map_or_else(|| name.clone(), |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(|a| format!("{} -> {}", a.pat.render(), a.body.render()))
                    .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| {
                        f.value.as_ref().map_or_else(
                            || f.name.clone(),
                            |v| format!("{} = {}", f.name, v.render()),
                        )
                    })
                    .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(|a| format!("{} -> {}", a.pat.render(), a.body.render()))
                    .collect();
                format!("try {} catch {}", body.render(), hs.join("; "))
            }
            Self::Section {
                op, operand, side, ..
            } => match (operand, side) {
                (Some(e), SectionSide::Left) => format!("({} {})", e.render(), op),
                (Some(e), SectionSide::Right) => format!("({} {})", op, e.render()),
                (None, _) => format!("({op})"),
            },
            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::Section { .. }
            | 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.
    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.
    pub fn application_args(&self) -> &[Self] {
        match self {
            Self::App { args, .. } => args,
            _ => &[],
        }
    }
}

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 {
    pub const fn pos(&self) -> Pos {
        match self {
            Self::Var { pos, .. }
            | Self::Wild { pos, .. }
            | Self::Con { pos, .. }
            | Self::Tuple { pos, .. }
            | Self::List { pos, .. }
            | Self::Lit { pos, .. }
            | Self::As { pos, .. }
            | Self::Other { pos, .. } => *pos,
        }
    }

    /// Byte span covering the whole pattern.
    pub const fn span(&self) -> Span {
        match self {
            Self::Var { span, .. }
            | Self::Wild { span, .. }
            | Self::Con { 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.
    pub fn render(&self) -> String {
        match self {
            Self::Var { name, .. } => name.clone(),
            Self::Wild { .. } => "_".to_string(),
            Self::Con {
                qualifier,
                name,
                args,
                ..
            } => {
                let head = qualifier
                    .as_ref()
                    .map_or_else(|| name.clone(), |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::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())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pos() -> Pos {
        Pos { line: 1, column: 1 }
    }

    fn span(start: usize, end: usize) -> Span {
        Span::new(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 expr_render_keeps_normalized_application_and_projection_shape() {
        let projection = Expr::BinOp {
            op: ".".to_string(),
            lhs: Box::new(Expr::Var {
                qualifier: None,
                name: "this".to_string(),
                pos: pos(),
                span: span(0, 4),
            }),
            rhs: Box::new(Expr::Var {
                qualifier: None,
                name: "note".to_string(),
                pos: pos(),
                span: span(5, 9),
            }),
            pos: pos(),
            span: span(0, 9),
        };

        let expr = Expr::App {
            func: Box::new(Expr::Var {
                qualifier: None,
                name: "length".to_string(),
                pos: pos(),
                span: span(0, 6),
            }),
            args: vec![projection],
            pos: pos(),
            span: span(0, 16),
        };

        assert_eq!(expr.render(), "length (this.note)");
    }

    #[test]
    fn section_render_depends_on_section_side() {
        let expr_left = Expr::Section {
            op: "+".to_string(),
            operand: Some(Box::new(Expr::Var {
                qualifier: None,
                name: "x".to_string(),
                pos: pos(),
                span: span(0, 1),
            })),
            side: SectionSide::Left,
            pos: pos(),
            span: span(0, 4),
        };
        let expr_right = Expr::Section {
            op: "+".to_string(),
            operand: Some(Box::new(Expr::Lit {
                kind: LitKind::Int,
                text: "1".to_string(),
                pos: pos(),
                span: span(0, 1),
            })),
            side: SectionSide::Right,
            pos: pos(),
            span: span(0, 4),
        };

        assert_eq!(expr_left.render(), "(x +)");
        assert_eq!(expr_right.render(), "(+ 1)");
    }

    #[test]
    fn pat_render_preserves_collection_shape() {
        let pat = Pat::Tuple {
            items: vec![
                Pat::Var {
                    name: "owner".to_string(),
                    pos: pos(),
                    span: span(1, 6),
                },
                Pat::List {
                    items: Vec::new(),
                    pos: pos(),
                    span: span(8, 10),
                },
            ],
            pos: pos(),
            span: span(0, 11),
        };

        assert_eq!(pat.render(), "(owner, [])");
    }
}