fel-core 0.3.0

Formspec Expression Language — parser, evaluator, and dependency analysis
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! FEL hand-rolled lexer — tokenization with spans and decimal numbers.
//!
//! Internal scanning uses a char buffer and cursor; [`Lexer::tokenize`] is the public entry point.
#![allow(clippy::missing_docs_in_private_items)]
use rust_decimal::Decimal;
use rust_decimal::prelude::*;

use crate::error::ParseError;

/// Lexical token for FEL source (literals, keywords, operators, punctuation).
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
    // Literals
    /// Decimal number literal.
    Number(Decimal),
    /// String literal (content without surrounding quotes).
    StringLit(String),
    /// Boolean `true`.
    True,
    /// Boolean `false`.
    False,
    /// `null` literal.
    Null,
    /// Date literal (`@YYYY-MM-DD`).
    DateLiteral(String),
    /// Date-time literal (`@YYYY-MM-DDTHH:MM:SS`).
    DateTimeLiteral(String),

    // Identifiers and keywords
    /// Unclassified name or function identifier.
    Identifier(String),
    /// `let` keyword.
    Let,
    /// `in` keyword (let binding body delimiter).
    In,
    /// `if` keyword.
    If,
    /// `then` keyword.
    Then,
    /// `else` keyword.
    Else,
    /// `and` keyword.
    And,
    /// `or` keyword.
    Or,
    /// `not` keyword.
    Not,
    /// `!` prefix (not followed by `=`). Semantically identical to `Not`
    /// but tracked separately for round-trip printer fidelity.
    Bang,

    // Operators
    /// `+` addition.
    Plus,
    /// `-` subtraction / negation.
    Minus,
    /// `*` multiplication.
    Star,
    /// `/` division.
    Slash,
    /// `%` modulo.
    Percent,
    /// `&` string concatenation.
    Ampersand,
    /// `=` or `==` equality.
    Eq,
    /// `!=` inequality.
    NotEq,
    /// `<` less-than.
    Lt,
    /// `>` greater-than.
    Gt,
    /// `<=` less-than-or-equal.
    LtEq,
    /// `>=` greater-than-or-equal.
    GtEq,
    /// `??` null-coalescing operator.
    DoubleQuestion,
    /// `?` conditional (ternary) operator.
    Question,

    // Punctuation
    /// `(` open parenthesis.
    LParen,
    /// `)` close parenthesis.
    RParen,
    /// `[` open bracket.
    LBracket,
    /// `]` close bracket.
    RBracket,
    /// `{` open brace.
    LBrace,
    /// `}` close brace.
    RBrace,
    /// `,` comma separator.
    Comma,
    /// `.` member-access dot.
    Dot,
    /// `:` key-value colon.
    Colon,

    // Special
    /// `$` field reference prefix.
    Dollar,
    /// `@` context reference prefix.
    At,

    // End
    /// End-of-input sentinel.
    Eof,
}

/// Byte/char span in the original source (Unicode scalar indices, inclusive start, exclusive end).
#[derive(Debug, Clone)]
pub struct Span {
    /// Start offset.
    pub start: usize,
    /// End offset (exclusive).
    pub end: usize,
}

/// A [`Token`] with its [`Span`].
#[derive(Debug, Clone)]
pub struct SpannedToken {
    /// Classified token.
    pub token: Token,
    /// Position in source.
    pub span: Span,
}

/// Character-based lexer over a FEL expression string.
pub struct Lexer<'a> {
    _input: &'a str,
    chars: Vec<char>,
    pos: usize,
}

impl<'a> Lexer<'a> {
    /// Create a lexer for `input` (no allocation beyond char buffer).
    pub fn new(input: &'a str) -> Self {
        Lexer {
            _input: input,
            chars: input.chars().collect(),
            pos: 0,
        }
    }

    /// Consume the entire input and return all tokens, ending with [`Token::Eof`].
    pub fn tokenize(&mut self) -> Result<Vec<SpannedToken>, ParseError> {
        let mut tokens = Vec::new();
        loop {
            self.skip_whitespace_and_comments()?;
            if self.pos >= self.chars.len() {
                tokens.push(SpannedToken {
                    token: Token::Eof,
                    span: Span {
                        start: self.pos,
                        end: self.pos,
                    },
                });
                break;
            }
            let start = self.pos;
            let token = self.next_token()?;
            tokens.push(SpannedToken {
                token,
                span: Span {
                    start,
                    end: self.pos,
                },
            });
        }
        Ok(tokens)
    }

