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}
283
284/// Which set operator.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum SetOp {
287 /// `UNION`.
288 Union,
289 /// `EXCEPT`.
290 Except,
291 /// `INTERSECT`.
292 Intersect,
293}
294
295/// Whether a set operator or an aggregate keeps duplicates.
296///
297/// `Unstated` is not the same as `All` even though the two agree for `UNION`, because they disagree
298/// for `INTERSECT` in some dialects and because an error message that says what was written is
299/// better than one that says what it was taken to mean.
300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
301pub enum Quantifier {
302 /// Neither word was written.
303 Unstated,
304 /// `ALL`.
305 All,
306 /// `DISTINCT`.
307 Distinct,
308}
309
310/// What the `DISTINCT` clause of a select said.
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312pub enum Distinct {
313 /// No clause, or the no-op `SELECT ALL`.
314 No,
315 /// `SELECT DISTINCT`.
316 Yes,
317 /// `SELECT DISTINCT ON (a, b)`, holding the expressions in the parentheses.
318 On(Slice),
319}
320
321/// One select block.
322///
323/// Every optional expression is `NONE` when it is absent rather than an `Option<u32>`, which keeps
324/// the struct at forty bytes and keeps the absent case spelled the same way it is spelled in the
325/// parse tree arena.
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327pub struct Select {
328 /// The `DISTINCT` clause.
329 pub distinct: Distinct,
330 /// The target list, as a run of [`Target`].
331 pub targets: Slice,
332 /// The `FROM` list, as a run of [`SourceRef`]. Several entries mean a cross product.
333 pub from: Slice,
334 /// The `WHERE` expression, or `NONE`.
335 pub filter: ExprRef,
336 /// The `GROUP BY` list, as a run of [`ExprRef`].
337 pub group_by: Slice,
338 /// Whether the clause was `GROUP BY ALL`.
339 pub group_by_all: bool,
340 /// The `HAVING` expression, or `NONE`.
341 pub having: ExprRef,
342}
343
344impl Select {
345 /// An empty select, which is what the transformer fills in from.
346 pub const fn empty() -> Self {
347 Self {
348 distinct: Distinct::No,
349 targets: Slice { start: 0, len: 0 },
350 from: Slice { start: 0, len: 0 },
351 filter: NONE,
352 group_by: Slice { start: 0, len: 0 },
353 group_by_all: false,
354 having: NONE,
355 }
356 }
357}
358
359/// One entry of a target list.
360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
361pub struct Target {
362 /// What is being selected.
363 pub expr: ExprRef,
364 /// The alias, or `NONE`. The binder invents one when there is none, because what it invents
365 /// depends on the expression and that is a binder question rather than a parser question.
366 pub alias: StrRef,
367}
368
369/// One entry of an order by list.
370#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371pub struct OrderItem {
372 /// What to sort on.
373 pub expr: ExprRef,
374 /// The direction.
375 pub order: Order,
376 /// Where nulls go.
377 pub nulls: Nulls,
378}
379
380/// Sort direction, with the unwritten case kept apart from the default it resolves to.
381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
382pub enum Order {
383 /// Nothing was written.
384 Unstated,
385 /// `ASC` or `ASCENDING`.
386 Ascending,
387 /// `DESC` or `DESCENDING`.
388 Descending,
389}
390
391/// Null placement in a sort.
392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
393pub enum Nulls {
394 /// Nothing was written, so the session default applies.
395 Unstated,
396 /// `NULLS FIRST`.
397 First,
398 /// `NULLS LAST`.
399 Last,
400}
401
402/// One entry in a `FROM` clause, which is a tree because joins nest.
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404pub enum Source {
405 /// A named table, possibly qualified by schema and catalog.
406 Table {
407 /// The name, as a run of [`StrRef`] in `Ast::parts`, outermost first.
408 name: Slice,
409 /// The alias, or `NONE`.
410 alias: StrRef,
411 /// Column aliases from `AS t(a, b)`, as a run of [`StrRef`].
412 columns: Slice,
413 },
414 /// A parenthesised query in the `FROM` clause.
415 Subquery {
416 /// The query.
417 query: QueryRef,
418 /// The alias, or `NONE`.
419 alias: StrRef,
420 /// Column aliases, as a run of [`StrRef`].
421 columns: Slice,
422 },
423 /// A function call where a table goes, such as `range(10)`.
424 ///
425 /// Held with the name as a qualified run rather than a single string, because `main.range(10)`
426 /// is legal and a function in a schema that does not exist has to say so rather than being
427 /// looked up unqualified and found.
428 Function {
429 /// The name, as a run of [`StrRef`] in `Ast::parts`, outermost first.
430 name: Slice,
431 /// The arguments, as a run of [`Target`] where the alias is the parameter name and is
432 /// `NONE` for a positional one.
433 args: Slice,
434 /// The alias, or `NONE`.
435 alias: StrRef,
436 /// Column aliases from `AS t(a, b)`, as a run of [`StrRef`].
437 columns: Slice,
438 },
439 /// A `VALUES` in the `FROM` clause.
440 Values {
441 /// The rows, as a run of [`Slice`] in `Ast::rows`.
442 rows: Slice,
443 /// The alias, or `NONE`.
444 alias: StrRef,
445 /// Column aliases, as a run of [`StrRef`].
446 columns: Slice,
447 },
448 /// Two sources joined.
449 Join {
450 /// The left side.
451 left: SourceRef,
452 /// The right side.
453 right: SourceRef,
454 /// Which join.
455 kind: JoinKind,
456 /// Whether it was written `NATURAL`.
457 natural: bool,
458 /// The `ON` expression, or `NONE`.
459 on: ExprRef,
460 /// The `USING` column list, as a run of [`StrRef`].
461 using: Slice,
462 },
463}
464
465/// Which join.
466#[derive(Debug, Clone, Copy, PartialEq, Eq)]
467pub enum JoinKind {
468 /// `[INNER] JOIN`.
469 Inner,
470 /// `LEFT [OUTER] JOIN`.
471 Left,
472 /// `RIGHT [OUTER] JOIN`.
473 Right,
474 /// `FULL [OUTER] JOIN`.
475 Full,
476 /// `SEMI JOIN`.
477 Semi,
478 /// `ANTI JOIN`.
479 Anti,
480 /// `CROSS JOIN`.
481 Cross,
482 /// `POSITIONAL JOIN`, which is DuckDB's own and pairs rows by ordinal.
483 Positional,
484}
485
486/// One expression.
487///
488/// Twenty four bytes, which is the widest variant rounded up. The precedence chain in the grammar
489/// does not survive into here: twenty levels of `X <- Y Tail*` become one [`Expr::Binary`] tree,
490/// because the levels exist to make the grammar unambiguous and mean nothing afterwards.
491#[derive(Debug, Clone, Copy, PartialEq, Eq)]
492pub enum Expr {
493 /// `*`, or `t.*` with a qualifier.
494 Star {
495 /// The qualifier, as a run of [`StrRef`], empty for a bare star.
496 qualifier: Slice,
497 /// `REPLACE (expression AS column)`, as a run of [`Target`] where the alias is the column
498 /// being replaced, empty for a star with no replace list.
499 ///
500 /// A [`Target`] rather than a type of its own because a replacement is an expression and a
501 /// name, which is exactly what a target is, and because that puts it in the arena every
502 /// other expression and name pair already lives in.
503 replacements: Slice,
504 },
505 /// A column reference, qualified or not.
506 Column {
507 /// The name, as a run of [`StrRef`], outermost first, so `s.t.a` is three parts.
508 name: Slice,
509 },
510 /// A literal, kept as the text that was written.
511 Literal {
512 /// Which kind.
513 kind: LiteralKind,
514 /// The text, with quotes stripped and escapes resolved for a string, `NONE` for a keyword
515 /// literal like `NULL` where the kind already says everything.
516 text: StrRef,
517 },
518 /// A prefix or postfix operator.
519 Unary {
520 /// Which operator.
521 op: UnaryOp,
522 /// What it applies to.
523 operand: ExprRef,
524 },
525 /// An infix operator.
526 Binary {
527 /// Which operator.
528 op: BinaryOp,
529 /// The left operand.
530 left: ExprRef,
531 /// The right operand.
532 right: ExprRef,
533 },
534 /// A function call.
535 Function {
536 /// The name, as a run of [`StrRef`], so `main.count` is two parts.
537 name: Slice,
538 /// The arguments, as a run of [`ExprRef`].
539 args: Slice,
540 /// Whether the call said `DISTINCT`.
541 distinct: bool,
542 },
543 /// `CAST(x AS t)` or `TRY_CAST(x AS t)`.
544 Cast {
545 /// What is being cast.
546 operand: ExprRef,
547 /// The target type, as the text it was written with. Parsing it is `rudb-common`'s job and
548 /// doing it here would put the type system in the parser.
549 ty: StrRef,
550 /// Whether a failure yields null rather than an error.
551 try_cast: bool,
552 },
553 /// `CASE`, searched or simple.
554 Case {
555 /// The operand of a simple `CASE x WHEN`, or `NONE` for a searched one.
556 operand: ExprRef,
557 /// The arms, as a run of [`CaseArm`].
558 arms: Slice,
559 /// The `ELSE`, or `NONE`.
560 otherwise: ExprRef,
561 },
562 /// `x BETWEEN a AND b`.
563 Between {
564 /// What is being tested.
565 operand: ExprRef,
566 /// The lower bound.
567 low: ExprRef,
568 /// The upper bound.
569 high: ExprRef,
570 /// Whether it was written `NOT BETWEEN`.
571 negated: bool,
572 },
573 /// `x IN (a, b, c)`.
574 In {
575 /// What is being tested.
576 operand: ExprRef,
577 /// The list, as a run of [`ExprRef`].
578 list: Slice,
579 /// Whether it was written `NOT IN`.
580 negated: bool,
581 },
582 /// A prepared statement parameter, written `?`, `?1`, `$1` or `$name`.
583 Parameter {
584 /// The identifier, which is the number for a positional one and the word for a named one.
585 /// A bare `?` is numbered by where it was written, so the identifier is there either way.
586 name: StrRef,
587 },
588 /// A bracketed list of expressions, `[a, b, c]`, which is a LIST value.
589 List {
590 /// The items, as a run of [`ExprRef`], in the order they were written.
591 items: Slice,
592 },
593 /// A parenthesised list of more than one expression, which is a row value.
594 Row {
595 /// The items, as a run of [`ExprRef`].
596 items: Slice,
597 },
598 /// A scalar subquery, `(SELECT ...)` where an expression is expected.
599 Subquery {
600 /// The query.
601 query: QueryRef,
602 },
603}
604
605/// One `WHEN a THEN b`.
606#[derive(Debug, Clone, Copy, PartialEq, Eq)]
607pub struct CaseArm {
608 /// The `WHEN`.
609 pub when: ExprRef,
610 /// The `THEN`.
611 pub then: ExprRef,
612}
613
614/// Which literal.
615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
616pub enum LiteralKind {
617 /// A number, kept as text because the width it wants depends on where it lands.
618 Number,
619 /// A string.
620 String,
621 /// `NULL`.
622 Null,
623 /// `TRUE`.
624 True,
625 /// `FALSE`.
626 False,
627}
628
629/// A prefix or postfix operator.
630#[derive(Debug, Clone, Copy, PartialEq, Eq)]
631pub enum UnaryOp {
632 /// `NOT x`.
633 Not,
634 /// `-x`.
635 Negate,
636 /// `+x`, which is a no-op that still has to survive to the binder so that `+'a'` errors.
637 Plus,
638 /// `~x`.
639 BitNot,
640 /// `x!`.
641 Factorial,
642 /// `x IS NULL` or `x ISNULL`.
643 IsNull,
644 /// `x IS NOT NULL` or `x NOTNULL`.
645 IsNotNull,
646 /// `x IS TRUE`.
647 IsTrue,
648 /// `x IS NOT TRUE`.
649 IsNotTrue,
650 /// `x IS FALSE`.
651 IsFalse,
652 /// `x IS NOT FALSE`.
653 IsNotFalse,
654 /// `x IS UNKNOWN`.
655 IsUnknown,
656 /// `x IS NOT UNKNOWN`.
657 IsNotUnknown,
658}
659
660/// An infix operator.
661///
662/// The list is the dialect and not a general idea of what operators are. `Named` is the one open
663/// door, because `OperatorLiteral` in the grammar takes any run of operator characters that is not
664/// already a token, and rejecting that here would reject SQL DuckDB accepts.
665#[derive(Debug, Clone, Copy, PartialEq, Eq)]
666pub enum BinaryOp {
667 /// `OR`.
668 Or,
669 /// `AND`.
670 And,
671 /// `=` or `==`.
672 Eq,
673 /// `!=` or `<>`.
674 NotEq,
675 /// `<`.
676 Lt,
677 /// `>`.
678 Gt,
679 /// `<=`.
680 LtEq,
681 /// `>=`.
682 GtEq,
683 /// `IS DISTINCT FROM`.
684 IsDistinctFrom,
685 /// `IS NOT DISTINCT FROM`.
686 IsNotDistinctFrom,
687 /// `+`.
688 Add,
689 /// `-`.
690 Subtract,
691 /// `*`.
692 Multiply,
693 /// `/`.
694 Divide,
695 /// `//`, integer division.
696 IntegerDivide,
697 /// `%`.
698 Modulo,
699 /// `^` or `**`.
700 Power,
701 /// `&`.
702 BitAnd,
703 /// `|`.
704 BitOr,
705 /// `<<`.
706 ShiftLeft,
707 /// `>>`.
708 ShiftRight,
709 /// `||`.
710 Concat,
711 /// `LIKE` or `~~`.
712 Like,
713 /// `NOT LIKE` or `!~~`.
714 NotLike,
715 /// `ILIKE` or `~~*`.
716 ILike,
717 /// `NOT ILIKE` or `!~~*`.
718 NotILike,
719 /// `GLOB` or `~~~`.
720 Glob,
721 /// `SIMILAR TO`.
722 SimilarTo,
723 /// `!~`, which the grammar calls the not-similar-to operator.
724 NotSimilarTo,
725 /// `~`, a regex match.
726 Regex,
727 /// `~*`, a case insensitive regex match.
728 RegexInsensitive,
729 /// `!~*`, a negated case insensitive regex match.
730 NotRegexInsensitive,
731 /// `COLLATE`.
732 Collate,
733 /// `AT TIME ZONE`.
734 AtTimeZone,
735 /// `->`.
736 Arrow,
737 /// `->>`.
738 LongArrow,
739 /// `@>`, contains.
740 Contains,
741 /// `<@`, contained by.
742 ContainedBy,
743 /// `&&`, overlaps.
744 Overlaps,
745 /// `^@`, starts with.
746 StartsWith,
747 /// `<<=`, an inet operator.
748 InetContainedByOrEq,
749 /// `>>=`, an inet operator.
750 InetContainsOrEq,
751 /// An operator the dialect does not name, which DuckDB resolves as a binary function of that
752 /// name. `a <=> b` is the shape.
753 Named(StrRef),
754}
755
756/// A parsed statement or script, with every arena it points into.
757///
758/// Cheap to clone, cheap to send, and self contained: no index in here refers to anything outside
759/// it, and nothing in here borrows the query text. The text is copied into `strings` on the way in,
760/// which costs one allocation per distinct identifier and buys an `Ast` that outlives the string it
761/// came from.
762#[derive(Debug, Clone, Default, PartialEq, Eq)]
763pub struct Ast {
764 /// The statements in the script, in order.
765 pub statements: Vec<Statement>,
766 /// The query arena.
767 pub queries: Vec<Query>,
768 /// The select arena.
769 pub selects: Vec<Select>,
770 /// The expression arena.
771 pub exprs: Vec<Expr>,
772 /// The from-item arena.
773 pub sources: Vec<Source>,
774 /// Interned text. Identifiers keep the case they were written in, because DuckDB does not fold
775 /// it at any point, including for quoted identifiers.
776 pub strings: Vec<String>,
777 /// Backing store for every [`Slice`] of names.
778 pub parts: Vec<StrRef>,
779 /// Backing store for every [`Slice`] of expressions.
780 pub expr_lists: Vec<ExprRef>,
781 /// Backing store for every [`Slice`] of from items.
782 pub source_lists: Vec<SourceRef>,
783 /// Backing store for every [`Slice`] of target list entries.
784 pub targets: Vec<Target>,
785 /// Backing store for every [`Slice`] of order by entries.
786 pub order_items: Vec<OrderItem>,
787 /// Backing store for every [`Slice`] of case arms.
788 pub case_arms: Vec<CaseArm>,
789 /// The `CREATE TABLE` arena.
790 pub create_tables: Vec<CreateTable>,
791 /// The `CREATE VIEW` arena.
792 pub create_views: Vec<CreateView>,
793 /// The `DROP TABLE` arena.
794 pub drop_tables: Vec<DropTable>,
795 /// The `INSERT` arena.
796 pub inserts: Vec<Insert>,
797 /// The `SET` and `RESET` arena.
798 pub settings: Vec<Setting>,
799 /// Backing store for every [`Slice`] of column definitions.
800 pub column_defs: Vec<ColumnDef>,
801 /// Backing store for every [`Slice`] of names, which is a name list rather than a name.
802 pub name_lists: Vec<Slice>,
803 /// Backing store for the rows of a `VALUES`, each of which is a run of expressions.
804 pub rows: Vec<Slice>,
805}
806
807impl Ast {
808 /// The text behind a [`StrRef`], or the empty string for `NONE`.
809 pub fn string(&self, index: StrRef) -> &str {
810 if index == NONE { "" } else { &self.strings[index as usize] }
811 }
812
813 /// Every parameter identifier the statement uses, once each, in the order they were written.
814 ///
815 /// The arena is built as the walk goes, so its order is the written order, and a parameter used
816 /// twice is one identifier here because it is one value to provide.
817 pub fn parameters(&self) -> Vec<&str> {
818 let mut found: Vec<&str> = Vec::new();
819 for expr in &self.exprs {
820 if let Expr::Parameter { name } = *expr {
821 let name = self.string(name);
822 if !found.contains(&name) {
823 found.push(name);
824 }
825 }
826 }
827 found
828 }
829
830 /// The parts of a name, outermost first.
831 pub fn name(&self, slice: Slice) -> impl Iterator<Item = &str> {
832 self.parts[slice.range()].iter().map(|&part| self.string(part))
833 }
834
835 /// A name written back out with dots between the parts, for error messages and tests.
836 pub fn name_text(&self, slice: Slice) -> String {
837 self.name(slice).collect::<Vec<_>>().join(".")
838 }
839
840 /// One expression.
841 pub fn expr(&self, index: ExprRef) -> Expr {
842 self.exprs[index as usize]
843 }
844
845 /// One from item.
846 pub fn source(&self, index: SourceRef) -> Source {
847 self.sources[index as usize]
848 }
849
850 /// One query.
851 pub fn query(&self, index: QueryRef) -> Query {
852 self.queries[index as usize]
853 }
854
855 /// One select block.
856 pub fn select(&self, index: SelectRef) -> Select {
857 self.selects[index as usize]
858 }
859
860 /// The expressions of a list.
861 pub fn expr_list(&self, slice: Slice) -> &[ExprRef] {
862 &self.expr_lists[slice.range()]
863 }
864
865 /// The from items of a list.
866 pub fn source_list(&self, slice: Slice) -> &[SourceRef] {
867 &self.source_lists[slice.range()]
868 }
869
870 /// The entries of a target list.
871 pub fn target_list(&self, slice: Slice) -> &[Target] {
872 &self.targets[slice.range()]
873 }
874
875 /// The entries of an order by list.
876 pub fn order_list(&self, slice: Slice) -> &[OrderItem] {
877 &self.order_items[slice.range()]
878 }
879
880 /// The arms of a case.
881 pub fn arm_list(&self, slice: Slice) -> &[CaseArm] {
882 &self.case_arms[slice.range()]
883 }
884
885 /// One `CREATE TABLE`.
886 pub fn create_table(&self, index: CreateTableRef) -> CreateTable {
887 self.create_tables[index as usize]
888 }
889
890 /// One `CREATE VIEW`.
891 pub fn create_view(&self, index: CreateViewRef) -> CreateView {
892 self.create_views[index as usize]
893 }
894
895 /// One `DROP TABLE`.
896 pub fn drop_table(&self, index: DropTableRef) -> DropTable {
897 self.drop_tables[index as usize]
898 }
899
900 /// One `INSERT`.
901 pub fn insert(&self, index: InsertRef) -> Insert {
902 self.inserts[index as usize]
903 }
904
905 /// One `SET` or `RESET`.
906 pub fn setting(&self, index: SettingRef) -> Setting {
907 self.settings[index as usize]
908 }
909
910 /// The column definitions of a `CREATE TABLE`.
911 pub fn column_defs(&self, slice: Slice) -> &[ColumnDef] {
912 &self.column_defs[slice.range()]
913 }
914
915 /// The names of a name list, each of which is itself a run of parts.
916 pub fn name_list(&self, slice: Slice) -> &[Slice] {
917 &self.name_lists[slice.range()]
918 }
919
920 /// The rows of a `VALUES`, each of which is itself a run of expressions.
921 pub fn rows(&self, slice: Slice) -> &[Slice] {
922 &self.rows[slice.range()]
923 }
924
925 /// How many nodes the whole tree is, across every arena.
926 ///
927 /// The number to watch when the transformer changes. A parse tree of five thousand nodes that
928 /// becomes an AST of thirty is the twenty precedence levels being thrown away, which is the
929 /// whole reason this module exists.
930 pub fn node_count(&self) -> usize {
931 self.queries.len() + self.selects.len() + self.exprs.len() + self.sources.len()
932 }
933}