rustf 1.0.0

A simple MVC web framework inspired by Total.js
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
use std::fmt;

/// Token types for Total.js template syntax
#[derive(Debug, Clone, PartialEq)]
pub enum TokenKind {
    // Literals
    Text(String),

    // Variable interpolation
    Variable(String),    // @{variable}
    RawVariable(String), // @{!variable}

    // Control flow
    If(String),     // @{if condition}
    Else,           // @{else}
    ElseIf(String), // @{elif condition}
    Fi,             // @{fi}

    // Loops
    Foreach(String, String), // @{foreach item in collection}
    End,                     // @{end}
    Break,                   // @{break}
    Continue,                // @{continue}

    // Sections
    SectionDef(String),  // @{section name}
    SectionCall(String), // @{section('name')}

    // Helpers
    HelperDef(String, Vec<String>),  // @{helper name(args)}
    HelperCall(String, Vec<String>), // @{name(args)}

    // Views and imports
    View(String, Option<String>), // @{view('name', model)}
    Import(Vec<String>),          // @{import('file1', 'file2')}

    // Special directives
    Meta(Option<String>, Option<String>, Option<String>), // @{meta(title, desc, keywords)}
    Title(String),                                        // @{title('value')} - raw arg expression
    Description(String),       // @{description('value')} - raw arg expression
    FormField(String, String), // @{text|textarea|...(...)} - (kind, raw args inside parens)
    Body,                      // @{body} - Standard Total.js layout content placeholder
    Head,                      // @{head} - Additional head section content
    Content, // @{content} - Our extension, same as @{body} for backward compatibility
    Csrf,    // @{csrf}

    // Localization
    Translate(String),    // @(text)
    TranslateKey(String), // @(#key)

    // Configuration
    Config(String), // @{'%config-key'}

    // Special variables
    Repository(String),   // @{repository.key} or @{R.key}
    App(String),          // @{APP.key} - Global repository
    Main(String),         // @{MAIN.key} - Global repository (alias)
    R(String),            // @{R.key} - Context repository (alias)
    Model(String),        // @{model.key} - Model data
    M(String),            // @{M.key} - Model data (alias)
    Session(String),      // @{session.key}
    Query(String),        // @{query.key}
    User(Option<String>), // @{user} or @{user.property}

    // Utility
    Index, // @{index} in loops
    Newline,
    Eof,
}

#[derive(Debug, Clone)]
pub struct Token {
    pub kind: TokenKind,
    pub line: usize,
    pub column: usize,
}

impl Token {
    pub fn new(kind: TokenKind, line: usize, column: usize) -> Self {
        Self { kind, line, column }
    }
}

impl fmt::Display for Token {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?} at {}:{}", self.kind, self.line, self.column)
    }
}

/// Lexer for Total.js templates
pub struct Lexer {
    input: Vec<char>,
    position: usize,
    current_char: Option<char>,
    line: usize,
    column: usize,
}

impl Lexer {
    pub fn new(input: &str) -> Self {
        let chars: Vec<char> = input.chars().collect();
        let current_char = if chars.is_empty() {
            None
        } else {
            Some(chars[0])
        };

        Self {
            input: chars,
            position: 0,
            current_char,
            line: 1,
            column: 1,
        }
    }

    /// Advance to the next character
    fn advance(&mut self) {
        if self.current_char == Some('\n') {
            self.line += 1;
            self.column = 1;
        } else {
            self.column += 1;
        }

        self.position += 1;
        self.current_char = if self.position < self.input.len() {
            Some(self.input[self.position])
        } else {
            None
        };
    }

    /// Peek at the next character without advancing
    fn peek(&self) -> Option<char> {
        if self.position + 1 < self.input.len() {
            Some(self.input[self.position + 1])
        } else {
            None
        }
    }

    /// Peek ahead n characters
    #[allow(dead_code)]
    fn peek_n(&self, n: usize) -> Option<char> {
        if self.position + n < self.input.len() {
            Some(self.input[self.position + n])
        } else {
            None
        }
    }

    /// Check if we're at a Total.js directive start
    fn is_directive_start(&self) -> bool {
        self.current_char == Some('@') && (self.peek() == Some('{') || self.peek() == Some('('))
    }

    /// Skip whitespace
    fn skip_whitespace(&mut self) {
        while let Some(ch) = self.current_char {
            if ch.is_whitespace() && ch != '\n' {
                self.advance();
            } else {
                break;
            }
        }
    }

