sqlexpr-congo-rust 1.0.0

Parser for SqlExprParser - Generated by CongoCC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Lexer implementation. Generated by CongoCC Parser Generator. Do not edit.

use crate::error::{ParseError, ParseResult};
use crate::tokens::{Token, TokenType, LexicalState, TokenSource};

/// The lexer/tokenizer for SqlExprParser
pub struct Lexer {
    /// The input string being tokenized
    input: String,
    /// Current position in the input
    position: usize,
    /// Current lexical state
    state: LexicalState,
    /// All tokens generated so far
    tokens: Vec<Token>,
    /// Current line number (1-indexed)
    current_line: usize,
    /// Current column number (1-indexed)
    current_column: usize,
    /// Line start offsets for quick line/column lookup
    line_starts: Vec<usize>,
}

impl Lexer {
    /// Create a new lexer for the given input
    pub fn new(input: String) -> Self {
        let mut line_starts = vec![0];
        for (i, ch) in input.char_indices() {
            if ch == '\n' {
                line_starts.push(i + 1);
            }
        }

        Lexer {
            input,
            position: 0,
            state: LexicalState::DEFAULT,
            tokens: Vec::new(),
            current_line: 1,
            current_column: 1,
            line_starts,
        }
    }

    /// Get the next token from the input
    pub fn next_token(&mut self) -> ParseResult<Token> {
        // Skip whitespace and comments based on lexical state
        self.skip_ignored()?;

        if self.position >= self.input.len() {
            // Return EOF token
            return Ok(Token::new(
                TokenType::EOF,
                String::new(),
                self.position,
                self.position,
            ));
        }

        let start_pos = self.position;
        let start_line = self.current_line;
        let start_column = self.current_column;

        // Try to match each token type in order
        if let Some(token) = self.try_match_token(start_pos)? {
            return Ok(token);
        }

        // If no token matched, it's an error
        Err(ParseError::at_location(
            format!("Unexpected character: '{}'", self.current_char()),
            start_line,
            start_column,
        ))
    }

    /// Try to match a token at the current position
    fn try_match_token(&mut self, start_pos: usize) -> ParseResult<Option<Token>> {
        let ch = self.current_char();

        if self.matches_string("!=") {
            return Ok(Some(self.consume_literal(TokenType::NE, "!=", start_pos)));
        }
        if self.matches_string("<>") {
            return Ok(Some(self.consume_literal(TokenType::NE, "<>", start_pos)));
        }
        if self.matches_string(">=") {
            return Ok(Some(self.consume_literal(TokenType::GE, ">=", start_pos)));
        }
        if self.matches_string("<=") {
            return Ok(Some(self.consume_literal(TokenType::LE, "<=", start_pos)));
        }
        match ch {
            ' ' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::SPACE,
                    " ".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '\t' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::TAB,
                    "\t".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '\n' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::NEWLINE,
                    "\n".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '\r' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::CR,
                    "\r".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '\x0c' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::FORM_FEED,
                    "\x0c".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '=' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::EQ,
                    "=".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '>' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::GT,
                    ">".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '<' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::LT,
                    "<".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '(' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::LPAREN,
                    "(".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            ',' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::COMMA,
                    ",".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            ')' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::RPAREN,
                    ")".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '+' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::PLUS,
                    "+".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '-' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::MINUS,
                    "-".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '*' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::STAR,
                    "*".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '/' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::SLASH,
                    "/".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            '%' => {
                self.advance();
                return Ok(Some(Token::new(
                    TokenType::PERCENT,
                    "%".to_string(),
                    start_pos,
                    self.position,
                )));
            }
            _ => {}
        }

        // String literal (single-quoted)
        if ch == '\'' {
            return self.match_string_literal(start_pos);
        }

        // Numeric literals (including leading-dot floats like .5)
        if ch.is_ascii_digit()
            || (ch == '.' && self.peek(1).is_some_and(|c| c.is_ascii_digit()))
        {
            return self.match_number(start_pos);
        }

        // Identifiers and keywords
        if ch.is_ascii_alphabetic() || ch == '_' || ch == '$' {
            return self.match_identifier_or_keyword(start_pos);
        }

        // No token matched
        Ok(None)
    }

