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