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