    /// Consume a literal string token
    fn consume_literal(&mut self, token_type: TokenType, literal: &str, start_pos: usize) -> Token {
        for _ in 0..literal.len() {
            self.advance();
        }
        Token::new(token_type, literal.to_string(), start_pos, self.position)
    }

    /// Match a single-quoted string literal
    fn match_string_literal(&mut self, start_pos: usize) -> ParseResult<Option<Token>> {
        // Consume opening quote
        self.advance();
        while self.position < self.input.len() {
            let ch = self.current_char();
            if ch == '\'' {
                // Check for escaped quote ('')
                if self.peek(1) == Some('\'') {
                    self.advance(); // consume first '
                    self.advance(); // consume second '
                    continue;
                }
                self.advance(); // consume closing quote
                let image = self.input[start_pos..self.position].to_string();
                return Ok(Some(Token::new(
                    TokenType::STRING_LITERAL,
                    image,
                    start_pos,
                    self.position,
                )));
            }
            self.advance();
        }
        // Unterminated string literal
        Err(ParseError::at_position(
            "Unterminated string literal".to_string(),
            start_pos,
        ))
    }

    /// Match a numeric literal (integer, hex, octal, or decimal/float)
    fn match_number(&mut self, start_pos: usize) -> ParseResult<Option<Token>> {
        // Check for hex (0x/0X) or octal (leading 0 + digits) prefix
        if self.current_char() == '0' {
            if self.peek(1).is_some_and(|ch| ch == 'x' || ch == 'X') {
                // Hex literal: 0x followed by hex digits
                self.advance(); // consume '0'
                self.advance(); // consume 'x'/'X'
                if self.position >= self.input.len() || !self.current_char().is_ascii_hexdigit() {
                    return Err(ParseError::at_position(
                        "Expected hex digit after 0x".to_string(),
                        start_pos,
                    ));
                }
                while self.position < self.input.len() && self.current_char().is_ascii_hexdigit() {
                    self.advance();
                }
                // Optional long suffix
                if self.position < self.input.len() && matches!(self.current_char(), 'L' | 'l') {
                    self.advance();
                }
                let image = self.input[start_pos..self.position].to_string();
                return Ok(Some(Token::new(
                    TokenType::HEX_LITERAL,
                    image,
                    start_pos,
                    self.position,
                )));
            }
            if self.peek(1).is_some_and(|ch| ('0'..='7').contains(&ch)) {
                // Octal literal: 0 followed by octal digits
                self.advance(); // consume leading '0'
                while self.position < self.input.len() && ('0'..='7').contains(&self.current_char()) {
                    self.advance();
                }
                // Optional long suffix
                if self.position < self.input.len() && matches!(self.current_char(), 'L' | 'l') {
                    self.advance();
                }
                let image = self.input[start_pos..self.position].to_string();
                return Ok(Some(Token::new(
                    TokenType::OCTAL_LITERAL,
                    image,
                    start_pos,
                    self.position,
                )));
            }
        }

        // Consume leading digits
        let mut is_float = false;
        while self.position < self.input.len() && self.current_char().is_ascii_digit() {
            self.advance();
        }
        // Check for decimal point followed by digits
        if self.position < self.input.len() && self.current_char() == '.'
            && self.peek(1).is_some_and(|ch| ch.is_ascii_digit())
        {
            is_float = true;
            self.advance(); // consume '.'
            while self.position < self.input.len() && self.current_char().is_ascii_digit() {
                self.advance();
            }
        }
        // Check for exponent (e/E followed by optional +/- and digits)
        if self.position < self.input.len() && matches!(self.current_char(), 'e' | 'E') {
            is_float = true;
            self.advance(); // consume 'e'/'E'
            if self.position < self.input.len() && matches!(self.current_char(), '+' | '-') {
                self.advance(); // consume sign
            }
            if self.position >= self.input.len() || !self.current_char().is_ascii_digit() {
                return Err(ParseError::at_position(
                    "Expected digit in exponent".to_string(),
                    start_pos,
                ));
            }
            while self.position < self.input.len() && self.current_char().is_ascii_digit() {
                self.advance();
            }
        }
        if is_float {
            let image = self.input[start_pos..self.position].to_string();
            return Ok(Some(Token::new(
                TokenType::FLOATING_POINT_LITERAL,
                image,
                start_pos,
                self.position,
            )));
        }
        // Optional long suffix for integer literals
        if self.position < self.input.len() && matches!(self.current_char(), 'L' | 'l') {
            self.advance();
        }
        let image = self.input[start_pos..self.position].to_string();
        Ok(Some(Token::new(
            TokenType::DECIMAL_LITERAL,
            image,
            start_pos,
            self.position,
        )))
    }

