vexy-json-core 1.5.11

Core parser for Vexy JSON's forgiving JSON syntax
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
// this_file: src/streaming/lexer.rs

//! Incremental lexer for streaming parser.
//!
//! This lexer can process input character by character and maintain state
//! across chunk boundaries, making it suitable for streaming scenarios.

use crate::ast::Token;
use crate::error::{Error, Result, Span};

/// State of the incremental lexer
#[derive(Debug, Clone)]
pub struct StreamingLexer {
    /// Current position in the overall input stream
    position: usize,
    /// Buffer for incomplete tokens
    buffer: String,
    /// Current lexer state
    state: LexerState,
    /// Pending tokens ready to be consumed
    pending_tokens: Vec<(Token, Span)>,
    /// Options for parsing
    options: crate::parser::ParserOptions,
}

/// Internal lexer state for incremental parsing
#[derive(Debug, Clone)]
enum LexerState {
    /// Normal state, looking for next token
    Normal,
    /// Inside a string literal
    InString {
        quote_char: char,
        escape: bool,
        start_pos: usize,
    },
    /// Inside a number
    InNumber {
        start_pos: usize,
        has_dot: bool,
        has_exp: bool,
    },
    /// Inside an identifier (could be keyword or unquoted string)
    InIdentifier {
        start_pos: usize,
    },
    /// Inside a single-line comment
    InSingleLineComment {
        start_pos: usize,
    },
    /// Inside a multi-line comment
    InMultiLineComment {
        start_pos: usize,
        star_seen: bool,
    },
    /// Potential comment start (seen /)
    PotentialComment {
        start_pos: usize,
    },
}

impl StreamingLexer {
    /// Create a new streaming lexer with default options
    pub fn new() -> Self {
        Self::with_options(crate::parser::ParserOptions::default())
    }

    /// Create a new streaming lexer with custom options
    pub fn with_options(options: crate::parser::ParserOptions) -> Self {
        Self {
            position: 0,
            buffer: String::new(),
            state: LexerState::Normal,
            pending_tokens: Vec::new(),
            options,
        }
    }

    /// Feed a character to the lexer
    pub fn feed_char(&mut self, ch: char) -> Result<()> {
        match self.state.clone() {
            LexerState::Normal => self.process_normal(ch)?,
            LexerState::InString { quote_char, escape, start_pos } => {
                self.process_string(ch, quote_char, escape, start_pos)?;
            }
            LexerState::InNumber { start_pos, has_dot, has_exp } => {
                self.process_number(ch, start_pos, has_dot, has_exp)?;
            }
            LexerState::InIdentifier { start_pos } => {
                self.process_identifier(ch, start_pos)?;
            }
            LexerState::InSingleLineComment { start_pos } => {
                self.process_single_line_comment(ch, start_pos)?;
            }
            LexerState::InMultiLineComment { start_pos, star_seen } => {
                self.process_multi_line_comment(ch, start_pos, star_seen)?;
            }
            LexerState::PotentialComment { start_pos } => {
                self.process_potential_comment(ch, start_pos)?;
            }
        }
        
        self.position += ch.len_utf8();
        Ok(())
    }

    /// Feed a string to the lexer
    pub fn feed_str(&mut self, s: &str) -> Result<()> {
        for ch in s.chars() {
            self.feed_char(ch)?;
        }
        Ok(())
    }

    /// Process a character in normal state
    fn process_normal(&mut self, ch: char) -> Result<()> {
        match ch {
            // Whitespace
            ' ' | '\t' | '\r' => {
                // Skip whitespace
            }
            '\n' => {
                if self.options.newline_as_comma {
                    // Emit comma token for newline
                    self.emit_token(Token::Comma, self.position, self.position + 1);
                }
            }
            // Structural characters
            '{' => self.emit_token(Token::LeftBrace, self.position, self.position + 1),
            '}' => self.emit_token(Token::RightBrace, self.position, self.position + 1),
            '[' => self.emit_token(Token::LeftBracket, self.position, self.position + 1),
            ']' => self.emit_token(Token::RightBracket, self.position, self.position + 1),
            ':' => self.emit_token(Token::Colon, self.position, self.position + 1),
            ',' => self.emit_token(Token::Comma, self.position, self.position + 1),
            // String literals
            '"' => {
                self.buffer.clear();
                self.state = LexerState::InString {
                    quote_char: '"',
                    escape: false,
                    start_pos: self.position,
                };
            }
            '\'' if self.options.allow_single_quotes => {
                self.buffer.clear();
                self.state = LexerState::InString {
                    quote_char: '\'',
                    escape: false,
                    start_pos: self.position,
                };
            }
            // Comments
            '/' if self.options.allow_comments => {
                self.state = LexerState::PotentialComment {
                    start_pos: self.position,
                };
            }
            // Numbers
            '-' | '0'..='9' => {
                self.buffer.clear();
                self.buffer.push(ch);
                self.state = LexerState::InNumber {
                    start_pos: self.position,
                    has_dot: false,
                    has_exp: false,
                };
            }
            // Identifiers (for keywords and unquoted strings)
            'a'..='z' | 'A'..='Z' | '_' => {
                self.buffer.clear();
                self.buffer.push(ch);
                self.state = LexerState::InIdentifier {
                    start_pos: self.position,
                };
            }
            _ => {
                return Err(Error::UnexpectedCharacter(ch, self.position));
            }
        }
        Ok(())
    }

