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