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