    /// Read until a specific character or pattern
    fn read_until(&mut self, delimiter: char) -> String {
        let mut result = String::new();
        let mut brace_depth = 0;

        while let Some(ch) = self.current_char {
            if ch == '{' {
                brace_depth += 1;
            } else if ch == '}' {
                if brace_depth == 0 && delimiter == '}' {
                    break;
                }
                brace_depth -= 1;
            } else if ch == delimiter && brace_depth == 0 {
                break;
            }

            result.push(ch);
            self.advance();
        }

        result
    }

    /// Read plain text until we hit a directive
    fn read_text(&mut self) -> String {
        let mut result = String::new();

        while let Some(ch) = self.current_char {
            if self.is_directive_start() {
                break;
            }

            result.push(ch);
            self.advance();
        }

        result
    }

    /// Parse a Total.js directive @{...}
    fn parse_directive(&mut self) -> Token {
        let line = self.line;
        let column = self.column;

        // Skip @{
        self.advance(); // @
        self.advance(); // {

        self.skip_whitespace();

        // Check for raw variable @{!...}
        if self.current_char == Some('!') {
            self.advance();
            let var_name = self.read_until('}').trim().to_string();
            self.advance(); // Skip }
            return Token::new(TokenKind::RawVariable(var_name), line, column);
        }

        // Read the directive content
        let content = self.read_until('}').trim().to_string();
        self.advance(); // Skip }

        // Parse the directive content
        let token_kind = self.parse_directive_content(&content);
        Token::new(token_kind, line, column)
    }

    /// Detect a top-level binary or ternary operator in directive content,
    /// ignoring anything inside quotes or parentheses. Used to route compound
    /// value expressions (e.g. `M.a || "default"`) to the parser's expression
    /// handling instead of the single-data-path token kinds.
    fn has_top_level_operator(expr: &str) -> bool {
        let chars: Vec<char> = expr.chars().collect();
        let mut paren_depth: i32 = 0;
        let mut in_quote = false;
        let mut quote_char = ' ';
        let mut i = 0;

        while i < chars.len() {
            let c = chars[i];

            // Track quotes (respecting backslash escapes)
            if (c == '"' || c == '\'') && (i == 0 || chars[i - 1] != '\\') {
                if !in_quote {
                    in_quote = true;
                    quote_char = c;
                } else if c == quote_char {
                    in_quote = false;
                }
                i += 1;
                continue;
            }
            if in_quote {
                i += 1;
                continue;
            }

            // Track parentheses
            if c == '(' {
                paren_depth += 1;
                i += 1;
                continue;
            }
            if c == ')' {
                paren_depth -= 1;
                i += 1;
                continue;
            }

            if paren_depth == 0 {
                // Ternary
                if c == '?' {
                    return true;
                }
                // Single-char arithmetic / comparison operators
                if matches!(c, '+' | '*' | '/' | '%' | '<' | '>') {
                    return true;
                }
                // Two-char operators
                if i + 1 < chars.len() {
                    let next = chars[i + 1];
                    if (c == '=' && next == '=')
                        || (c == '!' && next == '=')
                        || (c == '<' && next == '=')
                        || (c == '>' && next == '=')
                        || (c == '&' && next == '&')
                        || (c == '|' && next == '|')
                    {
                        return true;
                    }
                }
            }

            i += 1;
        }

        false
    }

