aletheiadb 0.1.0

A high-performance bi-temporal graph database for LLM integration
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! Cypher Query Language Lexer
//!
//! Hand-written tokenizer that converts a Cypher query string into a `Vec<Token>`.
//! This is the first stage of the Cypher pipeline, producing tokens that feed into
//! the recursive descent parser.
//!
//! # Design
//!
//! - **No external dependencies**: pure Rust, zero allocations beyond the output vec.
//! - **Case-insensitive keywords**: identifiers are upper-cased and compared to a keyword table.
//! - **Position tracking**: every token records its byte offset for error diagnostics.
//! - **Always ends with `Eof`**: the token stream is always terminated.

use super::CypherError;

// ---------------------------------------------------------------------------
// Token types
// ---------------------------------------------------------------------------

/// The kind of a Cypher token.
///
/// Covers keywords, operators, symbols, literals, parameters, identifiers,
/// and the end-of-input marker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenKind {
    // -- Keywords: clauses --------------------------------------------------
    /// `MATCH`
    Match,
    /// `OPTIONAL` (always followed by `MATCH` in valid Cypher, but lexed separately
    /// so the parser can enforce the pairing)
    OptionalMatch,
    /// `WHERE`
    Where,
    /// `RETURN`
    Return,
    /// `WITH`
    With,
    /// `UNWIND`
    Unwind,

    // -- Keywords: ordering / projection ------------------------------------
    /// `ORDER`
    Order,
    /// `BY`
    By,
    /// `LIMIT`
    Limit,
    /// `SKIP`
    Skip,
    /// `AS`
    As,
    /// `DISTINCT`
    Distinct,

    // -- Keywords: logical --------------------------------------------------
    /// `AND`
    And,
    /// `OR`
    Or,
    /// `NOT`
    Not,
    /// `IN`
    In,
    /// `IS`
    Is,

    // -- Keywords: sort direction -------------------------------------------
    /// `ASC`
    Asc,
    /// `DESC`
    Desc,

    // -- Keywords: literals -------------------------------------------------
    /// `TRUE`
    True,
    /// `FALSE`
    False,
    /// `NULL`
    Null,

    // -- Keywords: string predicates ----------------------------------------
    /// `CONTAINS`
    Contains,
    /// `STARTS` (used in `STARTS WITH`)
    StartsWith,
    /// `ENDS` (used in `ENDS WITH`)
    EndsWith,

    // -- Keywords: aggregation ----------------------------------------------
    /// `COUNT`
    Count,
    /// `COLLECT`
    Collect,
    /// `AVG`
    Avg,
    /// `SUM`
    Sum,
    /// `MIN`
    Min,
    /// `MAX`
    Max,

    // -- Keywords: temporal -------------------------------------------------
    /// `OF`
    Of,
    /// `TIMESTAMP`
    Timestamp,
    /// `BETWEEN`
    Between,
    /// `FOR`
    For,
    /// `SYSTEM_TIME`
    SystemTime,
    /// `VALID_TIME`
    ValidTime,

    // -- Comparison operators -----------------------------------------------
    /// `=`
    Eq,
    /// `<>` or `!=`
    Ne,
    /// `<`
    Lt,
    /// `<=`
    Le,
    /// `>`
    Gt,
    /// `>=`
    Ge,

    // -- Symbols / punctuation ----------------------------------------------
    /// `(`
    LParen,
    /// `)`
    RParen,
    /// `[`
    LBracket,
    /// `]`
    RBracket,
    /// `{`
    LBrace,
    /// `}`
    RBrace,
    /// `:`
    Colon,
    /// `.`
    Dot,
    /// `..`
    DotDot,
    /// `,`
    Comma,
    /// `|`
    Pipe,
    /// `-`
    Dash,
    /// `->`
    Arrow,
    /// `<-`
    LeftArrow,
    /// `*`
    Star,
    /// `+`
    Plus,
    /// `/`
    Slash,
    /// `%`
    Percent,

    // -- Literals -----------------------------------------------------------
    /// An integer literal (e.g. `42`).
    IntegerLiteral,
    /// A floating-point literal (e.g. `3.14`).
    FloatLiteral,
    /// A string literal (`'hello'` or `"hello"`). The `text` field of the
    /// [`Token`] holds the *unescaped* content without surrounding quotes.
    StringLiteral,
    /// A parameter reference (`$name`). The `text` field holds the name
    /// *without* the leading `$`.
    Parameter,
    /// An identifier that did not match any keyword.
    Identifier,

    // -- End of input -------------------------------------------------------
    /// Marks the end of the token stream.
    Eof,
}

