Skip to main content

utopia_query/tokenizer/
mod.rs

1//! SQL tokenizers: SQL text to [`Token`]s, per dialect.
2//!
3//! A [`Tokenizer`] splits SQL into keywords, identifiers, literals,
4//! operators, punctuation, placeholders, comments and whitespace, each with
5//! its byte position. [`Tokenizer::filter`] drops whitespace and comments,
6//! which is what the [`Parser`](crate::ast::Parser) reads. Token values
7//! borrow the SQL text where they can, so tokenizing allocates only the
8//! token list.
9//!
10//! PHP: `Utopia\Query\Tokenizer\*`.
11//!
12//! | PHP | Rust |
13//! |---|---|
14//! | `Tokenizer\Tokenizer` | [`Tokenizer::new`] |
15//! | `Tokenizer\MySQL` | [`Tokenizer::mysql`] |
16//! | `Tokenizer\MariaDB` | [`Tokenizer::mariadb`] |
17//! | `Tokenizer\PostgreSQL` | [`Tokenizer::postgresql`] |
18//! | `Tokenizer\SQLite` | [`Tokenizer::sqlite`] |
19//! | `Tokenizer\ClickHouse` | [`Tokenizer::clickhouse`] |
20//! | `Tokenizer::tokenize()` | [`Tokenizer::tokenize`] |
21//! | `Tokenizer::filter()` | [`Tokenizer::filter`] |
22//! | `Tokenizer\Token` | [`Token`] |
23//! | `Tokenizer\TokenType` | [`TokenType`] |
24//!
25//! ```
26//! use utopia_query::tokenizer::{TokenType, Tokenizer};
27//!
28//! let tokens = Tokenizer::filter(Tokenizer::new().tokenize("SELECT * FROM users")?);
29//! let kinds: Vec<TokenType> = tokens.iter().map(|t| t.kind).collect();
30//! assert_eq!(kinds, [TokenType::Keyword, TokenType::Star, TokenType::Keyword, TokenType::Identifier, TokenType::Eof]);
31//! assert_eq!(tokens[3].text(), "users");
32//! # Ok::<(), utopia_query::Error>(())
33//! ```
34//!
35//! ```php
36//! use Utopia\Query\Tokenizer\Tokenizer;
37//!
38//! $tokens = Tokenizer::filter((new Tokenizer())->tokenize('SELECT * FROM users'));
39//! echo implode(' ', array_map(fn ($t) => $t->type->name, $tokens)), "\n"; // Keyword Star Keyword Identifier Eof
40//! echo $tokens[3]->value, "\n"; // users
41//! ```
42
43use crate::StringLiteral;
44use std::borrow::Cow;
45
46use crate::error::{Error, Result};
47
48/// What a [`Token`] is.
49///
50/// PHP: `Utopia\Query\Tokenizer\TokenType`.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52pub enum TokenType {
53    /// A reserved word (`SELECT`, `FROM`), upper-cased.
54    Keyword,
55    /// A bare identifier, as written.
56    Identifier,
57    /// A quoted identifier, quotes included (`` `name` ``, `"name"`).
58    QuotedIdentifier,
59    /// An integer literal.
60    Integer,
61    /// A decimal or exponent literal (`1.5`, `.5`, `1e3`).
62    Float,
63    /// A string literal, quotes and escapes included.
64    String,
65    /// `TRUE` or `FALSE`, upper-cased.
66    Boolean,
67    /// `NULL`, upper-cased.
68    Null,
69    /// An operator, or any other character.
70    Operator,
71    /// `(`.
72    LeftParen,
73    /// `)`.
74    RightParen,
75    /// `,`.
76    Comma,
77    /// `;`.
78    Semicolon,
79    /// `.`.
80    Dot,
81    /// `*`.
82    Star,
83    /// `?`.
84    Placeholder,
85    /// `:name`.
86    NamedPlaceholder,
87    /// `$1`.
88    NumberedPlaceholder,
89    /// `-- comment` (and MySQL's `# comment`, rewritten to `-- `).
90    LineComment,
91    /// `/* comment */`.
92    BlockComment,
93    /// Spaces, tabs and line breaks.
94    Whitespace,
95    /// The end of the input.
96    Eof,
97}
98
99impl TokenType {
100    /// Every case, in declaration order.
101    ///
102    /// PHP: `TokenType::cases()`.
103    pub const CASES: &'static [TokenType] = &[
104        TokenType::Keyword,
105        TokenType::Identifier,
106        TokenType::QuotedIdentifier,
107        TokenType::Integer,
108        TokenType::Float,
109        TokenType::String,
110        TokenType::Boolean,
111        TokenType::Null,
112        TokenType::Operator,
113        TokenType::LeftParen,
114        TokenType::RightParen,
115        TokenType::Comma,
116        TokenType::Semicolon,
117        TokenType::Dot,
118        TokenType::Star,
119        TokenType::Placeholder,
120        TokenType::NamedPlaceholder,
121        TokenType::NumberedPlaceholder,
122        TokenType::LineComment,
123        TokenType::BlockComment,
124        TokenType::Whitespace,
125        TokenType::Eof,
126    ];
127
128    /// The case name.
129    ///
130    /// PHP: `->name`.
131    pub const fn name(self) -> &'static str {
132        match self {
133            TokenType::Keyword => "Keyword",
134            TokenType::Identifier => "Identifier",
135            TokenType::QuotedIdentifier => "QuotedIdentifier",
136            TokenType::Integer => "Integer",
137            TokenType::Float => "Float",
138            TokenType::String => "String",
139            TokenType::Boolean => "Boolean",
140            TokenType::Null => "Null",
141            TokenType::Operator => "Operator",
142            TokenType::LeftParen => "LeftParen",
143            TokenType::RightParen => "RightParen",
144            TokenType::Comma => "Comma",
145            TokenType::Semicolon => "Semicolon",
146            TokenType::Dot => "Dot",
147            TokenType::Star => "Star",
148            TokenType::Placeholder => "Placeholder",
149            TokenType::NamedPlaceholder => "NamedPlaceholder",
150            TokenType::NumberedPlaceholder => "NumberedPlaceholder",
151            TokenType::LineComment => "LineComment",
152            TokenType::BlockComment => "BlockComment",
153            TokenType::Whitespace => "Whitespace",
154            TokenType::Eof => "Eof",
155        }
156    }
157
158    /// The case named `name`, if any.
159    pub fn from_name(name: &str) -> Option<Self> {
160        Self::CASES.iter().copied().find(|c| c.name() == name)
161    }
162
163    /// Whether [`Tokenizer::filter`] drops tokens of this type (whitespace and comments).
164    pub const fn is_trivia(self) -> bool {
165        matches!(self, TokenType::Whitespace | TokenType::LineComment | TokenType::BlockComment)
166    }
167}
168
169/// One token: its type, its text and its byte position in the SQL.
170///
171/// The value is bytes, as PHP's strings are: a character the tokenizer does
172/// not know outside quotes is one operator token per byte, so a multi-byte
173/// UTF-8 character becomes several tokens that are not UTF-8 on their own
174/// ([`Token::text`] reads a value as text). It borrows the SQL text, except
175/// for keywords, `NULL` and booleans (upper-cased) and tokens of MySQL SQL
176/// whose `#` comments were rewritten.
177///
178/// PHP: `Utopia\Query\Tokenizer\Token` (`type`, `value`, `position`).
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct Token<'a> {
181    /// What the token is.
182    ///
183    /// PHP: `$type`.
184    pub kind: TokenType,
185    /// Its text.
186    ///
187    /// PHP: `$value`.
188    pub value: Cow<'a, [u8]>,
189    /// Its byte offset in the SQL.
190    ///
191    /// PHP: `$position`.
192    pub position: usize,
193}
194
195impl<'a> Token<'a> {
196    /// A token.
197    ///
198    /// PHP: `new Token($type, $value, $position)`.
199    pub fn new(kind: TokenType, value: impl Into<Cow<'a, [u8]>>, position: usize) -> Self {
200        Token { kind, value: value.into(), position }
201    }
202
203    /// The value as text (lossy where it is not UTF-8).
204    pub fn text(&self) -> Cow<'_, str> {
205        String::from_utf8_lossy(&self.value)
206    }
207
208    /// The token, owning its value.
209    pub fn into_owned(self) -> Token<'static> {
210        Token { kind: self.kind, value: Cow::Owned(self.value.into_owned()), position: self.position }
211    }
212}
213
214/// Splits SQL into [`Token`]s, the way one dialect writes it.
215///
216/// Dialects differ in the identifier quote (a backtick, or a double quote
217/// for PostgreSQL and SQLite), in MySQL's `#` line comments and in
218/// PostgreSQL's multi-character operators (`@>`, `<@`, `<=>`, `<->`, `<#>`,
219/// `?|`, `?&`).
220///
221/// PHP: `Utopia\Query\Tokenizer\Tokenizer` and its dialect subclasses.
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub struct Tokenizer {
224    quote: u8,
225    hash_comments: bool,
226    postgres_operators: bool,
227    literal: StringLiteral,
228}
229
230impl Default for Tokenizer {
231    /// [`Tokenizer::new`].
232    fn default() -> Self {
233        Tokenizer::new()
234    }
235}
236
237/// Single-character operators.
238const fn single_operator(c: u8) -> Option<&'static str> {
239    match c {
240        b'=' => Some("="),
241        b'<' => Some("<"),
242        b'>' => Some(">"),
243        b'+' => Some("+"),
244        b'-' => Some("-"),
245        b'/' => Some("/"),
246        b'%' => Some("%"),
247        _ => None,
248    }
249}
250
251/// The keyword (or `NULL` / boolean) an upper-cased word is, with its type.
252fn keyword(upper: &[u8]) -> Option<(TokenType, &'static str)> {
253    use TokenType::{Boolean, Keyword, Null};
254    Some(match upper {
255        b"NULL" => (Null, "NULL"),
256        b"TRUE" => (Boolean, "TRUE"),
257        b"FALSE" => (Boolean, "FALSE"),
258        b"SELECT" => (Keyword, "SELECT"),
259        b"FROM" => (Keyword, "FROM"),
260        b"WHERE" => (Keyword, "WHERE"),
261        b"AND" => (Keyword, "AND"),
262        b"OR" => (Keyword, "OR"),
263        b"NOT" => (Keyword, "NOT"),
264        b"JOIN" => (Keyword, "JOIN"),
265        b"LEFT" => (Keyword, "LEFT"),
266        b"RIGHT" => (Keyword, "RIGHT"),
267        b"INNER" => (Keyword, "INNER"),
268        b"OUTER" => (Keyword, "OUTER"),
269        b"FULL" => (Keyword, "FULL"),
270        b"CROSS" => (Keyword, "CROSS"),
271        b"NATURAL" => (Keyword, "NATURAL"),
272        b"ON" => (Keyword, "ON"),
273        b"AS" => (Keyword, "AS"),
274        b"ORDER" => (Keyword, "ORDER"),
275        b"BY" => (Keyword, "BY"),
276        b"GROUP" => (Keyword, "GROUP"),
277        b"HAVING" => (Keyword, "HAVING"),
278        b"LIMIT" => (Keyword, "LIMIT"),
279        b"OFFSET" => (Keyword, "OFFSET"),
280        b"ASC" => (Keyword, "ASC"),
281        b"DESC" => (Keyword, "DESC"),
282        b"IN" => (Keyword, "IN"),
283        b"BETWEEN" => (Keyword, "BETWEEN"),
284        b"LIKE" => (Keyword, "LIKE"),
285        b"ILIKE" => (Keyword, "ILIKE"),
286        b"IS" => (Keyword, "IS"),
287        b"CASE" => (Keyword, "CASE"),
288        b"WHEN" => (Keyword, "WHEN"),
289        b"THEN" => (Keyword, "THEN"),
290        b"ELSE" => (Keyword, "ELSE"),
291        b"END" => (Keyword, "END"),
292        b"EXISTS" => (Keyword, "EXISTS"),
293        b"DISTINCT" => (Keyword, "DISTINCT"),
294        b"ALL" => (Keyword, "ALL"),
295        b"UNION" => (Keyword, "UNION"),
296        b"INTERSECT" => (Keyword, "INTERSECT"),
297        b"EXCEPT" => (Keyword, "EXCEPT"),
298        b"WITH" => (Keyword, "WITH"),
299        b"RECURSIVE" => (Keyword, "RECURSIVE"),
300        b"SET" => (Keyword, "SET"),
301        b"INSERT" => (Keyword, "INSERT"),
302        b"INTO" => (Keyword, "INTO"),
303        b"VALUES" => (Keyword, "VALUES"),
304        b"UPDATE" => (Keyword, "UPDATE"),
305        b"DELETE" => (Keyword, "DELETE"),
306        b"CREATE" => (Keyword, "CREATE"),
307        b"ALTER" => (Keyword, "ALTER"),
308        b"DROP" => (Keyword, "DROP"),
309        b"TABLE" => (Keyword, "TABLE"),
310        b"INDEX" => (Keyword, "INDEX"),
311        b"VIEW" => (Keyword, "VIEW"),
312        b"OVER" => (Keyword, "OVER"),
313        b"PARTITION" => (Keyword, "PARTITION"),
314        b"WINDOW" => (Keyword, "WINDOW"),
315        b"ROWS" => (Keyword, "ROWS"),
316        b"RANGE" => (Keyword, "RANGE"),
317        b"UNBOUNDED" => (Keyword, "UNBOUNDED"),
318        b"PRECEDING" => (Keyword, "PRECEDING"),
319        b"FOLLOWING" => (Keyword, "FOLLOWING"),
320        b"CURRENT" => (Keyword, "CURRENT"),
321        b"ROW" => (Keyword, "ROW"),
322        b"FETCH" => (Keyword, "FETCH"),
323        b"NEXT" => (Keyword, "NEXT"),
324        b"FIRST" => (Keyword, "FIRST"),
325        b"LAST" => (Keyword, "LAST"),
326        b"NULLS" => (Keyword, "NULLS"),
327        b"CAST" => (Keyword, "CAST"),
328        b"FILTER" => (Keyword, "FILTER"),
329        b"WITHIN" => (Keyword, "WITHIN"),
330        _ => return None,
331    })
332}
333
334/// The longest keyword.
335const KEYWORD_MAX: usize = 9;
336
337const fn is_ident_start(c: u8) -> bool {
338    c.is_ascii_alphabetic() || c == b'_'
339}
340
341const fn is_ident_char(c: u8) -> bool {
342    c.is_ascii_alphanumeric() || c == b'_'
343}
344
345impl Tokenizer {
346    /// The standard tokenizer: identifiers quoted with backticks (or double quotes).
347    ///
348    /// PHP: `new Tokenizer\Tokenizer()`.
349    pub const fn new() -> Self {
350        Tokenizer { quote: b'`', hash_comments: false, postgres_operators: false, literal: StringLiteral::Backslash }
351    }
352
353    /// MySQL: also reads `#` line comments.
354    ///
355    /// PHP: `new Tokenizer\MySQL()`.
356    pub const fn mysql() -> Self {
357        Tokenizer { quote: b'`', hash_comments: true, postgres_operators: false, literal: StringLiteral::Backslash }
358    }
359
360    /// MariaDB: as MySQL.
361    ///
362    /// PHP: `new Tokenizer\MariaDB()`.
363    pub const fn mariadb() -> Self {
364        Self::mysql()
365    }
366
367    /// PostgreSQL: identifiers quoted with double quotes, and its
368    /// multi-character operators as one token.
369    ///
370    /// PHP: `new Tokenizer\PostgreSQL()`.
371    pub const fn postgresql() -> Self {
372        Tokenizer { quote: b'"', hash_comments: false, postgres_operators: true, literal: StringLiteral::Extended }
373    }
374
375    /// SQLite: a backslash is a character like any other.
376    ///
377    /// PHP: `new Tokenizer\SQLite()`.
378    pub const fn sqlite() -> Self {
379        Self::new().with_literal(StringLiteral::Standard)
380    }
381
382    /// ClickHouse: as the standard tokenizer.
383    ///
384    /// PHP: `new Tokenizer\ClickHouse()`.
385    pub const fn clickhouse() -> Self {
386        Self::new().with_literal(StringLiteral::BackslashUtf8)
387    }
388
389    /// The tokenizer reading string literals by `literal`'s rules.
390    ///
391    /// PHP: `new Tokenizer($literal)`.
392    #[must_use]
393    pub const fn with_literal(mut self, literal: StringLiteral) -> Self {
394        self.literal = literal;
395        self
396    }
397
398    /// The tokens of `sql`, whitespace and comments included, ending with an
399    /// [`TokenType::Eof`] token. Fails with [`Error::Validation`] on an
400    /// unterminated string literal or quoted identifier.
401    ///
402    /// PHP: `Tokenizer::tokenize()`.
403    ///
404    /// ```
405    /// use utopia_query::tokenizer::{TokenType, Tokenizer};
406    ///
407    /// let tokens = Tokenizer::mysql().tokenize("SELECT 1 #note")?;
408    /// assert_eq!(tokens[4].kind, TokenType::LineComment);
409    /// assert_eq!(tokens[4].text(), "-- note");
410    /// assert!(Tokenizer::new().tokenize("SELECT 'open").is_err());
411    /// # Ok::<(), utopia_query::Error>(())
412    /// ```
413    ///
414    /// ```php
415    /// use Utopia\Query\Tokenizer\MySQL;
416    ///
417    /// $tokens = (new MySQL())->tokenize('SELECT 1 #note');
418    /// echo $tokens[4]->type->name, ' ', $tokens[4]->value, "\n"; // LineComment -- note
419    /// ```
420    pub fn tokenize<'a, S: AsRef<[u8]> + ?Sized>(&self, sql: &'a S) -> Result<Vec<Token<'a>>> {
421        let sql: &'a [u8] = sql.as_ref();
422        if self.hash_comments
423            && let Some(rewritten) = replace_hash_comments(sql, self.literal.escapes_in_plain_literal())
424        {
425            let tokens = self.scan(&rewritten)?;
426            return Ok(tokens.into_iter().map(Token::into_owned).collect());
427        }
428        let mut tokens = self.scan(sql)?;
429        if self.postgres_operators {
430            merge_postgres_operators(sql, &mut tokens);
431        }
432        Ok(tokens)
433    }
434
435    /// `tokens` without whitespace and comments.
436    ///
437    /// PHP: `Tokenizer::filter()`.
438    pub fn filter(mut tokens: Vec<Token<'_>>) -> Vec<Token<'_>> {
439        tokens.retain(|t| !t.kind.is_trivia());
440        tokens
441    }
442
443    fn scan<'a>(&self, sql: &'a [u8]) -> Result<Vec<Token<'a>>> {
444        let mut scanner = Scanner { bytes: sql, pos: 0 };
445        let mut tokens = Vec::with_capacity(sql.len() / 3 + 1);
446        while scanner.pos < scanner.bytes.len() {
447            tokens.push(scanner.next(self)?);
448        }
449        tokens.push(Token { kind: TokenType::Eof, value: Cow::Borrowed(b""), position: scanner.pos });
450        Ok(tokens)
451    }
452}
453
454struct Scanner<'a> {
455    bytes: &'a [u8],
456    pos: usize,
457}
458
459impl<'a> Scanner<'a> {
460    fn peek(&self, offset: usize) -> Option<u8> {
461        self.bytes.get(self.pos + offset).copied()
462    }
463
464    fn at(&self, i: usize) -> Option<u8> {
465        self.bytes.get(i).copied()
466    }
467
468    fn token(&self, kind: TokenType, start: usize) -> Token<'a> {
469        Token { kind, value: Cow::Borrowed(&self.bytes[start..self.pos]), position: start }
470    }
471
472    fn fixed(&mut self, kind: TokenType, value: &'static str, start: usize) -> Token<'a> {
473        self.pos += value.len();
474        Token { kind, value: Cow::Borrowed(value.as_bytes()), position: start }
475    }
476
477    fn next(&mut self, tokenizer: &Tokenizer) -> Result<Token<'a>> {
478        let start = self.pos;
479        let c = self.bytes[start];
480        let quote = tokenizer.quote;
481        let prefix = tokenizer.literal.escape_prefix().as_bytes();
482        Ok(match c {
483            b' ' | b'\t' | b'\n' | b'\r' => {
484                while matches!(self.peek(0), Some(b' ' | b'\t' | b'\n' | b'\r')) {
485                    self.pos += 1;
486                }
487                self.token(TokenType::Whitespace, start)
488            }
489            b'-' if self.peek(1) == Some(b'-') => {
490                self.pos += 2;
491                while self.peek(0).is_some_and(|c| c != b'\n') {
492                    self.pos += 1;
493                }
494                self.token(TokenType::LineComment, start)
495            }
496            b'/' if self.peek(1) == Some(b'*') => self.block_comment(start),
497            b'\'' => self.string(start, tokenizer.literal.escapes_in_plain_literal())?,
498            // `E'...'`: a literal whose backslashes escape.
499            _ if !prefix.is_empty() && prefix[0].eq_ignore_ascii_case(&c) && self.peek(1) == Some(b'\'') => {
500                self.pos += prefix.len();
501                self.string(start, true)?
502            }
503            _ if c == quote => self.quoted_identifier(start, quote)?,
504            b'"' => self.quoted_identifier(start, b'"')?,
505            b'0'..=b'9' => self.number(start),
506            _ if is_ident_start(c) => self.word(start),
507            b'(' => self.fixed(TokenType::LeftParen, "(", start),
508            b')' => self.fixed(TokenType::RightParen, ")", start),
509            b',' => self.fixed(TokenType::Comma, ",", start),
510            b';' => self.fixed(TokenType::Semicolon, ";", start),
511            b'.' => {
512                if self.peek(1).is_some_and(|c| c.is_ascii_digit()) {
513                    self.number(start)
514                } else {
515                    self.fixed(TokenType::Dot, ".", start)
516                }
517            }
518            b'*' => self.fixed(TokenType::Star, "*", start),
519            b'?' => self.fixed(TokenType::Placeholder, "?", start),
520            b':' => match self.peek(1) {
521                Some(b':') => self.fixed(TokenType::Operator, "::", start),
522                Some(n) if is_ident_start(n) => {
523                    self.pos += 1;
524                    while self.peek(0).is_some_and(is_ident_char) {
525                        self.pos += 1;
526                    }
527                    self.token(TokenType::NamedPlaceholder, start)
528                }
529                _ => self.fixed(TokenType::Operator, ":", start),
530            },
531            b'$' => {
532                if self.peek(1).is_some_and(|c| c.is_ascii_digit()) {
533                    self.pos += 1;
534                    while self.peek(0).is_some_and(|c| c.is_ascii_digit()) {
535                        self.pos += 1;
536                    }
537                    self.token(TokenType::NumberedPlaceholder, start)
538                } else {
539                    self.fixed(TokenType::Operator, "$", start)
540                }
541            }
542            _ => self.operator(start, c),
543        })
544    }
545
546    fn block_comment(&mut self, start: usize) -> Token<'a> {
547        self.pos += 2;
548        let len = self.bytes.len();
549        let mut terminated = false;
550        while self.pos + 1 < len {
551            if self.bytes[self.pos] == b'*' && self.bytes[self.pos + 1] == b'/' {
552                self.pos += 2;
553                terminated = true;
554                break;
555            }
556            self.pos += 1;
557        }
558        if !terminated {
559            self.pos = len;
560        }
561        self.token(TokenType::BlockComment, start)
562    }
563
564    fn string(&mut self, start: usize, escapes: bool) -> Result<Token<'a>> {
565        self.pos += 1;
566        let len = self.bytes.len();
567        while self.pos < len {
568            match self.bytes[self.pos] {
569                b'\\' if escapes => {
570                    if self.pos + 1 >= len {
571                        break;
572                    }
573                    self.pos += 2;
574                }
575                b'\'' => {
576                    self.pos += 1;
577                    if self.peek(0) == Some(b'\'') {
578                        self.pos += 1;
579                        continue;
580                    }
581                    return Ok(self.token(TokenType::String, start));
582                }
583                _ => self.pos += 1,
584            }
585        }
586        Err(Error::Validation("Unterminated string literal".into()))
587    }
588
589    fn quoted_identifier(&mut self, start: usize, quote: u8) -> Result<Token<'a>> {
590        self.pos += 1;
591        while let Some(c) = self.peek(0) {
592            self.pos += 1;
593            if c == quote {
594                if self.peek(0) == Some(quote) {
595                    self.pos += 1;
596                    continue;
597                }
598                return Ok(self.token(TokenType::QuotedIdentifier, start));
599            }
600        }
601        Err(Error::Validation("Unterminated quoted identifier".into()))
602    }
603
604    fn digits(&mut self) {
605        while self.peek(0).is_some_and(|c| c.is_ascii_digit()) {
606            self.pos += 1;
607        }
608    }
609
610    fn number(&mut self, start: usize) -> Token<'a> {
611        let mut float = false;
612        if self.peek(0) == Some(b'.') {
613            float = true;
614            self.pos += 1;
615        }
616        self.digits();
617        if !float && self.peek(0) == Some(b'.') && self.peek(1).is_some_and(|c| c.is_ascii_digit()) {
618            float = true;
619            self.pos += 1;
620            self.digits();
621        }
622        if matches!(self.peek(0), Some(b'e' | b'E')) {
623            let mut next = self.pos + 1;
624            if matches!(self.at(next), Some(b'+' | b'-')) {
625                next += 1;
626            }
627            if self.at(next).is_some_and(|c| c.is_ascii_digit()) {
628                float = true;
629                self.pos = next;
630                self.digits();
631            }
632        }
633        self.token(if float { TokenType::Float } else { TokenType::Integer }, start)
634    }
635
636    fn word(&mut self, start: usize) -> Token<'a> {
637        while self.peek(0).is_some_and(is_ident_char) {
638            self.pos += 1;
639        }
640        let word = &self.bytes[start..self.pos];
641        if word.len() <= KEYWORD_MAX {
642            let mut upper = [0u8; KEYWORD_MAX];
643            for (u, c) in upper.iter_mut().zip(word) {
644                *u = c.to_ascii_uppercase();
645            }
646            if let Some((kind, value)) = keyword(&upper[..word.len()]) {
647                return Token { kind, value: Cow::Borrowed(value.as_bytes()), position: start };
648            }
649        }
650        self.token(TokenType::Identifier, start)
651    }
652
653    fn operator(&mut self, start: usize, c: u8) -> Token<'a> {
654        let two = match (c, self.peek(1)) {
655            (b'<', Some(b'=')) => Some("<="),
656            (b'>', Some(b'=')) => Some(">="),
657            (b'!', Some(b'=')) => Some("!="),
658            (b'<', Some(b'>')) => Some("<>"),
659            (b'|', Some(b'|')) => Some("||"),
660            _ => None,
661        };
662        if let Some(op) = two {
663            return self.fixed(TokenType::Operator, op, start);
664        }
665        if let Some(op) = single_operator(c) {
666            return self.fixed(TokenType::Operator, op, start);
667        }
668        // Any other byte is a one-byte operator (a multi-byte UTF-8
669        // character is one token per byte, as in PHP).
670        self.pos += 1;
671        self.token(TokenType::Operator, start)
672    }
673}
674
675/// MySQL's `#` comments rewritten to `-- ` outside strings and quoted
676/// identifiers (`None` when the SQL has none).
677fn replace_hash_comments(sql: &[u8], escapes: bool) -> Option<Vec<u8>> {
678    let bytes = sql;
679    let len = bytes.len();
680    let mut hashes = Vec::new();
681    let mut i = 0;
682    while i < len {
683        let c = bytes[i];
684        match c {
685            b'\'' | b'"' | b'`' => {
686                i += 1;
687                while i < len {
688                    let d = bytes[i];
689                    if d == b'\\' && (c == b'"' || (c == b'\'' && escapes)) {
690                        i += 2;
691                        continue;
692                    }
693                    i += 1;
694                    if d == c {
695                        if i < len && bytes[i] == c {
696                            i += 1;
697                            continue;
698                        }
699                        break;
700                    }
701                }
702            }
703            b'#' => {
704                hashes.push(i);
705                i += 1;
706            }
707            _ => i += 1,
708        }
709    }
710    if hashes.is_empty() {
711        return None;
712    }
713    let mut out = Vec::with_capacity(len + hashes.len() * 2);
714    let mut from = 0;
715    for h in hashes {
716        out.extend_from_slice(&sql[from..h]);
717        out.extend_from_slice(b"-- ");
718        from = h + 1;
719    }
720    out.extend_from_slice(&sql[from.min(len)..]);
721    Some(out)
722}
723
724fn is_op(t: &Token<'_>) -> bool {
725    matches!(t.kind, TokenType::Operator | TokenType::Star)
726}
727
728/// PostgreSQL's multi-character operators, merged from adjacent tokens.
729fn merge_postgres_operators<'a>(sql: &'a [u8], tokens: &mut Vec<Token<'a>>) {
730    let count = tokens.len();
731    let mut out = 0;
732    let mut i = 0;
733    // Adjacent tokens cover adjacent text: a merged operator is the span.
734    let span = |tokens: &[Token<'a>], from: usize, to: usize| -> &'a [u8] {
735        let start = tokens[from].position;
736        let end = tokens[to].position + tokens[to].value.len();
737        &sql[start..end]
738    };
739    while i < count {
740        let mut merged = None;
741        if i + 2 < count && is_op(&tokens[i]) && is_op(&tokens[i + 1]) && is_op(&tokens[i + 2]) {
742            let three = span(tokens, i, i + 2);
743            if three == b"<->" || three == b"<#>" {
744                merged = Some((three, 3));
745            }
746        }
747        if merged.is_none() && i + 1 < count && is_op(&tokens[i]) && is_op(&tokens[i + 1]) {
748            let two = span(tokens, i, i + 1);
749            if two == b"@>" || two == b"<@" || two == b"<=>" {
750                merged = Some((two, 2));
751            }
752        }
753        if merged.is_none()
754            && i + 1 < count
755            && tokens[i].kind == TokenType::Placeholder
756            && tokens[i + 1].kind == TokenType::Operator
757            && (*tokens[i + 1].value == *b"|" || *tokens[i + 1].value == *b"&")
758        {
759            merged = Some((span(tokens, i, i + 1), 2));
760        }
761        match merged {
762            Some((value, n)) => {
763                let position = tokens[i].position;
764                tokens[out] = Token { kind: TokenType::Operator, value: Cow::Borrowed(value), position };
765                i += n;
766            }
767            None => {
768                if out != i {
769                    tokens.swap(out, i);
770                }
771                i += 1;
772            }
773        }
774        out += 1;
775    }
776    tokens.truncate(out);
777}