    /// Match an identifier or keyword
    fn match_identifier_or_keyword(&mut self, start_pos: usize) -> ParseResult<Option<Token>> {
        // Consume identifier characters
        while self.position < self.input.len() {
            let ch = self.current_char();
            if ch.is_ascii_alphanumeric() || ch == '_' || ch == '$' {
                self.advance();
            } else {
                break;
            }
        }
        let image = self.input[start_pos..self.position].to_string();
        let upper = image.to_ascii_uppercase();

        // Check against keywords (case-insensitive)
        let token_type = match upper.as_str() {
            "NOT" => TokenType::NOT,
            "AND" => TokenType::AND,
            "OR" => TokenType::OR,
            "BETWEEN" => TokenType::BETWEEN,
            "LIKE" => TokenType::LIKE,
            "ESCAPE" => TokenType::ESCAPE,
            "IN" => TokenType::IN,
            "IS" => TokenType::IS,
            "TRUE" => TokenType::TRUE,
            "FALSE" => TokenType::FALSE,
            "NULL" => TokenType::NULL,
            _ => TokenType::ID,
        };

        Ok(Some(Token::new(token_type, image, start_pos, self.position)))
    }

    /// Skip whitespace and ignored tokens
    fn skip_ignored(&mut self) -> ParseResult<()> {
        while self.position < self.input.len() {
            let ch = self.current_char();

            // Skip whitespace
            if ch.is_whitespace() {
                self.advance();
                continue;
            }

            // Skip line comments: -- to end of line
            if ch == '-' && self.peek(1) == Some('-') {
                self.advance(); // consume first -
                self.advance(); // consume second -
                while self.position < self.input.len() && self.current_char() != '\n' {
                    self.advance();
                }
                continue;
            }

            // Skip block comments: /* ... */
            if ch == '/' && self.peek(1) == Some('*') {
                let start_pos = self.position;
                self.advance(); // consume /
                self.advance(); // consume *
                loop {
                    if self.position >= self.input.len() {
                        return Err(ParseError::at_position(
                            "Unterminated block comment".to_string(),
                            start_pos,
                        ));
                    }
                    if self.current_char() == '*' && self.peek(1) == Some('/') {
                        self.advance(); // consume *
                        self.advance(); // consume /
                        break;
                    }
                    self.advance();
                }
                continue;
            }

            break;
        }
        Ok(())
    }

    /// Get the current character without consuming it
    fn current_char(&self) -> char {
        self.input[self.position..].chars().next().unwrap_or('\0')
    }

    /// Advance to the next character
    fn advance(&mut self) {
        if self.position < self.input.len() {
            let ch = self.current_char();
            self.position += ch.len_utf8();

            if ch == '\n' {
                self.current_line += 1;
                self.current_column = 1;
            } else {
                self.current_column += 1;
            }
        }
    }

    /// Peek ahead n characters without consuming
    fn peek(&self, n: usize) -> Option<char> {
        self.input[self.position..].chars().nth(n)
    }

    /// Check if current position matches a string
    fn matches_string(&self, s: &str) -> bool {
        self.input[self.position..].starts_with(s)
    }
}

impl TokenSource for Lexer {
    fn get_line_from_offset(&self, offset: usize) -> usize {
        // Binary search for the line containing this offset
        match self.line_starts.binary_search(&offset) {
            Ok(line) => line + 1,
            Err(line) => line,
        }
    }

    fn get_column_from_offset(&self, offset: usize) -> usize {
        let line_num = self.get_line_from_offset(offset);
        if line_num == 0 || line_num > self.line_starts.len() {
            return 1;
        }

        let line_start = self.line_starts[line_num - 1];
        offset.saturating_sub(line_start) + 1
    }
}