    /// Parse the content of a directive to determine its type
    fn parse_directive_content(&self, content: &str) -> TokenKind {
        let trimmed = content.trim();

        // Control flow
        if trimmed.starts_with("if ") {
            let condition = trimmed[3..].trim().to_string();
            return TokenKind::If(condition);
        }

        if trimmed == "else" {
            return TokenKind::Else;
        }

        if trimmed.starts_with("elif ") {
            let condition = trimmed[5..].trim().to_string();
            return TokenKind::ElseIf(condition);
        }

        if trimmed == "fi" {
            return TokenKind::Fi;
        }

        // Loops
        if trimmed.starts_with("foreach ") {
            let parts = trimmed[8..].trim();
            if let Some(in_pos) = parts.find(" in ") {
                let item = parts[..in_pos].trim().to_string();
                let collection = parts[in_pos + 4..].trim().to_string();
                return TokenKind::Foreach(item, collection);
            }
        }

        if trimmed == "end" {
            return TokenKind::End;
        }

        if trimmed == "break" {
            return TokenKind::Break;
        }

        if trimmed == "continue" {
            return TokenKind::Continue;
        }

        if trimmed == "index" {
            return TokenKind::Index;
        }

        // Sections
        if trimmed.starts_with("section ") {
            let name = trimmed[8..].trim().to_string();
            return TokenKind::SectionDef(name);
        }

        if trimmed.starts_with("section(") && trimmed.ends_with(')') {
            let name = trimmed[8..trimmed.len() - 1]
                .trim_matches('\'')
                .trim_matches('"')
                .to_string();
            return TokenKind::SectionCall(name);
        }

        // Helpers
        if trimmed.starts_with("helper ") {
            if let Some(paren_pos) = trimmed.find('(') {
                let name = trimmed[7..paren_pos].trim().to_string();
                let args_str = &trimmed[paren_pos + 1..trimmed.len() - 1];
                let args = self.parse_args(args_str);
                return TokenKind::HelperDef(name, args);
            }
        }

        // Views
        if trimmed.starts_with("view(") && trimmed.ends_with(')') {
            let args_str = &trimmed[5..trimmed.len() - 1];
            let parts: Vec<&str> = args_str.split(',').collect();
            let view_name = parts[0].trim_matches('\'').trim_matches('"').to_string();
            let model = if parts.len() > 1 {
                Some(parts[1].trim().to_string())
            } else {
                None
            };
            return TokenKind::View(view_name, model);
        }

        // Import
        if trimmed.starts_with("import(") && trimmed.ends_with(')') {
            let args_str = &trimmed[7..trimmed.len() - 1];
            let files = self.parse_string_args(args_str);
            return TokenKind::Import(files);
        }

        // Meta
        if trimmed.starts_with("meta") {
            if trimmed == "meta" {
                return TokenKind::Meta(None, None, None);
            }
            if trimmed.starts_with("meta(") && trimmed.ends_with(')') {
                let args_str = &trimmed[5..trimmed.len() - 1];
                let parts = self.parse_string_args(args_str);
                let title = parts.first().cloned();
                let desc = parts.get(1).cloned();
                let keywords = parts.get(2).cloned();
                return TokenKind::Meta(title, desc, keywords);
            }
        }

        // Page title setter: @{title('value')} — keeps the raw argument so the
        // parser can evaluate it as an expression (string literal, variable...).
        if trimmed.starts_with("title(") && trimmed.ends_with(')') {
            let arg = trimmed[6..trimmed.len() - 1].trim().to_string();
            return TokenKind::Title(arg);
        }

        // Description meta setter: @{description('value')} (deferred, like title)
        if trimmed.starts_with("description(") && trimmed.ends_with(')') {
            let arg = trimmed[12..trimmed.len() - 1].trim().to_string();
            return TokenKind::Description(arg);
        }

        // Form-input helpers. Keep the raw argument list; the parser splits it
        // into field name + (value) + (label) + attribute object per helper.
        for kind in [
            "text", "password", "hidden", "textarea", "checkbox", "radio",
        ] {
            let prefix = format!("{}(", kind);
            if trimmed.starts_with(&prefix) && trimmed.ends_with(')') {
                let args = trimmed[prefix.len()..trimmed.len() - 1].trim().to_string();
                return TokenKind::FormField(kind.to_string(), args);
            }
        }

        // Special directives
        if trimmed == "body" {
            return TokenKind::Body;
        }

        if trimmed == "head" {
            return TokenKind::Head;
        }

        if trimmed == "content" {
            return TokenKind::Content;
        }

        if trimmed == "csrf" {
            return TokenKind::Csrf;
        }

        // Compound value expressions: when the content contains a top-level
        // binary or ternary operator (e.g. `M.a || "default"`, `x > 0 ? a : b`),
        // emit a generic Variable token so the parser evaluates it as a full
        // expression instead of short-circuiting to a single data path below.
        if Self::has_top_level_operator(trimmed) {
            return TokenKind::Variable(trimmed.to_string());
        }

        // Special variables with dot notation
        // Global repository (APP or MAIN)
        if trimmed.starts_with("APP.") {
            let key = trimmed[4..].to_string();
            return TokenKind::App(key);
        }

        if trimmed.starts_with("MAIN.") {
            let key = trimmed[5..].to_string();
            return TokenKind::Main(key);
        }

        // Context repository (repository or R)
        if trimmed.starts_with("repository.") {
            let key = trimmed[11..].to_string();
            return TokenKind::Repository(key);
        }

        if trimmed.starts_with("R.") {
            let key = trimmed[2..].to_string();
            return TokenKind::R(key);
        }

        // Model data (model)
        if trimmed.starts_with("model.") {
            let key = trimmed[6..].to_string();
            return TokenKind::Model(key);
        }

        // Model data (M - alias)
        if trimmed.starts_with("M.") {
            let key = trimmed[2..].to_string();
            return TokenKind::M(key);
        }

        if trimmed.starts_with("session.") {
            let key = trimmed[8..].to_string();
            return TokenKind::Session(key);
        }

        if trimmed.starts_with("query.") {
            let key = trimmed[6..].to_string();
            return TokenKind::Query(key);
        }

        if trimmed == "user" {
            return TokenKind::User(None);
        }

        if trimmed.starts_with("user.") {
            let property = trimmed[5..].to_string();
            return TokenKind::User(Some(property));
        }

        // Configuration variables
        if trimmed.starts_with('\'') && trimmed.ends_with('\'') {
            let inner = &trimmed[1..trimmed.len() - 1];
            if inner.starts_with('%') {
                let config_key = inner[1..].to_string();
                return TokenKind::Config(config_key);
            }
        }

        // Helper function calls
        if let Some(paren_pos) = trimmed.find('(') {
            if trimmed.ends_with(')') {
                let name = trimmed[..paren_pos].trim().to_string();
                let args_str = &trimmed[paren_pos + 1..trimmed.len() - 1];
                let args = self.parse_args(args_str);
                return TokenKind::HelperCall(name, args);
            }
        }

        // Default: treat as variable
        TokenKind::Variable(trimmed.to_string())
    }

