Skip to main content

rudb_parse/
transform.rs

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