    fn peek(&self) -> Option<char> {
        self.chars.get(self.pos).copied()
    }

    fn peek_at(&self, offset: usize) -> Option<char> {
        self.chars.get(self.pos + offset).copied()
    }

    fn advance(&mut self) -> Option<char> {
        let c = self.chars.get(self.pos).copied();
        if c.is_some() {
            self.pos += 1;
        }
        c
    }

    fn skip_whitespace_and_comments(&mut self) -> Result<(), ParseError> {
        let len = self.chars.len();
        loop {
            // Skip whitespace
            while self.pos < len && self.chars[self.pos].is_whitespace() {
                self.pos += 1;
            }
            // Skip line comments
            if self.pos + 1 < len && self.chars[self.pos] == '/' && self.chars[self.pos + 1] == '/'
            {
                while self.pos < len && self.chars[self.pos] != '\n' {
                    self.pos += 1;
                }
                continue;
            }
            // Skip block comments
            if self.pos + 1 < len && self.chars[self.pos] == '/' && self.chars[self.pos + 1] == '*'
            {
                let start = self.pos;
                self.pos += 2;
                let mut closed = false;
                while self.pos + 1 < len {
                    if self.chars[self.pos] == '*' && self.chars[self.pos + 1] == '/' {
                        self.pos += 2;
                        closed = true;
                        break;
                    }
                    self.pos += 1;
                }
                if !closed {
                    let end = self.pos.min(len);
                    return Err(ParseError::with_span(
                        start..end,
                        format!("unterminated block comment at position {start}"),
                    ));
                }
                continue;
            }
            break;
        }
        Ok(())
    }

    fn next_token(&mut self) -> Result<Token, ParseError> {
        let c = self.peek().unwrap();

        // Date/DateTime literals: @YYYY-...
        if c == '@' && self.is_date_literal_ahead() {
            return self.read_date_literal();
        }

        // Number literals (unary minus is handled by the parser).
        if c.is_ascii_digit() {
            return self.read_number();
        }

        // String literals
        if c == '"' || c == '\'' {
            return self.read_string(c);
        }

        // Identifiers and keywords
        if c.is_ascii_alphabetic() || c == '_' {
            return self.read_identifier();
        }

        // Operators and punctuation
        self.advance();
        match c {
            '+' => Ok(Token::Plus),
            '-' => Ok(Token::Minus),
            '*' => Ok(Token::Star),
            '/' => Ok(Token::Slash),
            '%' => Ok(Token::Percent),
            '&' => Ok(Token::Ampersand),
            '(' => Ok(Token::LParen),
            ')' => Ok(Token::RParen),
            '[' => Ok(Token::LBracket),
            ']' => Ok(Token::RBracket),
            '{' => Ok(Token::LBrace),
            '}' => Ok(Token::RBrace),
            ',' => Ok(Token::Comma),
            '.' => Ok(Token::Dot),
            ':' => Ok(Token::Colon),
            '$' => Ok(Token::Dollar),
            '@' => Ok(Token::At),
            '?' => {
                if self.peek() == Some('?') {
                    self.advance();
                    Ok(Token::DoubleQuestion)
                } else {
                    Ok(Token::Question)
                }
            }
            '=' => {
                if self.peek() == Some('=') {
                    self.advance();
                }
                Ok(Token::Eq)
            }
            '!' => {
                if self.peek() == Some('=') {
                    self.advance();
                    Ok(Token::NotEq)
                } else {
                    Ok(Token::Bang)
                }
            }
            '<' => {
                if self.peek() == Some('=') {
                    self.advance();
                    Ok(Token::LtEq)
                } else {
                    Ok(Token::Lt)
                }
            }
            '>' => {
                if self.peek() == Some('=') {
                    self.advance();
                    Ok(Token::GtEq)
                } else {
                    Ok(Token::Gt)
                }
            }
            '|' => {
                if self.peek() == Some('>') {
                    self.advance();
                    let pos = self.pos - 2;
                    Err(ParseError::with_span(
                        pos..self.pos,
                        format!("pipe operator `|>` is reserved for future use at position {pos}"),
                    ))
                } else {
                    let pos = self.pos - 1;
                    Err(ParseError::with_span(
                        pos..self.pos,
                        format!("unexpected character '|' at position {pos}"),
                    ))
                }
            }
            _ => {
                let pos = self.pos - 1;
                Err(ParseError::with_span(
                    pos..self.pos,
                    format!("unexpected character '{c}' at position {pos}"),
                ))
            }
        }
    }

