hamelin_lib 0.21.6

Core library for Hamelin query 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
use std::{
    fmt::{self, Display, Formatter},
    ops::RangeInclusive,
    rc::Rc,
    sync::Arc,
};

use super::node::Span;

use derive_more::derive::{From, TryUnwrap};

use crate::{
    antlr::{
        hamelinparser::{
            AssignmentClauseContextAll, AssignmentClauseContextAttrs, AssignmentContextAll,
            AssignmentContextAttrs, FromClauseContextAll, FromClauseContextAttrs,
            InnerTablePathContextAttrs, SelectionContextAll, SelectionContextAttrs,
            SortExpressionContextAll, SortExpressionContextAttrs, TableAliasContextAttrs,
            TablePathContextAll, TablePathContextAttrs, TablePathSegmentContextAll,
            TablePathSegmentContextAttrs, TableReferenceContextAll, TableReferenceContextAttrs,
            TemplatePairContextAttrs,
        },
        interval,
    },
    err::TranslationError,
    tree::ast::{
        context::{FromCst, ParseContext},
        dataset_identifier::{
            DatasetIdentifier, ParsedDatasetIdentifier, QualifiedDatasetIdentifier,
            UnqualifiedDatasetIdentifier,
        },
        identifier::Identifier,
    },
};

use super::{
    expression::{ErrorExpression, Expression},
    identifier::{ParsedIdentifier, ParsedSimpleIdentifier, SimpleIdentifier},
    node::Spannable,
};
use antlr_rust::tree::ParseTree;

// ============================================================================
// Assignment
// ============================================================================

#[derive(Debug, Clone)]
pub struct Assignment {
    pub span: Span,
    pub identifier: ParsedIdentifier,
    pub expression: Arc<Expression>,
}

impl PartialEq for Assignment {
    fn eq(&self, other: &Self) -> bool {
        self.identifier == other.identifier && self.expression == other.expression
    }
}

impl Assignment {
    pub fn from_parts(identifier: ParsedIdentifier, expression: Expression) -> Self {
        Self {
            span: Span::NONE,
            identifier,
            expression: Arc::new(expression),
        }
    }
}

impl Spannable for Assignment {
    fn span(&self) -> Option<RangeInclusive<usize>> {
        self.span.to_range()
    }
}

impl FromCst<Rc<AssignmentContextAll<'static>>> for Assignment {
    fn from_cst_with_context(
        cst: Rc<AssignmentContextAll<'static>>,
        ctx: &mut ParseContext,
    ) -> Self {
        let identifier = cst
            .identifier()
            .map(|id_cst| ParsedIdentifier::from_cst_with_context(id_cst, ctx))
            .unwrap_or_else(|| {
                ctx.error("missing identifier in assignment")
                    .at(cst.as_ref())
                    .emit()
                    .into()
            });

        let expression = if let Some(expr_ctx) = cst.expression() {
            Expression::from_cst_with_context(expr_ctx, ctx)
        } else {
            let err = ctx
                .error("missing expression in assignment")
                .at(cst.as_ref())
                .emit();
            Expression::from_kind(ErrorExpression { error: err })
        };

        Self {
            span: interval(cst.as_ref()).into(),
            identifier,
            expression: Arc::new(expression),
        }
    }
}

// ============================================================================
// AssignmentClause
// ============================================================================

/// An assignment clause is either an explicit assignment (identifier = expression)
/// or an error. Bare expressions are desugared to assignments at parse time
/// by inferring the identifier from the expression structure.
#[derive(Debug, Clone, From, PartialEq, TryUnwrap)]
pub enum AssignmentClause {
    Assignment(Assignment),
    Error(Arc<TranslationError>),
}

impl Spannable for AssignmentClause {
    fn span(&self) -> Option<RangeInclusive<usize>> {
        match self {
            AssignmentClause::Assignment(a) => a.span(),
            AssignmentClause::Error(_) => None,
        }
    }
}

