Skip to main content

kumosql_sql/
parser.rs

1//! Recursive-descent parser for GoogleSQL (BigQuery) statements, queries and expressions.
2//!
3//! Expressions use precedence climbing with BigQuery's operator precedence. Statements the AST
4//! does not model (`GRANT`, `CREATE MODEL`, ...) parse to [`Statement::Raw`] holding their text;
5//! a statement the parser does model but cannot read is an error.
6
7use crate::ast::*;
8use crate::error::{Result, SqlError};
9use crate::token::{is_reserved_keyword, tokenize, Punct, Span, Token, TokenKind};
10use serde::{Deserialize, Serialize};
11
12const MAX_DEPTH: usize = 200;
13
14/// What a significant token turned out to be, as the parser read it. Used by the formatter to
15/// change the case of keywords, function names, type names and literals only.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
17pub enum TokenRole {
18    Keyword,
19    Function,
20    Type,
21    /// `NULL`, `TRUE`, `FALSE`
22    Literal,
23    Identifier,
24    Other,
25}
26
27/// Statements with the tokens they were read from.
28#[derive(Debug, Clone)]
29pub struct ParsedScript {
30    pub statements: Vec<Statement>,
31    /// The significant tokens.
32    pub tokens: Vec<Token>,
33    /// The role of each significant token.
34    pub roles: Vec<TokenRole>,
35    /// The source span of each statement (without its semicolon).
36    pub spans: Vec<Span>,
37}
38
39/// Parse every statement of `sql` (separated by semicolons; a trailing one is optional).
40pub fn parse_statements(sql: &str) -> Result<Vec<Statement>> {
41    Ok(parse_script(sql)?.statements)
42}
43
44/// Parse `sql` keeping its tokens, their roles and each statement's span.
45pub fn parse_script(sql: &str) -> Result<ParsedScript> {
46    let tokens = tokenize(sql)?;
47    let mut parser = Parser::new(sql, tokens);
48    let (statements, spans) = parser.parse_statement_list()?;
49    Ok(ParsedScript {
50        statements,
51        roles: parser.roles,
52        tokens: parser.tokens,
53        spans,
54    })
55}
56
57/// Parse exactly one statement.
58pub fn parse_statement(sql: &str) -> Result<Statement> {
59    let mut statements = parse_statements(sql)?;
60    match statements.len() {
61        1 => Ok(statements.remove(0)),
62        0 => Err(SqlError::parse(
63            sql,
64            Span::new(0, sql.len()),
65            "expected a statement",
66        )),
67        n => Err(SqlError::parse(
68            sql,
69            Span::new(0, sql.len()),
70            format!("expected one statement, found {n}"),
71        )),
72    }
73}
74
75/// Parse exactly one query (a trailing semicolon is allowed).
76pub fn parse_query(sql: &str) -> Result<Query> {
77    match parse_statement(sql)? {
78        Statement::Query(q) => Ok(*q),
79        _ => Err(SqlError::parse(
80            sql,
81            Span::new(0, sql.len()),
82            "expected a query",
83        )),
84    }
85}
86
87/// Parse one expression.
88pub fn parse_expr(sql: &str) -> Result<Expr> {
89    let tokens = tokenize(sql)?;
90    let mut parser = Parser::new(sql, tokens);
91    let expr = parser.parse_expr()?;
92    parser.expect_end()?;
93    Ok(expr)
94}
95
96/// Parse one data type (`ARRAY<STRUCT<a INT64>>`).
97pub fn parse_data_type(sql: &str) -> Result<DataType> {
98    let tokens = tokenize(sql)?;
99    let mut parser = Parser::new(sql, tokens);
100    let ty = parser.parse_data_type()?;
101    parser.expect_end()?;
102    Ok(ty)
103}
104
105/// Words that may name a function even though they are reserved.
106const RESERVED_FUNCTIONS: &[&str] = &[
107    "IF", "LEFT", "RIGHT", "GROUPING", "RANGE", "COLLATE", "CONTAINS",
108];
109
110/// Functions BigQuery accepts without parentheses.
111const NO_PAREN_FUNCTIONS: &[&str] = &[
112    "CURRENT_DATE",
113    "CURRENT_DATETIME",
114    "CURRENT_TIME",
115    "CURRENT_TIMESTAMP",
116];
117
118/// Words that end a block of statements.
119const BLOCK_TERMINATORS: &[&str] = &["END", "ELSE", "ELSEIF", "WHEN", "UNTIL", "EXCEPTION"];
120
121/// The recursive-descent parser over significant tokens.
122pub struct Parser<'a> {
123    src: &'a str,
124    tokens: Vec<Token>,
125    roles: Vec<TokenRole>,
126    pos: usize,
127    depth: usize,
128    /// One past the highest token index whose role was set.
129    touched: usize,
130    /// Tokens split by [`Parser::expect_gt`], with their original form, so a failed attempt can undo them.
131    splits: Vec<(usize, Token)>,
132}
133
134impl<'a> Parser<'a> {
135    pub fn new(src: &'a str, tokens: Vec<Token>) -> Self {
136        let roles = vec![TokenRole::Other; tokens.len()];
137        Parser {
138            src,
139            tokens,
140            roles,
141            pos: 0,
142            depth: 0,
143            touched: 0,
144            splits: Vec::new(),
145        }
146    }
147
148    // ------------------------------------------------------------------ token helpers
149
150    fn peek(&self) -> Option<&Token> {
151        self.tokens.get(self.pos)
152    }
153
154    fn peek_nth(&self, n: usize) -> Option<&Token> {
155        self.tokens.get(self.pos + n)
156    }
157
158    fn at_end(&self) -> bool {
159        self.pos >= self.tokens.len()
160    }
161
162    fn peek_keyword(&self, keyword: &str) -> bool {
163        self.peek().is_some_and(|t| t.is_keyword(keyword))
164    }
165
166    fn peek_nth_keyword(&self, n: usize, keyword: &str) -> bool {
167        self.peek_nth(n).is_some_and(|t| t.is_keyword(keyword))
168    }
169
170    fn peek_any_keyword(&self, keywords: &[&str]) -> bool {
171        keywords.iter().any(|k| self.peek_keyword(k))
172    }
173
174    fn peek_punct(&self, punct: Punct) -> bool {
175        self.peek().is_some_and(|t| t.is_punct(punct))
176    }
177
178    fn peek_nth_punct(&self, n: usize, punct: Punct) -> bool {
179        self.peek_nth(n).is_some_and(|t| t.is_punct(punct))
180    }
181
182    fn set_role(&mut self, index: usize, role: TokenRole) {
183        if let Some(slot) = self.roles.get_mut(index) {
184            *slot = role;
185            self.touched = self.touched.max(index + 1);
186        }
187    }
188
189    fn parse_keyword(&mut self, keyword: &str) -> bool {
190        if self.peek_keyword(keyword) {
191            self.set_role(self.pos, TokenRole::Keyword);
192            self.pos += 1;
193            true
194        } else {
195            false
196        }
197    }
198
199    /// All of `keywords` in order, or nothing consumed.
200    fn parse_keywords(&mut self, keywords: &[&str]) -> bool {
201        if keywords
202            .iter()
203            .enumerate()
204            .all(|(i, k)| self.peek_nth_keyword(i, k))
205        {
206            for _ in keywords {
207                self.set_role(self.pos, TokenRole::Keyword);
208                self.pos += 1;
209            }
210            true
211        } else {
212            false
213        }
214    }
215
216    fn expect_keyword(&mut self, keyword: &str) -> Result<()> {
217        if self.parse_keyword(keyword) {
218            Ok(())
219        } else {
220            Err(self.error(&format!("expected {keyword}")))
221        }
222    }
223
224    fn expect_keywords(&mut self, keywords: &[&str]) -> Result<()> {
225        for k in keywords {
226            self.expect_keyword(k)?;
227        }
228        Ok(())
229    }
230
231    fn consume_punct(&mut self, punct: Punct) -> bool {
232        if self.peek_punct(punct) {
233            self.pos += 1;
234            true
235        } else {
236            false
237        }
238    }
239
240    fn expect_punct(&mut self, punct: Punct) -> Result<()> {
241        if self.consume_punct(punct) {
242            Ok(())
243        } else {
244            Err(self.error(&format!("expected '{}'", punct.as_str())))
245        }
246    }
247
248    /// `>`, splitting a `>>` or `>=` the lexer read as one token (`ARRAY<ARRAY<INT64>>`).
249    fn expect_gt(&mut self) -> Result<()> {
250        let kind = self.tokens.get(self.pos).map(|t| t.kind.clone());
251        match kind {
252            Some(TokenKind::Punct(Punct::Gt)) => {
253                self.pos += 1;
254                Ok(())
255            }
256            Some(TokenKind::Punct(p @ (Punct::ShiftRight | Punct::GtEq))) => {
257                let original = self.tokens[self.pos].clone();
258                self.splits.push((self.pos, original));
259                let rest = if p == Punct::ShiftRight {
260                    Punct::Gt
261                } else {
262                    Punct::Eq
263                };
264                let token = &mut self.tokens[self.pos];
265                token.kind = TokenKind::Punct(rest);
266                token.text = rest.as_str().to_string();
267                token.span.start += 1;
268                Ok(())
269            }
270            _ => Err(self.error("expected '>'")),
271        }
272    }
273
274    fn error(&self, message: &str) -> SqlError {
275        let span = match self.peek() {
276            Some(t) => t.span,
277            None => Span::new(self.src.len(), self.src.len()),
278        };
279        let found = match self.peek() {
280            Some(t) => describe(t),
281            None => "end of input".to_string(),
282        };
283        SqlError::parse(self.src, span, format!("{message}, found {found}"))
284    }
285
286    fn expect_end(&self) -> Result<()> {
287        if self.at_end() {
288            Ok(())
289        } else {
290            Err(self.error("expected end of input"))
291        }
292    }
293
294    fn enter(&mut self) -> Result<()> {
295        self.depth += 1;
296        if self.depth > MAX_DEPTH {
297            Err(self.error("nested too deeply"))
298        } else {
299            Ok(())
300        }
301    }
302
303    fn leave(&mut self) {
304        self.depth -= 1;
305    }
306
307    /// Try `f`; on failure rewind (roles included) and return `None`.
308    fn attempt<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Option<T> {
309        let start = self.pos;
310        let depth = self.depth;
311        let touched = std::mem::replace(&mut self.touched, start);
312        let splits = self.splits.len();
313        let result = f(self);
314        let reached = self.touched;
315        self.touched = touched.max(reached);
316        match result {
317            Ok(value) => Some(value),
318            Err(_) => {
319                // roles past `start` were only ever set by this attempt
320                for role in &mut self.roles[start.min(reached)..reached] {
321                    *role = TokenRole::Other;
322                }
323                while self.splits.len() > splits {
324                    if let Some((index, token)) = self.splits.pop() {
325                        self.tokens[index] = token;
326                    }
327                }
328                self.pos = start;
329                self.depth = depth;
330                None
331            }
332        }
333    }
334
335    // ------------------------------------------------------------------ identifiers
336
337    fn is_identifier_token(token: &Token) -> bool {
338        match &token.kind {
339            TokenKind::Word => !is_reserved_keyword(&token.text),
340            TokenKind::QuotedIdentifier(_) => true,
341            _ => false,
342        }
343    }
344
345    fn peek_identifier(&self) -> bool {
346        self.peek().is_some_and(Self::is_identifier_token)
347    }
348
349    /// An unreserved word or a backtick-quoted name.
350    pub fn parse_identifier(&mut self) -> Result<Ident> {
351        let Some(token) = self.peek().cloned() else {
352            return Err(self.error("expected an identifier"));
353        };
354        let ident = match token.kind {
355            TokenKind::Word if !is_reserved_keyword(&token.text) => Ident::new(token.text),
356            TokenKind::QuotedIdentifier(value) => Ident::quoted(value),
357            _ => return Err(self.error("expected an identifier")),
358        };
359        self.set_role(self.pos, TokenRole::Identifier);
360        self.pos += 1;
361        Ok(ident)
362    }
363
364    /// A name part after a dot, where reserved words are allowed.
365    fn parse_path_part(&mut self) -> Result<Ident> {
366        let Some(token) = self.peek().cloned() else {
367            return Err(self.error("expected a name"));
368        };
369        match token.kind {
370            TokenKind::Word => {
371                self.set_role(self.pos, TokenRole::Identifier);
372                self.pos += 1;
373                Ok(Ident::new(token.text))
374            }
375            TokenKind::QuotedIdentifier(value) => {
376                self.set_role(self.pos, TokenRole::Identifier);
377                self.pos += 1;
378                Ok(Ident::quoted(value))
379            }
380            TokenKind::Integer => {
381                // `t.2020_sales`: digits then an adjacent word
382                self.set_role(self.pos, TokenRole::Identifier);
383                self.pos += 1;
384                let mut text = token.text.clone();
385                let mut end = token.span.end;
386                while let Some(next) = self.peek() {
387                    if next.span.start == end
388                        && matches!(next.kind, TokenKind::Word | TokenKind::Integer)
389                    {
390                        text.push_str(&next.text);
391                        end = next.span.end;
392                        self.set_role(self.pos, TokenRole::Identifier);
393                        self.pos += 1;
394                    } else {
395                        break;
396                    }
397                }
398                Ok(Ident::new(text))
399            }
400            _ => Err(self.error("expected a name")),
401        }
402    }
403
404    /// A dotted name. With `table`, the first part may hold dashes (`my-project.ds.t`).
405    pub fn parse_object_name(&mut self, table: bool) -> Result<ObjectName> {
406        let first = if table {
407            self.parse_table_name_first_part()?
408        } else {
409            self.parse_identifier()?
410        };
411        let mut parts = vec![first];
412        while self.peek_punct(Punct::Dot)
413            && self.peek_nth(1).is_some_and(|t| {
414                matches!(
415                    t.kind,
416                    TokenKind::Word | TokenKind::QuotedIdentifier(_) | TokenKind::Integer
417                )
418            })
419        {
420            self.pos += 1;
421            parts.push(self.parse_path_part()?);
422        }
423        Ok(ObjectName(parts))
424    }
425
426    fn parse_table_name_first_part(&mut self) -> Result<Ident> {
427        let Some(token) = self.peek().cloned() else {
428            return Err(self.error("expected a table name"));
429        };
430        match &token.kind {
431            TokenKind::QuotedIdentifier(_) => self.parse_identifier(),
432            TokenKind::Word if !is_reserved_keyword(&token.text) => {
433                self.set_role(self.pos, TokenRole::Identifier);
434                self.pos += 1;
435                let mut text = token.text.clone();
436                let mut end = token.span.end;
437                // `my-project-123`: dashes and digits written without spaces
438                loop {
439                    let dash = self
440                        .peek()
441                        .is_some_and(|t| t.is_punct(Punct::Minus) && t.span.start == end);
442                    let after = self.peek_nth(1).cloned();
443                    match (dash, after) {
444                        (true, Some(next))
445                            if next.span.start == end + 1
446                                && matches!(next.kind, TokenKind::Word | TokenKind::Integer) =>
447                        {
448                            text.push('-');
449                            text.push_str(&next.text);
450                            end = next.span.end;
451                            self.set_role(self.pos, TokenRole::Identifier);
452                            self.set_role(self.pos + 1, TokenRole::Identifier);
453                            self.pos += 2;
454                            while let Some(more) = self.peek() {
455                                if more.span.start == end
456                                    && matches!(more.kind, TokenKind::Word | TokenKind::Integer)
457                                {
458                                    text.push_str(&more.text);
459                                    end = more.span.end;
460                                    self.set_role(self.pos, TokenRole::Identifier);
461                                    self.pos += 1;
462                                } else {
463                                    break;
464                                }
465                            }
466                        }
467                        _ => break,
468                    }
469                }
470                Ok(Ident::new(text))
471            }
472            _ => Err(self.error("expected a table name")),
473        }
474    }
475
476    fn parse_identifier_list(&mut self) -> Result<Vec<Ident>> {
477        let mut out = vec![self.parse_identifier()?];
478        while self.consume_punct(Punct::Comma) {
479            out.push(self.parse_identifier()?);
480        }
481        Ok(out)
482    }
483
484    fn parse_parenthesized_identifiers(&mut self) -> Result<Vec<Ident>> {
485        self.expect_punct(Punct::LParen)?;
486        let list = self.parse_identifier_list()?;
487        self.expect_punct(Punct::RParen)?;
488        Ok(list)
489    }
490
491    /// `AS name` or an implicit alias. `table` excludes the words that start a table operator.
492    fn parse_optional_alias(&mut self, table: bool) -> Result<Option<Ident>> {
493        if self.parse_keyword("AS") {
494            return self.parse_identifier().map(Some);
495        }
496        let Some(token) = self.peek() else {
497            return Ok(None);
498        };
499        if !Self::is_identifier_token(token) {
500            return Ok(None);
501        }
502        if table && token.is_word() {
503            let upper = token.upper();
504            let next_paren = self.peek_nth_punct(1, Punct::LParen);
505            if ((upper == "PIVOT" || upper == "MATCH_RECOGNIZE" || upper == "ALIGN") && next_paren)
506                || (upper == "UNPIVOT"
507                    && (next_paren
508                        || self.peek_nth_keyword(1, "INCLUDE")
509                        || self.peek_nth_keyword(1, "EXCLUDE")))
510            {
511                return Ok(None);
512            }
513        }
514        self.parse_identifier().map(Some)
515    }
516
517    // ------------------------------------------------------------------ statements
518
519    fn parse_statement_list(&mut self) -> Result<(Vec<Statement>, Vec<Span>)> {
520        let mut statements = Vec::new();
521        let mut spans = Vec::new();
522        loop {
523            while self.consume_punct(Punct::Semicolon) {}
524            if self.at_end() {
525                break;
526            }
527            let start = self.tokens[self.pos].span.start;
528            let statement = self.parse_statement()?;
529            let end = self.tokens[self.pos - 1].span.end;
530            statements.push(statement);
531            spans.push(Span::new(start, end));
532            if self.at_end() {
533                break;
534            }
535            if !self.consume_punct(Punct::Semicolon) {
536                return Err(self.error("expected ';' or end of input after the statement"));
537            }
538        }
539        Ok((statements, spans))
540    }
541
542    /// Statements up to one of `terminators` (each followed by a semicolon).
543    fn parse_block(&mut self, terminators: &[&str]) -> Result<Vec<Statement>> {
544        let mut out = Vec::new();
545        loop {
546            while self.consume_punct(Punct::Semicolon) {}
547            if self.at_end() {
548                return Err(self.error("unterminated block"));
549            }
550            if self.peek_any_keyword(terminators) && !self.terminator_is_statement() {
551                break;
552            }
553            out.push(self.parse_statement()?);
554            if !self.consume_punct(Punct::Semicolon) && !self.peek_any_keyword(BLOCK_TERMINATORS) {
555                return Err(self.error("expected ';' after the statement"));
556            }
557        }
558        Ok(out)
559    }
560
561    /// `WHEN` can only be a terminator; `END` always is. Nothing to disambiguate today, but a
562    /// statement starting with `CASE` is not confused with the block terminators.
563    fn terminator_is_statement(&self) -> bool {
564        false
565    }
566
567    /// Parse one statement at the current position.
568    pub fn parse_statement(&mut self) -> Result<Statement> {
569        self.enter()?;
570        let result = self.parse_statement_inner();
571        self.leave();
572        result
573    }
574
575    fn parse_statement_inner(&mut self) -> Result<Statement> {
576        let start = self.pos;
577        // `label: BEGIN|LOOP|WHILE|FOR|REPEAT`
578        let label = if self.peek_identifier()
579            && self.peek_nth_punct(1, Punct::Colon)
580            && ["BEGIN", "LOOP", "WHILE", "FOR", "REPEAT"]
581                .iter()
582                .any(|k| self.peek_nth_keyword(2, k))
583        {
584            let label = self.parse_identifier()?;
585            self.pos += 1;
586            Some(label)
587        } else {
588            None
589        };
590        let labelled = label.is_some();
591        let Some(token) = self.peek().cloned() else {
592            return Err(self.error("expected a statement"));
593        };
594        if token.is_punct(Punct::LParen) {
595            return Ok(Statement::Query(Box::new(self.parse_query()?)));
596        }
597        if !token.is_word() {
598            return Err(self.error("expected a statement"));
599        }
600        let statement = match token.upper().as_str() {
601            "SELECT" | "WITH" | "FROM" => Statement::Query(Box::new(self.parse_query()?)),
602            "CREATE" => self.parse_create(start)?,
603            "INSERT" => self.parse_insert()?,
604            "UPDATE" => self.parse_update()?,
605            "DELETE" => self.parse_delete()?,
606            "MERGE" => self.parse_merge()?,
607            "DROP" => self.parse_drop(start)?,
608            "ALTER" => self.parse_alter(start)?,
609            "TRUNCATE" => {
610                self.expect_keywords(&["TRUNCATE", "TABLE"])?;
611                Statement::Truncate {
612                    name: self.parse_object_name(true)?,
613                }
614            }
615            "DECLARE" => self.parse_declare()?,
616            "SET" => self.parse_set()?,
617            "BEGIN" => self.parse_begin(label)?,
618            "IF" => self.parse_if()?,
619            "LOOP" => {
620                self.expect_keyword("LOOP")?;
621                let body = self.parse_block(&["END"])?;
622                self.expect_keywords(&["END", "LOOP"])?;
623                self.skip_end_label(&label);
624                Statement::Loop { label, body }
625            }
626            "WHILE" => {
627                self.expect_keyword("WHILE")?;
628                let condition = self.parse_expr()?;
629                self.expect_keyword("DO")?;
630                let body = self.parse_block(&["END"])?;
631                self.expect_keywords(&["END", "WHILE"])?;
632                self.skip_end_label(&label);
633                Statement::While {
634                    label,
635                    condition,
636                    body,
637                }
638            }
639            "FOR" => {
640                self.expect_keyword("FOR")?;
641                let variable = self.parse_identifier()?;
642                self.expect_keyword("IN")?;
643                self.expect_punct(Punct::LParen)?;
644                let query = self.parse_query()?;
645                self.expect_punct(Punct::RParen)?;
646                self.expect_keyword("DO")?;
647                let body = self.parse_block(&["END"])?;
648                self.expect_keywords(&["END", "FOR"])?;
649                self.skip_end_label(&label);
650                Statement::ForIn {
651                    label,
652                    variable,
653                    query: Box::new(query),
654                    body,
655                }
656            }
657            "REPEAT" => {
658                self.expect_keyword("REPEAT")?;
659                let body = self.parse_block(&["UNTIL"])?;
660                self.expect_keyword("UNTIL")?;
661                let until = self.parse_expr()?;
662                self.expect_keywords(&["END", "REPEAT"])?;
663                self.skip_end_label(&label);
664                Statement::Repeat { label, body, until }
665            }
666            "CASE" => self.parse_case_statement()?,
667            "BREAK" | "LEAVE" | "CONTINUE" | "ITERATE" => {
668                let kind = match token.upper().as_str() {
669                    "BREAK" => ControlKind::Break,
670                    "LEAVE" => ControlKind::Leave,
671                    "CONTINUE" => ControlKind::Continue,
672                    _ => ControlKind::Iterate,
673                };
674                self.set_role(self.pos, TokenRole::Keyword);
675                self.pos += 1;
676                let label = if self.peek_identifier() {
677                    Some(self.parse_identifier()?)
678                } else {
679                    None
680                };
681                Statement::Control { kind, label }
682            }
683            "RETURN" => {
684                self.expect_keyword("RETURN")?;
685                Statement::Return
686            }
687            "RAISE" => {
688                self.expect_keyword("RAISE")?;
689                let message = if self.parse_keywords(&["USING", "MESSAGE"]) {
690                    self.expect_punct(Punct::Eq)?;
691                    Some(self.parse_expr()?)
692                } else {
693                    None
694                };
695                Statement::Raise { message }
696            }
697            "CALL" => {
698                self.expect_keyword("CALL")?;
699                let procedure = self.parse_object_name(true)?;
700                self.set_role(self.pos - 1, TokenRole::Function);
701                self.expect_punct(Punct::LParen)?;
702                let mut args = Vec::new();
703                if !self.peek_punct(Punct::RParen) {
704                    args.push(self.parse_expr()?);
705                    while self.consume_punct(Punct::Comma) {
706                        args.push(self.parse_expr()?);
707                    }
708                }
709                self.expect_punct(Punct::RParen)?;
710                Statement::Call { procedure, args }
711            }
712            "EXECUTE" => self.parse_execute()?,
713            "ASSERT" => {
714                self.expect_keyword("ASSERT")?;
715                let condition = self.parse_expr()?;
716                let description = if self.parse_keyword("AS") {
717                    Some(self.parse_expr()?)
718                } else {
719                    None
720                };
721                Statement::Assert {
722                    condition,
723                    description,
724                }
725            }
726            "COMMIT" | "ROLLBACK" => {
727                let kind = if token.is_keyword("COMMIT") {
728                    TransactionKind::Commit
729                } else {
730                    TransactionKind::Rollback
731                };
732                self.set_role(self.pos, TokenRole::Keyword);
733                self.pos += 1;
734                self.parse_keyword("TRANSACTION");
735                Statement::Transaction(kind)
736            }
737            "EXPORT" if self.peek_nth_keyword(1, "DATA") => self.parse_export()?,
738            "LOAD" if self.peek_nth_keyword(1, "DATA") => self.parse_load(start)?,
739            _ => self.parse_raw(start)?,
740        };
741        if labelled
742            && !matches!(
743                statement,
744                Statement::BeginEnd { .. }
745                    | Statement::Loop { .. }
746                    | Statement::While { .. }
747                    | Statement::ForIn { .. }
748                    | Statement::Repeat { .. }
749            )
750        {
751            return Err(self.error("a label must precede a block or loop"));
752        }
753        Ok(statement)
754    }
755
756    fn skip_end_label(&mut self, label: &Option<Ident>) {
757        if label.is_some() && self.peek_identifier() {
758            self.pos += 1;
759        }
760    }
761
762    /// The statement from `start` to its top-level semicolon, kept as text.
763    fn parse_raw(&mut self, start: usize) -> Result<Statement> {
764        self.pos = start;
765        let mut depth = 0usize;
766        let begin = self.tokens[start].span.start;
767        let mut end = begin;
768        while let Some(token) = self.peek() {
769            match token.kind {
770                TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::LBracket) => depth += 1,
771                TokenKind::Punct(Punct::RParen) | TokenKind::Punct(Punct::RBracket) => {
772                    depth = depth.saturating_sub(1)
773                }
774                TokenKind::Punct(Punct::Semicolon) if depth == 0 => break,
775                _ => {}
776            }
777            end = token.span.end;
778            self.pos += 1;
779        }
780        Ok(Statement::Raw(self.src[begin..end].to_string()))
781    }
782
783    fn parse_create(&mut self, start: usize) -> Result<Statement> {
784        self.expect_keyword("CREATE")?;
785        let or_replace = self.parse_keywords(&["OR", "REPLACE"]);
786        let temporary = self.parse_keyword("TEMP") || self.parse_keyword("TEMPORARY");
787        if self.parse_keywords(&["TABLE", "FUNCTION"]) {
788            return self.parse_create_table_function(or_replace, temporary);
789        }
790        if self.parse_keyword("TABLE") {
791            return self.parse_create_table(or_replace, temporary, TableKind::Table);
792        }
793        if self.peek_keyword("EXTERNAL") || self.peek_keyword("SNAPSHOT") {
794            let kind = if self.parse_keyword("EXTERNAL") {
795                TableKind::External
796            } else {
797                self.expect_keyword("SNAPSHOT")?;
798                TableKind::Snapshot
799            };
800            if !self.parse_keyword("TABLE") {
801                return self.parse_raw(start);
802            }
803            // unusual external-table clauses stay as text rather than failing
804            return match self.attempt(|p| p.parse_create_table(or_replace, temporary, kind)) {
805                Some(statement) => Ok(statement),
806                None => self.parse_raw(start),
807            };
808        }
809        if self.parse_keywords(&["MATERIALIZED", "VIEW"]) {
810            return self.parse_create_view(or_replace, true);
811        }
812        if self.parse_keyword("VIEW") {
813            return self.parse_create_view(or_replace, false);
814        }
815        if self.parse_keywords(&["AGGREGATE", "FUNCTION"]) {
816            return self.parse_create_function(or_replace, temporary, true, start);
817        }
818        if self.parse_keyword("FUNCTION") {
819            return self.parse_create_function(or_replace, temporary, false, start);
820        }
821        if self.parse_keyword("PROCEDURE") {
822            return match self.attempt(|p| p.parse_create_procedure(or_replace)) {
823                Some(statement) => Ok(statement),
824                None => self.parse_raw(start),
825            };
826        }
827        if self.parse_keyword("SCHEMA") {
828            let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
829            let name = self.parse_object_name(true)?;
830            let default_collate = if self.parse_keywords(&["DEFAULT", "COLLATE"]) {
831                Some(self.parse_expr()?)
832            } else {
833                None
834            };
835            let options = self.parse_optional_options()?;
836            return Ok(Statement::CreateSchema(Box::new(CreateSchema {
837                if_not_exists,
838                name,
839                default_collate,
840                options,
841            })));
842        }
843        self.parse_raw(start)
844    }
845
846    fn parse_optional_options(&mut self) -> Result<Vec<SqlOption>> {
847        if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
848            self.parse_keyword("OPTIONS");
849            self.parse_options_body()
850        } else {
851            Ok(Vec::new())
852        }
853    }
854
855    fn parse_options_body(&mut self) -> Result<Vec<SqlOption>> {
856        self.expect_punct(Punct::LParen)?;
857        let mut options = Vec::new();
858        while !self.peek_punct(Punct::RParen) {
859            let name = self.parse_path_part()?;
860            self.expect_punct(Punct::Eq)?;
861            let value = self.parse_expr()?;
862            options.push(SqlOption { name, value });
863            if !self.consume_punct(Punct::Comma) {
864                break;
865            }
866        }
867        self.expect_punct(Punct::RParen)?;
868        Ok(options)
869    }
870
871    fn parse_cluster_by(&mut self) -> Result<Vec<Expr>> {
872        let mut out = vec![self.parse_expr()?];
873        while self.consume_punct(Punct::Comma) {
874            out.push(self.parse_expr()?);
875        }
876        Ok(out)
877    }
878
879    fn parse_create_table(
880        &mut self,
881        or_replace: bool,
882        temporary: bool,
883        kind: TableKind,
884    ) -> Result<Statement> {
885        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
886        let name = self.parse_object_name(true)?;
887        let mut table = CreateTable {
888            or_replace,
889            temporary,
890            kind,
891            if_not_exists,
892            name,
893            columns: Vec::new(),
894            constraints: Vec::new(),
895            copy: None,
896            with_connection: None,
897            default_collate: None,
898            partition_by: None,
899            cluster_by: Vec::new(),
900            options: Vec::new(),
901            query: None,
902        };
903        if self.peek_punct(Punct::LParen) && !self.paren_starts_query() {
904            self.pos += 1;
905            loop {
906                if self.peek_keyword("PRIMARY")
907                    || self.peek_keyword("FOREIGN")
908                    || self.peek_keyword("CONSTRAINT")
909                {
910                    table.constraints.push(self.parse_table_constraint()?);
911                } else {
912                    table.columns.push(self.parse_column_def()?);
913                }
914                if !self.consume_punct(Punct::Comma) || self.peek_punct(Punct::RParen) {
915                    break;
916                }
917            }
918            self.expect_punct(Punct::RParen)?;
919        }
920        loop {
921            if self.peek_any_keyword(&["LIKE", "COPY", "CLONE"]) && table.copy.is_none() {
922                let copy_kind = if self.parse_keyword("LIKE") {
923                    CopyKind::Like
924                } else if self.parse_keyword("COPY") {
925                    CopyKind::Copy
926                } else {
927                    self.expect_keyword("CLONE")?;
928                    CopyKind::Clone
929                };
930                let source = self.parse_object_name(true)?;
931                let system_time = self.parse_system_time()?;
932                table.copy = Some(TableCopy {
933                    kind: copy_kind,
934                    source,
935                    system_time,
936                });
937            } else if self.parse_keywords(&["DEFAULT", "COLLATE"]) {
938                table.default_collate = Some(self.parse_expr()?);
939            } else if self.parse_keywords(&["PARTITION", "BY"]) {
940                table.partition_by = Some(self.parse_expr()?);
941            } else if self.parse_keywords(&["CLUSTER", "BY"]) {
942                table.cluster_by = self.parse_cluster_by()?;
943            } else if self.parse_keywords(&["WITH", "CONNECTION"]) {
944                table.with_connection = Some(self.parse_object_name(true)?);
945            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
946                table.options = self.parse_optional_options()?;
947            } else if self.parse_keyword("AS") {
948                table.query = Some(Box::new(self.parse_query()?));
949                break;
950            } else {
951                break;
952            }
953        }
954        Ok(Statement::CreateTable(Box::new(table)))
955    }
956
957    fn parse_system_time(&mut self) -> Result<Option<Expr>> {
958        if self.parse_keywords(&["FOR", "SYSTEM_TIME", "AS", "OF"]) {
959            Ok(Some(self.parse_expr()?))
960        } else {
961            Ok(None)
962        }
963    }
964
965    fn parse_table_constraint(&mut self) -> Result<TableConstraint> {
966        let name = if self.parse_keyword("CONSTRAINT") {
967            Some(self.parse_identifier()?)
968        } else {
969            None
970        };
971        if self.parse_keywords(&["PRIMARY", "KEY"]) {
972            let columns = self.parse_parenthesized_identifiers()?;
973            let not_enforced = self.parse_keywords(&["NOT", "ENFORCED"]);
974            return Ok(TableConstraint::PrimaryKey {
975                columns,
976                not_enforced,
977            });
978        }
979        self.expect_keywords(&["FOREIGN", "KEY"])?;
980        let columns = self.parse_parenthesized_identifiers()?;
981        self.expect_keyword("REFERENCES")?;
982        let foreign_table = self.parse_object_name(true)?;
983        let referred_columns = self.parse_parenthesized_identifiers()?;
984        let not_enforced = self.parse_keywords(&["NOT", "ENFORCED"]);
985        Ok(TableConstraint::ForeignKey {
986            name,
987            columns,
988            foreign_table,
989            referred_columns,
990            not_enforced,
991        })
992    }
993
994    fn parse_column_def(&mut self) -> Result<ColumnDef> {
995        let name = self.parse_identifier()?;
996        let data_type = self.parse_data_type()?;
997        let mut column = ColumnDef {
998            name,
999            data_type,
1000            collate: None,
1001            not_null: false,
1002            default: None,
1003            primary_key: false,
1004            options: Vec::new(),
1005        };
1006        loop {
1007            if self.parse_keyword("COLLATE") {
1008                column.collate = Some(self.parse_expr()?);
1009            } else if self.parse_keywords(&["NOT", "NULL"]) {
1010                column.not_null = true;
1011            } else if self.parse_keyword("DEFAULT") {
1012                column.default = Some(self.parse_expr()?);
1013            } else if self.parse_keywords(&["PRIMARY", "KEY", "NOT", "ENFORCED"]) {
1014                column.primary_key = true;
1015            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
1016                column.options = self.parse_optional_options()?;
1017            } else {
1018                break;
1019            }
1020        }
1021        Ok(column)
1022    }
1023
1024    fn parse_create_view(&mut self, or_replace: bool, materialized: bool) -> Result<Statement> {
1025        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1026        let name = self.parse_object_name(true)?;
1027        let mut columns = Vec::new();
1028        if self.peek_punct(Punct::LParen) && !self.paren_starts_query() {
1029            self.pos += 1;
1030            loop {
1031                let name = self.parse_identifier()?;
1032                let options = self.parse_optional_options()?;
1033                columns.push(ViewColumn { name, options });
1034                if !self.consume_punct(Punct::Comma) {
1035                    break;
1036                }
1037            }
1038            self.expect_punct(Punct::RParen)?;
1039        }
1040        let mut partition_by = None;
1041        let mut cluster_by = Vec::new();
1042        let mut options = Vec::new();
1043        loop {
1044            if self.parse_keywords(&["PARTITION", "BY"]) {
1045                partition_by = Some(self.parse_expr()?);
1046            } else if self.parse_keywords(&["CLUSTER", "BY"]) {
1047                cluster_by = self.parse_cluster_by()?;
1048            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
1049                options = self.parse_optional_options()?;
1050            } else {
1051                break;
1052            }
1053        }
1054        self.expect_keyword("AS")?;
1055        let query = self.parse_query()?;
1056        Ok(Statement::CreateView(Box::new(CreateView {
1057            or_replace,
1058            materialized,
1059            if_not_exists,
1060            name,
1061            columns,
1062            partition_by,
1063            cluster_by,
1064            options,
1065            query: Box::new(query),
1066        })))
1067    }
1068
1069    fn parse_param_type(&mut self) -> Result<ParamType> {
1070        if self.parse_keywords(&["ANY", "TYPE"]) {
1071            return Ok(ParamType::AnyType);
1072        }
1073        if self.parse_keywords(&["ANY", "TABLE"]) {
1074            return Ok(ParamType::AnyTable);
1075        }
1076        if self.peek_keyword("TABLE") && self.peek_nth_punct(1, Punct::Lt) {
1077            self.parse_keyword("TABLE");
1078            self.pos += 1;
1079            let fields = self.parse_struct_fields()?;
1080            return Ok(ParamType::Table(fields));
1081        }
1082        Ok(ParamType::Type(self.parse_data_type()?))
1083    }
1084
1085    fn parse_function_params(&mut self) -> Result<Vec<FunctionParam>> {
1086        self.expect_punct(Punct::LParen)?;
1087        let mut params = Vec::new();
1088        while !self.peek_punct(Punct::RParen) {
1089            let name = self.parse_identifier()?;
1090            let param_type = self.parse_param_type()?;
1091            let not_aggregate = self.parse_keywords(&["NOT", "AGGREGATE"]);
1092            params.push(FunctionParam {
1093                name,
1094                param_type,
1095                not_aggregate,
1096            });
1097            if !self.consume_punct(Punct::Comma) {
1098                break;
1099            }
1100        }
1101        self.expect_punct(Punct::RParen)?;
1102        Ok(params)
1103    }
1104
1105    fn parse_create_function(
1106        &mut self,
1107        or_replace: bool,
1108        temporary: bool,
1109        aggregate: bool,
1110        start: usize,
1111    ) -> Result<Statement> {
1112        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1113        let name = self.parse_object_name(true)?;
1114        self.set_role(self.pos - 1, TokenRole::Function);
1115        let params = self.parse_function_params()?;
1116        let mut function = CreateFunction {
1117            or_replace,
1118            temporary,
1119            aggregate,
1120            if_not_exists,
1121            name,
1122            params,
1123            returns: None,
1124            determinism: None,
1125            language: None,
1126            options: Vec::new(),
1127            body: FunctionBody::None,
1128        };
1129        loop {
1130            if self.parse_keyword("RETURNS") {
1131                function.returns = Some(self.parse_data_type()?);
1132            } else if self.parse_keyword("DETERMINISTIC") {
1133                function.determinism = Some(true);
1134            } else if self.parse_keywords(&["NOT", "DETERMINISTIC"]) {
1135                function.determinism = Some(false);
1136            } else if self.parse_keyword("LANGUAGE") {
1137                function.language = Some(self.parse_identifier()?);
1138            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
1139                function.options = self.parse_optional_options()?;
1140            } else if self.parse_keywords(&["REMOTE", "WITH", "CONNECTION"]) {
1141                function.body = FunctionBody::Remote(self.parse_object_name(true)?);
1142            } else if self.parse_keyword("AS") {
1143                if self.consume_punct(Punct::LParen) {
1144                    let expr = if self.peek_query_start() {
1145                        Expr::Subquery(Box::new(self.parse_query()?))
1146                    } else {
1147                        self.parse_expr()?
1148                    };
1149                    self.expect_punct(Punct::RParen)?;
1150                    function.body = FunctionBody::Expr(expr);
1151                } else {
1152                    match self.parse_prefix()? {
1153                        Expr::Literal(lit @ Literal::String(_)) => {
1154                            function.body = FunctionBody::Code(lit)
1155                        }
1156                        _ => return self.parse_raw(start),
1157                    }
1158                }
1159            } else {
1160                break;
1161            }
1162        }
1163        Ok(Statement::CreateFunction(Box::new(function)))
1164    }
1165
1166    fn parse_create_table_function(
1167        &mut self,
1168        or_replace: bool,
1169        temporary: bool,
1170    ) -> Result<Statement> {
1171        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1172        let name = self.parse_object_name(true)?;
1173        self.set_role(self.pos - 1, TokenRole::Function);
1174        let params = self.parse_function_params()?;
1175        let mut returns = None;
1176        let mut options = Vec::new();
1177        loop {
1178            if self.parse_keywords(&["RETURNS", "TABLE"]) {
1179                if !self.consume_punct(Punct::Lt) {
1180                    return Err(self.error("expected '<'"));
1181                }
1182                returns = Some(self.parse_struct_fields()?);
1183            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
1184                options = self.parse_optional_options()?;
1185            } else {
1186                break;
1187            }
1188        }
1189        self.expect_keyword("AS")?;
1190        let query = self.parse_query()?;
1191        Ok(Statement::CreateTableFunction(Box::new(
1192            CreateTableFunction {
1193                or_replace,
1194                temporary,
1195                if_not_exists,
1196                name,
1197                params,
1198                returns,
1199                options,
1200                query: Box::new(query),
1201            },
1202        )))
1203    }
1204
1205    fn parse_create_procedure(&mut self, or_replace: bool) -> Result<Statement> {
1206        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1207        let name = self.parse_object_name(true)?;
1208        self.set_role(self.pos - 1, TokenRole::Function);
1209        self.expect_punct(Punct::LParen)?;
1210        let mut params = Vec::new();
1211        while !self.peek_punct(Punct::RParen) {
1212            let mode = if self.parse_keyword("INOUT") {
1213                Some(ParamMode::InOut)
1214            } else if self.parse_keyword("OUT") {
1215                Some(ParamMode::Out)
1216            } else if self.peek_keyword("IN")
1217                && self.peek_nth(1).is_some_and(Self::is_identifier_token)
1218            {
1219                self.parse_keyword("IN");
1220                Some(ParamMode::In)
1221            } else {
1222                None
1223            };
1224            let name = self.parse_identifier()?;
1225            let param_type = self.parse_param_type()?;
1226            params.push(ProcedureParam {
1227                mode,
1228                name,
1229                param_type,
1230            });
1231            if !self.consume_punct(Punct::Comma) {
1232                break;
1233            }
1234        }
1235        self.expect_punct(Punct::RParen)?;
1236        let options = self.parse_optional_options()?;
1237        self.expect_keyword("BEGIN")?;
1238        let body = self.parse_block(&["END", "EXCEPTION"])?;
1239        let exception = self.parse_exception_handler()?;
1240        self.expect_keyword("END")?;
1241        Ok(Statement::CreateProcedure(Box::new(CreateProcedure {
1242            or_replace,
1243            if_not_exists,
1244            name,
1245            params,
1246            options,
1247            body,
1248            exception,
1249        })))
1250    }
1251
1252    fn parse_exception_handler(&mut self) -> Result<Option<Vec<Statement>>> {
1253        if self.parse_keyword("EXCEPTION") {
1254            self.expect_keyword("WHEN")?;
1255            self.expect_keyword("ERROR")?;
1256            self.expect_keyword("THEN")?;
1257            Ok(Some(self.parse_block(&["END"])?))
1258        } else {
1259            Ok(None)
1260        }
1261    }
1262
1263    fn parse_insert(&mut self) -> Result<Statement> {
1264        self.expect_keyword("INSERT")?;
1265        self.parse_keyword("INTO");
1266        let table = self.parse_object_name(true)?;
1267        let columns = if self.peek_punct(Punct::LParen) && !self.paren_starts_query() {
1268            self.parse_parenthesized_identifiers()?
1269        } else {
1270            Vec::new()
1271        };
1272        let source = if self.parse_keyword("VALUES") {
1273            let mut rows = vec![self.parse_values_row()?];
1274            while self.consume_punct(Punct::Comma) {
1275                rows.push(self.parse_values_row()?);
1276            }
1277            InsertSource::Values(rows)
1278        } else {
1279            InsertSource::Query(Box::new(self.parse_query()?))
1280        };
1281        Ok(Statement::Insert(Box::new(Insert {
1282            table,
1283            columns,
1284            source,
1285        })))
1286    }
1287
1288    fn parse_values_row(&mut self) -> Result<Vec<Expr>> {
1289        self.expect_punct(Punct::LParen)?;
1290        let mut row = vec![self.parse_expr()?];
1291        while self.consume_punct(Punct::Comma) {
1292            row.push(self.parse_expr()?);
1293        }
1294        self.expect_punct(Punct::RParen)?;
1295        Ok(row)
1296    }
1297
1298    fn parse_assignments(&mut self) -> Result<Vec<Assignment>> {
1299        let mut out = Vec::new();
1300        loop {
1301            let mut target = vec![self.parse_identifier()?];
1302            while self.consume_punct(Punct::Dot) {
1303                target.push(self.parse_path_part()?);
1304            }
1305            self.expect_punct(Punct::Eq)?;
1306            let value = self.parse_expr()?;
1307            out.push(Assignment { target, value });
1308            if !self.consume_punct(Punct::Comma) {
1309                break;
1310            }
1311        }
1312        Ok(out)
1313    }
1314
1315    fn parse_update(&mut self) -> Result<Statement> {
1316        self.expect_keyword("UPDATE")?;
1317        let table = self.parse_object_name(true)?;
1318        let alias = self.parse_optional_alias(false)?;
1319        self.expect_keyword("SET")?;
1320        let assignments = self.parse_assignments()?;
1321        let from = if self.parse_keyword("FROM") {
1322            self.parse_from_list()?
1323        } else {
1324            Vec::new()
1325        };
1326        let selection = if self.parse_keyword("WHERE") {
1327            Some(self.parse_expr()?)
1328        } else {
1329            None
1330        };
1331        Ok(Statement::Update(Box::new(Update {
1332            table,
1333            alias,
1334            assignments,
1335            from,
1336            selection,
1337        })))
1338    }
1339
1340    fn parse_delete(&mut self) -> Result<Statement> {
1341        self.expect_keyword("DELETE")?;
1342        self.parse_keyword("FROM");
1343        let table = self.parse_object_name(true)?;
1344        let alias = self.parse_optional_alias(false)?;
1345        let selection = if self.parse_keyword("WHERE") {
1346            Some(self.parse_expr()?)
1347        } else {
1348            None
1349        };
1350        Ok(Statement::Delete(Box::new(Delete {
1351            table,
1352            alias,
1353            selection,
1354        })))
1355    }
1356
1357    fn parse_merge(&mut self) -> Result<Statement> {
1358        self.expect_keyword("MERGE")?;
1359        self.parse_keyword("INTO");
1360        let target = self.parse_object_name(true)?;
1361        let target_alias = self.parse_optional_alias(false)?;
1362        self.expect_keyword("USING")?;
1363        let source = self.parse_table_factor()?;
1364        self.expect_keyword("ON")?;
1365        let on = self.parse_expr()?;
1366        let mut clauses = Vec::new();
1367        while self.parse_keyword("WHEN") {
1368            let not = self.parse_keyword("NOT");
1369            self.expect_keyword("MATCHED")?;
1370            let mut explicit_by_target = false;
1371            let kind = if not {
1372                if self.parse_keywords(&["BY", "SOURCE"]) {
1373                    MergeMatch::NotMatchedBySource
1374                } else {
1375                    explicit_by_target = self.parse_keywords(&["BY", "TARGET"]);
1376                    MergeMatch::NotMatchedByTarget
1377                }
1378            } else {
1379                MergeMatch::Matched
1380            };
1381            let condition = if self.parse_keyword("AND") {
1382                Some(self.parse_expr()?)
1383            } else {
1384                None
1385            };
1386            self.expect_keyword("THEN")?;
1387            let action = if self.parse_keyword("UPDATE") {
1388                self.expect_keyword("SET")?;
1389                MergeAction::Update(self.parse_assignments()?)
1390            } else if self.parse_keyword("DELETE") {
1391                MergeAction::Delete
1392            } else {
1393                self.expect_keyword("INSERT")?;
1394                let columns = if self.peek_punct(Punct::LParen) {
1395                    self.parse_parenthesized_identifiers()?
1396                } else {
1397                    Vec::new()
1398                };
1399                if self.parse_keyword("ROW") {
1400                    MergeAction::Insert {
1401                        columns,
1402                        values: Vec::new(),
1403                        row: true,
1404                    }
1405                } else {
1406                    self.expect_keyword("VALUES")?;
1407                    let values = self.parse_values_row()?;
1408                    MergeAction::Insert {
1409                        columns,
1410                        values,
1411                        row: false,
1412                    }
1413                }
1414            };
1415            clauses.push(MergeClause {
1416                kind,
1417                explicit_by_target,
1418                condition,
1419                action,
1420            });
1421        }
1422        if clauses.is_empty() {
1423            return Err(self.error("expected WHEN"));
1424        }
1425        Ok(Statement::Merge(Box::new(Merge {
1426            target,
1427            target_alias,
1428            source,
1429            on,
1430            clauses,
1431        })))
1432    }
1433
1434    fn parse_object_type(&mut self) -> Option<ObjectType> {
1435        let checks: &[(&[&str], ObjectType)] = &[
1436            (&["EXTERNAL", "TABLE"], ObjectType::ExternalTable),
1437            (&["SNAPSHOT", "TABLE"], ObjectType::SnapshotTable),
1438            (&["MATERIALIZED", "VIEW"], ObjectType::MaterializedView),
1439            (&["TABLE", "FUNCTION"], ObjectType::TableFunction),
1440            (&["TABLE"], ObjectType::Table),
1441            (&["VIEW"], ObjectType::View),
1442            (&["SCHEMA"], ObjectType::Schema),
1443            (&["FUNCTION"], ObjectType::Function),
1444            (&["PROCEDURE"], ObjectType::Procedure),
1445            (&["MODEL"], ObjectType::Model),
1446        ];
1447        for (words, kind) in checks {
1448            if self.parse_keywords(words) {
1449                return Some(*kind);
1450            }
1451        }
1452        None
1453    }
1454
1455    fn parse_drop(&mut self, start: usize) -> Result<Statement> {
1456        self.expect_keyword("DROP")?;
1457        let Some(object_type) = self.parse_object_type() else {
1458            return self.parse_raw(start);
1459        };
1460        let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1461        let name = self.parse_object_name(true)?;
1462        let cascade = if self.parse_keyword("CASCADE") {
1463            Some(true)
1464        } else if self.parse_keyword("RESTRICT") {
1465            Some(false)
1466        } else {
1467            None
1468        };
1469        Ok(Statement::Drop(Box::new(Drop {
1470            object_type,
1471            if_exists,
1472            name,
1473            cascade,
1474        })))
1475    }
1476
1477    fn parse_alter(&mut self, start: usize) -> Result<Statement> {
1478        self.expect_keyword("ALTER")?;
1479        let object_type = if self.parse_keywords(&["MATERIALIZED", "VIEW"]) {
1480            ObjectType::MaterializedView
1481        } else if self.parse_keyword("TABLE") {
1482            ObjectType::Table
1483        } else if self.parse_keyword("VIEW") {
1484            ObjectType::View
1485        } else {
1486            return self.parse_raw(start);
1487        };
1488        match self.attempt(|p| p.parse_alter_body(object_type)) {
1489            Some(statement) => Ok(statement),
1490            None => self.parse_raw(start),
1491        }
1492    }
1493
1494    fn parse_alter_body(&mut self, object_type: ObjectType) -> Result<Statement> {
1495        let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1496        let name = self.parse_object_name(true)?;
1497        let mut actions = Vec::new();
1498        loop {
1499            let action = if self.parse_keywords(&["ADD", "COLUMN"]) {
1500                let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1501                AlterAction::AddColumn {
1502                    if_not_exists,
1503                    column: self.parse_column_def()?,
1504                }
1505            } else if self.parse_keywords(&["DROP", "COLUMN"]) {
1506                let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1507                AlterAction::DropColumn {
1508                    if_exists,
1509                    name: self.parse_identifier()?,
1510                }
1511            } else if self.parse_keywords(&["RENAME", "TO"]) {
1512                AlterAction::RenameTo(self.parse_object_name(true)?)
1513            } else if self.parse_keywords(&["RENAME", "COLUMN"]) {
1514                let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1515                let from = self.parse_identifier()?;
1516                self.expect_keyword("TO")?;
1517                AlterAction::RenameColumn {
1518                    if_exists,
1519                    from,
1520                    to: self.parse_identifier()?,
1521                }
1522            } else if self.parse_keywords(&["SET", "DEFAULT", "COLLATE"]) {
1523                AlterAction::SetDefaultCollate(self.parse_expr()?)
1524            } else if self.parse_keywords(&["SET", "OPTIONS"]) {
1525                AlterAction::SetOptions(self.parse_options_body()?)
1526            } else if self.parse_keywords(&["ALTER", "COLUMN"]) {
1527                let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1528                let name = self.parse_identifier()?;
1529                let action = if self.parse_keywords(&["SET", "OPTIONS"]) {
1530                    AlterColumnAction::SetOptions(self.parse_options_body()?)
1531                } else if self.parse_keywords(&["DROP", "NOT", "NULL"]) {
1532                    AlterColumnAction::DropNotNull
1533                } else if self.parse_keywords(&["SET", "DATA", "TYPE"]) {
1534                    AlterColumnAction::SetDataType(self.parse_data_type()?)
1535                } else if self.parse_keywords(&["SET", "DEFAULT"]) {
1536                    AlterColumnAction::SetDefault(self.parse_expr()?)
1537                } else if self.parse_keywords(&["DROP", "DEFAULT"]) {
1538                    AlterColumnAction::DropDefault
1539                } else {
1540                    return Err(self.error("unsupported ALTER COLUMN action"));
1541                };
1542                AlterAction::AlterColumn {
1543                    if_exists,
1544                    name,
1545                    action,
1546                }
1547            } else {
1548                return Err(self.error("unsupported ALTER action"));
1549            };
1550            actions.push(action);
1551            if !self.consume_punct(Punct::Comma) {
1552                break;
1553            }
1554        }
1555        if !(self.at_end() || self.peek_punct(Punct::Semicolon)) {
1556            return Err(self.error("unsupported ALTER clause"));
1557        }
1558        Ok(Statement::AlterTable(Box::new(AlterTable {
1559            object_type,
1560            if_exists,
1561            name,
1562            actions,
1563        })))
1564    }
1565
1566    fn parse_declare(&mut self) -> Result<Statement> {
1567        self.expect_keyword("DECLARE")?;
1568        let names = self.parse_identifier_list()?;
1569        let data_type =
1570            if self.peek_keyword("DEFAULT") || self.at_end() || self.peek_punct(Punct::Semicolon) {
1571                None
1572            } else {
1573                Some(self.parse_data_type()?)
1574            };
1575        let default = if self.parse_keyword("DEFAULT") {
1576            Some(self.parse_expr()?)
1577        } else {
1578            None
1579        };
1580        Ok(Statement::Declare {
1581            names,
1582            data_type,
1583            default,
1584        })
1585    }
1586
1587    fn parse_set(&mut self) -> Result<Statement> {
1588        self.expect_keyword("SET")?;
1589        let targets = if self.consume_punct(Punct::LParen) {
1590            let mut out = vec![self.parse_set_target()?];
1591            while self.consume_punct(Punct::Comma) {
1592                out.push(self.parse_set_target()?);
1593            }
1594            self.expect_punct(Punct::RParen)?;
1595            out
1596        } else {
1597            vec![self.parse_set_target()?]
1598        };
1599        self.expect_punct(Punct::Eq)?;
1600        let value = self.parse_expr()?;
1601        Ok(Statement::Set { targets, value })
1602    }
1603
1604    fn parse_set_target(&mut self) -> Result<Expr> {
1605        if let Some(TokenKind::SystemVariable(name)) = self.peek().map(|t| t.kind.clone()) {
1606            self.pos += 1;
1607            return Ok(Expr::Parameter(Parameter::System(name)));
1608        }
1609        let first = self.parse_identifier()?;
1610        let mut parts = vec![first];
1611        while self.consume_punct(Punct::Dot) {
1612            parts.push(self.parse_path_part()?);
1613        }
1614        Ok(if parts.len() == 1 {
1615            Expr::Identifier(parts.remove(0))
1616        } else {
1617            Expr::CompoundIdentifier(parts)
1618        })
1619    }
1620
1621    fn parse_begin(&mut self, label: Option<Ident>) -> Result<Statement> {
1622        self.expect_keyword("BEGIN")?;
1623        if self.parse_keyword("TRANSACTION") || self.at_end() || self.peek_punct(Punct::Semicolon) {
1624            if label.is_some() {
1625                return Err(self.error("a label must precede a block or loop"));
1626            }
1627            return Ok(Statement::Transaction(TransactionKind::Begin));
1628        }
1629        let body = self.parse_block(&["END", "EXCEPTION"])?;
1630        let exception = self.parse_exception_handler()?;
1631        self.expect_keyword("END")?;
1632        self.skip_end_label(&label);
1633        Ok(Statement::BeginEnd {
1634            label,
1635            body,
1636            exception,
1637        })
1638    }
1639
1640    fn parse_if(&mut self) -> Result<Statement> {
1641        self.expect_keyword("IF")?;
1642        let mut branches = Vec::new();
1643        let condition = self.parse_expr()?;
1644        self.expect_keyword("THEN")?;
1645        let body = self.parse_block(&["ELSEIF", "ELSE", "END"])?;
1646        branches.push(ConditionalBlock { condition, body });
1647        let mut else_branch = None;
1648        loop {
1649            if self.parse_keyword("ELSEIF") {
1650                let condition = self.parse_expr()?;
1651                self.expect_keyword("THEN")?;
1652                let body = self.parse_block(&["ELSEIF", "ELSE", "END"])?;
1653                branches.push(ConditionalBlock { condition, body });
1654            } else if self.parse_keyword("ELSE") {
1655                else_branch = Some(self.parse_block(&["END"])?);
1656            } else {
1657                break;
1658            }
1659        }
1660        self.expect_keywords(&["END", "IF"])?;
1661        Ok(Statement::If {
1662            branches,
1663            else_branch,
1664        })
1665    }
1666
1667    fn parse_case_statement(&mut self) -> Result<Statement> {
1668        self.expect_keyword("CASE")?;
1669        let operand = if self.peek_keyword("WHEN") {
1670            None
1671        } else {
1672            Some(self.parse_expr()?)
1673        };
1674        let mut branches = Vec::new();
1675        while self.parse_keyword("WHEN") {
1676            let condition = self.parse_expr()?;
1677            self.expect_keyword("THEN")?;
1678            let body = self.parse_block(&["WHEN", "ELSE", "END"])?;
1679            branches.push(ConditionalBlock { condition, body });
1680        }
1681        let else_branch = if self.parse_keyword("ELSE") {
1682            Some(self.parse_block(&["END"])?)
1683        } else {
1684            None
1685        };
1686        self.expect_keywords(&["END", "CASE"])?;
1687        Ok(Statement::Case {
1688            operand,
1689            branches,
1690            else_branch,
1691        })
1692    }
1693
1694    fn parse_execute(&mut self) -> Result<Statement> {
1695        self.expect_keywords(&["EXECUTE", "IMMEDIATE"])?;
1696        let sql = self.parse_expr()?;
1697        let into = if self.parse_keyword("INTO") {
1698            self.parse_identifier_list()?
1699        } else {
1700            Vec::new()
1701        };
1702        let mut using = Vec::new();
1703        if self.parse_keyword("USING") {
1704            loop {
1705                let expr = self.parse_expr()?;
1706                let alias = if self.parse_keyword("AS") {
1707                    Some(self.parse_identifier()?)
1708                } else {
1709                    None
1710                };
1711                using.push(ExprWithAlias { expr, alias });
1712                if !self.consume_punct(Punct::Comma) {
1713                    break;
1714                }
1715            }
1716        }
1717        Ok(Statement::ExecuteImmediate { sql, into, using })
1718    }
1719
1720    fn parse_export(&mut self) -> Result<Statement> {
1721        self.expect_keywords(&["EXPORT", "DATA"])?;
1722        let connection = if self.parse_keywords(&["WITH", "CONNECTION"]) {
1723            Some(self.parse_object_name(true)?)
1724        } else {
1725            None
1726        };
1727        let options = self.parse_optional_options()?;
1728        self.expect_keyword("AS")?;
1729        let query = self.parse_query()?;
1730        Ok(Statement::ExportData(Box::new(ExportData {
1731            connection,
1732            options,
1733            query: Box::new(query),
1734        })))
1735    }
1736
1737    fn parse_load(&mut self, start: usize) -> Result<Statement> {
1738        self.expect_keywords(&["LOAD", "DATA"])?;
1739        let overwrite = if self.parse_keyword("OVERWRITE") {
1740            true
1741        } else if self.parse_keyword("INTO") {
1742            false
1743        } else {
1744            return self.parse_raw(start);
1745        };
1746        let temporary = if self.parse_keyword("TEMP") || self.parse_keyword("TEMPORARY") {
1747            self.expect_keyword("TABLE")?;
1748            true
1749        } else {
1750            false
1751        };
1752        let table = self.parse_object_name(true)?;
1753        let rest_start = self.peek().map(|t| t.span.start);
1754        let mut depth = 0usize;
1755        let mut end = rest_start.unwrap_or(self.src.len());
1756        while let Some(token) = self.peek() {
1757            match token.kind {
1758                TokenKind::Punct(Punct::LParen) => depth += 1,
1759                TokenKind::Punct(Punct::RParen) => depth = depth.saturating_sub(1),
1760                TokenKind::Punct(Punct::Semicolon) if depth == 0 => break,
1761                _ => {}
1762            }
1763            end = token.span.end;
1764            self.pos += 1;
1765        }
1766        let rest = rest_start
1767            .map(|s| self.src[s..end].to_string())
1768            .unwrap_or_default();
1769        Ok(Statement::LoadData(Box::new(LoadData {
1770            overwrite,
1771            temporary,
1772            table,
1773            rest,
1774        })))
1775    }
1776
1777    // ------------------------------------------------------------------ queries
1778
1779    /// Whether the `(` at the current position opens a query rather than an expression or join.
1780    fn paren_starts_query(&self) -> bool {
1781        let mut n = 0;
1782        while self.peek_nth_punct(n, Punct::LParen) {
1783            n += 1;
1784        }
1785        n > 0
1786            && self.peek_nth(n).is_some_and(|t| {
1787                t.is_keyword("SELECT") || t.is_keyword("WITH") || t.is_keyword("FROM")
1788            })
1789    }
1790
1791    fn peek_query_start(&self) -> bool {
1792        self.peek_keyword("SELECT") || self.peek_keyword("WITH") || self.peek_keyword("FROM")
1793    }
1794
1795    /// Parse a query at the current position.
1796    pub fn parse_query(&mut self) -> Result<Query> {
1797        self.enter()?;
1798        let result = self.parse_query_inner();
1799        self.leave();
1800        result
1801    }
1802
1803    fn parse_query_inner(&mut self) -> Result<Query> {
1804        let with = if self.peek_keyword("WITH") && !self.peek_nth_punct(1, Punct::LParen) {
1805            Some(self.parse_with()?)
1806        } else {
1807            None
1808        };
1809        let body = self.parse_set_expr()?;
1810        let order_by = if self.parse_keywords(&["ORDER", "BY"]) {
1811            self.parse_order_by_list()?
1812        } else {
1813            Vec::new()
1814        };
1815        let limit = if self.parse_keyword("LIMIT") {
1816            Some(self.parse_limit_body()?)
1817        } else {
1818            None
1819        };
1820        let mut pipes = Vec::new();
1821        while self.consume_punct(Punct::Pipe) {
1822            pipes.push(self.parse_pipe_operator()?);
1823        }
1824        Ok(Query {
1825            with,
1826            body,
1827            order_by,
1828            limit,
1829            pipes,
1830        })
1831    }
1832
1833    fn parse_limit_body(&mut self) -> Result<Limit> {
1834        let count = self.parse_expr()?;
1835        let offset = if self.parse_keyword("OFFSET") {
1836            Some(self.parse_expr()?)
1837        } else {
1838            None
1839        };
1840        Ok(Limit { count, offset })
1841    }
1842
1843    fn parse_with(&mut self) -> Result<With> {
1844        self.expect_keyword("WITH")?;
1845        let recursive = self.parse_keyword("RECURSIVE");
1846        let mut ctes = Vec::new();
1847        loop {
1848            let name = self.parse_identifier()?;
1849            self.expect_keyword("AS")?;
1850            self.expect_punct(Punct::LParen)?;
1851            let query = self.parse_query()?;
1852            self.expect_punct(Punct::RParen)?;
1853            ctes.push(Cte {
1854                name,
1855                query: Box::new(query),
1856            });
1857            if !self.consume_punct(Punct::Comma) {
1858                break;
1859            }
1860        }
1861        Ok(With { recursive, ctes })
1862    }
1863
1864    fn parse_set_expr(&mut self) -> Result<SetExpr> {
1865        let mut left = self.parse_set_operand()?;
1866        while let Some((op, quantifier, mode, corresponding)) = self.parse_set_operator()? {
1867            let right = self.parse_set_operand()?;
1868            left = SetExpr::SetOperation {
1869                op,
1870                quantifier,
1871                mode,
1872                corresponding,
1873                left: Box::new(left),
1874                right: Box::new(right),
1875            };
1876        }
1877        Ok(left)
1878    }
1879
1880    /// A set operator with its quantifier and column matching, if one starts here.
1881    #[allow(clippy::type_complexity)]
1882    fn parse_set_operator(
1883        &mut self,
1884    ) -> Result<
1885        Option<(
1886            SetOperator,
1887            SetQuantifier,
1888            Option<SetOpMode>,
1889            Option<Corresponding>,
1890        )>,
1891    > {
1892        let is_op = |p: &Self, n: usize| {
1893            p.peek_nth_keyword(n, "UNION")
1894                || p.peek_nth_keyword(n, "INTERSECT")
1895                || p.peek_nth_keyword(n, "EXCEPT")
1896        };
1897        let mode = if (self.peek_keyword("FULL") || self.peek_keyword("LEFT"))
1898            && (is_op(self, 1) || (self.peek_nth_keyword(1, "OUTER") && is_op(self, 2)))
1899        {
1900            let mode = if self.parse_keyword("FULL") {
1901                SetOpMode::Full
1902            } else {
1903                self.parse_keyword("LEFT");
1904                SetOpMode::Left
1905            };
1906            self.parse_keyword("OUTER");
1907            Some(mode)
1908        } else if self.peek_keyword("INNER") && is_op(self, 1) {
1909            self.parse_keyword("INNER");
1910            Some(SetOpMode::Inner)
1911        } else {
1912            None
1913        };
1914        let op = if self.parse_keyword("UNION") {
1915            SetOperator::Union
1916        } else if self.parse_keyword("INTERSECT") {
1917            SetOperator::Intersect
1918        } else if self.parse_keyword("EXCEPT") {
1919            SetOperator::Except
1920        } else {
1921            return Ok(None);
1922        };
1923        let quantifier = if self.parse_keyword("ALL") {
1924            SetQuantifier::All
1925        } else if self.parse_keyword("DISTINCT") {
1926            SetQuantifier::Distinct
1927        } else {
1928            SetQuantifier::None
1929        };
1930        let corresponding = self.parse_corresponding()?;
1931        Ok(Some((op, quantifier, mode, corresponding)))
1932    }
1933
1934    fn parse_corresponding(&mut self) -> Result<Option<Corresponding>> {
1935        if self.parse_keywords(&["BY", "NAME"]) {
1936            let on = if self.parse_keyword("ON") {
1937                self.parse_parenthesized_identifiers()?
1938            } else {
1939                Vec::new()
1940            };
1941            return Ok(Some(Corresponding::ByName(on)));
1942        }
1943        let strict = self.parse_keyword("STRICT");
1944        if self.parse_keyword("CORRESPONDING") {
1945            let by = if self.parse_keyword("BY") {
1946                self.parse_parenthesized_identifiers()?
1947            } else {
1948                Vec::new()
1949            };
1950            return Ok(Some(Corresponding::Corresponding { strict, by }));
1951        }
1952        if strict {
1953            return Err(self.error("expected CORRESPONDING"));
1954        }
1955        Ok(None)
1956    }
1957
1958    fn parse_set_operand(&mut self) -> Result<SetExpr> {
1959        if self.peek_keyword("SELECT") {
1960            return Ok(SetExpr::Select(Box::new(self.parse_select()?)));
1961        }
1962        if self.peek_keyword("FROM") {
1963            self.parse_keyword("FROM");
1964            return Ok(SetExpr::From(self.parse_from_list()?));
1965        }
1966        if self.consume_punct(Punct::LParen) {
1967            let query = self.parse_query()?;
1968            self.expect_punct(Punct::RParen)?;
1969            return Ok(SetExpr::Query(Box::new(query)));
1970        }
1971        Err(self.error("expected SELECT, FROM or '('"))
1972    }
1973
1974    fn parse_select(&mut self) -> Result<Select> {
1975        self.expect_keyword("SELECT")?;
1976        let distinct = if self.parse_keyword("DISTINCT") {
1977            true
1978        } else {
1979            self.parse_keyword("ALL");
1980            false
1981        };
1982        let select_as = self.parse_select_as();
1983        let projection = self.parse_select_items()?;
1984        let mut select = Select::new(projection);
1985        select.distinct = distinct;
1986        select.select_as = select_as;
1987        if self.parse_keyword("FROM") {
1988            select.from = self.parse_from_list()?;
1989        }
1990        if self.parse_keyword("WHERE") {
1991            select.where_clause = Some(self.parse_expr()?);
1992        }
1993        if self.parse_keywords(&["GROUP", "BY"]) {
1994            select.group_by = Some(self.parse_group_by()?);
1995        }
1996        if self.parse_keyword("HAVING") {
1997            select.having = Some(self.parse_expr()?);
1998        }
1999        if self.parse_keyword("QUALIFY") {
2000            select.qualify = Some(self.parse_expr()?);
2001        }
2002        if self.parse_keyword("WINDOW") {
2003            loop {
2004                let name = self.parse_identifier()?;
2005                self.expect_keyword("AS")?;
2006                let spec = if self.peek_punct(Punct::LParen) {
2007                    self.parse_window_spec()?
2008                } else {
2009                    WindowSpec {
2010                        base: Some(self.parse_identifier()?),
2011                        ..WindowSpec::default()
2012                    }
2013                };
2014                select.window.push(NamedWindow { name, spec });
2015                if !self.consume_punct(Punct::Comma) {
2016                    break;
2017                }
2018            }
2019        }
2020        Ok(select)
2021    }
2022
2023    fn parse_select_as(&mut self) -> Option<SelectAs> {
2024        if self.parse_keywords(&["AS", "STRUCT"]) {
2025            Some(SelectAs::Struct)
2026        } else if self.parse_keywords(&["AS", "VALUE"]) {
2027            Some(SelectAs::Value)
2028        } else {
2029            None
2030        }
2031    }
2032
2033    /// Whether the current token ends a list of select items (so a trailing comma before it is allowed).
2034    fn at_select_list_end(&self) -> bool {
2035        match self.peek() {
2036            None => true,
2037            Some(t)
2038                if t.is_punct(Punct::RParen)
2039                    || t.is_punct(Punct::Semicolon)
2040                    || t.is_punct(Punct::Pipe) =>
2041            {
2042                true
2043            }
2044            Some(t) => [
2045                "FROM",
2046                "WHERE",
2047                "GROUP",
2048                "HAVING",
2049                "QUALIFY",
2050                "WINDOW",
2051                "ORDER",
2052                "LIMIT",
2053                "UNION",
2054                "INTERSECT",
2055                "EXCEPT",
2056            ]
2057            .iter()
2058            .any(|k| t.is_keyword(k)),
2059        }
2060    }
2061
2062    fn parse_select_items(&mut self) -> Result<Vec<SelectItem>> {
2063        let mut items = vec![self.parse_select_item()?];
2064        while self.consume_punct(Punct::Comma) {
2065            if self.at_select_list_end() {
2066                break; // a trailing comma
2067            }
2068            items.push(self.parse_select_item()?);
2069        }
2070        Ok(items)
2071    }
2072
2073    fn parse_select_item(&mut self) -> Result<SelectItem> {
2074        if self.consume_punct(Punct::Star) {
2075            return Ok(SelectItem::Wildcard(self.parse_wildcard_options()?));
2076        }
2077        let expr = self.parse_expr()?;
2078        if self.peek_punct(Punct::Dot) && self.peek_nth_punct(1, Punct::Star) {
2079            self.pos += 2;
2080            return Ok(SelectItem::QualifiedWildcard {
2081                qualifier: expr,
2082                options: self.parse_wildcard_options()?,
2083            });
2084        }
2085        let alias = self.parse_optional_alias(false)?;
2086        Ok(SelectItem::Expr { expr, alias })
2087    }
2088
2089    fn parse_wildcard_options(&mut self) -> Result<WildcardOptions> {
2090        let mut options = WildcardOptions::default();
2091        if self.peek_keyword("EXCEPT") && self.peek_nth_punct(1, Punct::LParen) {
2092            self.parse_keyword("EXCEPT");
2093            options.except = self.parse_parenthesized_identifiers()?;
2094        }
2095        if self.peek_keyword("REPLACE") && self.peek_nth_punct(1, Punct::LParen) {
2096            self.parse_keyword("REPLACE");
2097            self.expect_punct(Punct::LParen)?;
2098            loop {
2099                let expr = self.parse_expr()?;
2100                self.expect_keyword("AS")?;
2101                let alias = self.parse_identifier()?;
2102                options.replace.push(ExprWithAlias {
2103                    expr,
2104                    alias: Some(alias),
2105                });
2106                if !self.consume_punct(Punct::Comma) {
2107                    break;
2108                }
2109            }
2110            self.expect_punct(Punct::RParen)?;
2111        }
2112        Ok(options)
2113    }
2114
2115    fn parse_group_by(&mut self) -> Result<GroupBy> {
2116        if self.parse_keyword("ALL") {
2117            return Ok(GroupBy::All);
2118        }
2119        let mut items = vec![self.parse_group_by_item()?];
2120        while self.consume_punct(Punct::Comma) {
2121            items.push(self.parse_group_by_item()?);
2122        }
2123        Ok(GroupBy::Items(items))
2124    }
2125
2126    fn parse_group_by_item(&mut self) -> Result<GroupByItem> {
2127        if self.peek_keyword("ROLLUP") || self.peek_keyword("CUBE") {
2128            let rollup = self.parse_keyword("ROLLUP");
2129            if !rollup {
2130                self.parse_keyword("CUBE");
2131            }
2132            self.expect_punct(Punct::LParen)?;
2133            let mut exprs = vec![self.parse_expr()?];
2134            while self.consume_punct(Punct::Comma) {
2135                exprs.push(self.parse_expr()?);
2136            }
2137            self.expect_punct(Punct::RParen)?;
2138            return Ok(if rollup {
2139                GroupByItem::Rollup(exprs)
2140            } else {
2141                GroupByItem::Cube(exprs)
2142            });
2143        }
2144        if self.parse_keywords(&["GROUPING", "SETS"]) {
2145            self.expect_punct(Punct::LParen)?;
2146            let mut sets = vec![self.parse_group_by_item()?];
2147            while self.consume_punct(Punct::Comma) {
2148                sets.push(self.parse_group_by_item()?);
2149            }
2150            self.expect_punct(Punct::RParen)?;
2151            return Ok(GroupByItem::GroupingSets(sets));
2152        }
2153        if self.peek_punct(Punct::LParen) && self.peek_nth_punct(1, Punct::RParen) {
2154            self.pos += 2;
2155            return Ok(GroupByItem::Empty);
2156        }
2157        Ok(GroupByItem::Expr(self.parse_expr()?))
2158    }
2159
2160    fn parse_order_by_list(&mut self) -> Result<Vec<OrderByExpr>> {
2161        let mut items = vec![self.parse_order_by_expr()?];
2162        while self.consume_punct(Punct::Comma) {
2163            items.push(self.parse_order_by_expr()?);
2164        }
2165        Ok(items)
2166    }
2167
2168    fn parse_order_by_expr(&mut self) -> Result<OrderByExpr> {
2169        let expr = self.parse_expr()?;
2170        let collate = if self.parse_keyword("COLLATE") {
2171            Some(self.parse_expr()?)
2172        } else {
2173            None
2174        };
2175        let (asc, nulls_first) = self.parse_order_spec();
2176        Ok(OrderByExpr {
2177            expr,
2178            collate,
2179            asc,
2180            nulls_first,
2181        })
2182    }
2183
2184    fn parse_order_spec(&mut self) -> (Option<bool>, Option<bool>) {
2185        let asc = if self.parse_keyword("ASC") {
2186            Some(true)
2187        } else if self.parse_keyword("DESC") {
2188            Some(false)
2189        } else {
2190            None
2191        };
2192        let nulls_first = if self.parse_keywords(&["NULLS", "FIRST"]) {
2193            Some(true)
2194        } else if self.parse_keywords(&["NULLS", "LAST"]) {
2195            Some(false)
2196        } else {
2197            None
2198        };
2199        (asc, nulls_first)
2200    }
2201
2202    // ------------------------------------------------------------------ FROM
2203
2204    fn parse_from_list(&mut self) -> Result<Vec<TableWithJoins>> {
2205        let mut items = vec![self.parse_table_with_joins()?];
2206        while self.consume_punct(Punct::Comma) {
2207            items.push(self.parse_table_with_joins()?);
2208        }
2209        Ok(items)
2210    }
2211
2212    fn parse_table_with_joins(&mut self) -> Result<TableWithJoins> {
2213        let relation = self.parse_table_factor()?;
2214        let mut joins = Vec::new();
2215        while let Some(join) = self.parse_join()? {
2216            joins.push(join);
2217        }
2218        Ok(TableWithJoins { relation, joins })
2219    }
2220
2221    /// A join operator and its right side, if one starts here.
2222    fn parse_join(&mut self) -> Result<Option<Join>> {
2223        let start = self.pos;
2224        let natural = self.parse_keyword("NATURAL");
2225        let kind = if self.parse_keyword("CROSS") {
2226            Some(JoinKind::Cross)
2227        } else if self.parse_keyword("INNER") {
2228            Some(JoinKind::Inner)
2229        } else if self.parse_keyword("LEFT") {
2230            self.parse_keyword("OUTER");
2231            Some(JoinKind::Left)
2232        } else if self.parse_keyword("RIGHT") {
2233            self.parse_keyword("OUTER");
2234            Some(JoinKind::Right)
2235        } else if self.parse_keyword("FULL") {
2236            self.parse_keyword("OUTER");
2237            Some(JoinKind::Full)
2238        } else {
2239            None
2240        };
2241        if !self.peek_keyword("JOIN") {
2242            // `LEFT UNION ALL ...` (a set operation mode) or nothing at all
2243            for role in &mut self.roles[start..self.pos] {
2244                *role = TokenRole::Other;
2245            }
2246            self.pos = start;
2247            return Ok(None);
2248        }
2249        self.parse_keyword("JOIN");
2250        let kind = kind.unwrap_or(JoinKind::Inner);
2251        let relation = self.parse_table_factor()?;
2252        let constraint = self.parse_join_constraint()?;
2253        Ok(Some(Join {
2254            kind,
2255            natural,
2256            relation,
2257            constraint,
2258        }))
2259    }
2260
2261    fn parse_join_constraint(&mut self) -> Result<JoinConstraint> {
2262        if self.parse_keyword("ON") {
2263            Ok(JoinConstraint::On(self.parse_expr()?))
2264        } else if self.parse_keyword("USING") {
2265            Ok(JoinConstraint::Using(
2266                self.parse_parenthesized_identifiers()?,
2267            ))
2268        } else {
2269            Ok(JoinConstraint::None)
2270        }
2271    }
2272
2273    /// One FROM item: a table, subquery, `UNNEST`, table function or parenthesized join, with
2274    /// any `PIVOT`, `UNPIVOT` and `TABLESAMPLE` after it.
2275    pub fn parse_table_factor(&mut self) -> Result<TableFactor> {
2276        self.enter()?;
2277        let result = self.parse_table_factor_inner();
2278        self.leave();
2279        result
2280    }
2281
2282    fn parse_table_factor_inner(&mut self) -> Result<TableFactor> {
2283        let mut factor = if self.peek_punct(Punct::LParen) {
2284            let as_query = if self.paren_starts_query() {
2285                self.attempt(|p| {
2286                    p.expect_punct(Punct::LParen)?;
2287                    let q = p.parse_query()?;
2288                    p.expect_punct(Punct::RParen)?;
2289                    Ok(q)
2290                })
2291            } else {
2292                None
2293            };
2294            match as_query {
2295                Some(query) => {
2296                    let alias = self.parse_optional_alias(true)?;
2297                    TableFactor::Derived {
2298                        subquery: Box::new(query),
2299                        alias,
2300                        sample: None,
2301                    }
2302                }
2303                None => {
2304                    self.expect_punct(Punct::LParen)?;
2305                    let table = self.parse_table_with_joins()?;
2306                    self.expect_punct(Punct::RParen)?;
2307                    let alias = self.parse_optional_alias(true)?;
2308                    TableFactor::NestedJoin {
2309                        table: Box::new(table),
2310                        alias,
2311                    }
2312                }
2313            }
2314        } else if self.peek_keyword("UNNEST") && self.peek_nth_punct(1, Punct::LParen) {
2315            self.parse_keyword("UNNEST");
2316            self.expect_punct(Punct::LParen)?;
2317            let array = self.parse_expr()?;
2318            self.expect_punct(Punct::RParen)?;
2319            let alias = self.parse_optional_alias(true)?;
2320            let with_offset = if self.parse_keywords(&["WITH", "OFFSET"]) {
2321                Some(self.parse_optional_alias(true)?)
2322            } else {
2323                None
2324            };
2325            TableFactor::Unnest {
2326                array: Box::new(array),
2327                alias,
2328                with_offset,
2329            }
2330        } else {
2331            let name = self.parse_object_name(true)?;
2332            if self.peek_punct(Punct::LParen) {
2333                let function = self.parse_function_call(name, self.pos.saturating_sub(1))?;
2334                let alias = self.parse_optional_alias(true)?;
2335                TableFactor::TableFunction { function, alias }
2336            } else {
2337                let mut system_time = self.parse_system_time()?;
2338                let alias = self.parse_optional_alias(true)?;
2339                if system_time.is_none() {
2340                    system_time = self.parse_system_time()?;
2341                }
2342                TableFactor::Table {
2343                    name,
2344                    alias,
2345                    system_time,
2346                    sample: None,
2347                }
2348            }
2349        };
2350        loop {
2351            if self.peek_keyword("PIVOT") && self.peek_nth_punct(1, Punct::LParen) {
2352                self.parse_keyword("PIVOT");
2353                let (aggregates, value_column, values) = self.parse_pivot_body()?;
2354                let alias = self.parse_optional_alias(true)?;
2355                factor = TableFactor::Pivot {
2356                    table: Box::new(factor),
2357                    aggregates,
2358                    value_column: Box::new(value_column),
2359                    values,
2360                    alias,
2361                };
2362            } else if self.peek_keyword("UNPIVOT")
2363                && (self.peek_nth_punct(1, Punct::LParen)
2364                    || self.peek_nth_keyword(1, "INCLUDE")
2365                    || self.peek_nth_keyword(1, "EXCLUDE"))
2366            {
2367                self.parse_keyword("UNPIVOT");
2368                let (include_nulls, value_columns, name_column, columns) =
2369                    self.parse_unpivot_body()?;
2370                let alias = self.parse_optional_alias(true)?;
2371                factor = TableFactor::Unpivot {
2372                    table: Box::new(factor),
2373                    include_nulls,
2374                    value_columns,
2375                    name_column,
2376                    columns,
2377                    alias,
2378                };
2379            } else if self.peek_keyword("MATCH_RECOGNIZE") && self.peek_nth_punct(1, Punct::LParen)
2380            {
2381                self.parse_keyword("MATCH_RECOGNIZE");
2382                let spec = self.parse_match_recognize_body()?;
2383                let alias = self.parse_optional_alias(true)?;
2384                factor = TableFactor::MatchRecognize {
2385                    table: Box::new(factor),
2386                    spec: Box::new(spec),
2387                    alias,
2388                };
2389            } else if self.peek_keyword("ALIGN") && self.peek_nth_punct(1, Punct::LParen) {
2390                self.parse_keyword("ALIGN");
2391                let spec = self.parse_align_body()?;
2392                let alias = self.parse_optional_alias(true)?;
2393                factor = TableFactor::Align {
2394                    table: Box::new(factor),
2395                    spec: Box::new(spec),
2396                    alias,
2397                };
2398            } else {
2399                break;
2400            }
2401        }
2402        if self.peek_keyword("TABLESAMPLE") {
2403            let parsed = self.parse_tablesample()?;
2404            match &mut factor {
2405                TableFactor::Table { sample, .. } | TableFactor::Derived { sample, .. } => {
2406                    *sample = Some(parsed)
2407                }
2408                _ => return Err(self.error("TABLESAMPLE applies to a table or subquery")),
2409            }
2410        }
2411        Ok(factor)
2412    }
2413
2414    fn parse_tablesample(&mut self) -> Result<TableSample> {
2415        self.expect_keyword("TABLESAMPLE")?;
2416        let method = self.parse_identifier()?;
2417        self.set_role(self.pos - 1, TokenRole::Keyword);
2418        self.expect_punct(Punct::LParen)?;
2419        let size = self.parse_expr()?;
2420        let unit = if self.parse_keyword("PERCENT") {
2421            SampleUnit::Percent
2422        } else {
2423            self.expect_keyword("ROWS")?;
2424            SampleUnit::Rows
2425        };
2426        self.expect_punct(Punct::RParen)?;
2427        Ok(TableSample { method, size, unit })
2428    }
2429
2430    fn parse_expr_with_alias_list(&mut self) -> Result<Vec<ExprWithAlias>> {
2431        let mut out = Vec::new();
2432        loop {
2433            let expr = self.parse_expr()?;
2434            let alias = self.parse_optional_alias(false)?;
2435            out.push(ExprWithAlias { expr, alias });
2436            if !self.consume_punct(Punct::Comma) {
2437                break;
2438            }
2439        }
2440        Ok(out)
2441    }
2442
2443    #[allow(clippy::type_complexity)]
2444    fn parse_pivot_body(&mut self) -> Result<(Vec<ExprWithAlias>, Expr, Vec<ExprWithAlias>)> {
2445        self.expect_punct(Punct::LParen)?;
2446        let aggregates = self.parse_expr_with_alias_list()?;
2447        self.expect_keyword("FOR")?;
2448        let value_column = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
2449        self.expect_keyword("IN")?;
2450        self.expect_punct(Punct::LParen)?;
2451        let values = self.parse_expr_with_alias_list()?;
2452        self.expect_punct(Punct::RParen)?;
2453        self.expect_punct(Punct::RParen)?;
2454        Ok((aggregates, value_column, values))
2455    }
2456
2457    #[allow(clippy::type_complexity)]
2458    fn parse_unpivot_body(
2459        &mut self,
2460    ) -> Result<(Option<bool>, Vec<Ident>, Ident, Vec<UnpivotColumns>)> {
2461        let include_nulls = if self.parse_keywords(&["INCLUDE", "NULLS"]) {
2462            Some(true)
2463        } else if self.parse_keywords(&["EXCLUDE", "NULLS"]) {
2464            Some(false)
2465        } else {
2466            None
2467        };
2468        self.expect_punct(Punct::LParen)?;
2469        let value_columns = if self.peek_punct(Punct::LParen) {
2470            self.parse_parenthesized_identifiers()?
2471        } else {
2472            vec![self.parse_identifier()?]
2473        };
2474        self.expect_keyword("FOR")?;
2475        let name_column = self.parse_identifier()?;
2476        self.expect_keyword("IN")?;
2477        self.expect_punct(Punct::LParen)?;
2478        let mut columns = Vec::new();
2479        loop {
2480            let cols = if self.peek_punct(Punct::LParen) {
2481                self.parse_parenthesized_identifiers()?
2482            } else {
2483                vec![self.parse_identifier()?]
2484            };
2485            let alias = if self.parse_keyword("AS") {
2486                Some(self.parse_prefix()?)
2487            } else {
2488                None
2489            };
2490            columns.push(UnpivotColumns {
2491                columns: cols,
2492                alias,
2493            });
2494            if !self.consume_punct(Punct::Comma) {
2495                break;
2496            }
2497        }
2498        self.expect_punct(Punct::RParen)?;
2499        self.expect_punct(Punct::RParen)?;
2500        Ok((include_nulls, value_columns, name_column, columns))
2501    }
2502
2503    // ------------------------------------------------------------------ MATCH_RECOGNIZE and ALIGN
2504
2505    /// An alias that must be written with `AS` (inside clauses whose next word could pass for one).
2506    fn parse_as_alias(&mut self) -> Result<Option<Ident>> {
2507        if self.parse_keyword("AS") {
2508            Ok(Some(self.parse_identifier()?))
2509        } else {
2510            Ok(None)
2511        }
2512    }
2513
2514    /// `( [PARTITION BY ...] ORDER BY ... MEASURES ... [AFTER MATCH SKIP ...] PATTERN (...) [DEFINE ...]
2515    /// [OPTIONS (...)] )`, the parentheses included.
2516    fn parse_match_recognize_body(&mut self) -> Result<MatchRecognize> {
2517        self.expect_punct(Punct::LParen)?;
2518        let mut partition_by = Vec::new();
2519        if self.parse_keywords(&["PARTITION", "BY"]) {
2520            loop {
2521                partition_by.push(self.parse_expr()?);
2522                if !self.consume_punct(Punct::Comma) {
2523                    break;
2524                }
2525            }
2526        }
2527        self.expect_keywords(&["ORDER", "BY"])?;
2528        let order_by = self.parse_order_by_list()?;
2529        self.expect_keyword("MEASURES")?;
2530        let mut measures = Vec::new();
2531        loop {
2532            let expr = self.parse_expr()?;
2533            self.expect_keyword("AS")?;
2534            measures.push((expr, self.parse_identifier()?));
2535            if !self.consume_punct(Punct::Comma) {
2536                break;
2537            }
2538        }
2539        let after_match = if self.parse_keywords(&["AFTER", "MATCH", "SKIP"]) {
2540            if self.parse_keywords(&["PAST", "LAST", "ROW"]) {
2541                Some(AfterMatchSkip::PastLastRow)
2542            } else {
2543                self.expect_keywords(&["TO", "NEXT", "ROW"])?;
2544                Some(AfterMatchSkip::ToNextRow)
2545            }
2546        } else {
2547            None
2548        };
2549        self.expect_keyword("PATTERN")?;
2550        self.expect_punct(Punct::LParen)?;
2551        let pattern = if self.peek_punct(Punct::RParen) {
2552            RowPattern::Empty
2553        } else {
2554            self.parse_row_pattern()?
2555        };
2556        self.expect_punct(Punct::RParen)?;
2557        let mut define = Vec::new();
2558        if self.parse_keyword("DEFINE") {
2559            loop {
2560                let symbol = self.parse_identifier()?;
2561                self.expect_keyword("AS")?;
2562                define.push((symbol, self.parse_expr()?));
2563                if !self.consume_punct(Punct::Comma) {
2564                    break;
2565                }
2566            }
2567        }
2568        let options = if self.parse_keyword("OPTIONS") {
2569            self.parse_options_body()?
2570        } else {
2571            Vec::new()
2572        };
2573        self.expect_punct(Punct::RParen)?;
2574        Ok(MatchRecognize {
2575            partition_by,
2576            order_by,
2577            measures,
2578            after_match,
2579            pattern,
2580            define,
2581            options,
2582        })
2583    }
2584
2585    /// `a | b c+`: alternation of concatenations of quantified primaries.
2586    fn parse_row_pattern(&mut self) -> Result<RowPattern> {
2587        let mut branches = vec![self.parse_row_pattern_concat()?];
2588        while self.consume_punct(Punct::Bar) {
2589            branches.push(self.parse_row_pattern_concat()?);
2590        }
2591        Ok(if branches.len() == 1 {
2592            branches.pop().unwrap()
2593        } else {
2594            RowPattern::Alternation(branches)
2595        })
2596    }
2597
2598    fn parse_row_pattern_concat(&mut self) -> Result<RowPattern> {
2599        let mut items = Vec::new();
2600        while !(self.at_end() || self.peek_punct(Punct::Bar) || self.peek_punct(Punct::RParen)) {
2601            let mut item = if self.consume_punct(Punct::LParen) {
2602                let inner = if self.peek_punct(Punct::RParen) {
2603                    RowPattern::Empty
2604                } else {
2605                    self.parse_row_pattern()?
2606                };
2607                self.expect_punct(Punct::RParen)?;
2608                RowPattern::Group(Box::new(inner))
2609            } else if self.consume_punct(Punct::Caret) {
2610                RowPattern::Start
2611            } else {
2612                RowPattern::Symbol(self.parse_identifier()?)
2613            };
2614            while let Some(quantifier) = self.parse_pattern_quantifier()? {
2615                let reluctant = self.consume_punct(Punct::Question);
2616                item = RowPattern::Quantified {
2617                    pattern: Box::new(item),
2618                    quantifier,
2619                    reluctant,
2620                };
2621            }
2622            items.push(item);
2623        }
2624        if items.is_empty() {
2625            return Err(self.error("expected a row pattern"));
2626        }
2627        Ok(if items.len() == 1 {
2628            items.pop().unwrap()
2629        } else {
2630            RowPattern::Concat(items)
2631        })
2632    }
2633
2634    fn parse_pattern_bound(&mut self) -> Result<Option<u64>> {
2635        match self.peek().map(|t| t.kind.clone()) {
2636            Some(TokenKind::Integer) => {
2637                let text = self.peek().unwrap().text.clone();
2638                let value = text
2639                    .parse::<u64>()
2640                    .map_err(|_| self.error("expected a whole number in a pattern quantifier"))?;
2641                self.pos += 1;
2642                Ok(Some(value))
2643            }
2644            _ => Ok(None),
2645        }
2646    }
2647
2648    fn parse_pattern_quantifier(&mut self) -> Result<Option<PatternQuantifier>> {
2649        if self.consume_punct(Punct::Star) {
2650            return Ok(Some(PatternQuantifier::ZeroOrMore));
2651        }
2652        if self.consume_punct(Punct::Plus) {
2653            return Ok(Some(PatternQuantifier::OneOrMore));
2654        }
2655        if self.consume_punct(Punct::Question) {
2656            return Ok(Some(PatternQuantifier::ZeroOrOne));
2657        }
2658        if !self.consume_punct(Punct::LBrace) {
2659            return Ok(None);
2660        }
2661        let min = self.parse_pattern_bound()?;
2662        let quantifier = if self.consume_punct(Punct::Comma) {
2663            let max = self.parse_pattern_bound()?;
2664            if let (Some(lo), Some(hi)) = (min, max) {
2665                if lo > hi {
2666                    return Err(self.error("a pattern quantifier's minimum is above its maximum"));
2667                }
2668            }
2669            PatternQuantifier::Range { min, max }
2670        } else {
2671            match min {
2672                Some(n) => PatternQuantifier::Exactly(n),
2673                None => return Err(self.error("expected a number in a pattern quantifier")),
2674            }
2675        };
2676        self.expect_punct(Punct::RBrace)?;
2677        Ok(Some(quantifier))
2678    }
2679
2680    /// The source text of the tokens from `start` up to (not including) the current one.
2681    fn source_between(&self, start: usize) -> String {
2682        if start >= self.pos {
2683            return String::new();
2684        }
2685        let from = self.tokens[start].span.start;
2686        let to = self.tokens[self.pos - 1].span.end;
2687        self.src[from..to].to_string()
2688    }
2689
2690    /// Skip a balanced token run up to a top-level word of `stops` or the closing parenthesis.
2691    fn skip_until_clause(&mut self, stops: &[&str]) -> Result<()> {
2692        let mut depth = 0usize;
2693        while let Some(token) = self.peek() {
2694            if token.is_punct(Punct::LParen) {
2695                depth += 1;
2696            } else if token.is_punct(Punct::RParen) {
2697                if depth == 0 {
2698                    return Ok(());
2699                }
2700                depth -= 1;
2701            } else if depth == 0 && stops.iter().any(|s| token.is_keyword(s)) {
2702                return Ok(());
2703            }
2704            self.pos += 1;
2705        }
2706        Err(self.error("unclosed parenthesis"))
2707    }
2708
2709    /// `( [TIMESTAMP column [AS name]] PERIOD interval [ORIGIN ...] [OUTPUT ...] [PARTITION BY ...]
2710    /// [METRICS ...] )`, the parentheses included.
2711    fn parse_align_body(&mut self) -> Result<Align> {
2712        self.expect_punct(Punct::LParen)?;
2713        let (timestamp, timestamp_alias) = if self.peek_keyword("TIMESTAMP")
2714            && self.peek_nth(1).is_some_and(Self::is_identifier_token)
2715            && !self.peek_nth_keyword(1, "PERIOD")
2716        {
2717            self.parse_keyword("TIMESTAMP");
2718            let column = self.parse_identifier()?;
2719            (Some(column), self.parse_as_alias()?)
2720        } else {
2721            (None, None)
2722        };
2723        self.expect_keyword("PERIOD")?;
2724        let period = self.parse_expr()?;
2725        let origin = if self.parse_keyword("ORIGIN") {
2726            Some(self.parse_expr()?)
2727        } else {
2728            None
2729        };
2730        let output = if self.parse_keyword("OUTPUT") {
2731            let start = self.pos;
2732            self.skip_until_clause(&["PARTITION", "METRICS"])?;
2733            if start == self.pos {
2734                return Err(self.error("expected the OUTPUT of ALIGN"));
2735            }
2736            Some(self.source_between(start))
2737        } else {
2738            None
2739        };
2740        let mut partition_by = Vec::new();
2741        if self.parse_keywords(&["PARTITION", "BY"]) {
2742            loop {
2743                let expr = self.parse_expr()?;
2744                let alias = self.parse_as_alias()?;
2745                partition_by.push(ExprWithAlias { expr, alias });
2746                if !self.consume_punct(Punct::Comma) {
2747                    break;
2748                }
2749            }
2750        }
2751        let mut metrics = Vec::new();
2752        if self.parse_keyword("METRICS") {
2753            loop {
2754                let expr = self.parse_expr()?;
2755                let within = if self.parse_keyword("WITHIN") {
2756                    if !matches!(expr, Expr::Function(_)) {
2757                        return Err(self.error("WITHIN follows an aggregate call"));
2758                    }
2759                    self.expect_punct(Punct::LParen)?;
2760                    let start = self.pos;
2761                    self.skip_until_clause(&[])?;
2762                    let text = self.source_between(start);
2763                    self.expect_punct(Punct::RParen)?;
2764                    Some(text)
2765                } else {
2766                    None
2767                };
2768                let alias = self.parse_as_alias()?;
2769                metrics.push(AlignMetric {
2770                    expr,
2771                    within,
2772                    alias,
2773                });
2774                if !self.consume_punct(Punct::Comma) {
2775                    break;
2776                }
2777            }
2778        }
2779        self.expect_punct(Punct::RParen)?;
2780        Ok(Align {
2781            timestamp,
2782            timestamp_alias,
2783            period,
2784            origin,
2785            output,
2786            partition_by,
2787            metrics,
2788        })
2789    }
2790
2791    // ------------------------------------------------------------------ pipe syntax
2792
2793    fn parse_pipe_expr_items(&mut self) -> Result<Vec<PipeExprItem>> {
2794        let mut out = Vec::new();
2795        loop {
2796            let expr = self.parse_expr()?;
2797            let alias = self.parse_optional_alias(false)?;
2798            let (asc, nulls_first) = self.parse_order_spec();
2799            out.push(PipeExprItem {
2800                expr,
2801                alias,
2802                asc,
2803                nulls_first,
2804            });
2805            if !self.consume_punct(Punct::Comma) || self.peek_keyword("GROUP") || self.at_pipe_end()
2806            {
2807                break;
2808            }
2809        }
2810        Ok(out)
2811    }
2812
2813    fn at_pipe_end(&self) -> bool {
2814        self.at_end()
2815            || self.peek_punct(Punct::Pipe)
2816            || self.peek_punct(Punct::RParen)
2817            || self.peek_punct(Punct::Semicolon)
2818    }
2819
2820    fn parse_pipe_operator(&mut self) -> Result<PipeOperator> {
2821        if self.parse_keyword("WHERE") {
2822            return Ok(PipeOperator::Where(self.parse_expr()?));
2823        }
2824        if self.parse_keyword("SELECT") {
2825            let distinct = if self.parse_keyword("DISTINCT") {
2826                true
2827            } else {
2828                self.parse_keyword("ALL");
2829                false
2830            };
2831            let select_as = self.parse_select_as();
2832            return Ok(PipeOperator::Select {
2833                distinct,
2834                select_as,
2835                items: self.parse_select_items()?,
2836            });
2837        }
2838        if self.parse_keyword("EXTEND") {
2839            return Ok(PipeOperator::Extend(self.parse_select_items()?));
2840        }
2841        if self.parse_keyword("WINDOW") {
2842            return Ok(PipeOperator::Window(self.parse_select_items()?));
2843        }
2844        if self.parse_keyword("SET") {
2845            return Ok(PipeOperator::Set(self.parse_assignments()?));
2846        }
2847        if self.parse_keyword("DROP") {
2848            let mut cols = vec![self.parse_identifier()?];
2849            while self.consume_punct(Punct::Comma) {
2850                if self.at_pipe_end() {
2851                    break;
2852                }
2853                cols.push(self.parse_identifier()?);
2854            }
2855            return Ok(PipeOperator::Drop(cols));
2856        }
2857        if self.parse_keyword("RENAME") {
2858            let mut pairs = Vec::new();
2859            loop {
2860                let from = self.parse_identifier()?;
2861                self.parse_keyword("AS");
2862                let to = self.parse_identifier()?;
2863                pairs.push((from, to));
2864                if !self.consume_punct(Punct::Comma) || self.at_pipe_end() {
2865                    break;
2866                }
2867            }
2868            return Ok(PipeOperator::Rename(pairs));
2869        }
2870        if self.parse_keyword("AS") {
2871            return Ok(PipeOperator::As(self.parse_identifier()?));
2872        }
2873        if self.parse_keyword("AGGREGATE") {
2874            let items = if self.peek_keyword("GROUP") || self.at_pipe_end() {
2875                Vec::new()
2876            } else {
2877                self.parse_pipe_expr_items()?
2878            };
2879            let mut group_by = Vec::new();
2880            let mut group_and_order = false;
2881            if self.parse_keywords(&["GROUP", "AND", "ORDER", "BY"]) {
2882                group_and_order = true;
2883                group_by = self.parse_pipe_expr_items()?;
2884            } else if self.parse_keywords(&["GROUP", "BY"]) {
2885                group_by = self.parse_pipe_expr_items()?;
2886            }
2887            return Ok(PipeOperator::Aggregate {
2888                items,
2889                group_by,
2890                group_and_order,
2891            });
2892        }
2893        if self.parse_keywords(&["ORDER", "BY"]) {
2894            return Ok(PipeOperator::OrderBy(self.parse_order_by_list()?));
2895        }
2896        if self.parse_keyword("LIMIT") {
2897            return Ok(PipeOperator::Limit(self.parse_limit_body()?));
2898        }
2899        if self.parse_keyword("DISTINCT") {
2900            return Ok(PipeOperator::Distinct);
2901        }
2902        if self.peek_keyword("TABLESAMPLE") {
2903            return Ok(PipeOperator::TableSample(self.parse_tablesample()?));
2904        }
2905        if self.parse_keyword("CALL") {
2906            let name = self.parse_object_name(true)?;
2907            let function = self.parse_function_call(name, self.pos.saturating_sub(1))?;
2908            let alias = self.parse_optional_alias(true)?;
2909            return Ok(PipeOperator::Call { function, alias });
2910        }
2911        if self.parse_keyword("PIVOT") {
2912            let (aggregates, value_column, values) = self.parse_pivot_body()?;
2913            let alias = self.parse_optional_alias(true)?;
2914            return Ok(PipeOperator::Pivot {
2915                aggregates,
2916                value_column: Box::new(value_column),
2917                values,
2918                alias,
2919            });
2920        }
2921        if self.parse_keyword("UNPIVOT") {
2922            let (include_nulls, value_columns, name_column, columns) = self.parse_unpivot_body()?;
2923            let alias = self.parse_optional_alias(true)?;
2924            return Ok(PipeOperator::Unpivot {
2925                include_nulls,
2926                value_columns,
2927                name_column,
2928                columns,
2929                alias,
2930            });
2931        }
2932        if self.peek_keyword("MATCH_RECOGNIZE") && self.peek_nth_punct(1, Punct::LParen) {
2933            self.parse_keyword("MATCH_RECOGNIZE");
2934            let spec = Box::new(self.parse_match_recognize_body()?);
2935            let alias = self.parse_optional_alias(true)?;
2936            return Ok(PipeOperator::MatchRecognize { spec, alias });
2937        }
2938        if self.peek_keyword("ALIGN") && self.peek_nth_punct(1, Punct::LParen) {
2939            self.parse_keyword("ALIGN");
2940            let spec = Box::new(self.parse_align_body()?);
2941            let alias = self.parse_optional_alias(true)?;
2942            return Ok(PipeOperator::Align { spec, alias });
2943        }
2944        if self.parse_keyword("ASSERT") {
2945            let condition = self.parse_expr()?;
2946            let mut payload = Vec::new();
2947            while self.consume_punct(Punct::Comma) {
2948                payload.push(self.parse_expr()?);
2949            }
2950            return Ok(PipeOperator::Assert { condition, payload });
2951        }
2952        if let Some((op, quantifier, mode, corresponding)) = self.parse_set_operator()? {
2953            let mut queries = Vec::new();
2954            loop {
2955                self.expect_punct(Punct::LParen)?;
2956                queries.push(self.parse_query()?);
2957                self.expect_punct(Punct::RParen)?;
2958                if !self.consume_punct(Punct::Comma) {
2959                    break;
2960                }
2961            }
2962            return Ok(PipeOperator::SetOperation {
2963                op,
2964                quantifier,
2965                mode,
2966                corresponding,
2967                queries,
2968            });
2969        }
2970        if let Some(join) = self.parse_join()? {
2971            return Ok(PipeOperator::Join(join));
2972        }
2973        Err(self.error("expected a pipe operator"))
2974    }
2975
2976    // ------------------------------------------------------------------ expressions
2977
2978    /// Parse a full expression.
2979    pub fn parse_expr(&mut self) -> Result<Expr> {
2980        self.parse_subexpr(0)
2981    }
2982
2983    fn parse_subexpr(&mut self, min_precedence: u8) -> Result<Expr> {
2984        self.enter()?;
2985        let result = (|| {
2986            let mut left = self.parse_prefix()?;
2987            loop {
2988                let precedence = self.infix_precedence();
2989                if precedence == 0 || precedence <= min_precedence {
2990                    break;
2991                }
2992                left = self.parse_infix(left, precedence)?;
2993            }
2994            Ok(left)
2995        })();
2996        self.leave();
2997        result
2998    }
2999
3000    fn infix_precedence(&self) -> u8 {
3001        let Some(token) = self.peek() else {
3002            return 0;
3003        };
3004        match &token.kind {
3005            TokenKind::Word => match token.upper().as_str() {
3006                "OR" => 1,
3007                "AND" => 2,
3008                "NOT" => {
3009                    if ["IN", "LIKE", "BETWEEN"]
3010                        .iter()
3011                        .any(|k| self.peek_nth_keyword(1, k))
3012                    {
3013                        COMPARISON_PRECEDENCE
3014                    } else {
3015                        0
3016                    }
3017                }
3018                "IS" | "IN" | "LIKE" | "BETWEEN" => COMPARISON_PRECEDENCE,
3019                _ => 0,
3020            },
3021            TokenKind::Punct(p) => match p {
3022                Punct::Eq
3023                | Punct::NotEq
3024                | Punct::LtGt
3025                | Punct::Lt
3026                | Punct::LtEq
3027                | Punct::Gt
3028                | Punct::GtEq => COMPARISON_PRECEDENCE,
3029                Punct::Bar => 5,
3030                Punct::Caret => 6,
3031                Punct::Ampersand => 7,
3032                Punct::ShiftLeft | Punct::ShiftRight => 8,
3033                Punct::Plus | Punct::Minus => 9,
3034                Punct::Star | Punct::Slash | Punct::Concat => 10,
3035                _ => 0,
3036            },
3037            _ => 0,
3038        }
3039    }
3040
3041    fn parse_infix(&mut self, left: Expr, precedence: u8) -> Result<Expr> {
3042        let token = self
3043            .peek()
3044            .cloned()
3045            .ok_or_else(|| self.error("expected an operator"))?;
3046        if let TokenKind::Punct(p) = token.kind {
3047            let op = match p {
3048                Punct::Eq => BinaryOperator::Eq,
3049                Punct::NotEq | Punct::LtGt => BinaryOperator::NotEq,
3050                Punct::Lt => BinaryOperator::Lt,
3051                Punct::LtEq => BinaryOperator::LtEq,
3052                Punct::Gt => BinaryOperator::Gt,
3053                Punct::GtEq => BinaryOperator::GtEq,
3054                Punct::Bar => BinaryOperator::BitOr,
3055                Punct::Caret => BinaryOperator::BitXor,
3056                Punct::Ampersand => BinaryOperator::BitAnd,
3057                Punct::ShiftLeft => BinaryOperator::ShiftLeft,
3058                Punct::ShiftRight => BinaryOperator::ShiftRight,
3059                Punct::Plus => BinaryOperator::Plus,
3060                Punct::Minus => BinaryOperator::Minus,
3061                Punct::Star => BinaryOperator::Multiply,
3062                Punct::Slash => BinaryOperator::Divide,
3063                Punct::Concat => BinaryOperator::Concat,
3064                _ => return Err(self.error("expected an operator")),
3065            };
3066            self.pos += 1;
3067            let right = self.parse_subexpr(precedence)?;
3068            return Ok(Expr::binary(left, op, right));
3069        }
3070        let upper = token.upper();
3071        match upper.as_str() {
3072            "OR" | "AND" => {
3073                self.parse_keyword(&upper);
3074                let op = if upper == "OR" {
3075                    BinaryOperator::Or
3076                } else {
3077                    BinaryOperator::And
3078                };
3079                let right = self.parse_subexpr(precedence)?;
3080                Ok(Expr::binary(left, op, right))
3081            }
3082            "IS" => {
3083                self.parse_keyword("IS");
3084                let negated = self.parse_keyword("NOT");
3085                if self.parse_keyword("NULL") {
3086                    self.set_role(self.pos - 1, TokenRole::Literal);
3087                    return Ok(Expr::IsNull {
3088                        expr: Box::new(left),
3089                        negated,
3090                    });
3091                }
3092                if self.parse_keyword("TRUE")
3093                    || self.parse_keyword("FALSE")
3094                    || self.parse_keyword("UNKNOWN")
3095                {
3096                    let word = self.tokens[self.pos - 1].upper();
3097                    self.set_role(self.pos - 1, TokenRole::Literal);
3098                    let value = match word.as_str() {
3099                        "TRUE" => Some(true),
3100                        "FALSE" => Some(false),
3101                        _ => None,
3102                    };
3103                    return Ok(Expr::IsBool {
3104                        expr: Box::new(left),
3105                        value,
3106                        negated,
3107                    });
3108                }
3109                if self.parse_keywords(&["DISTINCT", "FROM"]) {
3110                    let right = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
3111                    return Ok(Expr::IsDistinctFrom {
3112                        left: Box::new(left),
3113                        right: Box::new(right),
3114                        negated,
3115                    });
3116                }
3117                Err(self.error("expected NULL, TRUE, FALSE, UNKNOWN or DISTINCT FROM after IS"))
3118            }
3119            _ => {
3120                let negated = self.parse_keyword("NOT");
3121                if self.parse_keyword("IN") {
3122                    return self.parse_in(left, negated);
3123                }
3124                if self.parse_keyword("LIKE") {
3125                    return self.parse_like(left, negated);
3126                }
3127                if self.parse_keyword("BETWEEN") {
3128                    let low = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
3129                    self.expect_keyword("AND")?;
3130                    let high = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
3131                    return Ok(Expr::Between {
3132                        expr: Box::new(left),
3133                        negated,
3134                        low: Box::new(low),
3135                        high: Box::new(high),
3136                    });
3137                }
3138                Err(self.error("expected an operator"))
3139            }
3140        }
3141    }
3142
3143    fn parse_in(&mut self, left: Expr, negated: bool) -> Result<Expr> {
3144        if self.parse_keyword("UNNEST") {
3145            self.expect_punct(Punct::LParen)?;
3146            let array = self.parse_expr()?;
3147            self.expect_punct(Punct::RParen)?;
3148            return Ok(Expr::InUnnest {
3149                expr: Box::new(left),
3150                array: Box::new(array),
3151                negated,
3152            });
3153        }
3154        if let Some(query) = self.attempt_parenthesized_query() {
3155            return Ok(Expr::InSubquery {
3156                expr: Box::new(left),
3157                subquery: Box::new(query),
3158                negated,
3159            });
3160        }
3161        self.expect_punct(Punct::LParen)?;
3162        let mut list = vec![self.parse_expr()?];
3163        while self.consume_punct(Punct::Comma) {
3164            list.push(self.parse_expr()?);
3165        }
3166        self.expect_punct(Punct::RParen)?;
3167        Ok(Expr::InList {
3168            expr: Box::new(left),
3169            list,
3170            negated,
3171        })
3172    }
3173
3174    /// `( query )` when the parenthesis opens a query; nothing consumed otherwise.
3175    fn attempt_parenthesized_query(&mut self) -> Option<Query> {
3176        if !self.paren_starts_query() {
3177            return None;
3178        }
3179        self.attempt(|p| {
3180            p.expect_punct(Punct::LParen)?;
3181            let query = p.parse_query()?;
3182            p.expect_punct(Punct::RParen)?;
3183            Ok(query)
3184        })
3185    }
3186
3187    fn parse_like(&mut self, left: Expr, negated: bool) -> Result<Expr> {
3188        let quantifier = if self.parse_keyword("ANY") {
3189            Some(LikeQuantifier::Any)
3190        } else if self.parse_keyword("SOME") {
3191            Some(LikeQuantifier::Some)
3192        } else if self.parse_keyword("ALL") {
3193            Some(LikeQuantifier::All)
3194        } else {
3195            None
3196        };
3197        let Some(quantifier) = quantifier else {
3198            let pattern = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
3199            return Ok(Expr::Like {
3200                expr: Box::new(left),
3201                negated,
3202                pattern: Box::new(pattern),
3203            });
3204        };
3205        let patterns = if self.parse_keyword("UNNEST") {
3206            self.expect_punct(Punct::LParen)?;
3207            let array = self.parse_expr()?;
3208            self.expect_punct(Punct::RParen)?;
3209            LikePatterns::Unnest(Box::new(array))
3210        } else if let Some(query) = self.attempt_parenthesized_query() {
3211            LikePatterns::Subquery(Box::new(query))
3212        } else {
3213            self.expect_punct(Punct::LParen)?;
3214            let mut list = vec![self.parse_expr()?];
3215            while self.consume_punct(Punct::Comma) {
3216                list.push(self.parse_expr()?);
3217            }
3218            self.expect_punct(Punct::RParen)?;
3219            LikePatterns::List(list)
3220        };
3221        Ok(Expr::LikeQuantified {
3222            expr: Box::new(left),
3223            negated,
3224            quantifier,
3225            patterns,
3226        })
3227    }
3228
3229    /// A primary expression with its postfix field accesses and subscripts.
3230    fn parse_prefix(&mut self) -> Result<Expr> {
3231        let mut expr = self.parse_primary()?;
3232        loop {
3233            if self.peek_punct(Punct::LBracket) {
3234                self.pos += 1;
3235                let (kind, index) = self.parse_subscript()?;
3236                self.expect_punct(Punct::RBracket)?;
3237                expr = Expr::Subscript {
3238                    expr: Box::new(expr),
3239                    kind,
3240                    index: Box::new(index),
3241                };
3242            } else if self.peek_punct(Punct::Dot)
3243                && self.peek_nth(1).is_some_and(|t| {
3244                    matches!(
3245                        t.kind,
3246                        TokenKind::Word | TokenKind::QuotedIdentifier(_) | TokenKind::Integer
3247                    )
3248                })
3249            {
3250                self.pos += 1;
3251                let field = self.parse_path_part()?;
3252                expr = match expr {
3253                    Expr::Identifier(first) => Expr::CompoundIdentifier(vec![first, field]),
3254                    Expr::CompoundIdentifier(mut parts) => {
3255                        parts.push(field);
3256                        Expr::CompoundIdentifier(parts)
3257                    }
3258                    other => Expr::FieldAccess {
3259                        expr: Box::new(other),
3260                        field,
3261                    },
3262                };
3263            } else {
3264                break;
3265            }
3266        }
3267        Ok(expr)
3268    }
3269
3270    fn parse_subscript(&mut self) -> Result<(SubscriptKind, Expr)> {
3271        let kinds = [
3272            ("OFFSET", SubscriptKind::Offset),
3273            ("ORDINAL", SubscriptKind::Ordinal),
3274            ("SAFE_OFFSET", SubscriptKind::SafeOffset),
3275            ("SAFE_ORDINAL", SubscriptKind::SafeOrdinal),
3276        ];
3277        for (word, kind) in kinds {
3278            if self.peek_keyword(word) && self.peek_nth_punct(1, Punct::LParen) {
3279                self.parse_keyword(word);
3280                self.expect_punct(Punct::LParen)?;
3281                let index = self.parse_expr()?;
3282                self.expect_punct(Punct::RParen)?;
3283                return Ok((kind, index));
3284            }
3285        }
3286        Ok((SubscriptKind::Plain, self.parse_expr()?))
3287    }
3288
3289    fn parse_primary(&mut self) -> Result<Expr> {
3290        let Some(token) = self.peek().cloned() else {
3291            return Err(self.error("expected an expression"));
3292        };
3293        match &token.kind {
3294            TokenKind::Integer => {
3295                self.pos += 1;
3296                Ok(Expr::Literal(Literal::Int(token.text)))
3297            }
3298            TokenKind::Float => {
3299                self.pos += 1;
3300                Ok(Expr::Literal(Literal::Float(token.text)))
3301            }
3302            TokenKind::String { value, raw, quote } => {
3303                self.pos += 1;
3304                Ok(Expr::Literal(Literal::String(StringLiteral {
3305                    value: value.clone(),
3306                    raw: *raw,
3307                    quote: *quote,
3308                })))
3309            }
3310            TokenKind::Bytes { value, raw, quote } => {
3311                self.pos += 1;
3312                Ok(Expr::Literal(Literal::Bytes(BytesLiteral {
3313                    value: value.clone(),
3314                    raw: *raw,
3315                    quote: *quote,
3316                })))
3317            }
3318            TokenKind::Parameter(name) => {
3319                self.pos += 1;
3320                Ok(Expr::Parameter(Parameter::Named(name.clone())))
3321            }
3322            TokenKind::SystemVariable(name) => {
3323                self.pos += 1;
3324                Ok(Expr::Parameter(Parameter::System(name.clone())))
3325            }
3326            TokenKind::Punct(Punct::Question) => {
3327                self.pos += 1;
3328                Ok(Expr::Parameter(Parameter::Positional))
3329            }
3330            TokenKind::Punct(p @ (Punct::Minus | Punct::Plus | Punct::Tilde)) => {
3331                self.pos += 1;
3332                let op = match p {
3333                    Punct::Minus => UnaryOperator::Minus,
3334                    Punct::Plus => UnaryOperator::Plus,
3335                    _ => UnaryOperator::BitNot,
3336                };
3337                let expr = self.parse_subexpr(UNARY_PRECEDENCE)?;
3338                Ok(Expr::UnaryOp {
3339                    op,
3340                    expr: Box::new(expr),
3341                })
3342            }
3343            TokenKind::Punct(Punct::LParen) => self.parse_parenthesized(),
3344            TokenKind::Punct(Punct::LBracket) => {
3345                self.pos += 1;
3346                let elements = self.parse_array_elements()?;
3347                Ok(Expr::Array {
3348                    elements,
3349                    element_type: None,
3350                    keyword: false,
3351                })
3352            }
3353            TokenKind::QuotedIdentifier(_) => self.parse_identifier_chain(),
3354            TokenKind::Word => self.parse_word_expr(&token),
3355            _ => Err(self.error("expected an expression")),
3356        }
3357    }
3358
3359    fn parse_parenthesized(&mut self) -> Result<Expr> {
3360        if let Some(query) = self.attempt_parenthesized_query() {
3361            return Ok(Expr::Subquery(Box::new(query)));
3362        }
3363        self.expect_punct(Punct::LParen)?;
3364        let first = self.parse_expr()?;
3365        if self.consume_punct(Punct::Comma) {
3366            let mut items = vec![first];
3367            loop {
3368                items.push(self.parse_expr()?);
3369                if !self.consume_punct(Punct::Comma) {
3370                    break;
3371                }
3372            }
3373            self.expect_punct(Punct::RParen)?;
3374            return Ok(Expr::Tuple(items));
3375        }
3376        self.expect_punct(Punct::RParen)?;
3377        Ok(Expr::Nested(Box::new(first)))
3378    }
3379
3380    fn parse_array_elements(&mut self) -> Result<Vec<Expr>> {
3381        let mut elements = Vec::new();
3382        while !self.peek_punct(Punct::RBracket) {
3383            elements.push(self.parse_expr()?);
3384            if !self.consume_punct(Punct::Comma) {
3385                break;
3386            }
3387        }
3388        self.expect_punct(Punct::RBracket)?;
3389        Ok(elements)
3390    }
3391
3392    fn parse_identifier_chain(&mut self) -> Result<Expr> {
3393        let start = self.pos;
3394        let first = self.parse_identifier()?;
3395        let mut parts = vec![first];
3396        while self.peek_punct(Punct::Dot)
3397            && self.peek_nth(1).is_some_and(|t| {
3398                matches!(
3399                    t.kind,
3400                    TokenKind::Word | TokenKind::QuotedIdentifier(_) | TokenKind::Integer
3401                )
3402            })
3403        {
3404            self.pos += 1;
3405            parts.push(self.parse_path_part()?);
3406        }
3407        if self.peek_punct(Punct::LParen) {
3408            let function = self.parse_function_call(ObjectName(parts), self.pos - 1)?;
3409            return Ok(Expr::Function(Box::new(function)));
3410        }
3411        if parts.len() == 1 {
3412            let name = parts[0].value.to_ascii_uppercase();
3413            if !parts[0].quoted && NO_PAREN_FUNCTIONS.contains(&name.as_str()) {
3414                self.set_role(start, TokenRole::Function);
3415                let mut function = Function::new(&parts[0].value, Vec::new());
3416                function.no_parens = true;
3417                return Ok(Expr::Function(Box::new(function)));
3418            }
3419            return Ok(Expr::Identifier(parts.remove(0)));
3420        }
3421        Ok(Expr::CompoundIdentifier(parts))
3422    }
3423
3424    fn parse_word_expr(&mut self, token: &Token) -> Result<Expr> {
3425        let upper = token.upper();
3426        let next_is_string = matches!(
3427            self.peek_nth(1).map(|t| &t.kind),
3428            Some(TokenKind::String { .. })
3429        );
3430        let next_paren = self.peek_nth_punct(1, Punct::LParen);
3431        match upper.as_str() {
3432            "NOT" => {
3433                self.parse_keyword("NOT");
3434                let expr = self.parse_subexpr(NOT_PRECEDENCE)?;
3435                return Ok(Expr::UnaryOp {
3436                    op: UnaryOperator::Not,
3437                    expr: Box::new(expr),
3438                });
3439            }
3440            "NULL" => {
3441                self.set_role(self.pos, TokenRole::Literal);
3442                self.pos += 1;
3443                return Ok(Expr::null());
3444            }
3445            "TRUE" | "FALSE" => {
3446                self.set_role(self.pos, TokenRole::Literal);
3447                self.pos += 1;
3448                return Ok(Expr::Literal(Literal::Bool(upper == "TRUE")));
3449            }
3450            "DEFAULT" => {
3451                self.parse_keyword("DEFAULT");
3452                return Ok(Expr::Default);
3453            }
3454            "CASE" => return self.parse_case_expr(),
3455            "CAST" | "SAFE_CAST" if next_paren => return self.parse_cast(upper == "SAFE_CAST"),
3456            "EXTRACT" if next_paren => return self.parse_extract(),
3457            "EXISTS" if next_paren => {
3458                self.parse_keyword("EXISTS");
3459                self.expect_punct(Punct::LParen)?;
3460                let query = self.parse_query()?;
3461                self.expect_punct(Punct::RParen)?;
3462                return Ok(Expr::Exists(Box::new(query)));
3463            }
3464            "ARRAY" => return self.parse_array_expr(),
3465            "STRUCT" => return self.parse_struct_expr(),
3466            "INTERVAL" => return self.parse_interval(),
3467            "WITH" if next_paren => return self.parse_scalar_with(),
3468            "RANGE" if self.peek_nth_punct(1, Punct::Lt) => {
3469                self.parse_keyword("RANGE");
3470                self.set_role(self.pos - 1, TokenRole::Type);
3471                self.expect_punct(Punct::Lt)?;
3472                let element = self.parse_data_type()?;
3473                self.expect_gt()?;
3474                let value = self.expect_string()?;
3475                return Ok(Expr::Literal(Literal::Range {
3476                    element: Box::new(element),
3477                    value,
3478                }));
3479            }
3480            "DATE" | "DATETIME" | "TIME" | "TIMESTAMP" | "NUMERIC" | "BIGNUMERIC" | "DECIMAL"
3481            | "BIGDECIMAL" | "JSON"
3482                if next_is_string =>
3483            {
3484                self.set_role(self.pos, TokenRole::Keyword);
3485                self.pos += 1;
3486                let value = self.expect_string()?;
3487                let literal = match upper.as_str() {
3488                    "DATE" => Literal::Date(value),
3489                    "DATETIME" => Literal::Datetime(value),
3490                    "TIME" => Literal::Time(value),
3491                    "TIMESTAMP" => Literal::Timestamp(value),
3492                    "NUMERIC" | "DECIMAL" => Literal::Numeric(value),
3493                    "BIGNUMERIC" | "BIGDECIMAL" => Literal::BigNumeric(value),
3494                    _ => Literal::Json(value),
3495                };
3496                return Ok(Expr::Literal(literal));
3497            }
3498            _ => {}
3499        }
3500        if is_reserved_keyword(&upper) {
3501            if next_paren && RESERVED_FUNCTIONS.contains(&upper.as_str()) {
3502                self.pos += 1;
3503                let name = ObjectName(vec![Ident::new(token.text.clone())]);
3504                let function = self.parse_function_call(name, self.pos - 1)?;
3505                return Ok(Expr::Function(Box::new(function)));
3506            }
3507            return Err(self.error("expected an expression"));
3508        }
3509        self.parse_identifier_chain()
3510    }
3511
3512    fn expect_string(&mut self) -> Result<String> {
3513        match self.peek().map(|t| t.kind.clone()) {
3514            Some(TokenKind::String { value, .. }) => {
3515                self.pos += 1;
3516                Ok(value)
3517            }
3518            _ => Err(self.error("expected a string literal")),
3519        }
3520    }
3521
3522    fn parse_case_expr(&mut self) -> Result<Expr> {
3523        self.expect_keyword("CASE")?;
3524        let operand = if self.peek_keyword("WHEN") {
3525            None
3526        } else {
3527            Some(Box::new(self.parse_expr()?))
3528        };
3529        let mut branches = Vec::new();
3530        while self.parse_keyword("WHEN") {
3531            let condition = self.parse_expr()?;
3532            self.expect_keyword("THEN")?;
3533            let result = self.parse_expr()?;
3534            branches.push(CaseWhen { condition, result });
3535        }
3536        if branches.is_empty() {
3537            return Err(self.error("expected WHEN"));
3538        }
3539        let else_result = if self.parse_keyword("ELSE") {
3540            Some(Box::new(self.parse_expr()?))
3541        } else {
3542            None
3543        };
3544        self.expect_keyword("END")?;
3545        Ok(Expr::Case {
3546            operand,
3547            branches,
3548            else_result,
3549        })
3550    }
3551
3552    fn parse_cast(&mut self, safe: bool) -> Result<Expr> {
3553        self.set_role(self.pos, TokenRole::Function);
3554        self.pos += 1;
3555        self.expect_punct(Punct::LParen)?;
3556        let expr = self.parse_expr()?;
3557        self.expect_keyword("AS")?;
3558        let data_type = self.parse_data_type()?;
3559        let format = if self.parse_keyword("FORMAT") {
3560            Some(Box::new(self.parse_expr()?))
3561        } else {
3562            None
3563        };
3564        let time_zone = if self.parse_keywords(&["AT", "TIME", "ZONE"]) {
3565            Some(Box::new(self.parse_expr()?))
3566        } else {
3567            None
3568        };
3569        self.expect_punct(Punct::RParen)?;
3570        Ok(Expr::Cast {
3571            expr: Box::new(expr),
3572            data_type,
3573            safe,
3574            format,
3575            time_zone,
3576        })
3577    }
3578
3579    fn parse_extract(&mut self) -> Result<Expr> {
3580        self.set_role(self.pos, TokenRole::Function);
3581        self.pos += 1;
3582        self.expect_punct(Punct::LParen)?;
3583        let part_start = self.pos;
3584        let part = self.parse_expr()?;
3585        if part_start + 1 == self.pos {
3586            self.set_role(part_start, TokenRole::Keyword);
3587        }
3588        self.expect_keyword("FROM")?;
3589        let expr = self.parse_expr()?;
3590        let time_zone = if self.parse_keywords(&["AT", "TIME", "ZONE"]) {
3591            Some(Box::new(self.parse_expr()?))
3592        } else {
3593            None
3594        };
3595        self.expect_punct(Punct::RParen)?;
3596        Ok(Expr::Extract {
3597            part: Box::new(part),
3598            expr: Box::new(expr),
3599            time_zone,
3600        })
3601    }
3602
3603    fn parse_array_expr(&mut self) -> Result<Expr> {
3604        self.set_role(self.pos, TokenRole::Keyword);
3605        self.pos += 1;
3606        if self.peek_punct(Punct::LParen) {
3607            self.set_role(self.pos - 1, TokenRole::Function);
3608            self.pos += 1;
3609            let query = self.parse_query()?;
3610            self.expect_punct(Punct::RParen)?;
3611            return Ok(Expr::ArraySubquery(Box::new(query)));
3612        }
3613        let element_type = if self.consume_punct(Punct::Lt) {
3614            self.set_role(self.pos - 2, TokenRole::Type);
3615            let ty = self.parse_data_type()?;
3616            self.expect_gt()?;
3617            Some(Box::new(ty))
3618        } else {
3619            None
3620        };
3621        self.expect_punct(Punct::LBracket)?;
3622        let elements = self.parse_array_elements()?;
3623        Ok(Expr::Array {
3624            elements,
3625            element_type,
3626            keyword: true,
3627        })
3628    }
3629
3630    fn parse_struct_expr(&mut self) -> Result<Expr> {
3631        self.set_role(self.pos, TokenRole::Keyword);
3632        self.pos += 1;
3633        let typed = if self.consume_punct(Punct::Lt) {
3634            self.set_role(self.pos - 2, TokenRole::Type);
3635            Some(self.parse_struct_fields()?)
3636        } else {
3637            None
3638        };
3639        self.expect_punct(Punct::LParen)?;
3640        let mut fields = Vec::new();
3641        while !self.peek_punct(Punct::RParen) {
3642            let expr = self.parse_expr()?;
3643            let alias = if self.parse_keyword("AS") {
3644                Some(self.parse_identifier()?)
3645            } else {
3646                None
3647            };
3648            fields.push(StructExprField { expr, alias });
3649            if !self.consume_punct(Punct::Comma) {
3650                break;
3651            }
3652        }
3653        self.expect_punct(Punct::RParen)?;
3654        Ok(Expr::Struct { fields, typed })
3655    }
3656
3657    fn parse_interval(&mut self) -> Result<Expr> {
3658        self.expect_keyword("INTERVAL")?;
3659        let value = self.parse_subexpr(UNARY_PRECEDENCE)?;
3660        let leading = self.parse_date_part()?;
3661        let trailing = if self.parse_keyword("TO") {
3662            Some(self.parse_date_part()?)
3663        } else {
3664            None
3665        };
3666        Ok(Expr::Literal(Literal::Interval(IntervalLiteral {
3667            value: Box::new(value),
3668            leading,
3669            trailing,
3670        })))
3671    }
3672
3673    fn parse_date_part(&mut self) -> Result<String> {
3674        match self.peek() {
3675            Some(t) if t.is_word() => {
3676                let part = t.upper();
3677                self.set_role(self.pos, TokenRole::Keyword);
3678                self.pos += 1;
3679                Ok(part)
3680            }
3681            _ => Err(self.error("expected a date part")),
3682        }
3683    }
3684
3685    fn parse_scalar_with(&mut self) -> Result<Expr> {
3686        self.parse_keyword("WITH");
3687        self.expect_punct(Punct::LParen)?;
3688        let mut bindings = Vec::new();
3689        loop {
3690            if self.peek_identifier() && self.peek_nth_keyword(1, "AS") {
3691                let name = self.parse_identifier()?;
3692                self.expect_keyword("AS")?;
3693                let value = self.parse_expr()?;
3694                bindings.push((name, value));
3695                self.expect_punct(Punct::Comma)?;
3696            } else {
3697                let body = self.parse_expr()?;
3698                self.expect_punct(Punct::RParen)?;
3699                return Ok(Expr::ScalarWith {
3700                    bindings,
3701                    body: Box::new(body),
3702                });
3703            }
3704        }
3705    }
3706
3707    /// The call after its name; `name_token` is the index of the name's last token.
3708    fn parse_function_call(&mut self, name: ObjectName, name_token: usize) -> Result<Function> {
3709        self.set_role(name_token, TokenRole::Function);
3710        self.expect_punct(Punct::LParen)?;
3711        let mut function = Function {
3712            name,
3713            args: Vec::new(),
3714            distinct: false,
3715            null_treatment: None,
3716            having: None,
3717            order_by: Vec::new(),
3718            limit: None,
3719            over: None,
3720            no_parens: false,
3721        };
3722        function.distinct = self.parse_keyword("DISTINCT");
3723        while !self.peek_punct(Punct::RParen) && !self.peek_function_modifier() {
3724            function.args.push(self.parse_function_arg()?);
3725            if !self.consume_punct(Punct::Comma) {
3726                break;
3727            }
3728        }
3729        if self.parse_keywords(&["IGNORE", "NULLS"]) {
3730            function.null_treatment = Some(NullTreatment::IgnoreNulls);
3731        } else if self.parse_keywords(&["RESPECT", "NULLS"]) {
3732            function.null_treatment = Some(NullTreatment::RespectNulls);
3733        }
3734        if self.parse_keyword("HAVING") {
3735            let max = if self.parse_keyword("MAX") {
3736                true
3737            } else {
3738                self.expect_keyword("MIN")?;
3739                false
3740            };
3741            function.having = Some(HavingBound {
3742                max,
3743                expr: Box::new(self.parse_expr()?),
3744            });
3745        }
3746        if self.parse_keywords(&["ORDER", "BY"]) {
3747            function.order_by = self.parse_order_by_list()?;
3748        }
3749        if self.parse_keyword("LIMIT") {
3750            function.limit = Some(Box::new(self.parse_expr()?));
3751        }
3752        self.expect_punct(Punct::RParen)?;
3753        if self.parse_keyword("OVER") {
3754            function.over = Some(if self.peek_punct(Punct::LParen) {
3755                WindowType::Spec(self.parse_window_spec()?)
3756            } else {
3757                WindowType::Named(self.parse_identifier()?)
3758            });
3759        }
3760        Ok(function)
3761    }
3762
3763    fn peek_function_modifier(&self) -> bool {
3764        (self.peek_keyword("IGNORE") || self.peek_keyword("RESPECT"))
3765            && self.peek_nth_keyword(1, "NULLS")
3766            || self.peek_keyword("HAVING")
3767            || (self.peek_keyword("ORDER") && self.peek_nth_keyword(1, "BY"))
3768            || self.peek_keyword("LIMIT")
3769    }
3770
3771    fn parse_function_arg(&mut self) -> Result<FunctionArg> {
3772        if self.peek_punct(Punct::Star)
3773            && (self.peek_nth_punct(1, Punct::RParen) || self.peek_nth_punct(1, Punct::Comma))
3774        {
3775            self.pos += 1;
3776            return Ok(FunctionArg::Wildcard);
3777        }
3778        if (self.peek_keyword("TABLE") || self.peek_keyword("MODEL"))
3779            && self.peek_nth(1).is_some_and(|t| {
3780                Self::is_identifier_token(t) || matches!(t.kind, TokenKind::QuotedIdentifier(_))
3781            })
3782            && !self.peek_nth_punct(1, Punct::LParen)
3783        {
3784            let table = self.parse_keyword("TABLE");
3785            if !table {
3786                self.parse_keyword("MODEL");
3787            }
3788            let name = self.parse_object_name(true)?;
3789            return Ok(if table {
3790                FunctionArg::Table(name)
3791            } else {
3792                FunctionArg::Model(name)
3793            });
3794        }
3795        // `x -> body`
3796        if self.peek_identifier() && self.peek_nth_punct(1, Punct::Arrow) {
3797            let param = self.parse_identifier()?;
3798            self.pos += 1;
3799            let body = self.parse_expr()?;
3800            return Ok(FunctionArg::Expr(Expr::Lambda {
3801                params: vec![param],
3802                body: Box::new(body),
3803            }));
3804        }
3805        // `(a, b) -> body`
3806        if self.peek_punct(Punct::LParen) {
3807            if let Some(lambda) = self.attempt(|p| {
3808                let params = p.parse_parenthesized_identifiers()?;
3809                p.expect_punct(Punct::Arrow)?;
3810                let body = p.parse_expr()?;
3811                Ok(Expr::Lambda {
3812                    params,
3813                    body: Box::new(body),
3814                })
3815            }) {
3816                return Ok(FunctionArg::Expr(lambda));
3817            }
3818        }
3819        // `name => value`
3820        if self.peek_identifier() && self.peek_nth_punct(1, Punct::FatArrow) {
3821            let name = self.parse_identifier()?;
3822            self.pos += 1;
3823            let value = self.parse_expr()?;
3824            return Ok(FunctionArg::Expr(Expr::NamedArg {
3825                name,
3826                value: Box::new(value),
3827            }));
3828        }
3829        Ok(FunctionArg::Expr(self.parse_expr()?))
3830    }
3831
3832    fn parse_window_spec(&mut self) -> Result<WindowSpec> {
3833        self.expect_punct(Punct::LParen)?;
3834        let mut spec = WindowSpec::default();
3835        if self.peek_identifier()
3836            && !self.peek_keyword("PARTITION")
3837            && !self.peek_keyword("ORDER")
3838            && !self.peek_keyword("ROWS")
3839            && !self.peek_keyword("RANGE")
3840        {
3841            spec.base = Some(self.parse_identifier()?);
3842        }
3843        if self.parse_keywords(&["PARTITION", "BY"]) {
3844            spec.partition_by.push(self.parse_expr()?);
3845            while self.consume_punct(Punct::Comma) {
3846                spec.partition_by.push(self.parse_expr()?);
3847            }
3848        }
3849        if self.parse_keywords(&["ORDER", "BY"]) {
3850            spec.order_by = self.parse_order_by_list()?;
3851        }
3852        if self.peek_keyword("ROWS") || self.peek_keyword("RANGE") {
3853            let units = if self.parse_keyword("ROWS") {
3854                FrameUnits::Rows
3855            } else {
3856                self.parse_keyword("RANGE");
3857                FrameUnits::Range
3858            };
3859            let (start, end) = if self.parse_keyword("BETWEEN") {
3860                let start = self.parse_frame_bound()?;
3861                self.expect_keyword("AND")?;
3862                let end = self.parse_frame_bound()?;
3863                (start, Some(end))
3864            } else {
3865                (self.parse_frame_bound()?, None)
3866            };
3867            spec.frame = Some(WindowFrame { units, start, end });
3868        }
3869        self.expect_punct(Punct::RParen)?;
3870        Ok(spec)
3871    }
3872
3873    fn parse_frame_bound(&mut self) -> Result<FrameBound> {
3874        if self.parse_keywords(&["UNBOUNDED", "PRECEDING"]) {
3875            return Ok(FrameBound::UnboundedPreceding);
3876        }
3877        if self.parse_keywords(&["UNBOUNDED", "FOLLOWING"]) {
3878            return Ok(FrameBound::UnboundedFollowing);
3879        }
3880        if self.parse_keywords(&["CURRENT", "ROW"]) {
3881            return Ok(FrameBound::CurrentRow);
3882        }
3883        let expr = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
3884        if self.parse_keyword("PRECEDING") {
3885            Ok(FrameBound::Preceding(Box::new(expr)))
3886        } else {
3887            self.expect_keyword("FOLLOWING")?;
3888            Ok(FrameBound::Following(Box::new(expr)))
3889        }
3890    }
3891
3892    // ------------------------------------------------------------------ data types
3893
3894    /// Parse a data type at the current position.
3895    pub fn parse_data_type(&mut self) -> Result<DataType> {
3896        self.enter()?;
3897        let result = self.parse_data_type_inner();
3898        self.leave();
3899        result
3900    }
3901
3902    fn parse_data_type_inner(&mut self) -> Result<DataType> {
3903        let Some(token) = self.peek().cloned() else {
3904            return Err(self.error("expected a data type"));
3905        };
3906        let name = match &token.kind {
3907            TokenKind::Word => token.upper(),
3908            TokenKind::QuotedIdentifier(v) => {
3909                self.pos += 1;
3910                return Ok(DataType::Other(v.clone()));
3911            }
3912            _ => return Err(self.error("expected a data type")),
3913        };
3914        self.set_role(self.pos, TokenRole::Type);
3915        self.pos += 1;
3916        match name.as_str() {
3917            "ARRAY" => {
3918                self.expect_punct(Punct::Lt)?;
3919                let inner = self.parse_data_type()?;
3920                self.expect_gt()?;
3921                Ok(DataType::Array(Box::new(inner)))
3922            }
3923            "RANGE" => {
3924                self.expect_punct(Punct::Lt)?;
3925                let inner = self.parse_data_type()?;
3926                self.expect_gt()?;
3927                Ok(DataType::Range(Box::new(inner)))
3928            }
3929            "STRUCT" => {
3930                self.expect_punct(Punct::Lt)?;
3931                Ok(DataType::Struct(self.parse_struct_fields()?))
3932            }
3933            _ => {
3934                let base =
3935                    DataType::from_name(&name).unwrap_or_else(|| DataType::Other(name.clone()));
3936                match base {
3937                    DataType::Numeric(_) | DataType::BigNumeric(_)
3938                        if self.peek_punct(Punct::LParen) =>
3939                    {
3940                        self.pos += 1;
3941                        let precision = self.parse_u64()? as u32;
3942                        let scale = if self.consume_punct(Punct::Comma) {
3943                            Some(self.parse_u64()? as u32)
3944                        } else {
3945                            None
3946                        };
3947                        self.expect_punct(Punct::RParen)?;
3948                        Ok(if matches!(base, DataType::Numeric(_)) {
3949                            DataType::Numeric(Some((precision, scale)))
3950                        } else {
3951                            DataType::BigNumeric(Some((precision, scale)))
3952                        })
3953                    }
3954                    DataType::String(_) | DataType::Bytes(_) if self.peek_punct(Punct::LParen) => {
3955                        self.pos += 1;
3956                        let length = self.parse_u64()?;
3957                        self.expect_punct(Punct::RParen)?;
3958                        Ok(if matches!(base, DataType::String(_)) {
3959                            DataType::String(Some(length))
3960                        } else {
3961                            DataType::Bytes(Some(length))
3962                        })
3963                    }
3964                    other => Ok(other),
3965                }
3966            }
3967        }
3968    }
3969
3970    fn parse_u64(&mut self) -> Result<u64> {
3971        match self.peek() {
3972            Some(t) if t.kind == TokenKind::Integer => {
3973                let value = t
3974                    .text
3975                    .parse::<u64>()
3976                    .map_err(|_| self.error("expected a number"))?;
3977                self.pos += 1;
3978                Ok(value)
3979            }
3980            _ => Err(self.error("expected a number")),
3981        }
3982    }
3983
3984    /// Fields up to and including the closing `>` (the `<` already consumed).
3985    fn parse_struct_fields(&mut self) -> Result<Vec<StructField>> {
3986        let mut fields = Vec::new();
3987        if self.peek_punct(Punct::Gt) || self.peek_punct(Punct::ShiftRight) {
3988            self.expect_gt()?;
3989            return Ok(fields);
3990        }
3991        loop {
3992            let named = self.peek().is_some_and(|t| {
3993                matches!(t.kind, TokenKind::Word | TokenKind::QuotedIdentifier(_))
3994            }) && self.peek_nth(1).is_some_and(|t| {
3995                matches!(t.kind, TokenKind::Word | TokenKind::QuotedIdentifier(_))
3996            });
3997            let name = if named {
3998                Some(self.parse_path_part()?)
3999            } else {
4000                None
4001            };
4002            let data_type = self.parse_data_type()?;
4003            let not_null = self.parse_keywords(&["NOT", "NULL"]);
4004            let options = self.parse_optional_options()?;
4005            fields.push(StructField {
4006                name,
4007                data_type,
4008                not_null,
4009                options,
4010            });
4011            if !self.consume_punct(Punct::Comma) {
4012                break;
4013            }
4014        }
4015        self.expect_gt()?;
4016        Ok(fields)
4017    }
4018}
4019
4020fn describe(token: &Token) -> String {
4021    match &token.kind {
4022        TokenKind::Word => format!("'{}'", token.text),
4023        TokenKind::QuotedIdentifier(_) => "a quoted identifier".to_string(),
4024        TokenKind::String { .. } => "a string literal".to_string(),
4025        TokenKind::Bytes { .. } => "a bytes literal".to_string(),
4026        TokenKind::Integer | TokenKind::Float => "a number".to_string(),
4027        TokenKind::Parameter(_) | TokenKind::SystemVariable(_) => "a parameter".to_string(),
4028        TokenKind::Punct(p) => format!("'{}'", p.as_str()),
4029        TokenKind::Comment(_) => "a comment".to_string(),
4030        TokenKind::Whitespace => "whitespace".to_string(),
4031    }
4032}