-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathmod.rs
More file actions
1431 lines (1280 loc) · 54.6 KB
/
mod.rs
File metadata and controls
1431 lines (1280 loc) · 54.6 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
use std::cmp::Ordering;
use bitflags::bitflags;
use ruff_python_ast::{Mod, ModExpression, ModModule};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::parser::expression::ExpressionContext;
use crate::parser::progress::{ParserProgress, TokenId};
use crate::token::TokenValue;
use crate::token_set::TokenSet;
use crate::token_source::{TokenSource, TokenSourceCheckpoint};
use crate::{Mode, ParseError, ParseErrorType, TokenKind};
use crate::{Parsed, Tokens};
pub use crate::parser::options::ParseOptions;
mod expression;
mod helpers;
mod options;
mod pattern;
mod progress;
mod recovery;
mod statement;
#[cfg(test)]
mod tests;
#[derive(Debug)]
pub(crate) struct Parser<'src> {
source: &'src str,
/// Token source for the parser that skips over any non-trivia token.
tokens: TokenSource<'src>,
/// Stores all the syntax errors found during the parsing.
errors: Vec<ParseError>,
/// Options for how the code will be parsed.
options: ParseOptions,
/// The ID of the current token. This is used to track the progress of the parser
/// to avoid infinite loops when the parser is stuck.
current_token_id: TokenId,
/// The end of the previous token processed. This is used to determine a node's end.
prev_token_end: TextSize,
/// The recovery context in which the parser is currently in.
recovery_context: RecoveryContext,
/// The start offset in the source code from which to start parsing at.
start_offset: TextSize,
}
impl<'src> Parser<'src> {
/// Create a new parser for the given source code.
pub(crate) fn new(source: &'src str, options: ParseOptions) -> Self {
Parser::new_starts_at(source, TextSize::new(0), options)
}
/// Create a new parser for the given source code which starts parsing at the given offset.
pub(crate) fn new_starts_at(
source: &'src str,
start_offset: TextSize,
options: ParseOptions,
) -> Self {
let tokens = TokenSource::from_source(source, options.mode, start_offset);
Parser {
options,
source,
errors: Vec::new(),
tokens,
recovery_context: RecoveryContext::empty(),
prev_token_end: TextSize::new(0),
start_offset,
current_token_id: TokenId::default(),
}
}
/// Consumes the [`Parser`] and returns the parsed [`Parsed`].
pub(crate) fn parse(mut self) -> Parsed<Mod> {
let syntax = match self.options.mode {
Mode::Expression | Mode::ParenthesizedExpression => {
Mod::Expression(self.parse_single_expression())
}
Mode::Module | Mode::Ipython => Mod::Module(self.parse_module()),
};
self.finish(syntax)
}
/// Parses a single expression.
///
/// This is to be used for [`Mode::Expression`].
///
/// ## Recovery
///
/// After parsing a single expression, an error is reported and all remaining tokens are
/// dropped by the parser.
fn parse_single_expression(&mut self) -> ModExpression {
let start = self.node_start();
let parsed_expr = self.parse_expression_list(ExpressionContext::default());
// All remaining newlines are actually going to be non-logical newlines.
self.eat(TokenKind::Newline);
if !self.at(TokenKind::EndOfFile) {
self.add_error(
ParseErrorType::UnexpectedExpressionToken,
self.current_token_range(),
);
// TODO(dhruvmanila): How should error recovery work here? Just truncate after the expression?
let mut progress = ParserProgress::default();
loop {
progress.assert_progressing(self);
if self.at(TokenKind::EndOfFile) {
break;
}
self.bump_any();
}
}
self.bump(TokenKind::EndOfFile);
ModExpression {
body: Box::new(parsed_expr.expr),
range: self.node_range(start),
}
}
/// Parses a Python module.
///
/// This is to be used for [`Mode::Module`] and [`Mode::Ipython`].
fn parse_module(&mut self) -> ModModule {
let body = self.parse_list_into_vec(
RecoveryContextKind::ModuleStatements,
Parser::parse_statement,
);
self.bump(TokenKind::EndOfFile);
ModModule {
body,
range: TextRange::new(self.start_offset, self.current_token_range().end()),
}
}
fn finish(self, syntax: Mod) -> Parsed<Mod> {
assert_eq!(
self.current_token_kind(),
TokenKind::EndOfFile,
"Parser should be at the end of the file."
);
// TODO consider re-integrating lexical error handling into the parser?
let parse_errors = self.errors;
let (tokens, lex_errors) = self.tokens.finish();
// Fast path for when there are no lex errors.
// There's no fast path for when there are no parse errors because a lex error
// always results in a parse error.
if lex_errors.is_empty() {
return Parsed {
syntax,
tokens: Tokens::new(tokens),
errors: parse_errors,
};
}
let mut merged = Vec::with_capacity(parse_errors.len().saturating_add(lex_errors.len()));
let mut parse_errors = parse_errors.into_iter().peekable();
let mut lex_errors = lex_errors.into_iter().peekable();
while let (Some(parse_error), Some(lex_error)) = (parse_errors.peek(), lex_errors.peek()) {
match parse_error
.location
.start()
.cmp(&lex_error.location().start())
{
Ordering::Less => merged.push(parse_errors.next().unwrap()),
Ordering::Equal => {
// Skip the parse error if we already have a lex error at the same location..
parse_errors.next().unwrap();
merged.push(lex_errors.next().unwrap().into());
}
Ordering::Greater => merged.push(lex_errors.next().unwrap().into()),
}
}
merged.extend(parse_errors);
merged.extend(lex_errors.map(ParseError::from));
Parsed {
syntax,
tokens: Tokens::new(tokens),
errors: merged,
}
}
/// Returns the start position for a node that starts at the current token.
fn node_start(&self) -> TextSize {
self.current_token_range().start()
}
fn node_range(&self, start: TextSize) -> TextRange {
// It's possible during error recovery that the parsing didn't consume any tokens. In that
// case, `last_token_end` still points to the end of the previous token but `start` is the
// start of the current token. Calling `TextRange::new(start, self.last_token_end)` would
// panic in that case because `start > end`. This path "detects" this case and creates an
// empty range instead.
//
// The reason it's `<=` instead of just `==` is because there could be whitespaces between
// the two tokens. For example:
//
// ```python
// # last token end
// # | current token (newline) start
// # v v
// def foo \n
// # ^
// # assume there's trailing whitespace here
// ```
//
// Or, there could tokens that are considered "trivia" and thus aren't emitted by the token
// source. These are comments and non-logical newlines. For example:
//
// ```python
// # last token end
// # v
// def foo # comment\n
// # ^ current token (newline) start
// ```
//
// In either of the above cases, there's a "gap" between the end of the last token and start
// of the current token.
if self.prev_token_end <= start {
// We need to create an empty range at the last token end instead of the start because
// otherwise this node range will fall outside the range of it's parent node. Taking
// the above example:
//
// ```python
// if True:
// # function start
// # | function end
// # v v
// def foo # comment
// # ^ current token start
// ```
//
// Here, the current token start is the start of parameter range but the function ends
// at `foo`. Even if there's a function body, the range of parameters would still be
// before the comment.
// test_err node_range_with_gaps
// def foo # comment
// def bar(): ...
// def baz
TextRange::empty(self.prev_token_end)
} else {
TextRange::new(start, self.prev_token_end)
}
}
fn missing_node_range(&self) -> TextRange {
// TODO(dhruvmanila): This range depends on whether the missing node is
// on the leftmost or the rightmost of the expression. It's incorrect for
// the leftmost missing node because the range is outside the expression
// range. For example,
//
// ```python
// value = ** y
// # ^^^^ expression range
// # ^ last token end
// ```
TextRange::empty(self.prev_token_end)
}
/// Moves the parser to the next token.
fn do_bump(&mut self, kind: TokenKind) {
if !matches!(
self.current_token_kind(),
// TODO explore including everything up to the dedent as part of the body.
TokenKind::Dedent
// Don't include newlines in the body
| TokenKind::Newline
// TODO(micha): Including the semi feels more correct but it isn't compatible with lalrpop and breaks the
// formatters semicolon detection. Exclude it for now
| TokenKind::Semi
) {
self.prev_token_end = self.current_token_range().end();
}
self.tokens.bump(kind);
self.current_token_id.increment();
}
/// Returns the next token kind without consuming it.
fn peek(&mut self) -> TokenKind {
self.tokens.peek()
}
/// Returns the next two token kinds without consuming it.
fn peek2(&mut self) -> (TokenKind, TokenKind) {
self.tokens.peek2()
}
/// Returns the current token kind.
#[inline]
fn current_token_kind(&self) -> TokenKind {
self.tokens.current_kind()
}
/// Returns the range of the current token.
#[inline]
fn current_token_range(&self) -> TextRange {
self.tokens.current_range()
}
/// Returns the current token ID.
#[inline]
fn current_token_id(&self) -> TokenId {
self.current_token_id
}
/// Bumps the current token assuming it is of the given kind.
///
/// # Panics
///
/// If the current token is not of the given kind.
fn bump(&mut self, kind: TokenKind) {
assert_eq!(self.current_token_kind(), kind);
self.do_bump(kind);
}
/// Take the token value from the underlying token source and bump the current token.
///
/// # Panics
///
/// If the current token is not of the given kind.
fn bump_value(&mut self, kind: TokenKind) -> TokenValue {
let value = self.tokens.take_value();
self.bump(kind);
value
}
/// Bumps the current token assuming it is found in the given token set.
///
/// # Panics
///
/// If the current token is not found in the given token set.
fn bump_ts(&mut self, ts: TokenSet) {
let kind = self.current_token_kind();
assert!(ts.contains(kind));
self.do_bump(kind);
}
/// Bumps the current token regardless of its kind and advances to the next token.
///
/// # Panics
///
/// If the parser is at end of file.
fn bump_any(&mut self) {
let kind = self.current_token_kind();
assert_ne!(kind, TokenKind::EndOfFile);
self.do_bump(kind);
}
/// Bumps the soft keyword token as a `Name` token.
///
/// # Panics
///
/// If the current token is not a soft keyword.
pub(crate) fn bump_soft_keyword_as_name(&mut self) {
assert!(self.at_soft_keyword());
self.do_bump(TokenKind::Name);
}
/// Consume the current token if it is of the given kind. Returns `true` if it matches, `false`
/// otherwise.
fn eat(&mut self, kind: TokenKind) -> bool {
if self.at(kind) {
self.do_bump(kind);
true
} else {
false
}
}
/// Eat the current token if its of the expected kind, otherwise adds an appropriate error.
fn expect(&mut self, expected: TokenKind) -> bool {
if self.eat(expected) {
return true;
}
self.add_error(
ParseErrorType::ExpectedToken {
found: self.current_token_kind(),
expected,
},
self.current_token_range(),
);
false
}
fn add_error<T>(&mut self, error: ParseErrorType, ranged: T)
where
T: Ranged,
{
fn inner(errors: &mut Vec<ParseError>, error: ParseErrorType, range: TextRange) {
// Avoid flagging multiple errors at the same location
let is_same_location = errors
.last()
.is_some_and(|last| last.location.start() == range.start());
if !is_same_location {
errors.push(ParseError {
error,
location: range,
});
}
}
inner(&mut self.errors, error, ranged.range());
}
/// Returns `true` if the current token is of the given kind.
fn at(&self, kind: TokenKind) -> bool {
self.current_token_kind() == kind
}
/// Returns `true` if the current token is found in the given token set.
fn at_ts(&self, ts: TokenSet) -> bool {
ts.contains(self.current_token_kind())
}
fn src_text<T>(&self, ranged: T) -> &'src str
where
T: Ranged,
{
&self.source[ranged.range()]
}
/// Parses a list of elements into a vector where each element is parsed using
/// the given `parse_element` function.
fn parse_list_into_vec<T>(
&mut self,
recovery_context_kind: RecoveryContextKind,
parse_element: impl Fn(&mut Parser<'src>) -> T,
) -> Vec<T> {
let mut elements = Vec::new();
self.parse_list(recovery_context_kind, |p| elements.push(parse_element(p)));
elements
}
/// Parses a list of elements where each element is parsed using the given
/// `parse_element` function.
///
/// The difference between this function and `parse_list_into_vec` is that
/// this function does not return the parsed elements. Instead, it is the
/// caller's responsibility to handle the parsed elements. This is the reason
/// that the `parse_element` parameter is bound to [`FnMut`] instead of [`Fn`].
fn parse_list(
&mut self,
recovery_context_kind: RecoveryContextKind,
mut parse_element: impl FnMut(&mut Parser<'src>),
) {
let mut progress = ParserProgress::default();
let saved_context = self.recovery_context;
self.recovery_context = self
.recovery_context
.union(RecoveryContext::from_kind(recovery_context_kind));
loop {
progress.assert_progressing(self);
if recovery_context_kind.is_list_element(self) {
parse_element(self);
} else if recovery_context_kind.is_regular_list_terminator(self) {
break;
} else {
// Run the error recovery: If the token is recognised as an element or terminator
// of an enclosing list, then we try to re-lex in the context of a logical line and
// break out of list parsing.
if self.is_enclosing_list_element_or_terminator() {
self.tokens.re_lex_logical_token();
break;
}
self.add_error(
recovery_context_kind.create_error(self),
self.current_token_range(),
);
self.bump_any();
}
}
self.recovery_context = saved_context;
}
/// Parses a comma separated list of elements into a vector where each element
/// is parsed using the given `parse_element` function.
fn parse_comma_separated_list_into_vec<T>(
&mut self,
recovery_context_kind: RecoveryContextKind,
parse_element: impl Fn(&mut Parser<'src>) -> T,
) -> Vec<T> {
let mut elements = Vec::new();
self.parse_comma_separated_list(recovery_context_kind, |p| elements.push(parse_element(p)));
elements
}
/// Parses a comma separated list of elements where each element is parsed
/// sing the given `parse_element` function.
///
/// The difference between this function and `parse_comma_separated_list_into_vec`
/// is that this function does not return the parsed elements. Instead, it is the
/// caller's responsibility to handle the parsed elements. This is the reason
/// that the `parse_element` parameter is bound to [`FnMut`] instead of [`Fn`].
fn parse_comma_separated_list(
&mut self,
recovery_context_kind: RecoveryContextKind,
mut parse_element: impl FnMut(&mut Parser<'src>),
) {
let mut progress = ParserProgress::default();
let saved_context = self.recovery_context;
self.recovery_context = self
.recovery_context
.union(RecoveryContext::from_kind(recovery_context_kind));
let mut first_element = true;
let mut trailing_comma_range: Option<TextRange> = None;
loop {
progress.assert_progressing(self);
if recovery_context_kind.is_list_element(self) {
parse_element(self);
// Only unset this when we've completely parsed a single element. This is mainly to
// raise the correct error in case the first element isn't valid and the current
// token isn't a comma. Without this knowledge, the parser would later expect a
// comma instead of raising the context error.
first_element = false;
let maybe_comma_range = self.current_token_range();
if self.eat(TokenKind::Comma) {
trailing_comma_range = Some(maybe_comma_range);
continue;
}
trailing_comma_range = None;
}
// test_ok comma_separated_regular_list_terminator
// # The first element is parsed by `parse_list_like_expression` and the comma after
// # the first element is expected by `parse_list_expression`
// [0]
// [0, 1]
// [0, 1,]
// [0, 1, 2]
// [0, 1, 2,]
if recovery_context_kind.is_regular_list_terminator(self) {
break;
}
// test_err comma_separated_missing_comma_between_elements
// # The comma between the first two elements is expected in `parse_list_expression`.
// [0, 1 2]
if recovery_context_kind.is_list_element(self) {
// This is a special case to expect a comma between two elements and should be
// checked before running the error recovery. This is because the error recovery
// will always run as the parser is currently at a list element.
self.expect(TokenKind::Comma);
continue;
}
// Run the error recovery: If the token is recognised as an element or terminator of an
// enclosing list, then we try to re-lex in the context of a logical line and break out
// of list parsing.
if self.is_enclosing_list_element_or_terminator() {
self.tokens.re_lex_logical_token();
break;
}
if first_element || self.at(TokenKind::Comma) {
// There are two conditions when we need to add the recovery context error:
//
// 1. If the parser is at a comma which means that there's a missing element
// otherwise the comma would've been consumed by the first `eat` call above.
// And, the parser doesn't take the re-lexing route on a comma token.
// 2. If it's the first element and the current token is not a comma which means
// that it's an invalid element.
// test_err comma_separated_missing_element_between_commas
// [0, 1, , 2]
// test_err comma_separated_missing_first_element
// call(= 1)
self.add_error(
recovery_context_kind.create_error(self),
self.current_token_range(),
);
trailing_comma_range = if self.at(TokenKind::Comma) {
Some(self.current_token_range())
} else {
None
};
} else {
// Otherwise, there should've been a comma at this position. This could be because
// the element isn't consumed completely by `parse_element`.
// test_err comma_separated_missing_comma
// call(**x := 1)
self.expect(TokenKind::Comma);
trailing_comma_range = None;
}
self.bump_any();
}
if let Some(trailing_comma_range) = trailing_comma_range {
if !recovery_context_kind.allow_trailing_comma() {
self.add_error(
ParseErrorType::OtherError("Trailing comma not allowed".to_string()),
trailing_comma_range,
);
}
}
self.recovery_context = saved_context;
}
#[cold]
fn is_enclosing_list_element_or_terminator(&self) -> bool {
for context in self.recovery_context.kind_iter() {
if context.is_list_terminator(self) || context.is_list_element(self) {
return true;
}
}
false
}
/// Creates a checkpoint to which the parser can later return to using [`Self::rewind`].
fn checkpoint(&self) -> ParserCheckpoint {
ParserCheckpoint {
tokens: self.tokens.checkpoint(),
errors_position: self.errors.len(),
current_token_id: self.current_token_id,
prev_token_end: self.prev_token_end,
recovery_context: self.recovery_context,
}
}
/// Restore the parser to the given checkpoint.
fn rewind(&mut self, checkpoint: ParserCheckpoint) {
let ParserCheckpoint {
tokens,
errors_position,
current_token_id,
prev_token_end,
recovery_context,
} = checkpoint;
self.tokens.rewind(tokens);
self.errors.truncate(errors_position);
self.current_token_id = current_token_id;
self.prev_token_end = prev_token_end;
self.recovery_context = recovery_context;
}
}
struct ParserCheckpoint {
tokens: TokenSourceCheckpoint,
errors_position: usize,
current_token_id: TokenId,
prev_token_end: TextSize,
recovery_context: RecoveryContext,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum SequenceMatchPatternParentheses {
Tuple,
List,
}
impl SequenceMatchPatternParentheses {
/// Returns the token kind that closes the parentheses.
const fn closing_kind(self) -> TokenKind {
match self {
SequenceMatchPatternParentheses::Tuple => TokenKind::Rpar,
SequenceMatchPatternParentheses::List => TokenKind::Rsqb,
}
}
/// Returns `true` if the parentheses are for a list pattern e.g., `case [a, b]: ...`.
const fn is_list(self) -> bool {
matches!(self, SequenceMatchPatternParentheses::List)
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
enum FunctionKind {
/// A lambda expression, e.g., `lambda x: x`
Lambda,
/// A function definition, e.g., `def f(x): ...`
FunctionDef,
}
impl FunctionKind {
/// Returns the token that terminates a list of parameters.
const fn list_terminator(self) -> TokenKind {
match self {
FunctionKind::Lambda => TokenKind::Colon,
FunctionKind::FunctionDef => TokenKind::Rpar,
}
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
enum WithItemKind {
/// A list of `with` items that are surrounded by parentheses.
///
/// ```python
/// with (item1, item2): ...
/// with (item1, item2 as foo): ...
/// ```
///
/// The parentheses belongs to the `with` statement.
Parenthesized,
/// The `with` item has a parenthesized expression.
///
/// ```python
/// with (item) as foo: ...
/// ```
///
/// The parentheses belongs to the context expression.
ParenthesizedExpression,
/// The `with` items aren't parenthesized in any way.
///
/// ```python
/// with item: ...
/// with item as foo: ...
/// with item1, item2: ...
/// ```
///
/// There are no parentheses around the items.
Unparenthesized,
}
impl WithItemKind {
/// Returns `true` if the with items are parenthesized.
const fn is_parenthesized(self) -> bool {
matches!(self, WithItemKind::Parenthesized)
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
enum FStringElementsKind {
/// The regular f-string elements.
///
/// For example, the `"hello "`, `x`, and `" world"` elements in:
/// ```py
/// f"hello {x:.2f} world"
/// ```
Regular,
/// The f-string elements are part of the format specifier.
///
/// For example, the `.2f` in:
/// ```py
/// f"hello {x:.2f} world"
/// ```
FormatSpec,
}
impl FStringElementsKind {
const fn list_terminator(self) -> TokenKind {
match self {
FStringElementsKind::Regular => TokenKind::FStringEnd,
// test_ok fstring_format_spec_terminator
// f"hello {x:} world"
// f"hello {x:.3f} world"
FStringElementsKind::FormatSpec => TokenKind::Rbrace,
}
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
enum Parenthesized {
/// The elements are parenthesized, e.g., `(a, b)`.
Yes,
/// The elements are not parenthesized, e.g., `a, b`.
No,
}
impl From<bool> for Parenthesized {
fn from(value: bool) -> Self {
if value {
Parenthesized::Yes
} else {
Parenthesized::No
}
}
}
impl Parenthesized {
/// Returns `true` if the parenthesized value is `Yes`.
const fn is_yes(self) -> bool {
matches!(self, Parenthesized::Yes)
}
}
#[derive(Copy, Clone, Debug)]
enum ListTerminatorKind {
/// The current token terminates the list.
Regular,
/// The current token doesn't terminate the list, but is useful for better error recovery.
ErrorRecovery,
}
#[derive(Copy, Clone, Debug)]
enum RecoveryContextKind {
/// When parsing a list of statements at the module level i.e., at the top level of a file.
ModuleStatements,
/// When parsing a list of statements in a block e.g., the body of a function or a class.
BlockStatements,
/// The `elif` clauses of an `if` statement
Elif,
/// The `except` clauses of a `try` statement
Except,
/// When parsing a list of assignment targets
AssignmentTargets,
/// When parsing a list of type parameters
TypeParams,
/// When parsing a list of names in a `from ... import ...` statement
ImportFromAsNames(Parenthesized),
/// When parsing a list of names in an `import` statement
ImportNames,
/// When parsing a list of slice elements e.g., `data[1, 2]`.
///
/// This is different from `ListElements` as the surrounding context is
/// different in that the list is part of a subscript expression.
Slices,
/// When parsing a list of elements in a list expression e.g., `[1, 2]`
ListElements,
/// When parsing a list of elements in a set expression e.g., `{1, 2}`
SetElements,
/// When parsing a list of elements in a dictionary expression e.g., `{1: "a", **data}`
DictElements,
/// When parsing a list of elements in a tuple expression e.g., `(1, 2)`
TupleElements(Parenthesized),
/// When parsing a list of patterns in a match statement with an optional
/// parentheses, e.g., `case a, b: ...`, `case (a, b): ...`, `case [a, b]: ...`
SequenceMatchPattern(Option<SequenceMatchPatternParentheses>),
/// When parsing a mapping pattern in a match statement
MatchPatternMapping,
/// When parsing a list of arguments in a class pattern for the match statement
MatchPatternClassArguments,
/// When parsing a list of arguments in a function call or a class definition
Arguments,
/// When parsing a `del` statement
DeleteTargets,
/// When parsing a list of identifiers
Identifiers,
/// When parsing a list of parameters in a function definition which can be
/// either a function definition or a lambda expression.
Parameters(FunctionKind),
/// When parsing a list of items in a `with` statement
WithItems(WithItemKind),
/// When parsing a list of f-string elements which are either literal elements
/// or expressions.
FStringElements(FStringElementsKind),
}
impl RecoveryContextKind {
/// Returns `true` if a trailing comma is allowed in the current context.
const fn allow_trailing_comma(self) -> bool {
matches!(
self,
RecoveryContextKind::Slices
| RecoveryContextKind::TupleElements(_)
| RecoveryContextKind::SetElements
| RecoveryContextKind::ListElements
| RecoveryContextKind::DictElements
| RecoveryContextKind::Arguments
| RecoveryContextKind::MatchPatternMapping
| RecoveryContextKind::SequenceMatchPattern(_)
| RecoveryContextKind::MatchPatternClassArguments
// Only allow a trailing comma if the with item itself is parenthesized
| RecoveryContextKind::WithItems(WithItemKind::Parenthesized)
| RecoveryContextKind::Parameters(_)
| RecoveryContextKind::TypeParams
| RecoveryContextKind::DeleteTargets
| RecoveryContextKind::ImportFromAsNames(Parenthesized::Yes)
)
}
/// Returns `true` if the parser is at a token that terminates the list as per the context.
///
/// This token could either end the list or is only present for better error recovery. Refer to
/// [`is_regular_list_terminator`] to only check against the former.
///
/// [`is_regular_list_terminator`]: RecoveryContextKind::is_regular_list_terminator
fn is_list_terminator(self, p: &Parser) -> bool {
self.list_terminator_kind(p).is_some()
}
/// Returns `true` if the parser is at a token that terminates the list as per the context but
/// the token isn't part of the error recovery set.
fn is_regular_list_terminator(self, p: &Parser) -> bool {
matches!(
self.list_terminator_kind(p),
Some(ListTerminatorKind::Regular)
)
}
/// Checks the current token the parser is at and returns the list terminator kind if the token
/// terminates the list as per the context.
fn list_terminator_kind(self, p: &Parser) -> Option<ListTerminatorKind> {
// The end of file marker ends all lists.
if p.at(TokenKind::EndOfFile) {
return Some(ListTerminatorKind::Regular);
}
match self {
// The parser must consume all tokens until the end
RecoveryContextKind::ModuleStatements => None,
RecoveryContextKind::BlockStatements => p
.at(TokenKind::Dedent)
.then_some(ListTerminatorKind::Regular),
RecoveryContextKind::Elif => {
p.at(TokenKind::Else).then_some(ListTerminatorKind::Regular)
}
RecoveryContextKind::Except => {
matches!(p.current_token_kind(), TokenKind::Finally | TokenKind::Else)
.then_some(ListTerminatorKind::Regular)
}
RecoveryContextKind::AssignmentTargets => {
// test_ok assign_targets_terminator
// x = y = z = 1; a, b
// x = y = z = 1
// a, b
matches!(p.current_token_kind(), TokenKind::Newline | TokenKind::Semi)
.then_some(ListTerminatorKind::Regular)
}
// Tokens other than `]` are for better error recovery. For example, recover when we
// find the `:` of a clause header or the equal of a type assignment.
RecoveryContextKind::TypeParams => {
if p.at(TokenKind::Rsqb) {
Some(ListTerminatorKind::Regular)
} else {
matches!(
p.current_token_kind(),
TokenKind::Newline | TokenKind::Colon | TokenKind::Equal | TokenKind::Lpar
)
.then_some(ListTerminatorKind::ErrorRecovery)
}
}
// The names of an import statement cannot be parenthesized, so `)` is not a
// terminator.
RecoveryContextKind::ImportNames => {
// test_ok import_stmt_terminator