    /// Parse a localization directive @(...)
    fn parse_localization(&mut self) -> Token {
        let line = self.line;
        let column = self.column;

        // Skip @(
        self.advance(); // @
        self.advance(); // (

        self.skip_whitespace();

        // Check for key reference @(#key)
        if self.current_char == Some('#') {
            self.advance();
            let key = self.read_until(')').trim().to_string();
            self.advance(); // Skip )
            return Token::new(TokenKind::TranslateKey(key), line, column);
        }

        // Regular translation
        let text = self.read_until(')').trim().to_string();
        self.advance(); // Skip )

        Token::new(TokenKind::Translate(text), line, column)
    }

    /// Parse comma-separated arguments
    fn parse_args(&self, args_str: &str) -> Vec<String> {
        args_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect()
    }

    /// Parse comma-separated string arguments (removes quotes)
    fn parse_string_args(&self, args_str: &str) -> Vec<String> {
        args_str
            .split(',')
            .map(|s| s.trim().trim_matches('\'').trim_matches('"').to_string())
            .filter(|s| !s.is_empty())
            .collect()
    }

    /// Get the next token
    pub fn next_token(&mut self) -> Token {
        // Check for EOF
        if self.current_char.is_none() {
            return Token::new(TokenKind::Eof, self.line, self.column);
        }

        // Check for newline
        if self.current_char == Some('\n') {
            let token = Token::new(TokenKind::Newline, self.line, self.column);
            self.advance();
            return token;
        }

        // Check for Total.js directives
        if self.current_char == Some('@') {
            if self.peek() == Some('{') {
                return self.parse_directive();
            } else if self.peek() == Some('(') {
                return self.parse_localization();
            }
        }

        // Otherwise, read as plain text
        let text = self.read_text();
        if !text.is_empty() {
            Token::new(TokenKind::Text(text), self.line, self.column)
        } else {
            // This shouldn't happen, but handle gracefully
            self.advance();
            self.next_token()
        }
    }

