Skip to main content

rudb_parse/
transform.rs

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