forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer.rs
More file actions
1766 lines (1659 loc) · 60.2 KB
/
lexer.rs
File metadata and controls
1766 lines (1659 loc) · 60.2 KB
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 translated into separate tokens.
extern crate unic_emoji_char;
extern crate unicode_xid;
pub use super::token::Tok;
use crate::error::{LexicalError, LexicalErrorType};
use crate::location::Location;
use num_bigint::BigInt;
use num_traits::identities::Zero;
use num_traits::Num;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::str::FromStr;
use unic_emoji_char::is_emoji_presentation;
use unicode_xid::UnicodeXID;
use wtf8;
#[derive(Clone, Copy, PartialEq, Debug, Default)]
struct IndentationLevel {
tabs: usize,
spaces: usize,
}
impl IndentationLevel {
fn compare_strict(
&self,
other: &IndentationLevel,
location: Location,
) -> 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.
if self.tabs < other.tabs {
if self.spaces <= other.spaces {
Ok(Ordering::Less)
} else {
Err(LexicalError {
location,
error: LexicalErrorType::TabError,
})
}
} else if self.tabs > other.tabs {
if self.spaces >= other.spaces {
Ok(Ordering::Greater)
} else {
Err(LexicalError {
location,
error: LexicalErrorType::TabError,
})
}
} else {
Ok(self.spaces.cmp(&other.spaces))
}
}
}
pub struct Lexer<T: Iterator<Item = char>> {
chars: T,
at_begin_of_line: bool,
nesting: usize, // Amount of parenthesis
indentation_stack: Vec<IndentationLevel>,
pending: Vec<Spanned>,
chr0: Option<char>,
chr1: Option<char>,
chr2: Option<char>,
location: Location,
keywords: HashMap<String, Tok>,
}
pub fn get_keywords() -> HashMap<String, Tok> {
let mut keywords: HashMap<String, Tok> = HashMap::new();
// Alphabetical keywords:
keywords.insert(String::from("..."), Tok::Ellipsis);
keywords.insert(String::from("False"), Tok::False);
keywords.insert(String::from("None"), Tok::None);
keywords.insert(String::from("True"), Tok::True);
keywords.insert(String::from("and"), Tok::And);
keywords.insert(String::from("as"), Tok::As);
keywords.insert(String::from("assert"), Tok::Assert);
keywords.insert(String::from("async"), Tok::Async);
keywords.insert(String::from("await"), Tok::Await);
keywords.insert(String::from("break"), Tok::Break);
keywords.insert(String::from("class"), Tok::Class);
keywords.insert(String::from("continue"), Tok::Continue);
keywords.insert(String::from("def"), Tok::Def);
keywords.insert(String::from("del"), Tok::Del);
keywords.insert(String::from("elif"), Tok::Elif);
keywords.insert(String::from("else"), Tok::Else);
keywords.insert(String::from("except"), Tok::Except);
keywords.insert(String::from("finally"), Tok::Finally);
keywords.insert(String::from("for"), Tok::For);
keywords.insert(String::from("from"), Tok::From);
keywords.insert(String::from("global"), Tok::Global);
keywords.insert(String::from("if"), Tok::If);
keywords.insert(String::from("import"), Tok::Import);
keywords.insert(String::from("in"), Tok::In);
keywords.insert(String::from("is"), Tok::Is);
keywords.insert(String::from("lambda"), Tok::Lambda);
keywords.insert(String::from("nonlocal"), Tok::Nonlocal);
keywords.insert(String::from("not"), Tok::Not);
keywords.insert(String::from("or"), Tok::Or);
keywords.insert(String::from("pass"), Tok::Pass);
keywords.insert(String::from("raise"), Tok::Raise);
keywords.insert(String::from("return"), Tok::Return);
keywords.insert(String::from("try"), Tok::Try);
keywords.insert(String::from("while"), Tok::While);
keywords.insert(String::from("with"), Tok::With);
keywords.insert(String::from("yield"), Tok::Yield);
keywords
}
pub type Spanned = (Location, Tok, Location);
pub type LexResult = Result<Spanned, LexicalError>;
pub fn make_tokenizer<'a>(source: &'a str) -> impl Iterator<Item = LexResult> + 'a {
let nlh = NewlineHandler::new(source.chars());
let lch = LineContinationHandler::new(nlh);
Lexer::new(lch)
}
// The newline handler is an iterator which collapses different newline
// types into \n always.
pub struct NewlineHandler<T: Iterator<Item = char>> {
source: T,
chr0: Option<char>,
chr1: Option<char>,
}
impl<T> NewlineHandler<T>
where
T: Iterator<Item = char>,
{
pub fn new(source: T) -> Self {
let mut nlh = NewlineHandler {
source,
chr0: None,
chr1: None,
};
nlh.shift();
nlh.shift();
nlh
}
fn shift(&mut self) -> Option<char> {
let result = self.chr0;
self.chr0 = self.chr1;
self.chr1 = self.source.next();
result
}
}
impl<T> Iterator for NewlineHandler<T>
where
T: Iterator<Item = char>,
{
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
// Collapse \r\n into \n
loop {
if self.chr0 == Some('\r') {
if self.chr1 == Some('\n') {
// Transform windows EOL into \n
self.shift();
} else {
// Transform MAC EOL into \n
self.chr0 = Some('\n')
}
} else {
break;
}
}
self.shift()
}
}
// Glues \ and \n into a single line:
pub struct LineContinationHandler<T: Iterator<Item = char>> {
source: T,
chr0: Option<char>,
chr1: Option<char>,
}
impl<T> LineContinationHandler<T>
where
T: Iterator<Item = char>,
{
pub fn new(source: T) -> Self {
let mut nlh = LineContinationHandler {
source,
chr0: None,
chr1: None,
};
nlh.shift();
nlh.shift();
nlh
}
fn shift(&mut self) -> Option<char> {
let result = self.chr0;
self.chr0 = self.chr1;
self.chr1 = self.source.next();
result
}
}
impl<T> Iterator for LineContinationHandler<T>
where
T: Iterator<Item = char>,
{
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
// Collapse \r\n into \n
loop {
if self.chr0 == Some('\\') && self.chr1 == Some('\n') {
// Skip backslash and newline
self.shift();
self.shift();
// Idea: insert trailing newline here:
// } else if self.chr0 != Some('\n') && self.chr1.is_none() {
// self.chr1 = Some('\n');
} else {
break;
}
}
self.shift()
}
}
impl<T> Lexer<T>
where
T: Iterator<Item = char>,
{
pub fn new(input: T) -> Self {
let mut lxr = Lexer {
chars: input,
at_begin_of_line: true,
nesting: 0,
indentation_stack: vec![Default::default()],
pending: Vec::new(),
chr0: None,
location: Location::new(0, 0),
chr1: None,
chr2: None,
keywords: get_keywords(),
};
lxr.next_char();
lxr.next_char();
lxr.next_char();
// Start at top row (=1) left column (=1)
lxr.location.reset();
lxr
}
// Lexer helper functions:
fn lex_identifier(&mut self) -> LexResult {
let mut name = String::new();
let start_pos = self.get_pos();
// Detect potential string like rb'' b'' f'' u'' r''
let mut saw_b = false;
let mut saw_r = false;
let mut saw_u = false;
let mut saw_f = false;
loop {
// Detect r"", f"", b"" and u""
if !(saw_b || saw_u || saw_f) && (self.chr0 == Some('b') || self.chr0 == Some('B')) {
saw_b = true;
} else if !(saw_b || saw_r || saw_u || saw_f)
&& (self.chr0 == Some('u') || self.chr0 == Some('U'))
{
saw_u = true;
} else if !(saw_r || saw_u) && (self.chr0 == Some('r') || self.chr0 == Some('R')) {
saw_r = true;
} else if !(saw_b || saw_u || saw_f)
&& (self.chr0 == Some('f') || self.chr0 == Some('F'))
{
saw_f = true;
} else {
break;
}
// Take up char into name:
name.push(self.next_char().unwrap());
// Check if we have a string:
if self.chr0 == Some('"') || self.chr0 == Some('\'') {
return self.lex_string(saw_b, saw_r, saw_u, saw_f);
}
}
while self.is_identifier_continuation() {
name.push(self.next_char().unwrap());
}
let end_pos = self.get_pos();
if self.keywords.contains_key(&name) {
Ok((start_pos, self.keywords[&name].clone(), end_pos))
} else {
Ok((start_pos, Tok::Name { name }, end_pos))
}
}
/// Numeric lexing. The feast can start!
fn lex_number(&mut self) -> LexResult {
let start_pos = self.get_pos();
if self.chr0 == Some('0') {
if self.chr1 == Some('x') || self.chr1 == Some('X') {
// Hex!
self.next_char();
self.next_char();
self.lex_number_radix(start_pos, 16)
} else if self.chr1 == Some('o') || self.chr1 == Some('O') {
// Octal style!
self.next_char();
self.next_char();
self.lex_number_radix(start_pos, 8)
} else if self.chr1 == Some('b') || self.chr1 == Some('B') {
// Binary!
self.next_char();
self.next_char();
self.lex_number_radix(start_pos, 2)
} else {
self.lex_normal_number()
}
} else {
self.lex_normal_number()
}
}
/// Lex a hex/octal/decimal/binary number without a decimal point.
fn lex_number_radix(&mut self, start_pos: Location, 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.clone(),
})?;
Ok((start_pos, Tok::Int { value }, 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.chr0 == Some('0');
// Normal number:
let mut value_text = self.radix_run(10);
// If float:
if self.chr0 == Some('.') || self.at_exponent() {
// Take '.':
if self.chr0 == Some('.') {
if self.chr1 == Some('_') {
return Err(LexicalError {
error: LexicalErrorType::OtherError("Invalid Syntax".to_string()),
location: self.get_pos(),
});
}
value_text.push(self.next_char().unwrap());
value_text.push_str(&self.radix_run(10));
}
// 1e6 for example:
if self.chr0 == Some('e') || self.chr0 == Some('E') {
value_text.push(self.next_char().unwrap().to_ascii_lowercase());
// Optional +/-
if self.chr0 == Some('-') || self.chr0 == Some('+') {
value_text.push(self.next_char().unwrap());
}
value_text.push_str(&self.radix_run(10));
}
let value = f64::from_str(&value_text).unwrap();
// Parse trailing 'j':
if self.chr0 == Some('j') || self.chr0 == Some('J') {
self.next_char();
let end_pos = self.get_pos();
Ok((
start_pos,
Tok::Complex {
real: 0.0,
imag: value,
},
end_pos,
))
} else {
let end_pos = self.get_pos();
Ok((start_pos, Tok::Float { value }, end_pos))
}
} else {
// Parse trailing 'j':
if self.chr0 == Some('j') || self.chr0 == Some('J') {
self.next_char();
let end_pos = self.get_pos();
let imag = f64::from_str(&value_text).unwrap();
Ok((start_pos, Tok::Complex { real: 0.0, imag }, end_pos))
} else {
let end_pos = self.get_pos();
let value = value_text.parse::<BigInt>().unwrap();
if start_is_zero && !value.is_zero() {
return Err(LexicalError {
error: LexicalErrorType::OtherError("Invalid Token".to_string()),
location: self.get_pos(),
});
}
Ok((start_pos, Tok::Int { value }, 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.chr0 == Some('_') && Lexer::<T>::is_digit_of_radix(self.chr1, 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.chr0, radix);
if take_char {
Some(self.next_char().unwrap())
} else {
None
}
}
/// Test if a digit is of a certain radix.
fn is_digit_of_radix(c: Option<char>, radix: u32) -> bool {
match radix {
2 => match c {
Some('0'..='1') => true,
_ => false,
},
8 => match c {
Some('0'..='7') => true,
_ => false,
},
10 => match c {
Some('0'..='9') => true,
_ => false,
},
16 => match c {
Some('0'..='9') | Some('a'..='f') | Some('A'..='F') => true,
_ => false,
},
x => unimplemented!("Radix not implemented: {}", x),
}
}
/// Test if we face '[eE][-+]?[0-9]+'
fn at_exponent(&self) -> bool {
match self.chr0 {
Some('e') | Some('E') => match self.chr1 {
Some('+') | Some('-') => match self.chr2 {
Some('0'..='9') => true,
_ => false,
},
Some('0'..='9') => true,
_ => false,
},
_ => false,
}
}
/// Skip everything until end of line
fn lex_comment(&mut self) {
self.next_char();
loop {
match self.chr0 {
Some('\n') => return,
Some(_) => {}
None => return,
}
self.next_char();
}
}
fn unicode_literal(&mut self, literal_number: usize) -> Result<char, LexicalError> {
let mut p: u32 = 0u32;
let unicode_error = Err(LexicalError {
error: LexicalErrorType::UnicodeError,
location: self.get_pos(),
});
for i in 1..=literal_number {
match self.next_char() {
Some(c) => match c.to_digit(16) {
Some(d) => p += d << ((literal_number - i) * 4),
None => return unicode_error,
},
None => return unicode_error,
}
}
match wtf8::CodePoint::from_u32(p) {
Some(cp) => Ok(cp.to_char_lossy()),
None => unicode_error,
}
}
fn lex_string(
&mut self,
is_bytes: bool,
is_raw: bool,
_is_unicode: bool,
is_fstring: bool,
) -> LexResult {
let quote_char = self.next_char().unwrap();
let mut string_content = String::new();
let start_pos = self.get_pos();
// 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.chr0 == Some(quote_char) && self.chr1 == Some(quote_char) {
self.next_char();
self.next_char();
true
} else {
false
};
loop {
match self.next_char() {
Some('\\') => {
if self.chr0 == Some(quote_char) {
string_content.push(quote_char);
self.next_char();
} else if is_raw {
string_content.push('\\');
if let Some(c) = self.next_char() {
string_content.push(c)
} else {
return Err(LexicalError {
error: LexicalErrorType::StringError,
location: self.get_pos(),
});
}
} else {
match self.next_char() {
Some('\\') => {
string_content.push('\\');
}
Some('\'') => string_content.push('\''),
Some('\"') => string_content.push('\"'),
Some('\n') => {
// Ignore Unix EOL character
}
Some('a') => string_content.push('\x07'),
Some('b') => string_content.push('\x08'),
Some('f') => string_content.push('\x0c'),
Some('n') => {
string_content.push('\n');
}
Some('r') => string_content.push('\r'),
Some('t') => {
string_content.push('\t');
}
Some('u') => string_content.push(self.unicode_literal(4)?),
Some('U') => string_content.push(self.unicode_literal(8)?),
Some('x') if !is_bytes => string_content.push(self.unicode_literal(2)?),
Some('v') => string_content.push('\x0b'),
Some(c) => {
string_content.push('\\');
string_content.push(c);
}
None => {
return Err(LexicalError {
error: LexicalErrorType::StringError,
location: self.get_pos(),
});
}
}
}
}
Some(c) => {
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.chr0 == Some(quote_char) && self.chr1 == Some(quote_char) {
self.next_char();
self.next_char();
break;
}
string_content.push(c);
} else {
break;
}
} else {
if c == '\n' && !triple_quoted {
return Err(LexicalError {
error: LexicalErrorType::StringError,
location: self.get_pos(),
});
}
string_content.push(c);
}
}
None => {
return Err(LexicalError {
error: LexicalErrorType::StringError,
location: self.get_pos(),
});
}
}
}
let end_pos = self.get_pos();
let tok = if is_bytes {
if string_content.is_ascii() {
let value = if is_raw {
string_content.into_bytes()
} else {
lex_byte(string_content).map_err(|error| LexicalError {
error,
location: self.get_pos(),
})?
};
Tok::Bytes { value }
} else {
return Err(LexicalError {
error: LexicalErrorType::StringError,
location: self.get_pos(),
});
}
} else {
Tok::String {
value: string_content,
is_fstring,
}
};
Ok((start_pos, tok, end_pos))
}
fn is_identifier_start(&self, c: char) -> bool {
match c {
'_' => true,
c => UnicodeXID::is_xid_start(c),
}
}
fn is_identifier_continuation(&self) -> bool {
if let Some(c) = self.chr0 {
match c {
'_' | '0'..='9' => true,
c => UnicodeXID::is_xid_continue(c),
}
} else {
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: usize = 0;
let mut tabs: usize = 0;
loop {
match self.chr0 {
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_string()),
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::OtherError(
"Tabs not allowed as part of indentation after spaces".to_string(),
),
location: self.get_pos(),
});
}
self.next_char();
tabs += 1;
}
Some('#') => {
self.lex_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') => {
// Empty line!
self.next_char();
spaces = 0;
tabs = 0;
}
None => {
break;
}
_ => {
self.at_begin_of_line = false;
break;
}
}
}
Ok(IndentationLevel { spaces, tabs })
}
fn handle_indentations(&mut self) -> Result<(), LexicalError> {
let indentation_level = self.eat_indentation()?;
if self.nesting == 0 {
// Determine indent or dedent:
let current_indentation = self.indentation_stack.last().unwrap();
let ordering = indentation_level.compare_strict(current_indentation, self.get_pos())?;
match ordering {
Ordering::Equal => {
// Same same
}
Ordering::Greater => {
// New indentation level:
self.indentation_stack.push(indentation_level);
let tok_start = self.get_pos();
let tok_end = tok_start.clone();
self.emit((tok_start, Tok::Indent, tok_end));
}
Ordering::Less => {
// One or more dedentations
// Pop off other levels until col is found:
loop {
let current_indentation = self.indentation_stack.last().unwrap();
let ordering = indentation_level
.compare_strict(current_indentation, self.get_pos())?;
match ordering {
Ordering::Less => {
self.indentation_stack.pop();
let tok_start = self.get_pos();
let tok_end = tok_start.clone();
self.emit((tok_start, Tok::Dedent, tok_end));
}
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> {
// Check if we have some character:
if let Some(c) = self.chr0 {
// First check identifier:
if self.is_identifier_start(c) {
let identifier = self.lex_identifier()?;
self.emit(identifier);
} else if is_emoji_presentation(c) {
let tok_start = self.get_pos();
self.next_char();
let tok_end = self.get_pos();
self.emit((
tok_start,
Tok::Name {
name: c.to_string(),
},
tok_end,
));
} 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::NestingError,
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_pos.clone(), Tok::Newline, tok_pos.clone()));
}
// Next, flush the indentation stack to zero.
while self.indentation_stack.len() > 1 {
self.indentation_stack.pop();
self.emit((tok_pos.clone(), Tok::Dedent, tok_pos.clone()));
}
self.emit((tok_pos.clone(), Tok::EndOfFile, tok_pos));
}
Ok(())
}
/// Okay, we are facing a weird character, what is it? Determine that.
fn consume_character(&mut self, c: char) -> Result<(), LexicalError> {
match c {
'0'..='9' => {
let number = self.lex_number()?;
self.emit(number);
}
'#' => {
self.lex_comment();
}
'"' | '\'' => {
let string = self.lex_string(false, false, false, false)?;
self.emit(string);
}
'=' => {
let tok_start = self.get_pos();
self.next_char();
match self.chr0 {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((tok_start, Tok::EqEqual, tok_end));
}
_ => {
let tok_end = self.get_pos();
self.emit((tok_start, Tok::Equal, tok_end));
}
}
}
'+' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.chr0 {
self.next_char();
let tok_end = self.get_pos();
self.emit((tok_start, Tok::PlusEqual, tok_end));
} else {
let tok_end = self.get_pos();
self.emit((tok_start, Tok::Plus, tok_end));
}
}
'*' => {
let tok_start = self.get_pos();
self.next_char();
match self.chr0 {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((tok_start, Tok::StarEqual, tok_end));
}
Some('*') => {
self.next_char();
match self.chr0 {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((tok_start, Tok::DoubleStarEqual, tok_end));
}
_ => {
let tok_end = self.get_pos();
self.emit((tok_start, Tok::DoubleStar, tok_end));
}
}
}
_ => {
let tok_end = self.get_pos();
self.emit((tok_start, Tok::Star, tok_end));
}
}
}
'/' => {
let tok_start = self.get_pos();
self.next_char();
match self.chr0 {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((tok_start, Tok::SlashEqual, tok_end));
}
Some('/') => {
self.next_char();
match self.chr0 {
Some('=') => {
self.next_char();
let tok_end = self.get_pos();
self.emit((tok_start, Tok::DoubleSlashEqual, tok_end));
}
_ => {
let tok_end = self.get_pos();
self.emit((tok_start, Tok::DoubleSlash, tok_end));
}
}
}
_ => {
let tok_end = self.get_pos();
self.emit((tok_start, Tok::Slash, tok_end));
}
}
}
'%' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.chr0 {
self.next_char();
let tok_end = self.get_pos();
self.emit((tok_start, Tok::PercentEqual, tok_end));
} else {
let tok_end = self.get_pos();
self.emit((tok_start, Tok::Percent, tok_end));
}
}
'|' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.chr0 {
self.next_char();
let tok_end = self.get_pos();
self.emit((tok_start, Tok::VbarEqual, tok_end));
} else {
let tok_end = self.get_pos();
self.emit((tok_start, Tok::Vbar, tok_end));
}
}
'^' => {
let tok_start = self.get_pos();
self.next_char();
if let Some('=') = self.chr0 {
self.next_char();
let tok_end = self.get_pos();
self.emit((tok_start, Tok::CircumflexEqual, tok_end));
} else {
let tok_end = self.get_pos();
self.emit((tok_start, Tok::CircumFlex, tok_end));
}
}
'&' => {
let tok_start = self.get_pos();