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