hamelin_lib 0.21.3

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
use std::{
    collections::{HashMap, HashSet},
    fmt::{self, Display, Formatter},
    ops::RangeInclusive,
    rc::Rc,
    sync::Arc,
};

use ordermap::OrderSet;

use antlr_rust::tree::ParseTree;
use derive_more::derive::From;

use crate::antlr::strip_numeric_separators;

use super::clause::{FromClause, TableReference};
use super::dataset_identifier::QualifiedDatasetIdentifier;
use super::identifier::{Identifier, SimpleIdentifier};
use super::node::{Span, Spannable};
use super::query::push_datasets_for_table_reference;
use crate::tree::options::TemplateParameterKind;
use crate::{
    antlr::{
        hamelinparser::{
            ExactlyContextAttrs, NestedContext, NestedContextAttrs, PatternContextAll,
            QuantifiedContext, QuantifiedContextAttrs, QuantifierContextAll,
        },
        interval,
    },
    err::TranslationError,
    tree::ast::context::{FromCst, ParseContext},
};

// ============================================================================
// Pattern - Top-level pattern type for MATCH command
// ============================================================================

#[derive(Debug, Clone)]
pub struct Pattern {
    pub span: Span,
    pub kind: PatternKind,
}

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

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

impl From<PatternKind> for Pattern {
    fn from(kind: PatternKind) -> Self {
        Self {
            span: Span::NONE,
            kind,
        }
    }
}

impl Pattern {
    pub fn has_template_parameters(&self) -> bool {
        match &self.kind {
            PatternKind::Quantified(qp) => qp.from_clause.table_reference().is_templated(),
            PatternKind::Nested(np) => np.patterns.iter().any(|p| p.has_template_parameters()),
            PatternKind::Error(_) => false,
        }
    }

    /// Recursively extracts table references from this pattern, excluding CTEs and duplicates.
    /// Templated-vs-static handling is delegated to
    /// [`push_datasets_for_table_reference`](super::query::push_datasets_for_table_reference)
    /// so MATCH patterns and top-level FROM/UNION/JOIN clauses agree on expansion behavior and
    /// error messages.
    pub fn extract_datasets(
        &self,
        cte_names: &HashSet<Identifier>,
        datasets: &mut OrderSet<QualifiedDatasetIdentifier>,
        default_space: Option<&SimpleIdentifier>,
        template_parameters: Option<&HashMap<String, TemplateParameterKind>>,
    ) -> Result<(), Arc<TranslationError>> {
        match &self.kind {
            PatternKind::Quantified(qp) => {
                let table_ref = qp.from_clause.table_reference();
                push_datasets_for_table_reference(
                    &table_ref,
                    cte_names,
                    datasets,
                    default_space,
                    template_parameters,
                )?;
            }
            PatternKind::Nested(np) => {
                for pattern in &np.patterns {
                    pattern.extract_datasets(
                        cte_names,
                        datasets,
                        default_space,
                        template_parameters,
                    )?;
                }
            }
            PatternKind::Error(_) => {}
        }
        Ok(())
    }
}

impl FromCst<Rc<PatternContextAll<'static>>> for Pattern {
    fn from_cst_with_context(cst: Rc<PatternContextAll<'static>>, ctx: &mut ParseContext) -> Self {
        let kind = PatternKind::from_cst_with_context(Rc::clone(&cst), ctx);
        Self {
            span: interval(cst.as_ref()).into(),
            kind,
        }
    }
}

#[derive(Debug, Clone, From, PartialEq)]
pub enum PatternKind {
    Quantified(QuantifiedPattern),
    Nested(NestedPattern),
    Error(Arc<TranslationError>),
}

impl Spannable for PatternKind {
    fn span(&self) -> Option<RangeInclusive<usize>> {
        match self {
            PatternKind::Quantified(p) => p.span(),
            PatternKind::Nested(p) => p.span(),
            PatternKind::Error(_) => None,
        }
    }
}

impl FromCst<Rc<PatternContextAll<'static>>> for PatternKind {
    fn from_cst_with_context(cst: Rc<PatternContextAll<'static>>, ctx: &mut ParseContext) -> Self {
        match cst.as_ref() {
            PatternContextAll::QuantifiedContext(qctx) => {
                QuantifiedPattern::from_ast_with_context(qctx, ctx).into()
            }
            PatternContextAll::NestedContext(nctx) => {
                NestedPattern::from_ast_with_context(nctx, ctx).into()
            }
            PatternContextAll::Error(_) => ctx.error("parse error").at(cst.as_ref()).emit().into(),
        }
    }
}

// ============================================================================
// QuantifiedPattern - A from clause with optional quantifier
// ============================================================================

#[derive(Debug, Clone)]
pub struct QuantifiedPattern {
    pub span: Span,
    pub from_clause: Arc<FromClause>,
    pub quantifier: Option<Arc<Quantifier>>,
}

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

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