    fn is_date_literal_ahead(&self) -> bool {
        // Fixed-width probe for `@YYYY-MM-DD` without heap allocation.
        if self.pos + 11 > self.chars.len() {
            return false;
        }
        let s = &self.chars[self.pos..self.pos + 11];
        s[0] == '@'
            && s[1..5].iter().all(|c| c.is_ascii_digit())
            && s[5] == '-'
            && s[6..8].iter().all(|c| c.is_ascii_digit())
            && s[8] == '-'
            && s[9..11].iter().all(|c| c.is_ascii_digit())
    }

    fn read_date_literal(&mut self) -> Result<Token, ParseError> {
        let start = self.pos;
        self.advance(); // skip @
        // Read YYYY-MM-DD
        for _ in 0..10 {
            self.advance();
        }
        // Check for T (datetime)
        if self.peek() == Some('T') {
            self.advance(); // T
            // Read HH:MM:SS
            for _ in 0..8 {
                self.advance();
            }
            // Optional timezone
            match self.peek() {
                Some('Z') => {
                    self.advance();
                }
                Some('+') | Some('-') if self.peek_at(1).is_some_and(|c| c.is_ascii_digit()) => {
                    self.advance(); // sign
                    for _ in 0..5 {
                        // HH:MM
                        self.advance();
                    }
                }
                _ => {}
            }
            let s: String = self.chars[start..self.pos].iter().collect();
            Ok(Token::DateTimeLiteral(s))
        } else {
            let s: String = self.chars[start..self.pos].iter().collect();
            Ok(Token::DateLiteral(s))
        }
    }

    fn read_number(&mut self) -> Result<Token, ParseError> {
        let start = self.pos;
        // Optional minus
        if self.peek() == Some('-') {
            self.advance();
        }
        // Integer part
        while self.peek().is_some_and(|c| c.is_ascii_digit()) {
            self.advance();
        }
        // Fractional part
        if self.peek() == Some('.') && self.peek_at(1).is_some_and(|c| c.is_ascii_digit()) {
            self.advance(); // .
            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
                self.advance();
            }
        }
        // Exponent
        if self.peek().is_some_and(|c| c == 'e' || c == 'E') {
            self.advance();
            if self.peek().is_some_and(|c| c == '+' || c == '-') {
                self.advance();
            }
            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
                self.advance();
            }
        }
        let s: String = self.chars[start..self.pos].iter().collect();
        // Decimal doesn't parse scientific notation (e.g. 1e3) directly.
        // Try Decimal first; fall back through f64 for E notation.
        let n: Decimal = s
            .parse()
            .or_else(|_| s.parse::<f64>().ok().and_then(Decimal::from_f64).ok_or(()))
            .map_err(|_| {
                ParseError::with_span(
                    start..self.pos,
                    format!("invalid number '{s}' at position {start}"),
                )
            })?;
        Ok(Token::Number(n))
    }

    fn read_string(&mut self, quote: char) -> Result<Token, ParseError> {
        let open_start = self.pos;
        self.advance(); // skip opening quote
        let mut result = String::new();
        loop {
            match self.advance() {
                None => {
                    return Err(ParseError::with_span(
                        open_start..self.pos,
                        "unterminated string".to_string(),
                    ));
                }
                Some(c) if c == quote => return Ok(Token::StringLit(result)),
                Some('\\') => {
                    let esc_pos = self.pos - 1; // position of the backslash
                    match self.advance() {
                        Some('n') => result.push('\n'),
                        Some('t') => result.push('\t'),
                        Some('r') => result.push('\r'),
                        Some('\\') => result.push('\\'),
                        Some('"') => result.push('"'),
                        Some('\'') => result.push('\''),
                        Some('u') => {
                            let mut hex = String::with_capacity(4);
                            for _ in 0..4 {
                                match self.peek() {
                                    Some(h) if h.is_ascii_hexdigit() => {
                                        hex.push(h);
                                        self.advance();
                                    }
                                    _ => {
                                        return Err(ParseError::with_span(
                                            esc_pos..self.pos,
                                            format!(
                                                "invalid unicode escape '\\u{hex}' at position {esc_pos}: expected 4 hex digits"
                                            ),
                                        ));
                                    }
                                }
                            }
                            let cp = u32::from_str_radix(&hex, 16).unwrap();
                            match char::from_u32(cp) {
                                Some(ch) => result.push(ch),
                                None => {
                                    return Err(ParseError::with_span(
                                        esc_pos..self.pos,
                                        format!(
                                            "invalid unicode codepoint '\\u{hex}' at position {esc_pos}"
                                        ),
                                    ));
                                }
                            }
                        }
                        Some(c) => {
                            return Err(ParseError::with_span(
                                esc_pos..self.pos,
                                format!(
                                    "unrecognized escape sequence '\\{c}' at position {esc_pos}"
                                ),
                            ));
                        }
                        None => {
                            return Err(ParseError::with_span(
                                esc_pos..self.pos,
                                "unterminated string escape".to_string(),
                            ));
                        }
                    }
                }
                Some(c) => result.push(c),
            }
        }
    }

    fn read_identifier(&mut self) -> Result<Token, ParseError> {
        let start = self.pos;
        while self
            .peek()
            .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_')
        {
            self.advance();
        }
        let word: String = self.chars[start..self.pos].iter().collect();
        Ok(match word.as_str() {
            "true" => Token::True,
            "false" => Token::False,
            "null" => Token::Null,
            "let" => Token::Let,
            "in" => Token::In,
            "if" => Token::If,
            "then" => Token::Then,
            "else" => Token::Else,
            "and" => Token::And,
            "or" => Token::Or,
            "not" => Token::Not,
            _ => Token::Identifier(word),
        })
    }
}

