Skip to main content

rudb_parse/
ast.rs

1//! rudb's abstract syntax tree.
2//!
3//! The parse tree the matcher produces is DuckDB's grammar, faithfully. That is the point of it and
4//! it is also why nothing downstream should read it: a bump of the vendored grammar is allowed to
5//! rename `BetweenInLikeExpression`, and if the binder is matching on that name then the bump is a
6//! rewrite. This module is the boundary. It is ours, it changes when we decide it changes, and
7//! `transform` is the one place that knows both shapes.
8//!
9//! Everything is an arena with `u32` indices, per `spec/04-architecture.md` section 4.5. There is
10//! no `Box` and no `Vec` inside a node. A list of children is a [`Slice`] into a side vector, which
11//! means a node is a fixed size, the whole tree is a handful of allocations, and walking it is a
12//! sequential read rather than a pointer chase per node. It also means an `Ast` is `Clone` and
13//! `Send` without any thought, and that a subtree can be addressed by a `u32` in a plan or an
14//! error without borrowing anything.
15//!
16//! The one cost is that you cannot hold a reference to a node and index the arena at the same time,
17//! so the code reads a node out by value first. Nodes are small and `Copy`, so that is a register
18//! move.
19
20use rudb_common::Span;
21
22use crate::matcher::NONE;
23
24/// A run of items in one of the side vectors.
25///
26/// Empty is `len == 0`, and `start` is then meaningless rather than wrong. There is no `Option`
27/// wrapper because an absent list and an empty list are the same thing everywhere this is used.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
29pub struct Slice {
30    /// The first item.
31    pub start: u32,
32    /// How many items.
33    pub len: u32,
34}
35
36impl Slice {
37    /// Whether the run is empty.
38    pub const fn is_empty(self) -> bool {
39        self.len == 0
40    }
41
42    /// The run as a range, for indexing the backing vector.
43    pub const fn range(self) -> std::ops::Range<usize> {
44        self.start as usize..(self.start + self.len) as usize
45    }
46}
47
48/// An index into `Ast::strings`.
49pub type StrRef = u32;
50/// An index into `Ast::exprs`.
51pub type ExprRef = u32;
52/// An index into `Ast::sources`.
53pub type SourceRef = u32;
54/// An index into `Ast::queries`.
55pub type QueryRef = u32;
56/// An index into `Ast::selects`.
57pub type SelectRef = u32;
58/// An index into `Ast::create_tables`.
59pub type CreateTableRef = u32;
60/// An index into `Ast::create_views`.
61pub type CreateViewRef = u32;
62/// An index into `Ast::drop_tables`.
63pub type DropTableRef = u32;
64/// An index into `Ast::inserts`.
65pub type InsertRef = u32;
66/// An index into `Ast::settings`.
67pub type SettingRef = u32;
68/// An index into `Ast::windows`.
69pub type WindowRef = u32;
70
71/// One statement.
72///
73/// Seven of the twenty seven the grammar reaches. The rest are a transform error naming the rule
74/// rather than a variant that nothing fills in, so that adding one is a compile error somewhere
75/// useful rather than a silent `todo!()`.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum Statement {
78    /// A query, meaning a `SELECT` or a set operation over two of them.
79    Query(QueryRef),
80    /// `CREATE TABLE`.
81    CreateTable(CreateTableRef),
82    /// `CREATE VIEW`.
83    CreateView(CreateViewRef),
84    /// `DROP TABLE` or `DROP VIEW`, which are one rule in the grammar and one statement here.
85    DropTable(DropTableRef),
86    /// `INSERT INTO`.
87    Insert(InsertRef),
88    /// `SET name = value`.
89    Set(SettingRef),
90    /// `RESET name`, which is the same shape with nothing on the right of it.
91    Reset(SettingRef),
92    /// `CHECKPOINT` or `FORCE CHECKPOINT`.
93    Checkpoint,
94    /// `EXPLAIN` over a query, and whether `ANALYZE` was asked for.
95    ///
96    /// The query rather than a statement, because the grammar lets every statement be explained
97    /// and a plan is the only thing there is to show. `EXPLAIN INSERT` is a refusal rather than a
98    /// plan of the source, since the source is not what the statement does.
99    ///
100    /// `ANALYZE` means the query is run and the plan is printed with what happened on it, so it is
101    /// a flag on the same statement rather than a statement of its own. Everything between the
102    /// parser and the printer is the same either way, which is the point: the analyzed plan has to
103    /// be the plan that ran.
104    Explain { query: QueryRef, analyze: bool },
105}
106
107/// `SET name = value` and `RESET name`.
108///
109/// One struct for the two, because `RESET name` is `SET name` with no value and giving it its own
110/// arena would mean two of everything to say the same thing twice.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct Setting {
113    /// The setting name, as written.
114    pub name: StrRef,
115    /// The scope word, if one was written.
116    pub scope: Scope,
117    /// The value, or `NONE` for a `RESET`.
118    ///
119    /// An expression rather than text. `SET memory_limit = '1GB'` writes a string and `SET threads
120    /// = 4` writes a number, and what a setting does with either is the setting's business.
121    pub value: ExprRef,
122}
123
124/// Which copy of a setting a statement means.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
126pub enum Scope {
127    /// No scope word, which every setting reads as the one it has.
128    #[default]
129    Unwritten,
130    /// `GLOBAL`.
131    Global,
132    /// `SESSION`.
133    Session,
134    /// `LOCAL`.
135    Local,
136}
137
138impl Scope {
139    /// The word that was written, for the sentence an error prints.
140    #[must_use]
141    pub const fn keyword(self) -> &'static str {
142        match self {
143            Self::Unwritten => "",
144            Self::Global => "GLOBAL",
145            Self::Session => "SESSION",
146            Self::Local => "LOCAL",
147        }
148    }
149}
150
151/// `CREATE TABLE name (columns)` or `CREATE TABLE name AS query`.
152///
153/// Exactly one of `columns` and `query` says what the table is. A column list is the ordinary form
154/// and `query` is `CREATE TABLE AS`, where the columns come from what the query produced and the
155/// only thing the syntax contributes is optionally renaming them, which is `columns` with the types
156/// left as `NONE`.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub struct CreateTable {
159    /// The table name, as a run of [`Slice`] parts, outermost first.
160    pub name: Slice,
161    /// The column definitions, as a run of [`ColumnDef`].
162    pub columns: Slice,
163    /// The `AS` query, or `NONE`.
164    pub query: QueryRef,
165    /// Whether `IF NOT EXISTS` was written.
166    pub if_not_exists: bool,
167    /// Whether `OR REPLACE` was written.
168    pub or_replace: bool,
169    /// Whether `TEMP` or `TEMPORARY` was written.
170    pub temporary: bool,
171}
172
173/// One column of a `CREATE TABLE`.
174///
175/// The type is the text as written rather than a resolved type, because resolving a type is the
176/// binder's job and this crate is syntax. `VARCHAR(10)` and `STRUCT(a INTEGER)` reach the binder
177/// as themselves.
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub struct ColumnDef {
180    /// The column name.
181    pub name: StrRef,
182    /// The type as written, or `NONE` when the definition had none, which only `CREATE TABLE AS`
183    /// allows.
184    pub ty: StrRef,
185    /// Whether `NOT NULL` was written.
186    pub not_null: bool,
187}
188
189/// `CREATE VIEW name (columns) AS query`.
190///
191/// The body is kept twice over, as a bound reference into this same arena and as the text that was
192/// written. Both are needed and they are needed for different things. The reference is what binds
193/// the body at creation, which is where a view over a table that is not there is refused. The text
194/// is what the catalog keeps, because a view is bound again at every reference rather than frozen
195/// at creation: a view over `SELECT * FROM t` follows `t` when a column is added to it, which was
196/// measured, and the only way to follow it is to have the query to bind again.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub struct CreateView {
199    /// The view name, as a run of [`Slice`] parts, outermost first.
200    pub name: Slice,
201    /// The column aliases, as a run of parts, empty when the statement wrote no list.
202    pub columns: Slice,
203    /// The body.
204    pub query: QueryRef,
205    /// The body as it was written, which is what the catalog keeps.
206    pub sql: StrRef,
207    /// Whether `IF NOT EXISTS` was written.
208    pub if_not_exists: bool,
209    /// Whether `OR REPLACE` was written.
210    pub or_replace: bool,
211    /// Whether `TEMP` or `TEMPORARY` was written.
212    pub temporary: bool,
213}
214
215/// `DROP TABLE a, b` or `DROP VIEW a, b`.
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub struct DropTable {
218    /// The names, as a run of [`Slice`] into `Ast::name_lists`, each of which is a run of parts.
219    pub names: Slice,
220    /// Whether `IF EXISTS` was written.
221    pub if_exists: bool,
222    /// Whether `VIEW` was written where `TABLE` could have been. Dropping one as the other is an
223    /// error rather than a synonym, so which word was written has to survive the transform.
224    pub view: bool,
225}
226
227/// `INSERT INTO name (columns) query`.
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
229pub struct Insert {
230    /// The table name, as a run of parts, outermost first.
231    pub name: Slice,
232    /// The column list, as a run of parts, empty when the statement did not write one.
233    pub columns: Slice,
234    /// What produces the rows, which is a `VALUES` clause or any other query.
235    pub source: QueryRef,
236}
237
238/// A query: a body, plus the modifiers that apply to whatever the body produced.
239///
240/// The split is the grammar's, not an invention. `SelectStatementInternal <- WithClause?
241/// SelectSetOpChain ResultModifiers?` puts `ORDER BY` and `LIMIT` outside the set operator chain,
242/// which is the only place they can go and be right: `a UNION b ORDER BY x` sorts the union and not
243/// the second half of it. Hanging them off `Select` instead would have made that unrepresentable.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub struct Query {
246    /// What produces the rows.
247    pub body: QueryBody,
248    /// The `ORDER BY` list, as a run of [`OrderItem`].
249    pub order_by: Slice,
250    /// Whether the clause was `ORDER BY ALL`.
251    pub order_by_all: bool,
252    /// The `LIMIT` expression, or `NONE`.
253    pub limit: ExprRef,
254    /// Whether the limit was a percentage rather than a row count.
255    pub limit_percent: bool,
256    /// The `OFFSET` expression, or `NONE`.
257    pub offset: ExprRef,
258}
259
260impl Query {
261    /// A query with no modifiers on it.
262    pub const fn bare(body: QueryBody) -> Self {
263        Self {
264            body,
265            order_by: Slice { start: 0, len: 0 },
266            order_by_all: false,
267            limit: NONE,
268            limit_percent: false,
269            offset: NONE,
270        }
271    }
272}
273
274/// What produces the rows of a query.
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276pub enum QueryBody {
277    /// One `SELECT ... FROM ... WHERE ...` block.
278    Select(SelectRef),
279    /// `UNION`, `EXCEPT` or `INTERSECT` over two queries.
280    SetOp {
281        /// Which operator.
282        op: SetOp,
283        /// Whether duplicates survive.
284        quantifier: Quantifier,
285        /// Whether the columns are matched up by name rather than by position.
286        by_name: bool,
287        /// The query on the left.
288        left: QueryRef,
289        /// The query on the right.
290        right: QueryRef,
291    },
292    /// `VALUES (1, 'a'), (2, 'b')`, as a run of [`Slice`] in `Ast::rows`.
293    ///
294    /// A row count and a column count and nothing else, so it is a query body rather than a
295    /// statement of its own. That is also what makes `INSERT INTO t VALUES (1)` and
296    /// `INSERT INTO t SELECT 1` the same shape by the time anything downstream sees them, which is
297    /// the reason the insert walker does not have two arms.
298    Values(Slice),
299    /// `DESCRIBE SELECT ...`, `DESCRIBE t` and `DESCRIBE 'file.parquet'`.
300    ///
301    /// A query body rather than a statement, because that is where the grammar puts it:
302    /// `SelectStatementType <- ... / DescribeStatement / ...`, so `FROM (DESCRIBE SELECT 1)` is a
303    /// subquery over one and needs no rule of its own. The two spellings that name something
304    /// instead of writing a query arrive here as `DESCRIBE SELECT * FROM that`, which is not a
305    /// shortcut: on the reference binary `DESCRIBE t` and `DESCRIBE SELECT * FROM t` produce the
306    /// same six columns and the same rows, down to the primary key and the default.
307    Describe(QueryRef),
308    /// `SHOW name`, resolved as a setting or a deprecated table description while binding.
309    Show { name: Slice, relation: QueryRef },
310}
311
312/// Which set operator.
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
314pub enum SetOp {
315    /// `UNION`.
316    Union,
317    /// `EXCEPT`.
318    Except,
319    /// `INTERSECT`.
320    Intersect,
321}
322
323/// Whether a set operator or an aggregate keeps duplicates.
324///
325/// `Unstated` is not the same as `All` even though the two agree for `UNION`, because they disagree
326/// for `INTERSECT` in some dialects and because an error message that says what was written is
327/// better than one that says what it was taken to mean.
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
329pub enum Quantifier {
330    /// Neither word was written.
331    Unstated,
332    /// `ALL`.
333    All,
334    /// `DISTINCT`.
335    Distinct,
336}
337
338/// What the `DISTINCT` clause of a select said.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340pub enum Distinct {
341    /// No clause, or the no-op `SELECT ALL`.
342    No,
343    /// `SELECT DISTINCT`.
344    Yes,
345    /// `SELECT DISTINCT ON (a, b)`, holding the expressions in the parentheses.
346    On(Slice),
347}
348
349/// One select block.
350///
351/// Every optional expression is `NONE` when it is absent rather than an `Option<u32>`, which keeps
352/// the struct at forty bytes and keeps the absent case spelled the same way it is spelled in the
353/// parse tree arena.
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355pub struct Select {
356    /// The `DISTINCT` clause.
357    pub distinct: Distinct,
358    /// The target list, as a run of [`Target`].
359    pub targets: Slice,
360    /// The `FROM` list, as a run of [`SourceRef`]. Several entries mean a cross product.
361    pub from: Slice,
362    /// The `WHERE` expression, or `NONE`.
363    pub filter: ExprRef,
364    /// The `GROUP BY` list, as a run of [`ExprRef`].
365    pub group_by: Slice,
366    /// Whether the clause was `GROUP BY ALL`.
367    pub group_by_all: bool,
368    /// The `HAVING` expression, or `NONE`.
369    pub having: ExprRef,
370}
371
372impl Select {
373    /// An empty select, which is what the transformer fills in from.
374    pub const fn empty() -> Self {
375        Self {
376            distinct: Distinct::No,
377            targets: Slice { start: 0, len: 0 },
378            from: Slice { start: 0, len: 0 },
379            filter: NONE,
380            group_by: Slice { start: 0, len: 0 },
381            group_by_all: false,
382            having: NONE,
383        }
384    }
385}
386
387/// One entry of a target list.
388#[derive(Debug, Clone, Copy, PartialEq, Eq)]
389pub struct Target {
390    /// What is being selected.
391    pub expr: ExprRef,
392    /// The alias, or `NONE`. The binder invents one when there is none, because what it invents
393    /// depends on the expression and that is a binder question rather than a parser question.
394    pub alias: StrRef,
395}
396
397/// One entry of an order by list.
398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
399pub struct OrderItem {
400    /// What to sort on.
401    pub expr: ExprRef,
402    /// The direction.
403    pub order: Order,
404    /// Where nulls go.
405    pub nulls: Nulls,
406}
407
408/// Sort direction, with the unwritten case kept apart from the default it resolves to.
409#[derive(Debug, Clone, Copy, PartialEq, Eq)]
410pub enum Order {
411    /// Nothing was written.
412    Unstated,
413    /// `ASC` or `ASCENDING`.
414    Ascending,
415    /// `DESC` or `DESCENDING`.
416    Descending,
417}
418
419/// Null placement in a sort.
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421pub enum Nulls {
422    /// Nothing was written, so the session default applies.
423    Unstated,
424    /// `NULLS FIRST`.
425    First,
426    /// `NULLS LAST`.
427    Last,
428}
429
430/// How a window frame measures the distance to its bounds.
431#[derive(Debug, Clone, Copy, PartialEq, Eq)]
432pub enum WindowUnit {
433    /// `ROWS`, so a bound counts rows.
434    Rows,
435    /// `RANGE`, so a bound is a value offset from the current row's sort key.
436    Range,
437    /// `GROUPS`, so a bound counts runs of rows that tie on the sort key.
438    Groups,
439}
440
441/// One end of a window frame.
442#[derive(Debug, Clone, Copy, PartialEq, Eq)]
443pub enum WindowBound {
444    /// `UNBOUNDED PRECEDING`, the first row of the partition.
445    UnboundedPreceding,
446    /// `n PRECEDING`, holding the offset expression.
447    Preceding(ExprRef),
448    /// `CURRENT ROW`.
449    CurrentRow,
450    /// `n FOLLOWING`, holding the offset expression.
451    Following(ExprRef),
452    /// `UNBOUNDED FOLLOWING`, the last row of the partition.
453    UnboundedFollowing,
454}
455
456/// Which peers of the current row the frame drops once its bounds have been applied.
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
458pub enum WindowExclude {
459    /// `EXCLUDE NO OTHERS`, which is also what an unwritten clause means.
460    NoOthers,
461    /// `EXCLUDE CURRENT ROW`.
462    CurrentRow,
463    /// `EXCLUDE GROUP`, dropping the current row and everything that ties with it.
464    Group,
465    /// `EXCLUDE TIES`, dropping everything that ties with the current row but keeping it.
466    Ties,
467}
468
469/// Everything inside the parentheses of an `OVER`.
470///
471/// A named window is resolved here rather than downstream, because the resolution is a parser
472/// question on the reference binary: a reference to a window nobody defined is a `Parser Error`
473/// there, and a view written with `OVER w` comes back out of the catalog with the definition
474/// inlined. So nothing after the transform ever sees a name, and there is no window clause on
475/// [`Select`] for it to see one in.
476#[derive(Debug, Clone, Copy, PartialEq, Eq)]
477pub struct WindowSpec {
478    /// The `PARTITION BY` list, as a run of [`ExprRef`], empty when there was no clause.
479    pub partition: Slice,
480    /// The `ORDER BY` list, as a run of [`OrderItem`], empty when there was no clause.
481    pub order: Slice,
482    /// Which of the three units the bounds are measured in.
483    pub unit: WindowUnit,
484    /// Where the frame starts.
485    pub start: WindowBound,
486    /// Where the frame ends.
487    pub end: WindowBound,
488    /// Which peers the frame drops.
489    pub exclude: WindowExclude,
490}
491
492impl WindowSpec {
493    /// The frame a window with no frame clause gets, which the standard fixes and DuckDB follows.
494    pub const DEFAULT_UNIT: WindowUnit = WindowUnit::Range;
495    /// The start a window with no frame clause gets.
496    pub const DEFAULT_START: WindowBound = WindowBound::UnboundedPreceding;
497    /// The end a window with no frame clause gets.
498    pub const DEFAULT_END: WindowBound = WindowBound::CurrentRow;
499
500    /// A window with no clauses at all, which is what `OVER ()` means.
501    pub const fn empty() -> Self {
502        Self {
503            partition: Slice { start: 0, len: 0 },
504            order: Slice { start: 0, len: 0 },
505            unit: Self::DEFAULT_UNIT,
506            start: Self::DEFAULT_START,
507            end: Self::DEFAULT_END,
508            exclude: WindowExclude::NoOthers,
509        }
510    }
511
512    /// Whether the frame is the one an unwritten frame clause means.
513    ///
514    /// This is what decides whether the frame is printed, which is not a matter of taste: the
515    /// printed form is the column name a window target gets when the query wrote no alias, so
516    /// `SELECT sum(x) OVER (ORDER BY x)` has to be named without a frame in it to agree with the
517    /// reference binary.
518    pub fn frame_is_default(&self) -> bool {
519        self.unit == Self::DEFAULT_UNIT
520            && self.start == Self::DEFAULT_START
521            && self.end == Self::DEFAULT_END
522            && self.exclude == WindowExclude::NoOthers
523    }
524}
525
526/// One entry in a `FROM` clause, which is a tree because joins nest.
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528pub enum Source {
529    /// A named table, possibly qualified by schema and catalog.
530    Table {
531        /// The name, as a run of [`StrRef`] in `Ast::parts`, outermost first.
532        name: Slice,
533        /// The alias, or `NONE`.
534        alias: StrRef,
535        /// Column aliases from `AS t(a, b)`, as a run of [`StrRef`].
536        columns: Slice,
537    },
538    /// A parenthesised query in the `FROM` clause.
539    Subquery {
540        /// The query.
541        query: QueryRef,
542        /// The alias, or `NONE`.
543        alias: StrRef,
544        /// Column aliases, as a run of [`StrRef`].
545        columns: Slice,
546    },
547    /// A function call where a table goes, such as `range(10)`.
548    ///
549    /// Held with the name as a qualified run rather than a single string, because `main.range(10)`
550    /// is legal and a function in a schema that does not exist has to say so rather than being
551    /// looked up unqualified and found.
552    Function {
553        /// The name, as a run of [`StrRef`] in `Ast::parts`, outermost first.
554        name: Slice,
555        /// The arguments, as a run of [`Target`] where the alias is the parameter name and is
556        /// `NONE` for a positional one.
557        args: Slice,
558        /// The alias, or `NONE`.
559        alias: StrRef,
560        /// Column aliases from `AS t(a, b)`, as a run of [`StrRef`].
561        columns: Slice,
562        /// Whether the call was written as `PRAGMA name` rather than as a function call.
563        ///
564        /// The two are the same query, because `PRAGMA table_info('t')` is rewritten to
565        /// `SELECT * FROM pragma_table_info('t')` here the way upstream rewrites it, and the
566        /// rewritten form is what the plan and the deparser see. What the flag is for is the two
567        /// messages a bad call produces, which upstream writes in the spelling the user used:
568        /// `table_info()` rather than `pragma_table_info()`, and a candidate line reading
569        /// `PRAGMA "table_info"(VARCHAR)`. A user who wrote a pragma and is told about a function
570        /// they did not name has been handed the rewrite to debug rather than their own statement.
571        pragma: bool,
572    },
573    /// A `VALUES` in the `FROM` clause.
574    Values {
575        /// The rows, as a run of [`Slice`] in `Ast::rows`.
576        rows: Slice,
577        /// The alias, or `NONE`.
578        alias: StrRef,
579        /// Column aliases, as a run of [`StrRef`].
580        columns: Slice,
581    },
582    /// Two sources joined.
583    Join {
584        /// The left side.
585        left: SourceRef,
586        /// The right side.
587        right: SourceRef,
588        /// Which join.
589        kind: JoinKind,
590        /// Whether it was written `NATURAL`.
591        natural: bool,
592        /// The `ON` expression, or `NONE`.
593        on: ExprRef,
594        /// The `USING` column list, as a run of [`StrRef`].
595        using: Slice,
596    },
597}
598
599/// Which join.
600#[derive(Debug, Clone, Copy, PartialEq, Eq)]
601pub enum JoinKind {
602    /// `[INNER] JOIN`.
603    Inner,
604    /// `LEFT [OUTER] JOIN`.
605    Left,
606    /// `RIGHT [OUTER] JOIN`.
607    Right,
608    /// `FULL [OUTER] JOIN`.
609    Full,
610    /// `SEMI JOIN`.
611    Semi,
612    /// `ANTI JOIN`.
613    Anti,
614    /// `CROSS JOIN`.
615    Cross,
616    /// `POSITIONAL JOIN`, which is DuckDB's own and pairs rows by ordinal.
617    Positional,
618}
619
620/// One expression.
621///
622/// Twenty four bytes, which is the widest variant rounded up. The precedence chain in the grammar
623/// does not survive into here: twenty levels of `X <- Y Tail*` become one [`Expr::Binary`] tree,
624/// because the levels exist to make the grammar unambiguous and mean nothing afterwards.
625#[derive(Debug, Clone, Copy, PartialEq, Eq)]
626pub enum Expr {
627    /// `*`, or `t.*` with a qualifier.
628    Star {
629        /// The qualifier, as a run of [`StrRef`], empty for a bare star.
630        qualifier: Slice,
631        /// `REPLACE (expression AS column)`, as a run of [`Target`] where the alias is the column
632        /// being replaced, empty for a star with no replace list.
633        ///
634        /// A [`Target`] rather than a type of its own because a replacement is an expression and a
635        /// name, which is exactly what a target is, and because that puts it in the arena every
636        /// other expression and name pair already lives in.
637        replacements: Slice,
638    },
639    /// A column reference, qualified or not.
640    Column {
641        /// The name, as a run of [`StrRef`], outermost first, so `s.t.a` is three parts.
642        name: Slice,
643    },
644    /// A literal, kept as the text that was written.
645    Literal {
646        /// Which kind.
647        kind: LiteralKind,
648        /// The text, with quotes stripped and escapes resolved for a string, `NONE` for a keyword
649        /// literal like `NULL` where the kind already says everything.
650        text: StrRef,
651    },
652    /// A prefix or postfix operator.
653    Unary {
654        /// Which operator.
655        op: UnaryOp,
656        /// What it applies to.
657        operand: ExprRef,
658    },
659    /// An infix operator.
660    Binary {
661        /// Which operator.
662        op: BinaryOp,
663        /// The left operand.
664        left: ExprRef,
665        /// The right operand.
666        right: ExprRef,
667    },
668    /// A function call.
669    Function {
670        /// The name, as a run of [`StrRef`], so `main.count` is two parts.
671        name: Slice,
672        /// The arguments, as a run of [`ExprRef`].
673        args: Slice,
674        /// Whether the call said `DISTINCT`.
675        distinct: bool,
676    },
677    /// A function call with an `OVER` on the end of it.
678    ///
679    /// Kept apart from [`Expr::Function`] rather than given an optional window, because the two
680    /// are different things by every rule that applies to them: a window call is refused in a
681    /// `WHERE` and in a `HAVING`, it may not appear inside an aggregate, and it resolves against a
682    /// different set of names. A variant that only some of the code has to remember to look at is
683    /// a variant the rest of the code gets wrong.
684    Window {
685        /// The name, as a run of [`StrRef`], so `main.sum` is two parts.
686        name: Slice,
687        /// The arguments, as a run of [`ExprRef`].
688        args: Slice,
689        /// Whether the call said `DISTINCT`.
690        distinct: bool,
691        /// Whether the call said `IGNORE NULLS`. `RESPECT NULLS` is the default and is not kept,
692        /// because the reference binary drops it: a view written with it comes back without it.
693        ignore_nulls: bool,
694        /// The window itself, into `Ast::windows`.
695        spec: WindowRef,
696    },
697    /// `CAST(x AS t)` or `TRY_CAST(x AS t)`.
698    Cast {
699        /// What is being cast.
700        operand: ExprRef,
701        /// The target type, as the text it was written with. Parsing it is `rudb-common`'s job and
702        /// doing it here would put the type system in the parser.
703        ty: StrRef,
704        /// Whether a failure yields null rather than an error.
705        try_cast: bool,
706    },
707    /// `CASE`, searched or simple.
708    Case {
709        /// The operand of a simple `CASE x WHEN`, or `NONE` for a searched one.
710        operand: ExprRef,
711        /// The arms, as a run of [`CaseArm`].
712        arms: Slice,
713        /// The `ELSE`, or `NONE`.
714        otherwise: ExprRef,
715    },
716    /// `x BETWEEN a AND b`.
717    Between {
718        /// What is being tested.
719        operand: ExprRef,
720        /// The lower bound.
721        low: ExprRef,
722        /// The upper bound.
723        high: ExprRef,
724        /// Whether it was written `NOT BETWEEN`.
725        negated: bool,
726    },
727    /// `x IN (a, b, c)`.
728    In {
729        /// What is being tested.
730        operand: ExprRef,
731        /// The list, as a run of [`ExprRef`].
732        list: Slice,
733        /// Whether it was written `NOT IN`.
734        negated: bool,
735    },
736    /// `x IN (SELECT ...)` or its negation.
737    InSubquery {
738        /// What is being tested.
739        operand: ExprRef,
740        /// The query producing the candidates.
741        query: QueryRef,
742        /// Whether it was written `NOT IN`.
743        negated: bool,
744    },
745    /// `x op ANY (SELECT ...)` or `x op ALL (SELECT ...)`.
746    QuantifiedSubquery {
747        /// The value on the left of the comparison.
748        operand: ExprRef,
749        /// The comparison applied to each candidate.
750        op: BinaryOp,
751        /// The query producing the candidates.
752        query: QueryRef,
753        /// Whether the quantifier was `ALL` rather than `ANY`.
754        all: bool,
755    },
756    /// A prepared statement parameter, written `?`, `?1`, `$1` or `$name`.
757    Parameter {
758        /// The identifier, which is the number for a positional one and the word for a named one.
759        /// A bare `?` is numbered by where it was written, so the identifier is there either way.
760        name: StrRef,
761    },
762    /// A bracketed list of expressions, `[a, b, c]`, which is a LIST value.
763    List {
764        /// The items, as a run of [`ExprRef`], in the order they were written.
765        items: Slice,
766    },
767    /// A parenthesised list of more than one expression, which is a row value.
768    Row {
769        /// The items, as a run of [`ExprRef`].
770        items: Slice,
771    },
772    /// A scalar subquery, `(SELECT ...)` where an expression is expected.
773    Subquery {
774        /// The query.
775        query: QueryRef,
776    },
777    /// `EXISTS (SELECT ...)` or its negation.
778    Exists {
779        /// The query whose cardinality is tested.
780        query: QueryRef,
781        /// Whether `NOT` was written before `EXISTS`.
782        negated: bool,
783    },
784}
785
786/// One `WHEN a THEN b`.
787#[derive(Debug, Clone, Copy, PartialEq, Eq)]
788pub struct CaseArm {
789    /// The `WHEN`.
790    pub when: ExprRef,
791    /// The `THEN`.
792    pub then: ExprRef,
793}
794
795/// Which literal.
796#[derive(Debug, Clone, Copy, PartialEq, Eq)]
797pub enum LiteralKind {
798    /// A number, kept as text because the width it wants depends on where it lands.
799    Number,
800    /// A string.
801    String,
802    /// A blob, kept as the text a blob prints as, which is the text a cast reads it back from.
803    Blob,
804    /// `NULL`.
805    Null,
806    /// `TRUE`.
807    True,
808    /// `FALSE`.
809    False,
810}
811
812/// A prefix or postfix operator.
813#[derive(Debug, Clone, Copy, PartialEq, Eq)]
814pub enum UnaryOp {
815    /// `NOT x`.
816    Not,
817    /// `-x`.
818    Negate,
819    /// `+x`, which is a no-op that still has to survive to the binder so that `+'a'` errors.
820    Plus,
821    /// `~x`.
822    BitNot,
823    /// `x!`.
824    Factorial,
825    /// `x IS NULL` or `x ISNULL`.
826    IsNull,
827    /// `x IS NOT NULL` or `x NOTNULL`.
828    IsNotNull,
829    /// `x IS TRUE`.
830    IsTrue,
831    /// `x IS NOT TRUE`.
832    IsNotTrue,
833    /// `x IS FALSE`.
834    IsFalse,
835    /// `x IS NOT FALSE`.
836    IsNotFalse,
837    /// `x IS UNKNOWN`.
838    IsUnknown,
839    /// `x IS NOT UNKNOWN`.
840    IsNotUnknown,
841}
842
843/// An infix operator.
844///
845/// The list is the dialect and not a general idea of what operators are. `Named` is the one open
846/// door, because `OperatorLiteral` in the grammar takes any run of operator characters that is not
847/// already a token, and rejecting that here would reject SQL DuckDB accepts.
848#[derive(Debug, Clone, Copy, PartialEq, Eq)]
849pub enum BinaryOp {
850    /// `OR`.
851    Or,
852    /// `AND`.
853    And,
854    /// `=` or `==`.
855    Eq,
856    /// `!=` or `<>`.
857    NotEq,
858    /// `<`.
859    Lt,
860    /// `>`.
861    Gt,
862    /// `<=`.
863    LtEq,
864    /// `>=`.
865    GtEq,
866    /// `IS DISTINCT FROM`.
867    IsDistinctFrom,
868    /// `IS NOT DISTINCT FROM`.
869    IsNotDistinctFrom,
870    /// `+`.
871    Add,
872    /// `-`.
873    Subtract,
874    /// `*`.
875    Multiply,
876    /// `/`.
877    Divide,
878    /// `//`, integer division.
879    IntegerDivide,
880    /// `%`.
881    Modulo,
882    /// `^` or `**`.
883    Power,
884    /// `&`.
885    BitAnd,
886    /// `|`.
887    BitOr,
888    /// `<<`.
889    ShiftLeft,
890    /// `>>`.
891    ShiftRight,
892    /// `||`.
893    Concat,
894    /// `LIKE` or `~~`.
895    Like,
896    /// `NOT LIKE` or `!~~`.
897    NotLike,
898    /// `ILIKE` or `~~*`.
899    ILike,
900    /// `NOT ILIKE` or `!~~*`.
901    NotILike,
902    /// `GLOB` or `~~~`.
903    Glob,
904    /// `SIMILAR TO`.
905    SimilarTo,
906    /// `NOT SIMILAR TO`.
907    NotSimilarTo,
908    /// `~`, a regex match.
909    Regex,
910    /// `!~`, a negated regex match.
911    NotRegex,
912    /// `~*`, a case insensitive regex match.
913    RegexInsensitive,
914    /// `!~*`, a negated case insensitive regex match.
915    NotRegexInsensitive,
916    /// `COLLATE`.
917    Collate,
918    /// `AT TIME ZONE`.
919    AtTimeZone,
920    /// `->`.
921    Arrow,
922    /// `->>`.
923    LongArrow,
924    /// `@>`, contains.
925    Contains,
926    /// `<@`, contained by.
927    ContainedBy,
928    /// `&&`, overlaps.
929    Overlaps,
930    /// `^@`, starts with.
931    StartsWith,
932    /// `<<=`, an inet operator.
933    InetContainedByOrEq,
934    /// `>>=`, an inet operator.
935    InetContainsOrEq,
936    /// An operator the dialect does not name, which DuckDB resolves as a binary function of that
937    /// name. `a <=> b` is the shape.
938    Named(StrRef),
939}
940
941/// A parsed statement or script, with every arena it points into.
942///
943/// Cheap to clone, cheap to send, and self contained: no index in here refers to anything outside
944/// it, and nothing in here borrows the query text. The text is copied into `strings` on the way in,
945/// which costs one allocation per distinct identifier and buys an `Ast` that outlives the string it
946/// came from.
947#[derive(Debug, Clone, Default, PartialEq, Eq)]
948pub struct Ast {
949    /// The statements in the script, in order.
950    pub statements: Vec<Statement>,
951    /// The query arena.
952    pub queries: Vec<Query>,
953    /// Source ranges parallel to `queries`.
954    pub query_spans: Vec<Span>,
955    /// The select arena.
956    pub selects: Vec<Select>,
957    /// The expression arena.
958    pub exprs: Vec<Expr>,
959    /// Source ranges parallel to `exprs`.
960    pub expr_spans: Vec<Span>,
961    /// The from-item arena.
962    pub sources: Vec<Source>,
963    /// Interned text. Identifiers keep the case they were written in, because DuckDB does not fold
964    /// it at any point, including for quoted identifiers.
965    pub strings: Vec<String>,
966    /// Backing store for every [`Slice`] of names.
967    pub parts: Vec<StrRef>,
968    /// Backing store for every [`Slice`] of expressions.
969    pub expr_lists: Vec<ExprRef>,
970    /// Backing store for every [`Slice`] of from items.
971    pub source_lists: Vec<SourceRef>,
972    /// Backing store for every [`Slice`] of target list entries.
973    pub targets: Vec<Target>,
974    /// Backing store for every [`Slice`] of order by entries.
975    pub order_items: Vec<OrderItem>,
976    /// Backing store for every [`Slice`] of case arms.
977    pub case_arms: Vec<CaseArm>,
978    /// The `CREATE TABLE` arena.
979    pub create_tables: Vec<CreateTable>,
980    /// The `CREATE VIEW` arena.
981    pub create_views: Vec<CreateView>,
982    /// The `DROP TABLE` arena.
983    pub drop_tables: Vec<DropTable>,
984    /// The `INSERT` arena.
985    pub inserts: Vec<Insert>,
986    /// The `SET` and `RESET` arena.
987    pub settings: Vec<Setting>,
988    /// Backing store for every [`Slice`] of column definitions.
989    pub column_defs: Vec<ColumnDef>,
990    /// Backing store for every [`Slice`] of names, which is a name list rather than a name.
991    pub name_lists: Vec<Slice>,
992    /// Backing store for the rows of a `VALUES`, each of which is a run of expressions.
993    pub rows: Vec<Slice>,
994    /// The window arena, holding what was inside the parentheses of every `OVER`.
995    pub windows: Vec<WindowSpec>,
996}
997
998impl Ast {
999    /// The source range of an expression.
1000    pub fn expr_span(&self, expr: ExprRef) -> Span {
1001        self.expr_spans[expr as usize]
1002    }
1003
1004    /// The source range of a query.
1005    pub fn query_span(&self, query: QueryRef) -> Span {
1006        self.query_spans[query as usize]
1007    }
1008
1009    /// The text behind a [`StrRef`], or the empty string for `NONE`.
1010    pub fn string(&self, index: StrRef) -> &str {
1011        if index == NONE { "" } else { &self.strings[index as usize] }
1012    }
1013
1014    /// Every parameter identifier the statement uses, once each, in the order they were written.
1015    ///
1016    /// The arena is built as the walk goes, so its order is the written order, and a parameter used
1017    /// twice is one identifier here because it is one value to provide.
1018    pub fn parameters(&self) -> Vec<&str> {
1019        let mut found: Vec<&str> = Vec::new();
1020        for expr in &self.exprs {
1021            if let Expr::Parameter { name } = *expr {
1022                let name = self.string(name);
1023                if !found.contains(&name) {
1024                    found.push(name);
1025                }
1026            }
1027        }
1028        found
1029    }
1030
1031    /// The parts of a name, outermost first.
1032    pub fn name(&self, slice: Slice) -> impl Iterator<Item = &str> {
1033        self.parts[slice.range()].iter().map(|&part| self.string(part))
1034    }
1035
1036    /// A name written back out with dots between the parts, for error messages and tests.
1037    pub fn name_text(&self, slice: Slice) -> String {
1038        self.name(slice).collect::<Vec<_>>().join(".")
1039    }
1040
1041    /// One expression.
1042    pub fn expr(&self, index: ExprRef) -> Expr {
1043        self.exprs[index as usize]
1044    }
1045
1046    /// One from item.
1047    pub fn source(&self, index: SourceRef) -> Source {
1048        self.sources[index as usize]
1049    }
1050
1051    /// One query.
1052    pub fn query(&self, index: QueryRef) -> Query {
1053        self.queries[index as usize]
1054    }
1055
1056    /// One select block.
1057    pub fn select(&self, index: SelectRef) -> Select {
1058        self.selects[index as usize]
1059    }
1060
1061    /// One window.
1062    pub fn window(&self, index: WindowRef) -> WindowSpec {
1063        self.windows[index as usize]
1064    }
1065
1066    /// The expressions of a list.
1067    pub fn expr_list(&self, slice: Slice) -> &[ExprRef] {
1068        &self.expr_lists[slice.range()]
1069    }
1070
1071    /// The from items of a list.
1072    pub fn source_list(&self, slice: Slice) -> &[SourceRef] {
1073        &self.source_lists[slice.range()]
1074    }
1075
1076    /// The entries of a target list.
1077    pub fn target_list(&self, slice: Slice) -> &[Target] {
1078        &self.targets[slice.range()]
1079    }
1080
1081    /// The entries of an order by list.
1082    pub fn order_list(&self, slice: Slice) -> &[OrderItem] {
1083        &self.order_items[slice.range()]
1084    }
1085
1086    /// The arms of a case.
1087    pub fn arm_list(&self, slice: Slice) -> &[CaseArm] {
1088        &self.case_arms[slice.range()]
1089    }
1090
1091    /// One `CREATE TABLE`.
1092    pub fn create_table(&self, index: CreateTableRef) -> CreateTable {
1093        self.create_tables[index as usize]
1094    }
1095
1096    /// One `CREATE VIEW`.
1097    pub fn create_view(&self, index: CreateViewRef) -> CreateView {
1098        self.create_views[index as usize]
1099    }
1100
1101    /// One `DROP TABLE`.
1102    pub fn drop_table(&self, index: DropTableRef) -> DropTable {
1103        self.drop_tables[index as usize]
1104    }
1105
1106    /// One `INSERT`.
1107    pub fn insert(&self, index: InsertRef) -> Insert {
1108        self.inserts[index as usize]
1109    }
1110
1111    /// One `SET` or `RESET`.
1112    pub fn setting(&self, index: SettingRef) -> Setting {
1113        self.settings[index as usize]
1114    }
1115
1116    /// The column definitions of a `CREATE TABLE`.
1117    pub fn column_defs(&self, slice: Slice) -> &[ColumnDef] {
1118        &self.column_defs[slice.range()]
1119    }
1120
1121    /// The names of a name list, each of which is itself a run of parts.
1122    pub fn name_list(&self, slice: Slice) -> &[Slice] {
1123        &self.name_lists[slice.range()]
1124    }
1125
1126    /// The rows of a `VALUES`, each of which is itself a run of expressions.
1127    pub fn rows(&self, slice: Slice) -> &[Slice] {
1128        &self.rows[slice.range()]
1129    }
1130
1131    /// How many nodes the whole tree is, across every arena.
1132    ///
1133    /// The number to watch when the transformer changes. A parse tree of five thousand nodes that
1134    /// becomes an AST of thirty is the twenty precedence levels being thrown away, which is the
1135    /// whole reason this module exists.
1136    pub fn node_count(&self) -> usize {
1137        self.queries.len() + self.selects.len() + self.exprs.len() + self.sources.len()
1138    }
1139}