-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
Copy pathdiagnostics.rs
2529 lines (2380 loc) · 104 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 crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
use crate::late::{LifetimeBinderKind, LifetimeRes, LifetimeRibKind, LifetimeUseSet};
use crate::path_names_to_string;
use crate::{Module, ModuleKind, ModuleOrUniformRoot};
use crate::{PathResult, PathSource, Segment};
use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt};
use rustc_ast::{
self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
NodeId, Path, Ty, TyKind, DUMMY_NODE_ID,
};
use rustc_ast_pretty::pprust::path_segment_to_string;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{
pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
MultiSpan,
};
use rustc_hir as hir;
use rustc_hir::def::Namespace::{self, *};
use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::PrimTy;
use rustc_session::lint;
use rustc_session::parse::feature_err;
use rustc_session::Session;
use rustc_span::edition::Edition;
use rustc_span::hygiene::MacroKind;
use rustc_span::lev_distance::find_best_match_for_name;
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{BytePos, Span};
use std::iter;
use std::ops::Deref;
type Res = def::Res<ast::NodeId>;
/// A field or associated item from self type suggested in case of resolution failure.
enum AssocSuggestion {
Field,
MethodWithSelf,
AssocFn,
AssocType,
AssocConst,
}
impl AssocSuggestion {
fn action(&self) -> &'static str {
match self {
AssocSuggestion::Field => "use the available field",
AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
AssocSuggestion::AssocFn => "call the associated function",
AssocSuggestion::AssocConst => "use the associated `const`",
AssocSuggestion::AssocType => "use the associated type",
}
}
}
fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
}
fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
}
/// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
let variant_path = &suggestion.path;
let variant_path_string = path_names_to_string(variant_path);
let path_len = suggestion.path.segments.len();
let enum_path = ast::Path {
span: suggestion.path.span,
segments: suggestion.path.segments[0..path_len - 1].to_vec(),
tokens: None,
};
let enum_path_string = path_names_to_string(&enum_path);
(variant_path_string, enum_path_string)
}
/// Description of an elided lifetime.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(super) struct MissingLifetime {
/// Used to overwrite the resolution with the suggestion, to avoid cascasing errors.
pub id: NodeId,
/// Where to suggest adding the lifetime.
pub span: Span,
/// How the lifetime was introduced, to have the correct space and comma.
pub kind: MissingLifetimeKind,
/// Number of elided lifetimes, used for elision in path.
pub count: usize,
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(super) enum MissingLifetimeKind {
/// An explicit `'_`.
Underscore,
/// An elided lifetime `&' ty`.
Ampersand,
/// An elided lifetime in brackets with written brackets.
Comma,
/// An elided lifetime with elided brackets.
Brackets,
}
/// Description of the lifetimes appearing in a function parameter.
/// This is used to provide a literal explanation to the elision failure.
#[derive(Clone, Debug)]
pub(super) struct ElisionFnParameter {
/// The index of the argument in the original definition.
pub index: usize,
/// The name of the argument if it's a simple ident.
pub ident: Option<Ident>,
/// The number of lifetimes in the parameter.
pub lifetime_count: usize,
/// The span of the parameter.
pub span: Span,
}
/// Description of lifetimes that appear as candidates for elision.
/// This is used to suggest introducing an explicit lifetime.
#[derive(Debug)]
pub(super) enum LifetimeElisionCandidate {
/// This is not a real lifetime.
Ignore,
/// There is a named lifetime, we won't suggest anything.
Named,
Missing(MissingLifetime),
}
/// Only used for diagnostics.
struct BaseError {
msg: String,
fallback_label: String,
span: Span,
span_label: Option<(Span, &'static str)>,
could_be_expr: bool,
suggestion: Option<(Span, &'static str, String)>,
}
impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
fn def_span(&self, def_id: DefId) -> Option<Span> {
match def_id.krate {
LOCAL_CRATE => self.r.opt_span(def_id),
_ => Some(self.r.cstore().get_span_untracked(def_id, self.r.session)),
}
}
fn make_base_error(
&mut self,
path: &[Segment],
span: Span,
source: PathSource<'_>,
res: Option<Res>,
) -> BaseError {
// Make the base error.
let mut expected = source.descr_expected();
let path_str = Segment::names_to_string(path);
let item_str = path.last().unwrap().ident;
if let Some(res) = res {
BaseError {
msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
fallback_label: format!("not a {expected}"),
span,
span_label: match res {
Res::Def(kind, def_id) if kind == DefKind::TyParam => {
self.def_span(def_id).map(|span| (span, "found this type parameter"))
}
_ => None,
},
could_be_expr: match res {
Res::Def(DefKind::Fn, _) => {
// Verify whether this is a fn call or an Fn used as a type.
self.r
.session
.source_map()
.span_to_snippet(span)
.map(|snippet| snippet.ends_with(')'))
.unwrap_or(false)
}
Res::Def(
DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
_,
)
| Res::SelfCtor(_)
| Res::PrimTy(_)
| Res::Local(_) => true,
_ => false,
},
suggestion: None,
}
} else {
let item_span = path.last().unwrap().ident.span;
let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
debug!(?self.diagnostic_metadata.current_impl_items);
debug!(?self.diagnostic_metadata.current_function);
let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
&& let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
&& self.current_trait_ref.is_none()
&& let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
&& let Some(item) = items.iter().find(|i| {
if let AssocItemKind::Fn(fn_) = &i.kind
&& !fn_.sig.decl.has_self()
&& i.ident.name == item_str.name
{
debug!(?item_str.name);
debug!(?fn_.sig.decl.inputs);
return true
}
false
})
{
Some((
item_span,
"consider using the associated function",
format!("Self::{}", item.ident)
))
} else {
None
};
(String::new(), "this scope".to_string(), suggestion)
} else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
if self.r.session.edition() > Edition::Edition2015 {
// In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
// which overrides all other expectations of item type
expected = "crate";
(String::new(), "the list of imported crates".to_string(), None)
} else {
(String::new(), "the crate root".to_string(), None)
}
} else if path.len() == 2 && path[0].ident.name == kw::Crate {
(String::new(), "the crate root".to_string(), None)
} else {
let mod_path = &path[..path.len() - 1];
let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
_ => None,
}
.map_or_else(String::new, |res| format!("{} ", res.descr()));
(mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
};
let (fallback_label, suggestion) = if path_str == "async"
&& expected.starts_with("struct")
{
("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion)
} else {
// check if we are in situation of typo like `True` instead of `true`.
let override_suggestion =
if ["true", "false"].contains(&item_str.to_string().to_lowercase().as_str()) {
let item_typo = item_str.to_string().to_lowercase();
Some((
item_span,
"you may want to use a bool value instead",
format!("{}", item_typo),
))
} else {
suggestion
};
(format!("not found in {mod_str}"), override_suggestion)
};
BaseError {
msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
fallback_label,
span: item_span,
span_label: None,
could_be_expr: false,
suggestion,
}
}
}
/// Handles error reporting for `smart_resolve_path_fragment` function.
/// Creates base error and amends it with one short label and possibly some longer helps/notes.
pub(crate) fn smart_resolve_report_errors(
&mut self,
path: &[Segment],
span: Span,
source: PathSource<'_>,
res: Option<Res>,
) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
debug!(?res, ?source);
let base_error = self.make_base_error(path, span, source, res);
let code = source.error_code(res.is_some());
let mut err =
self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
if let Some((span, label)) = base_error.span_label {
err.span_label(span, label);
}
if let Some(ref sugg) = base_error.suggestion {
err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
}
self.suggest_bare_struct_literal(&mut err);
self.suggest_pattern_match_with_let(&mut err, source, span);
self.suggest_self_or_self_ref(&mut err, path, span);
self.detect_assoct_type_constraint_meant_as_path(&mut err, &base_error);
if self.suggest_self_ty(&mut err, source, path, span)
|| self.suggest_self_value(&mut err, source, path, span)
{
return (err, Vec::new());
}
let (found, candidates) =
self.try_lookup_name_relaxed(&mut err, source, path, span, res, &base_error);
if found {
return (err, candidates);
}
if !self.type_ascription_suggestion(&mut err, base_error.span) {
let mut fallback =
self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
fallback |= self.suggest_typo(&mut err, source, path, span, &base_error);
if fallback {
// Fallback label.
err.span_label(base_error.span, &base_error.fallback_label);
}
}
self.err_code_special_cases(&mut err, source, path, span);
(err, candidates)
}
fn detect_assoct_type_constraint_meant_as_path(
&self,
err: &mut Diagnostic,
base_error: &BaseError,
) {
let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
let TyKind::Path(_, path) = &ty.kind else { return; };
for segment in &path.segments {
let Some(params) = &segment.args else { continue; };
let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
for param in ¶ms.args {
let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
continue;
};
for bound in bounds {
let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
= bound else
{
continue;
};
if base_error.span == trait_ref.span {
err.span_suggestion_verbose(
constraint.ident.span.between(trait_ref.span),
"you might have meant to write a path instead of an associated type bound",
"::",
Applicability::MachineApplicable,
);
}
}
}
}
}
fn suggest_self_or_self_ref(&mut self, err: &mut Diagnostic, path: &[Segment], span: Span) {
let is_assoc_fn = self.self_type_is_available();
let Some(path_last_segment) = path.last() else { return };
let item_str = path_last_segment.ident;
// Emit help message for fake-self from other languages (e.g., `this` in Javascript).
if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
err.span_suggestion_short(
span,
"you might have meant to use `self` here instead",
"self",
Applicability::MaybeIncorrect,
);
if !self.self_value_is_available(path[0].ident.span) {
if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
&self.diagnostic_metadata.current_function
{
let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
(param.span.shrink_to_lo(), "&self, ")
} else {
(
self.r
.session
.source_map()
.span_through_char(*fn_span, '(')
.shrink_to_hi(),
"&self",
)
};
err.span_suggestion_verbose(
span,
"if you meant to use `self`, you are also missing a `self` receiver \
argument",
sugg,
Applicability::MaybeIncorrect,
);
}
}
}
}
fn try_lookup_name_relaxed(
&mut self,
err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
source: PathSource<'_>,
path: &[Segment],
span: Span,
res: Option<Res>,
base_error: &BaseError,
) -> (bool, Vec<ImportSuggestion>) {
// Try to lookup name in more relaxed fashion for better error reporting.
let ident = path.last().unwrap().ident;
let is_expected = &|res| source.is_expected(res);
let ns = source.namespace();
let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
let path_str = Segment::names_to_string(path);
let ident_span = path.last().map_or(span, |ident| ident.ident.span);
let mut candidates = self
.r
.lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
.into_iter()
.filter(|ImportSuggestion { did, .. }| {
match (did, res.and_then(|res| res.opt_def_id())) {
(Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
_ => true,
}
})
.collect::<Vec<_>>();
let crate_def_id = CRATE_DEF_ID.to_def_id();
// Try to filter out intrinsics candidates, as long as we have
// some other candidates to suggest.
let intrinsic_candidates: Vec<_> = candidates
.drain_filter(|sugg| {
let path = path_names_to_string(&sugg.path);
path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
})
.collect();
if candidates.is_empty() {
// Put them back if we have no more candidates to suggest...
candidates.extend(intrinsic_candidates);
}
if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
let mut enum_candidates: Vec<_> = self
.r
.lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
.into_iter()
.map(|suggestion| import_candidate_to_enum_paths(&suggestion))
.filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
.collect();
if !enum_candidates.is_empty() {
if let (PathSource::Type, Some(span)) =
(source, self.diagnostic_metadata.current_type_ascription.last())
{
if self
.r
.session
.parse_sess
.type_ascription_path_suggestions
.borrow()
.contains(span)
{
// Already reported this issue on the lhs of the type ascription.
err.delay_as_bug();
return (true, candidates);
}
}
enum_candidates.sort();
// Contextualize for E0412 "cannot find type", but don't belabor the point
// (that it's a variant) for E0573 "expected type, found variant".
let preamble = if res.is_none() {
let others = match enum_candidates.len() {
1 => String::new(),
2 => " and 1 other".to_owned(),
n => format!(" and {} others", n),
};
format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
} else {
String::new()
};
let msg = format!("{}try using the variant's enum", preamble);
err.span_suggestions(
span,
&msg,
enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
Applicability::MachineApplicable,
);
}
}
// Try Levenshtein algorithm.
let typo_sugg = self.lookup_typo_candidate(path, source.namespace(), is_expected);
if path.len() == 1 && self.self_type_is_available() {
if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
let self_is_available = self.self_value_is_available(path[0].ident.span);
match candidate {
AssocSuggestion::Field => {
if self_is_available {
err.span_suggestion(
span,
"you might have meant to use the available field",
format!("self.{path_str}"),
Applicability::MachineApplicable,
);
} else {
err.span_label(span, "a field by this name exists in `Self`");
}
}
AssocSuggestion::MethodWithSelf if self_is_available => {
err.span_suggestion(
span,
"you might have meant to call the method",
format!("self.{path_str}"),
Applicability::MachineApplicable,
);
}
AssocSuggestion::MethodWithSelf
| AssocSuggestion::AssocFn
| AssocSuggestion::AssocConst
| AssocSuggestion::AssocType => {
err.span_suggestion(
span,
&format!("you might have meant to {}", candidate.action()),
format!("Self::{path_str}"),
Applicability::MachineApplicable,
);
}
}
self.r.add_typo_suggestion(err, typo_sugg, ident_span);
return (true, candidates);
}
// If the first argument in call is `self` suggest calling a method.
if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
let mut args_snippet = String::new();
if let Some(args_span) = args_span {
if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
args_snippet = snippet;
}
}
err.span_suggestion(
call_span,
&format!("try calling `{ident}` as a method"),
format!("self.{path_str}({args_snippet})"),
Applicability::MachineApplicable,
);
return (true, candidates);
}
}
// Try context-dependent help if relaxed lookup didn't work.
if let Some(res) = res {
if self.smart_resolve_context_dependent_help(
err,
span,
source,
res,
&path_str,
&base_error.fallback_label,
) {
// We do this to avoid losing a secondary span when we override the main error span.
self.r.add_typo_suggestion(err, typo_sugg, ident_span);
return (true, candidates);
}
}
return (false, candidates);
}
fn suggest_trait_and_bounds(
&mut self,
err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
source: PathSource<'_>,
res: Option<Res>,
span: Span,
base_error: &BaseError,
) -> bool {
let is_macro =
base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
let mut fallback = false;
if let (
PathSource::Trait(AliasPossibility::Maybe),
Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
false,
) = (source, res, is_macro)
{
if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
fallback = true;
let spans: Vec<Span> = bounds
.iter()
.map(|bound| bound.span())
.filter(|&sp| sp != base_error.span)
.collect();
let start_span = bounds[0].span();
// `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
let end_span = bounds.last().unwrap().span();
// `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
let last_bound_span = spans.last().cloned().unwrap();
let mut multi_span: MultiSpan = spans.clone().into();
for sp in spans {
let msg = if sp == last_bound_span {
format!(
"...because of {these} bound{s}",
these = pluralize!("this", bounds.len() - 1),
s = pluralize!(bounds.len() - 1),
)
} else {
String::new()
};
multi_span.push_span_label(sp, msg);
}
multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
err.span_help(
multi_span,
"`+` is used to constrain a \"trait object\" type with lifetimes or \
auto-traits; structs and enums can't be bound in that way",
);
if bounds.iter().all(|bound| match bound {
ast::GenericBound::Outlives(_) => true,
ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
}) {
let mut sugg = vec![];
if base_error.span != start_span {
sugg.push((start_span.until(base_error.span), String::new()));
}
if base_error.span != end_span {
sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
}
err.multipart_suggestion(
"if you meant to use a type and not a trait here, remove the bounds",
sugg,
Applicability::MaybeIncorrect,
);
}
}
}
fallback |= self.restrict_assoc_type_in_where_clause(span, err);
fallback
}
fn suggest_typo(
&mut self,
err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
source: PathSource<'_>,
path: &[Segment],
span: Span,
base_error: &BaseError,
) -> bool {
let is_expected = &|res| source.is_expected(res);
let ident_span = path.last().map_or(span, |ident| ident.ident.span);
let typo_sugg = self.lookup_typo_candidate(path, source.namespace(), is_expected);
let mut fallback = false;
if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
fallback = true;
match self.diagnostic_metadata.current_let_binding {
Some((pat_sp, Some(ty_sp), None))
if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
{
err.span_suggestion_short(
pat_sp.between(ty_sp),
"use `=` if you meant to assign",
" = ",
Applicability::MaybeIncorrect,
);
}
_ => {}
}
// If the trait has a single item (which wasn't matched by Levenshtein), suggest it
let suggestion = self.get_single_associated_item(&path, &source, is_expected);
self.r.add_typo_suggestion(err, suggestion, ident_span);
}
fallback
}
fn err_code_special_cases(
&mut self,
err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
source: PathSource<'_>,
path: &[Segment],
span: Span,
) {
if let Some(err_code) = &err.code {
if err_code == &rustc_errors::error_code!(E0425) {
for label_rib in &self.label_ribs {
for (label_ident, node_id) in &label_rib.bindings {
let ident = path.last().unwrap().ident;
if format!("'{}", ident) == label_ident.to_string() {
err.span_label(label_ident.span, "a label with a similar name exists");
if let PathSource::Expr(Some(Expr {
kind: ExprKind::Break(None, Some(_)),
..
})) = source
{
err.span_suggestion(
span,
"use the similarly named label",
label_ident.name,
Applicability::MaybeIncorrect,
);
// Do not lint against unused label when we suggest them.
self.diagnostic_metadata.unused_labels.remove(node_id);
}
}
}
}
} else if err_code == &rustc_errors::error_code!(E0412) {
if let Some(correct) = Self::likely_rust_type(path) {
err.span_suggestion(
span,
"perhaps you intended to use this type",
correct,
Applicability::MaybeIncorrect,
);
}
}
}
}
/// Emit special messages for unresolved `Self` and `self`.
fn suggest_self_ty(
&mut self,
err: &mut Diagnostic,
source: PathSource<'_>,
path: &[Segment],
span: Span,
) -> bool {
if !is_self_type(path, source.namespace()) {
return false;
}
err.code(rustc_errors::error_code!(E0411));
err.span_label(
span,
"`Self` is only available in impls, traits, and type definitions".to_string(),
);
if let Some(item_kind) = self.diagnostic_metadata.current_item {
err.span_label(
item_kind.ident.span,
format!(
"`Self` not allowed in {} {}",
item_kind.kind.article(),
item_kind.kind.descr()
),
);
}
true
}
fn suggest_self_value(
&mut self,
err: &mut Diagnostic,
source: PathSource<'_>,
path: &[Segment],
span: Span,
) -> bool {
if !is_self_value(path, source.namespace()) {
return false;
}
debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
err.code(rustc_errors::error_code!(E0424));
err.span_label(
span,
match source {
PathSource::Pat => {
"`self` value is a keyword and may not be bound to variables or shadowed"
}
_ => "`self` value is a keyword only available in methods with a `self` parameter",
},
);
let is_assoc_fn = self.self_type_is_available();
if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
// The current function has a `self' parameter, but we were unable to resolve
// a reference to `self`. This can only happen if the `self` identifier we
// are resolving came from a different hygiene context.
if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
} else {
let doesnt = if is_assoc_fn {
let (span, sugg) = fn_kind
.decl()
.inputs
.get(0)
.map(|p| (p.span.shrink_to_lo(), "&self, "))
.unwrap_or_else(|| {
// Try to look for the "(" after the function name, if possible.
// This avoids placing the suggestion into the visibility specifier.
let span = fn_kind
.ident()
.map_or(*span, |ident| span.with_lo(ident.span.hi()));
(
self.r
.session
.source_map()
.span_through_char(span, '(')
.shrink_to_hi(),
"&self",
)
});
err.span_suggestion_verbose(
span,
"add a `self` receiver parameter to make the associated `fn` a method",
sugg,
Applicability::MaybeIncorrect,
);
"doesn't"
} else {
"can't"
};
if let Some(ident) = fn_kind.ident() {
err.span_label(
ident.span,
&format!("this function {} have a `self` parameter", doesnt),
);
}
}
} else if let Some(item_kind) = self.diagnostic_metadata.current_item {
err.span_label(
item_kind.ident.span,
format!(
"`self` not allowed in {} {}",
item_kind.kind.article(),
item_kind.kind.descr()
),
);
}
true
}
fn suggest_swapping_misplaced_self_ty_and_trait(
&mut self,
err: &mut Diagnostic,
source: PathSource<'_>,
res: Option<Res>,
span: Span,
) {
if let Some((trait_ref, self_ty)) =
self.diagnostic_metadata.currently_processing_impl_trait.clone()
&& let TyKind::Path(_, self_ty_path) = &self_ty.kind
&& let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
&& let ModuleKind::Def(DefKind::Trait, ..) = module.kind
&& trait_ref.path.span == span
&& let PathSource::Trait(_) = source
&& let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
&& let Ok(self_ty_str) =
self.r.session.source_map().span_to_snippet(self_ty.span)
&& let Ok(trait_ref_str) =
self.r.session.source_map().span_to_snippet(trait_ref.path.span)
{
err.multipart_suggestion(
"`impl` items mention the trait being implemented first and the type it is being implemented for second",
vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
Applicability::MaybeIncorrect,
);
}
}
fn suggest_bare_struct_literal(&mut self, err: &mut Diagnostic) {
if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
err.multipart_suggestion(
"you might have meant to write a `struct` literal",
vec![
(span.shrink_to_lo(), "{ SomeStruct ".to_string()),
(span.shrink_to_hi(), "}".to_string()),
],
Applicability::HasPlaceholders,
);
}
}
fn suggest_pattern_match_with_let(
&mut self,
err: &mut Diagnostic,
source: PathSource<'_>,
span: Span,
) {
if let PathSource::Expr(_) = source &&
let Some(Expr {
span: expr_span,
kind: ExprKind::Assign(lhs, _, _),
..
}) = self.diagnostic_metadata.in_if_condition {
// Icky heuristic so we don't suggest:
// `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
// `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
if lhs.is_approximately_pattern() && lhs.span.contains(span) {
err.span_suggestion_verbose(
expr_span.shrink_to_lo(),
"you might have meant to use pattern matching",
"let ",
Applicability::MaybeIncorrect,
);
}
}
}
fn get_single_associated_item(
&mut self,
path: &[Segment],
source: &PathSource<'_>,
filter_fn: &impl Fn(Res) -> bool,
) -> Option<TypoSuggestion> {
if let crate::PathSource::TraitItem(_) = source {
let mod_path = &path[..path.len() - 1];
if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
self.resolve_path(mod_path, None, None)
{
let resolutions = self.r.resolutions(module).borrow();
let targets: Vec<_> =
resolutions
.iter()
.filter_map(|(key, resolution)| {
resolution.borrow().binding.map(|binding| binding.res()).and_then(
|res| if filter_fn(res) { Some((key, res)) } else { None },
)
})
.collect();
if targets.len() == 1 {
let target = targets[0];
return Some(TypoSuggestion::single_item_from_res(
target.0.ident.name,
target.1,
));
}
}
}
None
}
/// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
// Detect that we are actually in a `where` predicate.
let (bounded_ty, bounds, where_span) =
if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
bounded_ty,
bound_generic_params,
bounds,
span,
})) = self.diagnostic_metadata.current_where_predicate
{
if !bound_generic_params.is_empty() {
return false;
}
(bounded_ty, bounds, span)
} else {
return false;
};
// Confirm that the target is an associated type.
let (ty, position, path) = if let ast::TyKind::Path(
Some(ast::QSelf { ty, position, .. }),
path,
) = &bounded_ty.kind
{
// use this to verify that ident is a type param.
let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
return false;
};
if !matches!(
partial_res.full_res(),
Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
) {
return false;
}
(ty, position, path)
} else {
return false;
};
let peeled_ty = ty.peel_refs();
if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
// Confirm that the `SelfTy` is a type parameter.
let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
return false;
};
if !matches!(
partial_res.full_res(),
Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
) {
return false;
}
if let (
[ast::PathSegment { ident: constrain_ident, args: None, .. }],
[ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
) = (&type_param_path.segments[..], &bounds[..])
{
if let [ast::PathSegment { ident, args: None, .. }] =
&poly_trait_ref.trait_ref.path.segments[..]