impl FromCst<Rc<AssignmentClauseContextAll<'static>>> for AssignmentClause {
    fn from_cst_with_context(
        cst: Rc<AssignmentClauseContextAll<'static>>,
        ctx: &mut ParseContext,
    ) -> Self {
        if let Some(assignment_ctx) = cst.assignment() {
            Assignment::from_cst_with_context(assignment_ctx, ctx).into()
        } else if let Some(expr_ctx) = cst.expression() {
            // Bare expression: desugar to assignment by inferring identifier
            let expression = Expression::from_cst_with_context(expr_ctx.clone(), ctx);

            // Try to infer identifier from AST structure, fall back to source text
            // Strip backticks (Hamelin quoting syntax) so they don't become literal chars in the name
            let identifier = Identifier::infer_from_expression(&expression).unwrap_or_else(|| {
                SimpleIdentifier::new(expr_ctx.get_text().replace('`', "")).into()
            });

            Assignment::from_parts(identifier, expression).into()
        } else {
            ctx.error("invalid assignment clause")
                .at(cst.as_ref())
                .emit()
                .into()
        }
    }
}

// ============================================================================
// FromClause
// ============================================================================

#[derive(Debug, Clone)]
pub struct TableAlias {
    pub span: Span,
    pub alias: ParsedSimpleIdentifier,
    pub table: TableReference,
}

impl Spannable for TableAlias {
    fn span(&self) -> Option<RangeInclusive<usize>> {
        self.span.to_range()
    }
}

impl PartialEq for TableAlias {
    fn eq(&self, other: &Self) -> bool {
        self.alias == other.alias && self.table == other.table
    }
}

/// One segment of a table path (`catalog.schema.table` or `foo.${p}_logs`).
#[derive(Debug, Clone, PartialEq)]
pub struct TablePathSegment {
    pub span: Span,
    pub parts: Vec<TableSegmentPart>,
}

/// A piece of a table path segment: literal identifier text or `${param}`.
#[derive(Debug, Clone, PartialEq)]
pub enum TableSegmentPart {
    Text(ParsedSimpleIdentifier),
    Parameter(ParsedSimpleIdentifier),
}

/// Table path containing at least one template parameter or multi-part segment.
#[derive(Debug, Clone, PartialEq)]
pub struct TemplatedTablePath {
    pub span: Span,
    /// Optional explicit space segment before `:` (may contain `${...}`).
    pub space: Option<TablePathSegment>,
    pub segments: Vec<TablePathSegment>,
}

#[derive(Debug, Clone, PartialEq, From)]
pub enum TableReferenceTarget {
    /// Statically known dataset reference that does not contain any `${...}` parameters.
    /// Resolvable against the catalog without substitution.
    Static(ParsedDatasetIdentifier),
    /// Path that contains at least one `${...}` parameter; must be substituted before
    /// it can be resolved to a single concrete identifier.
    Templated(TemplatedTablePath),
}

#[derive(Debug, Clone)]
pub struct TableReference {
    pub span: Span,
    pub target: TableReferenceTarget,
}

impl TableReference {
    /// Resolve to a statically-known catalog identifier, or fail for templated references.
    ///
    /// Use this when the caller fundamentally cannot operate on a templated reference (post-
    /// substitution lowering, normalization, single-table reflection). Code paths that *can* deal
    /// with templated references should match on `target` directly and call
    /// `expand_templated_table_path` for the templated arm.
    pub fn static_valid_dataset_ref(&self) -> Result<&DatasetIdentifier, Arc<TranslationError>> {
        match &self.target {
            TableReferenceTarget::Static(id) => id.valid_ref(),
            TableReferenceTarget::Templated(_) => Err(Arc::new(TranslationError::msg(
                self,
                "templated table reference cannot be used here; substitute template parameters first",
            ))),
        }
    }

    /// Two-part `namespace.table` identifier for SQL engines and executors.
    ///
    /// Applies [`DatasetIdentifier::qualify`] with `default_space`, then maps to a flat
    /// `schema.table` pair for SQL engines (nested namespace parts joined with dots).
    pub fn execution_identifier(
        &self,
        default_space: Option<&SimpleIdentifier>,
    ) -> Result<Identifier, Arc<TranslationError>> {
        let dataset = self.static_valid_dataset_ref()?;
        let qualified = dataset.clone().qualify(default_space).map_err(|e| {
            let msg = e.to_string();
            Arc::new(TranslationError::msg(self, &msg))
        })?;
        Ok(qualified.to_execution_identifier())
    }