/// FEL reserved keywords — identifiers that cannot be used as field/variable names.
const FEL_KEYWORDS: &[&str] = &[
    "true", "false", "null", "let", "in", "if", "then", "else", "and", "or", "not",
];

/// Returns `true` if `s` is a valid FEL identifier: `[a-zA-Z_][a-zA-Z0-9_]*` and not a reserved keyword.
pub fn is_valid_fel_identifier(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    let mut chars = s.chars();
    let first = chars.next().unwrap();
    if !first.is_ascii_alphabetic() && first != '_' {
        return false;
    }
    if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
        return false;
    }
    !FEL_KEYWORDS.contains(&s)
}

/// Sanitizes a string into a valid FEL identifier.
///
/// - Strips characters that aren't ASCII alphanumeric or underscore.
/// - Prepends `_` if the result starts with a digit.
/// - Appends `_` if the result is a reserved keyword.
/// - Returns `"_"` for an empty or all-invalid input.
pub fn sanitize_fel_identifier(s: &str) -> String {
    let mut result: String = s
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
        .collect();
    if result.is_empty() {
        return "_".to_string();
    }
    if result.chars().next().unwrap().is_ascii_digit() {
        result.insert(0, '_');
    }
    if FEL_KEYWORDS.contains(&result.as_str()) {
        result.push('_');
    }
    result
}

/// One lexeme from [`tokenize`] for host bindings and tooling (stable type names + source span).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PositionedToken {
    /// Logical token kind (e.g. `NumberLiteral`, `Identifier`).
    pub token_type: String,
    /// Lexeme text from the source.
    pub text: String,
    /// Start offset in Unicode scalar indices.
    pub start: usize,
    /// End offset (exclusive) in Unicode scalar indices.
    pub end: usize,
}

fn token_type_name(token: &Token) -> &'static str {
    match token {
        Token::Number(_) => "NumberLiteral",
        Token::StringLit(_) => "StringLiteral",
        Token::True => "True",
        Token::False => "False",
        Token::Null => "Null",
        Token::DateLiteral(_) => "DateLiteral",
        Token::DateTimeLiteral(_) => "DateTimeLiteral",
        Token::Identifier(_) => "Identifier",
        Token::Let => "Let",
        Token::In => "In",
        Token::If => "If",
        Token::Then => "Then",
        Token::Else => "Else",
        Token::And => "And",
        Token::Or => "Or",
        Token::Not => "Not",
        Token::Bang => "Bang",
        Token::Plus => "Plus",
        Token::Minus => "Minus",
        Token::Star => "Asterisk",
        Token::Slash => "Slash",
        Token::Percent => "Percent",
        Token::Ampersand => "Ampersand",
        Token::Eq => "Equals",
        Token::NotEq => "NotEquals",
        Token::Lt => "Less",
        Token::Gt => "Greater",
        Token::LtEq => "LessEqual",
        Token::GtEq => "GreaterEqual",
        Token::DoubleQuestion => "DoubleQuestion",
        Token::Question => "Question",
        Token::LParen => "LRound",
        Token::RParen => "RRound",
        Token::LBracket => "LSquare",
        Token::RBracket => "RSquare",
        Token::LBrace => "LCurly",
        Token::RBrace => "RCurly",
        Token::Comma => "Comma",
        Token::Dot => "Dot",
        Token::Colon => "Colon",
        Token::Dollar => "Dollar",
        Token::At => "At",
        Token::Eof => "EOF",
    }
}

