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 parenthesised list of more than one expression, which is a row value.
492 Row {
493 /// The items, as a run of [`ExprRef`].
494 items: Slice,
495 },
496 /// A scalar subquery, `(SELECT ...)` where an expression is expected.
497 Subquery {
498 /// The query.
499 query: QueryRef,
500 },
501}
502
503/// One `WHEN a THEN b`.
504#[derive(Debug, Clone, Copy, PartialEq, Eq)]
505pub struct CaseArm {
506 /// The `WHEN`.
507 pub when: ExprRef,
508 /// The `THEN`.
509 pub then: ExprRef,
510}
511
512/// Which literal.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub enum LiteralKind {
515 /// A number, kept as text because the width it wants depends on where it lands.
516 Number,
517 /// A string.
518 String,
519 /// `NULL`.
520 Null,
521 /// `TRUE`.
522 True,
523 /// `FALSE`.
524 False,
525}
526
527/// A prefix or postfix operator.
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
529pub enum UnaryOp {
530 /// `NOT x`.
531 Not,
532 /// `-x`.
533 Negate,
534 /// `+x`, which is a no-op that still has to survive to the binder so that `+'a'` errors.
535 Plus,
536 /// `~x`.
537 BitNot,
538 /// `x!`.
539 Factorial,
540 /// `x IS NULL` or `x ISNULL`.
541 IsNull,
542 /// `x IS NOT NULL` or `x NOTNULL`.
543 IsNotNull,
544 /// `x IS TRUE`.
545 IsTrue,
546 /// `x IS NOT TRUE`.
547 IsNotTrue,
548 /// `x IS FALSE`.
549 IsFalse,
550 /// `x IS NOT FALSE`.
551 IsNotFalse,
552 /// `x IS UNKNOWN`.
553 IsUnknown,
554 /// `x IS NOT UNKNOWN`.
555 IsNotUnknown,
556}
557
558/// An infix operator.
559///
560/// The list is the dialect and not a general idea of what operators are. `Named` is the one open
561/// door, because `OperatorLiteral` in the grammar takes any run of operator characters that is not
562/// already a token, and rejecting that here would reject SQL DuckDB accepts.
563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
564pub enum BinaryOp {
565 /// `OR`.
566 Or,
567 /// `AND`.
568 And,
569 /// `=` or `==`.
570 Eq,
571 /// `!=` or `<>`.
572 NotEq,
573 /// `<`.
574 Lt,
575 /// `>`.
576 Gt,
577 /// `<=`.
578 LtEq,
579 /// `>=`.
580 GtEq,
581 /// `IS DISTINCT FROM`.
582 IsDistinctFrom,
583 /// `IS NOT DISTINCT FROM`.
584 IsNotDistinctFrom,
585 /// `+`.
586 Add,
587 /// `-`.
588 Subtract,
589 /// `*`.
590 Multiply,
591 /// `/`.
592 Divide,
593 /// `//`, integer division.
594 IntegerDivide,
595 /// `%`.
596 Modulo,
597 /// `^` or `**`.
598 Power,
599 /// `&`.
600 BitAnd,
601 /// `|`.
602 BitOr,
603 /// `<<`.
604 ShiftLeft,
605 /// `>>`.
606 ShiftRight,
607 /// `||`.
608 Concat,
609 /// `LIKE` or `~~`.
610 Like,
611 /// `NOT LIKE` or `!~~`.
612 NotLike,
613 /// `ILIKE` or `~~*`.
614 ILike,
615 /// `NOT ILIKE` or `!~~*`.
616 NotILike,
617 /// `GLOB` or `~~~`.
618 Glob,
619 /// `SIMILAR TO`.
620 SimilarTo,
621 /// `!~`, which the grammar calls the not-similar-to operator.
622 NotSimilarTo,
623 /// `~`, a regex match.
624 Regex,
625 /// `~*`, a case insensitive regex match.
626 RegexInsensitive,
627 /// `!~*`, a negated case insensitive regex match.
628 NotRegexInsensitive,
629 /// `COLLATE`.
630 Collate,
631 /// `AT TIME ZONE`.
632 AtTimeZone,
633 /// `->`.
634 Arrow,
635 /// `->>`.
636 LongArrow,
637 /// `@>`, contains.
638 Contains,
639 /// `<@`, contained by.
640 ContainedBy,
641 /// `&&`, overlaps.
642 Overlaps,
643 /// `^@`, starts with.
644 StartsWith,
645 /// `<<=`, an inet operator.
646 InetContainedByOrEq,
647 /// `>>=`, an inet operator.
648 InetContainsOrEq,
649 /// An operator the dialect does not name, which DuckDB resolves as a binary function of that
650 /// name. `a <=> b` is the shape.
651 Named(StrRef),
652}
653
654/// A parsed statement or script, with every arena it points into.
655///
656/// Cheap to clone, cheap to send, and self contained: no index in here refers to anything outside
657/// it, and nothing in here borrows the query text. The text is copied into `strings` on the way in,
658/// which costs one allocation per distinct identifier and buys an `Ast` that outlives the string it
659/// came from.
660#[derive(Debug, Clone, Default, PartialEq, Eq)]
661pub struct Ast {
662 /// The statements in the script, in order.
663 pub statements: Vec<Statement>,
664 /// The query arena.
665 pub queries: Vec<Query>,
666 /// The select arena.
667 pub selects: Vec<Select>,
668 /// The expression arena.
669 pub exprs: Vec<Expr>,
670 /// The from-item arena.
671 pub sources: Vec<Source>,
672 /// Interned text. Identifiers keep the case they were written in, because DuckDB does not fold
673 /// it at any point, including for quoted identifiers.
674 pub strings: Vec<String>,
675 /// Backing store for every [`Slice`] of names.
676 pub parts: Vec<StrRef>,
677 /// Backing store for every [`Slice`] of expressions.
678 pub expr_lists: Vec<ExprRef>,
679 /// Backing store for every [`Slice`] of from items.
680 pub source_lists: Vec<SourceRef>,
681 /// Backing store for every [`Slice`] of target list entries.
682 pub targets: Vec<Target>,
683 /// Backing store for every [`Slice`] of order by entries.
684 pub order_items: Vec<OrderItem>,
685 /// Backing store for every [`Slice`] of case arms.
686 pub case_arms: Vec<CaseArm>,
687 /// The `CREATE TABLE` arena.
688 pub create_tables: Vec<CreateTable>,
689 /// The `DROP TABLE` arena.
690 pub drop_tables: Vec<DropTable>,
691 /// The `INSERT` arena.
692 pub inserts: Vec<Insert>,
693 /// Backing store for every [`Slice`] of column definitions.
694 pub column_defs: Vec<ColumnDef>,
695 /// Backing store for every [`Slice`] of names, which is a name list rather than a name.
696 pub name_lists: Vec<Slice>,
697 /// Backing store for the rows of a `VALUES`, each of which is a run of expressions.
698 pub rows: Vec<Slice>,
699}
700
701impl Ast {
702 /// The text behind a [`StrRef`], or the empty string for `NONE`.
703 pub fn string(&self, index: StrRef) -> &str {
704 if index == NONE { "" } else { &self.strings[index as usize] }
705 }
706
707 /// The parts of a name, outermost first.
708 pub fn name(&self, slice: Slice) -> impl Iterator<Item = &str> {
709 self.parts[slice.range()].iter().map(|&part| self.string(part))
710 }
711
712 /// A name written back out with dots between the parts, for error messages and tests.
713 pub fn name_text(&self, slice: Slice) -> String {
714 self.name(slice).collect::<Vec<_>>().join(".")
715 }
716
717 /// One expression.
718 pub fn expr(&self, index: ExprRef) -> Expr {
719 self.exprs[index as usize]
720 }
721
722 /// One from item.
723 pub fn source(&self, index: SourceRef) -> Source {
724 self.sources[index as usize]
725 }
726
727 /// One query.
728 pub fn query(&self, index: QueryRef) -> Query {
729 self.queries[index as usize]
730 }
731
732 /// One select block.
733 pub fn select(&self, index: SelectRef) -> Select {
734 self.selects[index as usize]
735 }
736
737 /// The expressions of a list.
738 pub fn expr_list(&self, slice: Slice) -> &[ExprRef] {
739 &self.expr_lists[slice.range()]
740 }
741
742 /// The from items of a list.
743 pub fn source_list(&self, slice: Slice) -> &[SourceRef] {
744 &self.source_lists[slice.range()]
745 }
746
747 /// The entries of a target list.
748 pub fn target_list(&self, slice: Slice) -> &[Target] {
749 &self.targets[slice.range()]
750 }
751
752 /// The entries of an order by list.
753 pub fn order_list(&self, slice: Slice) -> &[OrderItem] {
754 &self.order_items[slice.range()]
755 }
756
757 /// The arms of a case.
758 pub fn arm_list(&self, slice: Slice) -> &[CaseArm] {
759 &self.case_arms[slice.range()]
760 }
761
762 /// One `CREATE TABLE`.
763 pub fn create_table(&self, index: CreateTableRef) -> CreateTable {
764 self.create_tables[index as usize]
765 }
766
767 /// One `DROP TABLE`.
768 pub fn drop_table(&self, index: DropTableRef) -> DropTable {
769 self.drop_tables[index as usize]
770 }
771
772 /// One `INSERT`.
773 pub fn insert(&self, index: InsertRef) -> Insert {
774 self.inserts[index as usize]
775 }
776
777 /// The column definitions of a `CREATE TABLE`.
778 pub fn column_defs(&self, slice: Slice) -> &[ColumnDef] {
779 &self.column_defs[slice.range()]
780 }
781
782 /// The names of a name list, each of which is itself a run of parts.
783 pub fn name_list(&self, slice: Slice) -> &[Slice] {
784 &self.name_lists[slice.range()]
785 }
786
787 /// The rows of a `VALUES`, each of which is itself a run of expressions.
788 pub fn rows(&self, slice: Slice) -> &[Slice] {
789 &self.rows[slice.range()]
790 }
791
792 /// How many nodes the whole tree is, across every arena.
793 ///
794 /// The number to watch when the transformer changes. A parse tree of five thousand nodes that
795 /// becomes an AST of thirty is the twenty precedence levels being thrown away, which is the
796 /// whole reason this module exists.
797 pub fn node_count(&self) -> usize {
798 self.queries.len() + self.selects.len() + self.exprs.len() + self.sources.len()
799 }
800}