    /// Process a character inside a string
    fn process_string(&mut self, ch: char, quote_char: char, escape: bool, start_pos: usize) -> Result<()> {
        if escape {
            // Handle escape sequences
            self.buffer.push('\\');
            self.buffer.push(ch);
            self.state = LexerState::InString {
                quote_char,
                escape: false,
                start_pos,
            };
        } else if ch == '\\' {
            self.state = LexerState::InString {
                quote_char,
                escape: true,
                start_pos,
            };
        } else if ch == quote_char {
            // End of string
            self.emit_token(
                Token::String(self.buffer.clone()),
                start_pos,
                self.position + 1,
            );
            self.state = LexerState::Normal;
        } else {
            self.buffer.push(ch);
        }
        Ok(())
    }

    /// Process a character inside a number
    fn process_number(&mut self, ch: char, start_pos: usize, has_dot: bool, has_exp: bool) -> Result<()> {
        match ch {
            '0'..='9' => {
                self.buffer.push(ch);
            }
            '.' if !has_dot && !has_exp => {
                self.buffer.push(ch);
                self.state = LexerState::InNumber {
                    start_pos,
                    has_dot: true,
                    has_exp,
                };
            }
            'e' | 'E' if !has_exp => {
                self.buffer.push(ch);
                self.state = LexerState::InNumber {
                    start_pos,
                    has_dot,
                    has_exp: true,
                };
            }
            '+' | '-' if self.buffer.ends_with('e') || self.buffer.ends_with('E') => {
                self.buffer.push(ch);
            }
            _ => {
                // End of number
                self.emit_number_token(start_pos)?;
                self.state = LexerState::Normal;
                // Reprocess this character in normal state
                self.position -= ch.len_utf8();
                return self.feed_char(ch);
            }
        }
        Ok(())
    }