impl QuantifiedPattern {
    fn from_ast_with_context(qctx: &QuantifiedContext<'static>, ctx: &mut ParseContext) -> Self {
        let from_clause = Arc::new(
            qctx.fromClause()
                .map(|fc| FromClause::from_cst_with_context(fc, ctx))
                .unwrap_or_else(|| {
                    TableReference {
                        span: Span::NONE,
                        target: ctx
                            .error("missing from clause in quantified pattern")
                            .at(qctx)
                            .emit()
                            .into(),
                    }
                    .into()
                }),
        );

        let quantifier = qctx
            .quantifier()
            .map(|q| Arc::new(Quantifier::from_cst_with_context(q, ctx)));

        Self {
            span: interval(qctx).into(),
            from_clause,
            quantifier,
        }
    }
}

// ============================================================================
// NestedPattern - Nested patterns with quantifier (like ParenthesizedExpression)
// ============================================================================

#[derive(Debug, Clone)]
pub struct NestedPattern {
    pub span: Span,
    pub patterns: Vec<Arc<Pattern>>,
    pub quantifier: Arc<Quantifier>,
}

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

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

impl NestedPattern {
    fn from_ast_with_context(nctx: &NestedContext<'static>, ctx: &mut ParseContext) -> Self {
        let patterns = nctx
            .pattern_all()
            .into_iter()
            .map(|p| Arc::new(Pattern::from_cst_with_context(p, ctx)))
            .collect();

        let quantifier = Arc::new(
            nctx.quantifier()
                .map(|q| Quantifier::from_cst_with_context(q, ctx))
                .unwrap_or_else(|| {
                    ctx.error("missing quantifier in nested pattern")
                        .at(nctx)
                        .emit()
                        .into()
                }),
        );

        Self {
            span: interval(nctx).into(),
            patterns,
            quantifier,
        }
    }
}

// ============================================================================
// Quantifier - Pattern quantifiers (+, *, ?, {n})
// ============================================================================

#[derive(Debug, Clone)]
pub struct Quantifier {
    pub span: Span,
    pub kind: QuantifierKind,
}

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

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

impl From<QuantifierKind> for Quantifier {
    fn from(kind: QuantifierKind) -> Self {
        Self {
            span: Span::NONE,
            kind,
        }
    }
}

impl From<Arc<TranslationError>> for Quantifier {
    fn from(error: Arc<TranslationError>) -> Self {
        Self {
            span: Span::NONE,
            kind: QuantifierKind::Error(error),
        }
    }
}

impl FromCst<Rc<QuantifierContextAll<'static>>> for Quantifier {
    fn from_cst_with_context(
        cst: Rc<QuantifierContextAll<'static>>,
        ctx: &mut ParseContext,
    ) -> Self {
        let kind = QuantifierKind::from_cst_with_context(Rc::clone(&cst), ctx);
        Self {
            span: interval(cst.as_ref()).into(),
            kind,
        }
    }
}

#[derive(Debug, Clone, From, PartialEq)]
pub enum QuantifierKind {
    AtLeastOne,      // +
    AnyNumber,       // *
    ZeroOrOne,       // ?
    Exactly(String), // {n}
    Error(Arc<TranslationError>),
}

impl FromCst<Rc<QuantifierContextAll<'static>>> for QuantifierKind {
    fn from_cst_with_context(
        cst: Rc<QuantifierContextAll<'static>>,
        ctx: &mut ParseContext,
    ) -> Self {
        match cst.as_ref() {
            QuantifierContextAll::AtLeastOneContext(_) => QuantifierKind::AtLeastOne,
            QuantifierContextAll::AnyNumberContext(_) => QuantifierKind::AnyNumber,
            QuantifierContextAll::ZeroOrOneContext(_) => QuantifierKind::ZeroOrOne,
            QuantifierContextAll::ExactlyContext(ectx) => match ectx.INTEGER_VALUE() {
                Some(v) => {
                    QuantifierKind::Exactly(strip_numeric_separators(&v.get_text()).into_owned())
                }
                None => ctx
                    .error("missing integer value in exact quantifier")
                    .at(ectx)
                    .emit()
                    .into(),
            },
            QuantifierContextAll::Error(_) => {
                ctx.error("parse error").at(cst.as_ref()).emit().into()
            }
        }
    }
}

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

impl Pattern {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        self.kind.fmt_indented(f, indentation)
    }
}

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

impl PatternKind {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        match self {
            PatternKind::Quantified(q) => q.fmt_indented(f, indentation),
            PatternKind::Nested(n) => n.fmt_indented(f, indentation),
            PatternKind::Error(_) => write!(f, "?!"),
        }
    }
}

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

impl NestedPattern {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        write!(f, "(")?;
        for (i, pat) in self.patterns.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            pat.fmt_indented(f, indentation + 1)?;
        }
        write!(f, ")")?;
        write!(f, "{}", self.quantifier)
    }
}

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

impl Display for QuantifierKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            QuantifierKind::AtLeastOne => write!(f, "+"),
            QuantifierKind::AnyNumber => write!(f, "*"),
            QuantifierKind::ZeroOrOne => write!(f, "?"),
            QuantifierKind::Exactly(n) => write!(f, "{{{}}}", n),
            QuantifierKind::Error(_) => write!(f, "?!"),
        }
    }
}