-
Notifications
You must be signed in to change notification settings - Fork 252
/
Copy pathlexer.rs
1583 lines (1385 loc) · 56.7 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
use crate::token::DocStyle;
use super::{
errors::LexerErrorKind,
token::{FmtStrFragment, IntType, Keyword, SpannedToken, Token, Tokens},
};
use acvm::{AcirField, FieldElement};
use noirc_errors::{Position, Span};
use num_bigint::BigInt;
use num_traits::{Num, One};
use std::str::{CharIndices, FromStr};
/// The job of the lexer is to transform an iterator of characters (`char_iter`)
/// into an iterator of `SpannedToken`. Each `Token` corresponds roughly to 1 word or operator.
/// Tokens are tagged with their location in the source file (a `Span`) for use in error reporting.
pub struct Lexer<'a> {
chars: CharIndices<'a>,
position: Position,
done: bool,
skip_comments: bool,
skip_whitespaces: bool,
max_integer: BigInt,
}
pub type SpannedTokenResult = Result<SpannedToken, LexerErrorKind>;
impl<'a> Lexer<'a> {
/// Given a source file of noir code, return all the tokens in the file
/// in order, along with any lexing errors that occurred.
pub fn lex(source: &'a str) -> (Tokens, Vec<LexerErrorKind>) {
let lexer = Lexer::new(source);
let mut tokens = vec![];
let mut errors = vec![];
for result in lexer {
match result {
Ok(token) => tokens.push(token),
Err(error) => errors.push(error),
}
}
(Tokens(tokens), errors)
}
pub fn new(source: &'a str) -> Self {
Lexer {
chars: source.char_indices(),
position: 0,
done: false,
skip_comments: true,
skip_whitespaces: true,
max_integer: BigInt::from_biguint(num_bigint::Sign::Plus, FieldElement::modulus())
- BigInt::one(),
}
}
pub fn skip_comments(mut self, flag: bool) -> Self {
self.skip_comments = flag;
self
}
pub fn skip_whitespaces(mut self, flag: bool) -> Self {
self.skip_whitespaces = flag;
self
}
/// Iterates the cursor and returns the char at the new cursor position
fn next_char(&mut self) -> Option<char> {
let (position, ch) = self.chars.next()?;
self.position = position as u32;
Some(ch)
}
/// Peeks at the next char. Does not iterate the cursor
fn peek_char(&mut self) -> Option<char> {
self.chars.clone().next().map(|(_, ch)| ch)
}
/// Peeks at the character two positions ahead. Does not iterate the cursor
fn peek2_char(&mut self) -> Option<char> {
let mut chars = self.chars.clone();
chars.next();
chars.next().map(|(_, ch)| ch)
}
/// Peeks at the next char and returns true if it is equal to the char argument
fn peek_char_is(&mut self, ch: char) -> bool {
self.peek_char() == Some(ch)
}
/// Peeks at the character two positions ahead and returns true if it is equal to the char argument
fn peek2_char_is(&mut self, ch: char) -> bool {
self.peek2_char() == Some(ch)
}
fn ampersand(&mut self) -> SpannedTokenResult {
if self.peek_char_is('&') {
// When we issue this error the first '&' will already be consumed
// and the next token issued will be the next '&'.
let span = Span::inclusive(self.position, self.position + 1);
Err(LexerErrorKind::LogicalAnd { span })
} else {
self.single_char_token(Token::Ampersand)
}
}
fn next_token(&mut self) -> SpannedTokenResult {
if !self.skip_comments {
return self.next_token_without_checking_comments();
}
// Read tokens and skip comments. This is done like this to avoid recursion
// and hitting stack overflow when there are many comments in a row.
loop {
let token = self.next_token_without_checking_comments()?;
if matches!(token.token(), Token::LineComment(_, None) | Token::BlockComment(_, None)) {
continue;
}
return Ok(token);
}
}
/// Reads the next token, which might be a comment token (these aren't skipped in this method)
fn next_token_without_checking_comments(&mut self) -> SpannedTokenResult {
match self.next_char() {
Some(x) if Self::is_code_whitespace(x) => {
let spanned = self.eat_whitespace(x);
if self.skip_whitespaces {
self.next_token_without_checking_comments()
} else {
Ok(spanned)
}
}
Some('<') => self.glue(Token::Less),
Some('>') => self.glue(Token::Greater),
Some('=') => self.glue(Token::Assign),
Some('/') => self.glue(Token::Slash),
Some('.') => self.glue(Token::Dot),
Some(':') => self.glue(Token::Colon),
Some('!') => self.glue(Token::Bang),
Some('-') => self.glue(Token::Minus),
Some('&') => self.ampersand(),
Some('|') => self.single_char_token(Token::Pipe),
Some('%') => self.single_char_token(Token::Percent),
Some('^') => self.single_char_token(Token::Caret),
Some(';') => self.single_char_token(Token::Semicolon),
Some('*') => self.single_char_token(Token::Star),
Some('(') => self.single_char_token(Token::LeftParen),
Some(')') => self.single_char_token(Token::RightParen),
Some(',') => self.single_char_token(Token::Comma),
Some('+') => self.single_char_token(Token::Plus),
Some('{') => self.single_char_token(Token::LeftBrace),
Some('}') => self.single_char_token(Token::RightBrace),
Some('[') => self.single_char_token(Token::LeftBracket),
Some(']') => self.single_char_token(Token::RightBracket),
Some('$') => self.single_char_token(Token::DollarSign),
Some('"') => self.eat_string_literal(),
Some('f') => self.eat_format_string_or_alpha_numeric(),
Some('r') => self.eat_raw_string_or_alpha_numeric(),
Some('q') => self.eat_quote_or_alpha_numeric(),
Some('#') => self.eat_attribute_start(),
Some(ch) if ch.is_ascii_alphanumeric() || ch == '_' => self.eat_alpha_numeric(ch),
Some(ch) => {
// We don't report invalid tokens in the source as errors until parsing to
// avoid reporting the error twice. See the note on Token::Invalid's documentation for details.
Ok(Token::Invalid(ch).into_single_span(self.position))
}
None => {
self.done = true;
Ok(Token::EOF.into_single_span(self.position))
}
}
}
fn single_char_token(&self, token: Token) -> SpannedTokenResult {
Ok(token.into_single_span(self.position))
}
/// If `single` is followed by `character` then extend it as `double`.
fn single_double_peek_token(
&mut self,
character: char,
single: Token,
double: Token,
) -> SpannedTokenResult {
let start = self.position;
match self.peek_char_is(character) {
false => Ok(single.into_single_span(start)),
true => {
self.next_char();
Ok(double.into_span(start, start + 1))
}
}
}
/// Given that some tokens can contain two characters, such as <= , !=, >=, or even three like ..=
/// Glue will take the first character of the token and check if it can be glued onto the next character(s)
/// forming a double or triple token
///
/// Returns an error if called with a token which cannot be extended with anything.
fn glue(&mut self, prev_token: Token) -> SpannedTokenResult {
match prev_token {
Token::Dot => {
if self.peek_char_is('.') && self.peek2_char_is('=') {
let start = self.position;
self.next_char();
self.next_char();
Ok(Token::DoubleDotEqual.into_span(start, start + 2))
} else {
self.single_double_peek_token('.', prev_token, Token::DoubleDot)
}
}
Token::Less => {
let start = self.position;
if self.peek_char_is('=') {
self.next_char();
Ok(Token::LessEqual.into_span(start, start + 1))
} else if self.peek_char_is('<') {
self.next_char();
Ok(Token::ShiftLeft.into_span(start, start + 1))
} else {
Ok(prev_token.into_single_span(start))
}
}
Token::Greater => {
let start = self.position;
if self.peek_char_is('=') {
self.next_char();
Ok(Token::GreaterEqual.into_span(start, start + 1))
// Note: There is deliberately no case for RightShift. We always lex >> as
// two separate Greater tokens to help the parser parse nested generic types.
} else {
Ok(prev_token.into_single_span(start))
}
}
Token::Assign => {
let start = self.position;
if self.peek_char_is('=') {
self.next_char();
Ok(Token::Equal.into_span(start, start + 1))
} else if self.peek_char_is('>') {
self.next_char();
Ok(Token::FatArrow.into_span(start, start + 1))
} else {
Ok(prev_token.into_single_span(start))
}
}
Token::Bang => self.single_double_peek_token('=', prev_token, Token::NotEqual),
Token::Minus => self.single_double_peek_token('>', prev_token, Token::Arrow),
Token::Colon => self.single_double_peek_token(':', prev_token, Token::DoubleColon),
Token::Slash => {
let start = self.position;
if self.peek_char_is('/') {
self.next_char();
return self.parse_comment(start);
} else if self.peek_char_is('*') {
self.next_char();
return self.parse_block_comment(start);
}
Ok(prev_token.into_single_span(start))
}
_ => Err(LexerErrorKind::NotADoubleChar {
span: Span::single_char(self.position),
found: prev_token,
}),
}
}
/// Keeps consuming tokens as long as the predicate is satisfied
fn eat_while<F: Fn(char) -> bool>(
&mut self,
initial_char: Option<char>,
predicate: F,
) -> String {
// This function is only called when we want to continue consuming a character of the same type.
// For example, we see a digit and we want to consume the whole integer
// Therefore, the current character which triggered this function will need to be appended
let mut word = String::new();
if let Some(init_char) = initial_char {
word.push(init_char);
}
// Keep checking that we are not at the EOF
while let Some(peek_char) = self.peek_char() {
// Then check for the predicate, if predicate matches append char and increment the cursor
// If not, return word. The next character will be analyzed on the next iteration of next_token,
// Which will increment the cursor
if !predicate(peek_char) {
return word;
}
word.push(peek_char);
// If we arrive at this point, then the char has been added to the word and we should increment the cursor
self.next_char();
}
word
}
fn eat_alpha_numeric(&mut self, initial_char: char) -> SpannedTokenResult {
match initial_char {
'A'..='Z' | 'a'..='z' | '_' => Ok(self.eat_word(initial_char)?),
'0'..='9' => self.eat_digit(initial_char),
_ => Err(LexerErrorKind::UnexpectedCharacter {
span: Span::single_char(self.position),
found: initial_char.into(),
expected: "an alpha numeric character".to_owned(),
}),
}
}
fn eat_attribute_start(&mut self) -> SpannedTokenResult {
let start = self.position;
let is_inner = if self.peek_char_is('!') {
self.next_char();
true
} else {
false
};
if !self.peek_char_is('[') {
return Err(LexerErrorKind::UnexpectedCharacter {
span: Span::single_char(self.position),
found: self.next_char(),
expected: "[".to_owned(),
});
}
self.next_char();
let is_tag = self.peek_char_is('\'');
if is_tag {
self.next_char();
}
let end = self.position;
Ok(Token::AttributeStart { is_inner, is_tag }.into_span(start, end))
}
//XXX(low): Can increase performance if we use iterator semantic and utilize some of the methods on String. See below
// https://doc.rust-lang.org/stable/std/primitive.str.html#method.rsplit
fn eat_word(&mut self, initial_char: char) -> SpannedTokenResult {
let (start, word, end) = self.lex_word(initial_char);
self.lookup_word_token(word, start, end)
}
/// Lex the next word in the input stream. Returns (start position, word, end position)
fn lex_word(&mut self, initial_char: char) -> (Position, String, Position) {
let start = self.position;
let word = self.eat_while(Some(initial_char), |ch| {
ch.is_ascii_alphabetic() || ch.is_numeric() || ch == '_'
});
(start, word, self.position)
}
fn lookup_word_token(
&self,
word: String,
start: Position,
end: Position,
) -> SpannedTokenResult {
// Check if word either an identifier or a keyword
if let Some(keyword_token) = Keyword::lookup_keyword(&word) {
return Ok(keyword_token.into_span(start, end));
}
// Check if word an int type
// if no error occurred, then it is either a valid integer type or it is not an int type
let parsed_token = IntType::lookup_int_type(&word);
// Check if it is an int type
if let Some(int_type) = parsed_token {
return Ok(Token::IntType(int_type).into_span(start, end));
}
// Else it is just an identifier
let ident_token = Token::Ident(word);
Ok(ident_token.into_span(start, end))
}
fn eat_digit(&mut self, initial_char: char) -> SpannedTokenResult {
let start = self.position;
let integer_str = self.eat_while(Some(initial_char), |ch| {
ch.is_ascii_digit() | ch.is_ascii_hexdigit() | (ch == 'x') | (ch == '_')
});
let end = self.position;
// We want to enforce some simple rules about usage of underscores:
// 1. Underscores cannot appear at the end of a integer literal. e.g. 0x123_.
// 2. There cannot be more than one underscore consecutively, e.g. 0x5__5, 5__5.
//
// We're not concerned with an underscore at the beginning of a decimal literal
// such as `_5` as this would be lexed into an ident rather than an integer literal.
let invalid_underscore_location = integer_str.ends_with('_');
let consecutive_underscores = integer_str.contains("__");
if invalid_underscore_location || consecutive_underscores {
return Err(LexerErrorKind::InvalidIntegerLiteral {
span: Span::inclusive(start, end),
found: integer_str,
});
}
// Underscores needs to be stripped out before the literal can be converted to a `FieldElement.
let integer_str = integer_str.replace('_', "");
let bigint_result = match integer_str.strip_prefix("0x") {
Some(integer_str) => BigInt::from_str_radix(integer_str, 16),
None => BigInt::from_str(&integer_str),
};
let integer = match bigint_result {
Ok(bigint) => {
if bigint > self.max_integer {
return Err(LexerErrorKind::IntegerLiteralTooLarge {
span: Span::inclusive(start, end),
limit: self.max_integer.to_string(),
});
}
let big_uint = bigint.magnitude();
FieldElement::from_be_bytes_reduce(&big_uint.to_bytes_be())
}
Err(_) => {
return Err(LexerErrorKind::InvalidIntegerLiteral {
span: Span::inclusive(start, end),
found: integer_str,
})
}
};
let integer_token = Token::Int(integer);
Ok(integer_token.into_span(start, end))
}
fn eat_string_literal(&mut self) -> SpannedTokenResult {
let start = self.position;
let mut string = String::new();
loop {
if let Some(next) = self.next_char() {
let char = match next {
'"' => break,
'\\' => match self.next_char() {
Some('r') => '\r',
Some('n') => '\n',
Some('t') => '\t',
Some('0') => '\0',
Some('"') => '"',
Some('\\') => '\\',
Some(escaped) => {
let span = Span::inclusive(start, self.position);
return Err(LexerErrorKind::InvalidEscape { escaped, span });
}
None => {
let span = Span::inclusive(start, self.position);
return Err(LexerErrorKind::UnterminatedStringLiteral { span });
}
},
other => other,
};
string.push(char);
} else {
let span = Span::inclusive(start, self.position);
return Err(LexerErrorKind::UnterminatedStringLiteral { span });
}
}
let str_literal_token = Token::Str(string);
let end = self.position;
Ok(str_literal_token.into_span(start, end))
}
fn eat_fmt_string(&mut self) -> SpannedTokenResult {
let start = self.position;
self.next_char();
let mut fragments = Vec::new();
let mut length = 0;
loop {
// String fragment until '{' or '"'
let mut string = String::new();
let mut found_curly = false;
loop {
if let Some(next) = self.next_char() {
let char = match next {
'"' => break,
'\\' => match self.next_char() {
Some('r') => '\r',
Some('n') => '\n',
Some('t') => '\t',
Some('0') => '\0',
Some('"') => '"',
Some('\\') => '\\',
Some(escaped) => {
let span = Span::inclusive(start, self.position);
return Err(LexerErrorKind::InvalidEscape { escaped, span });
}
None => {
let span = Span::inclusive(start, self.position);
return Err(LexerErrorKind::UnterminatedStringLiteral { span });
}
},
'{' if self.peek_char_is('{') => {
self.next_char();
'{'
}
'}' if self.peek_char_is('}') => {
self.next_char();
'}'
}
'}' => {
let error_position = self.position;
// Keep consuming chars until we find the closing double quote
self.skip_until_string_end();
let span = Span::inclusive(error_position, error_position);
return Err(LexerErrorKind::InvalidFormatString { found: '}', span });
}
'{' => {
found_curly = true;
break;
}
other => other,
};
string.push(char);
length += 1;
if char == '{' || char == '}' {
// This might look a bit strange, but if there's `{{` or `}}` in the format string
// then it will be `{` and `}` in the string fragment respectively, but on the codegen
// phase it will be translated back to `{{` and `}}` to avoid executing an interpolation,
// thus the actual length of the codegen'd string will be one more than what we get here.
//
// We could just make the fragment include the double curly braces, but then the interpreter
// would need to undo the curly braces, so it's simpler to add them during codegen.
length += 1;
}
} else {
let span = Span::inclusive(start, self.position);
return Err(LexerErrorKind::UnterminatedStringLiteral { span });
}
}
if !string.is_empty() {
fragments.push(FmtStrFragment::String(string));
}
if !found_curly {
break;
}
length += 1; // for the curly brace
// Interpolation fragment until '}' or '"'
let mut string = String::new();
let interpolation_start = self.position + 1; // + 1 because we are at '{'
let mut first_char = true;
while let Some(next) = self.next_char() {
let char = match next {
'}' => {
if string.is_empty() {
let error_position = self.position;
// Keep consuming chars until we find the closing double quote
self.skip_until_string_end();
let span = Span::inclusive(error_position, error_position);
return Err(LexerErrorKind::EmptyFormatStringInterpolation { span });
}
break;
}
other => {
let is_valid_char = if first_char {
other.is_ascii_alphabetic() || other == '_'
} else {
other.is_ascii_alphanumeric() || other == '_'
};
if !is_valid_char {
let error_position = self.position;
// Keep consuming chars until we find the closing double quote
// (unless we bumped into a double quote now, in which case we are done)
if other != '"' {
self.skip_until_string_end();
}
let span = Span::inclusive(error_position, error_position);
return Err(LexerErrorKind::InvalidFormatString { found: other, span });
}
first_char = false;
other
}
};
length += 1;
string.push(char);
}
length += 1; // for the closing curly brace
let interpolation_span = Span::from(interpolation_start..self.position);
fragments.push(FmtStrFragment::Interpolation(string, interpolation_span));
}
let token = Token::FmtStr(fragments, length);
let end = self.position;
Ok(token.into_span(start, end))
}
fn skip_until_string_end(&mut self) {
while let Some(next) = self.next_char() {
if next == '\'' && self.peek_char_is('"') {
self.next_char();
} else if next == '"' {
break;
}
}
}
fn eat_format_string_or_alpha_numeric(&mut self) -> SpannedTokenResult {
if self.peek_char_is('"') {
self.eat_fmt_string()
} else {
self.eat_alpha_numeric('f')
}
}
fn eat_raw_string(&mut self) -> SpannedTokenResult {
let start = self.position;
let beginning_hashes = self.eat_while(None, |ch| ch == '#');
let beginning_hashes_count = beginning_hashes.chars().count();
if beginning_hashes_count > 255 {
// too many hashes (unlikely in practice)
// also, Rust disallows 256+ hashes as well
return Err(LexerErrorKind::UnexpectedCharacter {
span: Span::single_char(start + 255),
found: Some('#'),
expected: "\"".to_owned(),
});
}
if !self.peek_char_is('"') {
return Err(LexerErrorKind::UnexpectedCharacter {
span: Span::single_char(self.position),
found: self.next_char(),
expected: "\"".to_owned(),
});
}
self.next_char();
let mut str_literal = String::new();
loop {
let chars = self.eat_while(None, |ch| ch != '"');
str_literal.push_str(&chars[..]);
if !self.peek_char_is('"') {
return Err(LexerErrorKind::UnexpectedCharacter {
span: Span::single_char(self.position),
found: self.next_char(),
expected: "\"".to_owned(),
});
}
self.next_char();
let mut ending_hashes_count = 0;
while let Some('#') = self.peek_char() {
if ending_hashes_count == beginning_hashes_count {
break;
}
self.next_char();
ending_hashes_count += 1;
}
if ending_hashes_count == beginning_hashes_count {
break;
} else {
str_literal.push('"');
for _ in 0..ending_hashes_count {
str_literal.push('#');
}
}
}
let str_literal_token = Token::RawStr(str_literal, beginning_hashes_count as u8);
let end = self.position;
Ok(str_literal_token.into_span(start, end))
}
fn eat_raw_string_or_alpha_numeric(&mut self) -> SpannedTokenResult {
// Problem: we commit to eating raw strings once we see one or two characters.
// This is unclean, but likely ok in all practical cases, and works with existing
// `Lexer` methods.
let peek1 = self.peek_char().unwrap_or('X');
let peek2 = self.peek2_char().unwrap_or('X');
match (peek1, peek2) {
('#', '#') | ('#', '"') | ('"', _) => self.eat_raw_string(),
_ => self.eat_alpha_numeric('r'),
}
}
fn eat_quote_or_alpha_numeric(&mut self) -> SpannedTokenResult {
let (start, word, end) = self.lex_word('q');
if word != "quote" {
return self.lookup_word_token(word, start, end);
}
let mut delimiter = self.next_token()?;
while let Token::Whitespace(_) = delimiter.token() {
delimiter = self.next_token()?;
}
let (start_delim, end_delim) = match delimiter.token() {
Token::LeftBrace => (Token::LeftBrace, Token::RightBrace),
Token::LeftBracket => (Token::LeftBracket, Token::RightBracket),
Token::LeftParen => (Token::LeftParen, Token::RightParen),
_ => return Err(LexerErrorKind::InvalidQuoteDelimiter { delimiter }),
};
let mut tokens = Vec::new();
// Keep track of each nested delimiter we need to close.
let mut nested_delimiters = vec![delimiter];
while !nested_delimiters.is_empty() {
let token = self.next_token()?;
if *token.token() == start_delim {
nested_delimiters.push(token.clone());
} else if *token.token() == end_delim {
nested_delimiters.pop();
} else if *token.token() == Token::EOF {
let start_delim =
nested_delimiters.pop().expect("If this were empty, we wouldn't be looping");
return Err(LexerErrorKind::UnclosedQuote { start_delim, end_delim });
}
tokens.push(token);
}
// Pop the closing delimiter from the token stream
if !tokens.is_empty() {
tokens.pop();
}
let end = self.position;
Ok(Token::Quote(Tokens(tokens)).into_span(start, end))
}
fn parse_comment(&mut self, start: u32) -> SpannedTokenResult {
let doc_style = match self.peek_char() {
Some('!') => {
self.next_char();
Some(DocStyle::Inner)
}
Some('/') if self.peek2_char() != '/'.into() => {
self.next_char();
Some(DocStyle::Outer)
}
_ => None,
};
let comment = self.eat_while(None, |ch| ch != '\n');
if !comment.is_ascii() {
let span = Span::from(start..self.position);
return Err(LexerErrorKind::NonAsciiComment { span });
}
Ok(Token::LineComment(comment, doc_style).into_span(start, self.position))
}
fn parse_block_comment(&mut self, start: u32) -> SpannedTokenResult {
let doc_style = match self.peek_char() {
Some('!') => {
self.next_char();
Some(DocStyle::Inner)
}
Some('*') if !matches!(self.peek2_char(), Some('*' | '/')) => {
self.next_char();
Some(DocStyle::Outer)
}
_ => None,
};
let mut depth = 1usize;
let mut content = String::new();
while let Some(ch) = self.next_char() {
match ch {
'/' if self.peek_char_is('*') => {
self.next_char();
depth += 1;
}
'*' if self.peek_char_is('/') => {
self.next_char();
depth -= 1;
// This block comment is closed, so for a construction like "/* */ */"
// there will be a successfully parsed block comment "/* */"
// and " */" will be processed separately.
if depth == 0 {
break;
}
}
ch => content.push(ch),
}
}
if depth == 0 {
if !content.is_ascii() {
let span = Span::from(start..self.position);
return Err(LexerErrorKind::NonAsciiComment { span });
}
Ok(Token::BlockComment(content, doc_style).into_span(start, self.position))
} else {
let span = Span::inclusive(start, self.position);
Err(LexerErrorKind::UnterminatedBlockComment { span })
}
}
fn is_code_whitespace(c: char) -> bool {
c == '\t' || c == '\n' || c == '\r' || c == ' '
}
/// Skips white space. They are not significant in the source language
fn eat_whitespace(&mut self, initial_char: char) -> SpannedToken {
let start = self.position;
let whitespace = self.eat_while(initial_char.into(), Self::is_code_whitespace);
SpannedToken::new(Token::Whitespace(whitespace), Span::inclusive(start, self.position))
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = SpannedTokenResult;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
None
} else {
Some(self.next_token())
}
}
}
#[cfg(test)]
mod tests {
use iter_extended::vecmap;
use super::*;
#[test]
fn test_single_multi_char() {
let input = "! != + ( ) { } [ ] | , ; : :: < <= > >= & - -> . .. ..= % / * = == << >>";
let expected = vec![
Token::Bang,
Token::NotEqual,
Token::Plus,
Token::LeftParen,
Token::RightParen,
Token::LeftBrace,
Token::RightBrace,
Token::LeftBracket,
Token::RightBracket,
Token::Pipe,
Token::Comma,
Token::Semicolon,
Token::Colon,
Token::DoubleColon,
Token::Less,
Token::LessEqual,
Token::Greater,
Token::GreaterEqual,
Token::Ampersand,
Token::Minus,
Token::Arrow,
Token::Dot,
Token::DoubleDot,
Token::DoubleDotEqual,
Token::Percent,
Token::Slash,
Token::Star,
Token::Assign,
Token::Equal,
Token::ShiftLeft,
Token::Greater,
Token::Greater,
Token::EOF,
];
let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let got = lexer.next_token().unwrap();
assert_eq!(got, token);
}
}
#[test]
fn invalid_attribute() {
let input = "#";
let mut lexer = Lexer::new(input);
let token = lexer.next().unwrap();
assert!(token.is_err());
}
#[test]
fn test_attribute_start() {
let input = r#"#[something]"#;
let mut lexer = Lexer::new(input);
let token = lexer.next_token().unwrap();
assert_eq!(token.token(), &Token::AttributeStart { is_inner: false, is_tag: false });
}
#[test]
fn test_attribute_start_with_tag() {
let input = r#"#['something]"#;
let mut lexer = Lexer::new(input);
let token = lexer.next_token().unwrap();
assert_eq!(token.token(), &Token::AttributeStart { is_inner: false, is_tag: true });
}
#[test]
fn test_inner_attribute_start() {
let input = r#"#![something]"#;
let mut lexer = Lexer::new(input);
let token = lexer.next_token().unwrap();
assert_eq!(token.token(), &Token::AttributeStart { is_inner: true, is_tag: false });
}
#[test]
fn test_inner_attribute_start_with_tag() {
let input = r#"#!['something]"#;
let mut lexer = Lexer::new(input);
let token = lexer.next_token().unwrap();
assert_eq!(token.token(), &Token::AttributeStart { is_inner: true, is_tag: true });
}
#[test]
fn test_int_type() {
let input = "u16 i16 i108 u104.5";
let expected = vec![
Token::IntType(IntType::Unsigned(16)),
Token::IntType(IntType::Signed(16)),
Token::IntType(IntType::Signed(108)),
Token::IntType(IntType::Unsigned(104)),
Token::Dot,
Token::Int(5_i128.into()),
];
let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let got = lexer.next_token().unwrap();
assert_eq!(got, token);
}
}
#[test]
fn test_int_too_large() {
let modulus = FieldElement::modulus();
let input = modulus.to_string();
let mut lexer = Lexer::new(&input);
let token = lexer.next_token();
assert!(
matches!(token, Err(LexerErrorKind::IntegerLiteralTooLarge { .. })),
"expected {input} to throw error"
);
}
#[test]
fn test_arithmetic_sugar() {
let input = "+= -= *= /= %=";
let expected = vec![
Token::Plus,
Token::Assign,
Token::Minus,
Token::Assign,
Token::Star,
Token::Assign,
Token::Slash,
Token::Assign,
Token::Percent,
Token::Assign,
];
let mut lexer = Lexer::new(input);