    /// Whether this reference contains `${...}` in the path.
    pub fn is_templated(&self) -> bool {
        matches!(self.target, TableReferenceTarget::Templated(_))
    }
}

impl PartialEq for TableReference {
    fn eq(&self, other: &Self) -> bool {
        self.target == other.target
    }
}

impl Spannable for TableReference {
    fn span(&self) -> Option<RangeInclusive<usize>> {
        self.span.to_range()
    }
}

// Shortcut From impls so callers can `.into()` directly to a target without
// hand-writing the nested `Static(ParsedIdentifier::Valid/Error(...))` chain.
impl From<Arc<TranslationError>> for TableReferenceTarget {
    fn from(err: Arc<TranslationError>) -> Self {
        TableReferenceTarget::Static(ParsedDatasetIdentifier::Error(err))
    }
}

impl From<DatasetIdentifier> for TableReferenceTarget {
    fn from(id: DatasetIdentifier) -> Self {
        TableReferenceTarget::Static(ParsedDatasetIdentifier::Valid(id))
    }
}

impl FromCst<Rc<TablePathSegmentContextAll<'static>>> for TablePathSegment {
    fn from_cst_with_context(
        cst: Rc<TablePathSegmentContextAll<'static>>,
        ctx: &mut ParseContext,
    ) -> Self {
        let mut parts: Vec<TableSegmentPart> = Vec::new();

        if let Some(tok) = cst.IDENTIFIER() {
            let mut si = SimpleIdentifier::with_arc_name(ctx.intern(&tok.get_text()));
            si.span = interval(tok.as_ref()).into();
            parts.push(TableSegmentPart::Text(si.into()));
        } else if let Some(tok) = cst.BACKQUOTED_IDENTIFIER() {
            parts.push(TableSegmentPart::Text(backquoted_to_parsed(
                &tok.get_text(),
                interval(tok.as_ref()).into(),
                ctx,
            )));
        }

        for pair in cst.templatePair_all() {
            let parsed = pair
                .simpleIdentifier()
                .map(|si| ParsedSimpleIdentifier::from_cst_with_context(si.as_ref(), ctx))
                .unwrap_or_else(|| {
                    ctx.error("missing template parameter name in table path")
                        .at(pair.as_ref())
                        .emit()
                        .into()
                });
            parts.push(TableSegmentPart::Parameter(parsed));

            if let Some(tok) = pair.IDENTIFIER() {
                let mut si = SimpleIdentifier::with_arc_name(ctx.intern(&tok.get_text()));
                si.span = interval(tok.as_ref()).into();
                parts.push(TableSegmentPart::Text(si.into()));
            } else if let Some(tok) = pair.BACKQUOTED_IDENTIFIER() {
                parts.push(TableSegmentPart::Text(backquoted_to_parsed(
                    &tok.get_text(),
                    interval(tok.as_ref()).into(),
                    ctx,
                )));
            }
        }

        TablePathSegment {
            span: interval(cst.as_ref()).into(),
            parts,
        }
    }
}

/// Parse a raw `BACKQUOTED_IDENTIFIER` token text into a [`ParsedSimpleIdentifier`], applying the
/// same empty-backtick rejection as the shared `simpleIdentifier` CST path and interning through
/// the parse context.
fn backquoted_to_parsed(text: &str, span: Span, ctx: &mut ParseContext) -> ParsedSimpleIdentifier {
    let inner = text.strip_prefix('`').and_then(|s| s.strip_suffix('`'));
    match inner {
        Some(inner) if inner.is_empty() => ctx
            .error("empty backtick identifier")
            .at(&span)
            .emit()
            .into(),
        Some(inner) => {
            let unescaped = inner.replace("``", "`");
            let mut si = SimpleIdentifier::with_arc_name(ctx.intern(&unescaped));
            si.span = span;
            si.into()
        }
        None => ctx
            .error("invalid backtick identifier")
            .at(&span)
            .emit()
            .into(),
    }
}

