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                "CastExpression" => return self.cast(node),
1116                "CaseExpression" => return self.case(node),
1117                "ParenthesisExpression" => return self.row(node),
1118                "SubqueryExpression" => return self.subquery(node),
1119                _ if count == 1 => node = self.first(node),
1120                _ => return self.unsupported(node),
1121            }
1122        }
1123    }
1124
1125    /// `X <- Y XTail*` where `XTail <- Operator Y`, the shape ten precedence levels share.
1126    fn tail_chain(&mut self, node: u32) -> Result<ExprRef> {
1127        let mut kids = self.kids(node);
1128        let head = kids.next().unwrap_or(NONE);
1129        let mut left = self.expr(head)?;
1130        for tail in kids {
1131            let operator = self.first(tail);
1132            let op = self.binary_op(operator)?;
1133            // `ComparisonExpressionTail <- ComparisonOperator NotExpression? BetweenInLikeExpression`
1134            // is the one tail with an optional middle, so the operand is the last child and not the
1135            // second one. Taking the last is right for every tail and wrong for none.
1136            let operand = self.kids(tail).last().unwrap_or(NONE);
1137            if self.count(tail) > 2 {
1138                return self.unsupported(tail);
1139            }
1140            let right = self.expr(operand)?;
1141            left = self.push(Expr::Binary { op, left, right });
1142        }
1143        Ok(left)
1144    }
1145
1146    /// Which infix operator a tail's operator node is.
1147    fn binary_op(&mut self, node: u32) -> Result<BinaryOp> {
1148        // The operator rules nest: `ComparisonOperator` over `OperatorGreaterThan` over the symbol
1149        // itself. Every one of them covers the same tokens, so the text is the same at every level
1150        // and reading it once at the top is enough. The name is not, which is why the bottom of the
1151        // chain is walked to as well: `OtherOperator` says nothing and `OperatorLiteral` says
1152        // everything, and they are three levels apart.
1153        let mut leaf = node;
1154        while self.count(leaf) == 1 {
1155            leaf = self.first(leaf);
1156        }
1157        let text = self.text(node);
1158        let upper = text.to_ascii_uppercase();
1159        let op = match upper.as_str() {
1160            "OR" => BinaryOp::Or,
1161            "AND" => BinaryOp::And,
1162            "=" | "==" => BinaryOp::Eq,
1163            "!=" | "<>" => BinaryOp::NotEq,
1164            "<" => BinaryOp::Lt,
1165            ">" => BinaryOp::Gt,
1166            "<=" => BinaryOp::LtEq,
1167            ">=" => BinaryOp::GtEq,
1168            "+" => BinaryOp::Add,
1169            "-" => BinaryOp::Subtract,
1170            "*" => BinaryOp::Multiply,
1171            "/" => BinaryOp::Divide,
1172            "//" => BinaryOp::IntegerDivide,
1173            "%" => BinaryOp::Modulo,
1174            "^" | "**" => BinaryOp::Power,
1175            "&" => BinaryOp::BitAnd,
1176            "|" => BinaryOp::BitOr,
1177            "<<" => BinaryOp::ShiftLeft,
1178            ">>" => BinaryOp::ShiftRight,
1179            "||" => BinaryOp::Concat,
1180            "COLLATE" => BinaryOp::Collate,
1181            "->" => BinaryOp::Arrow,
1182            "->>" => BinaryOp::LongArrow,
1183            "@>" => BinaryOp::Contains,
1184            "<@" => BinaryOp::ContainedBy,
1185            "&&" => BinaryOp::Overlaps,
1186            "^@" => BinaryOp::StartsWith,
1187            "<<=" => BinaryOp::InetContainedByOrEq,
1188            ">>=" => BinaryOp::InetContainsOrEq,
1189            _ if self.name(leaf) == "AtTimeZoneOperator" => BinaryOp::AtTimeZone,
1190            // `IsDistinctFromOp <- 'IS' 'NOT'? 'DISTINCT' 'FROM'`, told apart by the middle word,
1191            // which is not in the tree because keywords are terminals.
1192            _ if self.name(leaf) == "IsDistinctFromOp" => {
1193                if upper.split_whitespace().any(|word| word == "NOT") {
1194                    BinaryOp::IsNotDistinctFrom
1195                } else {
1196                    BinaryOp::IsDistinctFrom
1197                }
1198            }
1199            // `OperatorLiteral` is the open end of the operator set. Its body in the grammar text
1200            // says `Identifier`, but it is one of the 24 rules whose body the matcher does not
1201            // walk and the matcher it is overridden to is the bare operator one, so what it
1202            // actually accepts is any run of operator characters that is not already a token.
1203            // `a <=> b` is such a run, DuckDB resolves it as a two argument function of that name,
1204            // and rejecting it here would reject SQL DuckDB accepts.
1205            _ if self.name(leaf) == "OperatorLiteral" => {
1206                let interned = self.intern(text);
1207                BinaryOp::Named(interned)
1208            }
1209            _ => return self.unsupported(node),
1210        };
1211        Ok(op)
1212    }
1213
1214    /// `LogicalOrExpression <- LogicalAndExpression LogicalOrExpressionTail*`, and the `AND` twin.
1215    ///
1216    /// Separate from the other tails because the tail here is `'OR' LogicalAndExpression` with the
1217    /// keyword as a terminal, so there is no operator node to read and the operator is the rule.
1218    fn logical(&mut self, node: u32, op: BinaryOp) -> Result<ExprRef> {
1219        let mut kids = self.kids(node);
1220        let head = kids.next().unwrap_or(NONE);
1221        let mut left = self.expr(head)?;
1222        for tail in kids {
1223            let right = self.expr(self.first(tail))?;
1224            left = self.push(Expr::Binary { op, left, right });
1225        }
1226        Ok(left)
1227    }
1228
1229    /// `LogicalNotExpression <- NotExpression? IsExpression`, where `NotExpression <- NotKeyword+`.
1230    ///
1231    /// The plus matters. `NOT NOT x` is two nodes in the parse tree and two negations in the AST,
1232    /// and folding them here would be an optimizer decision taken in the parser.
1233    fn logical_not(&mut self, node: u32) -> Result<ExprRef> {
1234        let negations = self.count(self.first(node));
1235        let mut expr = self.expr(self.nth(node, 1))?;
1236        for _ in 0..negations {
1237            expr = self.push(Expr::Unary { op: UnaryOp::Not, operand: expr });
1238        }
1239        Ok(expr)
1240    }
1241
1242    /// `IsExpression <- IsDistinctFromExpression IsTest*`, the postfix null and boolean tests.
1243    fn is_expression(&mut self, node: u32) -> Result<ExprRef> {
1244        let mut kids = self.kids(node);
1245        let head = kids.next().unwrap_or(NONE);
1246        let mut expr = self.expr(head)?;
1247        for test in kids {
1248            let inner = self.first(test);
1249            let negated = self.text(inner).to_ascii_uppercase().contains("NOT");
1250            let op = match self.name(inner) {
1251                "NotNull" => UnaryOp::IsNotNull,
1252                "IsNull" => UnaryOp::IsNull,
1253                // `IsLiteral <- 'IS' 'NOT'? IsLiteralValue`, and the value rule is one more level
1254                // down again because it is a choice of four and not four alternatives inlined.
1255                "IsLiteral" => match self.name(self.first(self.first(inner))) {
1256                    "NullLiteral" if negated => UnaryOp::IsNotNull,
1257                    "NullLiteral" => UnaryOp::IsNull,
1258                    "TrueLiteral" if negated => UnaryOp::IsNotTrue,
1259                    "TrueLiteral" => UnaryOp::IsTrue,
1260                    "FalseLiteral" if negated => UnaryOp::IsNotFalse,
1261                    "FalseLiteral" => UnaryOp::IsFalse,
1262                    "UnknownLiteral" if negated => UnaryOp::IsNotUnknown,
1263                    "UnknownLiteral" => UnaryOp::IsUnknown,
1264                    _ => return self.unsupported(inner),
1265                },
1266                _ => return self.unsupported(inner),
1267            };
1268            expr = self.push(Expr::Unary { op, operand: expr });
1269        }
1270        Ok(expr)
1271    }
1272
1273    /// `BetweenInLikeExpression <- OtherOperatorExpression BetweenInLikeOp?`.
1274    fn between_in_like(&mut self, node: u32) -> Result<ExprRef> {
1275        let operand = self.expr(self.first(node))?;
1276        // `BetweenInLikeOp <- 'NOT'? BetweenInLikeOpExpression`. The `NOT` is a terminal, so what
1277        // says it was written is that the op node covers a token the inner node does not.
1278        let op = self.nth(node, 1);
1279        let negated = self.text(op).to_ascii_uppercase().starts_with("NOT");
1280        let inner = self.first(self.first(op));
1281        match self.name(inner) {
1282            // `BetweenClause <- 'BETWEEN' x 'AND' y`.
1283            "BetweenClause" => {
1284                let low = self.expr(self.first(inner))?;
1285                let high = self.expr(self.nth(inner, 1))?;
1286                Ok(self.push(Expr::Between { operand, low, high, negated }))
1287            }
1288            // `InClause <- 'IN' InExpression`.
1289            "InClause" => {
1290                let expression = self.first(self.first(inner));
1291                match self.name(expression) {
1292                    "InExpressionList" => {
1293                        let mut items = Vec::new();
1294                        for kid in self.kids(expression) {
1295                            items.push(self.expr(kid)?);
1296                        }
1297                        let list = self.expr_slice(items);
1298                        Ok(self.push(Expr::In { operand, list, negated }))
1299                    }
1300                    _ => self.unsupported(expression),
1301                }
1302            }
1303            // `LikeClause <- LikeVariations x EscapeClause?`.
1304            "LikeClause" => {
1305                if self.find(inner, "EscapeClause") != NONE {
1306                    return self.unsupported(inner);
1307                }
1308                let variation = self.name(self.first(self.first(inner)));
1309                let op = match (variation, negated) {
1310                    ("LikeToken", false) | ("NotLikeOp", true) => BinaryOp::Like,
1311                    ("LikeToken", true) | ("NotLikeOp", false) => BinaryOp::NotLike,
1312                    ("ILikeToken", false) | ("NotILikeOp", true) => BinaryOp::ILike,
1313                    ("ILikeToken", true) | ("NotILikeOp", false) => BinaryOp::NotILike,
1314                    // Glob and the bare regex match have no negated spelling of their own in
1315                    // `LikeVariations`, so a `NOT` in front of either stays an explicit negation.
1316                    ("GlobToken", _) => BinaryOp::Glob,
1317                    ("RegexMatchToken", _) => BinaryOp::Regex,
1318                    ("SimilarToToken", false) | ("NotSimilarToOp", true) => BinaryOp::SimilarTo,
1319                    ("SimilarToToken", true) | ("NotSimilarToOp", false) => BinaryOp::NotSimilarTo,
1320                    ("RegexInsensitiveMatchToken", false)
1321                    | ("NotRegexInsensitiveMatchOp", true) => BinaryOp::RegexInsensitive,
1322                    ("RegexInsensitiveMatchToken", true)
1323                    | ("NotRegexInsensitiveMatchOp", false) => BinaryOp::NotRegexInsensitive,
1324                    _ => return self.unsupported(inner),
1325                };
1326                let right = self.expr(self.nth(inner, 1))?;
1327                let expr = self.push(Expr::Binary { op, left: operand, right });
1328                // The like family folds its negation into the operator because it has a spelling
1329                // for the negated form. Glob and regex do not, so theirs stays where it was.
1330                if negated && matches!(op, BinaryOp::Glob | BinaryOp::Regex) {
1331                    return Ok(self.push(Expr::Unary { op: UnaryOp::Not, operand: expr }));
1332                }
1333                Ok(expr)
1334            }
1335            _ => self.unsupported(inner),
1336        }
1337    }
1338
1339    /// `PrefixExpression <- PrefixOperator* BaseExpression`, applied right to left.
1340    fn prefix(&mut self, node: u32) -> Result<ExprRef> {
1341        let kids: Vec<u32> = self.kids(node).collect();
1342        let mut expr = self.expr(kids[kids.len() - 1])?;
1343        for &operator in kids[..kids.len() - 1].iter().rev() {
1344            let op = match self.name(self.first(operator)) {
1345                "MinusPrefixOperator" => UnaryOp::Negate,
1346                "PlusPrefixOperator" => UnaryOp::Plus,
1347                "TildePrefixOperator" => UnaryOp::BitNot,
1348                _ => return self.unsupported(operator),
1349            };
1350            expr = self.push(Expr::Unary { op, operand: expr });
1351        }
1352        Ok(expr)
1353    }
1354
1355    /// `BaseExpression <- SingleExpression IndirectionList?`, the postfix chain.
1356    fn indirection(&mut self, node: u32) -> Result<ExprRef> {
1357        let mut expr = self.expr(self.first(node))?;
1358        for step in self.kids(self.nth(node, 1)) {
1359            let inner = self.first(step);
1360            expr = match self.name(inner) {
1361                // `CastOperator <- '::' Type`.
1362                "CastOperator" => {
1363                    let text = self.text(self.first(inner)).to_string();
1364                    let ty = self.intern(&text);
1365                    self.push(Expr::Cast { operand: expr, ty, try_cast: false })
1366                }
1367                "DotOperator" => {
1368                    let dot = self.first(inner);
1369                    match self.name(dot) {
1370                        // `DotColumnOperator <- '.' ColLabel`, which DuckDB resolves as a call of
1371                        // `struct_extract`. Writing it as that call rather than as its own node
1372                        // keeps the binder from needing a rule for a thing that is already a
1373                        // function.
1374                        "DotColumnOperator" => {
1375                            let field = self.identifier(self.first(dot));
1376                            let text = self.ast.string(field).to_string();
1377                            let literal = self.intern(&text);
1378                            let key = self
1379                                .push(Expr::Literal { kind: LiteralKind::String, text: literal });
1380                            let name = self.function_name("struct_extract");
1381                            let args = self.expr_slice(vec![expr, key]);
1382                            self.push(Expr::Function { name, args, distinct: false })
1383                        }
1384                        // `DotMethodOperator <- '.' MethodExpression`, where `x.f(a)` is `f(x, a)`.
1385                        "DotMethodOperator" => {
1386                            let method = self.first(dot);
1387                            let text = self.text(self.first(method)).to_string();
1388                            let text = unquote(&text);
1389                            let name = self.function_name(&text);
1390                            let mut args = vec![expr];
1391                            let list = self.find(method, "MethodExpressionArguments");
1392                            if list != NONE {
1393                                let inner = self.first(list);
1394                                let arguments = self.find(inner, "MethodFunctionArguments");
1395                                if arguments != NONE {
1396                                    for kid in self.kids(arguments) {
1397                                        args.push(self.argument(kid)?);
1398                                    }
1399                                }
1400                            }
1401                            let args = self.expr_slice(args);
1402                            self.push(Expr::Function { name, args, distinct: false })
1403                        }
1404                        _ => return self.unsupported(dot),
1405                    }
1406                }
1407                // `SliceExpression <- '[' SliceBound ']'`, one index or a range.
1408                "SliceExpression" => {
1409                    let bound = self.first(inner);
1410                    let has_end = self.find(bound, "EndSliceBound") != NONE;
1411                    let has_step = self.find(bound, "StepSliceBound") != NONE;
1412                    if has_end || has_step {
1413                        return self.unsupported(inner);
1414                    }
1415                    let index = self.expr(self.first(bound))?;
1416                    let name = self.function_name("array_extract");
1417                    let args = self.expr_slice(vec![expr, index]);
1418                    self.push(Expr::Function { name, args, distinct: false })
1419                }
1420                // `PostfixOperator <- '!'`.
1421                "PostfixOperator" => {
1422                    self.push(Expr::Unary { op: UnaryOp::Factorial, operand: expr })
1423                }
1424                _ => return self.unsupported(inner),
1425            };
1426        }
1427        Ok(expr)
1428    }
1429
1430    /// A one part function name, for the calls the transformer invents rather than reads.
1431    fn function_name(&mut self, name: &str) -> Slice {
1432        let interned = self.intern(name);
1433        self.part_slice(vec![interned])
1434    }
1435
1436    /// `StarExpression <- StarQualifierList? '*' ExcludeList? ReplaceList? RenameList?`.
1437    fn star(&mut self, node: u32) -> Result<ExprRef> {
1438        for name in ["ExcludeList", "ReplaceList", "RenameList"] {
1439            let list = self.find(node, name);
1440            if list != NONE {
1441                return self.unsupported(list);
1442            }
1443        }
1444        let qualifier = self.find(node, "StarQualifierList");
1445        let qualifier =
1446            if qualifier == NONE { Slice::default() } else { self.name_parts(qualifier) };
1447        Ok(self.push(Expr::Star { qualifier }))
1448    }
1449
1450    /// `FunctionExpression <- FunctionIdentifier FunctionExpressionArguments WithinGroupClause?
1451    /// FilterClause? ExportClause? OverClause?`.
1452    fn function(&mut self, node: u32) -> Result<ExprRef> {
1453        for name in ["WithinGroupClause", "FilterClause", "ExportClause", "OverClause"] {
1454            let clause = self.find(node, name);
1455            if clause != NONE {
1456                return self.unsupported(clause);
1457            }
1458        }
1459        let name = self.name_parts(self.first(node));
1460        // `FunctionExpressionArguments <- Parens(FunctionExpressionArgumentList)` and
1461        // `FunctionExpressionArgumentList <- DistinctOrAll? FunctionArgumentList? OrderByClause?
1462        // IgnoreOrRespectNulls?`, so a call with no arguments still has both wrappers.
1463        let list = self.first(self.nth(node, 1));
1464        for name in ["OrderByClause", "IgnoreOrRespectNulls"] {
1465            let clause = self.find(list, name);
1466            if clause != NONE {
1467                return self.unsupported(clause);
1468            }
1469        }
1470        let distinct = self.quantifier(self.find(list, "DistinctOrAll")) == Quantifier::Distinct;
1471        let mut args = Vec::new();
1472        let arguments = self.find(list, "FunctionArgumentList");
1473        if arguments != NONE {
1474            for kid in self.kids(arguments) {
1475                args.push(self.argument(kid)?);
1476            }
1477        }
1478        let args = self.expr_slice(args);
1479        Ok(self.push(Expr::Function { name, args, distinct }))
1480    }
1481
1482    /// `FunctionArgument <- NamedFunctionArgument / PositionalFunctionArgument`.
1483    fn argument(&mut self, node: u32) -> Result<ExprRef> {
1484        let inner = self.first(node);
1485        match self.name(inner) {
1486            "PositionalFunctionArgument" => self.expr(self.first(inner)),
1487            _ => self.unsupported(inner),
1488        }
1489    }
1490
1491    /// `CastExpression <- CastOrTryCast Parens(CastArguments)`.
1492    fn cast(&mut self, node: u32) -> Result<ExprRef> {
1493        let try_cast = self.name(self.first(self.first(node))) == "TryCastKeyword";
1494        // `CastArguments <- Expression 'AS' Type`.
1495        let arguments = self.nth(node, 1);
1496        let operand = self.expr(self.first(arguments))?;
1497        let text = self.text(self.nth(arguments, 1)).to_string();
1498        let ty = self.intern(&text);
1499        Ok(self.push(Expr::Cast { operand, ty, try_cast }))
1500    }
1501
1502    /// `CaseExpression <- 'CASE' Expression? CaseWhenThen+ CaseElse? 'END'`.
1503    fn case(&mut self, node: u32) -> Result<ExprRef> {
1504        let mut operand = NONE;
1505        let mut arms = Vec::new();
1506        let mut otherwise = NONE;
1507        for kid in self.kids(node) {
1508            match self.name(kid) {
1509                // `CaseWhenThen <- 'WHEN' Expression 'THEN' Expression`.
1510                "CaseWhenThen" => {
1511                    let when = self.expr(self.first(kid))?;
1512                    let then = self.expr(self.nth(kid, 1))?;
1513                    arms.push(CaseArm { when, then });
1514                }
1515                // `CaseElse <- 'ELSE' Expression`.
1516                "CaseElse" => otherwise = self.expr(self.first(kid))?,
1517                // The bare `Expression` before the first `WHEN`, which makes it a simple case.
1518                _ => operand = self.expr(kid)?,
1519            }
1520        }
1521        let start = self.ast.case_arms.len() as u32;
1522        self.ast.case_arms.extend(arms);
1523        let arms = Slice { start, len: self.ast.case_arms.len() as u32 - start };
1524        Ok(self.push(Expr::Case { operand, arms, otherwise }))
1525    }
1526
1527    /// `ParenthesisExpression <- Parens(List(Expression)?)`, which is a row value.
1528    ///
1529    /// One item is not a row. `(a)` is `a` in every dialect and reading it as a one column row
1530    /// would change what `(a) = (b)` means.
1531    fn row(&mut self, node: u32) -> Result<ExprRef> {
1532        let mut items = Vec::new();
1533        for kid in self.kids(node) {
1534            items.push(self.expr(kid)?);
1535        }
1536        if items.len() == 1 {
1537            return Ok(items[0]);
1538        }
1539        let items = self.expr_slice(items);
1540        Ok(self.push(Expr::Row { items }))
1541    }
1542
1543    /// `SubqueryExpression <- SubqueryNot? SubqueryExists? SubqueryReference`.
1544    fn subquery(&mut self, node: u32) -> Result<ExprRef> {
1545        if self.find(node, "SubqueryNot") != NONE || self.find(node, "SubqueryExists") != NONE {
1546            return self.unsupported(node);
1547        }
1548        let reference = self.find(node, "SubqueryReference");
1549        let query = self.query(self.first(reference))?;
1550        Ok(self.push(Expr::Subquery { query }))
1551    }
1552
1553    /// The value of a string literal, with the quotes gone and the escapes resolved.
1554    ///
1555    /// A literal can be several tokens. `'a' 'b'` on two lines is one literal that is `ab`, which is
1556    /// the SQL standard's rule and DuckDB's, so the node is decoded token by token rather than by
1557    /// taking its text and stripping the outside.
1558    fn string_value(&self, node: u32) -> String {
1559        let span = self.tree.node(node);
1560        let mut value = String::new();
1561        for token in &self.tokens[span.start as usize..span.end as usize] {
1562            if token.kind != Kind::String {
1563                continue;
1564            }
1565            let text = token.text(self.query);
1566            match text.strip_prefix('\'').and_then(|rest| rest.strip_suffix('\'')) {
1567                Some(body) => value.push_str(&body.replace("''", "'")),
1568                None => value.push_str(text),
1569            }
1570        }
1571        value
1572    }
1573}
1574
1575/// Strip the quoting off an identifier.
1576///
1577/// DuckDB does not fold identifier case at any point, quoted or not, so this only removes the
1578/// quotes and resolves the doubled ones. Anything else would be the parser deciding what a name is.
1579fn unquote(text: &str) -> String {
1580    match text.strip_prefix('"').and_then(|rest| rest.strip_suffix('"')) {
1581        Some(body) => body.replace("\"\"", "\""),
1582        None => text.to_string(),
1583    }
1584}
1585
1586#[cfg(test)]
1587mod tests {
1588    use super::*;
1589    use crate::corpus::CORPUS;
1590    use crate::matcher::parse;
1591
1592    /// The AST written back out as text, which is what the assertions below read.
1593    ///
1594    /// Not a SQL printer and not trying to be. It is deliberately not valid SQL: operators are
1595    /// spelled with the name of the variant and every binary node is parenthesised, so that a test
1596    /// asserting on this text is asserting on the shape of the tree and not on a formatting choice.
1597    /// `a - b - c` and `a - (b - c)` have to look different here or the test that tells them apart
1598    /// is not a test.
1599    fn show(ast: &Ast, expr: ExprRef) -> String {
1600        if expr == NONE {
1601            return "-".to_string();
1602        }
1603        let list = |slice: Slice| {
1604            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
1605        };
1606        match ast.expr(expr) {
1607            Expr::Star { qualifier } if qualifier.is_empty() => "*".to_string(),
1608            Expr::Star { qualifier } => format!("{}.*", ast.name_text(qualifier)),
1609            Expr::Column { name } => ast.name_text(name),
1610            Expr::Literal { kind, text } => match kind {
1611                LiteralKind::Number => ast.string(text).to_string(),
1612                LiteralKind::String => format!("'{}'", ast.string(text)),
1613                other => format!("{other:?}").to_uppercase(),
1614            },
1615            Expr::Unary { op, operand } => format!("({op:?} {})", show(ast, operand)),
1616            Expr::Binary { op, left, right } => {
1617                let op = match op {
1618                    BinaryOp::Named(name) => ast.string(name).to_string(),
1619                    other => format!("{other:?}"),
1620                };
1621                format!("({} {op} {})", show(ast, left), show(ast, right))
1622            }
1623            Expr::Function { name, args, distinct } => {
1624                let distinct = if distinct { "DISTINCT " } else { "" };
1625                format!("{}({distinct}{})", ast.name_text(name), list(args))
1626            }
1627            Expr::Cast { operand, ty, try_cast } => {
1628                let word = if try_cast { "TRY_CAST" } else { "CAST" };
1629                format!("{word}({} AS {})", show(ast, operand), ast.string(ty))
1630            }
1631            Expr::Case { operand, arms, otherwise } => {
1632                let arms = ast
1633                    .arm_list(arms)
1634                    .iter()
1635                    .map(|arm| format!("WHEN {} THEN {}", show(ast, arm.when), show(ast, arm.then)))
1636                    .collect::<Vec<_>>()
1637                    .join(" ");
1638                format!("CASE {} {arms} ELSE {} END", show(ast, operand), show(ast, otherwise))
1639            }
1640            Expr::Between { operand, low, high, negated } => {
1641                let not = if negated { "NOT " } else { "" };
1642                format!(
1643                    "({not}{} BETWEEN {} AND {})",
1644                    show(ast, operand),
1645                    show(ast, low),
1646                    show(ast, high)
1647                )
1648            }
1649            Expr::In { operand, list: items, negated } => {
1650                let not = if negated { "NOT " } else { "" };
1651                format!("({not}{} IN [{}])", show(ast, operand), list(items))
1652            }
1653            Expr::Row { items } => format!("ROW({})", list(items)),
1654            Expr::Subquery { query } => format!("({})", show_query(ast, query)),
1655        }
1656    }
1657
1658    /// One from item written back out.
1659    fn show_source(ast: &Ast, source: SourceRef) -> String {
1660        let alias = |alias: StrRef| match alias {
1661            NONE => String::new(),
1662            other => format!(" AS {}", ast.string(other)),
1663        };
1664        match ast.source(source) {
1665            Source::Table { name, alias: name_alias, .. } => {
1666                format!("{}{}", ast.name_text(name), alias(name_alias))
1667            }
1668            Source::Function { name, args, alias: call_alias, .. } => {
1669                let args = ast
1670                    .expr_list(args)
1671                    .iter()
1672                    .map(|&item| show(ast, item))
1673                    .collect::<Vec<_>>()
1674                    .join(", ");
1675                format!("{}({args}){}", ast.name_text(name), alias(call_alias))
1676            }
1677            Source::Subquery { query, alias: query_alias, .. } => {
1678                format!("({}){}", show_query(ast, query), alias(query_alias))
1679            }
1680            Source::Values { rows, alias: values_alias, .. } => {
1681                format!("{}{}", show_rows(ast, rows), alias(values_alias))
1682            }
1683            Source::Join { left, right, kind, natural, on, using } => {
1684                let natural = if natural { "NATURAL " } else { "" };
1685                let on = if on == NONE { String::new() } else { format!(" ON {}", show(ast, on)) };
1686                let using = if using.is_empty() {
1687                    String::new()
1688                } else {
1689                    format!(" USING ({})", ast.name_text(using))
1690                };
1691                format!(
1692                    "({} {natural}{kind:?} JOIN {}{on}{using})",
1693                    show_source(ast, left),
1694                    show_source(ast, right)
1695                )
1696            }
1697        }
1698    }
1699
1700    /// The rows of a `VALUES` written back out.
1701    fn show_rows(ast: &Ast, rows: Slice) -> String {
1702        let rows = ast
1703            .rows(rows)
1704            .iter()
1705            .map(|&row| {
1706                let items = ast
1707                    .expr_list(row)
1708                    .iter()
1709                    .map(|&item| show(ast, item))
1710                    .collect::<Vec<_>>()
1711                    .join(", ");
1712                format!("({items})")
1713            })
1714            .collect::<Vec<_>>()
1715            .join(", ");
1716        format!("VALUES {rows}")
1717    }
1718
1719    /// One query written back out.
1720    fn show_query(ast: &Ast, index: QueryRef) -> String {
1721        let query = ast.query(index);
1722        let list = |slice: Slice| {
1723            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
1724        };
1725        let mut out = match query.body {
1726            QueryBody::SetOp { op, quantifier, by_name, left, right } => {
1727                let by_name = if by_name { " BY NAME" } else { "" };
1728                format!(
1729                    "({} {op:?} {quantifier:?}{by_name} {})",
1730                    show_query(ast, left),
1731                    show_query(ast, right)
1732                )
1733            }
1734            QueryBody::Select(index) => {
1735                let select = ast.select(index);
1736                let distinct = match select.distinct {
1737                    Distinct::No => String::new(),
1738                    Distinct::Yes => " DISTINCT".to_string(),
1739                    Distinct::On(on) => format!(" DISTINCT ON ({})", list(on)),
1740                };
1741                let targets = ast
1742                    .target_list(select.targets)
1743                    .iter()
1744                    .map(|target| match target.alias {
1745                        NONE => show(ast, target.expr),
1746                        alias => format!("{} AS {}", show(ast, target.expr), ast.string(alias)),
1747                    })
1748                    .collect::<Vec<_>>()
1749                    .join(", ");
1750                let mut out = format!("SELECT{distinct} {targets}");
1751                if !select.from.is_empty() {
1752                    let from = ast
1753                        .source_list(select.from)
1754                        .iter()
1755                        .map(|&source| show_source(ast, source))
1756                        .collect::<Vec<_>>()
1757                        .join(", ");
1758                    out += &format!(" FROM {from}");
1759                }
1760                if select.filter != NONE {
1761                    out += &format!(" WHERE {}", show(ast, select.filter));
1762                }
1763                if select.group_by_all {
1764                    out += " GROUP BY ALL";
1765                } else if !select.group_by.is_empty() {
1766                    out += &format!(" GROUP BY {}", list(select.group_by));
1767                }
1768                if select.having != NONE {
1769                    out += &format!(" HAVING {}", show(ast, select.having));
1770                }
1771                out
1772            }
1773            QueryBody::Values(rows) => show_rows(ast, rows),
1774        };
1775        if query.order_by_all {
1776            out += " ORDER BY ALL";
1777        } else if !query.order_by.is_empty() {
1778            let items = ast
1779                .order_list(query.order_by)
1780                .iter()
1781                .map(|item| format!("{} {:?} {:?}", show(ast, item.expr), item.order, item.nulls))
1782                .collect::<Vec<_>>()
1783                .join(", ");
1784            out += &format!(" ORDER BY {items}");
1785        }
1786        if query.limit != NONE {
1787            let percent = if query.limit_percent { "%" } else { "" };
1788            out += &format!(" LIMIT {}{percent}", show(ast, query.limit));
1789        }
1790        if query.offset != NONE {
1791            out += &format!(" OFFSET {}", show(ast, query.offset));
1792        }
1793        out
1794    }
1795
1796    /// One statement, transformed and written back out.
1797    fn round(query: &str) -> String {
1798        let ast = parse_ast(query).unwrap_or_else(|error| panic!("{query}: {error}"));
1799        assert_eq!(ast.statements.len(), 1, "{query} is one statement");
1800        let Statement::Query(index) = ast.statements[0] else {
1801            panic!("{query} is not a query");
1802        };
1803        show_query(&ast, index)
1804    }
1805
1806    /// One statement, transformed and written back out as the DDL and DML shape it is.
1807    fn round_statement(query: &str) -> String {
1808        let ast = parse_ast(query).unwrap_or_else(|error| panic!("{query}: {error}"));
1809        assert_eq!(ast.statements.len(), 1, "{query} is one statement");
1810        match ast.statements[0] {
1811            Statement::Query(index) => show_query(&ast, index),
1812            Statement::CreateTable(index) => {
1813                let create = ast.create_table(index);
1814                let mut out = "CREATE".to_string();
1815                if create.or_replace {
1816                    out += " OR REPLACE";
1817                }
1818                if create.temporary {
1819                    out += " TEMPORARY";
1820                }
1821                out += " TABLE";
1822                if create.if_not_exists {
1823                    out += " IF NOT EXISTS";
1824                }
1825                out += &format!(" {}", ast.name_text(create.name));
1826                let columns = ast
1827                    .column_defs(create.columns)
1828                    .iter()
1829                    .map(|def| {
1830                        let ty = match def.ty {
1831                            NONE => String::new(),
1832                            other => format!(" {}", ast.string(other)),
1833                        };
1834                        let null = if def.not_null { " NOT NULL" } else { "" };
1835                        format!("{}{ty}{null}", ast.string(def.name))
1836                    })
1837                    .collect::<Vec<_>>()
1838                    .join(", ");
1839                if !columns.is_empty() || create.query == NONE {
1840                    out += &format!(" ({columns})");
1841                }
1842                if create.query != NONE {
1843                    out += &format!(" AS {}", show_query(&ast, create.query));
1844                }
1845                out
1846            }
1847            Statement::DropTable(index) => {
1848                let drop = ast.drop_table(index);
1849                let mut out = "DROP TABLE".to_string();
1850                if drop.if_exists {
1851                    out += " IF EXISTS";
1852                }
1853                let names = ast
1854                    .name_list(drop.names)
1855                    .iter()
1856                    .map(|&name| ast.name_text(name))
1857                    .collect::<Vec<_>>()
1858                    .join(", ");
1859                out + &format!(" {names}")
1860            }
1861            Statement::Insert(index) => {
1862                let insert = ast.insert(index);
1863                let mut out = format!("INSERT INTO {}", ast.name_text(insert.name));
1864                if !insert.columns.is_empty() {
1865                    let columns = ast.name(insert.columns).collect::<Vec<_>>().join(", ");
1866                    out += &format!(" ({columns})");
1867                }
1868                out + &format!(" {}", show_query(&ast, insert.source))
1869            }
1870        }
1871    }
1872
1873    #[test]
1874    fn the_query_m0_has_to_run_transforms() {
1875        assert_eq!(round("SELECT * FROM t WHERE x > 5"), "SELECT * FROM t WHERE (x Gt 5)");
1876    }
1877
1878    #[test]
1879    fn a_create_table_keeps_its_types_as_text() {
1880        assert_eq!(
1881            round_statement("CREATE TABLE t (a INTEGER, b VARCHAR NOT NULL)"),
1882            "CREATE TABLE t (a INTEGER, b VARCHAR NOT NULL)"
1883        );
1884        // The type is the text between the identifier and whatever follows it, parentheses and
1885        // all, because resolving `DECIMAL(18, 3)` into a width and a scale is the binder's job and
1886        // doing it here would mean two places that know the type table.
1887        assert_eq!(
1888            round_statement("CREATE TABLE t (a DECIMAL(18, 3), b STRUCT(x INT))"),
1889            "CREATE TABLE t (a DECIMAL(18, 3), b STRUCT(x INT))"
1890        );
1891    }
1892
1893    #[test]
1894    fn the_three_modifiers_on_a_create_table_survive() {
1895        assert_eq!(
1896            round_statement("CREATE OR REPLACE TEMPORARY TABLE IF NOT EXISTS s.t (a INT)"),
1897            "CREATE OR REPLACE TEMPORARY TABLE IF NOT EXISTS s.t (a INT)"
1898        );
1899    }
1900
1901    #[test]
1902    fn a_create_table_as_carries_the_query_and_not_the_types() {
1903        assert_eq!(
1904            round_statement("CREATE TABLE t AS SELECT a FROM u"),
1905            "CREATE TABLE t AS SELECT a FROM u"
1906        );
1907        // The names are the syntax's to say and the types are the query's, so the column
1908        // definitions here have names and no types.
1909        assert_eq!(
1910            round_statement("CREATE TABLE t (x, y) AS SELECT a, b FROM u"),
1911            "CREATE TABLE t (x, y) AS SELECT a, b FROM u"
1912        );
1913    }
1914
1915    #[test]
1916    fn a_drop_table_is_a_list_of_qualified_names() {
1917        assert_eq!(round_statement("DROP TABLE t"), "DROP TABLE t");
1918        assert_eq!(round_statement("DROP TABLE IF EXISTS a, b.c"), "DROP TABLE IF EXISTS a, b.c");
1919    }
1920
1921    #[test]
1922    fn dropping_something_that_is_not_a_table_is_refused() {
1923        // `TableOrView` covers `VIEW` and `MATERIALIZED VIEW` as well, and a view dropped as if it
1924        // were a table is a wrong answer rather than a missing feature.
1925        let error = parse_ast("DROP VIEW v").unwrap_err().to_string();
1926        assert!(error.starts_with("Not implemented Error"), "{error}");
1927    }
1928
1929    #[test]
1930    fn both_spellings_of_insert_arrive_at_a_query() {
1931        assert_eq!(
1932            round_statement("INSERT INTO t VALUES (1, 'a'), (2, 'b')"),
1933            "INSERT INTO t VALUES (1, 'a'), (2, 'b')"
1934        );
1935        assert_eq!(
1936            round_statement("INSERT INTO t (a, b) SELECT x, y FROM u"),
1937            "INSERT INTO t (a, b) SELECT x, y FROM u"
1938        );
1939    }
1940
1941    #[test]
1942    fn an_insert_clause_that_changes_the_answer_is_refused() {
1943        for query in [
1944            "INSERT INTO t VALUES (1) RETURNING *",
1945            "INSERT OR REPLACE INTO t VALUES (1)",
1946            "INSERT INTO t BY NAME SELECT 1 AS a",
1947            "INSERT INTO t VALUES (1) ON CONFLICT DO NOTHING",
1948            "INSERT INTO t DEFAULT VALUES",
1949        ] {
1950            let error = parse_ast(query).unwrap_err().to_string();
1951            assert!(error.starts_with("Not implemented Error"), "{query} gave {error}");
1952        }
1953    }
1954
1955    #[test]
1956    fn a_column_constraint_that_is_not_not_null_is_refused() {
1957        // Nothing enforces a constraint yet. Accepting one and not enforcing it is the wrong
1958        // answer, so `NOT NULL` is kept because the column already has a nullability and the rest
1959        // are refused until there is somewhere to put them.
1960        for query in [
1961            "CREATE TABLE t (a INT PRIMARY KEY)",
1962            "CREATE TABLE t (a INT UNIQUE)",
1963            "CREATE TABLE t (a INT CHECK (a > 0))",
1964            "CREATE TABLE t (a INT DEFAULT 1)",
1965            "CREATE TABLE t (a INT REFERENCES u (b))",
1966            "CREATE TABLE t (a INT, PRIMARY KEY (a))",
1967        ] {
1968            let error = parse_ast(query).unwrap_err().to_string();
1969            assert!(error.starts_with("Not implemented Error"), "{query} gave {error}");
1970        }
1971    }
1972
1973    #[test]
1974    fn values_is_a_query_on_its_own_and_in_a_from() {
1975        assert_eq!(round("VALUES (1), (2)"), "VALUES (1), (2)");
1976        // Parenthesised it is a subquery whose body is the values, and bare it is a `ValuesRef`.
1977        // Two rules and one meaning, which is the grammar's doing and not something to flatten
1978        // here, because the parenthesised form can carry an order by and the bare one cannot.
1979        assert_eq!(
1980            round("SELECT * FROM (VALUES (1, 2), (3, 4)) t(a, b)"),
1981            "SELECT * FROM (VALUES (1, 2), (3, 4)) AS t"
1982        );
1983        assert_eq!(
1984            round("SELECT * FROM VALUES (1, 2), (3, 4) AS t(a, b)"),
1985            "SELECT * FROM VALUES (1, 2), (3, 4) AS t"
1986        );
1987        // Rows of different widths parse. Saying so wants the column count, which for an insert is
1988        // the table's, so the check belongs to the binder and not here.
1989        assert_eq!(round("VALUES (1), (2, 3)"), "VALUES (1), (2, 3)");
1990    }
1991
1992    #[test]
1993    fn every_statement_in_the_corpus_gets_a_defined_answer() {
1994        // The point of the test is the word defined. Forty of these are statement kinds and
1995        // clauses this milestone does not cover, and the requirement is not that they work, it is
1996        // that they fail by saying so. A panic, a silently dropped clause or an internal error
1997        // would each be a different bug and all three would be invisible without this.
1998        let mut done = 0;
1999        for query in CORPUS {
2000            match parse_ast(query) {
2001                Ok(ast) => {
2002                    assert_eq!(ast.statements.len(), 1, "{query}");
2003                    done += 1;
2004                }
2005                Err(error) => {
2006                    let message = error.to_string();
2007                    assert!(
2008                        message.starts_with("Not implemented Error"),
2009                        "{query} failed with {message}, which is not a not-implemented error"
2010                    );
2011                }
2012            }
2013        }
2014        // Not an assertion about the right number. It is a ratchet: this only moves up, and the
2015        // day it moves down somebody has taken a construct out without meaning to.
2016        assert!(done >= 22, "only {done} of the corpus transforms, which is fewer than it was");
2017    }
2018
2019    #[test]
2020    fn the_ast_is_far_smaller_than_the_parse_tree() {
2021        let query = CORPUS[4];
2022        let tree = parse(query).unwrap();
2023        let ast = parse_ast(query).unwrap();
2024        // The twenty precedence levels are the difference. Every one of them is a node in the
2025        // parse tree for every expression at every depth, and none of them survives into the AST.
2026        assert!(
2027            ast.node_count() * 20 < tree.arena_len(),
2028            "{} ast nodes against {} parse nodes",
2029            ast.node_count(),
2030            tree.arena_len()
2031        );
2032    }
2033
2034    #[test]
2035    fn precedence_comes_out_of_the_chain_and_into_the_tree() {
2036        assert_eq!(round("SELECT 1 + 2 * 3"), "SELECT (1 Add (2 Multiply 3))");
2037        assert_eq!(round("SELECT (1 + 2) * 3"), "SELECT ((1 Add 2) Multiply 3)");
2038        assert_eq!(round("SELECT 1 + 2 + 3"), "SELECT ((1 Add 2) Add 3)");
2039        assert_eq!(round("SELECT 1 - 2 - 3"), "SELECT ((1 Subtract 2) Subtract 3)");
2040        assert_eq!(
2041            round("SELECT a OR b AND c"),
2042            "SELECT (a Or (b And c))",
2043            "and binds tighter than or"
2044        );
2045    }
2046
2047    #[test]
2048    fn a_double_negation_is_two_nodes_and_not_none() {
2049        // Folding it would be an optimizer decision and this is not the optimizer. It also would
2050        // not be safe in general: `NOT NOT x` on a null is still null and on a non boolean it is
2051        // still an error, and both of those have to survive to the binder to be reported.
2052        assert_eq!(round("SELECT NOT NOT a"), "SELECT (Not (Not a))");
2053    }
2054
2055    #[test]
2056    fn a_parenthesised_single_expression_is_not_a_row() {
2057        assert_eq!(round("SELECT (a)"), "SELECT a");
2058        assert_eq!(round("SELECT (a, b)"), "SELECT ROW(a, b)");
2059    }
2060
2061    #[test]
2062    fn the_three_ways_to_write_an_alias_all_arrive() {
2063        assert_eq!(round("SELECT a AS b"), "SELECT a AS b");
2064        assert_eq!(round("SELECT a b"), "SELECT a AS b");
2065        assert_eq!(round("SELECT b: a"), "SELECT a AS b");
2066        assert_eq!(round("SELECT a"), "SELECT a", "and no alias when none was written");
2067    }
2068
2069    #[test]
2070    fn a_from_with_no_select_selects_everything() {
2071        // DuckDB's own shorthand. Inventing the star here rather than in the binder means the
2072        // binder never has to know that the clause it is looking at was the one that was missing.
2073        assert_eq!(round("FROM t"), "SELECT * FROM t");
2074        assert_eq!(round("FROM t SELECT a"), "SELECT a FROM t");
2075    }
2076
2077    #[test]
2078    fn joins_nest_to_the_left() {
2079        assert_eq!(
2080            round("SELECT * FROM a JOIN b ON a.i = b.i LEFT JOIN c USING (k)"),
2081            "SELECT * FROM ((a Inner JOIN b ON (a.i Eq b.i)) Left JOIN c USING (k))"
2082        );
2083        assert_eq!(
2084            round("SELECT * FROM a NATURAL JOIN b"),
2085            "SELECT * FROM (a NATURAL Inner JOIN b)"
2086        );
2087        assert_eq!(round("SELECT * FROM a CROSS JOIN b"), "SELECT * FROM (a Cross JOIN b)");
2088        assert_eq!(
2089            round("SELECT * FROM a POSITIONAL JOIN b"),
2090            "SELECT * FROM (a Positional JOIN b)"
2091        );
2092        assert_eq!(round("SELECT * FROM a, b"), "SELECT * FROM a, b", "a comma is not a join node");
2093    }
2094
2095    #[test]
2096    fn a_qualified_name_keeps_its_parts_however_it_was_spelled() {
2097        // Five grammar rules can produce a column reference and they disagree about which
2098        // component is a schema and which is a table. None of that is decidable without the
2099        // catalog, so the AST holds the parts and the binder decides.
2100        assert_eq!(round("SELECT a"), "SELECT a");
2101        assert_eq!(round("SELECT t.a"), "SELECT t.a");
2102        assert_eq!(round("SELECT s.t.a"), "SELECT s.t.a");
2103        assert_eq!(round("SELECT c.s.t.a"), "SELECT c.s.t.a");
2104        assert_eq!(round("SELECT * FROM s.t"), "SELECT * FROM s.t");
2105    }
2106
2107    #[test]
2108    fn a_star_can_be_qualified() {
2109        assert_eq!(round("SELECT *"), "SELECT *");
2110        assert_eq!(round("SELECT t.*"), "SELECT t.*");
2111        assert_eq!(round("SELECT s.t.*"), "SELECT s.t.*");
2112    }
2113
2114    #[test]
2115    fn a_quoted_identifier_keeps_its_case_and_loses_its_quotes() {
2116        // DuckDB does not fold identifier case at any point, quoted or not, which the tokenizer
2117        // work established by reading the source. So the only thing to do here is take the quotes
2118        // off and resolve the doubled ones.
2119        let ast = parse_ast("SELECT \"Mixed Case\", \"a\"\"b\"").unwrap();
2120        assert_eq!(ast.strings[0], "Mixed Case");
2121        assert_eq!(ast.strings[1], "a\"b");
2122    }
2123
2124    #[test]
2125    fn a_string_literal_is_decoded_and_adjacent_ones_are_joined() {
2126        assert_eq!(round("SELECT 'it''s'"), "SELECT 'it's'");
2127        assert_eq!(round("SELECT 'a'\n'b'"), "SELECT 'ab'", "the standard's adjacency rule");
2128    }
2129
2130    #[test]
2131    fn the_null_and_boolean_tests_are_postfix_unary_operators() {
2132        assert_eq!(round("SELECT x IS NULL"), "SELECT (IsNull x)");
2133        assert_eq!(round("SELECT x IS NOT NULL"), "SELECT (IsNotNull x)");
2134        assert_eq!(round("SELECT x ISNULL"), "SELECT (IsNull x)");
2135        assert_eq!(round("SELECT x NOTNULL"), "SELECT (IsNotNull x)");
2136        assert_eq!(round("SELECT x IS TRUE"), "SELECT (IsTrue x)");
2137        assert_eq!(round("SELECT x IS NOT FALSE"), "SELECT (IsNotFalse x)");
2138        assert_eq!(round("SELECT x IS DISTINCT FROM y"), "SELECT (x IsDistinctFrom y)");
2139        assert_eq!(round("SELECT x IS NOT DISTINCT FROM y"), "SELECT (x IsNotDistinctFrom y)");
2140    }
2141
2142    #[test]
2143    fn the_like_family_folds_its_negation_into_the_operator() {
2144        assert_eq!(round("SELECT x LIKE 'a'"), "SELECT (x Like 'a')");
2145        assert_eq!(round("SELECT x NOT LIKE 'a'"), "SELECT (x NotLike 'a')");
2146        assert_eq!(round("SELECT x ILIKE 'a'"), "SELECT (x ILike 'a')");
2147        assert_eq!(round("SELECT x ~~ 'a'"), "SELECT (x Like 'a')", "the operator spelling");
2148        assert_eq!(round("SELECT x !~~ 'a'"), "SELECT (x NotLike 'a')");
2149        assert_eq!(round("SELECT x SIMILAR TO 'a'"), "SELECT (x SimilarTo 'a')");
2150        // Glob has no negated operator to fold into, so the negation stays where it was written.
2151        assert_eq!(round("SELECT x NOT GLOB 'a'"), "SELECT (Not (x Glob 'a'))");
2152    }
2153
2154    #[test]
2155    fn between_and_in_carry_their_negation_as_a_flag() {
2156        assert_eq!(round("SELECT x BETWEEN 1 AND 2"), "SELECT (x BETWEEN 1 AND 2)");
2157        assert_eq!(round("SELECT x NOT BETWEEN 1 AND 2"), "SELECT (NOT x BETWEEN 1 AND 2)");
2158        assert_eq!(round("SELECT x IN (1, 2)"), "SELECT (x IN [1, 2])");
2159        assert_eq!(round("SELECT x NOT IN (1, 2)"), "SELECT (NOT x IN [1, 2])");
2160    }
2161
2162    #[test]
2163    fn both_spellings_of_a_cast_are_the_same_node() {
2164        assert_eq!(round("SELECT CAST(x AS BIGINT)"), "SELECT CAST(x AS BIGINT)");
2165        assert_eq!(round("SELECT x::BIGINT"), "SELECT CAST(x AS BIGINT)");
2166        assert_eq!(round("SELECT TRY_CAST(x AS BIGINT)"), "SELECT TRY_CAST(x AS BIGINT)");
2167        assert_eq!(
2168            round("SELECT x::DECIMAL(18, 3)"),
2169            "SELECT CAST(x AS DECIMAL(18, 3))",
2170            "the type is kept as text because parsing it is the type system's job"
2171        );
2172    }
2173
2174    #[test]
2175    fn a_case_keeps_its_arms_in_order() {
2176        assert_eq!(
2177            round("SELECT CASE WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"),
2178            "SELECT CASE - WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"
2179        );
2180        assert_eq!(
2181            round("SELECT CASE x WHEN 1 THEN 'a' END"),
2182            "SELECT CASE x WHEN 1 THEN 'a' ELSE - END",
2183            "a simple case keeps the operand and a missing else is not an implicit null yet"
2184        );
2185    }
2186
2187    #[test]
2188    fn a_field_access_and_a_method_call_are_ordinary_function_calls() {
2189        // Which is what DuckDB makes of them too. Giving each its own AST node would mean the
2190        // binder needs a rule for something the function resolver already handles.
2191        assert_eq!(round("SELECT (f(x)).y"), "SELECT struct_extract(f(x), 'y')");
2192        assert_eq!(round("SELECT a[1]"), "SELECT array_extract(a, 1)");
2193    }
2194
2195    #[test]
2196    fn an_aggregate_keeps_its_distinct() {
2197        assert_eq!(round("SELECT count(*)"), "SELECT count(*)");
2198        assert_eq!(round("SELECT count(DISTINCT x)"), "SELECT count(DISTINCT x)");
2199        assert_eq!(round("SELECT count(ALL x)"), "SELECT count(x)");
2200        assert_eq!(round("SELECT main.count(x)"), "SELECT main.count(x)");
2201    }
2202
2203    #[test]
2204    fn the_modifiers_hang_off_the_query_and_not_off_the_select() {
2205        // `a UNION b ORDER BY x` sorts the union. Putting the order by on the select would have
2206        // made that unrepresentable, which is why the grammar puts it outside the chain and why
2207        // the AST follows.
2208        assert_eq!(
2209            round("SELECT 1 UNION ALL SELECT 2 ORDER BY 1"),
2210            "(SELECT 1 Union All SELECT 2) ORDER BY 1 Unstated Unstated"
2211        );
2212        assert_eq!(
2213            round("SELECT a FROM t UNION SELECT b FROM u EXCEPT SELECT c FROM v"),
2214            "((SELECT a FROM t Union Unstated SELECT b FROM u) Except Unstated SELECT c FROM v)",
2215            "set operators are left associative"
2216        );
2217        assert_eq!(
2218            round("SELECT 1 UNION SELECT 2 INTERSECT SELECT 3"),
2219            "(SELECT 1 Union Unstated (SELECT 2 Intersect Unstated SELECT 3))",
2220            "and intersect binds tighter than the other two"
2221        );
2222    }
2223
2224    #[test]
2225    fn the_sort_and_limit_clauses_keep_what_was_written() {
2226        assert_eq!(
2227            round("SELECT a FROM t ORDER BY a"),
2228            "SELECT a FROM t ORDER BY a Unstated Unstated"
2229        );
2230        assert_eq!(
2231            round("SELECT a FROM t ORDER BY a DESC NULLS LAST"),
2232            "SELECT a FROM t ORDER BY a Descending Last"
2233        );
2234        assert_eq!(round("SELECT a FROM t ORDER BY ALL"), "SELECT a FROM t ORDER BY ALL");
2235        assert_eq!(round("SELECT a FROM t GROUP BY ALL"), "SELECT a FROM t GROUP BY ALL");
2236        assert_eq!(round("SELECT a FROM t LIMIT 10 OFFSET 5"), "SELECT a FROM t LIMIT 10 OFFSET 5");
2237        assert_eq!(round("SELECT a FROM t OFFSET 5 LIMIT 10"), "SELECT a FROM t LIMIT 10 OFFSET 5");
2238        assert_eq!(round("SELECT a FROM t LIMIT 10%"), "SELECT a FROM t LIMIT 10%");
2239        assert_eq!(round("SELECT a FROM t LIMIT ALL"), "SELECT a FROM t", "which is no limit");
2240    }
2241
2242    #[test]
2243    fn a_subquery_appears_in_both_places_it_can() {
2244        assert_eq!(
2245            round("SELECT * FROM (SELECT x FROM t) AS s"),
2246            "SELECT * FROM (SELECT x FROM t) AS s"
2247        );
2248        assert_eq!(round("SELECT (SELECT 1)"), "SELECT (SELECT 1)");
2249    }
2250
2251    #[test]
2252    fn distinct_on_keeps_its_expressions() {
2253        assert_eq!(round("SELECT DISTINCT a"), "SELECT DISTINCT a");
2254        assert_eq!(round("SELECT ALL a"), "SELECT a", "which is the default written out");
2255        assert_eq!(round("SELECT DISTINCT ON (a, b) a"), "SELECT DISTINCT ON (a, b) a");
2256    }
2257
2258    #[test]
2259    fn an_operator_the_dialect_does_not_name_is_kept_by_name() {
2260        // The grammar text says `OperatorLiteral <- Identifier`, which reads as though any bare
2261        // word could be written infix. It cannot. That rule is one of the 24 the matcher overrides
2262        // and it is overridden to the bare operator matcher, so what it takes is a run of operator
2263        // characters. Believing the body here would have produced a transformer that accepted
2264        // `a foo b`, which DuckDB rejects.
2265        assert_eq!(round("SELECT a <=> b"), "SELECT (a <=> b)");
2266        assert!(parse_ast("SELECT a foo b").is_err(), "a bare word is not an operator");
2267    }
2268
2269    #[test]
2270    fn a_script_is_a_list_of_statements() {
2271        let ast = parse_ast("SELECT 1; SELECT 2;").unwrap();
2272        assert_eq!(ast.statements.len(), 2);
2273        // A trailing semicolon makes an empty top level statement in the parse tree, because the
2274        // grammar's `Statement? (';'+ / EndOfInput)` is happy with nothing on both sides. It is
2275        // dropped here rather than pretended away in the matcher.
2276        let Statement::Query(second) = ast.statements[1] else {
2277            panic!("the second statement is a query");
2278        };
2279        assert_eq!(show_query(&ast, second), "SELECT 2");
2280    }
2281
2282    #[test]
2283    fn an_unsupported_construct_names_itself_and_what_was_written() {
2284        let error = parse_ast("ALTER TABLE t ADD COLUMN a INTEGER").unwrap_err().to_string();
2285        assert!(error.starts_with("Not implemented Error"), "{error}");
2286        assert!(error.contains("ALTER TABLE t ADD COLUMN a INTEGER"), "{error}");
2287        assert!(error.contains("AlterStatement"), "{error}");
2288    }
2289
2290    #[test]
2291    fn a_long_construct_is_cut_short_in_the_message() {
2292        let query = format!("ALTER TABLE t ADD COLUMN {} INTEGER", "a".repeat(80));
2293        let error = parse_ast(&query).unwrap_err().to_string();
2294        assert!(error.contains("..."), "{error}");
2295        assert!(error.len() < 200, "{error}");
2296    }
2297
2298    #[test]
2299    fn the_transformer_never_panics_on_anything_the_matcher_accepts() {
2300        // The matcher accepts a good deal that means nothing, because the grammar does. Every one
2301        // of these parses and none of them is a statement this milestone covers, and the contract
2302        // is that the answer is an error either way.
2303        for query in [
2304            "SELECT",
2305            "FROM t SELECT",
2306            "SELECT * FROM t WHERE",
2307            "SELECT ()",
2308            "SELECT a FROM t GROUP BY ()",
2309        ] {
2310            let answer = parse_ast(query);
2311            if let Err(error) = answer {
2312                let message = error.to_string();
2313                assert!(
2314                    message.starts_with("Not implemented Error")
2315                        || message.starts_with("Parser Error"),
2316                    "{query} failed with {message}"
2317                );
2318            }
2319        }
2320    }
2321
2322    #[test]
2323    fn a_function_call_in_a_from_clause_is_a_source_and_not_an_expression() {
2324        assert_eq!(round("SELECT * FROM range(3)"), "SELECT * FROM range(3)");
2325        assert_eq!(round("SELECT * FROM range(1, 10, 2)"), "SELECT * FROM range(1, 10, 2)");
2326        assert_eq!(round("SELECT * FROM main.range(3)"), "SELECT * FROM main.range(3)");
2327        assert_eq!(round("SELECT * FROM range(3) AS t"), "SELECT * FROM range(3) AS t");
2328        // The grammar allows a call with no arguments here and the transformer keeps it, because
2329        // whether a particular function takes none is the binder's question and not this one's.
2330        assert_eq!(round("SELECT * FROM some_function()"), "SELECT * FROM some_function()");
2331    }
2332
2333    #[test]
2334    fn the_forms_of_a_table_function_this_does_not_cover_are_turned_away_by_name() {
2335        for query in [
2336            "SELECT * FROM range(3) WITH ORDINALITY",
2337            "SELECT * FROM LATERAL range(3)",
2338            "SELECT * FROM t: range(3)",
2339        ] {
2340            let error = parse_ast(query).unwrap_err().to_string();
2341            assert!(error.contains("grammar rule"), "{query} failed with {error}");
2342        }
2343    }
2344
2345    #[test]
2346    fn interning_means_a_name_written_twice_is_stored_once() {
2347        let ast = parse_ast("SELECT a, a, a FROM t WHERE a = a").unwrap();
2348        assert_eq!(ast.strings.iter().filter(|text| *text == "a").count(), 1);
2349    }
2350}