-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathlexer.rs
1860 lines (1752 loc) · 63.6 KB
/
lexer.rs
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module takes care of lexing Python source text.
//!
//! This means source code is scanned and translated into separate tokens. The rules
//! governing what is and is not a valid token are defined in the Python reference
//! guide section on [Lexical analysis].
//!
//! The primary function in this module is [`lex`], which takes a string slice
//! and returns an iterator over the tokens in the source code. The tokens are currently returned
//! as a `Result<Spanned, LexicalError>`, where [`Spanned`] is a tuple containing the
//! start and end [`TextSize`] and a [`Tok`] denoting the token.
//!
//! # Example
//!
//! ```
//! use rustpython_parser::{lexer::lex, Tok, Mode, StringKind};
//!
//! let source = "x = 'RustPython'";
//! let tokens = lex(source, Mode::Module)
//! .map(|tok| tok.expect("Failed to lex"))
//! .collect::<Vec<_>>();
//!
//! for (token, range) in tokens {
//! println!(
//! "{token:?}@{range:?}",
//! );
//! }
//! ```
//!
//! [Lexical analysis]: https://docs.python.org/3/reference/lexical_analysis.html
use crate::{
ast::bigint::BigInt,
soft_keywords::SoftKeywordTransformer,
string::FStringErrorType,
text_size::{TextLen, TextRange, TextSize},
token::{StringKind, Tok},
Mode,
};
use log::trace;
use num_traits::{Num, Zero};
use std::{char, cmp::Ordering, ops::Index, slice::SliceIndex, str::FromStr};
use unic_emoji_char::is_emoji_presentation;
use unic_ucd_ident::{is_xid_continue, is_xid_start};
// Indentations are tracked by a stack of indentation levels. IndentationLevel keeps
// track of the number of tabs and spaces at the current level.
#[derive(Clone, Copy, PartialEq, Debug, Default)]
struct IndentationLevel {
tabs: u32,
spaces: u32,
}
impl IndentationLevel {
fn compare_strict(
&self,
other: &IndentationLevel,
location: TextSize,
) -> Result<Ordering, LexicalError> {
// We only know for sure that we're smaller or bigger if tabs
// and spaces both differ in the same direction. Otherwise we're
// dependent on the size of tabs.
match self.tabs.cmp(&other.tabs) {
Ordering::Less => {
if self.spaces <= other.spaces {
Ok(Ordering::Less)
} else {
Err(LexicalError {
location,
error: LexicalErrorType::TabError,
})
}
}
Ordering::Greater => {
if self.spaces >= other.spaces {
Ok(Ordering::Greater)
} else {
Err(LexicalError {
location,
error: LexicalErrorType::TabError,
})
}
}
Ordering::Equal => Ok(self.spaces.cmp(&other.spaces)),
}
}
}
// The indentations stack is used to keep track of the current indentation level.
// Similar to the CPython implementation, the Indentations stack always has at
// least one level which is never popped. See Reference 2.1.8.
#[derive(Debug)]
struct Indentations {
indent_stack: Vec<IndentationLevel>,
}
impl Indentations {
fn is_empty(&self) -> bool {
self.indent_stack.len() == 1
}
fn push(&mut self, indent: IndentationLevel) {
self.indent_stack.push(indent);
}
fn pop(&mut self) -> Option<IndentationLevel> {
if self.is_empty() {
return None;
}
self.indent_stack.pop()
}
fn current(&self) -> &IndentationLevel {
self.indent_stack
.last()
.expect("Indentations must have at least one level")
}
}
impl Default for Indentations {
fn default() -> Self {
Self {
indent_stack: vec![IndentationLevel::default()],
}
}
}
// A CharWindow is a sliding window over an iterator of chars. It is used to
// allow for look-ahead when scanning tokens from the source code.
struct CharWindow<T: Iterator<Item = char>, const N: usize> {
source: T,
window: [Option<char>; N],
}
impl<T, const N: usize> CharWindow<T, N>
where
T: Iterator<Item = char>,
{
fn new(source: T) -> Self {
Self {
source,
window: [None; N],
}
}
fn slide(&mut self) -> Option<char> {
self.window.rotate_left(1);
let next = self.source.next();
*self.window.last_mut().expect("never empty") = next;
next
}
}
impl<T, const N: usize, Idx> Index<Idx> for CharWindow<T, N>
where
T: Iterator<Item = char>,
Idx: SliceIndex<[Option<char>]>,
{
type Output = Idx::Output;
fn index(&self, index: Idx) -> &Self::Output {
&self.window[index]
}
}
/// A lexer for Python source code.
pub struct Lexer<T: Iterator<Item = char>> {
// Contains the source code to be lexed.
window: CharWindow<T, 3>,
// Are we at the beginning of a line?
at_begin_of_line: bool,
// Amount of parenthesis.
nesting: usize,
// Indentation levels.
indentations: Indentations,
// Pending list of tokens to be returned.
pending: Vec<Spanned>,
// The current location.
location: TextSize,
}
// generated in build.rs, in gen_phf()
/// A map of keywords to their tokens.
pub static KEYWORDS: phf::Map<&'static str, Tok> =
include!(concat!(env!("OUT_DIR"), "/keywords.rs"));
/// Contains a Token along with its `range`.
pub type Spanned = (Tok, TextRange);
/// The result of lexing a token.
pub type LexResult = Result<Spanned, LexicalError>;
/// Create a new lexer from a source string.
///
/// # Examples
///
/// ```
/// use rustpython_parser::{Mode, lexer::lex};
///
/// let source = "def hello(): return 'world'";
/// let lexer = lex(source, Mode::Module);
///
/// for token in lexer {
/// println!("{:?}", token);
/// }
/// ```
#[inline]
pub fn lex(source: &str, mode: Mode) -> impl Iterator<Item = LexResult> + '_ {
lex_starts_at(source, mode, TextSize::default())
}
/// Create a new lexer from a source string, starting at a given location.
/// You probably want to use [`lex`] instead.
pub fn lex_starts_at(
source: &str,
mode: Mode,
start_offset: TextSize,
) -> SoftKeywordTransformer<Lexer<std::str::Chars<'_>>> {
SoftKeywordTransformer::new(Lexer::new(source.chars(), start_offset), mode)
}
impl<T> Lexer<T>
where
T: Iterator<Item = char>,
{
/// Create a new lexer from T and a starting location. You probably want to use
/// [`lex`] instead.
pub fn new(input: T, start: TextSize) -> Self {
let mut lxr = Lexer {
at_begin_of_line: true,
nesting: 0,
indentations: Indentations::default(),
// Usually we have less than 5 tokens pending.
pending: Vec::with_capacity(5),
location: start,
window: CharWindow::new(input),
};
// Fill the window.
lxr.window.slide();
lxr.window.slide();
lxr.window.slide();
// TODO: Handle possible mismatch between BOM and explicit encoding declaration.
// spell-checker:ignore feff
if let Some('\u{feff}') = lxr.window[0] {
lxr.window.slide();
lxr.location += '\u{feff}'.text_len();
}
lxr
}
/// Lex an identifier. Also used for keywords and string/bytes literals with a prefix.
fn lex_identifier(&mut self) -> LexResult {
// Detect potential string like rb'' b'' f'' u'' r''
match self.window[..3] {
[Some(c), Some('"' | '\''), ..] => {
if let Ok(kind) = StringKind::try_from(c) {
return self.lex_string(kind);
}
}
[Some(c1), Some(c2), Some('"' | '\'')] => {
if let Ok(kind) = StringKind::try_from([c1, c2]) {
return self.lex_string(kind);
}
}
_ => {}
};
let start_pos = self.get_pos();
let mut name = String::with_capacity(8);
while self.is_identifier_continuation() {
name.push(self.next_char().unwrap());
}
let end_pos = self.get_pos();
if let Some(tok) = KEYWORDS.get(&name) {
Ok((tok.clone(), TextRange::new(start_pos, end_pos)))
} else {
Ok((Tok::Name { name }, TextRange::new(start_pos, end_pos)))
}
}
/// Numeric lexing. The feast can start!
fn lex_number(&mut self) -> LexResult {
let start_pos = self.get_pos();
match self.window[..2] {
[Some('0'), Some('x' | 'X')] => {
// Hex! (0xdeadbeef)
self.next_char();
self.next_char();
self.lex_number_radix(start_pos, 16)
}
[Some('0'), Some('o' | 'O')] => {
// Octal style! (0o377)
self.next_char();
self.next_char();
self.lex_number_radix(start_pos, 8)
}
[Some('0'), Some('b' | 'B')] => {
// Binary! (0b_1110_0101)
self.next_char();
self.next_char();
self.lex_number_radix(start_pos, 2)
}
_ => self.lex_normal_number(),
}
}
/// Lex a hex/octal/decimal/binary number without a decimal point.
fn lex_number_radix(&mut self, start_pos: TextSize, radix: u32) -> LexResult {
let value_text = self.radix_run(radix);
let end_pos = self.get_pos();
let value = BigInt::from_str_radix(&value_text, radix).map_err(|e| LexicalError {
error: LexicalErrorType::OtherError(format!("{e:?}")),
location: start_pos,
})?;
Ok((Tok::Int { value }, TextRange::new(start_pos, end_pos)))
}
/// Lex a normal number, that is, no octal, hex or binary number.
fn lex_normal_number(&mut self) -> LexResult {
let start_pos = self.get_pos();
let start_is_zero = self.window[0] == Some('0');
// Normal number:
let mut value_text = self.radix_run(10);
// If float:
if self.window[0] == Some('.') || self.at_exponent() {
// Take '.':
if self.window[0] == Some('.') {
if self.window[1] == Some('_') {
return Err(LexicalError {
error: LexicalErrorType::OtherError("Invalid Syntax".to_owned()),
location: self.get_pos(),
});
}
value_text.push(self.next_char().unwrap());
value_text.push_str(&self.radix_run(10));
}
// 1e6 for example:
if let Some('e' | 'E') = self.window[0] {
if self.window[1] == Some('_') {
return Err(LexicalError {
error: LexicalErrorType::OtherError("Invalid Syntax".to_owned()),
location: self.get_pos(),
});
}
value_text.push(self.next_char().unwrap().to_ascii_lowercase());
// Optional +/-
if matches!(self.window[0], Some('-' | '+')) {
if self.window[1] == Some('_') {
return Err(LexicalError {
error: LexicalErrorType::OtherError("Invalid Syntax".to_owned()),
location: self.get_pos(),
});
}
value_text.push(self.next_char().unwrap());
}
value_text.push_str(&self.radix_run(10));
}
let value = f64::from_str(&value_text).map_err(|_| LexicalError {
error: LexicalErrorType::OtherError("Invalid decimal literal".to_owned()),
location: self.get_pos(),
})?;
// Parse trailing 'j':
if matches!(self.window[0], Some('j' | 'J')) {
self.next_char();
let end_pos = self.get_pos();
Ok((
Tok::Complex {
real: 0.0,
imag: value,
},
TextRange::new(start_pos, end_pos),
))
} else {
let end_pos = self.get_pos();
Ok((Tok::Float { value }, TextRange::new(start_pos, end_pos)))
}
} else {
// Parse trailing 'j':
if matches!(self.window[0], Some('j' | 'J')) {
self.next_char();
let end_pos = self.get_pos();
let imag = f64::from_str(&value_text).unwrap();
Ok((
Tok::Complex { real: 0.0, imag },
TextRange::new(start_pos, end_pos),
))
} else {
let end_pos = self.get_pos();
let value = value_text.parse::<BigInt>().unwrap();
if start_is_zero && !value.is_zero() {
// leading zeros in decimal integer literals are not permitted
return Err(LexicalError {
error: LexicalErrorType::OtherError("Invalid Token".to_owned()),
location: self.get_pos(),
});
}
Ok((Tok::Int { value }, TextRange::new(start_pos, end_pos)))
}
}
}
/// Consume a sequence of numbers with the given radix,
/// the digits can be decorated with underscores
/// like this: '1_2_3_4' == '1234'
fn radix_run(&mut self, radix: u32) -> String {
let mut value_text = String::new();
loop {
if let Some(c) = self.take_number(radix) {
value_text.push(c);
} else if self.window[0] == Some('_')
&& Lexer::<T>::is_digit_of_radix(self.window[1], radix)
{
self.next_char();
} else {
break;
}
}
value_text
}
/// Consume a single character with the given radix.
fn take_number(&mut self, radix: u32) -> Option<char> {
let take_char = Lexer::<T>::is_digit_of_radix(self.window[0], radix);
take_char.then(|| self.next_char().unwrap())
}
/// Test if a digit is of a certain radix.
fn is_digit_of_radix(c: Option<char>, radix: u32) -> bool {
match radix {
2 => matches!(c, Some('0'..='1')),
8 => matches!(c, Some('0'..='7')),
10 => matches!(c, Some('0'..='9')),
16 => matches!(c, Some('0'..='9') | Some('a'..='f') | Some('A'..='F')),
other => unimplemented!("Radix not implemented: {}", other),
}
}
/// Test if we face '[eE][-+]?[0-9]+'
fn at_exponent(&self) -> bool {
match self.window[..2] {
[Some('e' | 'E'), Some('+' | '-')] => matches!(self.window[2], Some('0'..='9')),
[Some('e' | 'E'), Some('0'..='9')] => true,
_ => false,
}
}
/// Lex a single comment.
#[cfg(feature = "full-lexer")]
fn lex_comment(&mut self) -> LexResult {
let start_pos = self.get_pos();
let mut value = String::new();
loop {
match self.window[0] {
Some('\n' | '\r') | None => {
let end_pos = self.get_pos();
return Ok((Tok::Comment(value), TextRange::new(start_pos, end_pos)));
}
Some(_) => {}
}
value.push(self.next_char().unwrap());
}
}
#[cfg(feature = "full-lexer")]
fn lex_and_emit_comment(&mut self) -> Result<(), LexicalError> {
let comment = self.lex_comment()?;
self.emit(comment);
Ok(())
}
/// Discard comment if full-lexer is not enabled.
#[cfg(not(feature = "full-lexer"))]
fn lex_comment(&mut self) {
loop {
match self.window[0] {
Some('\n' | '\r') | None => {
return;
}
Some(_) => {}
}
self.next_char().unwrap();
}
}
#[cfg(not(feature = "full-lexer"))]
#[inline]
fn lex_and_emit_comment(&mut self) -> Result<(), LexicalError> {
self.lex_comment();
Ok(())
}
/// Lex a string literal.
fn lex_string(&mut self, kind: StringKind) -> LexResult {
let start_pos = self.get_pos();
for _ in 0..u32::from(kind.prefix_len()) {
self.next_char();
}
let quote_char = self.next_char().unwrap();
let mut string_content = String::with_capacity(5);
// If the next two characters are also the quote character, then we have a triple-quoted
// string; consume those two characters and ensure that we require a triple-quote to close
let triple_quoted = if self.window[..2] == [Some(quote_char); 2] {
self.next_char();
self.next_char();
true
} else {
false
};
loop {
match self.next_char() {
Some(c) => {
if c == '\\' {
if let Some(next_c) = self.next_char() {
string_content.push('\\');
string_content.push(next_c);
continue;
}
}
if c == '\n' && !triple_quoted {
return Err(LexicalError {
error: LexicalErrorType::OtherError(
"EOL while scanning string literal".to_owned(),
),
location: self.get_pos(),
});
}
if c == quote_char {
if triple_quoted {
// Look ahead at the next two characters; if we have two more
// quote_chars, it's the end of the string; consume the remaining
// closing quotes and break the loop
if self.window[..2] == [Some(quote_char); 2] {
self.next_char();
self.next_char();
break;
}
} else {
break;
}
}
string_content.push(c);
}
None => {
return Err(LexicalError {
error: if triple_quoted {
LexicalErrorType::Eof
} else {
LexicalErrorType::StringError
},
location: self.get_pos(),
});
}
}
}
let end_pos = self.get_pos();
let tok = Tok::String {
value: string_content,
kind,
triple_quoted,
};
Ok((tok, TextRange::new(start_pos, end_pos)))
}
// Checks if the character c is a valid starting character as described
// in https://docs.python.org/3/reference/lexical_analysis.html#identifiers
fn is_identifier_start(&self, c: char) -> bool {
match c {
'a'..='z' | 'A'..='Z' | '_' => true,
_ => is_xid_start(c),
}
}
// Checks if the character c is a valid continuation character as described
// in https://docs.python.org/3/reference/lexical_analysis.html#identifiers
fn is_identifier_continuation(&self) -> bool {
match self.window[0] {
Some('a'..='z' | 'A'..='Z' | '_' | '0'..='9') => true,
Some(c) => is_xid_continue(c),
_ => false,
}
}
// This is the main entry point. Call this function to retrieve the next token.
// This function is used by the iterator implementation.
fn inner_next(&mut self) -> LexResult {
// top loop, keep on processing, until we have something pending.
while self.pending.is_empty() {
// Detect indentation levels
if self.at_begin_of_line {
self.handle_indentations()?;
}
self.consume_normal()?;
}
Ok(self.pending.remove(0))
}
// Given we are at the start of a line, count the number of spaces and/or tabs until the first character.
fn eat_indentation(&mut self) -> Result<IndentationLevel, LexicalError> {
// Determine indentation:
let mut spaces: u32 = 0;
let mut tabs: u32 = 0;
loop {
match self.window[0] {
Some(' ') => {
/*
if tabs != 0 {
// Don't allow spaces after tabs as part of indentation.
// This is technically stricter than python3 but spaces after
// tabs is even more insane than mixing spaces and tabs.
return Some(Err(LexicalError {
error: LexicalErrorType::OtherError("Spaces not allowed as part of indentation after tabs".to_owned()),
location: self.get_pos(),
}));
}
*/
self.next_char();
spaces += 1;
}
Some('\t') => {
if spaces != 0 {
// Don't allow tabs after spaces as part of indentation.
// This is technically stricter than python3 but spaces before
// tabs is even more insane than mixing spaces and tabs.
return Err(LexicalError {
error: LexicalErrorType::TabsAfterSpaces,
location: self.get_pos(),
});
}
self.next_char();
tabs += 1;
}
Some('#') => {
self.lex_and_emit_comment()?;
spaces = 0;
tabs = 0;
}
Some('\x0C') => {
// Form feed character!
// Reset indentation for the Emacs user.
self.next_char();
spaces = 0;
tabs = 0;
}
Some('\n' | '\r') => {
// Empty line!
#[cfg(feature = "full-lexer")]
let tok_start = self.get_pos();
self.next_char();
#[cfg(feature = "full-lexer")]
let tok_end = self.get_pos();
#[cfg(feature = "full-lexer")]
self.emit((Tok::NonLogicalNewline, TextRange::new(tok_start, tok_end)));
spaces = 0;
tabs = 0;
}
None => {
spaces = 0;
tabs = 0;
break;
}
_ => {
self.at_begin_of_line = false;
break;
}
}
}
Ok(IndentationLevel { tabs, spaces })
}
// Push/pop indents/dedents based on the current indentation level.
fn handle_indentations(&mut self) -> Result<(), LexicalError> {
let indentation_level = self.eat_indentation()?;
if self.nesting != 0 {
return Ok(());
}
// Determine indent or dedent:
let current_indentation = self.indentations.current();
let ordering = indentation_level.compare_strict(current_indentation, self.get_pos())?;
match ordering {
Ordering::Equal => {
// Same same
}
Ordering::Greater => {
// New indentation level:
self.indentations.push(indentation_level);
let tok_pos = self.get_pos();
self.emit((
Tok::Indent,
TextRange::new(
tok_pos
- TextSize::new(indentation_level.spaces)
- TextSize::new(indentation_level.tabs),
tok_pos,
),
));
}
Ordering::Less => {
// One or more dedentations
// Pop off other levels until col is found:
loop {
let current_indentation = self.indentations.current();
let ordering =
indentation_level.compare_strict(current_indentation, self.get_pos())?;
match ordering {
Ordering::Less => {
self.indentations.pop();
let tok_pos = self.get_pos();
self.emit((Tok::Dedent, TextRange::empty(tok_pos)));
}
Ordering::Equal => {
// We arrived at proper level of indentation.
break;
}
Ordering::Greater => {
return Err(LexicalError {
error: LexicalErrorType::IndentationError,
location: self.get_pos(),
});
}
}
}
}
}
Ok(())
}
// Take a look at the next character, if any, and decide upon the next steps.
fn consume_normal(&mut self) -> Result<(), LexicalError> {
if let Some(c) = self.window[0] {
// Identifiers are the most common case.
if self.is_identifier_start(c) {
let identifier = self.lex_identifier()?;
self.emit(identifier);
} else {
self.consume_character(c)?;
}
} else {
// We reached end of file.
let tok_pos = self.get_pos();
// First of all, we need all nestings to be finished.
if self.nesting > 0 {
return Err(LexicalError {
error: LexicalErrorType::Eof,
location: tok_pos,
});
}
// Next, insert a trailing newline, if required.
if !self.at_begin_of_line {
self.at_begin_of_line = true;
self.emit((Tok::Newline, TextRange::empty(tok_pos)));
}
// Next, flush the indentation stack to zero.
while !self.indentations.is_empty() {
self.indentations.pop();
self.emit((Tok::Dedent, TextRange::empty(tok_pos)));
}
self.emit((Tok::EndOfFile, TextRange::empty(tok_pos)));
}
Ok(())
}
// Dispatch based on the given character.
fn consume_character(&mut self, c: char) -> Result<(), LexicalError> {
match c {
'0'..='9' => {
let number = self.lex_number()?;
self.emit(number);
}
'#' => {
self.lex_and_emit_comment()?;
}
'"' | '\'' => {
let string = self.lex_string(StringKind::String)?;
self.emit(string);
}
'=' => {
let tok_start = self.get_pos();
self.next_char();
match self.window[0] {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::EqEqual, TextRange::new(tok_start, tok_end)));
}
_ => {
let tok_end = self.get_pos();
self.emit((Tok::Equal, TextRange::new(tok_start, tok_end)));
}
}
}
'+' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.window[0] {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::PlusEqual, TextRange::new(tok_start, tok_end)));
} else {
let tok_end = self.get_pos();
self.emit((Tok::Plus, TextRange::new(tok_start, tok_end)));
}
}
'*' => {
let tok_start = self.get_pos();
self.next_char();
match self.window[0] {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::StarEqual, TextRange::new(tok_start, tok_end)));
}
Some('*') => {
self.next_char();
match self.window[0] {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((
Tok::DoubleStarEqual,
TextRange::new(tok_start, tok_end),
));
}
_ => {
let tok_end = self.get_pos();
self.emit((Tok::DoubleStar, TextRange::new(tok_start, tok_end)));
}
}
}
_ => {
let tok_end = self.get_pos();
self.emit((Tok::Star, TextRange::new(tok_start, tok_end)));
}
}
}
'/' => {
let tok_start = self.get_pos();
self.next_char();
match self.window[0] {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::SlashEqual, TextRange::new(tok_start, tok_end)));
}
Some('/') => {
self.next_char();
match self.window[0] {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((
Tok::DoubleSlashEqual,
TextRange::new(tok_start, tok_end),
));
}
_ => {
let tok_end = self.get_pos();
self.emit((Tok::DoubleSlash, TextRange::new(tok_start, tok_end)));
}
}
}
_ => {
let tok_end = self.get_pos();
self.emit((Tok::Slash, TextRange::new(tok_start, tok_end)));
}
}
}
'%' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.window[0] {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::PercentEqual, TextRange::new(tok_start, tok_end)));
} else {
let tok_end = self.get_pos();
self.emit((Tok::Percent, TextRange::new(tok_start, tok_end)));
}
}
'|' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.window[0] {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::VbarEqual, TextRange::new(tok_start, tok_end)));
} else {
let tok_end = self.get_pos();
self.emit((Tok::Vbar, TextRange::new(tok_start, tok_end)));
}
}
'^' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.window[0] {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::CircumflexEqual, TextRange::new(tok_start, tok_end)));
} else {
let tok_end = self.get_pos();
self.emit((Tok::CircumFlex, TextRange::new(tok_start, tok_end)));
}
}
'&' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.window[0] {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::AmperEqual, TextRange::new(tok_start, tok_end)));
} else {
let tok_end = self.get_pos();
self.emit((Tok::Amper, TextRange::new(tok_start, tok_end)));
}
}
'-' => {
let tok_start = self.get_pos();
self.next_char();
match self.window[0] {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::MinusEqual, TextRange::new(tok_start, tok_end)));
}
Some('>') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::Rarrow, TextRange::new(tok_start, tok_end)));
}
_ => {
let tok_end = self.get_pos();
self.emit((Tok::Minus, TextRange::new(tok_start, tok_end)));
}
}
}
'@' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.window[0] {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::AtEqual, TextRange::new(tok_start, tok_end)));
} else {
let tok_end = self.get_pos();
self.emit((Tok::At, TextRange::new(tok_start, tok_end)));
}
}
'!' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.window[0] {
self.next_char();
let tok_end = self.get_pos();
self.emit((Tok::NotEqual, TextRange::new(tok_start, tok_end)));
} else {
return Err(LexicalError {
error: LexicalErrorType::UnrecognizedToken { tok: '!' },
location: tok_start,
});
}
}
'~' => {
self.eat_single_char(Tok::Tilde);
}
'(' => {
self.eat_single_char(Tok::Lpar);
self.nesting += 1;
}
')' => {
self.eat_single_char(Tok::Rpar);
if self.nesting == 0 {
return Err(LexicalError {
error: LexicalErrorType::NestingError,
location: self.get_pos(),
});
}
self.nesting -= 1;
}
'[' => {
self.eat_single_char(Tok::Lsqb);
self.nesting += 1;