fn segment_to_simple(
    seg: &TablePathSegment,
    path_cst: &impl Spannable,
    ctx: &mut ParseContext,
) -> Result<SimpleIdentifier, TableReferenceTarget> {
    let mut acc = String::new();
    for p in &seg.parts {
        if let TableSegmentPart::Text(psi) = p {
            match psi.valid_ref() {
                Ok(si) => acc.push_str(si.name().as_ref()),
                Err(e) => return Err(e.clone().into()),
            }
        }
    }
    if acc.is_empty() {
        let err = ctx.error("empty table path segment").at(path_cst).emit();
        return Err(err.into());
    }
    let mut si = SimpleIdentifier::new(acc);
    si.span = seg.span;
    Ok(si)
}

fn table_path_to_target(
    path_cst: Rc<TablePathContextAll<'static>>,
    ctx: &mut ParseContext,
) -> TableReferenceTarget {
    let span = interval(path_cst.as_ref()).into();

    let space_segment = path_cst
        .COLON()
        .is_some()
        .then(|| {
            path_cst
                .tablePathSegment()
                .map(|s| TablePathSegment::from_cst_with_context(s, ctx))
        })
        .flatten();

    let inner_cst = match path_cst.innerTablePath() {
        Some(inner) => inner,
        None => {
            let err = ctx.error("missing table path").at(path_cst.as_ref()).emit();
            return err.into();
        }
    };

    let inner_segments: Vec<TablePathSegment> = inner_cst
        .tablePathSegment_all()
        .into_iter()
        .map(|s| TablePathSegment::from_cst_with_context(s, ctx))
        .collect();

    let is_templated = space_segment
        .iter()
        .chain(inner_segments.iter())
        .any(|seg| {
            seg.parts
                .iter()
                .any(|p| matches!(p, TableSegmentPart::Parameter(_)))
        });

    if is_templated {
        return TemplatedTablePath {
            span,
            space: space_segment,
            segments: inner_segments,
        }
        .into();
    }

    let space = match &space_segment {
        Some(seg) => match segment_to_simple(seg, path_cst.as_ref(), ctx) {
            Ok(si) => Some(si),
            Err(target) => return target,
        },
        None => None,
    };

    let Some(last_segment) = inner_segments.last() else {
        let err = ctx.error("empty table path").at(path_cst.as_ref()).emit();
        return err.into();
    };

    let table = match segment_to_simple(last_segment, path_cst.as_ref(), ctx) {
        Ok(si) => si,
        Err(target) => return target,
    };
    let namespace: Vec<SimpleIdentifier> = if inner_segments.len() <= 1 {
        Vec::new()
    } else {
        let mut parts = Vec::with_capacity(inner_segments.len() - 1);
        for seg in &inner_segments[..inner_segments.len() - 1] {
            match segment_to_simple(seg, path_cst.as_ref(), ctx) {
                Ok(si) => parts.push(si),
                Err(target) => return target,
            }
        }
        parts
    };

    let id = match space {
        Some(space) => DatasetIdentifier::Qualified(QualifiedDatasetIdentifier {
            space,
            namespace,
            table,
        }),
        None => DatasetIdentifier::Unqualified(UnqualifiedDatasetIdentifier { namespace, table }),
    };
    id.into()
}

impl FromCst<Rc<TableReferenceContextAll<'static>>> for TableReference {
    fn from_cst_with_context(
        cst: Rc<TableReferenceContextAll<'static>>,
        ctx: &mut ParseContext,
    ) -> Self {
        let target = match cst.tablePath() {
            Some(p) => table_path_to_target(p, ctx),
            None => {
                let err = ctx.error("missing table path").at(cst.as_ref()).emit();
                err.into()
            }
        };

        Self {
            span: interval(cst.as_ref()).into(),
            target,
        }
    }
}

#[derive(Debug, Clone, From, PartialEq, TryUnwrap)]
pub enum FromClause {
    TableAlias(Arc<TableAlias>),
    TableReference(Arc<TableReference>),
}

impl FromClause {
    /// Returns the underlying TableReference, cloning from TableAlias if needed.
    pub fn table_reference(&self) -> TableReference {
        match self {
            FromClause::TableReference(tr) => tr.as_ref().clone(),
            FromClause::TableAlias(ta) => ta.table.clone(),
        }
    }
}