// ---------------------------------------------------------------------------
// Token
// ---------------------------------------------------------------------------

/// A single token produced by the Cypher lexer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
    /// What kind of token this is.
    pub kind: TokenKind,
    /// The source text of the token. For string literals this is the unescaped
    /// content (no quotes). For parameters this is the name without `$`.
    pub text: String,
    /// Byte offset in the original input where this token starts.
    pub position: usize,
}

impl Token {
    /// Create a new token.
    fn new(kind: TokenKind, text: impl Into<String>, position: usize) -> Self {
        Self {
            kind,
            text: text.into(),
            position,
        }
    }
}

// ---------------------------------------------------------------------------
// Lexer
// ---------------------------------------------------------------------------

/// Cypher query language lexer.
///
/// Converts a Cypher query string into a vector of [`Token`]s. This is the
/// entry point for the lexer; use [`CypherLexer::tokenize`] to lex a query.
///
/// # Examples
///
/// ```rust,ignore
/// use aletheiadb::cypher::lexer::{CypherLexer, TokenKind};
///
/// let tokens = CypherLexer::tokenize("MATCH (n) RETURN n").unwrap();
/// assert_eq!(tokens[0].kind, TokenKind::Match);
/// ```
pub struct CypherLexer<'a> {
    input: &'a str,
    chars: std::iter::Peekable<std::str::CharIndices<'a>>,
    position: usize,
}

impl<'a> CypherLexer<'a> {
    /// Tokenize the complete input, returning a vector that always ends with
    /// [`TokenKind::Eof`].
    pub fn tokenize(input: &str) -> Result<Vec<Token>, CypherError> {
        let mut lexer = CypherLexer {
            input,
            chars: input.char_indices().peekable(),
            position: 0,
        };

        let mut tokens = Vec::with_capacity(input.len() / 4 + 1);
        loop {
            let tok = lexer.next_token()?;
            let is_eof = tok.kind == TokenKind::Eof;
            tokens.push(tok);
            if is_eof {
                break;
            }
        }
        Ok(tokens)
    }

    // -----------------------------------------------------------------------
    // Main dispatch
    // -----------------------------------------------------------------------

    fn next_token(&mut self) -> Result<Token, CypherError> {
        self.skip_whitespace_and_comments();

        let Some(&(pos, ch)) = self.chars.peek() else {
            return Ok(Token::new(TokenKind::Eof, "", self.input.len()));
        };
        self.position = pos;

        match ch {
            // -- Single-char symbols ----------------------------------------
            '(' => {
                self.advance();
                Ok(Token::new(TokenKind::LParen, "(", pos))
            }
            ')' => {
                self.advance();
                Ok(Token::new(TokenKind::RParen, ")", pos))
            }
            '[' => {
                self.advance();
                Ok(Token::new(TokenKind::LBracket, "[", pos))
            }
            ']' => {
                self.advance();
                Ok(Token::new(TokenKind::RBracket, "]", pos))
            }
            '{' => {
                self.advance();
                Ok(Token::new(TokenKind::LBrace, "{", pos))
            }
            '}' => {
                self.advance();
                Ok(Token::new(TokenKind::RBrace, "}", pos))
            }
            ':' => {
                self.advance();
                Ok(Token::new(TokenKind::Colon, ":", pos))
            }
            ',' => {
                self.advance();
                Ok(Token::new(TokenKind::Comma, ",", pos))
            }
            '*' => {
                self.advance();
                Ok(Token::new(TokenKind::Star, "*", pos))
            }
            '+' => {
                self.advance();
                Ok(Token::new(TokenKind::Plus, "+", pos))
            }
            '%' => {
                self.advance();
                Ok(Token::new(TokenKind::Percent, "%", pos))
            }
            '|' => {
                self.advance();
                Ok(Token::new(TokenKind::Pipe, "|", pos))
            }

            // -- Dot / DotDot ----------------------------------------------
            '.' => self.read_dot(pos),

            // -- Equals ----------------------------------------------------
            '=' => {
                self.advance();
                Ok(Token::new(TokenKind::Eq, "=", pos))
            }

            // -- Multi-char operators starting with specific chars ----------
            '-' => self.read_dash(pos),
            '<' => self.read_less_than(pos),
            '>' => self.read_greater_than(pos),
            '!' => self.read_bang(pos),
            '/' => self.read_slash(pos),

            // -- String literals -------------------------------------------
            '\'' | '"' => self.read_string(pos),

            // -- Parameter -------------------------------------------------
            '$' => self.read_parameter(pos),

            // -- Numbers ---------------------------------------------------
            '0'..='9' => self.read_number(pos),

            // -- Identifiers / keywords ------------------------------------
            'a'..='z' | 'A'..='Z' | '_' => self.read_identifier_or_keyword(pos),

            _ => Err(self.lex_error(pos, format!("Unexpected character: '{ch}'"))),
        }
    }