fn slice_by_char_offsets(input: &str, start: usize, end: usize) -> String {
    input
        .chars()
        .skip(start)
        .take(end.saturating_sub(start))
        .collect()
}

/// Tokenizes FEL source into [`PositionedToken`]s (lexical analysis only; no parse).
pub fn tokenize(input: &str) -> Result<Vec<PositionedToken>, String> {
    let mut lexer = Lexer::new(input);
    let tokens = lexer.tokenize().map_err(|e| e.to_string())?;
    Ok(tokens
        .into_iter()
        .map(|token| PositionedToken {
            token_type: token_type_name(&token.token).to_string(),
            text: slice_by_char_offsets(input, token.span.start, token.span.end),
            start: token.span.start,
            end: token.span.end,
        })
        .collect())
}

/// FEL lexer tokens as JSON for host bindings (default `camelCase`).
pub fn tokenize_to_json_value(input: &str) -> Result<serde_json::Value, String> {
    tokenize_to_json_value_styled(input, crate::wire_style::JsonWireStyle::JsCamel)
}

/// FEL lexer tokens as JSON with configurable key style.
pub fn tokenize_to_json_value_styled(
    input: &str,
    style: crate::wire_style::JsonWireStyle,
) -> Result<serde_json::Value, String> {
    let tokens = tokenize(input)?;
    Ok(serde_json::Value::Array(
        tokens
            .into_iter()
            .map(|token| match style {
                crate::wire_style::JsonWireStyle::JsCamel => serde_json::json!({
                    "tokenType": token.token_type,
                    "text": token.text,
                    "start": token.start,
                    "end": token.end,
                }),
                crate::wire_style::JsonWireStyle::PythonSnake => serde_json::json!({
                    "token_type": token.token_type,
                    "text": token.text,
                    "start": token.start,
                    "end": token.end,
                }),
            })
            .collect(),
    ))
}

#[cfg(test)]
mod tests {
    #![allow(clippy::missing_docs_in_private_items)]
    use super::*;

    fn lex_string(input: &str) -> Result<Vec<Token>, String> {
        let mut lexer = Lexer::new(input);
        lexer
            .tokenize()
            .map(|tokens| tokens.into_iter().map(|st| st.token).collect())
            .map_err(|e| e.to_string())
    }