    /// Process a character inside an identifier
    fn process_identifier(&mut self, ch: char, start_pos: usize) -> Result<()> {
        match ch {
            'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => {
                self.buffer.push(ch);
            }
            _ => {
                // End of identifier
                self.emit_identifier_token(start_pos)?;
                self.state = LexerState::Normal;
                // Reprocess this character in normal state
                self.position -= ch.len_utf8();
                return self.feed_char(ch);
            }
        }
        Ok(())
    }

    /// Process a character inside a single-line comment
    fn process_single_line_comment(&mut self, ch: char, start_pos: usize) -> Result<()> {
        if ch == '\n' {
            // End of comment
            self.emit_token(
                Token::Comment(self.buffer.clone()),
                start_pos,
                self.position,
            );
            self.state = LexerState::Normal;
            // Process newline in normal state
            self.position -= ch.len_utf8();
            return self.feed_char(ch);
        } else {
            self.buffer.push(ch);
        }
        Ok(())
    }

    /// Process a character inside a multi-line comment
    fn process_multi_line_comment(&mut self, ch: char, start_pos: usize, star_seen: bool) -> Result<()> {
        if star_seen && ch == '/' {
            // End of comment
            self.buffer.pop(); // Remove the *
            self.emit_token(
                Token::Comment(self.buffer.clone()),
                start_pos,
                self.position + 1,
            );
            self.state = LexerState::Normal;
        } else {
            if ch == '*' {
                self.state = LexerState::InMultiLineComment {
                    start_pos,
                    star_seen: true,
                };
            } else {
                self.state = LexerState::InMultiLineComment {
                    start_pos,
                    star_seen: false,
                };
            }
            self.buffer.push(ch);
        }
        Ok(())
    }

    /// Process a potential comment start
    fn process_potential_comment(&mut self, ch: char, start_pos: usize) -> Result<()> {
        match ch {
            '/' => {
                // Single-line comment
                self.buffer.clear();
                self.state = LexerState::InSingleLineComment { start_pos };
            }
            '*' => {
                // Multi-line comment
                self.buffer.clear();
                self.state = LexerState::InMultiLineComment {
                    start_pos,
                    star_seen: false,
                };
            }
            _ => {
                // Not a comment, emit division operator (not supported in JSON)
                return Err(Error::UnexpectedCharacter('/', start_pos));
            }
        }
        Ok(())
    }

    /// Emit a token
    fn emit_token(&mut self, token: Token, start: usize, end: usize) {
        self.pending_tokens.push((token, Span { start, end }));
    }

    /// Emit a number token
    fn emit_number_token(&mut self, start_pos: usize) -> Result<()> {
        let token = Token::Number(self.buffer.clone());
        self.emit_token(token, start_pos, self.position);
        Ok(())
    }

    /// Emit an identifier token (could be keyword or unquoted string)
    fn emit_identifier_token(&mut self, start_pos: usize) -> Result<()> {
        let token = match self.buffer.as_str() {
            "true" => Token::Bool(true),
            "false" => Token::Bool(false),
            "null" => Token::Null,
            _ => {
                if self.options.allow_unquoted_keys {
                    Token::UnquotedString(self.buffer.clone())
                } else {
                    return Err(Error::UnexpectedCharacter(
                        self.buffer.chars().next().unwrap(),
                        start_pos,
                    ));
                }
            }
        };
        self.emit_token(token, start_pos, self.position);
        Ok(())
    }

    /// Get the next token if available
    pub fn next_token(&mut self) -> Option<(Token, Span)> {
        if self.pending_tokens.is_empty() {
            None
        } else {
            Some(self.pending_tokens.remove(0))
        }
    }

    /// Check if there are pending tokens
    pub fn has_tokens(&self) -> bool {
        !self.pending_tokens.is_empty()
    }

    /// Finish lexing and emit any remaining tokens
    pub fn finish(&mut self) -> Result<()> {
        match &self.state {
            LexerState::Normal => Ok(()),
            LexerState::InString { start_pos, .. } => {
                Err(Error::UnterminatedString(*start_pos))
            }
            LexerState::InNumber { start_pos, .. } => {
                self.emit_number_token(*start_pos)
            }
            LexerState::InIdentifier { start_pos } => {
                self.emit_identifier_token(*start_pos)
            }
            LexerState::InSingleLineComment { start_pos } => {
                self.emit_token(
                    Token::Comment(self.buffer.clone()),
                    *start_pos,
                    self.position,
                );
                Ok(())
            }
            LexerState::InMultiLineComment { start_pos, .. } => {
                Err(Error::Custom(format!("Unterminated comment at position {}", start_pos), *start_pos))
            }
            LexerState::PotentialComment { start_pos } => {
                Err(Error::UnexpectedCharacter('/', *start_pos))
            }
        }
    }
}

impl Default for StreamingLexer {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_simple_tokens() {
        let mut lexer = StreamingLexer::new();
        lexer.feed_str("{\"key\": \"value\"}").unwrap();
        lexer.finish().unwrap();

        assert_eq!(lexer.next_token().unwrap().0, Token::LeftBrace);
        assert_eq!(lexer.next_token().unwrap().0, Token::String("key".to_string()));
        assert_eq!(lexer.next_token().unwrap().0, Token::Colon);
        assert_eq!(lexer.next_token().unwrap().0, Token::String("value".to_string()));
        assert_eq!(lexer.next_token().unwrap().0, Token::RightBrace);
        assert!(lexer.next_token().is_none());
    }

    #[test]
    fn test_incremental_string() {
        let mut lexer = StreamingLexer::new();
        lexer.feed_str("\"hel").unwrap();
        assert!(!lexer.has_tokens());
        
        lexer.feed_str("lo\"").unwrap();
        assert!(lexer.has_tokens());
        
        assert_eq!(lexer.next_token().unwrap().0, Token::String("hello".to_string()));
    }

    #[test]
    fn test_numbers() {
        let mut lexer = StreamingLexer::new();
        lexer.feed_str("123.45e-6").unwrap();
        lexer.finish().unwrap();

        assert_eq!(lexer.next_token().unwrap().0, Token::Number("123.45e-6".to_string()));
    }
}