impl Spannable for FromClause {
    fn span(&self) -> Option<RangeInclusive<usize>> {
        match self {
            FromClause::TableAlias(ta) => ta.span(),
            FromClause::TableReference(tr) => tr.span(),
        }
    }
}

impl FromCst<Rc<FromClauseContextAll<'static>>> for FromClause {
    fn from_cst_with_context(
        cst: Rc<FromClauseContextAll<'static>>,
        ctx: &mut ParseContext,
    ) -> Self {
        if let Some(table_alias_ctx) = cst.tableAlias() {
            let alias = table_alias_ctx
                .simpleIdentifier()
                .map(|x| ParsedSimpleIdentifier::from_cst_with_context(x.as_ref(), ctx))
                .unwrap_or_else(|| {
                    ctx.error("missing alias identifier")
                        .at(cst.as_ref())
                        .emit()
                        .into()
                });

            let table_ref_ctx = table_alias_ctx.tableReference();
            let table = match table_ref_ctx.as_ref() {
                Some(tr) => TableReference::from_cst_with_context(tr.clone(), ctx),
                None => TableReference {
                    span: Span::NONE,
                    target: ctx
                        .error("missing table reference")
                        .at(cst.as_ref())
                        .emit()
                        .into(),
                },
            };

            Arc::new(TableAlias {
                span: interval(table_alias_ctx.as_ref()).into(),
                alias,
                table,
            })
            .into()
        } else if let Some(table_ref_ctx) = cst.tableReference() {
            Arc::new(TableReference::from_cst_with_context(table_ref_ctx, ctx)).into()
        } else {
            Arc::new(TableReference {
                span: Span::NONE,
                target: ctx
                    .error("invalid from clause")
                    .at(cst.as_ref())
                    .emit()
                    .into(),
            })
            .into()
        }
    }
}

impl From<TableAlias> for FromClause {
    fn from(value: TableAlias) -> Self {
        Self::from(Arc::new(value))
    }
}

impl From<TableReference> for FromClause {
    fn from(value: TableReference) -> Self {
        Self::from(Arc::new(value))
    }
}

// ============================================================================
// SortExpression
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortOrder {
    Asc,
    Desc,
}

#[derive(Debug, Clone)]
pub struct SortExpression {
    pub span: Span,
    pub expression: Arc<Expression>,
    pub order: Option<SortOrder>,
}

impl PartialEq for SortExpression {
    fn eq(&self, other: &Self) -> bool {
        self.expression == other.expression && self.order == other.order
    }
}

impl Spannable for SortExpression {
    fn span(&self) -> Option<RangeInclusive<usize>> {
        self.span.to_range()
    }
}

impl FromCst<Rc<SortExpressionContextAll<'static>>> for SortExpression {
    fn from_cst_with_context(
        cst: Rc<SortExpressionContextAll<'static>>,
        ctx: &mut ParseContext,
    ) -> Self {
        let expression = if let Some(expr_ctx) = cst.expression() {
            Expression::from_cst_with_context(expr_ctx.clone(), ctx)
        } else {
            let err = ctx
                .error("missing expression in sort")
                .at(cst.as_ref())
                .emit();
            Expression::from_kind(ErrorExpression { error: err.clone() })
        };

        let order = if cst.ASC().is_some() {
            Some(SortOrder::Asc)
        } else if cst.DESC().is_some() {
            Some(SortOrder::Desc)
        } else {
            None
        };

        Self {
            span: interval(cst.as_ref()).into(),
            expression: Arc::new(expression),
            order,
        }
    }
}

// ============================================================================
// Selection
// ============================================================================

#[derive(Debug, Clone)]
pub struct Selection {
    pub span: Span,
    pub identifier: ParsedIdentifier,
}

impl PartialEq for Selection {
    fn eq(&self, other: &Self) -> bool {
        self.identifier == other.identifier
    }
}

impl Selection {
    pub fn from_identifier(identifier: ParsedIdentifier) -> Self {
        Self {
            span: Span::NONE,
            identifier,
        }
    }
}

