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