Repository navigation
Expand file tree
/
Copy patherror.rs
More file actions
1659 lines (1576 loc) · 63.3 KB
/
Copy patherror.rs
File metadata and controls
1659 lines (1576 loc) · 63.3 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::fmt::{self, Display};
use ruff_python_ast::token::TokenKind;
use ruff_python_ast::{ConstantValue, Expr, PythonVersion};
use ruff_text_size::{Ranged, TextRange};
use crate::string::InterpolatedStringKind;
/// Represents represent errors that occur during parsing and are
/// returned by the `parse_*` functions.
#[derive(Debug, PartialEq, Eq, Clone, get_size2::GetSize)]
pub struct ParseError {
pub error: ParseErrorType,
pub location: TextRange,
}
impl std::ops::Deref for ParseError {
type Target = ParseErrorType;
fn deref(&self) -> &Self::Target {
&self.error
}
}
impl std::error::Error for ParseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{} at byte range {:?}", self.error, self.location)
}
}
impl From<LexicalError> for ParseError {
fn from(error: LexicalError) -> Self {
ParseError {
location: error.location(),
error: ParseErrorType::Lexical(error.into_error()),
}
}
}
impl Ranged for ParseError {
fn range(&self) -> TextRange {
self.location
}
}
impl ParseError {
pub fn error(self) -> ParseErrorType {
self.error
}
}
/// The reason an escape sequence in a string literal cannot be decoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, get_size2::GetSize)]
pub enum UnicodeEscapeErrorKind {
/// `\x` is not followed by two hexadecimal digits.
TruncatedHexByte,
/// `\u` is not followed by four hexadecimal digits.
TruncatedShortUnicode,
/// `\U` is not followed by eight hexadecimal digits.
TruncatedLongUnicode,
/// `\U` names a code point above `U+10FFFF`.
IllegalCharacter,
/// `\N` is not followed by a non-empty name in braces.
MalformedName,
/// `\N{...}` names no Unicode character.
UnknownName,
}
impl Display for UnicodeEscapeErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::TruncatedHexByte => "truncated \\xXX escape",
Self::TruncatedShortUnicode => "truncated \\uXXXX escape",
Self::TruncatedLongUnicode => "truncated \\UXXXXXXXX escape",
Self::IllegalCharacter => "illegal Unicode character",
Self::MalformedName => "malformed \\N character escape",
Self::UnknownName => "unknown Unicode character name",
})
}
}
/// Represents the different types of errors that can occur during parsing of an f-string or t-string.
#[derive(Debug, Clone, PartialEq, Eq, get_size2::GetSize)]
pub enum InterpolatedStringErrorType {
/// Expected a right brace after an opened left brace.
UnclosedLbrace,
/// An invalid conversion flag was encountered.
InvalidConversionFlag,
/// A single right brace was encountered.
SingleRbrace,
/// Unterminated string, detected at the given one-based line.
UnterminatedString { detected_line: u32 },
/// Unterminated triple-quoted string, detected at the given one-based line.
UnterminatedTripleQuotedString { detected_line: u32 },
/// A lambda expression without parentheses was encountered.
LambdaWithoutParentheses,
/// Conversion flag does not immediately follow exclamation.
ConversionFlagNotImmediatelyAfterExclamation,
/// Newline inside of a format spec for a single quoted f- or t-string.
NewlineInFormatSpec,
/// A replacement field has no expression before the given separator.
ExpressionRequiredBefore(char),
/// A replacement field does not start with an expression.
ExpectedExpressionAfterLbrace,
/// The expression of a replacement field is not followed by `=`, `!`, `:` or `}`.
ExpectedSeparatorAfterExpression,
/// The `=` of a replacement field is not followed by `!`, `:` or `}`.
ExpectedSeparatorAfterDebug,
/// The conversion of a replacement field is not followed by `:` or `}`.
ExpectedSeparatorAfterConversion,
/// The format spec of a replacement field is not followed by `}`.
UnclosedFormatSpec,
/// A `!` is directly followed by `:` or `}`.
MissingConversionFlag,
/// A closing bracket closes the brace that opens a replacement field.
UnmatchedBracket(char),
}
impl std::fmt::Display for InterpolatedStringErrorType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Self::UnclosedLbrace => f.write_str("expecting '}'"),
Self::InvalidConversionFlag => write!(f, "invalid conversion character"),
Self::SingleRbrace => f.write_str("single '}' is not allowed"),
Self::UnterminatedString { .. } => write!(f, "unterminated string"),
Self::UnterminatedTripleQuotedString { .. } => {
write!(f, "unterminated triple-quoted string")
}
Self::LambdaWithoutParentheses => {
write!(f, "lambda expressions are not allowed without parentheses")
}
Self::ConversionFlagNotImmediatelyAfterExclamation => write!(
f,
"conversion type must come right after the exclamation mark"
),
Self::NewlineInFormatSpec => {
write!(
f,
"newlines are not allowed in format specifiers when using single quotes"
)
}
Self::ExpressionRequiredBefore(separator) => {
write!(f, "valid expression required before '{separator}'")
}
Self::ExpectedExpressionAfterLbrace => {
f.write_str("expecting a valid expression after '{'")
}
Self::ExpectedSeparatorAfterExpression => {
f.write_str("expecting '=', or '!', or ':', or '}'")
}
Self::ExpectedSeparatorAfterDebug => f.write_str("expecting '!', or ':', or '}'"),
Self::ExpectedSeparatorAfterConversion => f.write_str("expecting ':' or '}'"),
Self::UnclosedFormatSpec => f.write_str("expecting '}', or format specs"),
Self::MissingConversionFlag => f.write_str("missing conversion character"),
Self::UnmatchedBracket(closing) => write!(f, "unmatched '{closing}'"),
}
}
}
fn write_interpolated_string_error(
f: &mut std::fmt::Formatter,
kind: InterpolatedStringKind,
error: &InterpolatedStringErrorType,
) -> std::fmt::Result {
match error {
InterpolatedStringErrorType::UnterminatedString { detected_line } => {
write!(
f,
"unterminated {kind} literal (detected at line {detected_line})"
)
}
InterpolatedStringErrorType::UnterminatedTripleQuotedString { detected_line } => {
write!(
f,
"unterminated triple-quoted {kind} literal (detected at line {detected_line})"
)
}
InterpolatedStringErrorType::NewlineInFormatSpec => write!(
f,
"{kind}: newlines are not allowed in format specifiers for single quoted {kind}s"
),
_ => write!(f, "{kind}: {error}"),
}
}
/// Represents the different types of errors that can occur during parsing.
#[derive(Debug, PartialEq, Eq, Clone, get_size2::GetSize)]
pub enum ParseErrorType {
/// An unexpected error occurred.
OtherError(String),
/// An error specific to stringified annotations occurred.
StringAnnotationError(&'static str),
/// An empty slice was found during parsing, e.g `data[]`.
EmptySlice,
/// An empty global names list was found during parsing.
EmptyGlobalNames,
/// An empty nonlocal names list was found during parsing.
EmptyNonlocalNames,
/// An empty delete targets list was found during parsing.
EmptyDeleteTargets,
/// An empty import names list was found during parsing.
EmptyImportNames,
/// An empty type parameter list was found during parsing.
EmptyTypeParams,
/// An unparenthesized named expression was found where it is not allowed.
UnparenthesizedNamedExpression,
/// An unparenthesized tuple expression was found where it is not allowed.
UnparenthesizedTupleExpression,
/// An unparenthesized generator expression was found where it is not allowed.
UnparenthesizedGeneratorExpression,
/// An invalid usage of a lambda expression was found.
InvalidLambdaExpressionUsage,
/// An invalid usage of a yield expression was found.
InvalidYieldExpressionUsage,
/// An invalid usage of a starred expression was found.
InvalidStarredExpressionUsage,
/// A star pattern was found outside a sequence pattern.
InvalidStarPatternUsage,
/// An underscore was used as a binding target in a match pattern.
InvalidMatchPatternTarget,
/// A parameter was found after a vararg.
ParamAfterVarKeywordParam,
/// A non-default parameter follows a default parameter.
NonDefaultParamAfterDefaultParam,
/// A default value was found for a `*` or `**` parameter.
VarParameterWithDefault,
/// A default value was found for a `**` parameter.
VarKeywordParameterWithDefault,
/// A dictionary key after the first item is not followed by a `:`. The error range is the
/// last character of the key.
ExpectedColonAfterDictionaryKey,
/// An invalid expression was found in the assignment target. `maybe_comparison` is set when
/// the `=` after it may have been meant as `==`.
InvalidAssignmentTarget {
kind: ExpressionKind,
maybe_comparison: bool,
},
/// A name is assigned to where `==` or `:=` may have been meant.
AssignmentInsteadOfComparison,
/// A `yield` expression is assigned to.
AssignmentToYield,
/// An invalid expression was found in the named assignment target.
InvalidNamedAssignmentTarget(ExpressionKind),
/// An invalid expression was found in the annotated assignment target.
InvalidAnnotatedAssignmentTarget,
/// An invalid expression was found in the augmented assignment target.
InvalidAugmentedAssignmentTarget(ExpressionKind),
/// An invalid expression was found in the delete target.
InvalidDeleteTarget(ExpressionKind),
/// An invalid expression was found after `as` in an import.
InvalidImportTarget(ExpressionKind),
/// An invalid expression was found after `as` in a pattern.
InvalidPatternTarget(ExpressionKind),
/// An invalid expression was found after `as` in an `except` or `except*` clause.
InvalidExceptTarget { kind: ExpressionKind, star: bool },
/// A positional argument was found after a keyword argument.
PositionalAfterKeywordArgument,
/// A positional argument was found after a keyword argument unpacking.
PositionalAfterKeywordUnpacking,
/// An iterable argument unpacking was found after keyword argument unpacking.
InvalidArgumentUnpackingOrder,
/// An invalid usage of iterable unpacking in a comprehension was found.
IterableUnpackingInComprehension,
/// Multiple simple statements were found in the same line without a `;` separating them.
SimpleStatementsOnSameLine,
/// A simple statement and a compound statement was found in the same line.
SimpleAndCompoundStatementOnSameLine,
/// Expected one or more keyword parameter after `*` separator.
ExpectedKeywordParam,
/// Expected a real number for a complex literal pattern.
ExpectedRealNumber,
/// Expected an imaginary number for a complex literal pattern.
ExpectedImaginaryNumber,
/// Expected an expression at the current parser location.
ExpectedExpression,
/// Expected an identifier at the current parser location.
ExpectedIdentifier,
/// The parser expected a specific token that was not found.
ExpectedToken {
expected: TokenKind,
found: TokenKind,
},
/// A token that the grammar requires right after the preceding ones (a forced token, `&&`
/// in the PEG grammar) was not found.
ExpectedForcedToken {
expected: TokenKind,
found: TokenKind,
},
/// A compound statement header is not followed by an indented block. `line` is the line of
/// the header's keyword.
ExpectedIndentedBlock { clause: BlockClause, line: u32 },
/// An unexpected indentation was found during parsing.
UnexpectedIndentation,
/// The statement being parsed cannot be `async`.
UnexpectedTokenAfterAsync(TokenKind),
/// Ipython escape command was found
UnexpectedIpythonEscapeCommand,
/// An unexpected token was found at the end of an expression parsing
UnexpectedExpressionToken,
/// An f-string error containing the [`InterpolatedStringErrorType`].
FStringError(InterpolatedStringErrorType),
/// A t-string error containing the [`InterpolatedStringErrorType`].
TStringError(InterpolatedStringErrorType),
/// Parser encountered an error during lexing.
Lexical(LexicalErrorType),
}
/// The kind of an expression, as syntax errors name it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, get_size2::GetSize)]
pub enum ExpressionKind {
Attribute,
Subscript,
Starred,
Name,
List,
Tuple,
Lambda,
FunctionCall,
Expression,
GeneratorExpression,
YieldExpression,
AwaitExpression,
ListComprehension,
SetComprehension,
DictComprehension,
DictLiteral,
SetDisplay,
FStringExpression,
TStringExpression,
None,
False,
True,
Ellipsis,
Literal,
Comparison,
ConditionalExpression,
NamedExpression,
}
impl ExpressionKind {
pub fn of(expr: &Expr) -> Self {
match expr {
Expr::Attribute(_) => Self::Attribute,
Expr::Subscript(_) => Self::Subscript,
Expr::Starred(_) => Self::Starred,
Expr::Name(_) => Self::Name,
Expr::List(_) => Self::List,
Expr::Tuple(_) => Self::Tuple,
Expr::Lambda(_) => Self::Lambda,
Expr::Call(_) => Self::FunctionCall,
Expr::BoolOp(_)
| Expr::BinOp(_)
| Expr::UnaryOp(_)
| Expr::Slice(_)
| Expr::IpyEscapeCommand(_) => Self::Expression,
Expr::Generator(_) => Self::GeneratorExpression,
Expr::Yield(_) | Expr::YieldFrom(_) => Self::YieldExpression,
Expr::Await(_) => Self::AwaitExpression,
Expr::ListComp(_) => Self::ListComprehension,
Expr::SetComp(_) => Self::SetComprehension,
Expr::DictComp(_) => Self::DictComprehension,
Expr::Dict(_) => Self::DictLiteral,
Expr::Set(_) => Self::SetDisplay,
Expr::FString(_) => Self::FStringExpression,
Expr::TString(_) => Self::TStringExpression,
Expr::NoneLiteral(_) => Self::None,
Expr::BooleanLiteral(literal) if literal.value => Self::True,
Expr::BooleanLiteral(_) => Self::False,
Expr::EllipsisLiteral(_) => Self::Ellipsis,
Expr::StringLiteral(_) | Expr::BytesLiteral(_) | Expr::NumberLiteral(_) => {
Self::Literal
}
Expr::Compare(_) => Self::Comparison,
Expr::If(_) => Self::ConditionalExpression,
Expr::Named(_) => Self::NamedExpression,
Expr::Constant(constant) => match constant.value {
ConstantValue::None => Self::None,
ConstantValue::Boolean(true) => Self::True,
ConstantValue::Boolean(false) => Self::False,
ConstantValue::Ellipsis => Self::Ellipsis,
_ => Self::Literal,
},
}
}
}
impl std::fmt::Display for ExpressionKind {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(match self {
Self::Attribute => "attribute",
Self::Subscript => "subscript",
Self::Starred => "starred",
Self::Name => "name",
Self::List => "list",
Self::Tuple => "tuple",
Self::Lambda => "lambda",
Self::FunctionCall => "function call",
Self::Expression => "expression",
Self::GeneratorExpression => "generator expression",
Self::YieldExpression => "yield expression",
Self::AwaitExpression => "await expression",
Self::ListComprehension => "list comprehension",
Self::SetComprehension => "set comprehension",
Self::DictComprehension => "dict comprehension",
Self::DictLiteral => "dict literal",
Self::SetDisplay => "set display",
Self::FStringExpression => "f-string expression",
Self::TStringExpression => "t-string expression",
Self::None => "None",
Self::False => "False",
Self::True => "True",
Self::Ellipsis => "ellipsis",
Self::Literal => "literal",
Self::Comparison => "comparison",
Self::ConditionalExpression => "conditional expression",
Self::NamedExpression => "named expression",
})
}
}
/// The compound statement clause whose header precedes an indented block.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, get_size2::GetSize)]
pub enum BlockClause {
If,
Elif,
Else,
For,
With,
While,
Try,
Except,
ExceptStar,
Finally,
Match,
Case,
Class,
FunctionDef,
}
impl std::fmt::Display for BlockClause {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(match self {
Self::If => "'if' statement",
Self::Elif => "'elif' statement",
Self::Else => "'else' statement",
Self::For => "'for' statement",
Self::With => "'with' statement",
Self::While => "'while' statement",
Self::Try => "'try' statement",
Self::Except => "'except' statement",
Self::ExceptStar => "'except*' statement",
Self::Finally => "'finally' statement",
Self::Match => "'match' statement",
Self::Case => "'case' statement",
Self::Class => "class definition",
Self::FunctionDef => "function definition",
})
}
}
impl ParseErrorType {
pub(crate) fn from_interpolated_string_error(
error: InterpolatedStringErrorType,
string_kind: InterpolatedStringKind,
) -> Self {
match string_kind {
InterpolatedStringKind::FString => Self::FStringError(error),
InterpolatedStringKind::TString => Self::TStringError(error),
}
}
}
impl std::error::Error for ParseErrorType {}
impl std::fmt::Display for ParseErrorType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ParseErrorType::OtherError(msg) => f.write_str(msg),
ParseErrorType::ExpectedIndentedBlock { clause, line } => {
write!(
f,
"expected an indented block after {clause} on line {line}"
)
}
ParseErrorType::StringAnnotationError(msg) => f.write_str(msg),
ParseErrorType::ExpectedToken { found, expected } => match (*expected, *found) {
(TokenKind::Colon, TokenKind::Newline) => f.write_str("expected ':'"),
(TokenKind::Lpar, _) => f.write_str("expected '('"),
(TokenKind::Else, found) if found != TokenKind::Colon => {
f.write_str("expected 'else' after 'if' expression")
}
_ => f.write_str("invalid syntax"),
},
ParseErrorType::ExpectedForcedToken { expected, .. } => match expected {
TokenKind::Colon => f.write_str("expected ':'"),
TokenKind::Lpar => f.write_str("expected '('"),
expected => write!(f, "expected {expected}"),
},
ParseErrorType::Lexical(lex_error) => write!(f, "{lex_error}"),
ParseErrorType::SimpleStatementsOnSameLine => f.write_str("invalid syntax"),
ParseErrorType::SimpleAndCompoundStatementOnSameLine => f.write_str("invalid syntax"),
ParseErrorType::UnexpectedTokenAfterAsync(_) => f.write_str("invalid syntax"),
ParseErrorType::InvalidArgumentUnpackingOrder => {
f.write_str("iterable argument unpacking follows keyword argument unpacking")
}
ParseErrorType::IterableUnpackingInComprehension => {
f.write_str("iterable unpacking cannot be used in a comprehension")
}
ParseErrorType::UnparenthesizedNamedExpression => {
f.write_str("unparenthesized named expression cannot be used here")
}
ParseErrorType::UnparenthesizedTupleExpression => {
f.write_str("unparenthesized tuple expression cannot be used here")
}
ParseErrorType::UnparenthesizedGeneratorExpression => {
f.write_str("Generator expression must be parenthesized")
}
ParseErrorType::InvalidYieldExpressionUsage => {
f.write_str("yield expression cannot be used here")
}
ParseErrorType::InvalidLambdaExpressionUsage => {
f.write_str("lambda expression cannot be used here")
}
ParseErrorType::InvalidStarredExpressionUsage => f.write_str("invalid syntax"),
ParseErrorType::PositionalAfterKeywordArgument => {
f.write_str("positional argument follows keyword argument")
}
ParseErrorType::PositionalAfterKeywordUnpacking => {
f.write_str("positional argument follows keyword argument unpacking")
}
ParseErrorType::EmptySlice => f.write_str("expected index or slice expression"),
ParseErrorType::EmptyGlobalNames
| ParseErrorType::EmptyNonlocalNames
| ParseErrorType::EmptyDeleteTargets => f.write_str("invalid syntax"),
ParseErrorType::EmptyImportNames => {
f.write_str("Expected one or more names after 'import'")
}
ParseErrorType::EmptyTypeParams => f.write_str("Type parameter list cannot be empty"),
ParseErrorType::ParamAfterVarKeywordParam => {
f.write_str("arguments cannot follow var-keyword argument")
}
ParseErrorType::NonDefaultParamAfterDefaultParam => {
f.write_str("parameter without a default follows parameter with a default")
}
ParseErrorType::ExpectedKeywordParam => {
f.write_str("named arguments must follow bare *")
}
ParseErrorType::VarKeywordParameterWithDefault => {
f.write_str("var-keyword argument cannot have default value")
}
ParseErrorType::ExpectedColonAfterDictionaryKey => {
f.write_str("':' expected after dictionary key")
}
ParseErrorType::VarParameterWithDefault => {
f.write_str("var-positional argument cannot have default value")
}
ParseErrorType::InvalidStarPatternUsage => {
f.write_str("cannot use starred expression here")
}
ParseErrorType::InvalidMatchPatternTarget => f.write_str("cannot use '_' as a target"),
ParseErrorType::ExpectedRealNumber => {
f.write_str("expected a real number in complex literal pattern")
}
ParseErrorType::ExpectedImaginaryNumber => {
f.write_str("expected an imaginary number in complex literal pattern")
}
ParseErrorType::ExpectedExpression | ParseErrorType::ExpectedIdentifier => {
f.write_str("invalid syntax")
}
ParseErrorType::UnexpectedIndentation => f.write_str("unexpected indent"),
ParseErrorType::InvalidAssignmentTarget {
kind,
maybe_comparison: false,
} => write!(f, "cannot assign to {kind}"),
ParseErrorType::InvalidAssignmentTarget {
kind,
maybe_comparison: true,
} => write!(
f,
"cannot assign to {kind} here. Maybe you meant '==' instead of '='?"
),
ParseErrorType::AssignmentInsteadOfComparison => {
f.write_str("invalid syntax. Maybe you meant '==' or ':=' instead of '='?")
}
ParseErrorType::AssignmentToYield => {
f.write_str("assignment to yield expression not possible")
}
ParseErrorType::InvalidAnnotatedAssignmentTarget => {
f.write_str("illegal target for annotation")
}
ParseErrorType::InvalidNamedAssignmentTarget(kind) => {
write!(f, "cannot use assignment expressions with {kind}")
}
ParseErrorType::InvalidAugmentedAssignmentTarget(kind) => {
write!(
f,
"'{kind}' is an illegal expression for augmented assignment"
)
}
ParseErrorType::InvalidDeleteTarget(kind) => write!(f, "cannot delete {kind}"),
ParseErrorType::InvalidImportTarget(kind) => {
write!(f, "cannot use {kind} as import target")
}
ParseErrorType::InvalidPatternTarget(kind) => {
write!(f, "cannot use {kind} as pattern target")
}
ParseErrorType::InvalidExceptTarget { kind, star } => {
let clause = if *star { "except*" } else { "except" };
write!(f, "cannot use {clause} statement with {kind}")
}
ParseErrorType::UnexpectedIpythonEscapeCommand => {
f.write_str("IPython escape commands are only allowed in `Mode::Ipython`")
}
ParseErrorType::FStringError(error) => {
write_interpolated_string_error(f, InterpolatedStringKind::FString, error)
}
ParseErrorType::TStringError(error) => {
write_interpolated_string_error(f, InterpolatedStringKind::TString, error)
}
ParseErrorType::UnexpectedExpressionToken => f.write_str("invalid syntax"),
}
}
}
/// Represents an error that occur during lexing and are
/// returned by the `parse_*` functions in the iterator in the
/// [lexer] implementation.
///
/// [lexer]: crate::lexer
#[derive(Debug, Clone, PartialEq)]
pub struct LexicalError {
/// The type of error that occurred.
error: LexicalErrorType,
/// The location of the error.
location: TextRange,
}
impl LexicalError {
/// Creates a new `LexicalError` with the given error type and location.
pub fn new(error: LexicalErrorType, location: TextRange) -> Self {
Self { error, location }
}
pub fn error(&self) -> &LexicalErrorType {
&self.error
}
pub fn into_error(self) -> LexicalErrorType {
self.error
}
pub fn location(&self) -> TextRange {
self.location
}
}
impl std::ops::Deref for LexicalError {
type Target = LexicalErrorType;
fn deref(&self) -> &Self::Target {
self.error()
}
}
impl std::error::Error for LexicalError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self.error())
}
}
impl std::fmt::Display for LexicalError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{} at byte offset {}",
self.error(),
u32::from(self.location().start())
)
}
}
/// Represents the different types of errors that can occur during lexing.
#[derive(Debug, Clone, PartialEq, Eq, get_size2::GetSize)]
pub enum LexicalErrorType {
// TODO: Can probably be removed, the places it is used seem to be able
// to use the `UnicodeError` variant instead.
#[doc(hidden)]
StringError,
/// A string literal without the closing quote, detected at the given one-based line.
UnclosedStringError {
triple_quoted: bool,
/// The literal contains a backslash followed by its quote character.
escaped_end_quote: bool,
detected_line: u32,
},
/// An escape sequence in a string literal cannot be decoded. `start` and `end` are the
/// inclusive positions of the escape sequence in the string content, where a non-ASCII
/// character counts as its ten-character `\U` escape.
UnicodeEscapeError {
kind: UnicodeEscapeErrorKind,
start: u32,
end: u32,
},
/// A `\x` escape in a bytes literal at the given position of its content is not followed by
/// two hexadecimal digits.
BytesEscapeError { position: u32 },
/// A dedent does not match any outer indentation level.
IndentationError,
/// Tabs and spaces are mixed in a way that makes the indentation depend on the tab size.
TabError,
/// The indentation is nested too deeply.
TooDeepIndentation,
/// An unrecognized token was encountered.
UnrecognizedToken { tok: char },
/// An f-string error containing the [`InterpolatedStringErrorType`].
FStringError(InterpolatedStringErrorType),
/// A t-string error containing the [`InterpolatedStringErrorType`].
TStringError(InterpolatedStringErrorType),
/// Invalid character encountered in a byte literal.
InvalidByteLiteral,
/// An unexpected character was encountered after a line continuation.
LineContinuationError,
/// An unexpected end of file was encountered.
Eof,
/// A closing bracket without an opening bracket.
UnmatchedBracket { closing: char },
/// A closing bracket that does not match the innermost opening bracket. `opening_line` is the
/// line of the opening bracket if it is on another line.
MismatchedBracket {
closing: char,
opening: char,
opening_line: Option<u32>,
},
/// An opening bracket that is not closed by the end of the source.
///
/// `incomplete` is whether more input could still close it: the parser read to the end of the
/// source with the bracket open. Otherwise, the error is reported in place of an earlier syntax
/// error.
UnclosedBracket { opening: char, incomplete: bool },
/// Brackets are nested too deeply.
TooDeeplyNestedBrackets,
/// A malformed number literal, or one directly followed by a name.
InvalidNumberLiteral { kind: NumberLiteralKind },
/// A digit that is not valid in the octal or binary literal it appears in.
InvalidDigit {
digit: char,
kind: NumberLiteralKind,
},
/// A decimal integer literal with leading zeros.
LeadingZerosInDecimalInteger,
/// A string prefix that combines incompatible prefixes, such as `ub`.
IncompatibleStringPrefixes { first: char, second: char },
/// An unexpected error occurred.
OtherError(Box<str>),
}
impl std::error::Error for LexicalErrorType {}
/// The kind of a number literal, as named in error messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, get_size2::GetSize)]
pub enum NumberLiteralKind {
Decimal,
Hexadecimal,
Octal,
Binary,
Imaginary,
}
impl std::fmt::Display for NumberLiteralKind {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(match self {
Self::Decimal => "decimal",
Self::Hexadecimal => "hexadecimal",
Self::Octal => "octal",
Self::Binary => "binary",
Self::Imaginary => "imaginary",
})
}
}
/// Whether `c` is printable: not a control, format, surrogate, private use, unassigned or
/// separator character, other than the ASCII space.
fn is_printable(c: char) -> bool {
use icu_properties::props::{EnumeratedProperty, GeneralCategory};
c == ' '
|| !matches!(
GeneralCategory::for_char(c),
GeneralCategory::SpaceSeparator
| GeneralCategory::LineSeparator
| GeneralCategory::ParagraphSeparator
| GeneralCategory::Control
| GeneralCategory::Format
| GeneralCategory::Surrogate
| GeneralCategory::PrivateUse
| GeneralCategory::Unassigned
)
}
impl LexicalErrorType {
/// Returns `true` if the error reports a string literal without its closing quotes.
pub(crate) fn is_unclosed_string_error(&self) -> bool {
matches!(
self,
Self::UnclosedStringError { .. }
| Self::FStringError(InterpolatedStringErrorType::UnclosedLbrace)
| Self::TStringError(InterpolatedStringErrorType::UnclosedLbrace)
)
}
/// Returns `true` if the error stops tokenization, as opposed to an error found while
/// decoding the content of a token.
pub fn is_tokenizer_error(&self) -> bool {
match self {
Self::StringError
| Self::UnicodeEscapeError { .. }
| Self::BytesEscapeError { .. }
| Self::InvalidByteLiteral
| Self::OtherError(_) => false,
// An ASCII punctuation character is a token that the parser rejects.
Self::UnrecognizedToken { tok } => !tok.is_ascii() || !is_printable(*tok),
Self::FStringError(error) | Self::TStringError(error) => matches!(
error,
InterpolatedStringErrorType::UnterminatedString { .. }
| InterpolatedStringErrorType::UnterminatedTripleQuotedString { .. }
| InterpolatedStringErrorType::SingleRbrace
| InterpolatedStringErrorType::NewlineInFormatSpec
| InterpolatedStringErrorType::UnclosedLbrace
| InterpolatedStringErrorType::UnmatchedBracket(_)
),
Self::UnclosedStringError { .. }
| Self::IndentationError
| Self::TabError
| Self::TooDeepIndentation
| Self::LineContinuationError
| Self::Eof
| Self::UnmatchedBracket { .. }
| Self::MismatchedBracket { .. }
| Self::UnclosedBracket { .. }
| Self::TooDeeplyNestedBrackets
| Self::InvalidNumberLiteral { .. }
| Self::InvalidDigit { .. }
| Self::LeadingZerosInDecimalInteger
| Self::IncompatibleStringPrefixes { .. } => true,
}
}
pub(crate) fn from_interpolated_string_error(
error: InterpolatedStringErrorType,
string_kind: InterpolatedStringKind,
) -> Self {
match string_kind {
InterpolatedStringKind::FString => Self::FStringError(error),
InterpolatedStringKind::TString => Self::TStringError(error),
}
}
}
impl std::fmt::Display for LexicalErrorType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Self::StringError => write!(f, "got unexpected string"),
Self::FStringError(error) => {
write_interpolated_string_error(f, InterpolatedStringKind::FString, error)
}
Self::TStringError(error) => {
write_interpolated_string_error(f, InterpolatedStringKind::TString, error)
}
Self::InvalidByteLiteral => {
write!(f, "bytes can only contain ASCII literal characters")
}
Self::UnicodeEscapeError { kind, start, end } => write!(
f,
"(unicode error) 'unicodeescape' codec can't decode bytes in position {start}-{end}: {kind}"
),
Self::BytesEscapeError { position } => {
write!(f, "(value error) invalid \\x escape at position {position}")
}
Self::IndentationError => {
write!(f, "unindent does not match any outer indentation level")
}
Self::TabError => write!(f, "inconsistent use of tabs and spaces in indentation"),
Self::TooDeepIndentation => write!(f, "too many levels of indentation"),
Self::UnrecognizedToken { tok } if !is_printable(*tok) => {
write!(
f,
"invalid non-printable character U+{:04X}",
u32::from(*tok)
)
}
Self::UnrecognizedToken { tok } if !tok.is_ascii() => {
write!(f, "invalid character '{tok}' (U+{:04X})", u32::from(*tok))
}
Self::UnrecognizedToken { .. } => f.write_str("invalid syntax"),
Self::InvalidNumberLiteral { kind } => write!(f, "invalid {kind} literal"),
Self::InvalidDigit { digit, kind } => {
write!(f, "invalid digit '{digit}' in {kind} literal")
}
Self::LeadingZerosInDecimalInteger => f.write_str(
"leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers",
),
Self::IncompatibleStringPrefixes { first, second } => {
write!(f, "'{first}' and '{second}' prefixes are incompatible")
}
Self::LineContinuationError => {
write!(f, "unexpected character after line continuation character")
}
Self::Eof => write!(f, "unexpected EOF while parsing"),
Self::UnmatchedBracket { closing } => write!(f, "unmatched '{closing}'"),
Self::MismatchedBracket {
closing,
opening,
opening_line,
} => {
write!(
f,
"closing parenthesis '{closing}' does not match opening parenthesis '{opening}'"
)?;
if let Some(line) = opening_line {
write!(f, " on line {line}")?;
}
Ok(())
}
Self::UnclosedBracket { opening, .. } => write!(f, "'{opening}' was never closed"),
Self::TooDeeplyNestedBrackets => f.write_str("too many nested parentheses"),
Self::OtherError(msg) => write!(f, "{msg}"),
Self::UnclosedStringError {
triple_quoted: true,
detected_line,
..
} => write!(
f,
"unterminated triple-quoted string literal (detected at line {detected_line})"
),
Self::UnclosedStringError {
escaped_end_quote,
detected_line,
..
} => {
write!(
f,
"unterminated string literal (detected at line {detected_line})"
)?;
if *escaped_end_quote {
f.write_str("; perhaps you escaped the end quote?")?;
}
Ok(())
}
}
}
}
/// Represents a version-related syntax error detected during parsing.
///
/// An example of a version-related error is the use of a `match` statement before Python 3.10, when
/// it was first introduced. See [`UnsupportedSyntaxErrorKind`] for other kinds of errors.
#[derive(Debug, PartialEq, Clone, get_size2::GetSize)]
pub struct UnsupportedSyntaxError {
pub kind: UnsupportedSyntaxErrorKind,
pub range: TextRange,
/// The target [`PythonVersion`] for which this error was detected.
pub target_version: PythonVersion,
}
impl Ranged for UnsupportedSyntaxError {
fn range(&self) -> TextRange {
self.range
}
}
/// The type of tuple unpacking for [`UnsupportedSyntaxErrorKind::StarTuple`].
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, get_size2::GetSize)]
pub enum StarTupleKind {
Return,
Yield,
}
/// The type of PEP 701 f-string error for [`UnsupportedSyntaxErrorKind::Pep701FString`].
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, get_size2::GetSize)]
pub enum FStringKind {
Backslash,
Comment,
LineBreak,