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
//! Lexer for tokenizing Firefox preference files
//!
//! This module provides a tokenizer that converts character streams into tokens
//! for parsing Firefox prefs.js files. It handles all JavaScript escape sequences
//! and tracks line/column numbers for accurate error reporting.
use crate::error::{Error, Result};
use std::iter::Peekable;
use std::str::Chars;
/// Token types produced by the lexer
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
/// Identifier (e.g., user_pref, pref, lock_pref, sticky_pref)
Identifier(String),
/// String value with escape sequences already processed
String(String),
/// Numeric value (integer or float)
Number(f64),
/// Boolean value
Boolean(bool),
/// Null value
Null,
/// Left parenthesis
LeftParen,
/// Right parenthesis
RightParen,
/// Comma
Comma,
/// Semicolon
Semicolon,
/// End of input
Eof,
}
/// Lexer for tokenizing Firefox preference files
pub struct Lexer<'a> {
/// Input character iterator
chars: Peekable<Chars<'a>>,
/// Current line number (1-indexed)
line: usize,
/// Current column number (1-indexed)
column: usize,
/// Track if we're at the start of a line (for column tracking)
at_line_start: bool,
}
impl<'a> Lexer<'a> {
/// Create a new lexer for the given input
pub fn new(input: &'a str) -> Self {
Lexer {
chars: input.chars().peekable(),
line: 1,
column: 1,
at_line_start: true,
}
}
/// Get the next token from the input
pub fn next_token(&mut self) -> Result<Token> {
self.skip_whitespace_and_comments();
// Check for EOF
if self.chars.peek().is_none() {
return Ok(Token::Eof);
}
let c = *self.chars.peek().unwrap();
match c {
'(' => {
self.advance();
Ok(Token::LeftParen)
}
')' => {
self.advance();
Ok(Token::RightParen)
}
',' => {
self.advance();
Ok(Token::Comma)
}
';' => {
self.advance();
Ok(Token::Semicolon)
}
'"' => self.lex_string(),
'-' | '0'..='9' => self.lex_number(),
'a'..='z' | 'A'..='Z' | '_' => self.lex_identifier(),
_ => Err(Error::Lexer {
message: format!("Unexpected character: '{}'", c),
line: self.line,
column: self.column,
}),
}
}
/// Advance to the next character
fn advance(&mut self) {
if self.chars.next().is_some() {
if self.at_line_start {
self.at_line_start = false;
}
self.column += 1;
}
}
/// Skip whitespace and comments
fn skip_whitespace_and_comments(&mut self) {
loop {
// Skip whitespace (but track newlines)
while let Some(&c) = self.chars.peek() {
if c == ' ' || c == '\t' || c == '\r' {
self.advance();
} else if c == '\n' {
self.advance();
self.line += 1;
self.column = 1;
self.at_line_start = true;
} else {
break;
}
}
// Check for comments
if let Some(&'/') = self.chars.peek() {
self.advance();
match self.chars.peek() {
Some(&'/') => {
// Single-line comment: skip to end of line
self.advance();
while let Some(&c) = self.chars.peek() {
if c == '\n' {
break;
}
self.advance();
}
continue; // Loop again to handle whitespace after comment
}
Some(&'*') => {
// Multi-line comment: skip to */
self.advance();
let start_line = self.line;
let start_col = self.column;
loop {
match self.chars.next() {
Some('\n') => {
self.line += 1;
self.column = 1;
self.at_line_start = true;
}
Some('*') => {
self.column += 1;
if let Some(&'/') = self.chars.peek() {
self.advance();
break;
}
}
Some(_) => {
if self.at_line_start {
self.at_line_start = false;
}
self.column += 1;
}
None => {
// Unclosed comment - but we'll continue for error recovery
self.line = start_line;
self.column = start_col;
break;
}
}
}
continue; // Loop again to handle whitespace after comment
}
_ => {
// Not a comment, just a single slash
// We've already consumed it, so we need to put it back somehow
// For now, we'll just break and let the error happen elsewhere
// (this shouldn't happen in valid prefs.js files)
break;
}
}
} else {
break;
}
}
}
/// Lex an identifier (e.g., user_pref, pref, true, false, null)
fn lex_identifier(&mut self) -> Result<Token> {
let _start_line = self.line;
let _start_col = self.column;
let mut ident = String::new();
while let Some(&c) = self.chars.peek() {
if c.is_alphanumeric() || c == '_' {
ident.push(c);
self.advance();
} else {
break;
}
}
// Check for keywords
match ident.as_str() {
"true" => Ok(Token::Boolean(true)),
"false" => Ok(Token::Boolean(false)),
"null" => Ok(Token::Null),
_ => Ok(Token::Identifier(ident)),
}
}
/// Lex a string literal (only double-quoted strings in prefs.js)
fn lex_string(&mut self) -> Result<Token> {
let start_col = self.column;
// Skip opening quote
self.advance();
let mut result = String::new();
loop {
match self.chars.next() {
Some('"') => {
self.column += 1;
return Ok(Token::String(result));
}
Some('\\') => {
self.column += 1;
// Handle escape sequences
match self.chars.next() {
Some('"') => {
result.push('"');
self.column += 1;
}
Some('\'') => {
result.push('\'');
self.column += 1;
}
Some('\\') => {
result.push('\\');
self.column += 1;
}
Some('n') => {
result.push('\n');
self.column += 1;
}
Some('r') => {
result.push('\r');
self.column += 1;
}
Some('t') => {
result.push('\t');
self.column += 1;
}
Some('b') => {
result.push('\x08'); // Backspace (U+0008)
self.column += 1;
}
Some('f') => {
result.push('\x0c'); // Form feed (U+000C)
self.column += 1;
}
Some('0') => {
// Null character (U+0000)
// Check for octal escapes \00 or \000 (but allow \0 followed by digit)
if let Some(&c) = self.chars.peek() {
if c == '0' {
// \00 or \000 - octal escape, not supported
return Err(Error::Lexer {
message: "Octal escape sequences are not supported. Use \\x00 instead.".to_string(),
line: self.line,
column: self.column,
});
}
// \0 followed by 1-9 is fine - just null char followed by that digit
}
result.push('\x00');
self.column += 1;
}
Some('x') => {
// Hex escape: \xNN
self.column += 1;
let mut hex = String::new();
for _ in 0..2 {
if let Some(&c) = self.chars.peek() {
if c.is_ascii_hexdigit() {
hex.push(c);
self.advance();
}
}
}
if hex.len() == 2 {
if let Ok(byte) = u8::from_str_radix(&hex, 16) {
result.push(byte as char);
} else {
return Err(Error::Lexer {
message: format!("Invalid hex escape: \\x{}", hex),
line: self.line,
column: self.column,
});
}
} else {
return Err(Error::Lexer {
message: format!("Incomplete hex escape: \\x{}", hex),
line: self.line,
column: self.column,
});
}
}
Some('u') => {
// Unicode escape: \uNNNN
self.column += 1;
let mut hex = String::new();
for _ in 0..4 {
if let Some(&c) = self.chars.peek() {
if c.is_ascii_hexdigit() {
hex.push(c);
self.advance();
}
}
}
if hex.len() == 4 {
if let Ok(codepoint) = u16::from_str_radix(&hex, 16) {
// Convert UTF-16 codepoint to Rust char
// For BMP characters (<= 0xFFFF), this is straightforward
result.push(
std::char::from_u32(codepoint as u32).unwrap_or('\u{FFFD}'), // Replacement character
);
} else {
return Err(Error::Lexer {
message: format!("Invalid unicode escape: \\u{}", hex),
line: self.line,
column: self.column,
});
}
} else {
return Err(Error::Lexer {
message: format!("Incomplete unicode escape: \\u{}", hex),
line: self.line,
column: self.column,
});
}
}
Some(c) => {
return Err(Error::Lexer {
message: format!("Invalid escape sequence: \\{}", c),
line: self.line,
column: self.column,
});
}
None => {
return Err(Error::Lexer {
message: "Unexpected end of input in escape sequence".to_string(),
line: self.line,
column: self.column,
});
}
}
}
Some('\n') => {
self.line += 1;
self.column = 1;
self.at_line_start = true;
// Multiline strings are not valid in prefs.js, but we'll allow them
result.push('\n');
}
Some(c) => {
if self.at_line_start {
self.at_line_start = false;
}
self.column += 1;
result.push(c);
}
None => {
return Err(Error::Lexer {
message: "Unterminated string literal".to_string(),
line: self.line,
column: start_col,
});
}
}
}
}
/// Lex a number (integer or float, including scientific notation)
fn lex_number(&mut self) -> Result<Token> {
let start_col = self.column;
let mut num_str = String::new();
// Handle optional minus sign
if let Some(&'-') = self.chars.peek() {
num_str.push('-');
self.advance();
}
// Parse digits
while let Some(&c) = self.chars.peek() {
if c.is_ascii_digit() {
num_str.push(c);
self.advance();
} else {
break;
}
}
// Check for decimal point
if let Some(&'.') = self.chars.peek() {
num_str.push('.');
self.advance();
// Parse fractional digits
while let Some(&c) = self.chars.peek() {
if c.is_ascii_digit() {
num_str.push(c);
self.advance();
} else {
break;
}
}
}
// Check for scientific notation
if let Some(&'e' | &'E') = self.chars.peek() {
num_str.push('e');
self.advance();
// Optional + or -
if let Some(&'+' | &'-') = self.chars.peek() {
num_str.push(self.chars.next().unwrap());
self.column += 1;
}
// Parse exponent digits
let mut has_exp_digit = false;
while let Some(&c) = self.chars.peek() {
if c.is_ascii_digit() {
num_str.push(c);
self.advance();
has_exp_digit = true;
} else {
break;
}
}
if !has_exp_digit {
return Err(Error::Lexer {
message: "Missing exponent digits in scientific notation".to_string(),
line: self.line,
column: self.column,
});
}
}
// Parse the number
match num_str.parse::<f64>() {
Ok(n) => Ok(Token::Number(n)),
Err(_) => Err(Error::Lexer {
message: format!("Failed to parse number: {}", num_str),
line: self.line,
column: start_col,
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lexer_basic_tokens() {
let input = "( ) , ;";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::LeftParen);
assert_eq!(lexer.next_token().unwrap(), Token::RightParen);
assert_eq!(lexer.next_token().unwrap(), Token::Comma);
assert_eq!(lexer.next_token().unwrap(), Token::Semicolon);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_skip_whitespace() {
let input = " ( \t ) ;";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::LeftParen);
assert_eq!(lexer.next_token().unwrap(), Token::RightParen);
assert_eq!(lexer.next_token().unwrap(), Token::Semicolon);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_single_line_comment() {
let input = "( // this is a comment\n )";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::LeftParen);
assert_eq!(lexer.next_token().unwrap(), Token::RightParen);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_multiline_comment() {
let input = "( /* this is a\nmultiline comment */ )";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::LeftParen);
assert_eq!(lexer.next_token().unwrap(), Token::RightParen);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_identifier() {
let input = "user_pref pref lock_pref sticky_pref";
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::Identifier("user_pref".to_string())
);
assert_eq!(
lexer.next_token().unwrap(),
Token::Identifier("pref".to_string())
);
assert_eq!(
lexer.next_token().unwrap(),
Token::Identifier("lock_pref".to_string())
);
assert_eq!(
lexer.next_token().unwrap(),
Token::Identifier("sticky_pref".to_string())
);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_boolean() {
let input = "true false";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::Boolean(true));
assert_eq!(lexer.next_token().unwrap(), Token::Boolean(false));
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_null() {
let input = "null";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::Null);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_string_basic() {
let input = r#""hello world""#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("hello world".to_string())
);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_string_escaped_quotes() {
let input = r#""value with \"quotes\"""#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("value with \"quotes\"".to_string())
);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_string_backslashes() {
let input = r#""C:\\path\\to\\file""#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("C:\\path\\to\\file".to_string())
);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_string_unicode_escapes() {
let input = r#""\u0041""#; // Should decode to 'A'
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::String("A".to_string()));
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_string_hex_escapes() {
let input = r#""\x41""#; // Should decode to 'A'
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::String("A".to_string()));
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_string_newlines_tabs() {
let input = r#""line1\nline2\ttab""#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("line1\nline2\ttab".to_string())
);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_string_backspace_escape() {
let input = r#""test\bvalue""#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("test\x08value".to_string())
);
}
#[test]
fn test_lexer_string_form_feed_escape() {
let input = r#""test\fvalue""#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("test\x0cvalue".to_string())
);
}
#[test]
fn test_lexer_string_null_escape() {
let input = r#""test\0value""#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("test\x00value".to_string())
);
}
#[test]
fn test_lexer_string_null_escape_followed_by_digit() {
let input = r#""test\01""#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("test\x001".to_string())
);
}
#[test]
fn test_lexer_string_octal_escape_rejected() {
let input = r#""test\00""#;
let mut lexer = Lexer::new(input);
assert!(lexer.next_token().is_err());
}
#[test]
fn test_lexer_string_multiple_escapes_together() {
let input = r#""\b\f\0""#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("\x08\x0c\x00".to_string())
);
}
#[test]
fn test_lexer_integer() {
let input = "42";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::Number(42.0));
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_negative_integer() {
let input = "-42";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::Number(-42.0));
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_float() {
let input = "2.5";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::Number(2.5));
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_scientific_notation() {
let input = "1.5e10";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::Number(1.5e10));
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_scientific_notation_negative() {
let input = "3e-8";
let mut lexer = Lexer::new(input);
assert_eq!(lexer.next_token().unwrap(), Token::Number(3e-8));
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
#[test]
fn test_lexer_complex_tokens() {
let input = r#"user_pref("key", value);"#;
let mut lexer = Lexer::new(input);
assert_eq!(
lexer.next_token().unwrap(),
Token::Identifier("user_pref".to_string())
);
assert_eq!(lexer.next_token().unwrap(), Token::LeftParen);
assert_eq!(
lexer.next_token().unwrap(),
Token::String("key".to_string())
);
assert_eq!(lexer.next_token().unwrap(), Token::Comma);
assert_eq!(
lexer.next_token().unwrap(),
Token::Identifier("value".to_string())
);
assert_eq!(lexer.next_token().unwrap(), Token::RightParen);
assert_eq!(lexer.next_token().unwrap(), Token::Semicolon);
assert_eq!(lexer.next_token().unwrap(), Token::Eof);
}
}