Skip to main content

daml_parser/
ast_span.rs

1//! AST losslessness oracle for daml-fmt.
2//!
3//! Every AST node carries a byte `Span` (see `ast::Span`). This module proves
4//! those spans are faithful: it collects every node's span, checks they form a
5//! *laminar family* (each child contained in its parent, siblings ordered and
6//! disjoint — `ast::Span` invariants), and reconstructs the file by tiling the
7//! span forest with the verbatim source bytes that fall between sibling spans.
8//!
9//! If the spans nest correctly and the module span covers the file, the
10//! reconstruction is byte-identical to the source. A parser that dropped a
11//! token's bytes from every node span, or produced an overlap, fails here.
12
13use crate::ast::*;
14use crate::lexer::{Trivia, TriviaKind};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum AstSpanError {
19    InvalidSpan {
20        start: usize,
21        end: usize,
22    },
23    OverlappingSpans {
24        start: usize,
25        end: usize,
26        parent_start: usize,
27        parent_end: usize,
28    },
29    OverlappingTile {
30        start: usize,
31        end: usize,
32        previous_end: usize,
33    },
34    UncoveredBytes {
35        start: usize,
36        end: usize,
37        text: String,
38    },
39    UncoveredTail {
40        start: usize,
41        text: String,
42    },
43    ReconstructionMismatch {
44        reconstructed_len: usize,
45        source_len: usize,
46    },
47    IntervalStartAfterEnd {
48        start: usize,
49        end: usize,
50    },
51    IntervalExceedsSource {
52        start: usize,
53        end: usize,
54        source_len: usize,
55    },
56    IntervalNotUtf8Boundary {
57        start: usize,
58        end: usize,
59    },
60}
61
62impl std::fmt::Display for AstSpanError {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        match self {
65            Self::InvalidSpan { start, end } => write!(f, "invalid span [{start}, {end})"),
66            Self::OverlappingSpans {
67                start,
68                end,
69                parent_start,
70                parent_end,
71            } => write!(
72                f,
73                "span [{start}, {end}) overlaps [{parent_start}, {parent_end}) without nesting"
74            ),
75            Self::OverlappingTile {
76                start,
77                end,
78                previous_end,
79            } => write!(
80                f,
81                "span/trivia interval [{start}, {end}) overlaps previous tile ending at {previous_end}"
82            ),
83            Self::UncoveredBytes { start, end, text } => write!(
84                f,
85                "bytes {start}..{end} not covered by any node or trivia span: {text:?}"
86            ),
87            Self::UncoveredTail { start, text } => {
88                write!(f, "bytes {start}.. lost at EOF: {text:?}")
89            }
90            Self::ReconstructionMismatch {
91                reconstructed_len,
92                source_len,
93            } => write!(
94                f,
95                "reconstruction differs from source ({reconstructed_len} vs {source_len} bytes)"
96            ),
97            Self::IntervalStartAfterEnd { start, end } => {
98                write!(f, "span/trivia interval [{start}, {end}) has start after end")
99            }
100            Self::IntervalExceedsSource {
101                start,
102                end,
103                source_len,
104            } => write!(
105                f,
106                "span/trivia interval [{start}, {end}) exceeds source length {source_len}"
107            ),
108            Self::IntervalNotUtf8Boundary { start, end } => write!(
109                f,
110                "span/trivia interval [{start}, {end}) does not align with UTF-8 boundaries"
111            ),
112        }
113    }
114}
115
116impl std::error::Error for AstSpanError {}
117
118/// Reconstruct `source` from the AST's byte spans plus the lexer's `trivia`.
119///
120/// The AST-level mirror of `lexer::render_lossless`: it checks the spans nest
121/// (V2), then tiles the file from every *content* node span merged with the
122/// non-blank trivia spans (V1/V3). `Ok(reconstruction)` is byte-identical to
123/// `source`; `Err` names the first nesting violation or the first run of bytes
124/// no span covers (content the AST dropped).
125///
126/// Obtain `trivia` from [`crate::lexer::lex_with_trivia`].
127#[must_use = "check and handle render failures"]
128pub fn render_from_ast(
129    source: &str,
130    module: &Module,
131    trivia: &[Trivia],
132) -> Result<String, AstSpanError> {
133    check_nesting(module)?;
134    tile(source, module, trivia)
135}
136
137/// V2 — every child span is contained in its parent, and sibling spans are
138/// ordered and disjoint. Validates the whole node set (module container
139/// included) as a laminar family via a containment stack.
140fn check_nesting(module: &Module) -> Result<(), AstSpanError> {
141    let mut spans: Vec<Span> = Vec::new();
142    collect_module(module, &mut spans);
143    for span in &spans {
144        if !span.is_valid() {
145            return Err(AstSpanError::InvalidSpan {
146                start: span.start,
147                end: span.end,
148            });
149        }
150    }
151    spans.retain(|s| !s.is_empty());
152    // Outer-first: earlier start, then later end.
153    spans.sort_by(|a, b| a.start.cmp(&b.start).then(b.end.cmp(&a.end)));
154
155    let mut stack: Vec<Span> = Vec::new();
156    for span in spans {
157        // Pop ancestors that end at/before this span starts (its left siblings).
158        while stack.last().is_some_and(|top| top.end <= span.start) {
159            stack.pop();
160        }
161        // Whatever remains on top must contain this span; otherwise the two
162        // overlap without nesting (a sibling that starts before the previous
163        // one ended, or a child that spills past its parent).
164        if let Some(parent) = stack.last() {
165            if !parent.contains(&span) {
166                return Err(AstSpanError::OverlappingSpans {
167                    start: span.start,
168                    end: span.end,
169                    parent_start: parent.start,
170                    parent_end: parent.end,
171                });
172            }
173        }
174        stack.push(span);
175    }
176    Ok(())
177}
178
179/// V1/V3 — tile the file from content spans + non-blank trivia and reconstruct.
180/// "Content" excludes the whole-module container (which would cover everything
181/// trivially) but includes the `module … where` header. Any gap between spans
182/// must be whitespace-only; a non-whitespace gap is a real token no node claims,
183/// i.e. content the AST dropped.
184fn tile(source: &str, module: &Module, trivia: &[Trivia]) -> Result<String, AstSpanError> {
185    let mut content: Vec<Span> = Vec::new();
186    collect_module(module, &mut content);
187    let container = module.span;
188    content.retain(|s| !(s.is_empty() || (s.start == container.start && s.end == container.end)));
189
190    let mut items: Vec<(usize, usize)> = content.iter().map(|s| (s.start, s.end)).collect();
191    // Blank-line trivia carry no bytes; comment/CPP trivia fill the gaps that
192    // are legitimately not AST nodes.
193    items.extend(
194        trivia
195            .iter()
196            .filter(|t| !matches!(t.kind, TriviaKind::BlankLines(_)))
197            .map(|t| (t.start, t.end)),
198    );
199    // Outer-first, like `check_nesting`: when intervals share a start, emit the
200    // broader parent before contained children so child spans can be skipped as
201    // already-covered tiles.
202    items.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
203
204    let mut out = String::with_capacity(source.len());
205    let mut prev = 0usize;
206    for (start, end) in items {
207        validate_interval(source, start, end)?;
208        if start < prev {
209            // Nested AST child spans and contained trivia are already covered
210            // by their parent tile. A partial overlap that extends past `prev`
211            // cannot be tiled losslessly and means the interval set is invalid.
212            if end <= prev {
213                continue;
214            }
215            return Err(AstSpanError::OverlappingTile {
216                start,
217                end,
218                previous_end: prev,
219            });
220        }
221        let gap = &source[prev..start];
222        if !gap.chars().all(char::is_whitespace) {
223            return Err(AstSpanError::UncoveredBytes {
224                start: prev,
225                end: start,
226                text: gap.to_string(),
227            });
228        }
229        out.push_str(gap);
230        out.push_str(&source[start..end]);
231        prev = end;
232    }
233    let tail = &source[prev..];
234    if !tail.chars().all(char::is_whitespace) {
235        return Err(AstSpanError::UncoveredTail {
236            start: prev,
237            text: tail.to_string(),
238        });
239    }
240    out.push_str(tail);
241
242    if out != source {
243        return Err(AstSpanError::ReconstructionMismatch {
244            reconstructed_len: out.len(),
245            source_len: source.len(),
246        });
247    }
248    Ok(out)
249}
250
251const fn validate_interval(source: &str, start: usize, end: usize) -> Result<(), AstSpanError> {
252    if start > end {
253        return Err(AstSpanError::IntervalStartAfterEnd { start, end });
254    }
255    if end > source.len() {
256        return Err(AstSpanError::IntervalExceedsSource {
257            start,
258            end,
259            source_len: source.len(),
260        });
261    }
262    if !source.is_char_boundary(start) || !source.is_char_boundary(end) {
263        return Err(AstSpanError::IntervalNotUtf8Boundary { start, end });
264    }
265    Ok(())
266}
267
268// ----- span collection ---------------------------------------------------
269
270fn collect_module(module: &Module, spans: &mut Vec<Span>) {
271    spans.push(module.span);
272    if !module.header.is_empty() {
273        spans.push(module.header);
274    }
275    for import in &module.imports {
276        spans.push(import.span);
277    }
278    for decl in &module.decls {
279        collect_decl(decl, spans);
280    }
281}
282
283fn collect_decl(decl: &Decl, spans: &mut Vec<Span>) {
284    match decl {
285        Decl::Template(template) => {
286            spans.push(template.span);
287            for field in &template.fields {
288                spans.push(field.span);
289            }
290            for body_decl in &template.body {
291                collect_tbody(body_decl, spans);
292            }
293        }
294        Decl::Interface(interface) => {
295            spans.push(interface.span);
296            for method in &interface.methods {
297                spans.push(method.span);
298            }
299            for choice in &interface.choices {
300                collect_choice(choice, spans);
301            }
302        }
303        Decl::Function(function) => {
304            // `function.span` is the equations' extent (contiguous); the signature,
305            // which may sit apart, is a separate sibling span.
306            spans.push(function.span);
307            for equation in &function.equations {
308                collect_eq(equation, spans);
309            }
310            if let Some(sig) = function.sig_span {
311                spans.push(sig);
312            }
313        }
314        Decl::TypeDef { span, .. } | Decl::Unknown { span, .. } => spans.push(*span),
315    }
316}
317
318fn collect_tbody(template_body_decl: &TemplateBodyDecl, spans: &mut Vec<Span>) {
319    match template_body_decl {
320        TemplateBodyDecl::Signatory { parties, span, .. }
321        | TemplateBodyDecl::Observer { parties, span, .. } => {
322            spans.push(*span);
323            for party in parties {
324                collect_expr(party, spans);
325            }
326        }
327        TemplateBodyDecl::Ensure { expr, span, .. }
328        | TemplateBodyDecl::Maintainer { expr, span, .. }
329        | TemplateBodyDecl::Key { expr, span, .. } => {
330            spans.push(*span);
331            collect_expr(expr, spans);
332        }
333        TemplateBodyDecl::Choice(choice) => collect_choice(choice, spans),
334        TemplateBodyDecl::InterfaceInstance(interface_instance) => {
335            spans.push(interface_instance.span);
336            for method in &interface_instance.methods {
337                collect_binding(method, spans);
338            }
339        }
340        TemplateBodyDecl::Other { span, .. } => spans.push(*span),
341    }
342}
343
344fn collect_choice(choice: &ChoiceDecl, spans: &mut Vec<Span>) {
345    spans.push(choice.span);
346    for param in &choice.params {
347        spans.push(param.span);
348    }
349    for controller in &choice.controllers {
350        collect_expr(controller, spans);
351    }
352    for observer in &choice.observers {
353        collect_expr(observer, spans);
354    }
355    if let Some(body) = &choice.body {
356        collect_expr(body, spans);
357    }
358}
359
360fn collect_eq(equation: &Equation, spans: &mut Vec<Span>) {
361    spans.push(equation.span);
362    for param in &equation.params {
363        collect_pat(param, spans);
364    }
365    collect_expr(&equation.body, spans);
366    for (guard, body) in &equation.guards {
367        collect_expr(guard, spans);
368        collect_expr(body, spans);
369    }
370    for where_binding in &equation.where_bindings {
371        collect_binding(where_binding, spans);
372    }
373}
374
375fn collect_binding(binding: &Binding, spans: &mut Vec<Span>) {
376    spans.push(binding.span);
377    collect_pat(&binding.pat, spans);
378    for param in &binding.params {
379        collect_pat(param, spans);
380    }
381    collect_expr(&binding.expr, spans);
382}
383
384fn collect_pat(pattern: &Pat, spans: &mut Vec<Span>) {
385    spans.push(pattern.span());
386    match pattern {
387        Pat::Con { args, .. } => {
388            for arg in args {
389                collect_pat(arg, spans);
390            }
391        }
392        Pat::Tuple { items, .. } | Pat::List { items, .. } => {
393            for item in items {
394                collect_pat(item, spans);
395            }
396        }
397        Pat::As { pat, .. } => collect_pat(pat, spans),
398        Pat::Var { .. } | Pat::Wild { .. } | Pat::Lit { .. } | Pat::Other { .. } => {}
399    }
400}
401
402fn collect_expr(expr: &Expr, spans: &mut Vec<Span>) {
403    spans.push(expr.span());
404    match expr {
405        Expr::App { func, args, .. } => {
406            collect_expr(func, spans);
407            for arg in args {
408                collect_expr(arg, spans);
409            }
410        }
411        Expr::BinOp { lhs, rhs, .. } => {
412            collect_expr(lhs, spans);
413            collect_expr(rhs, spans);
414        }
415        Expr::Neg { expr, .. } => collect_expr(expr, spans),
416        Expr::Lambda { params, body, .. } => {
417            for param in params {
418                collect_pat(param, spans);
419            }
420            collect_expr(body, spans);
421        }
422        Expr::If {
423            cond,
424            then_branch,
425            else_branch,
426            ..
427        } => {
428            collect_expr(cond, spans);
429            collect_expr(then_branch, spans);
430            collect_expr(else_branch, spans);
431        }
432        Expr::Case {
433            scrutinee, alts, ..
434        } => {
435            collect_expr(scrutinee, spans);
436            for alt in alts {
437                collect_alt(alt, spans);
438            }
439        }
440        Expr::Do { stmts, .. } => {
441            for stmt in stmts {
442                collect_dostmt(stmt, spans);
443            }
444        }
445        Expr::LetIn { bindings, body, .. } => {
446            for binding in bindings {
447                collect_binding(binding, spans);
448            }
449            collect_expr(body, spans);
450        }
451        Expr::Record { base, fields, .. } => {
452            collect_expr(base, spans);
453            for field in fields {
454                collect_field_assign(field, spans);
455            }
456        }
457        Expr::Tuple { items, .. } | Expr::List { items, .. } => {
458            for item in items {
459                collect_expr(item, spans);
460            }
461        }
462        Expr::Try { body, handlers, .. } => {
463            collect_expr(body, spans);
464            for handler in handlers {
465                collect_alt(handler, spans);
466            }
467        }
468        Expr::Section {
469            operand: Some(operand),
470            ..
471        } => collect_expr(operand, spans),
472        Expr::Var { .. }
473        | Expr::Con { .. }
474        | Expr::Lit { .. }
475        | Expr::Section { operand: None, .. }
476        | Expr::Error { .. } => {}
477    }
478}
479
480fn collect_alt(alt: &Alt, spans: &mut Vec<Span>) {
481    spans.push(alt.span);
482    collect_pat(&alt.pat, spans);
483    collect_expr(&alt.body, spans);
484}
485
486fn collect_field_assign(field_assign: &FieldAssign, spans: &mut Vec<Span>) {
487    spans.push(field_assign.span);
488    if let Some(value) = &field_assign.value {
489        collect_expr(value, spans);
490    }
491}
492
493fn collect_dostmt(do_stmt: &DoStmt, spans: &mut Vec<Span>) {
494    match do_stmt {
495        DoStmt::Bind {
496            pat, expr, span, ..
497        } => {
498            spans.push(*span);
499            collect_pat(pat, spans);
500            collect_expr(expr, spans);
501        }
502        DoStmt::Let { bindings, span, .. } => {
503            spans.push(*span);
504            for binding in bindings {
505                collect_binding(binding, spans);
506            }
507        }
508        DoStmt::Expr { expr, span, .. } => {
509            spans.push(*span);
510            collect_expr(expr, spans);
511        }
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518    use crate::lexer::{Pos, Trivia};
519
520    #[test]
521    fn tile_reports_overlapping_intervals() {
522        let source = "module M where\n-- comment\n";
523        let module = Module {
524            name: "M".into(),
525            pos: Pos { line: 1, column: 1 },
526            span: Span::new(0, source.len()),
527            header: Span::new(0, "module M where".len()),
528            imports: Vec::new(),
529            decls: Vec::new(),
530        };
531        let trivia = vec![Trivia {
532            kind: TriviaKind::LineComment,
533            text: "-- comment".to_string(),
534            pos: Pos { line: 2, column: 1 },
535            start: "module M wher".len(),
536            end: "module M where\n-- comment".len(),
537        }];
538
539        let err = tile(source, &module, &trivia).unwrap_err();
540        assert!(
541            err.to_string().contains("overlaps previous tile"),
542            "overlap should fail loudly, got: {err}"
543        );
544    }
545
546    #[test]
547    fn validate_interval_reports_malformed_bounds() {
548        assert_eq!(
549            validate_interval("abc", 2, 1),
550            Err(AstSpanError::IntervalStartAfterEnd { start: 2, end: 1 })
551        );
552        assert_eq!(
553            validate_interval("abc", 0, 4),
554            Err(AstSpanError::IntervalExceedsSource {
555                start: 0,
556                end: 4,
557                source_len: 3
558            })
559        );
560        assert_eq!(
561            validate_interval("é", 1, 2),
562            Err(AstSpanError::IntervalNotUtf8Boundary { start: 1, end: 2 })
563        );
564    }
565
566    #[test]
567    fn tile_reports_uncovered_non_whitespace_bytes() {
568        let source = "module M where\nmissing\n";
569        let module = Module {
570            name: "M".into(),
571            pos: Pos { line: 1, column: 1 },
572            span: Span::new(0, source.len()),
573            header: Span::new(0, "module M where".len()),
574            imports: Vec::new(),
575            decls: Vec::new(),
576        };
577
578        assert_eq!(
579            tile(source, &module, &[]),
580            Err(AstSpanError::UncoveredTail {
581                start: "module M where".len(),
582                text: "\nmissing\n".to_string(),
583            })
584        );
585    }
586
587    #[test]
588    fn render_from_ast_roundtrips_header_only_module() {
589        let source = "module M where\n";
590        let module = Module {
591            name: "M".into(),
592            pos: Pos { line: 1, column: 1 },
593            span: Span::new(0, source.len()),
594            header: Span::new(0, "module M where".len()),
595            imports: Vec::new(),
596            decls: Vec::new(),
597        };
598
599        assert_eq!(render_from_ast(source, &module, &[]).as_deref(), Ok(source));
600    }
601}