    // -----------------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------------

    fn advance(&mut self) -> Option<(usize, char)> {
        self.chars.next()
    }

    fn peek_char(&mut self) -> Option<char> {
        self.chars.peek().map(|&(_, c)| c)
    }

    fn lex_error(&self, position: usize, message: String) -> CypherError {
        CypherError::LexError { position, message }
    }

    // -----------------------------------------------------------------------
    // Whitespace & comments
    // -----------------------------------------------------------------------

    fn skip_whitespace_and_comments(&mut self) {
        loop {
            // Skip whitespace
            while let Some(&(_, ch)) = self.chars.peek() {
                if ch.is_whitespace() {
                    self.advance();
                } else {
                    break;
                }
            }

            // Check for // line comment
            if let Some(&(_, '/')) = self.chars.peek() {
                let mut lookahead = self.chars.clone();
                lookahead.next();
                if let Some(&(_, '/')) = lookahead.peek() {
                    // Consume the two slashes
                    self.advance();
                    self.advance();
                    // Skip to end of line
                    while let Some(&(_, ch)) = self.chars.peek() {
                        if ch == '\n' {
                            self.advance();
                            break;
                        }
                        self.advance();
                    }
                    continue;
                }
            }

            break;
        }
    }

    // -----------------------------------------------------------------------
    // Dot / DotDot
    // -----------------------------------------------------------------------

    fn read_dot(&mut self, start: usize) -> Result<Token, CypherError> {
        self.advance(); // consume first '.'
        if let Some(&(_, '.')) = self.chars.peek() {
            self.advance(); // consume second '.'
            Ok(Token::new(TokenKind::DotDot, "..", start))
        } else {
            Ok(Token::new(TokenKind::Dot, ".", start))
        }
    }

    // -----------------------------------------------------------------------
    // Dash / Arrow
    // -----------------------------------------------------------------------

    fn read_dash(&mut self, start: usize) -> Result<Token, CypherError> {
        self.advance(); // consume '-'
        if let Some(&(_, '>')) = self.chars.peek() {
            self.advance();
            Ok(Token::new(TokenKind::Arrow, "->", start))
        } else {
            Ok(Token::new(TokenKind::Dash, "-", start))
        }
    }

    // -----------------------------------------------------------------------
    // Less-than family:  <  <=  <>  <-
    // -----------------------------------------------------------------------

    fn read_less_than(&mut self, start: usize) -> Result<Token, CypherError> {
        self.advance(); // consume '<'
        match self.peek_char() {
            Some('=') => {
                self.advance();
                Ok(Token::new(TokenKind::Le, "<=", start))
            }
            Some('>') => {
                self.advance();
                Ok(Token::new(TokenKind::Ne, "<>", start))
            }
            Some('-') => {
                self.advance();
                Ok(Token::new(TokenKind::LeftArrow, "<-", start))
            }
            _ => Ok(Token::new(TokenKind::Lt, "<", start)),
        }
    }

