-
Notifications
You must be signed in to change notification settings - Fork 13.2k
/
Copy pathdiagnostics.rs
3438 lines (3241 loc) · 145 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
// ignore-tidy-filelength
use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
use crate::late::{LifetimeBinderKind, LifetimeRes, LifetimeRibKind, LifetimeUseSet};
use crate::ty::fast_reject::SimplifiedType;
use crate::{errors, path_names_to_string};
use crate::{Module, ModuleKind, ModuleOrUniformRoot};
use crate::{PathResult, PathSource, Segment};
use rustc_hir::def::Namespace::{self, *};
use rustc_ast::ptr::P;
use rustc_ast::visit::{walk_ty, FnCtxt, FnKind, LifetimeCtxt, Visitor};
use rustc_ast::{
self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
MethodCall, NodeId, Path, Ty, TyKind, DUMMY_NODE_ID,
};
use rustc_ast_pretty::pprust::where_bound_predicate_to_string;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{
codes::*, pluralize, struct_span_code_err, Applicability, DiagnosticBuilder, ErrorGuaranteed,
MultiSpan, SuggestionStyle,
};
use rustc_hir as hir;
use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
use rustc_hir::def_id::{DefId, CRATE_DEF_ID};
use rustc_hir::PrimTy;
use rustc_session::lint;
use rustc_session::Session;
use rustc_span::edit_distance::find_best_match_for_name;
use rustc_span::edition::Edition;
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::Span;
use rustc_middle::ty;
use std::borrow::Cow;
use std::iter;
use std::ops::Deref;
use thin_vec::ThinVec;
use super::NoConstantGenericsReason;
type Res = def::Res<ast::NodeId>;
/// A field or associated item from self type suggested in case of resolution failure.
enum AssocSuggestion {
Field(Span),
MethodWithSelf { called: bool },
AssocFn { called: bool },
AssocType,
AssocConst,
}
impl AssocSuggestion {
fn action(&self) -> &'static str {
match self {
AssocSuggestion::Field(_) => "use the available field",
AssocSuggestion::MethodWithSelf { called: true } => {
"call the method with the fully-qualified path"
}
AssocSuggestion::MethodWithSelf { called: false } => {
"refer to the method with the fully-qualified path"
}
AssocSuggestion::AssocFn { called: true } => "call the associated function",
AssocSuggestion::AssocFn { called: false } => "refer to 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].iter().cloned().collect(),
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 cascading 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.
#[derive(Debug)]
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)>,
module: Option<DefId>,
}
#[derive(Debug)]
enum TypoCandidate {
Typo(TypoSuggestion),
Shadowed(Res, Option<Span>),
None,
}
impl TypoCandidate {
fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
match self {
TypoCandidate::Typo(sugg) => Some(sugg),
TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
}
}
}
impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
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(DefKind::TyParam, def_id) => {
Some((self.r.def_span(def_id), "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
.tcx
.sess
.source_map()
.span_to_snippet(span)
.is_ok_and(|snippet| snippet.ends_with(')'))
}
Res::Def(
DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
_,
)
| Res::SelfCtor(_)
| Res::PrimTy(_)
| Res::Local(_) => true,
_ => false,
},
suggestion: None,
module: None,
}
} else {
let mut span_label = None;
let item_ident = path.last().unwrap().ident;
let item_span = item_ident.span;
let (mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
debug!(?self.diagnostic_metadata.current_impl_items);
debug!(?self.diagnostic_metadata.current_function);
let suggestion = if self.current_trait_ref.is_none()
&& let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
&& let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
&& let FnKind::Fn(_, _, sig, ..) = fn_kind
&& let Some(items) = self.diagnostic_metadata.current_impl_items
&& let Some(item) = items.iter().find(|i| {
i.ident.name == item_str.name
// Don't suggest if the item is in Fn signature arguments (#112590).
&& !sig.span.contains(item_span)
}) {
let sp = item_span.shrink_to_lo();
// Account for `Foo { field }` when suggesting `self.field` so we result on
// `Foo { field: self.field }`.
let field = match source {
PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
expr.fields.iter().find(|f| f.ident == item_ident)
}
_ => None,
};
let pre = if let Some(field) = field
&& field.is_shorthand
{
format!("{item_ident}: ")
} else {
String::new()
};
// Ensure we provide a structured suggestion for an assoc fn only for
// expressions that are actually a fn call.
let is_call = match field {
Some(ast::ExprField { expr, .. }) => {
matches!(expr.kind, ExprKind::Call(..))
}
_ => matches!(
source,
PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
),
};
match &item.kind {
AssocItemKind::Fn(fn_)
if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
{
// Ensure that we only suggest `self.` if `self` is available,
// you can't call `fn foo(&self)` from `fn bar()` (#115992).
// We also want to mention that the method exists.
span_label = Some((
item.ident.span,
"a method by that name is available on `Self` here",
));
None
}
AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
span_label = Some((
item.ident.span,
"an associated function by that name is available on `Self` here",
));
None
}
AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
Some((sp, "consider using the method on `Self`", format!("{pre}self.")))
}
AssocItemKind::Fn(_) => Some((
sp,
"consider using the associated function on `Self`",
format!("{pre}Self::"),
)),
AssocItemKind::Const(..) => Some((
sp,
"consider using the associated constant on `Self`",
format!("{pre}Self::"),
)),
_ => None,
}
} else {
None
};
(String::new(), "this scope".to_string(), None, suggestion)
} else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
if self.r.tcx.sess.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, None)
} else {
(
String::new(),
"the crate root".to_string(),
Some(CRATE_DEF_ID.to_def_id()),
None,
)
}
} else if path.len() == 2 && path[0].ident.name == kw::Crate {
(String::new(), "the crate root".to_string(), Some(CRATE_DEF_ID.to_def_id()), None)
} else {
let mod_path = &path[..path.len() - 1];
let mod_res = self.resolve_path(mod_path, Some(TypeNS), None);
let mod_prefix = match mod_res {
PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
_ => None,
};
let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
let mod_prefix =
mod_prefix.map_or_else(String::new, |res| (format!("{} ", res.descr())));
(mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), module_did, 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", item_typo))
// FIXME(vincenzopalazzo): make the check smarter,
// and maybe expand with levenshtein distance checks
} else if item_str.as_str() == "printf" {
Some((
item_span,
"you may have meant to use the `print` macro",
"print!".to_owned(),
))
} 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,
could_be_expr: false,
suggestion,
module,
}
}
}
/// Try to suggest for a module path that cannot be resolved.
/// Such as `fmt::Debug` where `fmt` is not resolved without importing,
/// here we search with `lookup_import_candidates` for a module named `fmt`
/// with `TypeNS` as namespace.
///
/// We need a separate function here because we won't suggest for a path with single segment
/// and we won't change `SourcePath` api `is_expected` to match `Type` with `DefKind::Mod`
pub(crate) fn smart_resolve_partial_mod_path_errors(
&mut self,
prefix_path: &[Segment],
following_seg: Option<&Segment>,
) -> Vec<ImportSuggestion> {
if let Some(segment) = prefix_path.last()
&& let Some(following_seg) = following_seg
{
let candidates = self.r.lookup_import_candidates(
segment.ident,
Namespace::TypeNS,
&self.parent_scope,
&|res: Res| matches!(res, Res::Def(DefKind::Mod, _)),
);
// double check next seg is valid
candidates
.into_iter()
.filter(|candidate| {
if let Some(def_id) = candidate.did
&& let Some(module) = self.r.get_module(def_id)
{
Some(def_id) != self.parent_scope.module.opt_def_id()
&& self
.r
.resolutions(module)
.borrow()
.iter()
.any(|(key, _r)| key.ident.name == following_seg.ident.name)
} else {
false
}
})
.collect::<Vec<_>>()
} else {
Vec::new()
}
}
/// 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],
following_seg: Option<&Segment>,
span: Span,
source: PathSource<'_>,
res: Option<Res>,
) -> (DiagnosticBuilder<'tcx>, 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.dcx().struct_span_err(base_error.span, base_error.msg.clone());
err.code(code);
self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
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_changing_type_to_const_param(&mut err, res, source, span);
if self.suggest_pattern_match_with_let(&mut err, source, span) {
// Fallback label.
err.span_label(base_error.span, base_error.fallback_label);
return (err, Vec::new());
}
self.suggest_self_or_self_ref(&mut err, path, span);
self.detect_assoc_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, mut candidates) = self.try_lookup_name_relaxed(
&mut err,
source,
path,
following_seg,
span,
res,
&base_error,
);
if found {
return (err, candidates);
}
if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
// if there is already a shadowed name, don'suggest candidates for importing
candidates.clear();
}
let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
fallback |= self.suggest_typo(&mut err, source, path, following_seg, 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);
if let Some(module) = base_error.module {
self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
}
(err, candidates)
}
fn detect_assoc_type_constraint_meant_as_path(
&self,
err: &mut DiagnosticBuilder<'_>,
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::TraitBoundModifiers::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 DiagnosticBuilder<'_>,
path: &[Segment],
span: Span,
) {
if !self.self_type_is_available() {
return;
}
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()) {
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
.tcx
.sess
.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<'_>,
source: PathSource<'_>,
path: &[Segment],
following_seg: Option<&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<_>>();
// Try to filter out intrinsics candidates, as long as we have
// some other candidates to suggest.
let intrinsic_candidates: Vec<_> = candidates
.extract_if(|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 = intrinsic_candidates;
}
let crate_def_id = CRATE_DEF_ID.to_def_id();
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() {
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 {n} others"),
};
format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
} else {
String::new()
};
let msg = format!("{preamble}try using the variant's enum");
err.span_suggestions(
span,
msg,
enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
Applicability::MachineApplicable,
);
}
}
// Try finding a suitable replacement.
let typo_sugg = self
.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
.to_opt_suggestion();
if path.len() == 1
&& !matches!(source, PathSource::Delegation)
&& self.self_type_is_available()
{
if let Some(candidate) =
self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
{
let self_is_available = self.self_value_is_available(path[0].ident.span);
// Account for `Foo { field }` when suggesting `self.field` so we result on
// `Foo { field: self.field }`.
let pre = match source {
PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
if expr
.fields
.iter()
.any(|f| f.ident == path[0].ident && f.is_shorthand) =>
{
format!("{path_str}: ")
}
_ => String::new(),
};
match candidate {
AssocSuggestion::Field(field_span) => {
if self_is_available {
err.span_suggestion_verbose(
span.shrink_to_lo(),
"you might have meant to use the available field",
format!("{pre}self."),
Applicability::MachineApplicable,
);
} else {
err.span_label(field_span, "a field by that name exists in `Self`");
}
}
AssocSuggestion::MethodWithSelf { called } if self_is_available => {
let msg = if called {
"you might have meant to call the method"
} else {
"you might have meant to refer to the method"
};
err.span_suggestion_verbose(
span.shrink_to_lo(),
msg,
"self.",
Applicability::MachineApplicable,
);
}
AssocSuggestion::MethodWithSelf { .. }
| AssocSuggestion::AssocFn { .. }
| AssocSuggestion::AssocConst
| AssocSuggestion::AssocType => {
err.span_suggestion_verbose(
span.shrink_to_lo(),
format!("you might have meant to {}", candidate.action()),
"Self::",
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.tcx.sess.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,
path,
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);
}
}
// Try to find in last block rib
if let Some(rib) = &self.last_block_rib
&& let RibKind::Normal = rib.kind
{
for (ident, &res) in &rib.bindings {
if let Res::Local(_) = res
&& path.len() == 1
&& ident.span.eq_ctxt(path[0].ident.span)
&& ident.name == path[0].ident.name
{
err.span_help(
ident.span,
format!("the binding `{path_str}` is available in a different scope in the same function"),
);
return (true, candidates);
}
}
}
if candidates.is_empty() {
candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
}
return (false, candidates);
}
fn suggest_trait_and_bounds(
&mut self,
err: &mut DiagnosticBuilder<'_>,
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 @ [first_bound, .., last_bound]) =
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 = first_bound.span();
// `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
let end_span = last_bound.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<'_>,
source: PathSource<'_>,
path: &[Segment],
following_seg: Option<&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, following_seg, source.namespace(), is_expected);
let mut fallback = false;
let typo_sugg = typo_sugg.to_opt_suggestion();
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 the algorithm), suggest it
let suggestion = self.get_single_associated_item(path, &source, is_expected);
if !self.r.add_typo_suggestion(err, suggestion, ident_span) {
fallback = !self.let_binding_suggestion(err, ident_span);
}
}
fallback
}
fn suggest_shadowed(
&mut self,
err: &mut DiagnosticBuilder<'_>,
source: PathSource<'_>,
path: &[Segment],
following_seg: Option<&Segment>,
span: Span,
) -> bool {
let is_expected = &|res| source.is_expected(res);
let typo_sugg =
self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
let is_in_same_file = &|sp1, sp2| {
let source_map = self.r.tcx.sess.source_map();
let file1 = source_map.span_to_filename(sp1);
let file2 = source_map.span_to_filename(sp2);
file1 == file2
};
// print 'you might have meant' if the candidate is (1) is a shadowed name with
// accessible definition and (2) either defined in the same crate as the typo
// (could be in a different file) or introduced in the same file as the typo
// (could belong to a different crate)
if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
&& res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
{
err.span_label(
sugg_span,
format!("you might have meant to refer to this {}", res.descr()),
);
return true;
}
false
}
fn err_code_special_cases(
&mut self,
err: &mut DiagnosticBuilder<'_>,
source: PathSource<'_>,
path: &[Segment],
span: Span,
) {
if let Some(err_code) = err.code {
if err_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 == 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 DiagnosticBuilder<'_>,
source: PathSource<'_>,
path: &[Segment],
span: Span,
) -> bool {
if !is_self_type(path, source.namespace()) {
return false;
}
err.code(E0411);
err.span_label(span, "`Self` is only available in impls, traits, and type definitions");