    /// Tokenize the entire input
    pub fn tokenize(&mut self) -> Vec<Token> {
        let mut tokens = Vec::new();

        loop {
            let token = self.next_token();
            if token.kind == TokenKind::Eof {
                tokens.push(token);
                break;
            }
            tokens.push(token);
        }

        tokens
    }
}

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

    #[test]
    fn test_basic_text() {
        let mut lexer = Lexer::new("Hello World");
        let tokens = lexer.tokenize();

        assert_eq!(tokens.len(), 2);
        match &tokens[0].kind {
            TokenKind::Text(t) => assert_eq!(t, "Hello World"),
            _ => panic!("Expected text token"),
        }
    }

    #[test]
    fn test_variable() {
        let mut lexer = Lexer::new("Hello @{name}!");
        let tokens = lexer.tokenize();

        assert_eq!(tokens.len(), 4);
        match &tokens[1].kind {
            TokenKind::Variable(v) => assert_eq!(v, "name"),
            _ => panic!("Expected variable token"),
        }
    }

    #[test]
    fn test_raw_variable() {
        let mut lexer = Lexer::new("@{!htmlContent}");
        let tokens = lexer.tokenize();

        match &tokens[0].kind {
            TokenKind::RawVariable(v) => assert_eq!(v, "htmlContent"),
            _ => panic!("Expected raw variable token"),
        }
    }

    #[test]
    fn test_if_else() {
        let mut lexer = Lexer::new("@{if user.isActive}\nActive\n@{else}\nInactive\n@{fi}");
        let tokens = lexer.tokenize();

        // Verify the if token
        match &tokens[0].kind {
            TokenKind::If(cond) => assert_eq!(cond, "user.isActive"),
            _ => panic!("Expected if token"),
        }

        // Find and verify the Else token
        let else_pos = tokens
            .iter()
            .position(|t| matches!(t.kind, TokenKind::Else))
            .expect("Should have an Else token");
        assert!(matches!(tokens[else_pos].kind, TokenKind::Else));

        // Find and verify the Fi token
        let fi_pos = tokens
            .iter()
            .position(|t| matches!(t.kind, TokenKind::Fi))
            .expect("Should have a Fi token");
        assert!(matches!(tokens[fi_pos].kind, TokenKind::Fi));
    }

    #[test]
    fn test_foreach() {
        let mut lexer = Lexer::new("@{foreach item in items}\n@{item.name}\n@{end}");
        let tokens = lexer.tokenize();

        match &tokens[0].kind {
            TokenKind::Foreach(item, collection) => {
                assert_eq!(item, "item");
                assert_eq!(collection, "items");
            }
            _ => panic!("Expected foreach token"),
        }
    }

    #[test]
    fn test_section() {
        let mut lexer = Lexer::new("@{section header}\nHeader content\n@{end}");
        let tokens = lexer.tokenize();

        match &tokens[0].kind {
            TokenKind::SectionDef(name) => assert_eq!(name, "header"),
            _ => panic!("Expected section definition token"),
        }
    }

    #[test]
    fn test_view() {
        let mut lexer = Lexer::new("@{view('partial', model)}");
        let tokens = lexer.tokenize();

        match &tokens[0].kind {
            TokenKind::View(name, model) => {
                assert_eq!(name, "partial");
                assert_eq!(model.as_ref().unwrap(), "model");
            }
            _ => panic!("Expected view token"),
        }
    }

    #[test]
    fn test_import() {
        let mut lexer = Lexer::new("@{import('style.css', 'script.js')}");
        let tokens = lexer.tokenize();

        match &tokens[0].kind {
            TokenKind::Import(files) => {
                assert_eq!(files.len(), 2);
                assert_eq!(files[0], "style.css");
                assert_eq!(files[1], "script.js");
            }
            _ => panic!("Expected import token"),
        }
    }

    #[test]
    fn test_localization() {
        let mut lexer = Lexer::new("@(Hello World)");
        let tokens = lexer.tokenize();

        match &tokens[0].kind {
            TokenKind::Translate(text) => assert_eq!(text, "Hello World"),
            _ => panic!("Expected translate token"),
        }
    }

    #[test]
    fn test_localization_key() {
        let mut lexer = Lexer::new("@(#welcome.message)");
        let tokens = lexer.tokenize();

        match &tokens[0].kind {
            TokenKind::TranslateKey(key) => assert_eq!(key, "welcome.message"),
            _ => panic!("Expected translate key token"),
        }
    }

    #[test]
    fn test_special_variables() {
        let mut lexer = Lexer::new("@{repository.data} @{session.user} @{query.page}");
        let tokens = lexer.tokenize();

        // Filter out text/whitespace tokens to find the special tokens
        let special_tokens: Vec<_> = tokens
            .iter()
            .filter(|t| !matches!(t.kind, TokenKind::Text(_) | TokenKind::Eof))
            .collect();

        match &special_tokens[0].kind {
            TokenKind::Repository(key) => assert_eq!(key, "data"),
            _ => panic!(
                "Expected repository token, got {:?}",
                special_tokens[0].kind
            ),
        }

        match &special_tokens[1].kind {
            TokenKind::Session(key) => assert_eq!(key, "user"),
            _ => panic!("Expected session token, got {:?}", special_tokens[1].kind),
        }

        match &special_tokens[2].kind {
            TokenKind::Query(key) => assert_eq!(key, "page"),
            _ => panic!("Expected query token, got {:?}", special_tokens[2].kind),
        }
    }
}