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