Skip to main content

utopia_query/ast/
parser.rs

1//! [`Parser`]: tokens to a [`Select`].
2
3use crate::StringLiteral;
4use std::borrow::Cow;
5
6use php_std::Str;
7use php_std::format::{str_to_float, str_to_int};
8
9use super::node::{
10    Aliased, Between, Binary, CaseWhen, Cast, Column, Conditional, Cte, Exists, Expression, Func, In, InList,
11    JoinClause, Literal, OrderByItem, Placeholder, Select, Star, Subquery, SubquerySource, Table, TableSource, Unary,
12    Window, WindowDefinition, WindowSpecification,
13};
14use crate::enums::{NullsPosition, OrderDirection};
15use crate::error::{Error, Result};
16use crate::tokenizer::{Token, TokenType, Tokenizer};
17use crate::value::Value;
18
19/// How deep expressions may nest before parsing fails.
20const MAX_DEPTH: usize = 256;
21
22/// How many prefix operators (`NOT`, `-`, `+`) may chain. PHP has no limit
23/// short of its stack; this one keeps trees shallow enough to drop safely.
24const MAX_PREFIX: usize = 1024;
25
26/// Nesting levels parsed on one stack before parsing moves to a new thread.
27const STACK_LEVELS: usize = 32;
28
29/// The stack of each such thread.
30const STACK_SIZE: usize = 4 << 20;
31
32/// A recursive-descent parser of `SELECT` statements.
33///
34/// Reads filtered tokens (no whitespace or comments, ending with
35/// [`TokenType::Eof`], as [`Tokenizer::filter`] returns them) and builds a
36/// [`Select`] that a [`Walker`](super::Walker) can rewrite and a
37/// [`Serializer`](super::Serializer) write back. Not to be confused with the
38/// [`classifier`](crate::classifier), which only reads a statement's leading
39/// keyword.
40///
41/// PHP: `Utopia\Query\AST\Parser`.
42///
43/// ```
44/// use utopia_query::ast::{Expression, Parser};
45/// use utopia_query::tokenizer::Tokenizer;
46///
47/// let tokens = Tokenizer::filter(Tokenizer::new().tokenize("SELECT name FROM users WHERE age > 18")?);
48/// let select = Parser::new().parse(&tokens)?;
49/// assert!(matches!(select.where_clause, Some(Expression::Binary(ref b)) if b.operator == ">"));
50/// # Ok::<(), utopia_query::Error>(())
51/// ```
52///
53/// ```php
54/// use Utopia\Query\AST\Parser;
55/// use Utopia\Query\Tokenizer\Tokenizer;
56///
57/// $tokens = Tokenizer::filter((new Tokenizer())->tokenize('SELECT name FROM users WHERE age > 18'));
58/// $select = (new Parser())->parse($tokens);
59/// echo $select->where->operator, "\n"; // >
60/// ```
61#[derive(Debug, Clone, Copy, Default)]
62pub struct Parser {
63    literal: StringLiteral,
64    widened: bool,
65}
66
67impl Parser {
68    /// A parser.
69    ///
70    /// PHP: `new Parser()`.
71    pub const fn new() -> Self {
72        Parser { literal: StringLiteral::Backslash, widened: false }
73    }
74
75    /// The parser reading string literals by `literal`'s rules.
76    ///
77    /// PHP: `new Parser($literal)`.
78    #[must_use]
79    pub const fn with_literal(mut self, literal: StringLiteral) -> Self {
80        self.literal = literal;
81        self
82    }
83
84    /// The parser for tokens whose text holds a character for each byte, as the
85    /// PHP extension passes a string that is not UTF-8. What a literal's
86    /// escapes spell is then written the same way.
87    #[must_use]
88    pub const fn widened(mut self) -> Self {
89        self.widened = true;
90        self
91    }
92
93    /// The statement `tokens` spell: filtered tokens ending with
94    /// [`TokenType::Eof`]. Fails with [`Error::Query`] on a syntax error
95    /// (naming the token and its position) and [`Error::Validation`] when
96    /// expressions nest more than 256 deep.
97    ///
98    /// PHP: `Parser::parse()`.
99    pub fn parse(&self, tokens: &[Token<'_>]) -> Result<Select> {
100        let mut state = State { tokens, pos: 0, depth: 0, in_column_list: false, parser: *self };
101        let select = state.select()?;
102        state.match_and_consume(TokenType::Semicolon);
103        let t = state.current();
104        if t.kind != TokenType::Eof {
105            return Err(Error::Validation(format!(
106                "Unexpected token '{}' ({}) at position {}",
107                text(&t.value),
108                t.kind.name(),
109                t.position
110            )));
111        }
112        Ok(select)
113    }
114
115    /// The statement `sql` spells, tokenized with the standard
116    /// [`Tokenizer`] (as builders read their CTE queries).
117    ///
118    /// PHP: `$parser->parse(Tokenizer::filter((new Tokenizer())->tokenize($sql)))`.
119    pub fn parse_sql<S: AsRef<[u8]> + ?Sized>(&self, sql: &S) -> Result<Select> {
120        let tokens = Tokenizer::filter(Tokenizer::new().with_literal(self.literal).tokenize(sql)?);
121        self.parse(&tokens)
122    }
123}
124
125static EOF: Token<'static> = Token { kind: TokenType::Eof, value: Cow::Borrowed(b""), position: 0 };
126
127struct State<'t, 'a> {
128    tokens: &'t [Token<'a>],
129    pos: usize,
130    depth: usize,
131    in_column_list: bool,
132    parser: Parser,
133}
134
135fn error(message: String) -> Error {
136    Error::query(message)
137}
138
139/// An error quoting a token's value: `before`, the value's bytes, `after`
140/// (the message is not UTF-8 when the value is part of a character).
141fn quoting(before: String, value: &[u8], after: &str) -> Error {
142    let mut message = before.into_bytes();
143    message.extend_from_slice(value);
144    message.extend_from_slice(after.as_bytes());
145    Error::query_bytes(message)
146}
147
148fn eq_upper(value: &[u8], upper: &str) -> bool {
149    value.eq_ignore_ascii_case(upper.as_bytes())
150}
151
152/// `substr($raw, 1, -1)`.
153fn inner(raw: &[u8]) -> &[u8] {
154    raw.get(1..raw.len().saturating_sub(1).max(1)).unwrap_or(b"")
155}
156
157/// `str_replace($from, $to, $subject)` on bytes.
158fn replace(subject: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
159    let mut out = Vec::with_capacity(subject.len());
160    let mut i = 0;
161    while i < subject.len() {
162        if subject[i..].starts_with(from) {
163            out.extend_from_slice(to);
164            i += from.len();
165        } else {
166            out.push(subject[i]);
167            i += 1;
168        }
169    }
170    out
171}
172
173fn text(bytes: &[u8]) -> String {
174    String::from_utf8_lossy(bytes).into_owned()
175}
176
177fn unquote(raw: &[u8]) -> String {
178    let inner = inner(raw);
179    text(&match raw.first() {
180        Some(b'`') => replace(inner, b"``", b"`"),
181        Some(b'"') => replace(inner, b"\"\"", b"\""),
182        Some(b'[') => replace(inner, b"]]", b"]"),
183        _ => inner.to_vec(),
184    })
185}
186
187impl<'t, 'a> State<'t, 'a> {
188    fn current(&self) -> &'t Token<'a> {
189        match self.tokens.get(self.pos) {
190            Some(t) => t,
191            None => &EOF,
192        }
193    }
194
195    fn peek(&self, offset: usize) -> &'t Token<'a> {
196        match self.tokens.get(self.pos + offset).or_else(|| self.tokens.last()) {
197            Some(t) => t,
198            None => &EOF,
199        }
200    }
201
202    fn advance(&mut self) {
203        if self.pos + 1 < self.tokens.len() {
204            self.pos += 1;
205        }
206    }
207
208    fn is(&self, kind: TokenType) -> bool {
209        self.current().kind == kind
210    }
211
212    fn match_keyword(&self, keyword: &str) -> bool {
213        let t = self.current();
214        t.kind == TokenType::Keyword && eq_upper(&t.value, keyword)
215    }
216
217    fn peek_keyword(&self, offset: usize, keyword: &str) -> bool {
218        let t = self.peek(offset);
219        t.kind == TokenType::Keyword && eq_upper(&t.value, keyword)
220    }
221
222    fn consume_keyword(&mut self, keyword: &str) -> Result<()> {
223        if !self.match_keyword(keyword) {
224            let t = self.current();
225            return Err(quoting(
226                format!("Expected keyword '{keyword}' at position {}, got '", t.position),
227                &t.value,
228                "'",
229            ));
230        }
231        self.advance();
232        Ok(())
233    }
234
235    fn expect(&mut self, kind: TokenType) -> Result<()> {
236        let t = self.current();
237        if t.kind != kind {
238            return Err(quoting(format!("Expected {} at position {}, got '", kind.name(), t.position), &t.value, "'"));
239        }
240        self.advance();
241        Ok(())
242    }
243
244    fn match_and_consume(&mut self, kind: TokenType) -> bool {
245        if self.is(kind) {
246            self.advance();
247            true
248        } else {
249            false
250        }
251    }
252
253    fn expect_null(&mut self) -> Result<()> {
254        let t = self.current();
255        if t.kind != TokenType::Null {
256            return Err(quoting(format!("Expected NULL at position {}, got '", t.position), &t.value, "'"));
257        }
258        self.advance();
259        Ok(())
260    }
261
262    fn expect_identifier_value(&mut self, value: &str) -> Result<()> {
263        let t = self.current();
264        if matches!(t.kind, TokenType::Identifier | TokenType::Keyword) && eq_upper(&t.value, value) {
265            self.advance();
266            return Ok(());
267        }
268        Err(quoting(format!("Expected '{value}' at position {}, got '", t.position), &t.value, "'"))
269    }
270
271    fn extract_identifier(&self, t: &Token<'_>) -> Result<String> {
272        match t.kind {
273            TokenType::Identifier | TokenType::Keyword => Ok(text(&t.value)),
274            TokenType::QuotedIdentifier => Ok(unquote(&t.value)),
275            _ => Err(quoting(
276                format!("Expected identifier at position {}, got '", t.position),
277                &t.value,
278                &format!("' ({})", t.kind.name()),
279            )),
280        }
281    }
282
283    fn expect_identifier(&mut self) -> Result<String> {
284        let name = self.extract_identifier(self.current())?;
285        self.advance();
286        Ok(name)
287    }
288
289    fn select(&mut self) -> Result<Select> {
290        let mut ctes = Vec::new();
291        if self.match_keyword("WITH") {
292            self.advance();
293            let mut recursive = false;
294            if self.match_keyword("RECURSIVE") {
295                recursive = true;
296                self.advance();
297            }
298            loop {
299                ctes.push(self.cte(recursive)?);
300                if !self.match_and_consume(TokenType::Comma) {
301                    break;
302                }
303            }
304        }
305
306        self.consume_keyword("SELECT")?;
307
308        let mut distinct = false;
309        if self.match_keyword("DISTINCT") {
310            distinct = true;
311            self.advance();
312        }
313
314        let columns = self.column_list()?;
315        let mut select = Select { columns, distinct, ctes, ..Select::default() };
316
317        if self.match_keyword("FROM") {
318            self.advance();
319            select.from = Some(self.table_source()?);
320            select.joins = self.joins()?;
321        }
322        if self.match_keyword("WHERE") {
323            self.advance();
324            select.where_clause = Some(self.expression()?);
325        }
326        if self.match_keyword("GROUP") {
327            self.advance();
328            self.consume_keyword("BY")?;
329            select.group_by = self.expression_list()?;
330        }
331        if self.match_keyword("HAVING") {
332            self.advance();
333            select.having = Some(self.expression()?);
334        }
335        if self.match_keyword("WINDOW") {
336            self.advance();
337            select.windows = self.window_definitions()?;
338        }
339        if self.match_keyword("ORDER") {
340            self.advance();
341            self.consume_keyword("BY")?;
342            select.order_by = self.order_by_list()?;
343        }
344        if self.match_keyword("LIMIT") {
345            self.advance();
346            select.limit = Some(self.expression()?);
347        }
348        if self.match_keyword("OFFSET") {
349            self.advance();
350            select.offset = Some(self.expression()?);
351        }
352        if self.match_keyword("FETCH") {
353            self.advance();
354            if !(self.match_keyword("FIRST") || self.match_keyword("NEXT")) {
355                return Err(error(format!(
356                    "Expected FIRST or NEXT after FETCH at position {}",
357                    self.current().position
358                )));
359            }
360            self.advance();
361            select.limit = Some(self.expression()?);
362            if !(self.match_keyword("ROW") || self.match_keyword("ROWS")) {
363                return Err(error(format!("Expected ROW or ROWS at position {}", self.current().position)));
364            }
365            self.advance();
366            self.expect_identifier_value("ONLY")?;
367        }
368
369        Ok(select)
370    }
371
372    fn cte(&mut self, recursive: bool) -> Result<Cte> {
373        let name = self.expect_identifier()?;
374        let mut columns = Vec::new();
375
376        if self.is(TokenType::LeftParen) && self.peek_is_column_list() {
377            self.expect(TokenType::LeftParen)?;
378            columns.push(self.expect_identifier()?);
379            while self.match_and_consume(TokenType::Comma) {
380                columns.push(self.expect_identifier()?);
381            }
382            self.expect(TokenType::RightParen)?;
383        }
384
385        self.consume_keyword("AS")?;
386        self.expect(TokenType::LeftParen)?;
387        let query = self.select()?;
388        self.expect(TokenType::RightParen)?;
389
390        Ok(Cte { name, query, columns, recursive })
391    }
392
393    fn peek_is_column_list(&self) -> bool {
394        let mut depth = 0i64;
395        for (i, t) in self.tokens.iter().enumerate().skip(self.pos) {
396            match t.kind {
397                TokenType::LeftParen => depth += 1,
398                TokenType::RightParen => {
399                    depth -= 1;
400                    if depth == 0 {
401                        return self
402                            .tokens
403                            .get(i + 1)
404                            .is_some_and(|n| n.kind == TokenType::Keyword && eq_upper(&n.value, "AS"));
405                    }
406                }
407                _ => {}
408            }
409        }
410        false
411    }
412
413    fn column_list(&mut self) -> Result<Vec<Expression>> {
414        self.in_column_list = true;
415        let mut columns = vec![self.select_column()?];
416        while self.match_and_consume(TokenType::Comma) {
417            columns.push(self.select_column()?);
418        }
419        self.in_column_list = false;
420        Ok(columns)
421    }
422
423    fn select_column(&mut self) -> Result<Expression> {
424        let expression = self.expression()?;
425
426        if self.match_keyword("AS") {
427            self.advance();
428            let alias = self.expect_identifier()?;
429            return Ok(Aliased::new(expression, alias).into());
430        }
431
432        if self.in_column_list && matches!(self.current().kind, TokenType::Identifier | TokenType::QuotedIdentifier) {
433            let alias = self.expect_identifier()?;
434            return Ok(Aliased::new(expression, alias).into());
435        }
436
437        Ok(expression)
438    }
439
440    fn expression(&mut self) -> Result<Expression> {
441        if self.depth >= MAX_DEPTH {
442            return Err(Error::Validation("Expression nesting too deep".into()));
443        }
444        self.depth += 1;
445        let result = if self.depth.is_multiple_of(STACK_LEVELS) { self.or_on_new_stack() } else { self.or() };
446        self.depth -= 1;
447        result
448    }
449
450    /// [`State::or`] on a thread of its own: every [`STACK_LEVELS`] nesting
451    /// levels, parsing continues on a fresh stack, so the deepest nesting
452    /// allowed fits in any caller's stack (debug builds use kilobytes per
453    /// level).
454    #[cold]
455    fn or_on_new_stack(&mut self) -> Result<Expression> {
456        std::thread::scope(|scope| {
457            match std::thread::Builder::new().stack_size(STACK_SIZE).spawn_scoped(scope, || self.or()) {
458                Ok(handle) => handle.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
459                Err(_) => Err(Error::Validation("Expression nesting too deep".into())),
460            }
461        })
462    }
463
464    fn or(&mut self) -> Result<Expression> {
465        let mut left = self.and()?;
466        while self.match_keyword("OR") {
467            self.advance();
468            let right = self.and()?;
469            left = Binary::new(left, "OR", right).into();
470        }
471        Ok(left)
472    }
473
474    fn and(&mut self) -> Result<Expression> {
475        let mut left = self.not()?;
476        while self.match_keyword("AND") {
477            self.advance();
478            let right = self.not()?;
479            left = Binary::new(left, "AND", right).into();
480        }
481        Ok(left)
482    }
483
484    /// `NOT` chains, read in a loop (PHP recurses; the result is the same).
485    fn not(&mut self) -> Result<Expression> {
486        let mut nots = 0usize;
487        let mut operand = loop {
488            if !self.match_keyword("NOT") {
489                let left = self.addition()?;
490                break self.postfix(left)?;
491            }
492            if self.peek_keyword(1, "EXISTS") {
493                break self.not_exists()?;
494            }
495            self.advance();
496            nots += 1;
497            if nots > MAX_PREFIX {
498                return Err(Error::Validation("Expression nesting too deep".into()));
499            }
500        };
501        for _ in 0..nots {
502            operand = Unary::new("NOT", operand, true).into();
503        }
504        Ok(operand)
505    }
506
507    fn not_exists(&mut self) -> Result<Expression> {
508        self.advance();
509        self.advance();
510        self.expect(TokenType::LeftParen)?;
511        let subquery = self.select()?;
512        self.expect(TokenType::RightParen)?;
513        Ok(Exists::new(subquery, true).into())
514    }
515
516    fn postfix(&mut self, left: Expression) -> Result<Expression> {
517        if self.match_keyword("IS") {
518            self.advance();
519            if self.match_keyword("NOT") {
520                self.advance();
521                self.expect_null()?;
522                return Ok(Unary::new("IS NOT NULL", left, false).into());
523            }
524            self.expect_null()?;
525            return Ok(Unary::new("IS NULL", left, false).into());
526        }
527
528        if self.match_keyword("NOT") {
529            if self.peek_keyword(1, "IN") {
530                self.advance();
531                self.advance();
532                return self.in_list(left, true);
533            }
534            if self.peek_keyword(1, "BETWEEN") {
535                self.advance();
536                self.advance();
537                return self.between(left, true);
538            }
539            for (keyword, operator) in [("LIKE", "NOT LIKE"), ("ILIKE", "NOT ILIKE")] {
540                if self.peek_keyword(1, keyword) {
541                    self.advance();
542                    self.advance();
543                    return self.like(left, operator);
544                }
545            }
546        }
547
548        if self.match_keyword("IN") {
549            self.advance();
550            return self.in_list(left, false);
551        }
552        if self.match_keyword("BETWEEN") {
553            self.advance();
554            return self.between(left, false);
555        }
556        for keyword in ["LIKE", "ILIKE"] {
557            if self.match_keyword(keyword) {
558                self.advance();
559                return self.like(left, keyword);
560            }
561        }
562
563        let t = self.current();
564        if t.kind == TokenType::Operator && matches!(&*t.value, b"=" | b"!=" | b"<>" | b"<" | b">" | b"<=" | b">=") {
565            let operator = text(&t.value);
566            self.advance();
567            let right = self.addition()?;
568            return self.postfix(Binary::new(left, operator, right).into());
569        }
570
571        Ok(left)
572    }
573
574    fn in_list(&mut self, left: Expression, negated: bool) -> Result<Expression> {
575        self.expect(TokenType::LeftParen)?;
576
577        if self.match_keyword("SELECT") || self.match_keyword("WITH") {
578            let subquery = self.select()?;
579            self.expect(TokenType::RightParen)?;
580            return Ok(In::new(left, InList::Subquery(Box::new(subquery)), negated).into());
581        }
582
583        let mut list = vec![self.expression()?];
584        while self.match_and_consume(TokenType::Comma) {
585            list.push(self.expression()?);
586        }
587        self.expect(TokenType::RightParen)?;
588
589        Ok(In::new(left, InList::Values(list), negated).into())
590    }
591
592    fn between(&mut self, left: Expression, negated: bool) -> Result<Expression> {
593        let low = self.addition()?;
594        self.consume_keyword("AND")?;
595        let high = self.addition()?;
596        Ok(Between::new(left, low, high, negated).into())
597    }
598
599    fn addition(&mut self) -> Result<Expression> {
600        let mut left = self.multiplication()?;
601        loop {
602            let t = self.current();
603            if t.kind == TokenType::Operator && matches!(&*t.value, b"+" | b"-" | b"||") {
604                let operator = text(&t.value);
605                self.advance();
606                let right = self.multiplication()?;
607                left = Binary::new(left, operator, right).into();
608            } else {
609                return Ok(left);
610            }
611        }
612    }
613
614    fn multiplication(&mut self) -> Result<Expression> {
615        let mut left = self.unary()?;
616        loop {
617            let t = self.current();
618            let operator = match t.kind {
619                TokenType::Star => "*",
620                TokenType::Operator if *t.value == *b"/" => "/",
621                TokenType::Operator if *t.value == *b"%" => "%",
622                _ => return Ok(left),
623            };
624            self.advance();
625            let right = self.unary()?;
626            left = Binary::new(left, operator, right).into();
627        }
628    }
629
630    /// Prefix `-` / `+` chains, read in a loop (PHP recurses; the result is the same).
631    fn unary(&mut self) -> Result<Expression> {
632        let mut operators = Vec::new();
633        loop {
634            let t = self.current();
635            if t.kind == TokenType::Operator && (*t.value == *b"-" || *t.value == *b"+") {
636                operators.push(if *t.value == *b"-" { "-" } else { "+" });
637                if operators.len() > MAX_PREFIX {
638                    return Err(Error::Validation("Expression nesting too deep".into()));
639                }
640                self.advance();
641            } else {
642                break;
643            }
644        }
645
646        let mut expression = self.primary()?;
647        while self.current().kind == TokenType::Operator && *self.current().value == *b"::" {
648            self.advance();
649            let data_type = self.expect_identifier()?;
650            expression = Cast::new(expression, data_type)?.into();
651        }
652        for operator in operators.into_iter().rev() {
653            expression = Unary::new(operator, expression, true).into();
654        }
655        Ok(expression)
656    }
657
658    // `primary`, `expression` and the precedence levels between them recurse
659    // once per nesting level: they keep small frames, and the rest of a
660    // primary expression is read by `atom`.
661    fn primary(&mut self) -> Result<Expression> {
662        if !self.is(TokenType::LeftParen) {
663            return self.atom();
664        }
665        self.advance();
666        if self.match_keyword("SELECT") || self.match_keyword("WITH") {
667            return self.scalar_subquery();
668        }
669        let expression = self.expression()?;
670        self.expect(TokenType::RightParen)?;
671        Ok(expression)
672    }
673
674    fn scalar_subquery(&mut self) -> Result<Expression> {
675        let subquery = self.select()?;
676        self.expect(TokenType::RightParen)?;
677        Ok(Subquery::new(subquery).into())
678    }
679
680    fn atom(&mut self) -> Result<Expression> {
681        let t = self.current();
682        match t.kind {
683            TokenType::Integer => {
684                self.advance();
685                return Ok(Literal { value: Value::Int(str_to_int(&t.value)) }.into());
686            }
687            TokenType::Float => {
688                self.advance();
689                return Ok(Literal { value: Value::Float(str_to_float(&t.value)) }.into());
690            }
691            TokenType::String => {
692                self.advance();
693                let rules = self.parser.literal;
694                let value = if self.parser.widened {
695                    crate::literal::widen(&rules.unquote(&crate::literal::narrow(&t.value))?)
696                } else {
697                    rules.unquote(&t.value)?
698                };
699                return Ok(Literal { value: Value::Str(Str::from(value)) }.into());
700            }
701            TokenType::Boolean => {
702                self.advance();
703                return Ok(Literal { value: Value::Bool(eq_upper(&t.value, "TRUE")) }.into());
704            }
705            TokenType::Null => {
706                self.advance();
707                return Ok(Literal { value: Value::Null }.into());
708            }
709            TokenType::Placeholder | TokenType::NamedPlaceholder | TokenType::NumberedPlaceholder => {
710                self.advance();
711                return Ok(Placeholder::new(text(&t.value)).into());
712            }
713            TokenType::Star => {
714                self.advance();
715                return Ok(Star::default().into());
716            }
717            _ => {}
718        }
719
720        if self.match_keyword("CASE") {
721            return self.case();
722        }
723        if self.match_keyword("CAST") {
724            return self.cast();
725        }
726        if self.match_keyword("EXISTS") {
727            self.advance();
728            self.expect(TokenType::LeftParen)?;
729            let subquery = self.select()?;
730            self.expect(TokenType::RightParen)?;
731            return Ok(Exists::new(subquery, false).into());
732        }
733        if matches!(t.kind, TokenType::Identifier | TokenType::QuotedIdentifier)
734            || (t.kind == TokenType::Keyword && self.peek(1).kind == TokenType::LeftParen)
735        {
736            return self.identifier_expression();
737        }
738
739        Err(quoting(
740            "Unexpected token '".into(),
741            &t.value,
742            &format!("' ({}) at position {}", t.kind.name(), t.position),
743        ))
744    }
745
746    /// The pattern of a `LIKE`, and what `ESCAPE` names after it.
747    fn like(&mut self, left: Expression, operator: &str) -> Result<Expression> {
748        let like = Binary::new(left, operator, self.addition()?);
749        let t = self.current();
750        let escape = matches!(t.kind, TokenType::Identifier | TokenType::Keyword) && eq_upper(&t.value, "ESCAPE");
751        if !escape {
752            return Ok(like.into());
753        }
754        self.advance();
755        Ok(like.with_escape(self.addition()?).into())
756    }
757
758    fn identifier_expression(&mut self) -> Result<Expression> {
759        let name = self.extract_identifier(self.current())?;
760        self.advance();
761
762        match self.current().kind {
763            TokenType::LeftParen => self.function_call(name),
764            TokenType::Dot => {
765                self.advance();
766                if self.is(TokenType::Star) {
767                    self.advance();
768                    return Ok(Star { table: Some(name), schema: None }.into());
769                }
770                let second = self.extract_identifier(self.current())?;
771                self.advance();
772                if self.is(TokenType::Dot) {
773                    self.advance();
774                    if self.is(TokenType::Star) {
775                        self.advance();
776                        return Ok(Star { table: Some(second), schema: Some(name) }.into());
777                    }
778                    let third = self.extract_identifier(self.current())?;
779                    self.advance();
780                    return Ok(Column { name: third, table: Some(second), schema: Some(name) }.into());
781                }
782                Ok(Column { name: second, table: Some(name), schema: None }.into())
783            }
784            _ => Ok(Column::new(name).into()),
785        }
786    }
787
788    fn function_call(&mut self, name: String) -> Result<Expression> {
789        let name = name.to_ascii_uppercase();
790        self.expect(TokenType::LeftParen)?;
791
792        if self.is(TokenType::Star) {
793            self.advance();
794            self.expect(TokenType::RightParen)?;
795            return self.function_postfix(Func::new(name, vec![Star::default().into()], false, None)?);
796        }
797        if self.is(TokenType::RightParen) {
798            self.advance();
799            return self.function_postfix(Func::new(name, Vec::new(), false, None)?);
800        }
801
802        let mut distinct = false;
803        if self.match_keyword("DISTINCT") {
804            distinct = true;
805            self.advance();
806        }
807
808        let mut arguments = vec![self.expression()?];
809        while self.match_and_consume(TokenType::Comma) {
810            arguments.push(self.expression()?);
811        }
812        self.expect(TokenType::RightParen)?;
813
814        self.function_postfix(Func::new(name, arguments, distinct, None)?)
815    }
816
817    fn function_postfix(&mut self, mut function: Func) -> Result<Expression> {
818        if self.match_keyword("FILTER") {
819            self.advance();
820            self.expect(TokenType::LeftParen)?;
821            self.consume_keyword("WHERE")?;
822            function.filter = Some(Box::new(self.expression()?));
823            self.expect(TokenType::RightParen)?;
824        }
825
826        if self.match_keyword("OVER") {
827            self.advance();
828            if self.is(TokenType::Identifier) {
829                let window_name = self.extract_identifier(self.current())?;
830                self.advance();
831                return Ok(Window {
832                    function: Box::new(function.into()),
833                    window_name: Some(window_name),
834                    specification: None,
835                }
836                .into());
837            }
838            self.expect(TokenType::LeftParen)?;
839            let specification = self.window_specification()?;
840            self.expect(TokenType::RightParen)?;
841            return Ok(Window {
842                function: Box::new(function.into()),
843                window_name: None,
844                specification: Some(Box::new(specification)),
845            }
846            .into());
847        }
848
849        Ok(function.into())
850    }
851
852    fn case(&mut self) -> Result<Expression> {
853        self.consume_keyword("CASE")?;
854
855        let mut operand = None;
856        if !self.match_keyword("WHEN") {
857            operand = Some(Box::new(self.expression()?));
858        }
859
860        let mut whens = Vec::new();
861        while self.match_keyword("WHEN") {
862            self.advance();
863            let condition = self.expression()?;
864            self.consume_keyword("THEN")?;
865            let result = self.expression()?;
866            whens.push(CaseWhen::new(condition, result));
867        }
868
869        let mut else_result = None;
870        if self.match_keyword("ELSE") {
871            self.advance();
872            else_result = Some(Box::new(self.expression()?));
873        }
874
875        self.consume_keyword("END")?;
876
877        Ok(Conditional { operand, whens, else_result }.into())
878    }
879
880    fn cast(&mut self) -> Result<Expression> {
881        self.consume_keyword("CAST")?;
882        self.expect(TokenType::LeftParen)?;
883        let expression = self.expression()?;
884        self.consume_keyword("AS")?;
885        let data_type = self.expect_identifier()?;
886        self.expect(TokenType::RightParen)?;
887        Ok(Cast::new(expression, data_type)?.into())
888    }
889
890    fn table_source(&mut self) -> Result<TableSource> {
891        if self.is(TokenType::LeftParen) {
892            self.advance();
893            let subquery = self.select()?;
894            self.expect(TokenType::RightParen)?;
895            if self.match_keyword("AS") {
896                self.advance();
897            }
898            let alias = self.expect_identifier()?;
899            return Ok(SubquerySource::new(subquery, alias).into());
900        }
901        Ok(self.table_reference()?.into())
902    }
903
904    fn table_reference(&mut self) -> Result<Table> {
905        let mut name = self.expect_identifier()?;
906        let mut schema = None;
907        let mut alias = None;
908
909        if self.is(TokenType::Dot) {
910            self.advance();
911            schema = Some(name);
912            name = self.expect_identifier()?;
913        }
914
915        if self.match_keyword("AS") {
916            self.advance();
917            alias = Some(self.expect_identifier()?);
918        } else if matches!(self.current().kind, TokenType::Identifier | TokenType::QuotedIdentifier) {
919            alias = Some(self.expect_identifier()?);
920        }
921
922        Ok(Table { name, alias, schema })
923    }
924
925    fn joins(&mut self) -> Result<Vec<JoinClause>> {
926        let mut joins = Vec::new();
927        while let Some(kind) = self.join_type()? {
928            let table = self.table_source()?;
929            let mut condition = None;
930            if kind != "CROSS JOIN" && kind != "NATURAL JOIN" && self.match_keyword("ON") {
931                self.advance();
932                condition = Some(self.expression()?);
933            }
934            joins.push(JoinClause { kind: kind.to_owned(), table, condition });
935        }
936        Ok(joins)
937    }
938
939    fn join_type(&mut self) -> Result<Option<&'static str>> {
940        if self.match_keyword("JOIN") {
941            self.advance();
942            return Ok(Some("JOIN"));
943        }
944        let (kind, outer) = if self.match_keyword("INNER") {
945            ("INNER JOIN", false)
946        } else if self.match_keyword("LEFT") {
947            ("LEFT JOIN", true)
948        } else if self.match_keyword("RIGHT") {
949            ("RIGHT JOIN", true)
950        } else if self.match_keyword("FULL") {
951            ("FULL OUTER JOIN", true)
952        } else if self.match_keyword("CROSS") {
953            ("CROSS JOIN", false)
954        } else if self.match_keyword("NATURAL") {
955            ("NATURAL JOIN", false)
956        } else {
957            return Ok(None);
958        };
959        self.advance();
960        if outer && self.match_keyword("OUTER") {
961            self.advance();
962        }
963        self.consume_keyword("JOIN")?;
964        Ok(Some(kind))
965    }
966
967    fn expression_list(&mut self) -> Result<Vec<Expression>> {
968        let mut expressions = vec![self.expression()?];
969        while self.match_and_consume(TokenType::Comma) {
970            expressions.push(self.expression()?);
971        }
972        Ok(expressions)
973    }
974
975    fn order_by_list(&mut self) -> Result<Vec<OrderByItem>> {
976        let mut items = vec![self.order_by_item()?];
977        while self.match_and_consume(TokenType::Comma) {
978            items.push(self.order_by_item()?);
979        }
980        Ok(items)
981    }
982
983    fn order_by_item(&mut self) -> Result<OrderByItem> {
984        let expression = self.expression()?;
985
986        let mut direction = OrderDirection::Asc;
987        if self.match_keyword("ASC") {
988            self.advance();
989        } else if self.match_keyword("DESC") {
990            self.advance();
991            direction = OrderDirection::Desc;
992        }
993
994        let mut nulls = None;
995        if self.match_keyword("NULLS") {
996            self.advance();
997            if self.match_keyword("FIRST") {
998                self.advance();
999                nulls = Some(NullsPosition::First);
1000            } else if self.match_keyword("LAST") {
1001                self.advance();
1002                nulls = Some(NullsPosition::Last);
1003            } else {
1004                let t = self.current();
1005                return Err(quoting(
1006                    format!("Expected FIRST or LAST after NULLS at position {}, got '", t.position),
1007                    &t.value,
1008                    "'",
1009                ));
1010            }
1011        }
1012
1013        Ok(OrderByItem { expression, direction, nulls })
1014    }
1015
1016    fn window_definitions(&mut self) -> Result<Vec<WindowDefinition>> {
1017        let mut definitions = Vec::new();
1018        loop {
1019            let name = self.expect_identifier()?;
1020            self.consume_keyword("AS")?;
1021            self.expect(TokenType::LeftParen)?;
1022            let specification = self.window_specification()?;
1023            self.expect(TokenType::RightParen)?;
1024            definitions.push(WindowDefinition { name, specification });
1025            if !self.match_and_consume(TokenType::Comma) {
1026                return Ok(definitions);
1027            }
1028        }
1029    }
1030
1031    fn window_specification(&mut self) -> Result<WindowSpecification> {
1032        let mut specification = WindowSpecification::default();
1033
1034        if self.match_keyword("PARTITION") {
1035            self.advance();
1036            self.consume_keyword("BY")?;
1037            specification.partition_by = self.expression_list()?;
1038        }
1039        if self.match_keyword("ORDER") {
1040            self.advance();
1041            self.consume_keyword("BY")?;
1042            specification.order_by = self.order_by_list()?;
1043        }
1044        if self.match_keyword("ROWS") || self.match_keyword("RANGE") {
1045            specification.frame_type = Some(text(&self.current().value.to_ascii_uppercase()));
1046            self.advance();
1047            if self.match_keyword("BETWEEN") {
1048                self.advance();
1049                specification.frame_start = Some(self.frame_bound()?);
1050                self.consume_keyword("AND")?;
1051                specification.frame_end = Some(self.frame_bound()?);
1052            } else {
1053                specification.frame_start = Some(self.frame_bound()?);
1054            }
1055        }
1056
1057        Ok(specification)
1058    }
1059
1060    fn frame_bound(&mut self) -> Result<String> {
1061        if self.match_keyword("UNBOUNDED") {
1062            self.advance();
1063            if self.match_keyword("PRECEDING") {
1064                self.advance();
1065                return Ok("UNBOUNDED PRECEDING".into());
1066            }
1067            if self.match_keyword("FOLLOWING") {
1068                self.advance();
1069                return Ok("UNBOUNDED FOLLOWING".into());
1070            }
1071            return Err(error(format!(
1072                "Expected PRECEDING or FOLLOWING after UNBOUNDED at position {}",
1073                self.current().position
1074            )));
1075        }
1076
1077        if self.match_keyword("CURRENT") {
1078            self.advance();
1079            self.consume_keyword("ROW")?;
1080            return Ok("CURRENT ROW".into());
1081        }
1082
1083        if self.is(TokenType::Integer) {
1084            let n = text(&self.current().value);
1085            self.advance();
1086            for keyword in ["PRECEDING", "FOLLOWING"] {
1087                if self.match_keyword(keyword) {
1088                    self.advance();
1089                    return Ok(format!("{n} {keyword}"));
1090                }
1091            }
1092            return Err(error(format!(
1093                "Expected PRECEDING or FOLLOWING after number at position {}",
1094                self.current().position
1095            )));
1096        }
1097
1098        let t = self.current();
1099        Err(quoting("Unexpected frame bound token '".into(), &t.value, &format!("' at position {}", t.position)))
1100    }
1101}
1102
1103#[cfg(test)]
1104mod tests {
1105    use super::Parser;
1106
1107    /// Parses `depth` nested parentheses on a thread with a small stack.
1108    fn nested(depth: usize) -> Result<(), String> {
1109        let sql = format!("SELECT {}1{} FROM t", "(".repeat(depth), ")".repeat(depth));
1110        std::thread::Builder::new()
1111            .stack_size(1 << 20)
1112            .spawn(move || Parser::new().parse_sql(&sql).map(drop).map_err(|e| e.to_string()))
1113            .expect("thread")
1114            .join()
1115            .expect("no stack overflow")
1116    }
1117
1118    #[test]
1119    fn nesting_up_to_the_limit_fits_in_a_small_stack() {
1120        assert!(nested(255).is_ok());
1121        assert_eq!(nested(500), Err("Expression nesting too deep".to_owned()));
1122    }
1123}