    #[test]
    fn test_unicode_escape_basic() {
        let tokens = lex_string(r#""\u0041""#).unwrap();
        assert_eq!(tokens[0], Token::StringLit("A".into()));
    }

    #[test]
    fn test_unicode_escape_multibyte() {
        // \u00E9 = e-acute
        let tokens = lex_string(r#""\u00E9""#).unwrap();
        assert_eq!(tokens[0], Token::StringLit("\u{00E9}".into()));
    }

    #[test]
    fn test_unicode_escape_too_few_hex_digits() {
        let err = lex_string(r#""\u00G1""#).unwrap_err();
        assert!(err.contains("invalid unicode escape"), "got: {err}");
    }

    #[test]
    fn test_unicode_escape_no_digits() {
        let err = lex_string(r#""\u""#).unwrap_err();
        assert!(err.contains("invalid unicode escape"), "got: {err}");
    }

    #[test]
    fn test_unrecognized_escape_error() {
        let err = lex_string(r#""\q""#).unwrap_err();
        assert!(
            err.contains("unrecognized escape sequence '\\q'"),
            "got: {err}"
        );
    }

    #[test]
    fn test_slash_escape_removed() {
        // \/ is no longer a valid escape
        let err = lex_string(r#""\/""#).unwrap_err();
        assert!(err.contains("unrecognized escape sequence"), "got: {err}");
    }

    #[test]
    fn test_valid_escapes_still_work() {
        let tokens = lex_string(r#""a\nb\tc\\d\"e\'f""#).unwrap();
        assert_eq!(tokens[0], Token::StringLit("a\nb\tc\\d\"e'f".into()));
    }

    #[test]
    fn test_pipe_operator_rejected_as_reserved() {
        let err = lex_string("$a |> $b").unwrap_err();
        assert!(
            err.contains("pipe operator `|>` is reserved for future use"),
            "got: {err}"
        );
    }

    #[test]
    fn test_bare_pipe_rejected() {
        let err = lex_string("$a | $b").unwrap_err();
        assert!(err.contains("unexpected character '|'"), "got: {err}");
    }

    #[test]
    fn test_pipe_in_expression_rejected() {
        let err = lex_string("concat('a', 'b') |> upper()").unwrap_err();
        assert!(
            err.contains("pipe operator `|>` is reserved for future use"),
            "got: {err}"
        );
    }

    // ── is_valid_fel_identifier tests ────────────────────────────────

    #[test]
    fn test_valid_identifiers() {
        assert!(is_valid_fel_identifier("foo"));
        assert!(is_valid_fel_identifier("_bar"));
        assert!(is_valid_fel_identifier("camelCase123"));
        assert!(is_valid_fel_identifier("_"));
        assert!(is_valid_fel_identifier("x"));
        assert!(is_valid_fel_identifier("snake_case_name"));
    }

    #[test]
    fn test_invalid_identifiers() {
        assert!(!is_valid_fel_identifier(""));
        assert!(!is_valid_fel_identifier("123abc"));
        assert!(!is_valid_fel_identifier("$ref"));
        assert!(!is_valid_fel_identifier("foo-bar"));
        assert!(!is_valid_fel_identifier("foo bar"));
        assert!(!is_valid_fel_identifier("a.b"));
    }

    #[test]
    fn test_keywords_are_not_valid_identifiers() {
        for kw in FEL_KEYWORDS {
            assert!(
                !is_valid_fel_identifier(kw),
                "keyword '{kw}' should be invalid"
            );
        }
    }

    // ── sanitize_fel_identifier tests ────────────────────────────────

    #[test]
    fn test_sanitize_valid_stays_unchanged() {
        assert_eq!(sanitize_fel_identifier("foo"), "foo");
        assert_eq!(sanitize_fel_identifier("_bar"), "_bar");
    }

    #[test]
    fn test_sanitize_strips_invalid_chars() {
        assert_eq!(sanitize_fel_identifier("foo-bar"), "foobar");
        assert_eq!(sanitize_fel_identifier("hello world"), "helloworld");
        assert_eq!(sanitize_fel_identifier("$ref"), "ref");
        assert_eq!(sanitize_fel_identifier("a.b.c"), "abc");
    }

    #[test]
    fn test_sanitize_prepends_underscore_for_digit_start() {
        assert_eq!(sanitize_fel_identifier("123abc"), "_123abc");
    }

    #[test]
    fn test_sanitize_appends_underscore_for_keyword() {
        assert_eq!(sanitize_fel_identifier("true"), "true_");
        assert_eq!(sanitize_fel_identifier("null"), "null_");
        assert_eq!(sanitize_fel_identifier("and"), "and_");
    }

    #[test]
    fn test_sanitize_empty_or_all_invalid() {
        assert_eq!(sanitize_fel_identifier(""), "_");
        assert_eq!(sanitize_fel_identifier("!@#$"), "_");
    }

    #[test]
    fn tokenize_json_respects_wire_style() {
        use serde_json::json;

        use crate::wire_style::JsonWireStyle;

        let js = tokenize_to_json_value_styled("1", JsonWireStyle::JsCamel).expect("tokenize");
        let py = tokenize_to_json_value_styled("1", JsonWireStyle::PythonSnake).expect("tokenize");

        assert_eq!(
            js,
            json!([
                { "tokenType": "NumberLiteral", "text": "1", "start": 0, "end": 1 },
                { "tokenType": "EOF", "text": "", "start": 1, "end": 1 }
            ])
        );
        assert_eq!(
            py,
            json!([
                { "token_type": "NumberLiteral", "text": "1", "start": 0, "end": 1 },
                { "token_type": "EOF", "text": "", "start": 1, "end": 1 }
            ])
        );
    }
}