    // -----------------------------------------------------------------------
    // Greater-than family:  >  >=
    // -----------------------------------------------------------------------

    fn read_greater_than(&mut self, start: usize) -> Result<Token, CypherError> {
        self.advance(); // consume '>'
        if let Some('=') = self.peek_char() {
            self.advance();
            Ok(Token::new(TokenKind::Ge, ">=", start))
        } else {
            Ok(Token::new(TokenKind::Gt, ">", start))
        }
    }

    // -----------------------------------------------------------------------
    // Bang:  !=
    // -----------------------------------------------------------------------

    fn read_bang(&mut self, start: usize) -> Result<Token, CypherError> {
        self.advance(); // consume '!'
        if let Some('=') = self.peek_char() {
            self.advance();
            Ok(Token::new(TokenKind::Ne, "!=", start))
        } else {
            Err(self.lex_error(start, "Expected '=' after '!'".to_string()))
        }
    }

    // -----------------------------------------------------------------------
    // Slash (might be division, comments were already consumed)
    // -----------------------------------------------------------------------

    fn read_slash(&mut self, start: usize) -> Result<Token, CypherError> {
        self.advance(); // consume '/'
        Ok(Token::new(TokenKind::Slash, "/", start))
    }

    // -----------------------------------------------------------------------
    // String literals
    // -----------------------------------------------------------------------

