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