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