    fn read_string(&mut self, start: usize) -> Result<Token, CypherError> {
        let (_, quote) = self.advance().unwrap(); // consume opening quote
        let mut value = String::new();

        loop {
            match self.advance() {
                Some((_, ch)) if ch == quote => {
                    // End of string
                    return Ok(Token::new(TokenKind::StringLiteral, value, start));
                }
                Some((_, '\\')) => {
                    // Escape sequence
                    match self.advance() {
                        Some((_, c)) if c == quote => value.push(c),
                        Some((_, '\\')) => value.push('\\'),
                        Some((_, 'n')) => value.push('\n'),
                        Some((_, 't')) => value.push('\t'),
                        Some((_, 'r')) => value.push('\r'),
                        Some((_, other)) => {
                            value.push('\\');
                            value.push(other);
                        }
                        None => {
                            return Err(
                                self.lex_error(start, "Unterminated string literal".to_string())
                            );
                        }
                    }
                }
                Some((_, ch)) => value.push(ch),
                None => {
                    return Err(self.lex_error(start, "Unterminated string literal".to_string()));
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // Parameters
    // -----------------------------------------------------------------------

    fn read_parameter(&mut self, start: usize) -> Result<Token, CypherError> {
        self.advance(); // consume '$'
        let mut name = String::new();
        while let Some(&(_, ch)) = self.chars.peek() {
            if ch.is_alphanumeric() || ch == '_' {
                name.push(ch);
                self.advance();
            } else {
                break;
            }
        }
        if name.is_empty() {
            return Err(self.lex_error(start, "Expected parameter name after '$'".to_string()));
        }
        Ok(Token::new(TokenKind::Parameter, name, start))
    }

    // -----------------------------------------------------------------------
    // Numbers
    // -----------------------------------------------------------------------

    fn read_number(&mut self, start: usize) -> Result<Token, CypherError> {
        let mut is_float = false;

        // Consume leading digits
        while let Some(&(_, ch)) = self.chars.peek() {
            if ch.is_ascii_digit() {
                self.advance();
            } else {
                break;
            }
        }

        // Check for decimal point followed by digit (not `..` which is DotDot)
        if let Some(&(_, '.')) = self.chars.peek() {
            let mut lookahead = self.chars.clone();
            lookahead.next(); // skip the '.'
            match lookahead.peek() {
                Some(&(_, ch)) if ch.is_ascii_digit() => {
                    is_float = true;
                    self.advance(); // consume '.'
                    while let Some(&(_, ch)) = self.chars.peek() {
                        if ch.is_ascii_digit() {
                            self.advance();
                        } else {
                            break;
                        }
                    }
                }
                // '.' followed by another '.' => DotDot, don't consume
                _ => {}
            }
        }

        let end = self
            .chars
            .peek()
            .map(|&(pos, _)| pos)
            .unwrap_or(self.input.len());
        let text = &self.input[start..end];

        let kind = if is_float {
            TokenKind::FloatLiteral
        } else {
            TokenKind::IntegerLiteral
        };
        Ok(Token::new(kind, text, start))
    }

    // -----------------------------------------------------------------------
    // Identifiers / Keywords
    // -----------------------------------------------------------------------

    fn read_identifier_or_keyword(&mut self, start: usize) -> Result<Token, CypherError> {
        while let Some(&(_, ch)) = self.chars.peek() {
            if ch.is_alphanumeric() || ch == '_' {
                self.advance();
            } else {
                break;
            }
        }

        let end = self
            .chars
            .peek()
            .map(|&(pos, _)| pos)
            .unwrap_or(self.input.len());
        let text = &self.input[start..end];

        let kind = match text.to_uppercase().as_str() {
            // Clauses
            "MATCH" => TokenKind::Match,
            "OPTIONAL" => TokenKind::OptionalMatch,
            "WHERE" => TokenKind::Where,
            "RETURN" => TokenKind::Return,
            "WITH" => TokenKind::With,
            "UNWIND" => TokenKind::Unwind,

            // Ordering / projection
            "ORDER" => TokenKind::Order,
            "BY" => TokenKind::By,
            "LIMIT" => TokenKind::Limit,
            "SKIP" => TokenKind::Skip,
            "AS" => TokenKind::As,
            "DISTINCT" => TokenKind::Distinct,

            // Logical
            "AND" => TokenKind::And,
            "OR" => TokenKind::Or,
            "NOT" => TokenKind::Not,
            "IN" => TokenKind::In,
            "IS" => TokenKind::Is,

            // Sort direction
            "ASC" => TokenKind::Asc,
            "DESC" => TokenKind::Desc,

            // Literals
            "TRUE" => TokenKind::True,
            "FALSE" => TokenKind::False,
            "NULL" => TokenKind::Null,

            // String predicates
            "CONTAINS" => TokenKind::Contains,
            "STARTS" => TokenKind::StartsWith,
            "ENDS" => TokenKind::EndsWith,

            // Aggregation
            "COUNT" => TokenKind::Count,
            "COLLECT" => TokenKind::Collect,
            "AVG" => TokenKind::Avg,
            "SUM" => TokenKind::Sum,
            "MIN" => TokenKind::Min,
            "MAX" => TokenKind::Max,

            // Temporal
            "OF" => TokenKind::Of,
            "TIMESTAMP" => TokenKind::Timestamp,
            "BETWEEN" => TokenKind::Between,
            "FOR" => TokenKind::For,
            "SYSTEM_TIME" => TokenKind::SystemTime,
            "VALID_TIME" => TokenKind::ValidTime,

            // Not a keyword
            _ => TokenKind::Identifier,
        };

        Ok(Token::new(kind, text, start))
    }
}

#[cfg(test)]
mod unit_tests {
    use super::*;

    #[test]
    fn keyword_lookup_exhaustive() {
        // Ensure every keyword string maps to a non-Identifier kind.
        let keywords = [
            "MATCH",
            "OPTIONAL",
            "WHERE",
            "RETURN",
            "WITH",
            "UNWIND",
            "ORDER",
            "BY",
            "LIMIT",
            "SKIP",
            "AS",
            "DISTINCT",
            "AND",
            "OR",
            "NOT",
            "IN",
            "IS",
            "ASC",
            "DESC",
            "TRUE",
            "FALSE",
            "NULL",
            "CONTAINS",
            "STARTS",
            "ENDS",
            "COUNT",
            "COLLECT",
            "AVG",
            "SUM",
            "MIN",
            "MAX",
            "OF",
            "TIMESTAMP",
            "BETWEEN",
            "FOR",
            "SYSTEM_TIME",
            "VALID_TIME",
        ];
        for kw in keywords {
            let tokens = CypherLexer::tokenize(kw).unwrap();
            assert_ne!(
                tokens[0].kind,
                TokenKind::Identifier,
                "{kw} should be a keyword, not an identifier"
            );
        }
    }
}