Skip to main content

daml_parser/
ast.rs

1//! Typed, lossless parse tree produced by the recursive-descent parser
2//! (src/parse.rs).
3//!
4//! Every node carries a source position and byte span. Downstream crates
5//! consume this tree directly: daml-fmt re-prints layout from the spans, and
6//! daml-lint lowers it onto its own rule-facing IR.
7
8pub use crate::lexer::Pos;
9
10/// Byte span of an AST node.
11///
12/// `[start, end)` into the original source, same basis as `Token::start`/
13/// `Token::end`. Covers every (non-virtual) token that belongs to the node —
14/// first token's `start` to last token's `end`.
15///
16/// Invariants the parser maintains (checked over the corpus by
17/// `render_from_ast`): a child's span is contained in its parent's span, and
18/// sibling spans are ordered and non-overlapping. Trivia (comments, blank
19/// lines) live *between* sibling spans.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub struct Span {
22    pub start: usize,
23    pub end: usize,
24}
25
26impl Span {
27    pub const fn new(start: usize, end: usize) -> Self {
28        Self { start, end }
29    }
30
31    pub const fn is_empty(&self) -> bool {
32        self.start >= self.end
33    }
34
35    /// `self` fully contains `other`.
36    pub const fn contains(&self, other: &Self) -> bool {
37        self.start <= other.start && other.end <= self.end
38    }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum LitKind {
43    Int,
44    Decimal,
45    Text,
46    Char,
47}
48
49#[derive(Debug, Clone)]
50pub struct FieldAssign {
51    pub name: String,
52    /// None for record puns (`Foo with owner` meaning `owner = owner`)
53    /// and `..` wildcards.
54    pub value: Option<Expr>,
55    pub pos: Pos,
56    pub span: Span,
57}
58
59#[derive(Debug, Clone)]
60pub struct Alt {
61    pub pat: Pat,
62    pub body: Expr,
63    pub pos: Pos,
64    pub span: Span,
65}
66
67#[derive(Debug, Clone)]
68pub struct Binding {
69    /// Left-hand side: a variable with parameters, or a destructuring pattern.
70    pub pat: Pat,
71    /// Parameter patterns when the LHS is a function binding (`f x y = ...`).
72    pub params: Vec<Pat>,
73    pub expr: Expr,
74    pub pos: Pos,
75    pub span: Span,
76}
77
78#[derive(Debug, Clone)]
79pub enum Pat {
80    Var {
81        name: String,
82        pos: Pos,
83        span: Span,
84    },
85    Wild {
86        pos: Pos,
87        span: Span,
88    },
89    Con {
90        qualifier: Option<String>,
91        name: String,
92        args: Vec<Self>,
93        pos: Pos,
94        span: Span,
95    },
96    Tuple {
97        items: Vec<Self>,
98        pos: Pos,
99        span: Span,
100    },
101    List {
102        items: Vec<Self>,
103        pos: Pos,
104        span: Span,
105    },
106    Lit {
107        kind: LitKind,
108        text: String,
109        pos: Pos,
110        span: Span,
111    },
112    /// `name@pat`
113    As {
114        name: String,
115        pat: Box<Self>,
116        pos: Pos,
117        span: Span,
118    },
119    /// Anything the parser couldn't classify; raw text preserved.
120    Other {
121        raw: String,
122        pos: Pos,
123        span: Span,
124    },
125}
126
127#[derive(Debug, Clone)]
128pub enum Expr {
129    /// Lowercase variable reference, possibly qualified.
130    Var {
131        qualifier: Option<String>,
132        name: String,
133        pos: Pos,
134        span: Span,
135    },
136    /// Constructor / data-constructor reference, possibly qualified.
137    Con {
138        qualifier: Option<String>,
139        name: String,
140        pos: Pos,
141        span: Span,
142    },
143    Lit {
144        kind: LitKind,
145        text: String,
146        pos: Pos,
147        span: Span,
148    },
149    /// Application, flattened: `f a b c` is one App with three args.
150    App {
151        func: Box<Self>,
152        args: Vec<Self>,
153        pos: Pos,
154        span: Span,
155    },
156    /// Binary operator application with source-level operator text.
157    BinOp {
158        op: String,
159        lhs: Box<Self>,
160        rhs: Box<Self>,
161        pos: Pos,
162        span: Span,
163    },
164    /// Unary negation.
165    Neg {
166        expr: Box<Self>,
167        pos: Pos,
168        span: Span,
169    },
170    Lambda {
171        params: Vec<Pat>,
172        body: Box<Self>,
173        pos: Pos,
174        span: Span,
175    },
176    If {
177        cond: Box<Self>,
178        then_branch: Box<Self>,
179        else_branch: Box<Self>,
180        pos: Pos,
181        span: Span,
182    },
183    Case {
184        scrutinee: Box<Self>,
185        alts: Vec<Alt>,
186        pos: Pos,
187        span: Span,
188    },
189    Do {
190        stmts: Vec<DoStmt>,
191        pos: Pos,
192        span: Span,
193    },
194    LetIn {
195        bindings: Vec<Binding>,
196        body: Box<Self>,
197        pos: Pos,
198        span: Span,
199    },
200    /// `base with f = e, ...` — record construction when base is a Con,
201    /// record update otherwise.
202    Record {
203        base: Box<Self>,
204        fields: Vec<FieldAssign>,
205        pos: Pos,
206        span: Span,
207    },
208    Tuple {
209        items: Vec<Self>,
210        pos: Pos,
211        span: Span,
212    },
213    List {
214        items: Vec<Self>,
215        pos: Pos,
216        span: Span,
217    },
218    /// `try <body> catch <alts>`
219    Try {
220        body: Box<Self>,
221        handlers: Vec<Alt>,
222        pos: Pos,
223        span: Span,
224    },
225    /// Right operator section like `(+ 1)` / left section `(1 +)`.
226    Section {
227        op: String,
228        operand: Option<Box<Self>>,
229        left: bool,
230        pos: Pos,
231        span: Span,
232    },
233    /// Expression the parser could not understand; raw text preserved so
234    /// a parse failure degrades to the shim's behavior instead of dying.
235    Error { raw: String, pos: Pos, span: Span },
236}
237
238#[derive(Debug, Clone)]
239pub enum DoStmt {
240    /// `pat <- expr`
241    Bind {
242        pat: Pat,
243        expr: Expr,
244        pos: Pos,
245        span: Span,
246    },
247    /// `let x = e` (no `in`) inside a do block.
248    Let {
249        bindings: Vec<Binding>,
250        pos: Pos,
251        span: Span,
252    },
253    /// Bare expression statement.
254    Expr { expr: Expr, pos: Pos, span: Span },
255}
256
257/// Structured Daml type, parsed from the real token stream.
258///
259/// Scoped to the forms the corpus actually contains; it exists so consumers can
260/// tell a type *application* from a *function arrow* from an
261/// atomic constructor — a distinction a string matcher structurally cannot make.
262/// Every node carries a byte span so consumers can render exact source text from
263/// `(source, span)`.
264#[derive(Debug, Clone)]
265pub enum Type {
266    /// Type constructor, possibly qualified: `Party`, `DA.Map.Map`.
267    Con {
268        qualifier: Option<String>,
269        name: String,
270        span: Span,
271    },
272    /// Type application, head applied to one or more args: `ContractId Foo`,
273    /// `Map Text Int`, `Script ()`. Type-level nat literals (the `10` in
274    /// `Numeric 10`) are NOT types, so they are dropped from the arg list — a
275    /// `Numeric 10` collapses to the bare head `Con "Numeric"`.
276    App(Box<Self>, Vec<Self>, Span),
277    /// List type `[T]`.
278    List(Box<Self>, Span),
279    /// Tuple type `(a, b, ...)`.
280    Tuple(Vec<Self>, Span),
281    /// Function type `a -> b` (right-associative).
282    Fun(Box<Self>, Box<Self>, Span),
283    /// Lowercase type variable: `a`, `n`.
284    Var(String, Span),
285    /// The unit type `()`.
286    Unit(Span),
287    /// A constrained type `C a => T`: the context is not modeled, the body `T`
288    /// is kept.
289    Constrained(Box<Self>, Span),
290}
291
292impl Type {
293    pub const fn span(&self) -> Span {
294        match self {
295            Self::Con { span, .. }
296            | Self::App(_, _, span)
297            | Self::List(_, span)
298            | Self::Tuple(_, span)
299            | Self::Fun(_, _, span)
300            | Self::Var(_, span)
301            | Self::Unit(span)
302            | Self::Constrained(_, span) => *span,
303        }
304    }
305
306    pub(crate) const fn with_span(mut self, span: Span) -> Self {
307        match &mut self {
308            Self::Con { span: s, .. }
309            | Self::App(_, _, s)
310            | Self::List(_, s)
311            | Self::Tuple(_, s)
312            | Self::Fun(_, _, s)
313            | Self::Var(_, s)
314            | Self::Unit(s)
315            | Self::Constrained(_, s) => *s = span,
316        }
317        self
318    }
319}
320
321impl PartialEq for Type {
322    fn eq(&self, other: &Self) -> bool {
323        match (self, other) {
324            (
325                Self::Con {
326                    qualifier: aq,
327                    name: an,
328                    ..
329                },
330                Self::Con {
331                    qualifier: bq,
332                    name: bn,
333                    ..
334                },
335            ) => aq == bq && an == bn,
336            (Self::App(ah, aa, _), Self::App(bh, ba, _)) => ah == bh && aa == ba,
337            (Self::List(a, _), Self::List(b, _)) => a == b,
338            (Self::Tuple(a, _), Self::Tuple(b, _)) => a == b,
339            (Self::Fun(al, ar, _), Self::Fun(bl, br, _)) => al == bl && ar == br,
340            (Self::Var(a, _), Self::Var(b, _)) => a == b,
341            (Self::Unit(_), Self::Unit(_)) => true,
342            (Self::Constrained(a, _), Self::Constrained(b, _)) => a == b,
343            _ => false,
344        }
345    }
346}
347
348#[derive(Debug, Clone)]
349pub struct FieldDecl {
350    pub name: String,
351    /// Structured field type parsed from the token stream. `None` when the type
352    /// could not be parsed cleanly (analysis treats it as unknown).
353    pub ty: Option<Type>,
354    pub pos: Pos,
355    pub span: Span,
356}
357
358#[derive(Debug, Clone, Copy, PartialEq, Eq)]
359pub enum Consuming {
360    Consuming,
361    NonConsuming,
362    PreConsuming,
363    PostConsuming,
364}
365
366#[derive(Debug, Clone)]
367pub struct ChoiceDecl {
368    pub name: String,
369    pub consuming: Consuming,
370    /// Structured return type. `None` if it could not be parsed cleanly or the
371    /// choice declared no return type.
372    pub return_ty: Option<Type>,
373    pub params: Vec<FieldDecl>,
374    /// Comma-separated controller expressions.
375    pub controllers: Vec<Expr>,
376    /// Choice observers, if any.
377    pub observers: Vec<Expr>,
378    pub body: Option<Expr>,
379    pub pos: Pos,
380    pub span: Span,
381}
382
383#[derive(Debug, Clone)]
384pub enum TemplateBodyDecl {
385    Signatory {
386        parties: Vec<Expr>,
387        pos: Pos,
388        span: Span,
389    },
390    Observer {
391        parties: Vec<Expr>,
392        pos: Pos,
393        span: Span,
394    },
395    Ensure {
396        expr: Expr,
397        pos: Pos,
398        span: Span,
399    },
400    Key {
401        expr: Expr,
402        /// Structured key type. `None` if absent or not cleanly parseable.
403        ty: Option<Type>,
404        pos: Pos,
405        span: Span,
406    },
407    Maintainer {
408        expr: Expr,
409        pos: Pos,
410        span: Span,
411    },
412    Choice(ChoiceDecl),
413    InterfaceInstance(InterfaceInstanceDecl),
414    /// `agreement`, `let` blocks, deprecated `controller ... can`, etc.
415    Other {
416        raw: String,
417        pos: Pos,
418        span: Span,
419    },
420}
421
422#[derive(Debug, Clone)]
423pub struct InterfaceInstanceDecl {
424    /// Interface being implemented (`Disclosure.I`).
425    pub interface_name: String,
426    /// Template it is for (from `for Foo`); the enclosing template when
427    /// declared inside one.
428    pub for_template: String,
429    /// Method implementations: name → bound expression.
430    pub methods: Vec<Binding>,
431    pub pos: Pos,
432    pub span: Span,
433}
434
435#[derive(Debug, Clone)]
436pub struct TemplateDecl {
437    pub name: String,
438    pub fields: Vec<FieldDecl>,
439    pub body: Vec<TemplateBodyDecl>,
440    pub pos: Pos,
441    pub span: Span,
442}
443
444#[derive(Debug, Clone)]
445pub struct InterfaceDecl {
446    pub name: String,
447    /// Interfaces this interface requires (`requires Lockable.I, ...`).
448    pub requires: Vec<String>,
449    pub viewtype: Option<String>,
450    /// Method signatures: name and type text.
451    pub methods: Vec<FieldDecl>,
452    pub choices: Vec<ChoiceDecl>,
453    pub pos: Pos,
454    pub span: Span,
455}
456
457#[derive(Debug, Clone)]
458pub struct Equation {
459    pub params: Vec<Pat>,
460    pub body: Expr,
461    /// Guarded equations keep their guards as (guard, body) pairs; `body`
462    /// then holds the first guarded body for convenience.
463    pub guards: Vec<(Expr, Expr)>,
464    /// `where` helper bindings attached to this equation.
465    pub where_bindings: Vec<Binding>,
466    pub pos: Pos,
467    pub span: Span,
468}
469
470#[derive(Debug, Clone)]
471pub struct FunctionDecl {
472    pub name: String,
473    pub ty: Option<Type>,
474    pub equations: Vec<Equation>,
475    pub pos: Pos,
476    /// Span of the function's first appearance (signature or first equation).
477    /// Convenience anchor; a multi-equation function's precise ranges are the
478    /// per-`Equation` spans, since equations need not be contiguous in source.
479    pub span: Span,
480    /// Span of the standalone type signature `name : Type`, if one was seen.
481    pub sig_span: Option<Span>,
482}
483
484#[derive(Debug, Clone)]
485pub struct ImportDecl {
486    pub module_name: String,
487    pub qualified: bool,
488    pub alias: Option<String>,
489    pub pos: Pos,
490    pub span: Span,
491}
492
493#[derive(Debug, Clone)]
494pub enum Decl {
495    Template(TemplateDecl),
496    Interface(InterfaceDecl),
497    Function(FunctionDecl),
498    /// data/type/class/instance/exception — recorded with name + span.
499    TypeDef {
500        keyword: String,
501        name: String,
502        pos: Pos,
503        span: Span,
504    },
505    /// Anything unparseable at the top level (diagnostic already emitted).
506    Unknown {
507        raw: String,
508        pos: Pos,
509        span: Span,
510    },
511}
512
513#[derive(Debug, Clone)]
514pub struct Module {
515    pub name: String,
516    pub pos: Pos,
517    /// Whole-module extent: `[0, source.len())`. Container for all decls.
518    pub span: Span,
519    /// Span of the `module M (...) where` header clause; empty when the file
520    /// has no module header. Lets the span oracle treat header tokens as
521    /// covered without a dedicated header node.
522    pub header: Span,
523    pub imports: Vec<ImportDecl>,
524    pub decls: Vec<Decl>,
525}
526
527/// Why a [`ParseDiagnostic`] fired.
528///
529/// Lets a consumer separate syntax the parser deliberately does not model (still
530/// safe, just unanalyzed) from a genuine malformation, a recursion-limit
531/// degradation, or a lexical error.
532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
533pub enum DiagnosticCategory {
534    /// A whole declaration could not be parsed and was skipped to the next item.
535    SkippedDecl,
536    /// A malformed expression, pattern, or expected-token error inside an
537    /// otherwise-recognized construct.
538    Malformed,
539    /// A construct the parser intentionally does not support, e.g. legacy
540    /// `controller ... can` choice syntax.
541    UnsupportedSyntax,
542    /// Expression/pattern nesting exceeded the recursion bound and was degraded
543    /// to raw text.
544    RecursionLimit,
545    /// A lexical error (unterminated string/comment, stray character).
546    Lex,
547}
548
549impl DiagnosticCategory {
550    /// Stable kebab-case tag for machine-readable output (JSON/SARIF) and logs.
551    pub const fn as_str(self) -> &'static str {
552        match self {
553            Self::SkippedDecl => "skipped-declaration",
554            Self::Malformed => "malformed",
555            Self::UnsupportedSyntax => "unsupported-syntax",
556            Self::RecursionLimit => "recursion-limit",
557            Self::Lex => "lexical-error",
558        }
559    }
560}
561
562/// Parse diagnostic — never fatal; the scan continues.
563#[derive(Debug, Clone)]
564pub struct ParseDiagnostic {
565    pub message: String,
566    pub pos: Pos,
567    /// Byte span of the offending region. The end is the actionable addition
568    /// over `pos`-alone; zero-width when only a point is known (lex errors,
569    /// EOF).
570    pub span: Span,
571    pub category: DiagnosticCategory,
572}
573
574impl Expr {
575    pub const fn pos(&self) -> Pos {
576        match self {
577            Self::Var { pos, .. }
578            | Self::Con { pos, .. }
579            | Self::Lit { pos, .. }
580            | Self::App { pos, .. }
581            | Self::BinOp { pos, .. }
582            | Self::Neg { pos, .. }
583            | Self::Lambda { pos, .. }
584            | Self::If { pos, .. }
585            | Self::Case { pos, .. }
586            | Self::Do { pos, .. }
587            | Self::LetIn { pos, .. }
588            | Self::Record { pos, .. }
589            | Self::Tuple { pos, .. }
590            | Self::List { pos, .. }
591            | Self::Try { pos, .. }
592            | Self::Section { pos, .. }
593            | Self::Error { pos, .. } => *pos,
594        }
595    }
596
597    /// Byte span covering the whole expression.
598    pub const fn span(&self) -> Span {
599        match self {
600            Self::Var { span, .. }
601            | Self::Con { span, .. }
602            | Self::Lit { span, .. }
603            | Self::App { span, .. }
604            | Self::BinOp { span, .. }
605            | Self::Neg { span, .. }
606            | Self::Lambda { span, .. }
607            | Self::If { span, .. }
608            | Self::Case { span, .. }
609            | Self::Do { span, .. }
610            | Self::LetIn { span, .. }
611            | Self::Record { span, .. }
612            | Self::Tuple { span, .. }
613            | Self::List { span, .. }
614            | Self::Try { span, .. }
615            | Self::Section { span, .. }
616            | Self::Error { span, .. } => *span,
617        }
618    }
619
620    /// Render back to compact source-like text (raw-field compatibility).
621    pub fn render(&self) -> String {
622        match self {
623            Self::Var {
624                qualifier, name, ..
625            }
626            | Self::Con {
627                qualifier, name, ..
628            } => qualifier
629                .as_ref()
630                .map_or_else(|| name.clone(), |q| format!("{}.{}", q, name)),
631            Self::Lit { kind, text, .. } => match kind {
632                LitKind::Text => format!("{:?}", text),
633                LitKind::Char => format!("'{}'", text),
634                _ => text.clone(),
635            },
636            Self::App { func, args, .. } => {
637                let mut s = func.render_atomic();
638                for a in args {
639                    s.push(' ');
640                    s.push_str(&a.render_atomic());
641                }
642                s
643            }
644            Self::BinOp { op, lhs, rhs, .. } => {
645                if op == "." {
646                    // Record projection / composition: `account.custodian`.
647                    format!("{}.{}", lhs.render_atomic(), rhs.render_atomic())
648                } else {
649                    format!("{} {} {}", lhs.render_atomic(), op, rhs.render_atomic())
650                }
651            }
652            Self::Neg { expr, .. } => format!("-{}", expr.render_atomic()),
653            Self::Lambda { params, body, .. } => {
654                let ps: Vec<String> = params.iter().map(|p| p.render()).collect();
655                format!("\\{} -> {}", ps.join(" "), body.render())
656            }
657            Self::If {
658                cond,
659                then_branch,
660                else_branch,
661                ..
662            } => format!(
663                "if {} then {} else {}",
664                cond.render(),
665                then_branch.render(),
666                else_branch.render()
667            ),
668            Self::Case {
669                scrutinee, alts, ..
670            } => {
671                let arms: Vec<String> = alts
672                    .iter()
673                    .map(|a| format!("{} -> {}", a.pat.render(), a.body.render()))
674                    .collect();
675                format!("case {} of {}", scrutinee.render(), arms.join("; "))
676            }
677            Self::Do { stmts, .. } => {
678                let body: Vec<String> = stmts.iter().map(render_do_stmt).collect();
679                format!("do {}", body.join("; "))
680            }
681            Self::LetIn { bindings, body, .. } => {
682                let bs: Vec<String> = bindings.iter().map(render_binding).collect();
683                format!("let {} in {}", bs.join("; "), body.render())
684            }
685            Self::Record { base, fields, .. } => {
686                let fs: Vec<String> = fields
687                    .iter()
688                    .map(|f| {
689                        f.value.as_ref().map_or_else(
690                            || f.name.clone(),
691                            |v| format!("{} = {}", f.name, v.render()),
692                        )
693                    })
694                    .collect();
695                format!("{} with {}", base.render_atomic(), fs.join("; "))
696            }
697            Self::Tuple { items, .. } => {
698                let xs: Vec<String> = items.iter().map(|e| e.render()).collect();
699                format!("({})", xs.join(", "))
700            }
701            Self::List { items, .. } => {
702                let xs: Vec<String> = items.iter().map(|e| e.render()).collect();
703                format!("[{}]", xs.join(", "))
704            }
705            Self::Try { body, handlers, .. } => {
706                let hs: Vec<String> = handlers
707                    .iter()
708                    .map(|a| format!("{} -> {}", a.pat.render(), a.body.render()))
709                    .collect();
710                format!("try {} catch {}", body.render(), hs.join("; "))
711            }
712            Self::Section {
713                op, operand, left, ..
714            } => match (operand, left) {
715                (Some(e), true) => format!("({} {})", e.render(), op),
716                (Some(e), false) => format!("({} {})", op, e.render()),
717                (None, _) => format!("({})", op),
718            },
719            Self::Error { raw, .. } => raw.clone(),
720        }
721    }
722
723    /// Render with parentheses if this expression wouldn't survive as an
724    /// application argument.
725    fn render_atomic(&self) -> String {
726        match self {
727            Self::Var { .. }
728            | Self::Con { .. }
729            | Self::Lit { .. }
730            | Self::Tuple { .. }
731            | Self::List { .. }
732            | Self::Section { .. }
733            | Self::Error { .. } => self.render(),
734            _ => format!("({})", self.render()),
735        }
736    }
737
738    /// The head of an application spine: for `Foo.exercise cid X`, the
739    /// `Foo.exercise` Var. For non-apps, the expression itself.
740    pub fn application_head(&self) -> &Self {
741        match self {
742            Self::App { func, .. } => func.application_head(),
743            _ => self,
744        }
745    }
746
747    /// Application arguments, empty for non-apps.
748    pub fn application_args(&self) -> &[Self] {
749        match self {
750            Self::App { args, .. } => args,
751            _ => &[],
752        }
753    }
754}
755
756fn render_do_stmt(s: &DoStmt) -> String {
757    match s {
758        DoStmt::Bind { pat, expr, .. } => format!("{} <- {}", pat.render(), expr.render()),
759        DoStmt::Let { bindings, .. } => {
760            let bs: Vec<String> = bindings.iter().map(render_binding).collect();
761            format!("let {}", bs.join("; "))
762        }
763        DoStmt::Expr { expr, .. } => expr.render(),
764    }
765}
766
767fn render_binding(b: &Binding) -> String {
768    let mut s = b.pat.render();
769    for p in &b.params {
770        s.push(' ');
771        s.push_str(&p.render());
772    }
773    format!("{} = {}", s, b.expr.render())
774}
775
776impl Pat {
777    pub const fn pos(&self) -> Pos {
778        match self {
779            Self::Var { pos, .. }
780            | Self::Wild { pos, .. }
781            | Self::Con { pos, .. }
782            | Self::Tuple { pos, .. }
783            | Self::List { pos, .. }
784            | Self::Lit { pos, .. }
785            | Self::As { pos, .. }
786            | Self::Other { pos, .. } => *pos,
787        }
788    }
789
790    /// Byte span covering the whole pattern.
791    pub const fn span(&self) -> Span {
792        match self {
793            Self::Var { span, .. }
794            | Self::Wild { span, .. }
795            | Self::Con { span, .. }
796            | Self::Tuple { span, .. }
797            | Self::List { span, .. }
798            | Self::Lit { span, .. }
799            | Self::As { span, .. }
800            | Self::Other { span, .. } => *span,
801        }
802    }
803
804    pub fn render(&self) -> String {
805        match self {
806            Self::Var { name, .. } => name.clone(),
807            Self::Wild { .. } => "_".to_string(),
808            Self::Con {
809                qualifier,
810                name,
811                args,
812                ..
813            } => {
814                let head = qualifier
815                    .as_ref()
816                    .map_or_else(|| name.clone(), |q| format!("{}.{}", q, name));
817                if args.is_empty() {
818                    head
819                } else {
820                    let parts: Vec<String> = args.iter().map(|p| p.render()).collect();
821                    format!("({} {})", head, parts.join(" "))
822                }
823            }
824            Self::Tuple { items, .. } => {
825                let xs: Vec<String> = items.iter().map(|p| p.render()).collect();
826                format!("({})", xs.join(", "))
827            }
828            Self::List { items, .. } => {
829                let xs: Vec<String> = items.iter().map(|p| p.render()).collect();
830                format!("[{}]", xs.join(", "))
831            }
832            Self::Lit { kind, text, .. } => match kind {
833                LitKind::Text => format!("{:?}", text),
834                LitKind::Char => format!("'{}'", text),
835                _ => text.clone(),
836            },
837            Self::As { name, pat, .. } => format!("{}@{}", name, pat.render()),
838            Self::Other { raw, .. } => raw.clone(),
839        }
840    }
841}