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