impl Spannable for Selection {
    fn span(&self) -> Option<RangeInclusive<usize>> {
        self.span.to_range()
    }
}

impl FromCst<Rc<SelectionContextAll<'static>>> for Selection {
    fn from_cst_with_context(
        cst: Rc<SelectionContextAll<'static>>,
        ctx: &mut ParseContext,
    ) -> Self {
        let identifier = cst
            .identifier()
            .map(|id| ParsedIdentifier::from_cst_with_context(id, ctx))
            .unwrap_or_else(|| {
                ctx.error("missing identifier in selection")
                    .at(cst.as_ref())
                    .emit()
                    .into()
            });

        Self {
            span: interval(cst.as_ref()).into(),
            identifier,
        }
    }
}

// ============================================================================
// Display / fmt_indented implementations
// ============================================================================

impl Assignment {
    pub fn subelements(&self) -> usize {
        self.expression.subelements() + 1
    }

    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        write!(f, "{} = ", self.identifier)?;
        // For simple expressions, hang-indent after "name = " so continuations align.
        // For complex expressions, use the base indentation so block-indented
        // function calls don't get pushed too far right.
        let hang = indentation + self.identifier.to_string().len() + 3;
        let expr_indent = if self.expression.subelements() > 4 {
            indentation
        } else {
            hang
        };
        self.expression.fmt_indented(f, expr_indent)
    }
}

impl Display for Assignment {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.fmt_indented(f, 0)
    }
}

impl AssignmentClause {
    pub fn subelements(&self) -> usize {
        match self {
            AssignmentClause::Assignment(a) => a.subelements(),
            AssignmentClause::Error(_) => 0,
        }
    }

    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        match self {
            AssignmentClause::Assignment(a) => a.fmt_indented(f, indentation),
            AssignmentClause::Error(_) => write!(f, "?!"),
        }
    }
}

impl Display for AssignmentClause {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.fmt_indented(f, 0)
    }
}

impl Display for TableReference {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match &self.target {
            TableReferenceTarget::Static(id) => match id.valid_ref() {
                Ok(ds) => write!(f, "{}", ds),
                Err(_) => write!(f, "<error>"),
            },
            TableReferenceTarget::Templated(path) => {
                if let Some(space) = &path.space {
                    for part in &space.parts {
                        match part {
                            TableSegmentPart::Text(t) => write!(f, "{}", t)?,
                            TableSegmentPart::Parameter(p) => {
                                write!(f, "$")?;
                                write!(f, "{{")?;
                                write!(f, "{}", p)?;
                                write!(f, "}}")?;
                            }
                        }
                    }
                    write!(f, ":")?;
                }
                for (si, seg) in path.segments.iter().enumerate() {
                    if si > 0 {
                        write!(f, ".")?;
                    }
                    for part in &seg.parts {
                        match part {
                            TableSegmentPart::Text(t) => write!(f, "{}", t)?,
                            TableSegmentPart::Parameter(p) => {
                                write!(f, "$")?;
                                write!(f, "{{")?;
                                write!(f, "{}", p)?;
                                write!(f, "}}")?;
                            }
                        }
                    }
                }
                Ok(())
            }
        }
    }
}

impl Display for TableAlias {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} = {}", self.alias, self.table)
    }
}

impl FromClause {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, _indentation: usize) -> fmt::Result {
        match self {
            FromClause::TableAlias(ta) => write!(f, "{}", ta),
            FromClause::TableReference(tr) => write!(f, "{}", tr),
        }
    }
}

impl Display for FromClause {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.fmt_indented(f, 0)
    }
}

impl Display for SortOrder {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            SortOrder::Asc => write!(f, "ASC"),
            SortOrder::Desc => write!(f, "DESC"),
        }
    }
}

impl SortExpression {
    pub fn subelements(&self) -> usize {
        self.expression.subelements() + 1
    }

    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        self.expression.fmt_indented(f, indentation)?;
        if let Some(order) = &self.order {
            write!(f, " {}", order)?;
        }
        Ok(())
    }
}

impl Display for SortExpression {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.fmt_indented(f, 0)
    }
}

impl Display for Selection {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.identifier)
    }
}