Skip to main content

rudb_parse/
transform.rs

1//! From the parse tree to the AST.
2//!
3//! This is the one module that reads rule names out of the vendored grammar, and that is deliberate
4//! containment: an upstream bump that renames a rule breaks a match arm here and nothing else in
5//! the repository. `spec/04-architecture.md` section 4.5 says this transformer is ours and has to
6//! be total over the rule table, and total is the load bearing word. Every rule reaches a defined
7//! answer. For the ones this milestone covers that answer is an AST node, and for the rest it is a
8//! `Not implemented` error naming the construct, which is what DuckDB itself answers for syntax it
9//! parses and does not support. There is no arm that panics and none that silently drops a clause,
10//! because a dropped clause is a wrong answer and a wrong answer is worse than an error.
11//!
12//! The mechanism that makes it tractable is the default arm. Two thirds of the parse tree is the
13//! expression precedence chain, twenty rules of the form `X <- Y Tail*` that exist to make the
14//! grammar unambiguous and that carry no meaning once it has been parsed. Rather than name all
15//! twenty, the expression walker handles the case where a rule matched something interesting and
16//! otherwise descends through any node with exactly one child. That is not a shortcut. It is the
17//! statement that a rule with one child said nothing, which is true of every chain link, and it
18//! means the twenty first precedence level upstream adds costs us nothing.
19
20use std::collections::HashMap;
21
22use rudb_common::{Error, Result};
23
24use crate::ast::{
25    Ast, BinaryOp, CaseArm, ColumnDef, CreateTable, Distinct, DropTable, Expr, ExprRef, Insert,
26    JoinKind, LiteralKind, Nulls, Order, OrderItem, Quantifier, Query, QueryBody, QueryRef, Select,
27    SelectRef, SetOp, Slice, Source, SourceRef, Statement, StrRef, Target, UnaryOp,
28};
29use crate::generated::rules::PROGRAM;
30use crate::matcher::{NONE, Tree, parse_tokens};
31use crate::token::{Kind, Token};
32use crate::tokenize::tokenize;
33
34/// Parse a script and transform it into the AST.
35///
36/// The tokens are produced once and handed to both halves. Calling [`crate::parse`] here instead
37/// would be shorter and would tokenize the query a second time, which `cargo xtask bench` prices
38/// at about a tenth of the whole front end.
39pub fn parse_ast(query: &str) -> Result<Ast> {
40    let tokens = tokenize(query)?;
41    let tree = parse_tokens(query, &tokens, PROGRAM, true)?;
42    transform(query, &tokens, &tree)
43}
44
45/// Transform a parse tree that has already been produced.
46pub fn transform(query: &str, tokens: &[Token], tree: &Tree) -> Result<Ast> {
47    let mut transform =
48        Transform { query, tokens, tree, ast: Ast::default(), interned: HashMap::new() };
49    transform.program(tree.root())?;
50    Ok(transform.ast)
51}
52
53struct Transform<'a> {
54    query: &'a str,
55    tokens: &'a [Token],
56    tree: &'a Tree,
57    ast: Ast,
58    interned: HashMap<String, StrRef>,
59}
60
61impl<'a> Transform<'a> {
62    // The parts that walk the parse tree without caring what it says.
63
64    /// The text a node covers.
65    fn text(&self, node: u32) -> &'a str {
66        self.tree.text(node, self.query, self.tokens)
67    }
68
69    /// The name of the rule a node is.
70    fn name(&self, node: u32) -> &'static str {
71        self.tree.name(node)
72    }
73
74    /// The children of a node.
75    ///
76    /// Returned with the tree's lifetime rather than the borrow of `self`, so that the caller can
77    /// iterate it while calling the `&mut self` methods that build the arena. Copying the `&Tree`
78    /// out first is what buys that, and it is why every walker here starts by doing so.
79    fn kids(&self, node: u32) -> impl Iterator<Item = u32> + use<'a> {
80        let tree = self.tree;
81        tree.children(node)
82    }
83
84    /// How many children a node has.
85    fn count(&self, node: u32) -> usize {
86        self.kids(node).count()
87    }
88
89    /// The n'th child, or `NONE`.
90    fn nth(&self, node: u32, n: usize) -> u32 {
91        self.kids(node).nth(n).unwrap_or(NONE)
92    }
93
94    /// The first child, or `NONE`.
95    fn first(&self, node: u32) -> u32 {
96        self.nth(node, 0)
97    }
98
99    /// The first child named `name`, or `NONE`.
100    ///
101    /// Optional parts of a sequence do not leave a placeholder behind, so `SimpleSelect` with a
102    /// `WHERE` and no `GROUP BY` has the where clause as its second child and a `SimpleSelect` with
103    /// neither has something else there. Positional indexing into an optional sequence is the
104    /// single easiest way to write a transformer that is subtly wrong, so nothing here does it.
105    fn find(&self, node: u32, name: &str) -> u32 {
106        self.kids(node).find(|&kid| self.name(kid) == name).unwrap_or(NONE)
107    }
108
109    /// Every leaf of a subtree, in order.
110    ///
111    /// A leaf is a rule that matched only terminals, which for a name is the identifier itself. It
112    /// is how all thirty odd spellings of a qualified name collapse into one walk: whether the
113    /// parse said `SchemaQualification ReservedTableQualification ReservedColumnName` or
114    /// `IdentifierDot IdentifierDot ColumnName`, the leaves are the parts in order.
115    fn leaves(&self, node: u32, out: &mut Vec<u32>) {
116        let mut any = false;
117        for kid in self.kids(node) {
118            any = true;
119            self.leaves(kid, &mut *out);
120        }
121        if !any {
122            out.push(node);
123        }
124    }
125
126    // The parts that build the arena.
127
128    /// Intern a string, returning its index.
129    fn intern(&mut self, text: &str) -> StrRef {
130        if let Some(&index) = self.interned.get(text) {
131            return index;
132        }
133        let index = u32::try_from(self.ast.strings.len())
134            .map_err(|_| Error::internal("more than four billion strings in one query"))
135            .unwrap_or(NONE);
136        self.ast.strings.push(text.to_string());
137        self.interned.insert(text.to_string(), index);
138        index
139    }
140
141    /// Push an expression and return its index.
142    fn push(&mut self, expr: Expr) -> ExprRef {
143        let index = self.ast.exprs.len() as u32;
144        self.ast.exprs.push(expr);
145        index
146    }
147
148    /// Push a from item and return its index.
149    fn push_source(&mut self, source: Source) -> SourceRef {
150        let index = self.ast.sources.len() as u32;
151        self.ast.sources.push(source);
152        index
153    }
154
155    /// Push a query and return its index.
156    fn push_query(&mut self, query: Query) -> QueryRef {
157        let index = self.ast.queries.len() as u32;
158        self.ast.queries.push(query);
159        index
160    }
161
162    /// Push a select and return its index.
163    fn push_select(&mut self, select: Select) -> SelectRef {
164        let index = self.ast.selects.len() as u32;
165        self.ast.selects.push(select);
166        index
167    }
168
169    /// Turn a vector of expressions into a slice of the expression list arena.
170    fn expr_slice(&mut self, items: Vec<ExprRef>) -> Slice {
171        let start = self.ast.expr_lists.len() as u32;
172        self.ast.expr_lists.extend(items);
173        Slice { start, len: self.ast.expr_lists.len() as u32 - start }
174    }
175
176    /// Turn a vector of strings into a slice of the name arena.
177    fn part_slice(&mut self, items: Vec<StrRef>) -> Slice {
178        let start = self.ast.parts.len() as u32;
179        self.ast.parts.extend(items);
180        Slice { start, len: self.ast.parts.len() as u32 - start }
181    }
182
183    /// Turn a vector of column definitions into a slice of the column arena.
184    fn column_def_slice(&mut self, items: Vec<ColumnDef>) -> Slice {
185        let start = self.ast.column_defs.len() as u32;
186        self.ast.column_defs.extend(items);
187        Slice { start, len: self.ast.column_defs.len() as u32 - start }
188    }
189
190    /// Turn a vector of qualified names into a slice of the name list arena.
191    fn name_list_slice(&mut self, items: Vec<Slice>) -> Slice {
192        let start = self.ast.name_lists.len() as u32;
193        self.ast.name_lists.extend(items);
194        Slice { start, len: self.ast.name_lists.len() as u32 - start }
195    }
196
197    /// The error for a construct the transformer does not cover yet.
198    ///
199    /// Both halves matter. The text is what the user wrote, which is the only part they can act on,
200    /// and the rule name is what we act on, because it is the exact grammar rule to go implement.
201    fn unsupported<T>(&self, node: u32) -> Result<T> {
202        let text = self.text(node);
203        let text = if text.chars().count() > 60 {
204            let cut = text.char_indices().nth(60).map_or(text.len(), |(at, _)| at);
205            format!("{}...", &text[..cut])
206        } else {
207            text.to_string()
208        };
209        Err(Error::not_implemented(format!(
210            "{text} is not supported yet, the grammar rule is {}",
211            self.name(node)
212        )))
213    }
214
215    // Names.
216
217    /// One identifier out of a subtree, with the quoting and any trailing dot removed.
218    fn identifier(&mut self, node: u32) -> StrRef {
219        let mut leaves = Vec::new();
220        self.leaves(node, &mut leaves);
221        let text = leaves.last().map_or("", |&leaf| self.text(leaf));
222        let text = unquote(text.strip_suffix('.').unwrap_or(text));
223        self.intern(&text)
224    }
225
226    /// Every part of a qualified name, outermost first.
227    fn name_parts(&mut self, node: u32) -> Slice {
228        let mut leaves = Vec::new();
229        self.leaves(node, &mut leaves);
230        let mut parts = Vec::with_capacity(leaves.len());
231        for leaf in leaves {
232            let text = self.text(leaf);
233            // A node that covers no tokens is an optional part that was not written, and a bare
234            // `*` is the star and not a name part. Neither is a component of anything.
235            if text.is_empty() || text == "*" {
236                continue;
237            }
238            let text = unquote(text.strip_suffix('.').unwrap_or(text));
239            let interned = self.intern(&text);
240            parts.push(interned);
241        }
242        self.part_slice(parts)
243    }
244
245    // Statements.
246
247    /// `Program <- TopLevelStatement*`.
248    fn program(&mut self, node: u32) -> Result<()> {
249        for top in self.kids(node) {
250            // A script that ends in a semicolon produces a last `TopLevelStatement` whose only
251            // child is the end of input, because the grammar says `Statement? (';'+ / EndOfInput)`
252            // and both halves of that are happy to match nothing. It is a real node and it is not a
253            // statement, so it is dropped here rather than pretended away in the matcher.
254            let Some(statement) = self.kids(top).find(|&kid| self.name(kid) == "Statement") else {
255                continue;
256            };
257            let statement = self.statement(statement)?;
258            self.ast.statements.push(statement);
259        }
260        Ok(())
261    }
262
263    /// `Statement <- SelectStatement / ...`, twenty seven alternatives of which four are done.
264    fn statement(&mut self, node: u32) -> Result<Statement> {
265        let inner = self.first(node);
266        match self.name(inner) {
267            "SelectStatement" => {
268                let query = self.query(self.first(inner))?;
269                Ok(Statement::Query(query))
270            }
271            "CreateStatement" => self.create_statement(inner),
272            "DropStatement" => self.drop_statement(inner),
273            "InsertStatement" => self.insert_statement(inner),
274            _ => self.unsupported(inner),
275        }
276    }
277
278    /// `CreateStatement <- 'CREATE' OrReplace? Temporary? CreateStatementVariation`.
279    ///
280    /// Of the nine variations, `CreateTableStmt` is the one that is done. The other eight are a
281    /// view, a macro, a sequence, a type, a schema, an index, a secret and a trigger, and each of
282    /// them is a catalog entry this database has no room for yet.
283    fn create_statement(&mut self, node: u32) -> Result<Statement> {
284        let or_replace = self.find(node, "OrReplace") != NONE;
285        let temporary = self.find(node, "Temporary") != NONE;
286        let variation = self.find(node, "CreateStatementVariation");
287        let inner = self.first(variation);
288        if self.name(inner) != "CreateTableStmt" {
289            return self.unsupported(inner);
290        }
291        let name = self.name_parts(self.find(inner, "QualifiedName"));
292        let if_not_exists = self.find(inner, "IfNotExists") != NONE;
293        let definition = self.find(inner, "CreateTableDefinition");
294        let body = self.first(definition);
295        let (columns, query) = match self.name(body) {
296            "CreateColumnList" => (self.column_list(body)?, NONE),
297            "CreateTableAs" => self.create_table_as(body)?,
298            _ => return self.unsupported(body),
299        };
300        let index = self.ast.create_tables.len() as u32;
301        self.ast.create_tables.push(CreateTable {
302            name,
303            columns,
304            query,
305            if_not_exists,
306            or_replace,
307            temporary,
308        });
309        Ok(Statement::CreateTable(index))
310    }
311
312    /// `CreateColumnList <- Parens(CreateTableColumnList?) PartitionSortedOptions? WithList?`.
313    fn column_list(&mut self, node: u32) -> Result<Slice> {
314        for kid in self.kids(node) {
315            if matches!(self.name(kid), "PartitionOptions" | "SortedOptions" | "WithList") {
316                return self.unsupported(kid);
317            }
318        }
319        let list = self.find(node, "CreateTableColumnList");
320        if list == NONE {
321            // `CREATE TABLE t ()` parses. It is a table of no columns, and the catalog is entitled
322            // to refuse it, but that is not this layer's refusal to make.
323            return Ok(Slice::default());
324        }
325        let mut defs = Vec::new();
326        for element in self.kids(list) {
327            let inner = self.first(element);
328            if self.name(inner) != "CreateTableColumnDefinition" {
329                // A table level `PRIMARY KEY`, `UNIQUE`, `CHECK` or `FOREIGN KEY`. Constraints are
330                // not enforced anywhere yet and silently dropping one is a wrong answer waiting to
331                // happen, so it is refused instead.
332                return self.unsupported(inner);
333            }
334            defs.push(self.column_definition(self.first(inner))?);
335        }
336        Ok(self.column_def_slice(defs))
337    }
338
339    /// `ColumnDefinition <- DottedIdentifier Type? GeneratedColumn? ConstraintNameClause?
340    /// ColumnConstraint*`.
341    fn column_definition(&mut self, node: u32) -> Result<ColumnDef> {
342        let name = self.identifier(self.find(node, "DottedIdentifier"));
343        let type_node = self.find(node, "Type");
344        let ty = if type_node == NONE {
345            NONE
346        } else {
347            let text = self.text(type_node).to_string();
348            self.intern(&text)
349        };
350        if self.find(node, "GeneratedColumn") != NONE {
351            return self.unsupported(self.find(node, "GeneratedColumn"));
352        }
353        let mut not_null = false;
354        for kid in self.kids(node) {
355            if self.name(kid) != "ColumnConstraint" {
356                continue;
357            }
358            let constraint = self.first(kid);
359            match self.name(constraint) {
360                "NotNullConstraint" => {
361                    not_null = self.name(self.first(constraint)) == "NotNullColumnConstraint";
362                }
363                _ => return self.unsupported(constraint),
364            }
365        }
366        Ok(ColumnDef { name, ty, not_null })
367    }
368
369    /// `CreateTableAs <- IdentifierList? PartitionSortedOptions? WithList? 'AS' Statement
370    /// WithData?`.
371    ///
372    /// The names in the `IdentifierList` become column definitions with no type, because the types
373    /// are the query's and only the names are the syntax's to say.
374    fn create_table_as(&mut self, node: u32) -> Result<(Slice, QueryRef)> {
375        for kid in self.kids(node) {
376            if matches!(
377                self.name(kid),
378                "PartitionOptions" | "SortedOptions" | "WithList" | "WithData"
379            ) {
380                return self.unsupported(kid);
381            }
382        }
383        let names = self.find(node, "IdentifierList");
384        let columns = if names == NONE {
385            Slice::default()
386        } else {
387            let mut defs = Vec::new();
388            for kid in self.kids(names) {
389                let name = self.identifier(kid);
390                defs.push(ColumnDef { name, ty: NONE, not_null: false });
391            }
392            self.column_def_slice(defs)
393        };
394        let statement = self.find(node, "Statement");
395        let inner = self.first(statement);
396        if self.name(inner) != "SelectStatement" {
397            return self.unsupported(inner);
398        }
399        let query = self.query(self.first(inner))?;
400        Ok((columns, query))
401    }
402
403    /// `DropStatement <- 'DROP' DropEntries DropBehavior?`.
404    ///
405    /// `DropTable <- TableOrView IfExists? List(BaseTableName)`, and `TableOrView` covers `VIEW`
406    /// and `MATERIALIZED VIEW` as well as `TABLE`, so it is checked rather than assumed.
407    fn drop_statement(&mut self, node: u32) -> Result<Statement> {
408        if self.find(node, "DropBehavior") != NONE {
409            return self.unsupported(self.find(node, "DropBehavior"));
410        }
411        let entries = self.find(node, "DropEntries");
412        let inner = self.first(entries);
413        if self.name(inner) != "DropTable" {
414            return self.unsupported(inner);
415        }
416        let kind = self.find(inner, "TableOrView");
417        if self.name(self.first(kind)) != "CommentTable" {
418            return self.unsupported(kind);
419        }
420        let if_exists = self.find(inner, "IfExists") != NONE;
421        let mut names = Vec::new();
422        for kid in self.kids(inner) {
423            if self.name(kid) == "BaseTableName" {
424                names.push(self.name_parts(kid));
425            }
426        }
427        let names = self.name_list_slice(names);
428        let index = self.ast.drop_tables.len() as u32;
429        self.ast.drop_tables.push(DropTable { names, if_exists });
430        Ok(Statement::DropTable(index))
431    }
432
433    /// `InsertStatement <- ... InsertTarget InsertColumnList? InsertValues ...`.
434    ///
435    /// `ON CONFLICT`, `RETURNING`, `BY NAME`, `BY POSITION`, `OR REPLACE` and the rest of the
436    /// clauses the grammar hangs off this are each a refusal, because every one of them changes
437    /// what the statement means and none of them changes it in a way anything downstream would
438    /// notice if it were dropped.
439    fn insert_statement(&mut self, node: u32) -> Result<Statement> {
440        for kid in self.kids(node) {
441            if matches!(
442                self.name(kid),
443                "InsertTarget" | "InsertColumnList" | "InsertValues" | "WithClause"
444            ) {
445                continue;
446            }
447            return self.unsupported(kid);
448        }
449        if self.find(node, "WithClause") != NONE {
450            return self.unsupported(self.find(node, "WithClause"));
451        }
452        let name = self.name_parts(self.find(self.find(node, "InsertTarget"), "BaseTableName"));
453        let list = self.find(node, "InsertColumnList");
454        let columns = if list == NONE {
455            Slice::default()
456        } else {
457            let mut parts = Vec::new();
458            for kid in self.kids(self.find(list, "ColumnList")) {
459                parts.push(self.identifier(kid));
460            }
461            self.part_slice(parts)
462        };
463        let values = self.find(node, "InsertValues");
464        let inner = self.first(values);
465        if self.name(inner) != "SelectInsertValues" {
466            return self.unsupported(inner);
467        }
468        let source = self.query(self.find(inner, "SelectStatementInternal"))?;
469        let index = self.ast.inserts.len() as u32;
470        self.ast.inserts.push(Insert { name, columns, source });
471        Ok(Statement::Insert(index))
472    }
473
474    /// `SelectStatementInternal <- WithClause? SelectSetOpChain ResultModifiers?`.
475    fn query(&mut self, node: u32) -> Result<QueryRef> {
476        if self.find(node, "WithClause") != NONE {
477            return self.unsupported(self.find(node, "WithClause"));
478        }
479        let chain = self.find(node, "SelectSetOpChain");
480        if chain == NONE {
481            return self.unsupported(node);
482        }
483        let query = self.set_op_chain(chain)?;
484        let modifiers = self.find(node, "ResultModifiers");
485        if modifiers != NONE {
486            self.result_modifiers(query, modifiers)?;
487        }
488        Ok(query)
489    }
490
491    /// `SelectSetOpChain <- IntersectChain SelectSetOpChainTail*`, left associative.
492    fn set_op_chain(&mut self, node: u32) -> Result<QueryRef> {
493        let mut kids = self.kids(node);
494        let head = kids.next().unwrap_or(NONE);
495        let mut left = self.intersect_chain(head)?;
496        for tail in kids {
497            // `SelectSetOpChainTail <- SetopClause IntersectChain`.
498            let clause = self.first(tail);
499            let (op, quantifier, by_name) = self.setop_clause(clause)?;
500            let right = self.intersect_chain(self.nth(tail, 1))?;
501            left = self.push_query(Query::bare(QueryBody::SetOp {
502                op,
503                quantifier,
504                by_name,
505                left,
506                right,
507            }));
508        }
509        Ok(left)
510    }
511
512    /// `IntersectChain <- SelectAtom IntersectChainTail*`, which binds tighter than union.
513    fn intersect_chain(&mut self, node: u32) -> Result<QueryRef> {
514        let mut kids = self.kids(node);
515        let head = kids.next().unwrap_or(NONE);
516        let mut left = self.select_atom(head)?;
517        for tail in kids {
518            // `IntersectChainTail <- SetIntersectClause SelectAtom`.
519            let clause = self.first(tail);
520            let quantifier = self.quantifier(self.find(clause, "DistinctOrAll"));
521            let right = self.select_atom(self.nth(tail, 1))?;
522            left = self.push_query(Query::bare(QueryBody::SetOp {
523                op: SetOp::Intersect,
524                quantifier,
525                by_name: false,
526                left,
527                right,
528            }));
529        }
530        Ok(left)
531    }
532
533    /// `SetopClause <- SetopType DistinctOrAll? ByName?`.
534    fn setop_clause(&mut self, node: u32) -> Result<(SetOp, Quantifier, bool)> {
535        let kind = self.find(node, "SetopType");
536        let op = match self.name(self.first(kind)) {
537            "SetopUnion" => SetOp::Union,
538            "SetopExcept" => SetOp::Except,
539            _ => return self.unsupported(kind),
540        };
541        let quantifier = self.quantifier(self.find(node, "DistinctOrAll"));
542        Ok((op, quantifier, self.find(node, "ByName") != NONE))
543    }
544
545    /// `DistinctOrAll <- DistinctKeyword / AllKeyword`, absent included.
546    fn quantifier(&self, node: u32) -> Quantifier {
547        if node == NONE {
548            return Quantifier::Unstated;
549        }
550        match self.name(self.first(node)) {
551            "DistinctKeyword" => Quantifier::Distinct,
552            "AllKeyword" => Quantifier::All,
553            _ => Quantifier::Unstated,
554        }
555    }
556
557    /// `SelectAtom <- SelectParens / SelectStatementType`.
558    fn select_atom(&mut self, node: u32) -> Result<QueryRef> {
559        let inner = self.first(node);
560        match self.name(inner) {
561            // `SelectParens <- Parens(SelectStatementInternal)`, so the parens buy a query that
562            // carries its own order by and limit and nothing else.
563            "SelectParens" => self.query(self.first(inner)),
564            "SelectStatementType" => {
565                let kind = self.first(inner);
566                match self.name(kind) {
567                    "OptionalParensSimpleSelect" => {
568                        let select = self.simple_select(self.unwrap_parens(kind))?;
569                        Ok(self.push_query(Query::bare(QueryBody::Select(select))))
570                    }
571                    "ValuesClause" => {
572                        let rows = self.values_clause(kind)?;
573                        Ok(self.push_query(Query::bare(QueryBody::Values(rows))))
574                    }
575                    _ => self.unsupported(kind),
576                }
577            }
578            _ => self.unsupported(inner),
579        }
580    }
581
582    /// `ValuesClause <- 'VALUES' List(ValuesExpressions)`, each of which is `Parens(List(Expression))`.
583    ///
584    /// The rows are not checked against each other for width here. Two rows of different widths
585    /// parse, and saying so is the binder's job, because the message wants to name the column count
586    /// it expected and the parser does not know it for `INSERT` where the table decides.
587    fn values_clause(&mut self, node: u32) -> Result<Slice> {
588        let mut rows = Vec::new();
589        for kid in self.kids(node) {
590            if self.name(kid) != "ValuesExpressions" {
591                continue;
592            }
593            let mut items = Vec::new();
594            for expr in self.kids(kid) {
595                items.push(self.expr(expr)?);
596            }
597            let slice = self.expr_slice(items);
598            rows.push(slice);
599        }
600        let start = self.ast.rows.len() as u32;
601        self.ast.rows.extend(rows);
602        Ok(Slice { start, len: self.ast.rows.len() as u32 - start })
603    }
604
605    /// `OptionalParensSimpleSelect <- SimpleSelectParens / SimpleSelect`, down to the select.
606    fn unwrap_parens(&self, node: u32) -> u32 {
607        let mut node = self.first(node);
608        while self.name(node) == "SimpleSelectParens" {
609            node = self.first(node);
610        }
611        node
612    }
613
614    /// `ResultModifiers <- OrderByClause? LimitOffset?`.
615    fn result_modifiers(&mut self, query: QueryRef, node: u32) -> Result<()> {
616        let order = self.find(node, "OrderByClause");
617        if order != NONE {
618            let (items, all) = self.order_by(order)?;
619            let start = self.ast.order_items.len() as u32;
620            self.ast.order_items.extend(items);
621            self.ast.queries[query as usize].order_by =
622                Slice { start, len: self.ast.order_items.len() as u32 - start };
623            self.ast.queries[query as usize].order_by_all = all;
624        }
625        let limit = self.find(node, "LimitOffset");
626        if limit != NONE {
627            self.limit_offset(query, self.first(limit))?;
628        }
629        Ok(())
630    }
631
632    /// The four spellings of a limit and an offset, in either order and either one alone.
633    fn limit_offset(&mut self, query: QueryRef, node: u32) -> Result<()> {
634        match self.name(node) {
635            "LimitOffsetClause" | "OffsetLimitClause" => {
636                let limit = self.find(node, "LimitClause");
637                if limit != NONE {
638                    self.limit(query, limit)?;
639                }
640                let offset = self.find(node, "OffsetClause");
641                if offset != NONE {
642                    self.offset(query, offset)?;
643                }
644                Ok(())
645            }
646            _ => self.unsupported(node),
647        }
648    }
649
650    /// `LimitClause <- 'LIMIT' LimitValue`.
651    fn limit(&mut self, query: QueryRef, node: u32) -> Result<()> {
652        let value = self.first(node);
653        let inner = self.first(value);
654        match self.name(inner) {
655            // `LIMIT ALL` is no limit at all, which is what an absent limit already means.
656            "LimitAll" => Ok(()),
657            // `LimitExpression <- Expression '%'?`. The percent sign is a terminal so it leaves no
658            // node behind, and the only thing that says it was written is the text of the rule that
659            // matched it.
660            "LimitExpression" => {
661                let expr = self.expr(self.first(inner))?;
662                self.ast.queries[query as usize].limit = expr;
663                self.ast.queries[query as usize].limit_percent = self.text(inner).ends_with('%');
664                Ok(())
665            }
666            "LimitLiteralPercent" => {
667                let expr = self.expr(self.first(inner))?;
668                self.ast.queries[query as usize].limit = expr;
669                self.ast.queries[query as usize].limit_percent = true;
670                Ok(())
671            }
672            _ => self.unsupported(inner),
673        }
674    }
675
676    /// `OffsetClause <- 'OFFSET' OffsetValue`, where `OffsetValue <- Expression RowOrRows?`.
677    fn offset(&mut self, query: QueryRef, node: u32) -> Result<()> {
678        let value = self.first(node);
679        let expr = self.expr(self.first(value))?;
680        self.ast.queries[query as usize].offset = expr;
681        Ok(())
682    }
683
684    /// `SimpleSelect <- SelectFrom WhereClause? GroupByClause? HavingClause? WindowClause?
685    /// QualifyClause? SampleClause?`.
686    fn simple_select(&mut self, node: u32) -> Result<SelectRef> {
687        for name in ["WindowClause", "QualifyClause", "SampleClause"] {
688            let clause = self.find(node, name);
689            if clause != NONE {
690                return self.unsupported(clause);
691            }
692        }
693        let mut select = Select::empty();
694        self.select_from(&mut select, self.first(node))?;
695        let filter = self.find(node, "WhereClause");
696        if filter != NONE {
697            select.filter = self.expr(self.first(filter))?;
698        }
699        let group = self.find(node, "GroupByClause");
700        if group != NONE {
701            self.group_by(&mut select, self.first(group))?;
702        }
703        let having = self.find(node, "HavingClause");
704        if having != NONE {
705            select.having = self.expr(self.first(having))?;
706        }
707        Ok(self.push_select(select))
708    }
709
710    /// `SelectFrom <- SelectFromClause / FromSelectClause`, which is `SELECT ... FROM ...` and
711    /// DuckDB's `FROM ... SELECT ...` written the other way round.
712    fn select_from(&mut self, select: &mut Select, node: u32) -> Result<()> {
713        let clause = self.first(node);
714        let targets = self.find(clause, "SelectClause");
715        let from = self.find(clause, "FromClause");
716        if from != NONE {
717            select.from = self.sources(from)?;
718        }
719        if targets == NONE {
720            // `FROM t` on its own. DuckDB reads it as `SELECT * FROM t`, and inventing the star
721            // here rather than in the binder keeps the binder from having to know the shape of the
722            // clause that was missing.
723            let star = self.push(Expr::Star { qualifier: Slice::default() });
724            let start = self.ast.targets.len() as u32;
725            self.ast.targets.push(Target { expr: star, alias: NONE });
726            select.targets = Slice { start, len: 1 };
727            return Ok(());
728        }
729        self.select_clause(select, targets)
730    }
731
732    /// `SelectClause <- 'SELECT' DistinctClause? TargetList?`.
733    fn select_clause(&mut self, select: &mut Select, node: u32) -> Result<()> {
734        let distinct = self.find(node, "DistinctClause");
735        if distinct != NONE {
736            let inner = self.first(distinct);
737            select.distinct = match self.name(inner) {
738                // `SELECT ALL` is the default spelled out.
739                "DistinctAll" => Distinct::No,
740                "DistinctOn" => {
741                    let on = self.find(inner, "DistinctOnTargets");
742                    if on == NONE {
743                        Distinct::Yes
744                    } else {
745                        let mut items = Vec::new();
746                        for kid in self.kids(on) {
747                            items.push(self.expr(kid)?);
748                        }
749                        Distinct::On(self.expr_slice(items))
750                    }
751                }
752                _ => return self.unsupported(inner),
753            };
754        }
755        let list = self.find(node, "TargetList");
756        if list == NONE {
757            return Ok(());
758        }
759        let mut targets = Vec::new();
760        for kid in self.kids(list) {
761            targets.push(self.target(kid)?);
762        }
763        let start = self.ast.targets.len() as u32;
764        self.ast.targets.extend(targets);
765        select.targets = Slice { start, len: self.ast.targets.len() as u32 - start };
766        Ok(())
767    }
768
769    /// `AliasedExpression <- ColIdExpression / ExpressionAsCollabel / ExpressionOptIdentifier`.
770    fn target(&mut self, node: u32) -> Result<Target> {
771        let inner = self.first(node);
772        match self.name(inner) {
773            // `ColIdExpression <- ColId ':' Expression`, the alias written first.
774            "ColIdExpression" => {
775                let alias = self.identifier(self.first(inner));
776                let expr = self.expr(self.nth(inner, 1))?;
777                Ok(Target { expr, alias })
778            }
779            "ExpressionAsCollabel" => {
780                let expr = self.expr(self.first(inner))?;
781                let alias = self.identifier(self.nth(inner, 1));
782                Ok(Target { expr, alias })
783            }
784            "ExpressionOptIdentifier" => {
785                let expr = self.expr(self.first(inner))?;
786                let alias =
787                    if self.count(inner) > 1 { self.identifier(self.nth(inner, 1)) } else { NONE };
788                Ok(Target { expr, alias })
789            }
790            _ => self.unsupported(inner),
791        }
792    }
793
794    /// `GroupByClause <- 'GROUP' 'BY' GroupByExpressions`.
795    fn group_by(&mut self, select: &mut Select, node: u32) -> Result<()> {
796        let inner = self.first(node);
797        match self.name(inner) {
798            "GroupByAll" => {
799                select.group_by_all = true;
800                Ok(())
801            }
802            "GroupByList" => {
803                let mut items = Vec::new();
804                for kid in self.kids(inner) {
805                    // `GroupByExpression <- EmptyGroupingItem / CubeOrRollupClause /
806                    // GroupingSetsClause / GroupByBaseExpression`.
807                    let expression = self.first(kid);
808                    if self.name(expression) != "GroupByBaseExpression" {
809                        return self.unsupported(expression);
810                    }
811                    items.push(self.expr(self.first(expression))?);
812                }
813                select.group_by = self.expr_slice(items);
814                Ok(())
815            }
816            _ => self.unsupported(inner),
817        }
818    }
819
820    /// `OrderByClause <- 'ORDER' 'BY' OrderByExpressions`, where `OrderByExpressions <- OrderByAll
821    /// / OrderByExpressionList`.
822    fn order_by(&mut self, node: u32) -> Result<(Vec<OrderItem>, bool)> {
823        let inner = self.first(self.first(node));
824        match self.name(inner) {
825            "OrderByAll" => {
826                let (order, nulls) = self.sort_options(inner);
827                Ok((vec![OrderItem { expr: NONE, order, nulls }], true))
828            }
829            "OrderByExpressionList" => {
830                let mut items = Vec::new();
831                for kid in self.kids(inner) {
832                    // `OrderByExpression <- Expression DescOrAsc? NullsFirstOrLast?`.
833                    let expr = self.expr(self.first(kid))?;
834                    let (order, nulls) = self.sort_options(kid);
835                    items.push(OrderItem { expr, order, nulls });
836                }
837                Ok((items, false))
838            }
839            _ => self.unsupported(inner),
840        }
841    }
842
843    /// The direction and the null placement of one sort key, either of which may be unwritten.
844    fn sort_options(&self, node: u32) -> (Order, Nulls) {
845        let direction = self.find(node, "DescOrAsc");
846        let order = if direction == NONE {
847            Order::Unstated
848        } else if self.name(self.first(direction)) == "DescendingOrder" {
849            Order::Descending
850        } else {
851            Order::Ascending
852        };
853        let placement = self.find(node, "NullsFirstOrLast");
854        let nulls = if placement == NONE {
855            Nulls::Unstated
856        } else if self.name(self.first(placement)) == "NullsFirst" {
857            Nulls::First
858        } else {
859            Nulls::Last
860        };
861        (order, nulls)
862    }
863
864    // From clauses.
865
866    /// `FromClause <- 'FROM' List(TableRef)`.
867    fn sources(&mut self, node: u32) -> Result<Slice> {
868        let mut items = Vec::new();
869        for kid in self.kids(node) {
870            items.push(self.table_ref(kid)?);
871        }
872        let start = self.ast.source_lists.len() as u32;
873        self.ast.source_lists.extend(items);
874        Ok(Slice { start, len: self.ast.source_lists.len() as u32 - start })
875    }
876
877    /// `TableRef <- InnerTableRef JoinOrPivot*`, left associative like the set operators.
878    fn table_ref(&mut self, node: u32) -> Result<SourceRef> {
879        let mut kids = self.kids(node);
880        let head = kids.next().unwrap_or(NONE);
881        let mut left = self.inner_table_ref(head)?;
882        for tail in kids {
883            let clause = self.first(tail);
884            if self.name(clause) != "JoinClause" {
885                return self.unsupported(clause);
886            }
887            left = self.join(left, self.first(clause))?;
888        }
889        Ok(left)
890    }
891
892    /// `InnerTableRef <- ValuesRef / TableFunction / TableSubquery / BaseTableRef / ParensTableRef`.
893    fn inner_table_ref(&mut self, node: u32) -> Result<SourceRef> {
894        let inner = if self.name(node) == "InnerTableRef" { self.first(node) } else { node };
895        match self.name(inner) {
896            "BaseTableRef" => {
897                if self.find(inner, "TableAliasColon") != NONE {
898                    return self.unsupported(inner);
899                }
900                for name in ["AtClause", "SampleClause"] {
901                    let clause = self.find(inner, name);
902                    if clause != NONE {
903                        return self.unsupported(clause);
904                    }
905                }
906                let name = self.name_parts(self.find(inner, "BaseTableName"));
907                let (alias, columns) = self.table_alias(self.find(inner, "TableAlias"));
908                Ok(self.push_source(Source::Table { name, alias, columns }))
909            }
910            "TableSubquery" => {
911                if self.find(inner, "TableAliasColon") != NONE
912                    || self.find(inner, "Lateral") != NONE
913                {
914                    return self.unsupported(inner);
915                }
916                // `SubqueryReference <- Parens(SelectStatementInternal)`.
917                let reference = self.find(inner, "SubqueryReference");
918                let query = self.query(self.first(reference))?;
919                let (alias, columns) = self.table_alias(self.find(inner, "TableAlias"));
920                Ok(self.push_source(Source::Subquery { query, alias, columns }))
921            }
922            // `TableFunction <- TableFunctionLateralOpt / TableFunctionAliasColon`, and
923            // `TableFunctionLateralOpt <- Lateral? QualifiedTableFunction TableFunctionArguments
924            // WithOrdinality? TableAlias?`. The colon form and `LATERAL` are their own work, and
925            // `WITH ORDINALITY` adds a column, so all three are turned away rather than dropped.
926            "TableFunction" => {
927                let form = self.first(inner);
928                for name in ["TableAliasColon", "Lateral", "WithOrdinality", "SampleClause"] {
929                    let clause = self.find(form, name);
930                    if clause != NONE {
931                        return self.unsupported(clause);
932                    }
933                }
934                let name = self.name_parts(self.find(form, "QualifiedTableFunction"));
935                let mut args = Vec::new();
936                // `TableFunctionArguments <- Parens(List(FunctionArgument)?)`, so a call with no
937                // arguments has the wrapper and no list under it.
938                let list = self.find(form, "TableFunctionArguments");
939                for kid in self.kids(list) {
940                    args.push(self.argument(kid)?);
941                }
942                let args = self.expr_slice(args);
943                let (alias, columns) = self.table_alias(self.find(form, "TableAlias"));
944                Ok(self.push_source(Source::Function { name, args, alias, columns }))
945            }
946            "ValuesRef" => {
947                if self.find(inner, "TableAliasColon") != NONE {
948                    return self.unsupported(inner);
949                }
950                let rows = self.values_clause(self.find(inner, "ValuesClause"))?;
951                let (alias, columns) = self.table_alias(self.find(inner, "TableAlias"));
952                Ok(self.push_source(Source::Values { rows, alias, columns }))
953            }
954            "ParensTableRef" => {
955                if self.find(inner, "TableAliasColon") != NONE
956                    || self.find(inner, "SampleClause") != NONE
957                    || self.find(inner, "TableAlias") != NONE
958                {
959                    return self.unsupported(inner);
960                }
961                self.table_ref(self.find(inner, "TableRef"))
962            }
963            _ => self.unsupported(inner),
964        }
965    }
966
967    /// `TableAlias <- TableAliasAs / TableAliasWithoutAs`, either with a column alias list.
968    fn table_alias(&mut self, node: u32) -> (StrRef, Slice) {
969        if node == NONE {
970            return (NONE, Slice::default());
971        }
972        let inner = self.first(node);
973        let alias = self.identifier(self.first(inner));
974        let list = self.find(inner, "ColumnAliases");
975        if list == NONE {
976            return (alias, Slice::default());
977        }
978        let mut columns = Vec::new();
979        for kid in self.kids(list) {
980            let name = self.identifier(kid);
981            columns.push(name);
982        }
983        (alias, self.part_slice(columns))
984    }
985
986    /// `JoinClause <- JoinByClause / RegularJoinClause / JoinWithoutOnClause / NearestJoinClause`.
987    fn join(&mut self, left: SourceRef, node: u32) -> Result<SourceRef> {
988        match self.name(node) {
989            // `RegularJoinClause <- Asof? JoinType? 'JOIN' TableRef JoinQualifier`.
990            "RegularJoinClause" => {
991                if self.find(node, "Asof") != NONE {
992                    return self.unsupported(node);
993                }
994                let kind = self.join_type(self.find(node, "JoinType"));
995                let right = self.table_ref(self.find(node, "TableRef"))?;
996                let (on, using) = self.join_qualifier(self.find(node, "JoinQualifier"))?;
997                Ok(self.push_source(Source::Join { left, right, kind, natural: false, on, using }))
998            }
999            // `JoinWithoutOnClause <- JoinPrefix 'JOIN' InnerTableRef`, which is cross, natural and
1000            // positional. Those three are exactly the joins that carry no condition.
1001            "JoinWithoutOnClause" => {
1002                let prefix = self.first(self.find(node, "JoinPrefix"));
1003                let (kind, natural) = match self.name(prefix) {
1004                    "CrossJoinPrefix" => (JoinKind::Cross, false),
1005                    "PositionalJoinPrefix" => (JoinKind::Positional, false),
1006                    "NaturalJoinPrefix" => (self.join_type(self.find(prefix, "JoinType")), true),
1007                    _ => return self.unsupported(prefix),
1008                };
1009                let right = self.inner_table_ref(self.find(node, "InnerTableRef"))?;
1010                Ok(self.push_source(Source::Join {
1011                    left,
1012                    right,
1013                    kind,
1014                    natural,
1015                    on: NONE,
1016                    using: Slice::default(),
1017                }))
1018            }
1019            _ => self.unsupported(node),
1020        }
1021    }
1022
1023    /// `JoinType <- FullJoin / LeftJoin / RightJoin / SemiJoin / AntiJoin / InnerJoin`, absent
1024    /// meaning inner, which is what SQL has always meant by a bare `JOIN`.
1025    fn join_type(&self, node: u32) -> JoinKind {
1026        if node == NONE {
1027            return JoinKind::Inner;
1028        }
1029        match self.name(self.first(node)) {
1030            "FullJoin" => JoinKind::Full,
1031            "LeftJoin" => JoinKind::Left,
1032            "RightJoin" => JoinKind::Right,
1033            "SemiJoin" => JoinKind::Semi,
1034            "AntiJoin" => JoinKind::Anti,
1035            _ => JoinKind::Inner,
1036        }
1037    }
1038
1039    /// `JoinQualifier <- OnClause / UsingClause`.
1040    fn join_qualifier(&mut self, node: u32) -> Result<(ExprRef, Slice)> {
1041        let inner = self.first(node);
1042        match self.name(inner) {
1043            "OnClause" => Ok((self.expr(self.first(inner))?, Slice::default())),
1044            "UsingClause" => {
1045                let mut columns = Vec::new();
1046                for kid in self.kids(inner) {
1047                    let name = self.identifier(kid);
1048                    columns.push(name);
1049                }
1050                Ok((NONE, self.part_slice(columns)))
1051            }
1052            _ => self.unsupported(inner),
1053        }
1054    }
1055
1056    // Expressions.
1057
1058    /// One expression, from wherever in the precedence chain it starts.
1059    ///
1060    /// The loop is the whole design. A rule that says something gets an arm, a rule with exactly
1061    /// one child said nothing and is stepped through, and anything else is an error naming itself.
1062    /// The chain rules never get an arm for their one child case, which is why adding a precedence
1063    /// level upstream costs nothing here.
1064    fn expr(&mut self, node: u32) -> Result<ExprRef> {
1065        let mut node = node;
1066        loop {
1067            let count = self.count(node);
1068            let name = self.name(node);
1069            match name {
1070                "LogicalOrExpression" if count > 1 => return self.logical(node, BinaryOp::Or),
1071                "LogicalAndExpression" if count > 1 => return self.logical(node, BinaryOp::And),
1072                "LogicalNotExpression" if count > 1 => return self.logical_not(node),
1073                "IsExpression" if count > 1 => return self.is_expression(node),
1074                "BetweenInLikeExpression" if count > 1 => return self.between_in_like(node),
1075                "PrefixExpression" if count > 1 => return self.prefix(node),
1076                "BaseExpression" if count > 1 => return self.indirection(node),
1077                "LambdaArrowExpression"
1078                | "IsDistinctFromExpression"
1079                | "ComparisonExpression"
1080                | "OtherOperatorExpression"
1081                | "BitwiseExpression"
1082                | "AdditiveExpression"
1083                | "MultiplicativeExpression"
1084                | "ExponentiationExpression"
1085                | "CollateExpression"
1086                | "AtTimeZoneExpression"
1087                    if count > 1 =>
1088                {
1089                    return self.tail_chain(node);
1090                }
1091                "ColumnReference" => {
1092                    let name = self.name_parts(node);
1093                    return Ok(self.push(Expr::Column { name }));
1094                }
1095                "StarExpression" => return self.star(node),
1096                "NumberLiteral" => {
1097                    let text = self.text(node).to_string();
1098                    let text = self.intern(&text);
1099                    return Ok(self.push(Expr::Literal { kind: LiteralKind::Number, text }));
1100                }
1101                "StringLiteral" => {
1102                    let text = self.string_value(node);
1103                    let text = self.intern(&text);
1104                    return Ok(self.push(Expr::Literal { kind: LiteralKind::String, text }));
1105                }
1106                "NullLiteral" | "TrueLiteral" | "FalseLiteral" => {
1107                    let kind = match name {
1108                        "NullLiteral" => LiteralKind::Null,
1109                        "TrueLiteral" => LiteralKind::True,
1110                        _ => LiteralKind::False,
1111                    };
1112                    return Ok(self.push(Expr::Literal { kind, text: NONE }));
1113                }
1114                "FunctionExpression" => return self.function(node),
1115                "ExtractExpression" => return self.extract(node),
1116                "CastExpression" => return self.cast(node),
1117                "CaseExpression" => return self.case(node),
1118                "ParenthesisExpression" => return self.row(node),
1119                "SubqueryExpression" => return self.subquery(node),
1120                _ if count == 1 => node = self.first(node),
1121                _ => return self.unsupported(node),
1122            }
1123        }
1124    }
1125
1126    /// `X <- Y XTail*` where `XTail <- Operator Y`, the shape ten precedence levels share.
1127    fn tail_chain(&mut self, node: u32) -> Result<ExprRef> {
1128        let mut kids = self.kids(node);
1129        let head = kids.next().unwrap_or(NONE);
1130        let mut left = self.expr(head)?;
1131        for tail in kids {
1132            let operator = self.first(tail);
1133            let op = self.binary_op(operator)?;
1134            // `ComparisonExpressionTail <- ComparisonOperator NotExpression? BetweenInLikeExpression`
1135            // is the one tail with an optional middle, so the operand is the last child and not the
1136            // second one. Taking the last is right for every tail and wrong for none.
1137            let operand = self.kids(tail).last().unwrap_or(NONE);
1138            if self.count(tail) > 2 {
1139                return self.unsupported(tail);
1140            }
1141            let right = self.expr(operand)?;
1142            left = self.push(Expr::Binary { op, left, right });
1143        }
1144        Ok(left)
1145    }
1146
1147    /// Which infix operator a tail's operator node is.
1148    fn binary_op(&mut self, node: u32) -> Result<BinaryOp> {
1149        // The operator rules nest: `ComparisonOperator` over `OperatorGreaterThan` over the symbol
1150        // itself. Every one of them covers the same tokens, so the text is the same at every level
1151        // and reading it once at the top is enough. The name is not, which is why the bottom of the
1152        // chain is walked to as well: `OtherOperator` says nothing and `OperatorLiteral` says
1153        // everything, and they are three levels apart.
1154        let mut leaf = node;
1155        while self.count(leaf) == 1 {
1156            leaf = self.first(leaf);
1157        }
1158        let text = self.text(node);
1159        let upper = text.to_ascii_uppercase();
1160        let op = match upper.as_str() {
1161            "OR" => BinaryOp::Or,
1162            "AND" => BinaryOp::And,
1163            "=" | "==" => BinaryOp::Eq,
1164            "!=" | "<>" => BinaryOp::NotEq,
1165            "<" => BinaryOp::Lt,
1166            ">" => BinaryOp::Gt,
1167            "<=" => BinaryOp::LtEq,
1168            ">=" => BinaryOp::GtEq,
1169            "+" => BinaryOp::Add,
1170            "-" => BinaryOp::Subtract,
1171            "*" => BinaryOp::Multiply,
1172            "/" => BinaryOp::Divide,
1173            "//" => BinaryOp::IntegerDivide,
1174            "%" => BinaryOp::Modulo,
1175            "^" | "**" => BinaryOp::Power,
1176            "&" => BinaryOp::BitAnd,
1177            "|" => BinaryOp::BitOr,
1178            "<<" => BinaryOp::ShiftLeft,
1179            ">>" => BinaryOp::ShiftRight,
1180            "||" => BinaryOp::Concat,
1181            "COLLATE" => BinaryOp::Collate,
1182            "->" => BinaryOp::Arrow,
1183            "->>" => BinaryOp::LongArrow,
1184            "@>" => BinaryOp::Contains,
1185            "<@" => BinaryOp::ContainedBy,
1186            "&&" => BinaryOp::Overlaps,
1187            "^@" => BinaryOp::StartsWith,
1188            "<<=" => BinaryOp::InetContainedByOrEq,
1189            ">>=" => BinaryOp::InetContainsOrEq,
1190            _ if self.name(leaf) == "AtTimeZoneOperator" => BinaryOp::AtTimeZone,
1191            // `IsDistinctFromOp <- 'IS' 'NOT'? 'DISTINCT' 'FROM'`, told apart by the middle word,
1192            // which is not in the tree because keywords are terminals.
1193            _ if self.name(leaf) == "IsDistinctFromOp" => {
1194                if upper.split_whitespace().any(|word| word == "NOT") {
1195                    BinaryOp::IsNotDistinctFrom
1196                } else {
1197                    BinaryOp::IsDistinctFrom
1198                }
1199            }
1200            // `OperatorLiteral` is the open end of the operator set. Its body in the grammar text
1201            // says `Identifier`, but it is one of the 24 rules whose body the matcher does not
1202            // walk and the matcher it is overridden to is the bare operator one, so what it
1203            // actually accepts is any run of operator characters that is not already a token.
1204            // `a <=> b` is such a run, DuckDB resolves it as a two argument function of that name,
1205            // and rejecting it here would reject SQL DuckDB accepts.
1206            _ if self.name(leaf) == "OperatorLiteral" => {
1207                let interned = self.intern(text);
1208                BinaryOp::Named(interned)
1209            }
1210            _ => return self.unsupported(node),
1211        };
1212        Ok(op)
1213    }
1214
1215    /// `LogicalOrExpression <- LogicalAndExpression LogicalOrExpressionTail*`, and the `AND` twin.
1216    ///
1217    /// Separate from the other tails because the tail here is `'OR' LogicalAndExpression` with the
1218    /// keyword as a terminal, so there is no operator node to read and the operator is the rule.
1219    fn logical(&mut self, node: u32, op: BinaryOp) -> Result<ExprRef> {
1220        let mut kids = self.kids(node);
1221        let head = kids.next().unwrap_or(NONE);
1222        let mut left = self.expr(head)?;
1223        for tail in kids {
1224            let right = self.expr(self.first(tail))?;
1225            left = self.push(Expr::Binary { op, left, right });
1226        }
1227        Ok(left)
1228    }
1229
1230    /// `LogicalNotExpression <- NotExpression? IsExpression`, where `NotExpression <- NotKeyword+`.
1231    ///
1232    /// The plus matters. `NOT NOT x` is two nodes in the parse tree and two negations in the AST,
1233    /// and folding them here would be an optimizer decision taken in the parser.
1234    fn logical_not(&mut self, node: u32) -> Result<ExprRef> {
1235        let negations = self.count(self.first(node));
1236        let mut expr = self.expr(self.nth(node, 1))?;
1237        for _ in 0..negations {
1238            expr = self.push(Expr::Unary { op: UnaryOp::Not, operand: expr });
1239        }
1240        Ok(expr)
1241    }
1242
1243    /// `IsExpression <- IsDistinctFromExpression IsTest*`, the postfix null and boolean tests.
1244    fn is_expression(&mut self, node: u32) -> Result<ExprRef> {
1245        let mut kids = self.kids(node);
1246        let head = kids.next().unwrap_or(NONE);
1247        let mut expr = self.expr(head)?;
1248        for test in kids {
1249            let inner = self.first(test);
1250            let negated = self.text(inner).to_ascii_uppercase().contains("NOT");
1251            let op = match self.name(inner) {
1252                "NotNull" => UnaryOp::IsNotNull,
1253                "IsNull" => UnaryOp::IsNull,
1254                // `IsLiteral <- 'IS' 'NOT'? IsLiteralValue`, and the value rule is one more level
1255                // down again because it is a choice of four and not four alternatives inlined.
1256                "IsLiteral" => match self.name(self.first(self.first(inner))) {
1257                    "NullLiteral" if negated => UnaryOp::IsNotNull,
1258                    "NullLiteral" => UnaryOp::IsNull,
1259                    "TrueLiteral" if negated => UnaryOp::IsNotTrue,
1260                    "TrueLiteral" => UnaryOp::IsTrue,
1261                    "FalseLiteral" if negated => UnaryOp::IsNotFalse,
1262                    "FalseLiteral" => UnaryOp::IsFalse,
1263                    "UnknownLiteral" if negated => UnaryOp::IsNotUnknown,
1264                    "UnknownLiteral" => UnaryOp::IsUnknown,
1265                    _ => return self.unsupported(inner),
1266                },
1267                _ => return self.unsupported(inner),
1268            };
1269            expr = self.push(Expr::Unary { op, operand: expr });
1270        }
1271        Ok(expr)
1272    }
1273
1274    /// `BetweenInLikeExpression <- OtherOperatorExpression BetweenInLikeOp?`.
1275    fn between_in_like(&mut self, node: u32) -> Result<ExprRef> {
1276        let operand = self.expr(self.first(node))?;
1277        // `BetweenInLikeOp <- 'NOT'? BetweenInLikeOpExpression`. The `NOT` is a terminal, so what
1278        // says it was written is that the op node covers a token the inner node does not.
1279        let op = self.nth(node, 1);
1280        let negated = self.text(op).to_ascii_uppercase().starts_with("NOT");
1281        let inner = self.first(self.first(op));
1282        match self.name(inner) {
1283            // `BetweenClause <- 'BETWEEN' x 'AND' y`.
1284            "BetweenClause" => {
1285                let low = self.expr(self.first(inner))?;
1286                let high = self.expr(self.nth(inner, 1))?;
1287                Ok(self.push(Expr::Between { operand, low, high, negated }))
1288            }
1289            // `InClause <- 'IN' InExpression`.
1290            "InClause" => {
1291                let expression = self.first(self.first(inner));
1292                match self.name(expression) {
1293                    "InExpressionList" => {
1294                        let mut items = Vec::new();
1295                        for kid in self.kids(expression) {
1296                            items.push(self.expr(kid)?);
1297                        }
1298                        let list = self.expr_slice(items);
1299                        Ok(self.push(Expr::In { operand, list, negated }))
1300                    }
1301                    _ => self.unsupported(expression),
1302                }
1303            }
1304            // `LikeClause <- LikeVariations x EscapeClause?`.
1305            "LikeClause" => {
1306                if self.find(inner, "EscapeClause") != NONE {
1307                    return self.unsupported(inner);
1308                }
1309                let variation = self.name(self.first(self.first(inner)));
1310                let op = match (variation, negated) {
1311                    ("LikeToken", false) | ("NotLikeOp", true) => BinaryOp::Like,
1312                    ("LikeToken", true) | ("NotLikeOp", false) => BinaryOp::NotLike,
1313                    ("ILikeToken", false) | ("NotILikeOp", true) => BinaryOp::ILike,
1314                    ("ILikeToken", true) | ("NotILikeOp", false) => BinaryOp::NotILike,
1315                    // Glob and the bare regex match have no negated spelling of their own in
1316                    // `LikeVariations`, so a `NOT` in front of either stays an explicit negation.
1317                    ("GlobToken", _) => BinaryOp::Glob,
1318                    ("RegexMatchToken", _) => BinaryOp::Regex,
1319                    ("SimilarToToken", false) | ("NotSimilarToOp", true) => BinaryOp::SimilarTo,
1320                    ("SimilarToToken", true) | ("NotSimilarToOp", false) => BinaryOp::NotSimilarTo,
1321                    ("RegexInsensitiveMatchToken", false)
1322                    | ("NotRegexInsensitiveMatchOp", true) => BinaryOp::RegexInsensitive,
1323                    ("RegexInsensitiveMatchToken", true)
1324                    | ("NotRegexInsensitiveMatchOp", false) => BinaryOp::NotRegexInsensitive,
1325                    _ => return self.unsupported(inner),
1326                };
1327                let right = self.expr(self.nth(inner, 1))?;
1328                let expr = self.push(Expr::Binary { op, left: operand, right });
1329                // The like family folds its negation into the operator because it has a spelling
1330                // for the negated form. Glob and regex do not, so theirs stays where it was.
1331                if negated && matches!(op, BinaryOp::Glob | BinaryOp::Regex) {
1332                    return Ok(self.push(Expr::Unary { op: UnaryOp::Not, operand: expr }));
1333                }
1334                Ok(expr)
1335            }
1336            _ => self.unsupported(inner),
1337        }
1338    }
1339
1340    /// `PrefixExpression <- PrefixOperator* BaseExpression`, applied right to left.
1341    fn prefix(&mut self, node: u32) -> Result<ExprRef> {
1342        let kids: Vec<u32> = self.kids(node).collect();
1343        let mut expr = self.expr(kids[kids.len() - 1])?;
1344        for &operator in kids[..kids.len() - 1].iter().rev() {
1345            let op = match self.name(self.first(operator)) {
1346                "MinusPrefixOperator" => UnaryOp::Negate,
1347                "PlusPrefixOperator" => UnaryOp::Plus,
1348                "TildePrefixOperator" => UnaryOp::BitNot,
1349                _ => return self.unsupported(operator),
1350            };
1351            expr = self.push(Expr::Unary { op, operand: expr });
1352        }
1353        Ok(expr)
1354    }
1355
1356    /// `BaseExpression <- SingleExpression IndirectionList?`, the postfix chain.
1357    fn indirection(&mut self, node: u32) -> Result<ExprRef> {
1358        let mut expr = self.expr(self.first(node))?;
1359        for step in self.kids(self.nth(node, 1)) {
1360            let inner = self.first(step);
1361            expr = match self.name(inner) {
1362                // `CastOperator <- '::' Type`.
1363                "CastOperator" => {
1364                    let text = self.text(self.first(inner)).to_string();
1365                    let ty = self.intern(&text);
1366                    self.push(Expr::Cast { operand: expr, ty, try_cast: false })
1367                }
1368                "DotOperator" => {
1369                    let dot = self.first(inner);
1370                    match self.name(dot) {
1371                        // `DotColumnOperator <- '.' ColLabel`, which DuckDB resolves as a call of
1372                        // `struct_extract`. Writing it as that call rather than as its own node
1373                        // keeps the binder from needing a rule for a thing that is already a
1374                        // function.
1375                        "DotColumnOperator" => {
1376                            let field = self.identifier(self.first(dot));
1377                            let text = self.ast.string(field).to_string();
1378                            let literal = self.intern(&text);
1379                            let key = self
1380                                .push(Expr::Literal { kind: LiteralKind::String, text: literal });
1381                            let name = self.function_name("struct_extract");
1382                            let args = self.expr_slice(vec![expr, key]);
1383                            self.push(Expr::Function { name, args, distinct: false })
1384                        }
1385                        // `DotMethodOperator <- '.' MethodExpression`, where `x.f(a)` is `f(x, a)`.
1386                        "DotMethodOperator" => {
1387                            let method = self.first(dot);
1388                            let text = self.text(self.first(method)).to_string();
1389                            let text = unquote(&text);
1390                            let name = self.function_name(&text);
1391                            let mut args = vec![expr];
1392                            let list = self.find(method, "MethodExpressionArguments");
1393                            if list != NONE {
1394                                let inner = self.first(list);
1395                                let arguments = self.find(inner, "MethodFunctionArguments");
1396                                if arguments != NONE {
1397                                    for kid in self.kids(arguments) {
1398                                        args.push(self.argument(kid)?);
1399                                    }
1400                                }
1401                            }
1402                            let args = self.expr_slice(args);
1403                            self.push(Expr::Function { name, args, distinct: false })
1404                        }
1405                        _ => return self.unsupported(dot),
1406                    }
1407                }
1408                // `SliceExpression <- '[' SliceBound ']'`, one index or a range.
1409                "SliceExpression" => {
1410                    let bound = self.first(inner);
1411                    let has_end = self.find(bound, "EndSliceBound") != NONE;
1412                    let has_step = self.find(bound, "StepSliceBound") != NONE;
1413                    if has_end || has_step {
1414                        return self.unsupported(inner);
1415                    }
1416                    let index = self.expr(self.first(bound))?;
1417                    let name = self.function_name("array_extract");
1418                    let args = self.expr_slice(vec![expr, index]);
1419                    self.push(Expr::Function { name, args, distinct: false })
1420                }
1421                // `PostfixOperator <- '!'`.
1422                "PostfixOperator" => {
1423                    self.push(Expr::Unary { op: UnaryOp::Factorial, operand: expr })
1424                }
1425                _ => return self.unsupported(inner),
1426            };
1427        }
1428        Ok(expr)
1429    }
1430
1431    /// A one part function name, for the calls the transformer invents rather than reads.
1432    fn function_name(&mut self, name: &str) -> Slice {
1433        let interned = self.intern(name);
1434        self.part_slice(vec![interned])
1435    }
1436
1437    /// `StarExpression <- StarQualifierList? '*' ExcludeList? ReplaceList? RenameList?`.
1438    fn star(&mut self, node: u32) -> Result<ExprRef> {
1439        for name in ["ExcludeList", "ReplaceList", "RenameList"] {
1440            let list = self.find(node, name);
1441            if list != NONE {
1442                return self.unsupported(list);
1443            }
1444        }
1445        let qualifier = self.find(node, "StarQualifierList");
1446        let qualifier =
1447            if qualifier == NONE { Slice::default() } else { self.name_parts(qualifier) };
1448        Ok(self.push(Expr::Star { qualifier }))
1449    }
1450
1451    /// `FunctionExpression <- FunctionIdentifier FunctionExpressionArguments WithinGroupClause?
1452    /// FilterClause? ExportClause? OverClause?`.
1453    fn function(&mut self, node: u32) -> Result<ExprRef> {
1454        for name in ["WithinGroupClause", "FilterClause", "ExportClause", "OverClause"] {
1455            let clause = self.find(node, name);
1456            if clause != NONE {
1457                return self.unsupported(clause);
1458            }
1459        }
1460        let name = self.name_parts(self.first(node));
1461        // `FunctionExpressionArguments <- Parens(FunctionExpressionArgumentList)` and
1462        // `FunctionExpressionArgumentList <- DistinctOrAll? FunctionArgumentList? OrderByClause?
1463        // IgnoreOrRespectNulls?`, so a call with no arguments still has both wrappers.
1464        let list = self.first(self.nth(node, 1));
1465        for name in ["OrderByClause", "IgnoreOrRespectNulls"] {
1466            let clause = self.find(list, name);
1467            if clause != NONE {
1468                return self.unsupported(clause);
1469            }
1470        }
1471        let distinct = self.quantifier(self.find(list, "DistinctOrAll")) == Quantifier::Distinct;
1472        let mut args = Vec::new();
1473        let arguments = self.find(list, "FunctionArgumentList");
1474        if arguments != NONE {
1475            for kid in self.kids(arguments) {
1476                args.push(self.argument(kid)?);
1477            }
1478        }
1479        let args = self.expr_slice(args);
1480        Ok(self.push(Expr::Function { name, args, distinct }))
1481    }
1482
1483    /// `ExtractExpression <- 'EXTRACT' Parens(ExtractArguments)` and
1484    /// `ExtractArguments <- ExtractArgument 'FROM' Expression`.
1485    ///
1486    /// `EXTRACT` is not a function in the grammar because its argument list is not an argument
1487    /// list, and it is a function everywhere after here because DuckDB's parser does the same
1488    /// rewrite: `EXTRACT(minute FROM t)` is `date_part('minute', t)` and there is no separate
1489    /// implementation of one of them. The part is a keyword, an identifier or a string in the
1490    /// grammar, and all three become the string, which is why this is a rewrite and not a node.
1491    fn extract(&mut self, node: u32) -> Result<ExprRef> {
1492        let arguments = self.find(node, "ExtractArguments");
1493        if arguments == NONE {
1494            return self.unsupported(node);
1495        }
1496        let argument = self.first(self.first(arguments));
1497        let part = match self.name(argument) {
1498            "ExtractStringArgument" => self.string_value(argument),
1499            // A keyword or an identifier, both taken as written. Which specifier names are legal is
1500            // not a question about syntax, so the answer to it lives with the function.
1501            "ExtractDatePartArgument" | "ExtractIdentifierArgument" => {
1502                self.text(argument).to_string()
1503            }
1504            _ => return self.unsupported(argument),
1505        };
1506        let text = self.intern(&part);
1507        let part = self.push(Expr::Literal { kind: LiteralKind::String, text });
1508        let operand = self.expr(self.nth(arguments, 1))?;
1509        let name = self.function_name("date_part");
1510        let args = self.expr_slice(vec![part, operand]);
1511        Ok(self.push(Expr::Function { name, args, distinct: false }))
1512    }
1513
1514    /// `FunctionArgument <- NamedFunctionArgument / PositionalFunctionArgument`.
1515    fn argument(&mut self, node: u32) -> Result<ExprRef> {
1516        let inner = self.first(node);
1517        match self.name(inner) {
1518            "PositionalFunctionArgument" => self.expr(self.first(inner)),
1519            _ => self.unsupported(inner),
1520        }
1521    }
1522
1523    /// `CastExpression <- CastOrTryCast Parens(CastArguments)`.
1524    fn cast(&mut self, node: u32) -> Result<ExprRef> {
1525        let try_cast = self.name(self.first(self.first(node))) == "TryCastKeyword";
1526        // `CastArguments <- Expression 'AS' Type`.
1527        let arguments = self.nth(node, 1);
1528        let operand = self.expr(self.first(arguments))?;
1529        let text = self.text(self.nth(arguments, 1)).to_string();
1530        let ty = self.intern(&text);
1531        Ok(self.push(Expr::Cast { operand, ty, try_cast }))
1532    }
1533
1534    /// `CaseExpression <- 'CASE' Expression? CaseWhenThen+ CaseElse? 'END'`.
1535    fn case(&mut self, node: u32) -> Result<ExprRef> {
1536        let mut operand = NONE;
1537        let mut arms = Vec::new();
1538        let mut otherwise = NONE;
1539        for kid in self.kids(node) {
1540            match self.name(kid) {
1541                // `CaseWhenThen <- 'WHEN' Expression 'THEN' Expression`.
1542                "CaseWhenThen" => {
1543                    let when = self.expr(self.first(kid))?;
1544                    let then = self.expr(self.nth(kid, 1))?;
1545                    arms.push(CaseArm { when, then });
1546                }
1547                // `CaseElse <- 'ELSE' Expression`.
1548                "CaseElse" => otherwise = self.expr(self.first(kid))?,
1549                // The bare `Expression` before the first `WHEN`, which makes it a simple case.
1550                _ => operand = self.expr(kid)?,
1551            }
1552        }
1553        let start = self.ast.case_arms.len() as u32;
1554        self.ast.case_arms.extend(arms);
1555        let arms = Slice { start, len: self.ast.case_arms.len() as u32 - start };
1556        Ok(self.push(Expr::Case { operand, arms, otherwise }))
1557    }
1558
1559    /// `ParenthesisExpression <- Parens(List(Expression)?)`, which is a row value.
1560    ///
1561    /// One item is not a row. `(a)` is `a` in every dialect and reading it as a one column row
1562    /// would change what `(a) = (b)` means.
1563    fn row(&mut self, node: u32) -> Result<ExprRef> {
1564        let mut items = Vec::new();
1565        for kid in self.kids(node) {
1566            items.push(self.expr(kid)?);
1567        }
1568        if items.len() == 1 {
1569            return Ok(items[0]);
1570        }
1571        let items = self.expr_slice(items);
1572        Ok(self.push(Expr::Row { items }))
1573    }
1574
1575    /// `SubqueryExpression <- SubqueryNot? SubqueryExists? SubqueryReference`.
1576    fn subquery(&mut self, node: u32) -> Result<ExprRef> {
1577        if self.find(node, "SubqueryNot") != NONE || self.find(node, "SubqueryExists") != NONE {
1578            return self.unsupported(node);
1579        }
1580        let reference = self.find(node, "SubqueryReference");
1581        let query = self.query(self.first(reference))?;
1582        Ok(self.push(Expr::Subquery { query }))
1583    }
1584
1585    /// The value of a string literal, with the quotes gone and the escapes resolved.
1586    ///
1587    /// A literal can be several tokens. `'a' 'b'` on two lines is one literal that is `ab`, which is
1588    /// the SQL standard's rule and DuckDB's, so the node is decoded token by token rather than by
1589    /// taking its text and stripping the outside.
1590    fn string_value(&self, node: u32) -> String {
1591        let span = self.tree.node(node);
1592        let mut value = String::new();
1593        for token in &self.tokens[span.start as usize..span.end as usize] {
1594            if token.kind != Kind::String {
1595                continue;
1596            }
1597            let text = token.text(self.query);
1598            match text.strip_prefix('\'').and_then(|rest| rest.strip_suffix('\'')) {
1599                Some(body) => value.push_str(&body.replace("''", "'")),
1600                None => value.push_str(text),
1601            }
1602        }
1603        value
1604    }
1605}
1606
1607/// Strip the quoting off an identifier.
1608///
1609/// DuckDB does not fold identifier case at any point, quoted or not, so this only removes the
1610/// quotes and resolves the doubled ones. Anything else would be the parser deciding what a name is.
1611fn unquote(text: &str) -> String {
1612    match text.strip_prefix('"').and_then(|rest| rest.strip_suffix('"')) {
1613        Some(body) => body.replace("\"\"", "\""),
1614        None => text.to_string(),
1615    }
1616}
1617
1618#[cfg(test)]
1619mod tests {
1620    use super::*;
1621    use crate::corpus::CORPUS;
1622    use crate::matcher::parse;
1623
1624    /// The AST written back out as text, which is what the assertions below read.
1625    ///
1626    /// Not a SQL printer and not trying to be. It is deliberately not valid SQL: operators are
1627    /// spelled with the name of the variant and every binary node is parenthesised, so that a test
1628    /// asserting on this text is asserting on the shape of the tree and not on a formatting choice.
1629    /// `a - b - c` and `a - (b - c)` have to look different here or the test that tells them apart
1630    /// is not a test.
1631    fn show(ast: &Ast, expr: ExprRef) -> String {
1632        if expr == NONE {
1633            return "-".to_string();
1634        }
1635        let list = |slice: Slice| {
1636            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
1637        };
1638        match ast.expr(expr) {
1639            Expr::Star { qualifier } if qualifier.is_empty() => "*".to_string(),
1640            Expr::Star { qualifier } => format!("{}.*", ast.name_text(qualifier)),
1641            Expr::Column { name } => ast.name_text(name),
1642            Expr::Literal { kind, text } => match kind {
1643                LiteralKind::Number => ast.string(text).to_string(),
1644                LiteralKind::String => format!("'{}'", ast.string(text)),
1645                other => format!("{other:?}").to_uppercase(),
1646            },
1647            Expr::Unary { op, operand } => format!("({op:?} {})", show(ast, operand)),
1648            Expr::Binary { op, left, right } => {
1649                let op = match op {
1650                    BinaryOp::Named(name) => ast.string(name).to_string(),
1651                    other => format!("{other:?}"),
1652                };
1653                format!("({} {op} {})", show(ast, left), show(ast, right))
1654            }
1655            Expr::Function { name, args, distinct } => {
1656                let distinct = if distinct { "DISTINCT " } else { "" };
1657                format!("{}({distinct}{})", ast.name_text(name), list(args))
1658            }
1659            Expr::Cast { operand, ty, try_cast } => {
1660                let word = if try_cast { "TRY_CAST" } else { "CAST" };
1661                format!("{word}({} AS {})", show(ast, operand), ast.string(ty))
1662            }
1663            Expr::Case { operand, arms, otherwise } => {
1664                let arms = ast
1665                    .arm_list(arms)
1666                    .iter()
1667                    .map(|arm| format!("WHEN {} THEN {}", show(ast, arm.when), show(ast, arm.then)))
1668                    .collect::<Vec<_>>()
1669                    .join(" ");
1670                format!("CASE {} {arms} ELSE {} END", show(ast, operand), show(ast, otherwise))
1671            }
1672            Expr::Between { operand, low, high, negated } => {
1673                let not = if negated { "NOT " } else { "" };
1674                format!(
1675                    "({not}{} BETWEEN {} AND {})",
1676                    show(ast, operand),
1677                    show(ast, low),
1678                    show(ast, high)
1679                )
1680            }
1681            Expr::In { operand, list: items, negated } => {
1682                let not = if negated { "NOT " } else { "" };
1683                format!("({not}{} IN [{}])", show(ast, operand), list(items))
1684            }
1685            Expr::Row { items } => format!("ROW({})", list(items)),
1686            Expr::Subquery { query } => format!("({})", show_query(ast, query)),
1687        }
1688    }
1689
1690    /// One from item written back out.
1691    fn show_source(ast: &Ast, source: SourceRef) -> String {
1692        let alias = |alias: StrRef| match alias {
1693            NONE => String::new(),
1694            other => format!(" AS {}", ast.string(other)),
1695        };
1696        match ast.source(source) {
1697            Source::Table { name, alias: name_alias, .. } => {
1698                format!("{}{}", ast.name_text(name), alias(name_alias))
1699            }
1700            Source::Function { name, args, alias: call_alias, .. } => {
1701                let args = ast
1702                    .expr_list(args)
1703                    .iter()
1704                    .map(|&item| show(ast, item))
1705                    .collect::<Vec<_>>()
1706                    .join(", ");
1707                format!("{}({args}){}", ast.name_text(name), alias(call_alias))
1708            }
1709            Source::Subquery { query, alias: query_alias, .. } => {
1710                format!("({}){}", show_query(ast, query), alias(query_alias))
1711            }
1712            Source::Values { rows, alias: values_alias, .. } => {
1713                format!("{}{}", show_rows(ast, rows), alias(values_alias))
1714            }
1715            Source::Join { left, right, kind, natural, on, using } => {
1716                let natural = if natural { "NATURAL " } else { "" };
1717                let on = if on == NONE { String::new() } else { format!(" ON {}", show(ast, on)) };
1718                let using = if using.is_empty() {
1719                    String::new()
1720                } else {
1721                    format!(" USING ({})", ast.name_text(using))
1722                };
1723                format!(
1724                    "({} {natural}{kind:?} JOIN {}{on}{using})",
1725                    show_source(ast, left),
1726                    show_source(ast, right)
1727                )
1728            }
1729        }
1730    }
1731
1732    /// The rows of a `VALUES` written back out.
1733    fn show_rows(ast: &Ast, rows: Slice) -> String {
1734        let rows = ast
1735            .rows(rows)
1736            .iter()
1737            .map(|&row| {
1738                let items = ast
1739                    .expr_list(row)
1740                    .iter()
1741                    .map(|&item| show(ast, item))
1742                    .collect::<Vec<_>>()
1743                    .join(", ");
1744                format!("({items})")
1745            })
1746            .collect::<Vec<_>>()
1747            .join(", ");
1748        format!("VALUES {rows}")
1749    }
1750
1751    /// One query written back out.
1752    fn show_query(ast: &Ast, index: QueryRef) -> String {
1753        let query = ast.query(index);
1754        let list = |slice: Slice| {
1755            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
1756        };
1757        let mut out = match query.body {
1758            QueryBody::SetOp { op, quantifier, by_name, left, right } => {
1759                let by_name = if by_name { " BY NAME" } else { "" };
1760                format!(
1761                    "({} {op:?} {quantifier:?}{by_name} {})",
1762                    show_query(ast, left),
1763                    show_query(ast, right)
1764                )
1765            }
1766            QueryBody::Select(index) => {
1767                let select = ast.select(index);
1768                let distinct = match select.distinct {
1769                    Distinct::No => String::new(),
1770                    Distinct::Yes => " DISTINCT".to_string(),
1771                    Distinct::On(on) => format!(" DISTINCT ON ({})", list(on)),
1772                };
1773                let targets = ast
1774                    .target_list(select.targets)
1775                    .iter()
1776                    .map(|target| match target.alias {
1777                        NONE => show(ast, target.expr),
1778                        alias => format!("{} AS {}", show(ast, target.expr), ast.string(alias)),
1779                    })
1780                    .collect::<Vec<_>>()
1781                    .join(", ");
1782                let mut out = format!("SELECT{distinct} {targets}");
1783                if !select.from.is_empty() {
1784                    let from = ast
1785                        .source_list(select.from)
1786                        .iter()
1787                        .map(|&source| show_source(ast, source))
1788                        .collect::<Vec<_>>()
1789                        .join(", ");
1790                    out += &format!(" FROM {from}");
1791                }
1792                if select.filter != NONE {
1793                    out += &format!(" WHERE {}", show(ast, select.filter));
1794                }
1795                if select.group_by_all {
1796                    out += " GROUP BY ALL";
1797                } else if !select.group_by.is_empty() {
1798                    out += &format!(" GROUP BY {}", list(select.group_by));
1799                }
1800                if select.having != NONE {
1801                    out += &format!(" HAVING {}", show(ast, select.having));
1802                }
1803                out
1804            }
1805            QueryBody::Values(rows) => show_rows(ast, rows),
1806        };
1807        if query.order_by_all {
1808            out += " ORDER BY ALL";
1809        } else if !query.order_by.is_empty() {
1810            let items = ast
1811                .order_list(query.order_by)
1812                .iter()
1813                .map(|item| format!("{} {:?} {:?}", show(ast, item.expr), item.order, item.nulls))
1814                .collect::<Vec<_>>()
1815                .join(", ");
1816            out += &format!(" ORDER BY {items}");
1817        }
1818        if query.limit != NONE {
1819            let percent = if query.limit_percent { "%" } else { "" };
1820            out += &format!(" LIMIT {}{percent}", show(ast, query.limit));
1821        }
1822        if query.offset != NONE {
1823            out += &format!(" OFFSET {}", show(ast, query.offset));
1824        }
1825        out
1826    }
1827
1828    /// One statement, transformed and written back out.
1829    fn round(query: &str) -> String {
1830        let ast = parse_ast(query).unwrap_or_else(|error| panic!("{query}: {error}"));
1831        assert_eq!(ast.statements.len(), 1, "{query} is one statement");
1832        let Statement::Query(index) = ast.statements[0] else {
1833            panic!("{query} is not a query");
1834        };
1835        show_query(&ast, index)
1836    }
1837
1838    /// One statement, transformed and written back out as the DDL and DML shape it is.
1839    fn round_statement(query: &str) -> String {
1840        let ast = parse_ast(query).unwrap_or_else(|error| panic!("{query}: {error}"));
1841        assert_eq!(ast.statements.len(), 1, "{query} is one statement");
1842        match ast.statements[0] {
1843            Statement::Query(index) => show_query(&ast, index),
1844            Statement::CreateTable(index) => {
1845                let create = ast.create_table(index);
1846                let mut out = "CREATE".to_string();
1847                if create.or_replace {
1848                    out += " OR REPLACE";
1849                }
1850                if create.temporary {
1851                    out += " TEMPORARY";
1852                }
1853                out += " TABLE";
1854                if create.if_not_exists {
1855                    out += " IF NOT EXISTS";
1856                }
1857                out += &format!(" {}", ast.name_text(create.name));
1858                let columns = ast
1859                    .column_defs(create.columns)
1860                    .iter()
1861                    .map(|def| {
1862                        let ty = match def.ty {
1863                            NONE => String::new(),
1864                            other => format!(" {}", ast.string(other)),
1865                        };
1866                        let null = if def.not_null { " NOT NULL" } else { "" };
1867                        format!("{}{ty}{null}", ast.string(def.name))
1868                    })
1869                    .collect::<Vec<_>>()
1870                    .join(", ");
1871                if !columns.is_empty() || create.query == NONE {
1872                    out += &format!(" ({columns})");
1873                }
1874                if create.query != NONE {
1875                    out += &format!(" AS {}", show_query(&ast, create.query));
1876                }
1877                out
1878            }
1879            Statement::DropTable(index) => {
1880                let drop = ast.drop_table(index);
1881                let mut out = "DROP TABLE".to_string();
1882                if drop.if_exists {
1883                    out += " IF EXISTS";
1884                }
1885                let names = ast
1886                    .name_list(drop.names)
1887                    .iter()
1888                    .map(|&name| ast.name_text(name))
1889                    .collect::<Vec<_>>()
1890                    .join(", ");
1891                out + &format!(" {names}")
1892            }
1893            Statement::Insert(index) => {
1894                let insert = ast.insert(index);
1895                let mut out = format!("INSERT INTO {}", ast.name_text(insert.name));
1896                if !insert.columns.is_empty() {
1897                    let columns = ast.name(insert.columns).collect::<Vec<_>>().join(", ");
1898                    out += &format!(" ({columns})");
1899                }
1900                out + &format!(" {}", show_query(&ast, insert.source))
1901            }
1902        }
1903    }
1904
1905    #[test]
1906    fn the_query_m0_has_to_run_transforms() {
1907        assert_eq!(round("SELECT * FROM t WHERE x > 5"), "SELECT * FROM t WHERE (x Gt 5)");
1908    }
1909
1910    #[test]
1911    fn a_create_table_keeps_its_types_as_text() {
1912        assert_eq!(
1913            round_statement("CREATE TABLE t (a INTEGER, b VARCHAR NOT NULL)"),
1914            "CREATE TABLE t (a INTEGER, b VARCHAR NOT NULL)"
1915        );
1916        // The type is the text between the identifier and whatever follows it, parentheses and
1917        // all, because resolving `DECIMAL(18, 3)` into a width and a scale is the binder's job and
1918        // doing it here would mean two places that know the type table.
1919        assert_eq!(
1920            round_statement("CREATE TABLE t (a DECIMAL(18, 3), b STRUCT(x INT))"),
1921            "CREATE TABLE t (a DECIMAL(18, 3), b STRUCT(x INT))"
1922        );
1923    }
1924
1925    #[test]
1926    fn the_three_modifiers_on_a_create_table_survive() {
1927        assert_eq!(
1928            round_statement("CREATE OR REPLACE TEMPORARY TABLE IF NOT EXISTS s.t (a INT)"),
1929            "CREATE OR REPLACE TEMPORARY TABLE IF NOT EXISTS s.t (a INT)"
1930        );
1931    }
1932
1933    #[test]
1934    fn a_create_table_as_carries_the_query_and_not_the_types() {
1935        assert_eq!(
1936            round_statement("CREATE TABLE t AS SELECT a FROM u"),
1937            "CREATE TABLE t AS SELECT a FROM u"
1938        );
1939        // The names are the syntax's to say and the types are the query's, so the column
1940        // definitions here have names and no types.
1941        assert_eq!(
1942            round_statement("CREATE TABLE t (x, y) AS SELECT a, b FROM u"),
1943            "CREATE TABLE t (x, y) AS SELECT a, b FROM u"
1944        );
1945    }
1946
1947    #[test]
1948    fn a_drop_table_is_a_list_of_qualified_names() {
1949        assert_eq!(round_statement("DROP TABLE t"), "DROP TABLE t");
1950        assert_eq!(round_statement("DROP TABLE IF EXISTS a, b.c"), "DROP TABLE IF EXISTS a, b.c");
1951    }
1952
1953    #[test]
1954    fn dropping_something_that_is_not_a_table_is_refused() {
1955        // `TableOrView` covers `VIEW` and `MATERIALIZED VIEW` as well, and a view dropped as if it
1956        // were a table is a wrong answer rather than a missing feature.
1957        let error = parse_ast("DROP VIEW v").unwrap_err().to_string();
1958        assert!(error.starts_with("Not implemented Error"), "{error}");
1959    }
1960
1961    #[test]
1962    fn both_spellings_of_insert_arrive_at_a_query() {
1963        assert_eq!(
1964            round_statement("INSERT INTO t VALUES (1, 'a'), (2, 'b')"),
1965            "INSERT INTO t VALUES (1, 'a'), (2, 'b')"
1966        );
1967        assert_eq!(
1968            round_statement("INSERT INTO t (a, b) SELECT x, y FROM u"),
1969            "INSERT INTO t (a, b) SELECT x, y FROM u"
1970        );
1971    }
1972
1973    #[test]
1974    fn an_insert_clause_that_changes_the_answer_is_refused() {
1975        for query in [
1976            "INSERT INTO t VALUES (1) RETURNING *",
1977            "INSERT OR REPLACE INTO t VALUES (1)",
1978            "INSERT INTO t BY NAME SELECT 1 AS a",
1979            "INSERT INTO t VALUES (1) ON CONFLICT DO NOTHING",
1980            "INSERT INTO t DEFAULT VALUES",
1981        ] {
1982            let error = parse_ast(query).unwrap_err().to_string();
1983            assert!(error.starts_with("Not implemented Error"), "{query} gave {error}");
1984        }
1985    }
1986
1987    #[test]
1988    fn a_column_constraint_that_is_not_not_null_is_refused() {
1989        // Nothing enforces a constraint yet. Accepting one and not enforcing it is the wrong
1990        // answer, so `NOT NULL` is kept because the column already has a nullability and the rest
1991        // are refused until there is somewhere to put them.
1992        for query in [
1993            "CREATE TABLE t (a INT PRIMARY KEY)",
1994            "CREATE TABLE t (a INT UNIQUE)",
1995            "CREATE TABLE t (a INT CHECK (a > 0))",
1996            "CREATE TABLE t (a INT DEFAULT 1)",
1997            "CREATE TABLE t (a INT REFERENCES u (b))",
1998            "CREATE TABLE t (a INT, PRIMARY KEY (a))",
1999        ] {
2000            let error = parse_ast(query).unwrap_err().to_string();
2001            assert!(error.starts_with("Not implemented Error"), "{query} gave {error}");
2002        }
2003    }
2004
2005    #[test]
2006    fn values_is_a_query_on_its_own_and_in_a_from() {
2007        assert_eq!(round("VALUES (1), (2)"), "VALUES (1), (2)");
2008        // Parenthesised it is a subquery whose body is the values, and bare it is a `ValuesRef`.
2009        // Two rules and one meaning, which is the grammar's doing and not something to flatten
2010        // here, because the parenthesised form can carry an order by and the bare one cannot.
2011        assert_eq!(
2012            round("SELECT * FROM (VALUES (1, 2), (3, 4)) t(a, b)"),
2013            "SELECT * FROM (VALUES (1, 2), (3, 4)) AS t"
2014        );
2015        assert_eq!(
2016            round("SELECT * FROM VALUES (1, 2), (3, 4) AS t(a, b)"),
2017            "SELECT * FROM VALUES (1, 2), (3, 4) AS t"
2018        );
2019        // Rows of different widths parse. Saying so wants the column count, which for an insert is
2020        // the table's, so the check belongs to the binder and not here.
2021        assert_eq!(round("VALUES (1), (2, 3)"), "VALUES (1), (2, 3)");
2022    }
2023
2024    #[test]
2025    fn every_statement_in_the_corpus_gets_a_defined_answer() {
2026        // The point of the test is the word defined. Forty of these are statement kinds and
2027        // clauses this milestone does not cover, and the requirement is not that they work, it is
2028        // that they fail by saying so. A panic, a silently dropped clause or an internal error
2029        // would each be a different bug and all three would be invisible without this.
2030        let mut done = 0;
2031        for query in CORPUS {
2032            match parse_ast(query) {
2033                Ok(ast) => {
2034                    assert_eq!(ast.statements.len(), 1, "{query}");
2035                    done += 1;
2036                }
2037                Err(error) => {
2038                    let message = error.to_string();
2039                    assert!(
2040                        message.starts_with("Not implemented Error"),
2041                        "{query} failed with {message}, which is not a not-implemented error"
2042                    );
2043                }
2044            }
2045        }
2046        // Not an assertion about the right number. It is a ratchet: this only moves up, and the
2047        // day it moves down somebody has taken a construct out without meaning to.
2048        assert!(done >= 22, "only {done} of the corpus transforms, which is fewer than it was");
2049    }
2050
2051    #[test]
2052    fn the_ast_is_far_smaller_than_the_parse_tree() {
2053        let query = CORPUS[4];
2054        let tree = parse(query).unwrap();
2055        let ast = parse_ast(query).unwrap();
2056        // The twenty precedence levels are the difference. Every one of them is a node in the
2057        // parse tree for every expression at every depth, and none of them survives into the AST.
2058        assert!(
2059            ast.node_count() * 20 < tree.arena_len(),
2060            "{} ast nodes against {} parse nodes",
2061            ast.node_count(),
2062            tree.arena_len()
2063        );
2064    }
2065
2066    #[test]
2067    fn precedence_comes_out_of_the_chain_and_into_the_tree() {
2068        assert_eq!(round("SELECT 1 + 2 * 3"), "SELECT (1 Add (2 Multiply 3))");
2069        assert_eq!(round("SELECT (1 + 2) * 3"), "SELECT ((1 Add 2) Multiply 3)");
2070        assert_eq!(round("SELECT 1 + 2 + 3"), "SELECT ((1 Add 2) Add 3)");
2071        assert_eq!(round("SELECT 1 - 2 - 3"), "SELECT ((1 Subtract 2) Subtract 3)");
2072        assert_eq!(
2073            round("SELECT a OR b AND c"),
2074            "SELECT (a Or (b And c))",
2075            "and binds tighter than or"
2076        );
2077    }
2078
2079    #[test]
2080    fn a_double_negation_is_two_nodes_and_not_none() {
2081        // Folding it would be an optimizer decision and this is not the optimizer. It also would
2082        // not be safe in general: `NOT NOT x` on a null is still null and on a non boolean it is
2083        // still an error, and both of those have to survive to the binder to be reported.
2084        assert_eq!(round("SELECT NOT NOT a"), "SELECT (Not (Not a))");
2085    }
2086
2087    #[test]
2088    fn a_parenthesised_single_expression_is_not_a_row() {
2089        assert_eq!(round("SELECT (a)"), "SELECT a");
2090        assert_eq!(round("SELECT (a, b)"), "SELECT ROW(a, b)");
2091    }
2092
2093    #[test]
2094    fn the_three_ways_to_write_an_alias_all_arrive() {
2095        assert_eq!(round("SELECT a AS b"), "SELECT a AS b");
2096        assert_eq!(round("SELECT a b"), "SELECT a AS b");
2097        assert_eq!(round("SELECT b: a"), "SELECT a AS b");
2098        assert_eq!(round("SELECT a"), "SELECT a", "and no alias when none was written");
2099    }
2100
2101    #[test]
2102    fn a_from_with_no_select_selects_everything() {
2103        // DuckDB's own shorthand. Inventing the star here rather than in the binder means the
2104        // binder never has to know that the clause it is looking at was the one that was missing.
2105        assert_eq!(round("FROM t"), "SELECT * FROM t");
2106        assert_eq!(round("FROM t SELECT a"), "SELECT a FROM t");
2107    }
2108
2109    #[test]
2110    fn joins_nest_to_the_left() {
2111        assert_eq!(
2112            round("SELECT * FROM a JOIN b ON a.i = b.i LEFT JOIN c USING (k)"),
2113            "SELECT * FROM ((a Inner JOIN b ON (a.i Eq b.i)) Left JOIN c USING (k))"
2114        );
2115        assert_eq!(
2116            round("SELECT * FROM a NATURAL JOIN b"),
2117            "SELECT * FROM (a NATURAL Inner JOIN b)"
2118        );
2119        assert_eq!(round("SELECT * FROM a CROSS JOIN b"), "SELECT * FROM (a Cross JOIN b)");
2120        assert_eq!(
2121            round("SELECT * FROM a POSITIONAL JOIN b"),
2122            "SELECT * FROM (a Positional JOIN b)"
2123        );
2124        assert_eq!(round("SELECT * FROM a, b"), "SELECT * FROM a, b", "a comma is not a join node");
2125    }
2126
2127    #[test]
2128    fn a_qualified_name_keeps_its_parts_however_it_was_spelled() {
2129        // Five grammar rules can produce a column reference and they disagree about which
2130        // component is a schema and which is a table. None of that is decidable without the
2131        // catalog, so the AST holds the parts and the binder decides.
2132        assert_eq!(round("SELECT a"), "SELECT a");
2133        assert_eq!(round("SELECT t.a"), "SELECT t.a");
2134        assert_eq!(round("SELECT s.t.a"), "SELECT s.t.a");
2135        assert_eq!(round("SELECT c.s.t.a"), "SELECT c.s.t.a");
2136        assert_eq!(round("SELECT * FROM s.t"), "SELECT * FROM s.t");
2137    }
2138
2139    #[test]
2140    fn a_star_can_be_qualified() {
2141        assert_eq!(round("SELECT *"), "SELECT *");
2142        assert_eq!(round("SELECT t.*"), "SELECT t.*");
2143        assert_eq!(round("SELECT s.t.*"), "SELECT s.t.*");
2144    }
2145
2146    #[test]
2147    fn a_quoted_identifier_keeps_its_case_and_loses_its_quotes() {
2148        // DuckDB does not fold identifier case at any point, quoted or not, which the tokenizer
2149        // work established by reading the source. So the only thing to do here is take the quotes
2150        // off and resolve the doubled ones.
2151        let ast = parse_ast("SELECT \"Mixed Case\", \"a\"\"b\"").unwrap();
2152        assert_eq!(ast.strings[0], "Mixed Case");
2153        assert_eq!(ast.strings[1], "a\"b");
2154    }
2155
2156    #[test]
2157    fn a_string_literal_is_decoded_and_adjacent_ones_are_joined() {
2158        assert_eq!(round("SELECT 'it''s'"), "SELECT 'it's'");
2159        assert_eq!(round("SELECT 'a'\n'b'"), "SELECT 'ab'", "the standard's adjacency rule");
2160    }
2161
2162    #[test]
2163    fn the_null_and_boolean_tests_are_postfix_unary_operators() {
2164        assert_eq!(round("SELECT x IS NULL"), "SELECT (IsNull x)");
2165        assert_eq!(round("SELECT x IS NOT NULL"), "SELECT (IsNotNull x)");
2166        assert_eq!(round("SELECT x ISNULL"), "SELECT (IsNull x)");
2167        assert_eq!(round("SELECT x NOTNULL"), "SELECT (IsNotNull x)");
2168        assert_eq!(round("SELECT x IS TRUE"), "SELECT (IsTrue x)");
2169        assert_eq!(round("SELECT x IS NOT FALSE"), "SELECT (IsNotFalse x)");
2170        assert_eq!(round("SELECT x IS DISTINCT FROM y"), "SELECT (x IsDistinctFrom y)");
2171        assert_eq!(round("SELECT x IS NOT DISTINCT FROM y"), "SELECT (x IsNotDistinctFrom y)");
2172    }
2173
2174    #[test]
2175    fn the_like_family_folds_its_negation_into_the_operator() {
2176        assert_eq!(round("SELECT x LIKE 'a'"), "SELECT (x Like 'a')");
2177        assert_eq!(round("SELECT x NOT LIKE 'a'"), "SELECT (x NotLike 'a')");
2178        assert_eq!(round("SELECT x ILIKE 'a'"), "SELECT (x ILike 'a')");
2179        assert_eq!(round("SELECT x ~~ 'a'"), "SELECT (x Like 'a')", "the operator spelling");
2180        assert_eq!(round("SELECT x !~~ 'a'"), "SELECT (x NotLike 'a')");
2181        assert_eq!(round("SELECT x SIMILAR TO 'a'"), "SELECT (x SimilarTo 'a')");
2182        // Glob has no negated operator to fold into, so the negation stays where it was written.
2183        assert_eq!(round("SELECT x NOT GLOB 'a'"), "SELECT (Not (x Glob 'a'))");
2184    }
2185
2186    #[test]
2187    fn between_and_in_carry_their_negation_as_a_flag() {
2188        assert_eq!(round("SELECT x BETWEEN 1 AND 2"), "SELECT (x BETWEEN 1 AND 2)");
2189        assert_eq!(round("SELECT x NOT BETWEEN 1 AND 2"), "SELECT (NOT x BETWEEN 1 AND 2)");
2190        assert_eq!(round("SELECT x IN (1, 2)"), "SELECT (x IN [1, 2])");
2191        assert_eq!(round("SELECT x NOT IN (1, 2)"), "SELECT (NOT x IN [1, 2])");
2192    }
2193
2194    #[test]
2195    fn both_spellings_of_a_cast_are_the_same_node() {
2196        assert_eq!(round("SELECT CAST(x AS BIGINT)"), "SELECT CAST(x AS BIGINT)");
2197        assert_eq!(round("SELECT x::BIGINT"), "SELECT CAST(x AS BIGINT)");
2198        assert_eq!(round("SELECT TRY_CAST(x AS BIGINT)"), "SELECT TRY_CAST(x AS BIGINT)");
2199        assert_eq!(
2200            round("SELECT x::DECIMAL(18, 3)"),
2201            "SELECT CAST(x AS DECIMAL(18, 3))",
2202            "the type is kept as text because parsing it is the type system's job"
2203        );
2204    }
2205
2206    #[test]
2207    fn a_case_keeps_its_arms_in_order() {
2208        assert_eq!(
2209            round("SELECT CASE WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"),
2210            "SELECT CASE - WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"
2211        );
2212        assert_eq!(
2213            round("SELECT CASE x WHEN 1 THEN 'a' END"),
2214            "SELECT CASE x WHEN 1 THEN 'a' ELSE - END",
2215            "a simple case keeps the operand and a missing else is not an implicit null yet"
2216        );
2217    }
2218
2219    #[test]
2220    fn a_field_access_and_a_method_call_are_ordinary_function_calls() {
2221        // Which is what DuckDB makes of them too. Giving each its own AST node would mean the
2222        // binder needs a rule for something the function resolver already handles.
2223        assert_eq!(round("SELECT (f(x)).y"), "SELECT struct_extract(f(x), 'y')");
2224        assert_eq!(round("SELECT a[1]"), "SELECT array_extract(a, 1)");
2225    }
2226
2227    #[test]
2228    fn an_aggregate_keeps_its_distinct() {
2229        assert_eq!(round("SELECT count(*)"), "SELECT count(*)");
2230        assert_eq!(round("SELECT count(DISTINCT x)"), "SELECT count(DISTINCT x)");
2231        assert_eq!(round("SELECT count(ALL x)"), "SELECT count(x)");
2232        assert_eq!(round("SELECT main.count(x)"), "SELECT main.count(x)");
2233    }
2234
2235    #[test]
2236    fn the_modifiers_hang_off_the_query_and_not_off_the_select() {
2237        // `a UNION b ORDER BY x` sorts the union. Putting the order by on the select would have
2238        // made that unrepresentable, which is why the grammar puts it outside the chain and why
2239        // the AST follows.
2240        assert_eq!(
2241            round("SELECT 1 UNION ALL SELECT 2 ORDER BY 1"),
2242            "(SELECT 1 Union All SELECT 2) ORDER BY 1 Unstated Unstated"
2243        );
2244        assert_eq!(
2245            round("SELECT a FROM t UNION SELECT b FROM u EXCEPT SELECT c FROM v"),
2246            "((SELECT a FROM t Union Unstated SELECT b FROM u) Except Unstated SELECT c FROM v)",
2247            "set operators are left associative"
2248        );
2249        assert_eq!(
2250            round("SELECT 1 UNION SELECT 2 INTERSECT SELECT 3"),
2251            "(SELECT 1 Union Unstated (SELECT 2 Intersect Unstated SELECT 3))",
2252            "and intersect binds tighter than the other two"
2253        );
2254    }
2255
2256    #[test]
2257    fn the_sort_and_limit_clauses_keep_what_was_written() {
2258        assert_eq!(
2259            round("SELECT a FROM t ORDER BY a"),
2260            "SELECT a FROM t ORDER BY a Unstated Unstated"
2261        );
2262        assert_eq!(
2263            round("SELECT a FROM t ORDER BY a DESC NULLS LAST"),
2264            "SELECT a FROM t ORDER BY a Descending Last"
2265        );
2266        assert_eq!(round("SELECT a FROM t ORDER BY ALL"), "SELECT a FROM t ORDER BY ALL");
2267        assert_eq!(round("SELECT a FROM t GROUP BY ALL"), "SELECT a FROM t GROUP BY ALL");
2268        assert_eq!(round("SELECT a FROM t LIMIT 10 OFFSET 5"), "SELECT a FROM t LIMIT 10 OFFSET 5");
2269        assert_eq!(round("SELECT a FROM t OFFSET 5 LIMIT 10"), "SELECT a FROM t LIMIT 10 OFFSET 5");
2270        assert_eq!(round("SELECT a FROM t LIMIT 10%"), "SELECT a FROM t LIMIT 10%");
2271        assert_eq!(round("SELECT a FROM t LIMIT ALL"), "SELECT a FROM t", "which is no limit");
2272    }
2273
2274    #[test]
2275    fn a_subquery_appears_in_both_places_it_can() {
2276        assert_eq!(
2277            round("SELECT * FROM (SELECT x FROM t) AS s"),
2278            "SELECT * FROM (SELECT x FROM t) AS s"
2279        );
2280        assert_eq!(round("SELECT (SELECT 1)"), "SELECT (SELECT 1)");
2281    }
2282
2283    #[test]
2284    fn distinct_on_keeps_its_expressions() {
2285        assert_eq!(round("SELECT DISTINCT a"), "SELECT DISTINCT a");
2286        assert_eq!(round("SELECT ALL a"), "SELECT a", "which is the default written out");
2287        assert_eq!(round("SELECT DISTINCT ON (a, b) a"), "SELECT DISTINCT ON (a, b) a");
2288    }
2289
2290    #[test]
2291    fn an_operator_the_dialect_does_not_name_is_kept_by_name() {
2292        // The grammar text says `OperatorLiteral <- Identifier`, which reads as though any bare
2293        // word could be written infix. It cannot. That rule is one of the 24 the matcher overrides
2294        // and it is overridden to the bare operator matcher, so what it takes is a run of operator
2295        // characters. Believing the body here would have produced a transformer that accepted
2296        // `a foo b`, which DuckDB rejects.
2297        assert_eq!(round("SELECT a <=> b"), "SELECT (a <=> b)");
2298        assert!(parse_ast("SELECT a foo b").is_err(), "a bare word is not an operator");
2299    }
2300
2301    #[test]
2302    fn a_script_is_a_list_of_statements() {
2303        let ast = parse_ast("SELECT 1; SELECT 2;").unwrap();
2304        assert_eq!(ast.statements.len(), 2);
2305        // A trailing semicolon makes an empty top level statement in the parse tree, because the
2306        // grammar's `Statement? (';'+ / EndOfInput)` is happy with nothing on both sides. It is
2307        // dropped here rather than pretended away in the matcher.
2308        let Statement::Query(second) = ast.statements[1] else {
2309            panic!("the second statement is a query");
2310        };
2311        assert_eq!(show_query(&ast, second), "SELECT 2");
2312    }
2313
2314    #[test]
2315    fn an_unsupported_construct_names_itself_and_what_was_written() {
2316        let error = parse_ast("ALTER TABLE t ADD COLUMN a INTEGER").unwrap_err().to_string();
2317        assert!(error.starts_with("Not implemented Error"), "{error}");
2318        assert!(error.contains("ALTER TABLE t ADD COLUMN a INTEGER"), "{error}");
2319        assert!(error.contains("AlterStatement"), "{error}");
2320    }
2321
2322    #[test]
2323    fn a_long_construct_is_cut_short_in_the_message() {
2324        let query = format!("ALTER TABLE t ADD COLUMN {} INTEGER", "a".repeat(80));
2325        let error = parse_ast(&query).unwrap_err().to_string();
2326        assert!(error.contains("..."), "{error}");
2327        assert!(error.len() < 200, "{error}");
2328    }
2329
2330    #[test]
2331    fn the_transformer_never_panics_on_anything_the_matcher_accepts() {
2332        // The matcher accepts a good deal that means nothing, because the grammar does. Every one
2333        // of these parses and none of them is a statement this milestone covers, and the contract
2334        // is that the answer is an error either way.
2335        for query in [
2336            "SELECT",
2337            "FROM t SELECT",
2338            "SELECT * FROM t WHERE",
2339            "SELECT ()",
2340            "SELECT a FROM t GROUP BY ()",
2341        ] {
2342            let answer = parse_ast(query);
2343            if let Err(error) = answer {
2344                let message = error.to_string();
2345                assert!(
2346                    message.starts_with("Not implemented Error")
2347                        || message.starts_with("Parser Error"),
2348                    "{query} failed with {message}"
2349                );
2350            }
2351        }
2352    }
2353
2354    #[test]
2355    fn a_function_call_in_a_from_clause_is_a_source_and_not_an_expression() {
2356        assert_eq!(round("SELECT * FROM range(3)"), "SELECT * FROM range(3)");
2357        assert_eq!(round("SELECT * FROM range(1, 10, 2)"), "SELECT * FROM range(1, 10, 2)");
2358        assert_eq!(round("SELECT * FROM main.range(3)"), "SELECT * FROM main.range(3)");
2359        assert_eq!(round("SELECT * FROM range(3) AS t"), "SELECT * FROM range(3) AS t");
2360        // The grammar allows a call with no arguments here and the transformer keeps it, because
2361        // whether a particular function takes none is the binder's question and not this one's.
2362        assert_eq!(round("SELECT * FROM some_function()"), "SELECT * FROM some_function()");
2363    }
2364
2365    #[test]
2366    fn the_forms_of_a_table_function_this_does_not_cover_are_turned_away_by_name() {
2367        for query in [
2368            "SELECT * FROM range(3) WITH ORDINALITY",
2369            "SELECT * FROM LATERAL range(3)",
2370            "SELECT * FROM t: range(3)",
2371        ] {
2372            let error = parse_ast(query).unwrap_err().to_string();
2373            assert!(error.contains("grammar rule"), "{query} failed with {error}");
2374        }
2375    }
2376
2377    #[test]
2378    fn interning_means_a_name_written_twice_is_stored_once() {
2379        let ast = parse_ast("SELECT a, a, a FROM t WHERE a = a").unwrap();
2380        assert_eq!(ast.strings.iter().filter(|text| *text == "a").count(), 1);
2381    }
2382}