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.
1611///
1612/// Single quotes are stripped too, and the only way one gets here is the file name in `FROM
1613/// 'hits.parquet'`, because the matcher takes a string for a name in that position and in `COPY t TO
1614/// '...'` and nowhere else. Leaving them on would make that name different from the one `FROM
1615/// "hits.parquet"` writes, and DuckDB reads both of those as the same file.
1616fn unquote(text: &str) -> String {
1617    if let Some(body) = text.strip_prefix('"').and_then(|rest| rest.strip_suffix('"')) {
1618        return body.replace("\"\"", "\"");
1619    }
1620    match text.strip_prefix('\'').and_then(|rest| rest.strip_suffix('\'')) {
1621        Some(body) => body.replace("''", "'"),
1622        None => text.to_string(),
1623    }
1624}
1625
1626#[cfg(test)]
1627mod tests {
1628    use super::*;
1629    use crate::corpus::CORPUS;
1630    use crate::matcher::parse;
1631
1632    /// The AST written back out as text, which is what the assertions below read.
1633    ///
1634    /// Not a SQL printer and not trying to be. It is deliberately not valid SQL: operators are
1635    /// spelled with the name of the variant and every binary node is parenthesised, so that a test
1636    /// asserting on this text is asserting on the shape of the tree and not on a formatting choice.
1637    /// `a - b - c` and `a - (b - c)` have to look different here or the test that tells them apart
1638    /// is not a test.
1639    fn show(ast: &Ast, expr: ExprRef) -> String {
1640        if expr == NONE {
1641            return "-".to_string();
1642        }
1643        let list = |slice: Slice| {
1644            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
1645        };
1646        match ast.expr(expr) {
1647            Expr::Star { qualifier } if qualifier.is_empty() => "*".to_string(),
1648            Expr::Star { qualifier } => format!("{}.*", ast.name_text(qualifier)),
1649            Expr::Column { name } => ast.name_text(name),
1650            Expr::Literal { kind, text } => match kind {
1651                LiteralKind::Number => ast.string(text).to_string(),
1652                LiteralKind::String => format!("'{}'", ast.string(text)),
1653                other => format!("{other:?}").to_uppercase(),
1654            },
1655            Expr::Unary { op, operand } => format!("({op:?} {})", show(ast, operand)),
1656            Expr::Binary { op, left, right } => {
1657                let op = match op {
1658                    BinaryOp::Named(name) => ast.string(name).to_string(),
1659                    other => format!("{other:?}"),
1660                };
1661                format!("({} {op} {})", show(ast, left), show(ast, right))
1662            }
1663            Expr::Function { name, args, distinct } => {
1664                let distinct = if distinct { "DISTINCT " } else { "" };
1665                format!("{}({distinct}{})", ast.name_text(name), list(args))
1666            }
1667            Expr::Cast { operand, ty, try_cast } => {
1668                let word = if try_cast { "TRY_CAST" } else { "CAST" };
1669                format!("{word}({} AS {})", show(ast, operand), ast.string(ty))
1670            }
1671            Expr::Case { operand, arms, otherwise } => {
1672                let arms = ast
1673                    .arm_list(arms)
1674                    .iter()
1675                    .map(|arm| format!("WHEN {} THEN {}", show(ast, arm.when), show(ast, arm.then)))
1676                    .collect::<Vec<_>>()
1677                    .join(" ");
1678                format!("CASE {} {arms} ELSE {} END", show(ast, operand), show(ast, otherwise))
1679            }
1680            Expr::Between { operand, low, high, negated } => {
1681                let not = if negated { "NOT " } else { "" };
1682                format!(
1683                    "({not}{} BETWEEN {} AND {})",
1684                    show(ast, operand),
1685                    show(ast, low),
1686                    show(ast, high)
1687                )
1688            }
1689            Expr::In { operand, list: items, negated } => {
1690                let not = if negated { "NOT " } else { "" };
1691                format!("({not}{} IN [{}])", show(ast, operand), list(items))
1692            }
1693            Expr::Row { items } => format!("ROW({})", list(items)),
1694            Expr::Subquery { query } => format!("({})", show_query(ast, query)),
1695        }
1696    }
1697
1698    /// One from item written back out.
1699    fn show_source(ast: &Ast, source: SourceRef) -> String {
1700        let alias = |alias: StrRef| match alias {
1701            NONE => String::new(),
1702            other => format!(" AS {}", ast.string(other)),
1703        };
1704        match ast.source(source) {
1705            Source::Table { name, alias: name_alias, .. } => {
1706                format!("{}{}", ast.name_text(name), alias(name_alias))
1707            }
1708            Source::Function { name, args, alias: call_alias, .. } => {
1709                let args = ast
1710                    .expr_list(args)
1711                    .iter()
1712                    .map(|&item| show(ast, item))
1713                    .collect::<Vec<_>>()
1714                    .join(", ");
1715                format!("{}({args}){}", ast.name_text(name), alias(call_alias))
1716            }
1717            Source::Subquery { query, alias: query_alias, .. } => {
1718                format!("({}){}", show_query(ast, query), alias(query_alias))
1719            }
1720            Source::Values { rows, alias: values_alias, .. } => {
1721                format!("{}{}", show_rows(ast, rows), alias(values_alias))
1722            }
1723            Source::Join { left, right, kind, natural, on, using } => {
1724                let natural = if natural { "NATURAL " } else { "" };
1725                let on = if on == NONE { String::new() } else { format!(" ON {}", show(ast, on)) };
1726                let using = if using.is_empty() {
1727                    String::new()
1728                } else {
1729                    format!(" USING ({})", ast.name_text(using))
1730                };
1731                format!(
1732                    "({} {natural}{kind:?} JOIN {}{on}{using})",
1733                    show_source(ast, left),
1734                    show_source(ast, right)
1735                )
1736            }
1737        }
1738    }
1739
1740    /// The rows of a `VALUES` written back out.
1741    fn show_rows(ast: &Ast, rows: Slice) -> String {
1742        let rows = ast
1743            .rows(rows)
1744            .iter()
1745            .map(|&row| {
1746                let items = ast
1747                    .expr_list(row)
1748                    .iter()
1749                    .map(|&item| show(ast, item))
1750                    .collect::<Vec<_>>()
1751                    .join(", ");
1752                format!("({items})")
1753            })
1754            .collect::<Vec<_>>()
1755            .join(", ");
1756        format!("VALUES {rows}")
1757    }
1758
1759    /// One query written back out.
1760    fn show_query(ast: &Ast, index: QueryRef) -> String {
1761        let query = ast.query(index);
1762        let list = |slice: Slice| {
1763            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
1764        };
1765        let mut out = match query.body {
1766            QueryBody::SetOp { op, quantifier, by_name, left, right } => {
1767                let by_name = if by_name { " BY NAME" } else { "" };
1768                format!(
1769                    "({} {op:?} {quantifier:?}{by_name} {})",
1770                    show_query(ast, left),
1771                    show_query(ast, right)
1772                )
1773            }
1774            QueryBody::Select(index) => {
1775                let select = ast.select(index);
1776                let distinct = match select.distinct {
1777                    Distinct::No => String::new(),
1778                    Distinct::Yes => " DISTINCT".to_string(),
1779                    Distinct::On(on) => format!(" DISTINCT ON ({})", list(on)),
1780                };
1781                let targets = ast
1782                    .target_list(select.targets)
1783                    .iter()
1784                    .map(|target| match target.alias {
1785                        NONE => show(ast, target.expr),
1786                        alias => format!("{} AS {}", show(ast, target.expr), ast.string(alias)),
1787                    })
1788                    .collect::<Vec<_>>()
1789                    .join(", ");
1790                let mut out = format!("SELECT{distinct} {targets}");
1791                if !select.from.is_empty() {
1792                    let from = ast
1793                        .source_list(select.from)
1794                        .iter()
1795                        .map(|&source| show_source(ast, source))
1796                        .collect::<Vec<_>>()
1797                        .join(", ");
1798                    out += &format!(" FROM {from}");
1799                }
1800                if select.filter != NONE {
1801                    out += &format!(" WHERE {}", show(ast, select.filter));
1802                }
1803                if select.group_by_all {
1804                    out += " GROUP BY ALL";
1805                } else if !select.group_by.is_empty() {
1806                    out += &format!(" GROUP BY {}", list(select.group_by));
1807                }
1808                if select.having != NONE {
1809                    out += &format!(" HAVING {}", show(ast, select.having));
1810                }
1811                out
1812            }
1813            QueryBody::Values(rows) => show_rows(ast, rows),
1814        };
1815        if query.order_by_all {
1816            out += " ORDER BY ALL";
1817        } else if !query.order_by.is_empty() {
1818            let items = ast
1819                .order_list(query.order_by)
1820                .iter()
1821                .map(|item| format!("{} {:?} {:?}", show(ast, item.expr), item.order, item.nulls))
1822                .collect::<Vec<_>>()
1823                .join(", ");
1824            out += &format!(" ORDER BY {items}");
1825        }
1826        if query.limit != NONE {
1827            let percent = if query.limit_percent { "%" } else { "" };
1828            out += &format!(" LIMIT {}{percent}", show(ast, query.limit));
1829        }
1830        if query.offset != NONE {
1831            out += &format!(" OFFSET {}", show(ast, query.offset));
1832        }
1833        out
1834    }
1835
1836    /// One statement, transformed and written back out.
1837    fn round(query: &str) -> String {
1838        let ast = parse_ast(query).unwrap_or_else(|error| panic!("{query}: {error}"));
1839        assert_eq!(ast.statements.len(), 1, "{query} is one statement");
1840        let Statement::Query(index) = ast.statements[0] else {
1841            panic!("{query} is not a query");
1842        };
1843        show_query(&ast, index)
1844    }
1845
1846    /// One statement, transformed and written back out as the DDL and DML shape it is.
1847    fn round_statement(query: &str) -> String {
1848        let ast = parse_ast(query).unwrap_or_else(|error| panic!("{query}: {error}"));
1849        assert_eq!(ast.statements.len(), 1, "{query} is one statement");
1850        match ast.statements[0] {
1851            Statement::Query(index) => show_query(&ast, index),
1852            Statement::CreateTable(index) => {
1853                let create = ast.create_table(index);
1854                let mut out = "CREATE".to_string();
1855                if create.or_replace {
1856                    out += " OR REPLACE";
1857                }
1858                if create.temporary {
1859                    out += " TEMPORARY";
1860                }
1861                out += " TABLE";
1862                if create.if_not_exists {
1863                    out += " IF NOT EXISTS";
1864                }
1865                out += &format!(" {}", ast.name_text(create.name));
1866                let columns = ast
1867                    .column_defs(create.columns)
1868                    .iter()
1869                    .map(|def| {
1870                        let ty = match def.ty {
1871                            NONE => String::new(),
1872                            other => format!(" {}", ast.string(other)),
1873                        };
1874                        let null = if def.not_null { " NOT NULL" } else { "" };
1875                        format!("{}{ty}{null}", ast.string(def.name))
1876                    })
1877                    .collect::<Vec<_>>()
1878                    .join(", ");
1879                if !columns.is_empty() || create.query == NONE {
1880                    out += &format!(" ({columns})");
1881                }
1882                if create.query != NONE {
1883                    out += &format!(" AS {}", show_query(&ast, create.query));
1884                }
1885                out
1886            }
1887            Statement::DropTable(index) => {
1888                let drop = ast.drop_table(index);
1889                let mut out = "DROP TABLE".to_string();
1890                if drop.if_exists {
1891                    out += " IF EXISTS";
1892                }
1893                let names = ast
1894                    .name_list(drop.names)
1895                    .iter()
1896                    .map(|&name| ast.name_text(name))
1897                    .collect::<Vec<_>>()
1898                    .join(", ");
1899                out + &format!(" {names}")
1900            }
1901            Statement::Insert(index) => {
1902                let insert = ast.insert(index);
1903                let mut out = format!("INSERT INTO {}", ast.name_text(insert.name));
1904                if !insert.columns.is_empty() {
1905                    let columns = ast.name(insert.columns).collect::<Vec<_>>().join(", ");
1906                    out += &format!(" ({columns})");
1907                }
1908                out + &format!(" {}", show_query(&ast, insert.source))
1909            }
1910        }
1911    }
1912
1913    #[test]
1914    fn the_query_m0_has_to_run_transforms() {
1915        assert_eq!(round("SELECT * FROM t WHERE x > 5"), "SELECT * FROM t WHERE (x Gt 5)");
1916    }
1917
1918    #[test]
1919    fn a_create_table_keeps_its_types_as_text() {
1920        assert_eq!(
1921            round_statement("CREATE TABLE t (a INTEGER, b VARCHAR NOT NULL)"),
1922            "CREATE TABLE t (a INTEGER, b VARCHAR NOT NULL)"
1923        );
1924        // The type is the text between the identifier and whatever follows it, parentheses and
1925        // all, because resolving `DECIMAL(18, 3)` into a width and a scale is the binder's job and
1926        // doing it here would mean two places that know the type table.
1927        assert_eq!(
1928            round_statement("CREATE TABLE t (a DECIMAL(18, 3), b STRUCT(x INT))"),
1929            "CREATE TABLE t (a DECIMAL(18, 3), b STRUCT(x INT))"
1930        );
1931    }
1932
1933    #[test]
1934    fn the_three_modifiers_on_a_create_table_survive() {
1935        assert_eq!(
1936            round_statement("CREATE OR REPLACE TEMPORARY TABLE IF NOT EXISTS s.t (a INT)"),
1937            "CREATE OR REPLACE TEMPORARY TABLE IF NOT EXISTS s.t (a INT)"
1938        );
1939    }
1940
1941    #[test]
1942    fn a_create_table_as_carries_the_query_and_not_the_types() {
1943        assert_eq!(
1944            round_statement("CREATE TABLE t AS SELECT a FROM u"),
1945            "CREATE TABLE t AS SELECT a FROM u"
1946        );
1947        // The names are the syntax's to say and the types are the query's, so the column
1948        // definitions here have names and no types.
1949        assert_eq!(
1950            round_statement("CREATE TABLE t (x, y) AS SELECT a, b FROM u"),
1951            "CREATE TABLE t (x, y) AS SELECT a, b FROM u"
1952        );
1953    }
1954
1955    #[test]
1956    fn a_drop_table_is_a_list_of_qualified_names() {
1957        assert_eq!(round_statement("DROP TABLE t"), "DROP TABLE t");
1958        assert_eq!(round_statement("DROP TABLE IF EXISTS a, b.c"), "DROP TABLE IF EXISTS a, b.c");
1959    }
1960
1961    #[test]
1962    fn dropping_something_that_is_not_a_table_is_refused() {
1963        // `TableOrView` covers `VIEW` and `MATERIALIZED VIEW` as well, and a view dropped as if it
1964        // were a table is a wrong answer rather than a missing feature.
1965        let error = parse_ast("DROP VIEW v").unwrap_err().to_string();
1966        assert!(error.starts_with("Not implemented Error"), "{error}");
1967    }
1968
1969    #[test]
1970    fn both_spellings_of_insert_arrive_at_a_query() {
1971        assert_eq!(
1972            round_statement("INSERT INTO t VALUES (1, 'a'), (2, 'b')"),
1973            "INSERT INTO t VALUES (1, 'a'), (2, 'b')"
1974        );
1975        assert_eq!(
1976            round_statement("INSERT INTO t (a, b) SELECT x, y FROM u"),
1977            "INSERT INTO t (a, b) SELECT x, y FROM u"
1978        );
1979    }
1980
1981    #[test]
1982    fn an_insert_clause_that_changes_the_answer_is_refused() {
1983        for query in [
1984            "INSERT INTO t VALUES (1) RETURNING *",
1985            "INSERT OR REPLACE INTO t VALUES (1)",
1986            "INSERT INTO t BY NAME SELECT 1 AS a",
1987            "INSERT INTO t VALUES (1) ON CONFLICT DO NOTHING",
1988            "INSERT INTO t DEFAULT VALUES",
1989        ] {
1990            let error = parse_ast(query).unwrap_err().to_string();
1991            assert!(error.starts_with("Not implemented Error"), "{query} gave {error}");
1992        }
1993    }
1994
1995    #[test]
1996    fn a_column_constraint_that_is_not_not_null_is_refused() {
1997        // Nothing enforces a constraint yet. Accepting one and not enforcing it is the wrong
1998        // answer, so `NOT NULL` is kept because the column already has a nullability and the rest
1999        // are refused until there is somewhere to put them.
2000        for query in [
2001            "CREATE TABLE t (a INT PRIMARY KEY)",
2002            "CREATE TABLE t (a INT UNIQUE)",
2003            "CREATE TABLE t (a INT CHECK (a > 0))",
2004            "CREATE TABLE t (a INT DEFAULT 1)",
2005            "CREATE TABLE t (a INT REFERENCES u (b))",
2006            "CREATE TABLE t (a INT, PRIMARY KEY (a))",
2007        ] {
2008            let error = parse_ast(query).unwrap_err().to_string();
2009            assert!(error.starts_with("Not implemented Error"), "{query} gave {error}");
2010        }
2011    }
2012
2013    #[test]
2014    fn values_is_a_query_on_its_own_and_in_a_from() {
2015        assert_eq!(round("VALUES (1), (2)"), "VALUES (1), (2)");
2016        // Parenthesised it is a subquery whose body is the values, and bare it is a `ValuesRef`.
2017        // Two rules and one meaning, which is the grammar's doing and not something to flatten
2018        // here, because the parenthesised form can carry an order by and the bare one cannot.
2019        assert_eq!(
2020            round("SELECT * FROM (VALUES (1, 2), (3, 4)) t(a, b)"),
2021            "SELECT * FROM (VALUES (1, 2), (3, 4)) AS t"
2022        );
2023        assert_eq!(
2024            round("SELECT * FROM VALUES (1, 2), (3, 4) AS t(a, b)"),
2025            "SELECT * FROM VALUES (1, 2), (3, 4) AS t"
2026        );
2027        // Rows of different widths parse. Saying so wants the column count, which for an insert is
2028        // the table's, so the check belongs to the binder and not here.
2029        assert_eq!(round("VALUES (1), (2, 3)"), "VALUES (1), (2, 3)");
2030    }
2031
2032    #[test]
2033    fn every_statement_in_the_corpus_gets_a_defined_answer() {
2034        // The point of the test is the word defined. Forty of these are statement kinds and
2035        // clauses this milestone does not cover, and the requirement is not that they work, it is
2036        // that they fail by saying so. A panic, a silently dropped clause or an internal error
2037        // would each be a different bug and all three would be invisible without this.
2038        let mut done = 0;
2039        for query in CORPUS {
2040            match parse_ast(query) {
2041                Ok(ast) => {
2042                    assert_eq!(ast.statements.len(), 1, "{query}");
2043                    done += 1;
2044                }
2045                Err(error) => {
2046                    let message = error.to_string();
2047                    assert!(
2048                        message.starts_with("Not implemented Error"),
2049                        "{query} failed with {message}, which is not a not-implemented error"
2050                    );
2051                }
2052            }
2053        }
2054        // Not an assertion about the right number. It is a ratchet: this only moves up, and the
2055        // day it moves down somebody has taken a construct out without meaning to.
2056        assert!(done >= 22, "only {done} of the corpus transforms, which is fewer than it was");
2057    }
2058
2059    #[test]
2060    fn the_ast_is_far_smaller_than_the_parse_tree() {
2061        let query = CORPUS[4];
2062        let tree = parse(query).unwrap();
2063        let ast = parse_ast(query).unwrap();
2064        // The twenty precedence levels are the difference. Every one of them is a node in the
2065        // parse tree for every expression at every depth, and none of them survives into the AST.
2066        assert!(
2067            ast.node_count() * 20 < tree.arena_len(),
2068            "{} ast nodes against {} parse nodes",
2069            ast.node_count(),
2070            tree.arena_len()
2071        );
2072    }
2073
2074    #[test]
2075    fn precedence_comes_out_of_the_chain_and_into_the_tree() {
2076        assert_eq!(round("SELECT 1 + 2 * 3"), "SELECT (1 Add (2 Multiply 3))");
2077        assert_eq!(round("SELECT (1 + 2) * 3"), "SELECT ((1 Add 2) Multiply 3)");
2078        assert_eq!(round("SELECT 1 + 2 + 3"), "SELECT ((1 Add 2) Add 3)");
2079        assert_eq!(round("SELECT 1 - 2 - 3"), "SELECT ((1 Subtract 2) Subtract 3)");
2080        assert_eq!(
2081            round("SELECT a OR b AND c"),
2082            "SELECT (a Or (b And c))",
2083            "and binds tighter than or"
2084        );
2085    }
2086
2087    #[test]
2088    fn a_double_negation_is_two_nodes_and_not_none() {
2089        // Folding it would be an optimizer decision and this is not the optimizer. It also would
2090        // not be safe in general: `NOT NOT x` on a null is still null and on a non boolean it is
2091        // still an error, and both of those have to survive to the binder to be reported.
2092        assert_eq!(round("SELECT NOT NOT a"), "SELECT (Not (Not a))");
2093    }
2094
2095    #[test]
2096    fn a_parenthesised_single_expression_is_not_a_row() {
2097        assert_eq!(round("SELECT (a)"), "SELECT a");
2098        assert_eq!(round("SELECT (a, b)"), "SELECT ROW(a, b)");
2099    }
2100
2101    #[test]
2102    fn the_three_ways_to_write_an_alias_all_arrive() {
2103        assert_eq!(round("SELECT a AS b"), "SELECT a AS b");
2104        assert_eq!(round("SELECT a b"), "SELECT a AS b");
2105        assert_eq!(round("SELECT b: a"), "SELECT a AS b");
2106        assert_eq!(round("SELECT a"), "SELECT a", "and no alias when none was written");
2107    }
2108
2109    #[test]
2110    fn a_from_with_no_select_selects_everything() {
2111        // DuckDB's own shorthand. Inventing the star here rather than in the binder means the
2112        // binder never has to know that the clause it is looking at was the one that was missing.
2113        assert_eq!(round("FROM t"), "SELECT * FROM t");
2114        assert_eq!(round("FROM t SELECT a"), "SELECT a FROM t");
2115    }
2116
2117    #[test]
2118    fn joins_nest_to_the_left() {
2119        assert_eq!(
2120            round("SELECT * FROM a JOIN b ON a.i = b.i LEFT JOIN c USING (k)"),
2121            "SELECT * FROM ((a Inner JOIN b ON (a.i Eq b.i)) Left JOIN c USING (k))"
2122        );
2123        assert_eq!(
2124            round("SELECT * FROM a NATURAL JOIN b"),
2125            "SELECT * FROM (a NATURAL Inner JOIN b)"
2126        );
2127        assert_eq!(round("SELECT * FROM a CROSS JOIN b"), "SELECT * FROM (a Cross JOIN b)");
2128        assert_eq!(
2129            round("SELECT * FROM a POSITIONAL JOIN b"),
2130            "SELECT * FROM (a Positional JOIN b)"
2131        );
2132        assert_eq!(round("SELECT * FROM a, b"), "SELECT * FROM a, b", "a comma is not a join node");
2133    }
2134
2135    #[test]
2136    fn a_qualified_name_keeps_its_parts_however_it_was_spelled() {
2137        // Five grammar rules can produce a column reference and they disagree about which
2138        // component is a schema and which is a table. None of that is decidable without the
2139        // catalog, so the AST holds the parts and the binder decides.
2140        assert_eq!(round("SELECT a"), "SELECT a");
2141        assert_eq!(round("SELECT t.a"), "SELECT t.a");
2142        assert_eq!(round("SELECT s.t.a"), "SELECT s.t.a");
2143        assert_eq!(round("SELECT c.s.t.a"), "SELECT c.s.t.a");
2144        assert_eq!(round("SELECT * FROM s.t"), "SELECT * FROM s.t");
2145    }
2146
2147    #[test]
2148    fn a_star_can_be_qualified() {
2149        assert_eq!(round("SELECT *"), "SELECT *");
2150        assert_eq!(round("SELECT t.*"), "SELECT t.*");
2151        assert_eq!(round("SELECT s.t.*"), "SELECT s.t.*");
2152    }
2153
2154    #[test]
2155    fn a_quoted_identifier_keeps_its_case_and_loses_its_quotes() {
2156        // DuckDB does not fold identifier case at any point, quoted or not, which the tokenizer
2157        // work established by reading the source. So the only thing to do here is take the quotes
2158        // off and resolve the doubled ones.
2159        let ast = parse_ast("SELECT \"Mixed Case\", \"a\"\"b\"").unwrap();
2160        assert_eq!(ast.strings[0], "Mixed Case");
2161        assert_eq!(ast.strings[1], "a\"b");
2162    }
2163
2164    #[test]
2165    fn a_string_literal_is_decoded_and_adjacent_ones_are_joined() {
2166        assert_eq!(round("SELECT 'it''s'"), "SELECT 'it's'");
2167        assert_eq!(round("SELECT 'a'\n'b'"), "SELECT 'ab'", "the standard's adjacency rule");
2168    }
2169
2170    #[test]
2171    fn the_null_and_boolean_tests_are_postfix_unary_operators() {
2172        assert_eq!(round("SELECT x IS NULL"), "SELECT (IsNull x)");
2173        assert_eq!(round("SELECT x IS NOT NULL"), "SELECT (IsNotNull x)");
2174        assert_eq!(round("SELECT x ISNULL"), "SELECT (IsNull x)");
2175        assert_eq!(round("SELECT x NOTNULL"), "SELECT (IsNotNull x)");
2176        assert_eq!(round("SELECT x IS TRUE"), "SELECT (IsTrue x)");
2177        assert_eq!(round("SELECT x IS NOT FALSE"), "SELECT (IsNotFalse x)");
2178        assert_eq!(round("SELECT x IS DISTINCT FROM y"), "SELECT (x IsDistinctFrom y)");
2179        assert_eq!(round("SELECT x IS NOT DISTINCT FROM y"), "SELECT (x IsNotDistinctFrom y)");
2180    }
2181
2182    #[test]
2183    fn the_like_family_folds_its_negation_into_the_operator() {
2184        assert_eq!(round("SELECT x LIKE 'a'"), "SELECT (x Like 'a')");
2185        assert_eq!(round("SELECT x NOT LIKE 'a'"), "SELECT (x NotLike 'a')");
2186        assert_eq!(round("SELECT x ILIKE 'a'"), "SELECT (x ILike 'a')");
2187        assert_eq!(round("SELECT x ~~ 'a'"), "SELECT (x Like 'a')", "the operator spelling");
2188        assert_eq!(round("SELECT x !~~ 'a'"), "SELECT (x NotLike 'a')");
2189        assert_eq!(round("SELECT x SIMILAR TO 'a'"), "SELECT (x SimilarTo 'a')");
2190        // Glob has no negated operator to fold into, so the negation stays where it was written.
2191        assert_eq!(round("SELECT x NOT GLOB 'a'"), "SELECT (Not (x Glob 'a'))");
2192    }
2193
2194    #[test]
2195    fn between_and_in_carry_their_negation_as_a_flag() {
2196        assert_eq!(round("SELECT x BETWEEN 1 AND 2"), "SELECT (x BETWEEN 1 AND 2)");
2197        assert_eq!(round("SELECT x NOT BETWEEN 1 AND 2"), "SELECT (NOT x BETWEEN 1 AND 2)");
2198        assert_eq!(round("SELECT x IN (1, 2)"), "SELECT (x IN [1, 2])");
2199        assert_eq!(round("SELECT x NOT IN (1, 2)"), "SELECT (NOT x IN [1, 2])");
2200    }
2201
2202    #[test]
2203    fn both_spellings_of_a_cast_are_the_same_node() {
2204        assert_eq!(round("SELECT CAST(x AS BIGINT)"), "SELECT CAST(x AS BIGINT)");
2205        assert_eq!(round("SELECT x::BIGINT"), "SELECT CAST(x AS BIGINT)");
2206        assert_eq!(round("SELECT TRY_CAST(x AS BIGINT)"), "SELECT TRY_CAST(x AS BIGINT)");
2207        assert_eq!(
2208            round("SELECT x::DECIMAL(18, 3)"),
2209            "SELECT CAST(x AS DECIMAL(18, 3))",
2210            "the type is kept as text because parsing it is the type system's job"
2211        );
2212    }
2213
2214    #[test]
2215    fn a_case_keeps_its_arms_in_order() {
2216        assert_eq!(
2217            round("SELECT CASE WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"),
2218            "SELECT CASE - WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"
2219        );
2220        assert_eq!(
2221            round("SELECT CASE x WHEN 1 THEN 'a' END"),
2222            "SELECT CASE x WHEN 1 THEN 'a' ELSE - END",
2223            "a simple case keeps the operand and a missing else is not an implicit null yet"
2224        );
2225    }
2226
2227    #[test]
2228    fn a_field_access_and_a_method_call_are_ordinary_function_calls() {
2229        // Which is what DuckDB makes of them too. Giving each its own AST node would mean the
2230        // binder needs a rule for something the function resolver already handles.
2231        assert_eq!(round("SELECT (f(x)).y"), "SELECT struct_extract(f(x), 'y')");
2232        assert_eq!(round("SELECT a[1]"), "SELECT array_extract(a, 1)");
2233    }
2234
2235    #[test]
2236    fn an_aggregate_keeps_its_distinct() {
2237        assert_eq!(round("SELECT count(*)"), "SELECT count(*)");
2238        assert_eq!(round("SELECT count(DISTINCT x)"), "SELECT count(DISTINCT x)");
2239        assert_eq!(round("SELECT count(ALL x)"), "SELECT count(x)");
2240        assert_eq!(round("SELECT main.count(x)"), "SELECT main.count(x)");
2241    }
2242
2243    #[test]
2244    fn the_modifiers_hang_off_the_query_and_not_off_the_select() {
2245        // `a UNION b ORDER BY x` sorts the union. Putting the order by on the select would have
2246        // made that unrepresentable, which is why the grammar puts it outside the chain and why
2247        // the AST follows.
2248        assert_eq!(
2249            round("SELECT 1 UNION ALL SELECT 2 ORDER BY 1"),
2250            "(SELECT 1 Union All SELECT 2) ORDER BY 1 Unstated Unstated"
2251        );
2252        assert_eq!(
2253            round("SELECT a FROM t UNION SELECT b FROM u EXCEPT SELECT c FROM v"),
2254            "((SELECT a FROM t Union Unstated SELECT b FROM u) Except Unstated SELECT c FROM v)",
2255            "set operators are left associative"
2256        );
2257        assert_eq!(
2258            round("SELECT 1 UNION SELECT 2 INTERSECT SELECT 3"),
2259            "(SELECT 1 Union Unstated (SELECT 2 Intersect Unstated SELECT 3))",
2260            "and intersect binds tighter than the other two"
2261        );
2262    }
2263
2264    #[test]
2265    fn the_sort_and_limit_clauses_keep_what_was_written() {
2266        assert_eq!(
2267            round("SELECT a FROM t ORDER BY a"),
2268            "SELECT a FROM t ORDER BY a Unstated Unstated"
2269        );
2270        assert_eq!(
2271            round("SELECT a FROM t ORDER BY a DESC NULLS LAST"),
2272            "SELECT a FROM t ORDER BY a Descending Last"
2273        );
2274        assert_eq!(round("SELECT a FROM t ORDER BY ALL"), "SELECT a FROM t ORDER BY ALL");
2275        assert_eq!(round("SELECT a FROM t GROUP BY ALL"), "SELECT a FROM t GROUP BY ALL");
2276        assert_eq!(round("SELECT a FROM t LIMIT 10 OFFSET 5"), "SELECT a FROM t LIMIT 10 OFFSET 5");
2277        assert_eq!(round("SELECT a FROM t OFFSET 5 LIMIT 10"), "SELECT a FROM t LIMIT 10 OFFSET 5");
2278        assert_eq!(round("SELECT a FROM t LIMIT 10%"), "SELECT a FROM t LIMIT 10%");
2279        assert_eq!(round("SELECT a FROM t LIMIT ALL"), "SELECT a FROM t", "which is no limit");
2280    }
2281
2282    #[test]
2283    fn a_subquery_appears_in_both_places_it_can() {
2284        assert_eq!(
2285            round("SELECT * FROM (SELECT x FROM t) AS s"),
2286            "SELECT * FROM (SELECT x FROM t) AS s"
2287        );
2288        assert_eq!(round("SELECT (SELECT 1)"), "SELECT (SELECT 1)");
2289    }
2290
2291    #[test]
2292    fn distinct_on_keeps_its_expressions() {
2293        assert_eq!(round("SELECT DISTINCT a"), "SELECT DISTINCT a");
2294        assert_eq!(round("SELECT ALL a"), "SELECT a", "which is the default written out");
2295        assert_eq!(round("SELECT DISTINCT ON (a, b) a"), "SELECT DISTINCT ON (a, b) a");
2296    }
2297
2298    #[test]
2299    fn an_operator_the_dialect_does_not_name_is_kept_by_name() {
2300        // The grammar text says `OperatorLiteral <- Identifier`, which reads as though any bare
2301        // word could be written infix. It cannot. That rule is one of the 24 the matcher overrides
2302        // and it is overridden to the bare operator matcher, so what it takes is a run of operator
2303        // characters. Believing the body here would have produced a transformer that accepted
2304        // `a foo b`, which DuckDB rejects.
2305        assert_eq!(round("SELECT a <=> b"), "SELECT (a <=> b)");
2306        assert!(parse_ast("SELECT a foo b").is_err(), "a bare word is not an operator");
2307    }
2308
2309    #[test]
2310    fn a_script_is_a_list_of_statements() {
2311        let ast = parse_ast("SELECT 1; SELECT 2;").unwrap();
2312        assert_eq!(ast.statements.len(), 2);
2313        // A trailing semicolon makes an empty top level statement in the parse tree, because the
2314        // grammar's `Statement? (';'+ / EndOfInput)` is happy with nothing on both sides. It is
2315        // dropped here rather than pretended away in the matcher.
2316        let Statement::Query(second) = ast.statements[1] else {
2317            panic!("the second statement is a query");
2318        };
2319        assert_eq!(show_query(&ast, second), "SELECT 2");
2320    }
2321
2322    #[test]
2323    fn an_unsupported_construct_names_itself_and_what_was_written() {
2324        let error = parse_ast("ALTER TABLE t ADD COLUMN a INTEGER").unwrap_err().to_string();
2325        assert!(error.starts_with("Not implemented Error"), "{error}");
2326        assert!(error.contains("ALTER TABLE t ADD COLUMN a INTEGER"), "{error}");
2327        assert!(error.contains("AlterStatement"), "{error}");
2328    }
2329
2330    #[test]
2331    fn a_long_construct_is_cut_short_in_the_message() {
2332        let query = format!("ALTER TABLE t ADD COLUMN {} INTEGER", "a".repeat(80));
2333        let error = parse_ast(&query).unwrap_err().to_string();
2334        assert!(error.contains("..."), "{error}");
2335        assert!(error.len() < 200, "{error}");
2336    }
2337
2338    #[test]
2339    fn the_transformer_never_panics_on_anything_the_matcher_accepts() {
2340        // The matcher accepts a good deal that means nothing, because the grammar does. Every one
2341        // of these parses and none of them is a statement this milestone covers, and the contract
2342        // is that the answer is an error either way.
2343        for query in [
2344            "SELECT",
2345            "FROM t SELECT",
2346            "SELECT * FROM t WHERE",
2347            "SELECT ()",
2348            "SELECT a FROM t GROUP BY ()",
2349        ] {
2350            let answer = parse_ast(query);
2351            if let Err(error) = answer {
2352                let message = error.to_string();
2353                assert!(
2354                    message.starts_with("Not implemented Error")
2355                        || message.starts_with("Parser Error"),
2356                    "{query} failed with {message}"
2357                );
2358            }
2359        }
2360    }
2361
2362    #[test]
2363    fn a_file_name_in_a_from_clause_is_a_table_name_with_the_quotes_off() {
2364        // Both spellings have to arrive as the same name, because the binder decides whether it is
2365        // a file by looking at the name, and `'hits.parquet'` with the quotes still on it is not
2366        // a path that anything can open.
2367        assert_eq!(round("SELECT * FROM 'hits.parquet'"), "SELECT * FROM hits.parquet");
2368        assert_eq!(round("SELECT * FROM \"hits.parquet\""), "SELECT * FROM hits.parquet");
2369        assert_eq!(round("SELECT * FROM 'hits.parquet' AS h"), "SELECT * FROM hits.parquet AS h");
2370    }
2371
2372    #[test]
2373    fn a_function_call_in_a_from_clause_is_a_source_and_not_an_expression() {
2374        assert_eq!(round("SELECT * FROM range(3)"), "SELECT * FROM range(3)");
2375        assert_eq!(round("SELECT * FROM range(1, 10, 2)"), "SELECT * FROM range(1, 10, 2)");
2376        assert_eq!(round("SELECT * FROM main.range(3)"), "SELECT * FROM main.range(3)");
2377        assert_eq!(round("SELECT * FROM range(3) AS t"), "SELECT * FROM range(3) AS t");
2378        // The grammar allows a call with no arguments here and the transformer keeps it, because
2379        // whether a particular function takes none is the binder's question and not this one's.
2380        assert_eq!(round("SELECT * FROM some_function()"), "SELECT * FROM some_function()");
2381    }
2382
2383    #[test]
2384    fn the_forms_of_a_table_function_this_does_not_cover_are_turned_away_by_name() {
2385        for query in [
2386            "SELECT * FROM range(3) WITH ORDINALITY",
2387            "SELECT * FROM LATERAL range(3)",
2388            "SELECT * FROM t: range(3)",
2389        ] {
2390            let error = parse_ast(query).unwrap_err().to_string();
2391            assert!(error.contains("grammar rule"), "{query} failed with {error}");
2392        }
2393    }
2394
2395    #[test]
2396    fn interning_means_a_name_written_twice_is_stored_once() {
2397        let ast = parse_ast("SELECT a, a, a FROM t WHERE a = a").unwrap();
2398        assert_eq!(ast.strings.iter().filter(|text| *text == "a").count(), 1);
2399    }
2400}