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, Distinct, Expr, ExprRef, JoinKind, LiteralKind, Nulls, Order,
26    OrderItem, Quantifier, Query, QueryBody, QueryRef, Select, SelectRef, SetOp, Slice, Source,
27    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 =
48        Transform { query, tokens, tree, ast: Ast::default(), interned: HashMap::new() };
49    transform.program(tree.root())?;
50    Ok(transform.ast)
51}
52
53struct Transform<'a> {
54    query: &'a str,
55    tokens: &'a [Token],
56    tree: &'a Tree,
57    ast: Ast,
58    interned: HashMap<String, StrRef>,
59}
60
61impl<'a> Transform<'a> {
62    // The parts that walk the parse tree without caring what it says.
63
64    /// The text a node covers.
65    fn text(&self, node: u32) -> &'a str {
66        self.tree.text(node, self.query, self.tokens)
67    }
68
69    /// The name of the rule a node is.
70    fn name(&self, node: u32) -> &'static str {
71        self.tree.name(node)
72    }
73
74    /// The children of a node.
75    ///
76    /// Returned with the tree's lifetime rather than the borrow of `self`, so that the caller can
77    /// iterate it while calling the `&mut self` methods that build the arena. Copying the `&Tree`
78    /// out first is what buys that, and it is why every walker here starts by doing so.
79    fn kids(&self, node: u32) -> impl Iterator<Item = u32> + use<'a> {
80        let tree = self.tree;
81        tree.children(node)
82    }
83
84    /// How many children a node has.
85    fn count(&self, node: u32) -> usize {
86        self.kids(node).count()
87    }
88
89    /// The n'th child, or `NONE`.
90    fn nth(&self, node: u32, n: usize) -> u32 {
91        self.kids(node).nth(n).unwrap_or(NONE)
92    }
93
94    /// The first child, or `NONE`.
95    fn first(&self, node: u32) -> u32 {
96        self.nth(node, 0)
97    }
98
99    /// The first child named `name`, or `NONE`.
100    ///
101    /// Optional parts of a sequence do not leave a placeholder behind, so `SimpleSelect` with a
102    /// `WHERE` and no `GROUP BY` has the where clause as its second child and a `SimpleSelect` with
103    /// neither has something else there. Positional indexing into an optional sequence is the
104    /// single easiest way to write a transformer that is subtly wrong, so nothing here does it.
105    fn find(&self, node: u32, name: &str) -> u32 {
106        self.kids(node).find(|&kid| self.name(kid) == name).unwrap_or(NONE)
107    }
108
109    /// Every leaf of a subtree, in order.
110    ///
111    /// A leaf is a rule that matched only terminals, which for a name is the identifier itself. It
112    /// is how all thirty odd spellings of a qualified name collapse into one walk: whether the
113    /// parse said `SchemaQualification ReservedTableQualification ReservedColumnName` or
114    /// `IdentifierDot IdentifierDot ColumnName`, the leaves are the parts in order.
115    fn leaves(&self, node: u32, out: &mut Vec<u32>) {
116        let mut any = false;
117        for kid in self.kids(node) {
118            any = true;
119            self.leaves(kid, &mut *out);
120        }
121        if !any {
122            out.push(node);
123        }
124    }
125
126    // The parts that build the arena.
127
128    /// Intern a string, returning its index.
129    fn intern(&mut self, text: &str) -> StrRef {
130        if let Some(&index) = self.interned.get(text) {
131            return index;
132        }
133        let index = u32::try_from(self.ast.strings.len())
134            .map_err(|_| Error::internal("more than four billion strings in one query"))
135            .unwrap_or(NONE);
136        self.ast.strings.push(text.to_string());
137        self.interned.insert(text.to_string(), index);
138        index
139    }
140
141    /// Push an expression and return its index.
142    fn push(&mut self, expr: Expr) -> ExprRef {
143        let index = self.ast.exprs.len() as u32;
144        self.ast.exprs.push(expr);
145        index
146    }
147
148    /// Push a from item and return its index.
149    fn push_source(&mut self, source: Source) -> SourceRef {
150        let index = self.ast.sources.len() as u32;
151        self.ast.sources.push(source);
152        index
153    }
154
155    /// Push a query and return its index.
156    fn push_query(&mut self, query: Query) -> QueryRef {
157        let index = self.ast.queries.len() as u32;
158        self.ast.queries.push(query);
159        index
160    }
161
162    /// Push a select and return its index.
163    fn push_select(&mut self, select: Select) -> SelectRef {
164        let index = self.ast.selects.len() as u32;
165        self.ast.selects.push(select);
166        index
167    }
168
169    /// Turn a vector of expressions into a slice of the expression list arena.
170    fn expr_slice(&mut self, items: Vec<ExprRef>) -> Slice {
171        let start = self.ast.expr_lists.len() as u32;
172        self.ast.expr_lists.extend(items);
173        Slice { start, len: self.ast.expr_lists.len() as u32 - start }
174    }
175
176    /// Turn a vector of strings into a slice of the name arena.
177    fn part_slice(&mut self, items: Vec<StrRef>) -> Slice {
178        let start = self.ast.parts.len() as u32;
179        self.ast.parts.extend(items);
180        Slice { start, len: self.ast.parts.len() as u32 - start }
181    }
182
183    /// The error for a construct the transformer does not cover yet.
184    ///
185    /// Both halves matter. The text is what the user wrote, which is the only part they can act on,
186    /// and the rule name is what we act on, because it is the exact grammar rule to go implement.
187    fn unsupported<T>(&self, node: u32) -> Result<T> {
188        let text = self.text(node);
189        let text = if text.chars().count() > 60 {
190            let cut = text.char_indices().nth(60).map_or(text.len(), |(at, _)| at);
191            format!("{}...", &text[..cut])
192        } else {
193            text.to_string()
194        };
195        Err(Error::not_implemented(format!(
196            "{text} is not supported yet, the grammar rule is {}",
197            self.name(node)
198        )))
199    }
200
201    // Names.
202
203    /// One identifier out of a subtree, with the quoting and any trailing dot removed.
204    fn identifier(&mut self, node: u32) -> StrRef {
205        let mut leaves = Vec::new();
206        self.leaves(node, &mut leaves);
207        let text = leaves.last().map_or("", |&leaf| self.text(leaf));
208        let text = unquote(text.strip_suffix('.').unwrap_or(text));
209        self.intern(&text)
210    }
211
212    /// Every part of a qualified name, outermost first.
213    fn name_parts(&mut self, node: u32) -> Slice {
214        let mut leaves = Vec::new();
215        self.leaves(node, &mut leaves);
216        let mut parts = Vec::with_capacity(leaves.len());
217        for leaf in leaves {
218            let text = self.text(leaf);
219            // A node that covers no tokens is an optional part that was not written, and a bare
220            // `*` is the star and not a name part. Neither is a component of anything.
221            if text.is_empty() || text == "*" {
222                continue;
223            }
224            let text = unquote(text.strip_suffix('.').unwrap_or(text));
225            let interned = self.intern(&text);
226            parts.push(interned);
227        }
228        self.part_slice(parts)
229    }
230
231    // Statements.
232
233    /// `Program <- TopLevelStatement*`.
234    fn program(&mut self, node: u32) -> Result<()> {
235        for top in self.kids(node) {
236            // A script that ends in a semicolon produces a last `TopLevelStatement` whose only
237            // child is the end of input, because the grammar says `Statement? (';'+ / EndOfInput)`
238            // and both halves of that are happy to match nothing. It is a real node and it is not a
239            // statement, so it is dropped here rather than pretended away in the matcher.
240            let Some(statement) = self.kids(top).find(|&kid| self.name(kid) == "Statement") else {
241                continue;
242            };
243            let statement = self.statement(statement)?;
244            self.ast.statements.push(statement);
245        }
246        Ok(())
247    }
248
249    /// `Statement <- SelectStatement / ...`, twenty seven alternatives of which one is done.
250    fn statement(&mut self, node: u32) -> Result<Statement> {
251        let inner = self.first(node);
252        match self.name(inner) {
253            "SelectStatement" => {
254                let query = self.query(self.first(inner))?;
255                Ok(Statement::Query(query))
256            }
257            _ => self.unsupported(inner),
258        }
259    }
260
261    /// `SelectStatementInternal <- WithClause? SelectSetOpChain ResultModifiers?`.
262    fn query(&mut self, node: u32) -> Result<QueryRef> {
263        if self.find(node, "WithClause") != NONE {
264            return self.unsupported(self.find(node, "WithClause"));
265        }
266        let chain = self.find(node, "SelectSetOpChain");
267        if chain == NONE {
268            return self.unsupported(node);
269        }
270        let query = self.set_op_chain(chain)?;
271        let modifiers = self.find(node, "ResultModifiers");
272        if modifiers != NONE {
273            self.result_modifiers(query, modifiers)?;
274        }
275        Ok(query)
276    }
277
278    /// `SelectSetOpChain <- IntersectChain SelectSetOpChainTail*`, left associative.
279    fn set_op_chain(&mut self, node: u32) -> Result<QueryRef> {
280        let mut kids = self.kids(node);
281        let head = kids.next().unwrap_or(NONE);
282        let mut left = self.intersect_chain(head)?;
283        for tail in kids {
284            // `SelectSetOpChainTail <- SetopClause IntersectChain`.
285            let clause = self.first(tail);
286            let (op, quantifier, by_name) = self.setop_clause(clause)?;
287            let right = self.intersect_chain(self.nth(tail, 1))?;
288            left = self.push_query(Query::bare(QueryBody::SetOp {
289                op,
290                quantifier,
291                by_name,
292                left,
293                right,
294            }));
295        }
296        Ok(left)
297    }
298
299    /// `IntersectChain <- SelectAtom IntersectChainTail*`, which binds tighter than union.
300    fn intersect_chain(&mut self, node: u32) -> Result<QueryRef> {
301        let mut kids = self.kids(node);
302        let head = kids.next().unwrap_or(NONE);
303        let mut left = self.select_atom(head)?;
304        for tail in kids {
305            // `IntersectChainTail <- SetIntersectClause SelectAtom`.
306            let clause = self.first(tail);
307            let quantifier = self.quantifier(self.find(clause, "DistinctOrAll"));
308            let right = self.select_atom(self.nth(tail, 1))?;
309            left = self.push_query(Query::bare(QueryBody::SetOp {
310                op: SetOp::Intersect,
311                quantifier,
312                by_name: false,
313                left,
314                right,
315            }));
316        }
317        Ok(left)
318    }
319
320    /// `SetopClause <- SetopType DistinctOrAll? ByName?`.
321    fn setop_clause(&mut self, node: u32) -> Result<(SetOp, Quantifier, bool)> {
322        let kind = self.find(node, "SetopType");
323        let op = match self.name(self.first(kind)) {
324            "SetopUnion" => SetOp::Union,
325            "SetopExcept" => SetOp::Except,
326            _ => return self.unsupported(kind),
327        };
328        let quantifier = self.quantifier(self.find(node, "DistinctOrAll"));
329        Ok((op, quantifier, self.find(node, "ByName") != NONE))
330    }
331
332    /// `DistinctOrAll <- DistinctKeyword / AllKeyword`, absent included.
333    fn quantifier(&self, node: u32) -> Quantifier {
334        if node == NONE {
335            return Quantifier::Unstated;
336        }
337        match self.name(self.first(node)) {
338            "DistinctKeyword" => Quantifier::Distinct,
339            "AllKeyword" => Quantifier::All,
340            _ => Quantifier::Unstated,
341        }
342    }
343
344    /// `SelectAtom <- SelectParens / SelectStatementType`.
345    fn select_atom(&mut self, node: u32) -> Result<QueryRef> {
346        let inner = self.first(node);
347        match self.name(inner) {
348            // `SelectParens <- Parens(SelectStatementInternal)`, so the parens buy a query that
349            // carries its own order by and limit and nothing else.
350            "SelectParens" => self.query(self.first(inner)),
351            "SelectStatementType" => {
352                let kind = self.first(inner);
353                match self.name(kind) {
354                    "OptionalParensSimpleSelect" => {
355                        let select = self.simple_select(self.unwrap_parens(kind))?;
356                        Ok(self.push_query(Query::bare(QueryBody::Select(select))))
357                    }
358                    _ => self.unsupported(kind),
359                }
360            }
361            _ => self.unsupported(inner),
362        }
363    }
364
365    /// `OptionalParensSimpleSelect <- SimpleSelectParens / SimpleSelect`, down to the select.
366    fn unwrap_parens(&self, node: u32) -> u32 {
367        let mut node = self.first(node);
368        while self.name(node) == "SimpleSelectParens" {
369            node = self.first(node);
370        }
371        node
372    }
373
374    /// `ResultModifiers <- OrderByClause? LimitOffset?`.
375    fn result_modifiers(&mut self, query: QueryRef, node: u32) -> Result<()> {
376        let order = self.find(node, "OrderByClause");
377        if order != NONE {
378            let (items, all) = self.order_by(order)?;
379            let start = self.ast.order_items.len() as u32;
380            self.ast.order_items.extend(items);
381            self.ast.queries[query as usize].order_by =
382                Slice { start, len: self.ast.order_items.len() as u32 - start };
383            self.ast.queries[query as usize].order_by_all = all;
384        }
385        let limit = self.find(node, "LimitOffset");
386        if limit != NONE {
387            self.limit_offset(query, self.first(limit))?;
388        }
389        Ok(())
390    }
391
392    /// The four spellings of a limit and an offset, in either order and either one alone.
393    fn limit_offset(&mut self, query: QueryRef, node: u32) -> Result<()> {
394        match self.name(node) {
395            "LimitOffsetClause" | "OffsetLimitClause" => {
396                let limit = self.find(node, "LimitClause");
397                if limit != NONE {
398                    self.limit(query, limit)?;
399                }
400                let offset = self.find(node, "OffsetClause");
401                if offset != NONE {
402                    self.offset(query, offset)?;
403                }
404                Ok(())
405            }
406            _ => self.unsupported(node),
407        }
408    }
409
410    /// `LimitClause <- 'LIMIT' LimitValue`.
411    fn limit(&mut self, query: QueryRef, node: u32) -> Result<()> {
412        let value = self.first(node);
413        let inner = self.first(value);
414        match self.name(inner) {
415            // `LIMIT ALL` is no limit at all, which is what an absent limit already means.
416            "LimitAll" => Ok(()),
417            // `LimitExpression <- Expression '%'?`. The percent sign is a terminal so it leaves no
418            // node behind, and the only thing that says it was written is the text of the rule that
419            // matched it.
420            "LimitExpression" => {
421                let expr = self.expr(self.first(inner))?;
422                self.ast.queries[query as usize].limit = expr;
423                self.ast.queries[query as usize].limit_percent = self.text(inner).ends_with('%');
424                Ok(())
425            }
426            "LimitLiteralPercent" => {
427                let expr = self.expr(self.first(inner))?;
428                self.ast.queries[query as usize].limit = expr;
429                self.ast.queries[query as usize].limit_percent = true;
430                Ok(())
431            }
432            _ => self.unsupported(inner),
433        }
434    }
435
436    /// `OffsetClause <- 'OFFSET' OffsetValue`, where `OffsetValue <- Expression RowOrRows?`.
437    fn offset(&mut self, query: QueryRef, node: u32) -> Result<()> {
438        let value = self.first(node);
439        let expr = self.expr(self.first(value))?;
440        self.ast.queries[query as usize].offset = expr;
441        Ok(())
442    }
443
444    /// `SimpleSelect <- SelectFrom WhereClause? GroupByClause? HavingClause? WindowClause?
445    /// QualifyClause? SampleClause?`.
446    fn simple_select(&mut self, node: u32) -> Result<SelectRef> {
447        for name in ["WindowClause", "QualifyClause", "SampleClause"] {
448            let clause = self.find(node, name);
449            if clause != NONE {
450                return self.unsupported(clause);
451            }
452        }
453        let mut select = Select::empty();
454        self.select_from(&mut select, self.first(node))?;
455        let filter = self.find(node, "WhereClause");
456        if filter != NONE {
457            select.filter = self.expr(self.first(filter))?;
458        }
459        let group = self.find(node, "GroupByClause");
460        if group != NONE {
461            self.group_by(&mut select, self.first(group))?;
462        }
463        let having = self.find(node, "HavingClause");
464        if having != NONE {
465            select.having = self.expr(self.first(having))?;
466        }
467        Ok(self.push_select(select))
468    }
469
470    /// `SelectFrom <- SelectFromClause / FromSelectClause`, which is `SELECT ... FROM ...` and
471    /// DuckDB's `FROM ... SELECT ...` written the other way round.
472    fn select_from(&mut self, select: &mut Select, node: u32) -> Result<()> {
473        let clause = self.first(node);
474        let targets = self.find(clause, "SelectClause");
475        let from = self.find(clause, "FromClause");
476        if from != NONE {
477            select.from = self.sources(from)?;
478        }
479        if targets == NONE {
480            // `FROM t` on its own. DuckDB reads it as `SELECT * FROM t`, and inventing the star
481            // here rather than in the binder keeps the binder from having to know the shape of the
482            // clause that was missing.
483            let star = self.push(Expr::Star { qualifier: Slice::default() });
484            let start = self.ast.targets.len() as u32;
485            self.ast.targets.push(Target { expr: star, alias: NONE });
486            select.targets = Slice { start, len: 1 };
487            return Ok(());
488        }
489        self.select_clause(select, targets)
490    }
491
492    /// `SelectClause <- 'SELECT' DistinctClause? TargetList?`.
493    fn select_clause(&mut self, select: &mut Select, node: u32) -> Result<()> {
494        let distinct = self.find(node, "DistinctClause");
495        if distinct != NONE {
496            let inner = self.first(distinct);
497            select.distinct = match self.name(inner) {
498                // `SELECT ALL` is the default spelled out.
499                "DistinctAll" => Distinct::No,
500                "DistinctOn" => {
501                    let on = self.find(inner, "DistinctOnTargets");
502                    if on == NONE {
503                        Distinct::Yes
504                    } else {
505                        let mut items = Vec::new();
506                        for kid in self.kids(on) {
507                            items.push(self.expr(kid)?);
508                        }
509                        Distinct::On(self.expr_slice(items))
510                    }
511                }
512                _ => return self.unsupported(inner),
513            };
514        }
515        let list = self.find(node, "TargetList");
516        if list == NONE {
517            return Ok(());
518        }
519        let mut targets = Vec::new();
520        for kid in self.kids(list) {
521            targets.push(self.target(kid)?);
522        }
523        let start = self.ast.targets.len() as u32;
524        self.ast.targets.extend(targets);
525        select.targets = Slice { start, len: self.ast.targets.len() as u32 - start };
526        Ok(())
527    }
528
529    /// `AliasedExpression <- ColIdExpression / ExpressionAsCollabel / ExpressionOptIdentifier`.
530    fn target(&mut self, node: u32) -> Result<Target> {
531        let inner = self.first(node);
532        match self.name(inner) {
533            // `ColIdExpression <- ColId ':' Expression`, the alias written first.
534            "ColIdExpression" => {
535                let alias = self.identifier(self.first(inner));
536                let expr = self.expr(self.nth(inner, 1))?;
537                Ok(Target { expr, alias })
538            }
539            "ExpressionAsCollabel" => {
540                let expr = self.expr(self.first(inner))?;
541                let alias = self.identifier(self.nth(inner, 1));
542                Ok(Target { expr, alias })
543            }
544            "ExpressionOptIdentifier" => {
545                let expr = self.expr(self.first(inner))?;
546                let alias =
547                    if self.count(inner) > 1 { self.identifier(self.nth(inner, 1)) } else { NONE };
548                Ok(Target { expr, alias })
549            }
550            _ => self.unsupported(inner),
551        }
552    }
553
554    /// `GroupByClause <- 'GROUP' 'BY' GroupByExpressions`.
555    fn group_by(&mut self, select: &mut Select, node: u32) -> Result<()> {
556        let inner = self.first(node);
557        match self.name(inner) {
558            "GroupByAll" => {
559                select.group_by_all = true;
560                Ok(())
561            }
562            "GroupByList" => {
563                let mut items = Vec::new();
564                for kid in self.kids(inner) {
565                    // `GroupByExpression <- EmptyGroupingItem / CubeOrRollupClause /
566                    // GroupingSetsClause / GroupByBaseExpression`.
567                    let expression = self.first(kid);
568                    if self.name(expression) != "GroupByBaseExpression" {
569                        return self.unsupported(expression);
570                    }
571                    items.push(self.expr(self.first(expression))?);
572                }
573                select.group_by = self.expr_slice(items);
574                Ok(())
575            }
576            _ => self.unsupported(inner),
577        }
578    }
579
580    /// `OrderByClause <- 'ORDER' 'BY' OrderByExpressions`, where `OrderByExpressions <- OrderByAll
581    /// / OrderByExpressionList`.
582    fn order_by(&mut self, node: u32) -> Result<(Vec<OrderItem>, bool)> {
583        let inner = self.first(self.first(node));
584        match self.name(inner) {
585            "OrderByAll" => {
586                let (order, nulls) = self.sort_options(inner);
587                Ok((vec![OrderItem { expr: NONE, order, nulls }], true))
588            }
589            "OrderByExpressionList" => {
590                let mut items = Vec::new();
591                for kid in self.kids(inner) {
592                    // `OrderByExpression <- Expression DescOrAsc? NullsFirstOrLast?`.
593                    let expr = self.expr(self.first(kid))?;
594                    let (order, nulls) = self.sort_options(kid);
595                    items.push(OrderItem { expr, order, nulls });
596                }
597                Ok((items, false))
598            }
599            _ => self.unsupported(inner),
600        }
601    }
602
603    /// The direction and the null placement of one sort key, either of which may be unwritten.
604    fn sort_options(&self, node: u32) -> (Order, Nulls) {
605        let direction = self.find(node, "DescOrAsc");
606        let order = if direction == NONE {
607            Order::Unstated
608        } else if self.name(self.first(direction)) == "DescendingOrder" {
609            Order::Descending
610        } else {
611            Order::Ascending
612        };
613        let placement = self.find(node, "NullsFirstOrLast");
614        let nulls = if placement == NONE {
615            Nulls::Unstated
616        } else if self.name(self.first(placement)) == "NullsFirst" {
617            Nulls::First
618        } else {
619            Nulls::Last
620        };
621        (order, nulls)
622    }
623
624    // From clauses.
625
626    /// `FromClause <- 'FROM' List(TableRef)`.
627    fn sources(&mut self, node: u32) -> Result<Slice> {
628        let mut items = Vec::new();
629        for kid in self.kids(node) {
630            items.push(self.table_ref(kid)?);
631        }
632        let start = self.ast.source_lists.len() as u32;
633        self.ast.source_lists.extend(items);
634        Ok(Slice { start, len: self.ast.source_lists.len() as u32 - start })
635    }
636
637    /// `TableRef <- InnerTableRef JoinOrPivot*`, left associative like the set operators.
638    fn table_ref(&mut self, node: u32) -> Result<SourceRef> {
639        let mut kids = self.kids(node);
640        let head = kids.next().unwrap_or(NONE);
641        let mut left = self.inner_table_ref(head)?;
642        for tail in kids {
643            let clause = self.first(tail);
644            if self.name(clause) != "JoinClause" {
645                return self.unsupported(clause);
646            }
647            left = self.join(left, self.first(clause))?;
648        }
649        Ok(left)
650    }
651
652    /// `InnerTableRef <- ValuesRef / TableFunction / TableSubquery / BaseTableRef / ParensTableRef`.
653    fn inner_table_ref(&mut self, node: u32) -> Result<SourceRef> {
654        let inner = if self.name(node) == "InnerTableRef" { self.first(node) } else { node };
655        match self.name(inner) {
656            "BaseTableRef" => {
657                if self.find(inner, "TableAliasColon") != NONE {
658                    return self.unsupported(inner);
659                }
660                for name in ["AtClause", "SampleClause"] {
661                    let clause = self.find(inner, name);
662                    if clause != NONE {
663                        return self.unsupported(clause);
664                    }
665                }
666                let name = self.name_parts(self.find(inner, "BaseTableName"));
667                let (alias, columns) = self.table_alias(self.find(inner, "TableAlias"));
668                Ok(self.push_source(Source::Table { name, alias, columns }))
669            }
670            "TableSubquery" => {
671                if self.find(inner, "TableAliasColon") != NONE
672                    || self.find(inner, "Lateral") != NONE
673                {
674                    return self.unsupported(inner);
675                }
676                // `SubqueryReference <- Parens(SelectStatementInternal)`.
677                let reference = self.find(inner, "SubqueryReference");
678                let query = self.query(self.first(reference))?;
679                let (alias, columns) = self.table_alias(self.find(inner, "TableAlias"));
680                Ok(self.push_source(Source::Subquery { query, alias, columns }))
681            }
682            "ParensTableRef" => {
683                if self.find(inner, "TableAliasColon") != NONE
684                    || self.find(inner, "SampleClause") != NONE
685                    || self.find(inner, "TableAlias") != NONE
686                {
687                    return self.unsupported(inner);
688                }
689                self.table_ref(self.find(inner, "TableRef"))
690            }
691            _ => self.unsupported(inner),
692        }
693    }
694
695    /// `TableAlias <- TableAliasAs / TableAliasWithoutAs`, either with a column alias list.
696    fn table_alias(&mut self, node: u32) -> (StrRef, Slice) {
697        if node == NONE {
698            return (NONE, Slice::default());
699        }
700        let inner = self.first(node);
701        let alias = self.identifier(self.first(inner));
702        let list = self.find(inner, "ColumnAliases");
703        if list == NONE {
704            return (alias, Slice::default());
705        }
706        let mut columns = Vec::new();
707        for kid in self.kids(list) {
708            let name = self.identifier(kid);
709            columns.push(name);
710        }
711        (alias, self.part_slice(columns))
712    }
713
714    /// `JoinClause <- JoinByClause / RegularJoinClause / JoinWithoutOnClause / NearestJoinClause`.
715    fn join(&mut self, left: SourceRef, node: u32) -> Result<SourceRef> {
716        match self.name(node) {
717            // `RegularJoinClause <- Asof? JoinType? 'JOIN' TableRef JoinQualifier`.
718            "RegularJoinClause" => {
719                if self.find(node, "Asof") != NONE {
720                    return self.unsupported(node);
721                }
722                let kind = self.join_type(self.find(node, "JoinType"));
723                let right = self.table_ref(self.find(node, "TableRef"))?;
724                let (on, using) = self.join_qualifier(self.find(node, "JoinQualifier"))?;
725                Ok(self.push_source(Source::Join { left, right, kind, natural: false, on, using }))
726            }
727            // `JoinWithoutOnClause <- JoinPrefix 'JOIN' InnerTableRef`, which is cross, natural and
728            // positional. Those three are exactly the joins that carry no condition.
729            "JoinWithoutOnClause" => {
730                let prefix = self.first(self.find(node, "JoinPrefix"));
731                let (kind, natural) = match self.name(prefix) {
732                    "CrossJoinPrefix" => (JoinKind::Cross, false),
733                    "PositionalJoinPrefix" => (JoinKind::Positional, false),
734                    "NaturalJoinPrefix" => (self.join_type(self.find(prefix, "JoinType")), true),
735                    _ => return self.unsupported(prefix),
736                };
737                let right = self.inner_table_ref(self.find(node, "InnerTableRef"))?;
738                Ok(self.push_source(Source::Join {
739                    left,
740                    right,
741                    kind,
742                    natural,
743                    on: NONE,
744                    using: Slice::default(),
745                }))
746            }
747            _ => self.unsupported(node),
748        }
749    }
750
751    /// `JoinType <- FullJoin / LeftJoin / RightJoin / SemiJoin / AntiJoin / InnerJoin`, absent
752    /// meaning inner, which is what SQL has always meant by a bare `JOIN`.
753    fn join_type(&self, node: u32) -> JoinKind {
754        if node == NONE {
755            return JoinKind::Inner;
756        }
757        match self.name(self.first(node)) {
758            "FullJoin" => JoinKind::Full,
759            "LeftJoin" => JoinKind::Left,
760            "RightJoin" => JoinKind::Right,
761            "SemiJoin" => JoinKind::Semi,
762            "AntiJoin" => JoinKind::Anti,
763            _ => JoinKind::Inner,
764        }
765    }
766
767    /// `JoinQualifier <- OnClause / UsingClause`.
768    fn join_qualifier(&mut self, node: u32) -> Result<(ExprRef, Slice)> {
769        let inner = self.first(node);
770        match self.name(inner) {
771            "OnClause" => Ok((self.expr(self.first(inner))?, Slice::default())),
772            "UsingClause" => {
773                let mut columns = Vec::new();
774                for kid in self.kids(inner) {
775                    let name = self.identifier(kid);
776                    columns.push(name);
777                }
778                Ok((NONE, self.part_slice(columns)))
779            }
780            _ => self.unsupported(inner),
781        }
782    }
783
784    // Expressions.
785
786    /// One expression, from wherever in the precedence chain it starts.
787    ///
788    /// The loop is the whole design. A rule that says something gets an arm, a rule with exactly
789    /// one child said nothing and is stepped through, and anything else is an error naming itself.
790    /// The chain rules never get an arm for their one child case, which is why adding a precedence
791    /// level upstream costs nothing here.
792    fn expr(&mut self, node: u32) -> Result<ExprRef> {
793        let mut node = node;
794        loop {
795            let count = self.count(node);
796            let name = self.name(node);
797            match name {
798                "LogicalOrExpression" if count > 1 => return self.logical(node, BinaryOp::Or),
799                "LogicalAndExpression" if count > 1 => return self.logical(node, BinaryOp::And),
800                "LogicalNotExpression" if count > 1 => return self.logical_not(node),
801                "IsExpression" if count > 1 => return self.is_expression(node),
802                "BetweenInLikeExpression" if count > 1 => return self.between_in_like(node),
803                "PrefixExpression" if count > 1 => return self.prefix(node),
804                "BaseExpression" if count > 1 => return self.indirection(node),
805                "LambdaArrowExpression"
806                | "IsDistinctFromExpression"
807                | "ComparisonExpression"
808                | "OtherOperatorExpression"
809                | "BitwiseExpression"
810                | "AdditiveExpression"
811                | "MultiplicativeExpression"
812                | "ExponentiationExpression"
813                | "CollateExpression"
814                | "AtTimeZoneExpression"
815                    if count > 1 =>
816                {
817                    return self.tail_chain(node);
818                }
819                "ColumnReference" => {
820                    let name = self.name_parts(node);
821                    return Ok(self.push(Expr::Column { name }));
822                }
823                "StarExpression" => return self.star(node),
824                "NumberLiteral" => {
825                    let text = self.text(node).to_string();
826                    let text = self.intern(&text);
827                    return Ok(self.push(Expr::Literal { kind: LiteralKind::Number, text }));
828                }
829                "StringLiteral" => {
830                    let text = self.string_value(node);
831                    let text = self.intern(&text);
832                    return Ok(self.push(Expr::Literal { kind: LiteralKind::String, text }));
833                }
834                "NullLiteral" | "TrueLiteral" | "FalseLiteral" => {
835                    let kind = match name {
836                        "NullLiteral" => LiteralKind::Null,
837                        "TrueLiteral" => LiteralKind::True,
838                        _ => LiteralKind::False,
839                    };
840                    return Ok(self.push(Expr::Literal { kind, text: NONE }));
841                }
842                "FunctionExpression" => return self.function(node),
843                "CastExpression" => return self.cast(node),
844                "CaseExpression" => return self.case(node),
845                "ParenthesisExpression" => return self.row(node),
846                "SubqueryExpression" => return self.subquery(node),
847                _ if count == 1 => node = self.first(node),
848                _ => return self.unsupported(node),
849            }
850        }
851    }
852
853    /// `X <- Y XTail*` where `XTail <- Operator Y`, the shape ten precedence levels share.
854    fn tail_chain(&mut self, node: u32) -> Result<ExprRef> {
855        let mut kids = self.kids(node);
856        let head = kids.next().unwrap_or(NONE);
857        let mut left = self.expr(head)?;
858        for tail in kids {
859            let operator = self.first(tail);
860            let op = self.binary_op(operator)?;
861            // `ComparisonExpressionTail <- ComparisonOperator NotExpression? BetweenInLikeExpression`
862            // is the one tail with an optional middle, so the operand is the last child and not the
863            // second one. Taking the last is right for every tail and wrong for none.
864            let operand = self.kids(tail).last().unwrap_or(NONE);
865            if self.count(tail) > 2 {
866                return self.unsupported(tail);
867            }
868            let right = self.expr(operand)?;
869            left = self.push(Expr::Binary { op, left, right });
870        }
871        Ok(left)
872    }
873
874    /// Which infix operator a tail's operator node is.
875    fn binary_op(&mut self, node: u32) -> Result<BinaryOp> {
876        // The operator rules nest: `ComparisonOperator` over `OperatorGreaterThan` over the symbol
877        // itself. Every one of them covers the same tokens, so the text is the same at every level
878        // and reading it once at the top is enough. The name is not, which is why the bottom of the
879        // chain is walked to as well: `OtherOperator` says nothing and `OperatorLiteral` says
880        // everything, and they are three levels apart.
881        let mut leaf = node;
882        while self.count(leaf) == 1 {
883            leaf = self.first(leaf);
884        }
885        let text = self.text(node);
886        let upper = text.to_ascii_uppercase();
887        let op = match upper.as_str() {
888            "OR" => BinaryOp::Or,
889            "AND" => BinaryOp::And,
890            "=" | "==" => BinaryOp::Eq,
891            "!=" | "<>" => BinaryOp::NotEq,
892            "<" => BinaryOp::Lt,
893            ">" => BinaryOp::Gt,
894            "<=" => BinaryOp::LtEq,
895            ">=" => BinaryOp::GtEq,
896            "+" => BinaryOp::Add,
897            "-" => BinaryOp::Subtract,
898            "*" => BinaryOp::Multiply,
899            "/" => BinaryOp::Divide,
900            "//" => BinaryOp::IntegerDivide,
901            "%" => BinaryOp::Modulo,
902            "^" | "**" => BinaryOp::Power,
903            "&" => BinaryOp::BitAnd,
904            "|" => BinaryOp::BitOr,
905            "<<" => BinaryOp::ShiftLeft,
906            ">>" => BinaryOp::ShiftRight,
907            "||" => BinaryOp::Concat,
908            "COLLATE" => BinaryOp::Collate,
909            "->" => BinaryOp::Arrow,
910            "->>" => BinaryOp::LongArrow,
911            "@>" => BinaryOp::Contains,
912            "<@" => BinaryOp::ContainedBy,
913            "&&" => BinaryOp::Overlaps,
914            "^@" => BinaryOp::StartsWith,
915            "<<=" => BinaryOp::InetContainedByOrEq,
916            ">>=" => BinaryOp::InetContainsOrEq,
917            _ if self.name(leaf) == "AtTimeZoneOperator" => BinaryOp::AtTimeZone,
918            // `IsDistinctFromOp <- 'IS' 'NOT'? 'DISTINCT' 'FROM'`, told apart by the middle word,
919            // which is not in the tree because keywords are terminals.
920            _ if self.name(leaf) == "IsDistinctFromOp" => {
921                if upper.split_whitespace().any(|word| word == "NOT") {
922                    BinaryOp::IsNotDistinctFrom
923                } else {
924                    BinaryOp::IsDistinctFrom
925                }
926            }
927            // `OperatorLiteral` is the open end of the operator set. Its body in the grammar text
928            // says `Identifier`, but it is one of the 24 rules whose body the matcher does not
929            // walk and the matcher it is overridden to is the bare operator one, so what it
930            // actually accepts is any run of operator characters that is not already a token.
931            // `a <=> b` is such a run, DuckDB resolves it as a two argument function of that name,
932            // and rejecting it here would reject SQL DuckDB accepts.
933            _ if self.name(leaf) == "OperatorLiteral" => {
934                let interned = self.intern(text);
935                BinaryOp::Named(interned)
936            }
937            _ => return self.unsupported(node),
938        };
939        Ok(op)
940    }
941
942    /// `LogicalOrExpression <- LogicalAndExpression LogicalOrExpressionTail*`, and the `AND` twin.
943    ///
944    /// Separate from the other tails because the tail here is `'OR' LogicalAndExpression` with the
945    /// keyword as a terminal, so there is no operator node to read and the operator is the rule.
946    fn logical(&mut self, node: u32, op: BinaryOp) -> Result<ExprRef> {
947        let mut kids = self.kids(node);
948        let head = kids.next().unwrap_or(NONE);
949        let mut left = self.expr(head)?;
950        for tail in kids {
951            let right = self.expr(self.first(tail))?;
952            left = self.push(Expr::Binary { op, left, right });
953        }
954        Ok(left)
955    }
956
957    /// `LogicalNotExpression <- NotExpression? IsExpression`, where `NotExpression <- NotKeyword+`.
958    ///
959    /// The plus matters. `NOT NOT x` is two nodes in the parse tree and two negations in the AST,
960    /// and folding them here would be an optimizer decision taken in the parser.
961    fn logical_not(&mut self, node: u32) -> Result<ExprRef> {
962        let negations = self.count(self.first(node));
963        let mut expr = self.expr(self.nth(node, 1))?;
964        for _ in 0..negations {
965            expr = self.push(Expr::Unary { op: UnaryOp::Not, operand: expr });
966        }
967        Ok(expr)
968    }
969
970    /// `IsExpression <- IsDistinctFromExpression IsTest*`, the postfix null and boolean tests.
971    fn is_expression(&mut self, node: u32) -> Result<ExprRef> {
972        let mut kids = self.kids(node);
973        let head = kids.next().unwrap_or(NONE);
974        let mut expr = self.expr(head)?;
975        for test in kids {
976            let inner = self.first(test);
977            let negated = self.text(inner).to_ascii_uppercase().contains("NOT");
978            let op = match self.name(inner) {
979                "NotNull" => UnaryOp::IsNotNull,
980                "IsNull" => UnaryOp::IsNull,
981                // `IsLiteral <- 'IS' 'NOT'? IsLiteralValue`, and the value rule is one more level
982                // down again because it is a choice of four and not four alternatives inlined.
983                "IsLiteral" => match self.name(self.first(self.first(inner))) {
984                    "NullLiteral" if negated => UnaryOp::IsNotNull,
985                    "NullLiteral" => UnaryOp::IsNull,
986                    "TrueLiteral" if negated => UnaryOp::IsNotTrue,
987                    "TrueLiteral" => UnaryOp::IsTrue,
988                    "FalseLiteral" if negated => UnaryOp::IsNotFalse,
989                    "FalseLiteral" => UnaryOp::IsFalse,
990                    "UnknownLiteral" if negated => UnaryOp::IsNotUnknown,
991                    "UnknownLiteral" => UnaryOp::IsUnknown,
992                    _ => return self.unsupported(inner),
993                },
994                _ => return self.unsupported(inner),
995            };
996            expr = self.push(Expr::Unary { op, operand: expr });
997        }
998        Ok(expr)
999    }
1000
1001    /// `BetweenInLikeExpression <- OtherOperatorExpression BetweenInLikeOp?`.
1002    fn between_in_like(&mut self, node: u32) -> Result<ExprRef> {
1003        let operand = self.expr(self.first(node))?;
1004        // `BetweenInLikeOp <- 'NOT'? BetweenInLikeOpExpression`. The `NOT` is a terminal, so what
1005        // says it was written is that the op node covers a token the inner node does not.
1006        let op = self.nth(node, 1);
1007        let negated = self.text(op).to_ascii_uppercase().starts_with("NOT");
1008        let inner = self.first(self.first(op));
1009        match self.name(inner) {
1010            // `BetweenClause <- 'BETWEEN' x 'AND' y`.
1011            "BetweenClause" => {
1012                let low = self.expr(self.first(inner))?;
1013                let high = self.expr(self.nth(inner, 1))?;
1014                Ok(self.push(Expr::Between { operand, low, high, negated }))
1015            }
1016            // `InClause <- 'IN' InExpression`.
1017            "InClause" => {
1018                let expression = self.first(self.first(inner));
1019                match self.name(expression) {
1020                    "InExpressionList" => {
1021                        let mut items = Vec::new();
1022                        for kid in self.kids(expression) {
1023                            items.push(self.expr(kid)?);
1024                        }
1025                        let list = self.expr_slice(items);
1026                        Ok(self.push(Expr::In { operand, list, negated }))
1027                    }
1028                    _ => self.unsupported(expression),
1029                }
1030            }
1031            // `LikeClause <- LikeVariations x EscapeClause?`.
1032            "LikeClause" => {
1033                if self.find(inner, "EscapeClause") != NONE {
1034                    return self.unsupported(inner);
1035                }
1036                let variation = self.name(self.first(self.first(inner)));
1037                let op = match (variation, negated) {
1038                    ("LikeToken", false) | ("NotLikeOp", true) => BinaryOp::Like,
1039                    ("LikeToken", true) | ("NotLikeOp", false) => BinaryOp::NotLike,
1040                    ("ILikeToken", false) | ("NotILikeOp", true) => BinaryOp::ILike,
1041                    ("ILikeToken", true) | ("NotILikeOp", false) => BinaryOp::NotILike,
1042                    // Glob and the bare regex match have no negated spelling of their own in
1043                    // `LikeVariations`, so a `NOT` in front of either stays an explicit negation.
1044                    ("GlobToken", _) => BinaryOp::Glob,
1045                    ("RegexMatchToken", _) => BinaryOp::Regex,
1046                    ("SimilarToToken", false) | ("NotSimilarToOp", true) => BinaryOp::SimilarTo,
1047                    ("SimilarToToken", true) | ("NotSimilarToOp", false) => BinaryOp::NotSimilarTo,
1048                    ("RegexInsensitiveMatchToken", false)
1049                    | ("NotRegexInsensitiveMatchOp", true) => BinaryOp::RegexInsensitive,
1050                    ("RegexInsensitiveMatchToken", true)
1051                    | ("NotRegexInsensitiveMatchOp", false) => BinaryOp::NotRegexInsensitive,
1052                    _ => return self.unsupported(inner),
1053                };
1054                let right = self.expr(self.nth(inner, 1))?;
1055                let expr = self.push(Expr::Binary { op, left: operand, right });
1056                // The like family folds its negation into the operator because it has a spelling
1057                // for the negated form. Glob and regex do not, so theirs stays where it was.
1058                if negated && matches!(op, BinaryOp::Glob | BinaryOp::Regex) {
1059                    return Ok(self.push(Expr::Unary { op: UnaryOp::Not, operand: expr }));
1060                }
1061                Ok(expr)
1062            }
1063            _ => self.unsupported(inner),
1064        }
1065    }
1066
1067    /// `PrefixExpression <- PrefixOperator* BaseExpression`, applied right to left.
1068    fn prefix(&mut self, node: u32) -> Result<ExprRef> {
1069        let kids: Vec<u32> = self.kids(node).collect();
1070        let mut expr = self.expr(kids[kids.len() - 1])?;
1071        for &operator in kids[..kids.len() - 1].iter().rev() {
1072            let op = match self.name(self.first(operator)) {
1073                "MinusPrefixOperator" => UnaryOp::Negate,
1074                "PlusPrefixOperator" => UnaryOp::Plus,
1075                "TildePrefixOperator" => UnaryOp::BitNot,
1076                _ => return self.unsupported(operator),
1077            };
1078            expr = self.push(Expr::Unary { op, operand: expr });
1079        }
1080        Ok(expr)
1081    }
1082
1083    /// `BaseExpression <- SingleExpression IndirectionList?`, the postfix chain.
1084    fn indirection(&mut self, node: u32) -> Result<ExprRef> {
1085        let mut expr = self.expr(self.first(node))?;
1086        for step in self.kids(self.nth(node, 1)) {
1087            let inner = self.first(step);
1088            expr = match self.name(inner) {
1089                // `CastOperator <- '::' Type`.
1090                "CastOperator" => {
1091                    let text = self.text(self.first(inner)).to_string();
1092                    let ty = self.intern(&text);
1093                    self.push(Expr::Cast { operand: expr, ty, try_cast: false })
1094                }
1095                "DotOperator" => {
1096                    let dot = self.first(inner);
1097                    match self.name(dot) {
1098                        // `DotColumnOperator <- '.' ColLabel`, which DuckDB resolves as a call of
1099                        // `struct_extract`. Writing it as that call rather than as its own node
1100                        // keeps the binder from needing a rule for a thing that is already a
1101                        // function.
1102                        "DotColumnOperator" => {
1103                            let field = self.identifier(self.first(dot));
1104                            let text = self.ast.string(field).to_string();
1105                            let literal = self.intern(&text);
1106                            let key = self
1107                                .push(Expr::Literal { kind: LiteralKind::String, text: literal });
1108                            let name = self.function_name("struct_extract");
1109                            let args = self.expr_slice(vec![expr, key]);
1110                            self.push(Expr::Function { name, args, distinct: false })
1111                        }
1112                        // `DotMethodOperator <- '.' MethodExpression`, where `x.f(a)` is `f(x, a)`.
1113                        "DotMethodOperator" => {
1114                            let method = self.first(dot);
1115                            let text = self.text(self.first(method)).to_string();
1116                            let text = unquote(&text);
1117                            let name = self.function_name(&text);
1118                            let mut args = vec![expr];
1119                            let list = self.find(method, "MethodExpressionArguments");
1120                            if list != NONE {
1121                                let inner = self.first(list);
1122                                let arguments = self.find(inner, "MethodFunctionArguments");
1123                                if arguments != NONE {
1124                                    for kid in self.kids(arguments) {
1125                                        args.push(self.argument(kid)?);
1126                                    }
1127                                }
1128                            }
1129                            let args = self.expr_slice(args);
1130                            self.push(Expr::Function { name, args, distinct: false })
1131                        }
1132                        _ => return self.unsupported(dot),
1133                    }
1134                }
1135                // `SliceExpression <- '[' SliceBound ']'`, one index or a range.
1136                "SliceExpression" => {
1137                    let bound = self.first(inner);
1138                    let has_end = self.find(bound, "EndSliceBound") != NONE;
1139                    let has_step = self.find(bound, "StepSliceBound") != NONE;
1140                    if has_end || has_step {
1141                        return self.unsupported(inner);
1142                    }
1143                    let index = self.expr(self.first(bound))?;
1144                    let name = self.function_name("array_extract");
1145                    let args = self.expr_slice(vec![expr, index]);
1146                    self.push(Expr::Function { name, args, distinct: false })
1147                }
1148                // `PostfixOperator <- '!'`.
1149                "PostfixOperator" => {
1150                    self.push(Expr::Unary { op: UnaryOp::Factorial, operand: expr })
1151                }
1152                _ => return self.unsupported(inner),
1153            };
1154        }
1155        Ok(expr)
1156    }
1157
1158    /// A one part function name, for the calls the transformer invents rather than reads.
1159    fn function_name(&mut self, name: &str) -> Slice {
1160        let interned = self.intern(name);
1161        self.part_slice(vec![interned])
1162    }
1163
1164    /// `StarExpression <- StarQualifierList? '*' ExcludeList? ReplaceList? RenameList?`.
1165    fn star(&mut self, node: u32) -> Result<ExprRef> {
1166        for name in ["ExcludeList", "ReplaceList", "RenameList"] {
1167            let list = self.find(node, name);
1168            if list != NONE {
1169                return self.unsupported(list);
1170            }
1171        }
1172        let qualifier = self.find(node, "StarQualifierList");
1173        let qualifier =
1174            if qualifier == NONE { Slice::default() } else { self.name_parts(qualifier) };
1175        Ok(self.push(Expr::Star { qualifier }))
1176    }
1177
1178    /// `FunctionExpression <- FunctionIdentifier FunctionExpressionArguments WithinGroupClause?
1179    /// FilterClause? ExportClause? OverClause?`.
1180    fn function(&mut self, node: u32) -> Result<ExprRef> {
1181        for name in ["WithinGroupClause", "FilterClause", "ExportClause", "OverClause"] {
1182            let clause = self.find(node, name);
1183            if clause != NONE {
1184                return self.unsupported(clause);
1185            }
1186        }
1187        let name = self.name_parts(self.first(node));
1188        // `FunctionExpressionArguments <- Parens(FunctionExpressionArgumentList)` and
1189        // `FunctionExpressionArgumentList <- DistinctOrAll? FunctionArgumentList? OrderByClause?
1190        // IgnoreOrRespectNulls?`, so a call with no arguments still has both wrappers.
1191        let list = self.first(self.nth(node, 1));
1192        for name in ["OrderByClause", "IgnoreOrRespectNulls"] {
1193            let clause = self.find(list, name);
1194            if clause != NONE {
1195                return self.unsupported(clause);
1196            }
1197        }
1198        let distinct = self.quantifier(self.find(list, "DistinctOrAll")) == Quantifier::Distinct;
1199        let mut args = Vec::new();
1200        let arguments = self.find(list, "FunctionArgumentList");
1201        if arguments != NONE {
1202            for kid in self.kids(arguments) {
1203                args.push(self.argument(kid)?);
1204            }
1205        }
1206        let args = self.expr_slice(args);
1207        Ok(self.push(Expr::Function { name, args, distinct }))
1208    }
1209
1210    /// `FunctionArgument <- NamedFunctionArgument / PositionalFunctionArgument`.
1211    fn argument(&mut self, node: u32) -> Result<ExprRef> {
1212        let inner = self.first(node);
1213        match self.name(inner) {
1214            "PositionalFunctionArgument" => self.expr(self.first(inner)),
1215            _ => self.unsupported(inner),
1216        }
1217    }
1218
1219    /// `CastExpression <- CastOrTryCast Parens(CastArguments)`.
1220    fn cast(&mut self, node: u32) -> Result<ExprRef> {
1221        let try_cast = self.name(self.first(self.first(node))) == "TryCastKeyword";
1222        // `CastArguments <- Expression 'AS' Type`.
1223        let arguments = self.nth(node, 1);
1224        let operand = self.expr(self.first(arguments))?;
1225        let text = self.text(self.nth(arguments, 1)).to_string();
1226        let ty = self.intern(&text);
1227        Ok(self.push(Expr::Cast { operand, ty, try_cast }))
1228    }
1229
1230    /// `CaseExpression <- 'CASE' Expression? CaseWhenThen+ CaseElse? 'END'`.
1231    fn case(&mut self, node: u32) -> Result<ExprRef> {
1232        let mut operand = NONE;
1233        let mut arms = Vec::new();
1234        let mut otherwise = NONE;
1235        for kid in self.kids(node) {
1236            match self.name(kid) {
1237                // `CaseWhenThen <- 'WHEN' Expression 'THEN' Expression`.
1238                "CaseWhenThen" => {
1239                    let when = self.expr(self.first(kid))?;
1240                    let then = self.expr(self.nth(kid, 1))?;
1241                    arms.push(CaseArm { when, then });
1242                }
1243                // `CaseElse <- 'ELSE' Expression`.
1244                "CaseElse" => otherwise = self.expr(self.first(kid))?,
1245                // The bare `Expression` before the first `WHEN`, which makes it a simple case.
1246                _ => operand = self.expr(kid)?,
1247            }
1248        }
1249        let start = self.ast.case_arms.len() as u32;
1250        self.ast.case_arms.extend(arms);
1251        let arms = Slice { start, len: self.ast.case_arms.len() as u32 - start };
1252        Ok(self.push(Expr::Case { operand, arms, otherwise }))
1253    }
1254
1255    /// `ParenthesisExpression <- Parens(List(Expression)?)`, which is a row value.
1256    ///
1257    /// One item is not a row. `(a)` is `a` in every dialect and reading it as a one column row
1258    /// would change what `(a) = (b)` means.
1259    fn row(&mut self, node: u32) -> Result<ExprRef> {
1260        let mut items = Vec::new();
1261        for kid in self.kids(node) {
1262            items.push(self.expr(kid)?);
1263        }
1264        if items.len() == 1 {
1265            return Ok(items[0]);
1266        }
1267        let items = self.expr_slice(items);
1268        Ok(self.push(Expr::Row { items }))
1269    }
1270
1271    /// `SubqueryExpression <- SubqueryNot? SubqueryExists? SubqueryReference`.
1272    fn subquery(&mut self, node: u32) -> Result<ExprRef> {
1273        if self.find(node, "SubqueryNot") != NONE || self.find(node, "SubqueryExists") != NONE {
1274            return self.unsupported(node);
1275        }
1276        let reference = self.find(node, "SubqueryReference");
1277        let query = self.query(self.first(reference))?;
1278        Ok(self.push(Expr::Subquery { query }))
1279    }
1280
1281    /// The value of a string literal, with the quotes gone and the escapes resolved.
1282    ///
1283    /// A literal can be several tokens. `'a' 'b'` on two lines is one literal that is `ab`, which is
1284    /// the SQL standard's rule and DuckDB's, so the node is decoded token by token rather than by
1285    /// taking its text and stripping the outside.
1286    fn string_value(&self, node: u32) -> String {
1287        let span = self.tree.node(node);
1288        let mut value = String::new();
1289        for token in &self.tokens[span.start as usize..span.end as usize] {
1290            if token.kind != Kind::String {
1291                continue;
1292            }
1293            let text = token.text(self.query);
1294            match text.strip_prefix('\'').and_then(|rest| rest.strip_suffix('\'')) {
1295                Some(body) => value.push_str(&body.replace("''", "'")),
1296                None => value.push_str(text),
1297            }
1298        }
1299        value
1300    }
1301}
1302
1303/// Strip the quoting off an identifier.
1304///
1305/// DuckDB does not fold identifier case at any point, quoted or not, so this only removes the
1306/// quotes and resolves the doubled ones. Anything else would be the parser deciding what a name is.
1307fn unquote(text: &str) -> String {
1308    match text.strip_prefix('"').and_then(|rest| rest.strip_suffix('"')) {
1309        Some(body) => body.replace("\"\"", "\""),
1310        None => text.to_string(),
1311    }
1312}
1313
1314#[cfg(test)]
1315mod tests {
1316    use super::*;
1317    use crate::corpus::CORPUS;
1318    use crate::matcher::parse;
1319
1320    /// The AST written back out as text, which is what the assertions below read.
1321    ///
1322    /// Not a SQL printer and not trying to be. It is deliberately not valid SQL: operators are
1323    /// spelled with the name of the variant and every binary node is parenthesised, so that a test
1324    /// asserting on this text is asserting on the shape of the tree and not on a formatting choice.
1325    /// `a - b - c` and `a - (b - c)` have to look different here or the test that tells them apart
1326    /// is not a test.
1327    fn show(ast: &Ast, expr: ExprRef) -> String {
1328        if expr == NONE {
1329            return "-".to_string();
1330        }
1331        let list = |slice: Slice| {
1332            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
1333        };
1334        match ast.expr(expr) {
1335            Expr::Star { qualifier } if qualifier.is_empty() => "*".to_string(),
1336            Expr::Star { qualifier } => format!("{}.*", ast.name_text(qualifier)),
1337            Expr::Column { name } => ast.name_text(name),
1338            Expr::Literal { kind, text } => match kind {
1339                LiteralKind::Number => ast.string(text).to_string(),
1340                LiteralKind::String => format!("'{}'", ast.string(text)),
1341                other => format!("{other:?}").to_uppercase(),
1342            },
1343            Expr::Unary { op, operand } => format!("({op:?} {})", show(ast, operand)),
1344            Expr::Binary { op, left, right } => {
1345                let op = match op {
1346                    BinaryOp::Named(name) => ast.string(name).to_string(),
1347                    other => format!("{other:?}"),
1348                };
1349                format!("({} {op} {})", show(ast, left), show(ast, right))
1350            }
1351            Expr::Function { name, args, distinct } => {
1352                let distinct = if distinct { "DISTINCT " } else { "" };
1353                format!("{}({distinct}{})", ast.name_text(name), list(args))
1354            }
1355            Expr::Cast { operand, ty, try_cast } => {
1356                let word = if try_cast { "TRY_CAST" } else { "CAST" };
1357                format!("{word}({} AS {})", show(ast, operand), ast.string(ty))
1358            }
1359            Expr::Case { operand, arms, otherwise } => {
1360                let arms = ast
1361                    .arm_list(arms)
1362                    .iter()
1363                    .map(|arm| format!("WHEN {} THEN {}", show(ast, arm.when), show(ast, arm.then)))
1364                    .collect::<Vec<_>>()
1365                    .join(" ");
1366                format!("CASE {} {arms} ELSE {} END", show(ast, operand), show(ast, otherwise))
1367            }
1368            Expr::Between { operand, low, high, negated } => {
1369                let not = if negated { "NOT " } else { "" };
1370                format!(
1371                    "({not}{} BETWEEN {} AND {})",
1372                    show(ast, operand),
1373                    show(ast, low),
1374                    show(ast, high)
1375                )
1376            }
1377            Expr::In { operand, list: items, negated } => {
1378                let not = if negated { "NOT " } else { "" };
1379                format!("({not}{} IN [{}])", show(ast, operand), list(items))
1380            }
1381            Expr::Row { items } => format!("ROW({})", list(items)),
1382            Expr::Subquery { query } => format!("({})", show_query(ast, query)),
1383        }
1384    }
1385
1386    /// One from item written back out.
1387    fn show_source(ast: &Ast, source: SourceRef) -> String {
1388        let alias = |alias: StrRef| match alias {
1389            NONE => String::new(),
1390            other => format!(" AS {}", ast.string(other)),
1391        };
1392        match ast.source(source) {
1393            Source::Table { name, alias: name_alias, .. } => {
1394                format!("{}{}", ast.name_text(name), alias(name_alias))
1395            }
1396            Source::Subquery { query, alias: query_alias, .. } => {
1397                format!("({}){}", show_query(ast, query), alias(query_alias))
1398            }
1399            Source::Join { left, right, kind, natural, on, using } => {
1400                let natural = if natural { "NATURAL " } else { "" };
1401                let on = if on == NONE { String::new() } else { format!(" ON {}", show(ast, on)) };
1402                let using = if using.is_empty() {
1403                    String::new()
1404                } else {
1405                    format!(" USING ({})", ast.name_text(using))
1406                };
1407                format!(
1408                    "({} {natural}{kind:?} JOIN {}{on}{using})",
1409                    show_source(ast, left),
1410                    show_source(ast, right)
1411                )
1412            }
1413        }
1414    }
1415
1416    /// One query written back out.
1417    fn show_query(ast: &Ast, index: QueryRef) -> String {
1418        let query = ast.query(index);
1419        let list = |slice: Slice| {
1420            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
1421        };
1422        let mut out = match query.body {
1423            QueryBody::SetOp { op, quantifier, by_name, left, right } => {
1424                let by_name = if by_name { " BY NAME" } else { "" };
1425                format!(
1426                    "({} {op:?} {quantifier:?}{by_name} {})",
1427                    show_query(ast, left),
1428                    show_query(ast, right)
1429                )
1430            }
1431            QueryBody::Select(index) => {
1432                let select = ast.select(index);
1433                let distinct = match select.distinct {
1434                    Distinct::No => String::new(),
1435                    Distinct::Yes => " DISTINCT".to_string(),
1436                    Distinct::On(on) => format!(" DISTINCT ON ({})", list(on)),
1437                };
1438                let targets = ast
1439                    .target_list(select.targets)
1440                    .iter()
1441                    .map(|target| match target.alias {
1442                        NONE => show(ast, target.expr),
1443                        alias => format!("{} AS {}", show(ast, target.expr), ast.string(alias)),
1444                    })
1445                    .collect::<Vec<_>>()
1446                    .join(", ");
1447                let mut out = format!("SELECT{distinct} {targets}");
1448                if !select.from.is_empty() {
1449                    let from = ast
1450                        .source_list(select.from)
1451                        .iter()
1452                        .map(|&source| show_source(ast, source))
1453                        .collect::<Vec<_>>()
1454                        .join(", ");
1455                    out += &format!(" FROM {from}");
1456                }
1457                if select.filter != NONE {
1458                    out += &format!(" WHERE {}", show(ast, select.filter));
1459                }
1460                if select.group_by_all {
1461                    out += " GROUP BY ALL";
1462                } else if !select.group_by.is_empty() {
1463                    out += &format!(" GROUP BY {}", list(select.group_by));
1464                }
1465                if select.having != NONE {
1466                    out += &format!(" HAVING {}", show(ast, select.having));
1467                }
1468                out
1469            }
1470        };
1471        if query.order_by_all {
1472            out += " ORDER BY ALL";
1473        } else if !query.order_by.is_empty() {
1474            let items = ast
1475                .order_list(query.order_by)
1476                .iter()
1477                .map(|item| format!("{} {:?} {:?}", show(ast, item.expr), item.order, item.nulls))
1478                .collect::<Vec<_>>()
1479                .join(", ");
1480            out += &format!(" ORDER BY {items}");
1481        }
1482        if query.limit != NONE {
1483            let percent = if query.limit_percent { "%" } else { "" };
1484            out += &format!(" LIMIT {}{percent}", show(ast, query.limit));
1485        }
1486        if query.offset != NONE {
1487            out += &format!(" OFFSET {}", show(ast, query.offset));
1488        }
1489        out
1490    }
1491
1492    /// One statement, transformed and written back out.
1493    fn round(query: &str) -> String {
1494        let ast = parse_ast(query).unwrap_or_else(|error| panic!("{query}: {error}"));
1495        assert_eq!(ast.statements.len(), 1, "{query} is one statement");
1496        let Statement::Query(index) = ast.statements[0];
1497        show_query(&ast, index)
1498    }
1499
1500    #[test]
1501    fn the_query_m0_has_to_run_transforms() {
1502        assert_eq!(round("SELECT * FROM t WHERE x > 5"), "SELECT * FROM t WHERE (x Gt 5)");
1503    }
1504
1505    #[test]
1506    fn every_statement_in_the_corpus_gets_a_defined_answer() {
1507        // The point of the test is the word defined. Forty of these are statement kinds and
1508        // clauses this milestone does not cover, and the requirement is not that they work, it is
1509        // that they fail by saying so. A panic, a silently dropped clause or an internal error
1510        // would each be a different bug and all three would be invisible without this.
1511        let mut done = 0;
1512        for query in CORPUS {
1513            match parse_ast(query) {
1514                Ok(ast) => {
1515                    assert_eq!(ast.statements.len(), 1, "{query}");
1516                    done += 1;
1517                }
1518                Err(error) => {
1519                    let message = error.to_string();
1520                    assert!(
1521                        message.starts_with("Not implemented Error"),
1522                        "{query} failed with {message}, which is not a not-implemented error"
1523                    );
1524                }
1525            }
1526        }
1527        // Not an assertion about the right number. It is a ratchet: this only moves up, and the
1528        // day it moves down somebody has taken a construct out without meaning to.
1529        assert!(done >= 19, "only {done} of the corpus transforms, which is fewer than it was");
1530    }
1531
1532    #[test]
1533    fn the_ast_is_far_smaller_than_the_parse_tree() {
1534        let query = CORPUS[4];
1535        let tree = parse(query).unwrap();
1536        let ast = parse_ast(query).unwrap();
1537        // The twenty precedence levels are the difference. Every one of them is a node in the
1538        // parse tree for every expression at every depth, and none of them survives into the AST.
1539        assert!(
1540            ast.node_count() * 20 < tree.arena_len(),
1541            "{} ast nodes against {} parse nodes",
1542            ast.node_count(),
1543            tree.arena_len()
1544        );
1545    }
1546
1547    #[test]
1548    fn precedence_comes_out_of_the_chain_and_into_the_tree() {
1549        assert_eq!(round("SELECT 1 + 2 * 3"), "SELECT (1 Add (2 Multiply 3))");
1550        assert_eq!(round("SELECT (1 + 2) * 3"), "SELECT ((1 Add 2) Multiply 3)");
1551        assert_eq!(round("SELECT 1 + 2 + 3"), "SELECT ((1 Add 2) Add 3)");
1552        assert_eq!(round("SELECT 1 - 2 - 3"), "SELECT ((1 Subtract 2) Subtract 3)");
1553        assert_eq!(
1554            round("SELECT a OR b AND c"),
1555            "SELECT (a Or (b And c))",
1556            "and binds tighter than or"
1557        );
1558    }
1559
1560    #[test]
1561    fn a_double_negation_is_two_nodes_and_not_none() {
1562        // Folding it would be an optimizer decision and this is not the optimizer. It also would
1563        // not be safe in general: `NOT NOT x` on a null is still null and on a non boolean it is
1564        // still an error, and both of those have to survive to the binder to be reported.
1565        assert_eq!(round("SELECT NOT NOT a"), "SELECT (Not (Not a))");
1566    }
1567
1568    #[test]
1569    fn a_parenthesised_single_expression_is_not_a_row() {
1570        assert_eq!(round("SELECT (a)"), "SELECT a");
1571        assert_eq!(round("SELECT (a, b)"), "SELECT ROW(a, b)");
1572    }
1573
1574    #[test]
1575    fn the_three_ways_to_write_an_alias_all_arrive() {
1576        assert_eq!(round("SELECT a AS b"), "SELECT a AS b");
1577        assert_eq!(round("SELECT a b"), "SELECT a AS b");
1578        assert_eq!(round("SELECT b: a"), "SELECT a AS b");
1579        assert_eq!(round("SELECT a"), "SELECT a", "and no alias when none was written");
1580    }
1581
1582    #[test]
1583    fn a_from_with_no_select_selects_everything() {
1584        // DuckDB's own shorthand. Inventing the star here rather than in the binder means the
1585        // binder never has to know that the clause it is looking at was the one that was missing.
1586        assert_eq!(round("FROM t"), "SELECT * FROM t");
1587        assert_eq!(round("FROM t SELECT a"), "SELECT a FROM t");
1588    }
1589
1590    #[test]
1591    fn joins_nest_to_the_left() {
1592        assert_eq!(
1593            round("SELECT * FROM a JOIN b ON a.i = b.i LEFT JOIN c USING (k)"),
1594            "SELECT * FROM ((a Inner JOIN b ON (a.i Eq b.i)) Left JOIN c USING (k))"
1595        );
1596        assert_eq!(
1597            round("SELECT * FROM a NATURAL JOIN b"),
1598            "SELECT * FROM (a NATURAL Inner JOIN b)"
1599        );
1600        assert_eq!(round("SELECT * FROM a CROSS JOIN b"), "SELECT * FROM (a Cross JOIN b)");
1601        assert_eq!(
1602            round("SELECT * FROM a POSITIONAL JOIN b"),
1603            "SELECT * FROM (a Positional JOIN b)"
1604        );
1605        assert_eq!(round("SELECT * FROM a, b"), "SELECT * FROM a, b", "a comma is not a join node");
1606    }
1607
1608    #[test]
1609    fn a_qualified_name_keeps_its_parts_however_it_was_spelled() {
1610        // Five grammar rules can produce a column reference and they disagree about which
1611        // component is a schema and which is a table. None of that is decidable without the
1612        // catalog, so the AST holds the parts and the binder decides.
1613        assert_eq!(round("SELECT a"), "SELECT a");
1614        assert_eq!(round("SELECT t.a"), "SELECT t.a");
1615        assert_eq!(round("SELECT s.t.a"), "SELECT s.t.a");
1616        assert_eq!(round("SELECT c.s.t.a"), "SELECT c.s.t.a");
1617        assert_eq!(round("SELECT * FROM s.t"), "SELECT * FROM s.t");
1618    }
1619
1620    #[test]
1621    fn a_star_can_be_qualified() {
1622        assert_eq!(round("SELECT *"), "SELECT *");
1623        assert_eq!(round("SELECT t.*"), "SELECT t.*");
1624        assert_eq!(round("SELECT s.t.*"), "SELECT s.t.*");
1625    }
1626
1627    #[test]
1628    fn a_quoted_identifier_keeps_its_case_and_loses_its_quotes() {
1629        // DuckDB does not fold identifier case at any point, quoted or not, which the tokenizer
1630        // work established by reading the source. So the only thing to do here is take the quotes
1631        // off and resolve the doubled ones.
1632        let ast = parse_ast("SELECT \"Mixed Case\", \"a\"\"b\"").unwrap();
1633        assert_eq!(ast.strings[0], "Mixed Case");
1634        assert_eq!(ast.strings[1], "a\"b");
1635    }
1636
1637    #[test]
1638    fn a_string_literal_is_decoded_and_adjacent_ones_are_joined() {
1639        assert_eq!(round("SELECT 'it''s'"), "SELECT 'it's'");
1640        assert_eq!(round("SELECT 'a'\n'b'"), "SELECT 'ab'", "the standard's adjacency rule");
1641    }
1642
1643    #[test]
1644    fn the_null_and_boolean_tests_are_postfix_unary_operators() {
1645        assert_eq!(round("SELECT x IS NULL"), "SELECT (IsNull x)");
1646        assert_eq!(round("SELECT x IS NOT NULL"), "SELECT (IsNotNull x)");
1647        assert_eq!(round("SELECT x ISNULL"), "SELECT (IsNull x)");
1648        assert_eq!(round("SELECT x NOTNULL"), "SELECT (IsNotNull x)");
1649        assert_eq!(round("SELECT x IS TRUE"), "SELECT (IsTrue x)");
1650        assert_eq!(round("SELECT x IS NOT FALSE"), "SELECT (IsNotFalse x)");
1651        assert_eq!(round("SELECT x IS DISTINCT FROM y"), "SELECT (x IsDistinctFrom y)");
1652        assert_eq!(round("SELECT x IS NOT DISTINCT FROM y"), "SELECT (x IsNotDistinctFrom y)");
1653    }
1654
1655    #[test]
1656    fn the_like_family_folds_its_negation_into_the_operator() {
1657        assert_eq!(round("SELECT x LIKE 'a'"), "SELECT (x Like 'a')");
1658        assert_eq!(round("SELECT x NOT LIKE 'a'"), "SELECT (x NotLike 'a')");
1659        assert_eq!(round("SELECT x ILIKE 'a'"), "SELECT (x ILike 'a')");
1660        assert_eq!(round("SELECT x ~~ 'a'"), "SELECT (x Like 'a')", "the operator spelling");
1661        assert_eq!(round("SELECT x !~~ 'a'"), "SELECT (x NotLike 'a')");
1662        assert_eq!(round("SELECT x SIMILAR TO 'a'"), "SELECT (x SimilarTo 'a')");
1663        // Glob has no negated operator to fold into, so the negation stays where it was written.
1664        assert_eq!(round("SELECT x NOT GLOB 'a'"), "SELECT (Not (x Glob 'a'))");
1665    }
1666
1667    #[test]
1668    fn between_and_in_carry_their_negation_as_a_flag() {
1669        assert_eq!(round("SELECT x BETWEEN 1 AND 2"), "SELECT (x BETWEEN 1 AND 2)");
1670        assert_eq!(round("SELECT x NOT BETWEEN 1 AND 2"), "SELECT (NOT x BETWEEN 1 AND 2)");
1671        assert_eq!(round("SELECT x IN (1, 2)"), "SELECT (x IN [1, 2])");
1672        assert_eq!(round("SELECT x NOT IN (1, 2)"), "SELECT (NOT x IN [1, 2])");
1673    }
1674
1675    #[test]
1676    fn both_spellings_of_a_cast_are_the_same_node() {
1677        assert_eq!(round("SELECT CAST(x AS BIGINT)"), "SELECT CAST(x AS BIGINT)");
1678        assert_eq!(round("SELECT x::BIGINT"), "SELECT CAST(x AS BIGINT)");
1679        assert_eq!(round("SELECT TRY_CAST(x AS BIGINT)"), "SELECT TRY_CAST(x AS BIGINT)");
1680        assert_eq!(
1681            round("SELECT x::DECIMAL(18, 3)"),
1682            "SELECT CAST(x AS DECIMAL(18, 3))",
1683            "the type is kept as text because parsing it is the type system's job"
1684        );
1685    }
1686
1687    #[test]
1688    fn a_case_keeps_its_arms_in_order() {
1689        assert_eq!(
1690            round("SELECT CASE WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"),
1691            "SELECT CASE - WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"
1692        );
1693        assert_eq!(
1694            round("SELECT CASE x WHEN 1 THEN 'a' END"),
1695            "SELECT CASE x WHEN 1 THEN 'a' ELSE - END",
1696            "a simple case keeps the operand and a missing else is not an implicit null yet"
1697        );
1698    }
1699
1700    #[test]
1701    fn a_field_access_and_a_method_call_are_ordinary_function_calls() {
1702        // Which is what DuckDB makes of them too. Giving each its own AST node would mean the
1703        // binder needs a rule for something the function resolver already handles.
1704        assert_eq!(round("SELECT (f(x)).y"), "SELECT struct_extract(f(x), 'y')");
1705        assert_eq!(round("SELECT a[1]"), "SELECT array_extract(a, 1)");
1706    }
1707
1708    #[test]
1709    fn an_aggregate_keeps_its_distinct() {
1710        assert_eq!(round("SELECT count(*)"), "SELECT count(*)");
1711        assert_eq!(round("SELECT count(DISTINCT x)"), "SELECT count(DISTINCT x)");
1712        assert_eq!(round("SELECT count(ALL x)"), "SELECT count(x)");
1713        assert_eq!(round("SELECT main.count(x)"), "SELECT main.count(x)");
1714    }
1715
1716    #[test]
1717    fn the_modifiers_hang_off_the_query_and_not_off_the_select() {
1718        // `a UNION b ORDER BY x` sorts the union. Putting the order by on the select would have
1719        // made that unrepresentable, which is why the grammar puts it outside the chain and why
1720        // the AST follows.
1721        assert_eq!(
1722            round("SELECT 1 UNION ALL SELECT 2 ORDER BY 1"),
1723            "(SELECT 1 Union All SELECT 2) ORDER BY 1 Unstated Unstated"
1724        );
1725        assert_eq!(
1726            round("SELECT a FROM t UNION SELECT b FROM u EXCEPT SELECT c FROM v"),
1727            "((SELECT a FROM t Union Unstated SELECT b FROM u) Except Unstated SELECT c FROM v)",
1728            "set operators are left associative"
1729        );
1730        assert_eq!(
1731            round("SELECT 1 UNION SELECT 2 INTERSECT SELECT 3"),
1732            "(SELECT 1 Union Unstated (SELECT 2 Intersect Unstated SELECT 3))",
1733            "and intersect binds tighter than the other two"
1734        );
1735    }
1736
1737    #[test]
1738    fn the_sort_and_limit_clauses_keep_what_was_written() {
1739        assert_eq!(
1740            round("SELECT a FROM t ORDER BY a"),
1741            "SELECT a FROM t ORDER BY a Unstated Unstated"
1742        );
1743        assert_eq!(
1744            round("SELECT a FROM t ORDER BY a DESC NULLS LAST"),
1745            "SELECT a FROM t ORDER BY a Descending Last"
1746        );
1747        assert_eq!(round("SELECT a FROM t ORDER BY ALL"), "SELECT a FROM t ORDER BY ALL");
1748        assert_eq!(round("SELECT a FROM t GROUP BY ALL"), "SELECT a FROM t GROUP BY ALL");
1749        assert_eq!(round("SELECT a FROM t LIMIT 10 OFFSET 5"), "SELECT a FROM t LIMIT 10 OFFSET 5");
1750        assert_eq!(round("SELECT a FROM t OFFSET 5 LIMIT 10"), "SELECT a FROM t LIMIT 10 OFFSET 5");
1751        assert_eq!(round("SELECT a FROM t LIMIT 10%"), "SELECT a FROM t LIMIT 10%");
1752        assert_eq!(round("SELECT a FROM t LIMIT ALL"), "SELECT a FROM t", "which is no limit");
1753    }
1754
1755    #[test]
1756    fn a_subquery_appears_in_both_places_it_can() {
1757        assert_eq!(
1758            round("SELECT * FROM (SELECT x FROM t) AS s"),
1759            "SELECT * FROM (SELECT x FROM t) AS s"
1760        );
1761        assert_eq!(round("SELECT (SELECT 1)"), "SELECT (SELECT 1)");
1762    }
1763
1764    #[test]
1765    fn distinct_on_keeps_its_expressions() {
1766        assert_eq!(round("SELECT DISTINCT a"), "SELECT DISTINCT a");
1767        assert_eq!(round("SELECT ALL a"), "SELECT a", "which is the default written out");
1768        assert_eq!(round("SELECT DISTINCT ON (a, b) a"), "SELECT DISTINCT ON (a, b) a");
1769    }
1770
1771    #[test]
1772    fn an_operator_the_dialect_does_not_name_is_kept_by_name() {
1773        // The grammar text says `OperatorLiteral <- Identifier`, which reads as though any bare
1774        // word could be written infix. It cannot. That rule is one of the 24 the matcher overrides
1775        // and it is overridden to the bare operator matcher, so what it takes is a run of operator
1776        // characters. Believing the body here would have produced a transformer that accepted
1777        // `a foo b`, which DuckDB rejects.
1778        assert_eq!(round("SELECT a <=> b"), "SELECT (a <=> b)");
1779        assert!(parse_ast("SELECT a foo b").is_err(), "a bare word is not an operator");
1780    }
1781
1782    #[test]
1783    fn a_script_is_a_list_of_statements() {
1784        let ast = parse_ast("SELECT 1; SELECT 2;").unwrap();
1785        assert_eq!(ast.statements.len(), 2);
1786        // A trailing semicolon makes an empty top level statement in the parse tree, because the
1787        // grammar's `Statement? (';'+ / EndOfInput)` is happy with nothing on both sides. It is
1788        // dropped here rather than pretended away in the matcher.
1789        let Statement::Query(second) = ast.statements[1];
1790        assert_eq!(show_query(&ast, second), "SELECT 2");
1791    }
1792
1793    #[test]
1794    fn an_unsupported_construct_names_itself_and_what_was_written() {
1795        let error = parse_ast("CREATE TABLE t (a INTEGER)").unwrap_err().to_string();
1796        assert!(error.starts_with("Not implemented Error"), "{error}");
1797        assert!(error.contains("CREATE TABLE t (a INTEGER)"), "{error}");
1798        assert!(error.contains("CreateStatement"), "{error}");
1799    }
1800
1801    #[test]
1802    fn a_long_construct_is_cut_short_in_the_message() {
1803        let query =
1804            format!("CREATE TABLE t AS SELECT {} FROM u", "averylongcolumnname, ".repeat(8));
1805        let error = parse_ast(&query).unwrap_err().to_string();
1806        assert!(error.contains("..."), "{error}");
1807        assert!(error.len() < 200, "{error}");
1808    }
1809
1810    #[test]
1811    fn the_transformer_never_panics_on_anything_the_matcher_accepts() {
1812        // The matcher accepts a good deal that means nothing, because the grammar does. Every one
1813        // of these parses and none of them is a statement this milestone covers, and the contract
1814        // is that the answer is an error either way.
1815        for query in [
1816            "SELECT",
1817            "FROM t SELECT",
1818            "SELECT * FROM t WHERE",
1819            "SELECT ()",
1820            "SELECT a FROM t GROUP BY ()",
1821        ] {
1822            let answer = parse_ast(query);
1823            if let Err(error) = answer {
1824                let message = error.to_string();
1825                assert!(
1826                    message.starts_with("Not implemented Error")
1827                        || message.starts_with("Parser Error"),
1828                    "{query} failed with {message}"
1829                );
1830            }
1831        }
1832    }
1833
1834    #[test]
1835    fn interning_means_a_name_written_twice_is_stored_once() {
1836        let ast = parse_ast("SELECT a, a, a FROM t WHERE a = a").unwrap();
1837        assert_eq!(ast.strings.iter().filter(|text| *text == "a").count(), 1);
1838    }
1839}