-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
diagnostics.rs
3132 lines (2921 loc) · 119 KB
/
diagnostics.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 super::pat::Expected;
use super::{
BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep,
TokenExpectType, TokenType,
};
use crate::lexer::UnmatchedBrace;
use rustc_ast as ast;
use rustc_ast::ptr::P;
use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind};
use rustc_ast::util::parser::AssocOp;
use rustc_ast::{
AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingAnnotation, Block,
BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Param, Pat, PatKind,
Path, PathSegment, QSelf, Ty, TyKind,
};
use rustc_ast_pretty::pprust;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{
fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, Handler, MultiSpan, PResult,
};
use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed};
use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic};
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, sym, Ident};
use rustc_span::{Span, SpanSnippetError, DUMMY_SP};
use std::ops::{Deref, DerefMut};
use std::mem::take;
use crate::parser;
const TURBOFISH_SUGGESTION_STR: &str =
"use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments";
/// Creates a placeholder argument.
pub(super) fn dummy_arg(ident: Ident) -> Param {
let pat = P(Pat {
id: ast::DUMMY_NODE_ID,
kind: PatKind::Ident(BindingAnnotation::NONE, ident, None),
span: ident.span,
tokens: None,
});
let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
Param {
attrs: AttrVec::default(),
id: ast::DUMMY_NODE_ID,
pat,
span: ident.span,
ty: P(ty),
is_placeholder: false,
}
}
pub enum Error {
UselessDocComment,
}
impl Error {
fn span_err(
self,
sp: impl Into<MultiSpan>,
handler: &Handler,
) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
match self {
Error::UselessDocComment => {
let mut err = struct_span_err!(
handler,
sp,
E0585,
"found a documentation comment that doesn't document anything",
);
err.help(
"doc comments must come before what they document, maybe a comment was \
intended with `//`?",
);
err
}
}
}
}
pub(super) trait RecoverQPath: Sized + 'static {
const PATH_STYLE: PathStyle = PathStyle::Expr;
fn to_ty(&self) -> Option<P<Ty>>;
fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
}
impl RecoverQPath for Ty {
const PATH_STYLE: PathStyle = PathStyle::Type;
fn to_ty(&self) -> Option<P<Ty>> {
Some(P(self.clone()))
}
fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
Self {
span: path.span,
kind: TyKind::Path(qself, path),
id: ast::DUMMY_NODE_ID,
tokens: None,
}
}
}
impl RecoverQPath for Pat {
fn to_ty(&self) -> Option<P<Ty>> {
self.to_ty()
}
fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
Self {
span: path.span,
kind: PatKind::Path(qself, path),
id: ast::DUMMY_NODE_ID,
tokens: None,
}
}
}
impl RecoverQPath for Expr {
fn to_ty(&self) -> Option<P<Ty>> {
self.to_ty()
}
fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
Self {
span: path.span,
kind: ExprKind::Path(qself, path),
attrs: AttrVec::new(),
id: ast::DUMMY_NODE_ID,
tokens: None,
}
}
}
/// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
pub(crate) enum ConsumeClosingDelim {
Yes,
No,
}
#[derive(Clone, Copy)]
pub enum AttemptLocalParseRecovery {
Yes,
No,
}
impl AttemptLocalParseRecovery {
pub fn yes(&self) -> bool {
match self {
AttemptLocalParseRecovery::Yes => true,
AttemptLocalParseRecovery::No => false,
}
}
pub fn no(&self) -> bool {
match self {
AttemptLocalParseRecovery::Yes => false,
AttemptLocalParseRecovery::No => true,
}
}
}
/// Information for emitting suggestions and recovering from
/// C-style `i++`, `--i`, etc.
#[derive(Debug, Copy, Clone)]
struct IncDecRecovery {
/// Is this increment/decrement its own statement?
standalone: IsStandalone,
/// Is this an increment or decrement?
op: IncOrDec,
/// Is this pre- or postfix?
fixity: UnaryFixity,
}
/// Is an increment or decrement expression its own statement?
#[derive(Debug, Copy, Clone)]
enum IsStandalone {
/// It's standalone, i.e., its own statement.
Standalone,
/// It's a subexpression, i.e., *not* standalone.
Subexpr,
/// It's maybe standalone; we're not sure.
Maybe,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum IncOrDec {
Inc,
// FIXME: `i--` recovery isn't implemented yet
#[allow(dead_code)]
Dec,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum UnaryFixity {
Pre,
Post,
}
impl IncOrDec {
fn chr(&self) -> char {
match self {
Self::Inc => '+',
Self::Dec => '-',
}
}
fn name(&self) -> &'static str {
match self {
Self::Inc => "increment",
Self::Dec => "decrement",
}
}
}
impl std::fmt::Display for UnaryFixity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Pre => write!(f, "prefix"),
Self::Post => write!(f, "postfix"),
}
}
}
struct MultiSugg {
msg: String,
patches: Vec<(Span, String)>,
applicability: Applicability,
}
impl MultiSugg {
fn emit(self, err: &mut Diagnostic) {
err.multipart_suggestion(&self.msg, self.patches, self.applicability);
}
/// Overrides individual messages and applicabilities.
fn emit_many(
err: &mut Diagnostic,
msg: &str,
applicability: Applicability,
suggestions: impl Iterator<Item = Self>,
) {
err.multipart_suggestions(msg, suggestions.map(|s| s.patches), applicability);
}
}
#[derive(SessionDiagnostic)]
#[diag(parser::maybe_report_ambiguous_plus)]
struct AmbiguousPlus {
pub sum_ty: String,
#[primary_span]
#[suggestion(code = "({sum_ty})")]
pub span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::maybe_recover_from_bad_type_plus, code = "E0178")]
struct BadTypePlus {
pub ty: String,
#[primary_span]
pub span: Span,
#[subdiagnostic]
pub sub: BadTypePlusSub,
}
#[derive(SessionSubdiagnostic)]
pub enum BadTypePlusSub {
#[suggestion(
parser::add_paren,
code = "{sum_with_parens}",
applicability = "machine-applicable"
)]
AddParen {
sum_with_parens: String,
#[primary_span]
span: Span,
},
#[label(parser::forgot_paren)]
ForgotParen {
#[primary_span]
span: Span,
},
#[label(parser::expect_path)]
ExpectPath {
#[primary_span]
span: Span,
},
}
#[derive(SessionDiagnostic)]
#[diag(parser::maybe_recover_from_bad_qpath_stage_2)]
struct BadQPathStage2 {
#[primary_span]
#[suggestion(applicability = "maybe-incorrect")]
span: Span,
ty: String,
}
#[derive(SessionDiagnostic)]
#[diag(parser::incorrect_semicolon)]
struct IncorrectSemicolon<'a> {
#[primary_span]
#[suggestion_short(applicability = "machine-applicable")]
span: Span,
#[help]
opt_help: Option<()>,
name: &'a str,
}
#[derive(SessionDiagnostic)]
#[diag(parser::incorrect_use_of_await)]
struct IncorrectUseOfAwait {
#[primary_span]
#[suggestion(parser::parentheses_suggestion, applicability = "machine-applicable")]
span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::incorrect_use_of_await)]
struct IncorrectAwait {
#[primary_span]
span: Span,
#[suggestion(parser::postfix_suggestion, code = "{expr}.await{question_mark}")]
sugg_span: (Span, Applicability),
expr: String,
question_mark: &'static str,
}
#[derive(SessionDiagnostic)]
#[diag(parser::in_in_typo)]
struct InInTypo {
#[primary_span]
span: Span,
#[suggestion(applicability = "machine-applicable")]
sugg_span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::invalid_variable_declaration)]
pub struct InvalidVariableDeclaration {
#[primary_span]
pub span: Span,
#[subdiagnostic]
pub sub: InvalidVariableDeclarationSub,
}
#[derive(SessionSubdiagnostic)]
pub enum InvalidVariableDeclarationSub {
#[suggestion(
parser::switch_mut_let_order,
applicability = "maybe-incorrect",
code = "let mut"
)]
SwitchMutLetOrder(#[primary_span] Span),
#[suggestion(
parser::missing_let_before_mut,
applicability = "machine-applicable",
code = "let mut"
)]
MissingLet(#[primary_span] Span),
#[suggestion(parser::use_let_not_auto, applicability = "machine-applicable", code = "let")]
UseLetNotAuto(#[primary_span] Span),
#[suggestion(parser::use_let_not_var, applicability = "machine-applicable", code = "let")]
UseLetNotVar(#[primary_span] Span),
}
#[derive(SessionDiagnostic)]
#[diag(parser::invalid_comparison_operator)]
pub(crate) struct InvalidComparisonOperator {
#[primary_span]
pub span: Span,
pub invalid: String,
#[subdiagnostic]
pub sub: InvalidComparisonOperatorSub,
}
#[derive(SessionSubdiagnostic)]
pub(crate) enum InvalidComparisonOperatorSub {
#[suggestion_short(
parser::use_instead,
applicability = "machine-applicable",
code = "{correct}"
)]
Correctable {
#[primary_span]
span: Span,
invalid: String,
correct: String,
},
#[label(parser::spaceship_operator_invalid)]
Spaceship(#[primary_span] Span),
}
#[derive(SessionDiagnostic)]
#[diag(parser::invalid_logical_operator)]
#[note]
pub(crate) struct InvalidLogicalOperator {
#[primary_span]
pub span: Span,
pub incorrect: String,
#[subdiagnostic]
pub sub: InvalidLogicalOperatorSub,
}
#[derive(SessionSubdiagnostic)]
pub(crate) enum InvalidLogicalOperatorSub {
#[suggestion_short(
parser::use_amp_amp_for_conjunction,
applicability = "machine-applicable",
code = "&&"
)]
Conjunction(#[primary_span] Span),
#[suggestion_short(
parser::use_pipe_pipe_for_disjunction,
applicability = "machine-applicable",
code = "||"
)]
Disjunction(#[primary_span] Span),
}
#[derive(SessionDiagnostic)]
#[diag(parser::tilde_is_not_unary_operator)]
pub(crate) struct TildeAsUnaryOperator(
#[primary_span]
#[suggestion_short(applicability = "machine-applicable", code = "!")]
pub Span,
);
#[derive(SessionDiagnostic)]
#[diag(parser::unexpected_token_after_not)]
pub(crate) struct NotAsNegationOperator {
#[primary_span]
pub negated: Span,
pub negated_desc: String,
#[suggestion_short(applicability = "machine-applicable", code = "!")]
pub not: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::malformed_loop_label)]
pub(crate) struct MalformedLoopLabel {
#[primary_span]
#[suggestion(applicability = "machine-applicable", code = "{correct_label}")]
pub span: Span,
pub correct_label: Ident,
}
#[derive(SessionDiagnostic)]
#[diag(parser::lifetime_in_borrow_expression)]
pub(crate) struct LifetimeInBorrowExpression {
#[primary_span]
pub span: Span,
#[suggestion(applicability = "machine-applicable", code = "")]
#[label]
pub lifetime_span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::field_expression_with_generic)]
pub(crate) struct FieldExpressionWithGeneric(#[primary_span] pub Span);
#[derive(SessionDiagnostic)]
#[diag(parser::macro_invocation_with_qualified_path)]
pub(crate) struct MacroInvocationWithQualifiedPath(#[primary_span] pub Span);
#[derive(SessionDiagnostic)]
#[diag(parser::unexpected_token_after_label)]
pub(crate) struct UnexpectedTokenAfterLabel(
#[primary_span]
#[label(parser::unexpected_token_after_label)]
pub Span,
);
#[derive(SessionDiagnostic)]
#[diag(parser::require_colon_after_labeled_expression)]
#[note]
pub(crate) struct RequireColonAfterLabeledExpression {
#[primary_span]
pub span: Span,
#[label]
pub label: Span,
#[suggestion_short(applicability = "machine-applicable", code = ": ")]
pub label_end: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::do_catch_syntax_removed)]
#[note]
pub(crate) struct DoCatchSyntaxRemoved {
#[primary_span]
#[suggestion(applicability = "machine-applicable", code = "try")]
pub span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::float_literal_requires_integer_part)]
pub(crate) struct FloatLiteralRequiresIntegerPart {
#[primary_span]
#[suggestion(applicability = "machine-applicable", code = "{correct}")]
pub span: Span,
pub correct: String,
}
#[derive(SessionDiagnostic)]
#[diag(parser::invalid_int_literal_width)]
#[help]
pub(crate) struct InvalidIntLiteralWidth {
#[primary_span]
pub span: Span,
pub width: String,
}
#[derive(SessionDiagnostic)]
#[diag(parser::invalid_num_literal_base_prefix)]
#[note]
pub(crate) struct InvalidNumLiteralBasePrefix {
#[primary_span]
#[suggestion(applicability = "maybe-incorrect", code = "{fixed}")]
pub span: Span,
pub fixed: String,
}
#[derive(SessionDiagnostic)]
#[diag(parser::invalid_num_literal_suffix)]
#[help]
pub(crate) struct InvalidNumLiteralSuffix {
#[primary_span]
#[label]
pub span: Span,
pub suffix: String,
}
#[derive(SessionDiagnostic)]
#[diag(parser::invalid_float_literal_width)]
#[help]
pub(crate) struct InvalidFloatLiteralWidth {
#[primary_span]
pub span: Span,
pub width: String,
}
#[derive(SessionDiagnostic)]
#[diag(parser::invalid_float_literal_suffix)]
#[help]
pub(crate) struct InvalidFloatLiteralSuffix {
#[primary_span]
#[label]
pub span: Span,
pub suffix: String,
}
#[derive(SessionDiagnostic)]
#[diag(parser::int_literal_too_large)]
pub(crate) struct IntLiteralTooLarge {
#[primary_span]
pub span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::missing_semicolon_before_array)]
pub(crate) struct MissingSemicolonBeforeArray {
#[primary_span]
pub open_delim: Span,
#[suggestion_verbose(applicability = "maybe-incorrect", code = ";")]
pub semicolon: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::invalid_block_macro_segment)]
pub(crate) struct InvalidBlockMacroSegment {
#[primary_span]
pub span: Span,
#[label]
pub context: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::if_expression_missing_then_block)]
pub(crate) struct IfExpressionMissingThenBlock {
#[primary_span]
pub if_span: Span,
#[subdiagnostic]
pub sub: IfExpressionMissingThenBlockSub,
}
#[derive(SessionSubdiagnostic)]
pub(crate) enum IfExpressionMissingThenBlockSub {
#[help(parser::condition_possibly_unfinished)]
UnfinishedCondition(#[primary_span] Span),
#[help(parser::add_then_block)]
AddThenBlock(#[primary_span] Span),
}
#[derive(SessionDiagnostic)]
#[diag(parser::if_expression_missing_condition)]
pub(crate) struct IfExpressionMissingCondition {
#[primary_span]
#[label(parser::condition_label)]
pub if_span: Span,
#[label(parser::block_label)]
pub block_span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::expected_expression_found_let)]
pub(crate) struct ExpectedExpressionFoundLet {
#[primary_span]
pub span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::expected_else_block)]
pub(crate) struct ExpectedElseBlock {
#[primary_span]
pub first_tok_span: Span,
pub first_tok: String,
#[label]
pub else_span: Span,
#[suggestion(applicability = "maybe-incorrect", code = "if ")]
pub condition_start: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::outer_attribute_not_allowed_on_if_else)]
pub(crate) struct OuterAttributeNotAllowedOnIfElse {
#[primary_span]
pub last: Span,
#[label(parser::branch_label)]
pub branch_span: Span,
#[label(parser::ctx_label)]
pub ctx_span: Span,
pub ctx: String,
#[suggestion(applicability = "machine-applicable", code = "")]
pub attributes: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::missing_in_in_for_loop)]
pub(crate) struct MissingInInForLoop {
#[primary_span]
pub span: Span,
#[subdiagnostic]
pub sub: MissingInInForLoopSub,
}
#[derive(SessionSubdiagnostic)]
pub(crate) enum MissingInInForLoopSub {
// Has been misleading, at least in the past (closed Issue #48492), thus maybe-incorrect
#[suggestion_short(parser::use_in_not_of, applicability = "maybe-incorrect", code = "in")]
InNotOf(#[primary_span] Span),
#[suggestion_short(parser::add_in, applicability = "maybe-incorrect", code = " in ")]
AddIn(#[primary_span] Span),
}
#[derive(SessionDiagnostic)]
#[diag(parser::missing_comma_after_match_arm)]
pub(crate) struct MissingCommaAfterMatchArm {
#[primary_span]
#[suggestion(applicability = "machine-applicable", code = ",")]
pub span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::catch_after_try)]
#[help]
pub(crate) struct CatchAfterTry {
#[primary_span]
pub span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::comma_after_base_struct)]
#[note]
pub(crate) struct CommaAfterBaseStruct {
#[primary_span]
pub span: Span,
#[suggestion_short(applicability = "machine-applicable", code = "")]
pub comma: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::eq_field_init)]
pub(crate) struct EqFieldInit {
#[primary_span]
pub span: Span,
#[suggestion(applicability = "machine-applicable", code = ":")]
pub eq: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::dotdotdot)]
pub(crate) struct DotDotDot {
#[primary_span]
#[suggestion(parser::suggest_exclusive_range, applicability = "maybe-incorrect", code = "..")]
#[suggestion(parser::suggest_inclusive_range, applicability = "maybe-incorrect", code = "..=")]
pub span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::left_arrow_operator)]
pub(crate) struct LeftArrowOperator {
#[primary_span]
#[suggestion(applicability = "maybe-incorrect", code = "< -")]
pub span: Span,
}
#[derive(SessionDiagnostic)]
#[diag(parser::remove_let)]
pub(crate) struct RemoveLet {
#[primary_span]
#[suggestion(applicability = "machine-applicable", code = "")]
pub span: Span,
}
// SnapshotParser is used to create a snapshot of the parser
// without causing duplicate errors being emitted when the `Parser`
// is dropped.
pub struct SnapshotParser<'a> {
parser: Parser<'a>,
unclosed_delims: Vec<UnmatchedBrace>,
}
impl<'a> Deref for SnapshotParser<'a> {
type Target = Parser<'a>;
fn deref(&self) -> &Self::Target {
&self.parser
}
}
impl<'a> DerefMut for SnapshotParser<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.parser
}
}
impl<'a> Parser<'a> {
#[rustc_lint_diagnostics]
pub(super) fn span_err<S: Into<MultiSpan>>(
&self,
sp: S,
err: Error,
) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
err.span_err(sp, self.diagnostic())
}
#[rustc_lint_diagnostics]
pub fn struct_span_err<S: Into<MultiSpan>>(
&self,
sp: S,
m: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
self.sess.span_diagnostic.struct_span_err(sp, m)
}
pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<DiagnosticMessage>) -> ! {
self.sess.span_diagnostic.span_bug(sp, m)
}
pub(super) fn diagnostic(&self) -> &'a Handler {
&self.sess.span_diagnostic
}
/// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
/// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
*self = snapshot.parser;
self.unclosed_delims.extend(snapshot.unclosed_delims);
}
pub fn unclosed_delims(&self) -> &[UnmatchedBrace] {
&self.unclosed_delims
}
/// Create a snapshot of the `Parser`.
pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
let mut snapshot = self.clone();
let unclosed_delims = self.unclosed_delims.clone();
// Clear `unclosed_delims` in snapshot to avoid
// duplicate errors being emitted when the `Parser`
// is dropped (which may or may not happen, depending
// if the parsing the snapshot is created for is successful)
snapshot.unclosed_delims.clear();
SnapshotParser { parser: snapshot, unclosed_delims }
}
pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
self.sess.source_map().span_to_snippet(span)
}
pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
let mut err = self.struct_span_err(
self.token.span,
&format!("expected identifier, found {}", super::token_descr(&self.token)),
);
let valid_follow = &[
TokenKind::Eq,
TokenKind::Colon,
TokenKind::Comma,
TokenKind::Semi,
TokenKind::ModSep,
TokenKind::OpenDelim(Delimiter::Brace),
TokenKind::OpenDelim(Delimiter::Parenthesis),
TokenKind::CloseDelim(Delimiter::Brace),
TokenKind::CloseDelim(Delimiter::Parenthesis),
];
match self.token.ident() {
Some((ident, false))
if ident.is_raw_guess()
&& self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
{
err.span_suggestion_verbose(
ident.span.shrink_to_lo(),
&format!("escape `{}` to use it as an identifier", ident.name),
"r#",
Applicability::MaybeIncorrect,
);
}
_ => {}
}
if let Some(token_descr) = super::token_descr_opt(&self.token) {
err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
} else {
err.span_label(self.token.span, "expected identifier");
if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
err.span_suggestion(
self.token.span,
"remove this comma",
"",
Applicability::MachineApplicable,
);
}
}
err
}
pub(super) fn expected_one_of_not_found(
&mut self,
edible: &[TokenKind],
inedible: &[TokenKind],
) -> PResult<'a, bool /* recovered */> {
debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
fn tokens_to_string(tokens: &[TokenType]) -> String {
let mut i = tokens.iter();
// This might be a sign we need a connect method on `Iterator`.
let b = i.next().map_or_else(String::new, |t| t.to_string());
i.enumerate().fold(b, |mut b, (i, a)| {
if tokens.len() > 2 && i == tokens.len() - 2 {
b.push_str(", or ");
} else if tokens.len() == 2 && i == tokens.len() - 2 {
b.push_str(" or ");
} else {
b.push_str(", ");
}
b.push_str(&a.to_string());
b
})
}
let mut expected = edible
.iter()
.map(|x| TokenType::Token(x.clone()))
.chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
.chain(self.expected_tokens.iter().cloned())
.filter_map(|token| {
// filter out suggestions which suggest the same token which was found and deemed incorrect
fn is_ident_eq_keyword(found: &TokenKind, expected: &TokenType) -> bool {
if let TokenKind::Ident(current_sym, _) = found {
if let TokenType::Keyword(suggested_sym) = expected {
return current_sym == suggested_sym;
}
}
false
}
if token != parser::TokenType::Token(self.token.kind.clone()) {
let eq = is_ident_eq_keyword(&self.token.kind, &token);
// if the suggestion is a keyword and the found token is an ident,
// the content of which are equal to the suggestion's content,
// we can remove that suggestion (see the return None statement below)
// if this isn't the case however, and the suggestion is a token the
// content of which is the same as the found token's, we remove it as well
if !eq {
if let TokenType::Token(kind) = &token {
if kind == &self.token.kind {
return None;
}
}
return Some(token);
}
}
return None;
})
.collect::<Vec<_>>();
expected.sort_by_cached_key(|x| x.to_string());
expected.dedup();
let sm = self.sess.source_map();
let msg = format!("expected `;`, found {}", super::token_descr(&self.token));
let appl = Applicability::MachineApplicable;
if expected.contains(&TokenType::Token(token::Semi)) {
if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
// Likely inside a macro, can't provide meaningful suggestions.
} else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
// The current token is in the same line as the prior token, not recoverable.
} else if [token::Comma, token::Colon].contains(&self.token.kind)
&& self.prev_token.kind == token::CloseDelim(Delimiter::Parenthesis)
{
// Likely typo: The current token is on a new line and is expected to be
// `.`, `;`, `?`, or an operator after a close delimiter token.
//
// let a = std::process::Command::new("echo")
// .arg("1")
// ,arg("2")
// ^
// https://github.com/rust-lang/rust/issues/72253
} else if self.look_ahead(1, |t| {
t == &token::CloseDelim(Delimiter::Brace)
|| t.can_begin_expr() && t.kind != token::Colon
}) && [token::Comma, token::Colon].contains(&self.token.kind)
{
// Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
// either `,` or `:`, and the next token could either start a new statement or is a
// block close. For example:
//
// let x = 32:
// let y = 42;
self.bump();
let sp = self.prev_token.span;
self.struct_span_err(sp, &msg)
.span_suggestion_short(sp, "change this to `;`", ";", appl)
.emit();
return Ok(true);
} else if self.look_ahead(0, |t| {
t == &token::CloseDelim(Delimiter::Brace)
|| ((t.can_begin_expr() || t.can_begin_item())
&& t != &token::Semi
&& t != &token::Pound)
// Avoid triggering with too many trailing `#` in raw string.
|| (sm.is_multiline(
self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
) && t == &token::Pound)
}) && !expected.contains(&TokenType::Token(token::Comma))
{
// Missing semicolon typo. This is triggered if the next token could either start a
// new statement or is a block close. For example:
//
// let x = 32
// let y = 42;
let sp = self.prev_token.span.shrink_to_hi();
self.struct_span_err(sp, &msg)
.span_label(self.token.span, "unexpected token")
.span_suggestion_short(sp, "add `;` here", ";", appl)
.emit();
return Ok(true);
}
}
let expect = tokens_to_string(&expected);
let actual = super::token_descr(&self.token);
let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
let short_expect = if expected.len() > 6 {
format!("{} possible tokens", expected.len())
} else {
expect.clone()
};
(
format!("expected one of {expect}, found {actual}"),
(self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")),
)
} else if expected.is_empty() {
(
format!("unexpected token: {actual}"),
(self.prev_token.span, "unexpected token after this".to_string()),
)
} else {
(
format!("expected {expect}, found {actual}"),
(self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
)
};
self.last_unexpected_token_span = Some(self.token.span);
let mut err = self.struct_span_err(self.token.span, &msg_exp);
if let TokenKind::Ident(symbol, _) = &self.prev_token.kind {
if ["def", "fun", "func", "function"].contains(&symbol.as_str()) {
err.span_suggestion_short(
self.prev_token.span,
&format!("write `fn` instead of `{symbol}` to declare a function"),
"fn",
appl,
);
}
}
// `pub` may be used for an item or `pub(crate)`
if self.prev_token.is_ident_named(sym::public)
&& (self.token.can_begin_item()
|| self.token.kind == TokenKind::OpenDelim(Delimiter::Parenthesis))