]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_resolve/src/late/diagnostics.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / compiler / rustc_resolve / src / late / diagnostics.rs
1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
4 use crate::late::{LifetimeBinderKind, LifetimeRibKind, LifetimeUseSet};
5 use crate::path_names_to_string;
6 use crate::{Module, ModuleKind, ModuleOrUniformRoot};
7 use crate::{PathResult, PathSource, Segment};
8
9 use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt};
10 use rustc_ast::{
11 self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
12 NodeId, Path, Ty, TyKind,
13 };
14 use rustc_ast_pretty::pprust::path_segment_to_string;
15 use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
16 use rustc_errors::{
17 pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
18 MultiSpan,
19 };
20 use rustc_hir as hir;
21 use rustc_hir::def::Namespace::{self, *};
22 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
23 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
24 use rustc_hir::PrimTy;
25 use rustc_session::lint;
26 use rustc_session::parse::feature_err;
27 use rustc_session::Session;
28 use rustc_span::edition::Edition;
29 use rustc_span::hygiene::MacroKind;
30 use rustc_span::lev_distance::find_best_match_for_name;
31 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 use rustc_span::{BytePos, Span, DUMMY_SP};
33
34 use std::iter;
35 use std::ops::Deref;
36
37 use tracing::debug;
38
39 type Res = def::Res<ast::NodeId>;
40
41 /// A field or associated item from self type suggested in case of resolution failure.
42 enum AssocSuggestion {
43 Field,
44 MethodWithSelf,
45 AssocFn,
46 AssocType,
47 AssocConst,
48 }
49
50 impl AssocSuggestion {
51 fn action(&self) -> &'static str {
52 match self {
53 AssocSuggestion::Field => "use the available field",
54 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
55 AssocSuggestion::AssocFn => "call the associated function",
56 AssocSuggestion::AssocConst => "use the associated `const`",
57 AssocSuggestion::AssocType => "use the associated type",
58 }
59 }
60 }
61
62 pub(crate) enum MissingLifetimeSpot<'tcx> {
63 Generics(&'tcx hir::Generics<'tcx>),
64 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
65 Static,
66 }
67
68 pub(crate) enum ForLifetimeSpanType {
69 BoundEmpty,
70 BoundTail,
71 TypeEmpty,
72 TypeTail,
73 }
74
75 impl ForLifetimeSpanType {
76 pub(crate) fn descr(&self) -> &'static str {
77 match self {
78 Self::BoundEmpty | Self::BoundTail => "bound",
79 Self::TypeEmpty | Self::TypeTail => "type",
80 }
81 }
82
83 pub(crate) fn suggestion(&self, sugg: &str) -> String {
84 match self {
85 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
86 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
87 }
88 }
89 }
90
91 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &&'tcx hir::Generics<'tcx> {
92 fn into(self) -> MissingLifetimeSpot<'tcx> {
93 MissingLifetimeSpot::Generics(self)
94 }
95 }
96
97 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
98 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
99 }
100
101 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
102 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
103 }
104
105 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
106 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
107 let variant_path = &suggestion.path;
108 let variant_path_string = path_names_to_string(variant_path);
109
110 let path_len = suggestion.path.segments.len();
111 let enum_path = ast::Path {
112 span: suggestion.path.span,
113 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
114 tokens: None,
115 };
116 let enum_path_string = path_names_to_string(&enum_path);
117
118 (variant_path_string, enum_path_string)
119 }
120
121 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
122 fn def_span(&self, def_id: DefId) -> Option<Span> {
123 match def_id.krate {
124 LOCAL_CRATE => self.r.opt_span(def_id),
125 _ => Some(
126 self.r
127 .session
128 .source_map()
129 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
130 ),
131 }
132 }
133
134 /// Handles error reporting for `smart_resolve_path_fragment` function.
135 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
136 pub(crate) fn smart_resolve_report_errors(
137 &mut self,
138 path: &[Segment],
139 span: Span,
140 source: PathSource<'_>,
141 res: Option<Res>,
142 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
143 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
144 let ns = source.namespace();
145 let is_expected = &|res| source.is_expected(res);
146 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
147
148 debug!(?res, ?source);
149
150 // Make the base error.
151 struct BaseError<'a> {
152 msg: String,
153 fallback_label: String,
154 span: Span,
155 could_be_expr: bool,
156 suggestion: Option<(Span, &'a str, String)>,
157 }
158 let mut expected = source.descr_expected();
159 let path_str = Segment::names_to_string(path);
160 let item_str = path.last().unwrap().ident;
161 let base_error = if let Some(res) = res {
162 BaseError {
163 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
164 fallback_label: format!("not a {expected}"),
165 span,
166 could_be_expr: match res {
167 Res::Def(DefKind::Fn, _) => {
168 // Verify whether this is a fn call or an Fn used as a type.
169 self.r
170 .session
171 .source_map()
172 .span_to_snippet(span)
173 .map(|snippet| snippet.ends_with(')'))
174 .unwrap_or(false)
175 }
176 Res::Def(
177 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
178 _,
179 )
180 | Res::SelfCtor(_)
181 | Res::PrimTy(_)
182 | Res::Local(_) => true,
183 _ => false,
184 },
185 suggestion: None,
186 }
187 } else {
188 let item_span = path.last().unwrap().ident.span;
189 let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
190 debug!(?self.diagnostic_metadata.current_impl_items);
191 debug!(?self.diagnostic_metadata.current_function);
192 let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
193 && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
194 && self.current_trait_ref.is_none()
195 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
196 && let Some(item) = items.iter().find(|i| {
197 if let AssocItemKind::Fn(fn_) = &i.kind
198 && !fn_.sig.decl.has_self()
199 && i.ident.name == item_str.name
200 {
201 debug!(?item_str.name);
202 debug!(?fn_.sig.decl.inputs);
203 return true
204 }
205 false
206 })
207 {
208 Some((
209 item_span,
210 "consider using the associated function",
211 format!("Self::{}", item.ident)
212 ))
213 } else {
214 None
215 };
216 (String::new(), "this scope".to_string(), suggestion)
217 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
218 if self.r.session.edition() > Edition::Edition2015 {
219 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
220 // which overrides all other expectations of item type
221 expected = "crate";
222 (String::new(), "the list of imported crates".to_string(), None)
223 } else {
224 (String::new(), "the crate root".to_string(), None)
225 }
226 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
227 (String::new(), "the crate root".to_string(), None)
228 } else {
229 let mod_path = &path[..path.len() - 1];
230 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
231 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
232 _ => None,
233 }
234 .map_or_else(String::new, |res| format!("{} ", res.descr()));
235 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
236 };
237 BaseError {
238 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
239 fallback_label: if path_str == "async" && expected.starts_with("struct") {
240 "`async` blocks are only allowed in Rust 2018 or later".to_string()
241 } else {
242 format!("not found in {mod_str}")
243 },
244 span: item_span,
245 could_be_expr: false,
246 suggestion,
247 }
248 };
249
250 let code = source.error_code(res.is_some());
251 let mut err =
252 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
253
254 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
255
256 if let Some(sugg) = base_error.suggestion {
257 err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
258 }
259
260 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
261 err.multipart_suggestion(
262 "you might have meant to write a `struct` literal",
263 vec![
264 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
265 (span.shrink_to_hi(), "}".to_string()),
266 ],
267 Applicability::HasPlaceholders,
268 );
269 }
270 match (source, self.diagnostic_metadata.in_if_condition) {
271 (
272 PathSource::Expr(_),
273 Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }),
274 ) => {
275 // Icky heuristic so we don't suggest:
276 // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
277 // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
278 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
279 err.span_suggestion_verbose(
280 expr_span.shrink_to_lo(),
281 "you might have meant to use pattern matching",
282 "let ",
283 Applicability::MaybeIncorrect,
284 );
285 }
286 }
287 _ => {}
288 }
289
290 let is_assoc_fn = self.self_type_is_available();
291 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
292 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
293 err.span_suggestion_short(
294 span,
295 "you might have meant to use `self` here instead",
296 "self",
297 Applicability::MaybeIncorrect,
298 );
299 if !self.self_value_is_available(path[0].ident.span) {
300 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
301 &self.diagnostic_metadata.current_function
302 {
303 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
304 (param.span.shrink_to_lo(), "&self, ")
305 } else {
306 (
307 self.r
308 .session
309 .source_map()
310 .span_through_char(*fn_span, '(')
311 .shrink_to_hi(),
312 "&self",
313 )
314 };
315 err.span_suggestion_verbose(
316 span,
317 "if you meant to use `self`, you are also missing a `self` receiver \
318 argument",
319 sugg,
320 Applicability::MaybeIncorrect,
321 );
322 }
323 }
324 }
325
326 self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
327
328 // Emit special messages for unresolved `Self` and `self`.
329 if is_self_type(path, ns) {
330 err.code(rustc_errors::error_code!(E0411));
331 err.span_label(
332 span,
333 "`Self` is only available in impls, traits, and type definitions".to_string(),
334 );
335 if let Some(item_kind) = self.diagnostic_metadata.current_item {
336 err.span_label(
337 item_kind.ident.span,
338 format!(
339 "`Self` not allowed in {} {}",
340 item_kind.kind.article(),
341 item_kind.kind.descr()
342 ),
343 );
344 }
345 return (err, Vec::new());
346 }
347 if is_self_value(path, ns) {
348 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
349
350 err.code(rustc_errors::error_code!(E0424));
351 err.span_label(span, match source {
352 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
353 .to_string(),
354 _ => "`self` value is a keyword only available in methods with a `self` parameter"
355 .to_string(),
356 });
357 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
358 // The current function has a `self' parameter, but we were unable to resolve
359 // a reference to `self`. This can only happen if the `self` identifier we
360 // are resolving came from a different hygiene context.
361 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
362 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
363 } else {
364 let doesnt = if is_assoc_fn {
365 let (span, sugg) = fn_kind
366 .decl()
367 .inputs
368 .get(0)
369 .map(|p| (p.span.shrink_to_lo(), "&self, "))
370 .unwrap_or_else(|| {
371 // Try to look for the "(" after the function name, if possible.
372 // This avoids placing the suggestion into the visibility specifier.
373 let span = fn_kind
374 .ident()
375 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
376 (
377 self.r
378 .session
379 .source_map()
380 .span_through_char(span, '(')
381 .shrink_to_hi(),
382 "&self",
383 )
384 });
385 err.span_suggestion_verbose(
386 span,
387 "add a `self` receiver parameter to make the associated `fn` a method",
388 sugg,
389 Applicability::MaybeIncorrect,
390 );
391 "doesn't"
392 } else {
393 "can't"
394 };
395 if let Some(ident) = fn_kind.ident() {
396 err.span_label(
397 ident.span,
398 &format!("this function {} have a `self` parameter", doesnt),
399 );
400 }
401 }
402 } else if let Some(item_kind) = self.diagnostic_metadata.current_item {
403 err.span_label(
404 item_kind.ident.span,
405 format!(
406 "`self` not allowed in {} {}",
407 item_kind.kind.article(),
408 item_kind.kind.descr()
409 ),
410 );
411 }
412 return (err, Vec::new());
413 }
414
415 // Try to lookup name in more relaxed fashion for better error reporting.
416 let ident = path.last().unwrap().ident;
417 let mut candidates = self
418 .r
419 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
420 .into_iter()
421 .filter(|ImportSuggestion { did, .. }| {
422 match (did, res.and_then(|res| res.opt_def_id())) {
423 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
424 _ => true,
425 }
426 })
427 .collect::<Vec<_>>();
428 let crate_def_id = CRATE_DEF_ID.to_def_id();
429 // Try to filter out intrinsics candidates, as long as we have
430 // some other candidates to suggest.
431 let intrinsic_candidates: Vec<_> = candidates
432 .drain_filter(|sugg| {
433 let path = path_names_to_string(&sugg.path);
434 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
435 })
436 .collect();
437 if candidates.is_empty() {
438 // Put them back if we have no more candidates to suggest...
439 candidates.extend(intrinsic_candidates);
440 }
441 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
442 let mut enum_candidates: Vec<_> = self
443 .r
444 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
445 .into_iter()
446 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
447 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
448 .collect();
449 if !enum_candidates.is_empty() {
450 if let (PathSource::Type, Some(span)) =
451 (source, self.diagnostic_metadata.current_type_ascription.last())
452 {
453 if self
454 .r
455 .session
456 .parse_sess
457 .type_ascription_path_suggestions
458 .borrow()
459 .contains(span)
460 {
461 // Already reported this issue on the lhs of the type ascription.
462 err.delay_as_bug();
463 return (err, candidates);
464 }
465 }
466
467 enum_candidates.sort();
468
469 // Contextualize for E0412 "cannot find type", but don't belabor the point
470 // (that it's a variant) for E0573 "expected type, found variant".
471 let preamble = if res.is_none() {
472 let others = match enum_candidates.len() {
473 1 => String::new(),
474 2 => " and 1 other".to_owned(),
475 n => format!(" and {} others", n),
476 };
477 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
478 } else {
479 String::new()
480 };
481 let msg = format!("{}try using the variant's enum", preamble);
482
483 err.span_suggestions(
484 span,
485 &msg,
486 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
487 Applicability::MachineApplicable,
488 );
489 }
490 }
491 // Try Levenshtein algorithm.
492 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
493 if path.len() == 1 && self.self_type_is_available() {
494 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
495 let self_is_available = self.self_value_is_available(path[0].ident.span);
496 match candidate {
497 AssocSuggestion::Field => {
498 if self_is_available {
499 err.span_suggestion(
500 span,
501 "you might have meant to use the available field",
502 format!("self.{path_str}"),
503 Applicability::MachineApplicable,
504 );
505 } else {
506 err.span_label(span, "a field by this name exists in `Self`");
507 }
508 }
509 AssocSuggestion::MethodWithSelf if self_is_available => {
510 err.span_suggestion(
511 span,
512 "you might have meant to call the method",
513 format!("self.{path_str}"),
514 Applicability::MachineApplicable,
515 );
516 }
517 AssocSuggestion::MethodWithSelf
518 | AssocSuggestion::AssocFn
519 | AssocSuggestion::AssocConst
520 | AssocSuggestion::AssocType => {
521 err.span_suggestion(
522 span,
523 &format!("you might have meant to {}", candidate.action()),
524 format!("Self::{path_str}"),
525 Applicability::MachineApplicable,
526 );
527 }
528 }
529 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
530 return (err, candidates);
531 }
532
533 // If the first argument in call is `self` suggest calling a method.
534 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
535 let mut args_snippet = String::new();
536 if let Some(args_span) = args_span {
537 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
538 args_snippet = snippet;
539 }
540 }
541
542 err.span_suggestion(
543 call_span,
544 &format!("try calling `{ident}` as a method"),
545 format!("self.{path_str}({args_snippet})"),
546 Applicability::MachineApplicable,
547 );
548 return (err, candidates);
549 }
550 }
551
552 // Try context-dependent help if relaxed lookup didn't work.
553 if let Some(res) = res {
554 if self.smart_resolve_context_dependent_help(
555 &mut err,
556 span,
557 source,
558 res,
559 &path_str,
560 &base_error.fallback_label,
561 ) {
562 // We do this to avoid losing a secondary span when we override the main error span.
563 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
564 return (err, candidates);
565 }
566 }
567
568 let is_macro =
569 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
570 if !self.type_ascription_suggestion(&mut err, base_error.span) {
571 let mut fallback = false;
572 if let (
573 PathSource::Trait(AliasPossibility::Maybe),
574 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
575 false,
576 ) = (source, res, is_macro)
577 {
578 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
579 fallback = true;
580 let spans: Vec<Span> = bounds
581 .iter()
582 .map(|bound| bound.span())
583 .filter(|&sp| sp != base_error.span)
584 .collect();
585
586 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
587 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
588 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
589 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
590 let last_bound_span = spans.last().cloned().unwrap();
591 let mut multi_span: MultiSpan = spans.clone().into();
592 for sp in spans {
593 let msg = if sp == last_bound_span {
594 format!(
595 "...because of {these} bound{s}",
596 these = pluralize!("this", bounds.len() - 1),
597 s = pluralize!(bounds.len() - 1),
598 )
599 } else {
600 String::new()
601 };
602 multi_span.push_span_label(sp, msg);
603 }
604 multi_span.push_span_label(
605 base_error.span,
606 "expected this type to be a trait...".to_string(),
607 );
608 err.span_help(
609 multi_span,
610 "`+` is used to constrain a \"trait object\" type with lifetimes or \
611 auto-traits; structs and enums can't be bound in that way",
612 );
613 if bounds.iter().all(|bound| match bound {
614 ast::GenericBound::Outlives(_) => true,
615 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
616 }) {
617 let mut sugg = vec![];
618 if base_error.span != start_span {
619 sugg.push((start_span.until(base_error.span), String::new()));
620 }
621 if base_error.span != end_span {
622 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
623 }
624
625 err.multipart_suggestion(
626 "if you meant to use a type and not a trait here, remove the bounds",
627 sugg,
628 Applicability::MaybeIncorrect,
629 );
630 }
631 }
632 }
633
634 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
635
636 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
637 fallback = true;
638 match self.diagnostic_metadata.current_let_binding {
639 Some((pat_sp, Some(ty_sp), None))
640 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
641 {
642 err.span_suggestion_short(
643 pat_sp.between(ty_sp),
644 "use `=` if you meant to assign",
645 " = ",
646 Applicability::MaybeIncorrect,
647 );
648 }
649 _ => {}
650 }
651
652 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
653 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
654 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
655 }
656 if fallback {
657 // Fallback label.
658 err.span_label(base_error.span, base_error.fallback_label);
659 }
660 }
661 if let Some(err_code) = &err.code {
662 if err_code == &rustc_errors::error_code!(E0425) {
663 for label_rib in &self.label_ribs {
664 for (label_ident, node_id) in &label_rib.bindings {
665 if format!("'{}", ident) == label_ident.to_string() {
666 err.span_label(label_ident.span, "a label with a similar name exists");
667 if let PathSource::Expr(Some(Expr {
668 kind: ExprKind::Break(None, Some(_)),
669 ..
670 })) = source
671 {
672 err.span_suggestion(
673 span,
674 "use the similarly named label",
675 label_ident.name,
676 Applicability::MaybeIncorrect,
677 );
678 // Do not lint against unused label when we suggest them.
679 self.diagnostic_metadata.unused_labels.remove(node_id);
680 }
681 }
682 }
683 }
684 } else if err_code == &rustc_errors::error_code!(E0412) {
685 if let Some(correct) = Self::likely_rust_type(path) {
686 err.span_suggestion(
687 span,
688 "perhaps you intended to use this type",
689 correct,
690 Applicability::MaybeIncorrect,
691 );
692 }
693 }
694 }
695
696 (err, candidates)
697 }
698
699 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
700 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
701 let TyKind::Path(_, path) = &ty.kind else { return; };
702 for segment in &path.segments {
703 let Some(params) = &segment.args else { continue; };
704 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
705 for param in &params.args {
706 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
707 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
708 continue;
709 };
710 for bound in bounds {
711 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
712 = bound else
713 {
714 continue;
715 };
716 if base_span == trait_ref.span {
717 err.span_suggestion_verbose(
718 constraint.ident.span.between(trait_ref.span),
719 "you might have meant to write a path instead of an associated type bound",
720 "::",
721 Applicability::MachineApplicable,
722 );
723 }
724 }
725 }
726 }
727 }
728
729 fn suggest_swapping_misplaced_self_ty_and_trait(
730 &mut self,
731 err: &mut Diagnostic,
732 source: PathSource<'_>,
733 res: Option<Res>,
734 span: Span,
735 ) {
736 if let Some((trait_ref, self_ty)) =
737 self.diagnostic_metadata.currently_processing_impl_trait.clone()
738 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
739 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
740 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
741 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
742 && trait_ref.path.span == span
743 && let PathSource::Trait(_) = source
744 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
745 && let Ok(self_ty_str) =
746 self.r.session.source_map().span_to_snippet(self_ty.span)
747 && let Ok(trait_ref_str) =
748 self.r.session.source_map().span_to_snippet(trait_ref.path.span)
749 {
750 err.multipart_suggestion(
751 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
752 vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
753 Applicability::MaybeIncorrect,
754 );
755 }
756 }
757
758 fn get_single_associated_item(
759 &mut self,
760 path: &[Segment],
761 source: &PathSource<'_>,
762 filter_fn: &impl Fn(Res) -> bool,
763 ) -> Option<TypoSuggestion> {
764 if let crate::PathSource::TraitItem(_) = source {
765 let mod_path = &path[..path.len() - 1];
766 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
767 self.resolve_path(mod_path, None, None)
768 {
769 let resolutions = self.r.resolutions(module).borrow();
770 let targets: Vec<_> =
771 resolutions
772 .iter()
773 .filter_map(|(key, resolution)| {
774 resolution.borrow().binding.map(|binding| binding.res()).and_then(
775 |res| if filter_fn(res) { Some((key, res)) } else { None },
776 )
777 })
778 .collect();
779 if targets.len() == 1 {
780 let target = targets[0];
781 return Some(TypoSuggestion::single_item_from_res(
782 target.0.ident.name,
783 target.1,
784 ));
785 }
786 }
787 }
788 None
789 }
790
791 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
792 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
793 // Detect that we are actually in a `where` predicate.
794 let (bounded_ty, bounds, where_span) =
795 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
796 bounded_ty,
797 bound_generic_params,
798 bounds,
799 span,
800 })) = self.diagnostic_metadata.current_where_predicate
801 {
802 if !bound_generic_params.is_empty() {
803 return false;
804 }
805 (bounded_ty, bounds, span)
806 } else {
807 return false;
808 };
809
810 // Confirm that the target is an associated type.
811 let (ty, position, path) = if let ast::TyKind::Path(
812 Some(ast::QSelf { ty, position, .. }),
813 path,
814 ) = &bounded_ty.kind
815 {
816 // use this to verify that ident is a type param.
817 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
818 return false;
819 };
820 if !(matches!(
821 partial_res.base_res(),
822 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
823 ) && partial_res.unresolved_segments() == 0)
824 {
825 return false;
826 }
827 (ty, position, path)
828 } else {
829 return false;
830 };
831
832 let peeled_ty = ty.peel_refs();
833 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
834 // Confirm that the `SelfTy` is a type parameter.
835 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
836 return false;
837 };
838 if !(matches!(
839 partial_res.base_res(),
840 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
841 ) && partial_res.unresolved_segments() == 0)
842 {
843 return false;
844 }
845 if let (
846 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
847 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
848 ) = (&type_param_path.segments[..], &bounds[..])
849 {
850 if let [ast::PathSegment { ident, args: None, .. }] =
851 &poly_trait_ref.trait_ref.path.segments[..]
852 {
853 if ident.span == span {
854 err.span_suggestion_verbose(
855 *where_span,
856 &format!("constrain the associated type to `{}`", ident),
857 format!(
858 "{}: {}<{} = {}>",
859 self.r
860 .session
861 .source_map()
862 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
863 .unwrap_or_else(|_| constrain_ident.to_string()),
864 path.segments[..*position]
865 .iter()
866 .map(|segment| path_segment_to_string(segment))
867 .collect::<Vec<_>>()
868 .join("::"),
869 path.segments[*position..]
870 .iter()
871 .map(|segment| path_segment_to_string(segment))
872 .collect::<Vec<_>>()
873 .join("::"),
874 ident,
875 ),
876 Applicability::MaybeIncorrect,
877 );
878 }
879 return true;
880 }
881 }
882 }
883 false
884 }
885
886 /// Check if the source is call expression and the first argument is `self`. If true,
887 /// return the span of whole call and the span for all arguments expect the first one (`self`).
888 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
889 let mut has_self_arg = None;
890 if let PathSource::Expr(Some(parent)) = source {
891 match &parent.kind {
892 ExprKind::Call(_, args) if !args.is_empty() => {
893 let mut expr_kind = &args[0].kind;
894 loop {
895 match expr_kind {
896 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
897 if arg_name.segments[0].ident.name == kw::SelfLower {
898 let call_span = parent.span;
899 let tail_args_span = if args.len() > 1 {
900 Some(Span::new(
901 args[1].span.lo(),
902 args.last().unwrap().span.hi(),
903 call_span.ctxt(),
904 None,
905 ))
906 } else {
907 None
908 };
909 has_self_arg = Some((call_span, tail_args_span));
910 }
911 break;
912 }
913 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
914 _ => break,
915 }
916 }
917 }
918 _ => (),
919 }
920 };
921 has_self_arg
922 }
923
924 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
925 // HACK(estebank): find a better way to figure out that this was a
926 // parser issue where a struct literal is being used on an expression
927 // where a brace being opened means a block is being started. Look
928 // ahead for the next text to see if `span` is followed by a `{`.
929 let sm = self.r.session.source_map();
930 let mut sp = span;
931 loop {
932 sp = sm.next_point(sp);
933 match sm.span_to_snippet(sp) {
934 Ok(ref snippet) => {
935 if snippet.chars().any(|c| !c.is_whitespace()) {
936 break;
937 }
938 }
939 _ => break,
940 }
941 }
942 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
943 // In case this could be a struct literal that needs to be surrounded
944 // by parentheses, find the appropriate span.
945 let mut i = 0;
946 let mut closing_brace = None;
947 loop {
948 sp = sm.next_point(sp);
949 match sm.span_to_snippet(sp) {
950 Ok(ref snippet) => {
951 if snippet == "}" {
952 closing_brace = Some(span.to(sp));
953 break;
954 }
955 }
956 _ => break,
957 }
958 i += 1;
959 // The bigger the span, the more likely we're incorrect --
960 // bound it to 100 chars long.
961 if i > 100 {
962 break;
963 }
964 }
965 (followed_by_brace, closing_brace)
966 }
967
968 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
969 /// function.
970 /// Returns `true` if able to provide context-dependent help.
971 fn smart_resolve_context_dependent_help(
972 &mut self,
973 err: &mut Diagnostic,
974 span: Span,
975 source: PathSource<'_>,
976 res: Res,
977 path_str: &str,
978 fallback_label: &str,
979 ) -> bool {
980 let ns = source.namespace();
981 let is_expected = &|res| source.is_expected(res);
982
983 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
984 ExprKind::Field(_, ident) => {
985 err.span_suggestion(
986 expr.span,
987 "use the path separator to refer to an item",
988 format!("{}::{}", path_str, ident),
989 Applicability::MaybeIncorrect,
990 );
991 true
992 }
993 ExprKind::MethodCall(ref segment, ..) => {
994 let span = expr.span.with_hi(segment.ident.span.hi());
995 err.span_suggestion(
996 span,
997 "use the path separator to refer to an item",
998 format!("{}::{}", path_str, segment.ident),
999 Applicability::MaybeIncorrect,
1000 );
1001 true
1002 }
1003 _ => false,
1004 };
1005
1006 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
1007 match source {
1008 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1009 | PathSource::TupleStruct(span, _) => {
1010 // We want the main underline to cover the suggested code as well for
1011 // cleaner output.
1012 err.set_span(*span);
1013 *span
1014 }
1015 _ => span,
1016 }
1017 };
1018
1019 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
1020 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
1021
1022 match source {
1023 PathSource::Expr(Some(
1024 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1025 )) if path_sep(err, &parent) => {}
1026 PathSource::Expr(
1027 None
1028 | Some(Expr {
1029 kind:
1030 ExprKind::Path(..)
1031 | ExprKind::Binary(..)
1032 | ExprKind::Unary(..)
1033 | ExprKind::If(..)
1034 | ExprKind::While(..)
1035 | ExprKind::ForLoop(..)
1036 | ExprKind::Match(..),
1037 ..
1038 }),
1039 ) if followed_by_brace => {
1040 if let Some(sp) = closing_brace {
1041 err.span_label(span, fallback_label);
1042 err.multipart_suggestion(
1043 "surround the struct literal with parentheses",
1044 vec![
1045 (sp.shrink_to_lo(), "(".to_string()),
1046 (sp.shrink_to_hi(), ")".to_string()),
1047 ],
1048 Applicability::MaybeIncorrect,
1049 );
1050 } else {
1051 err.span_label(
1052 span, // Note the parentheses surrounding the suggestion below
1053 format!(
1054 "you might want to surround a struct literal with parentheses: \
1055 `({} {{ /* fields */ }})`?",
1056 path_str
1057 ),
1058 );
1059 }
1060 }
1061 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1062 let span = find_span(&source, err);
1063 if let Some(span) = self.def_span(def_id) {
1064 err.span_label(span, &format!("`{}` defined here", path_str));
1065 }
1066 let (tail, descr, applicability) = match source {
1067 PathSource::Pat | PathSource::TupleStruct(..) => {
1068 ("", "pattern", Applicability::MachineApplicable)
1069 }
1070 _ => (": val", "literal", Applicability::HasPlaceholders),
1071 };
1072 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1073 Some(fields) => (
1074 fields
1075 .iter()
1076 .map(|f| format!("{}{}", f.node, tail))
1077 .collect::<Vec<String>>()
1078 .join(", "),
1079 applicability,
1080 ),
1081 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1082 };
1083 let pad = match self.r.field_names.get(&def_id) {
1084 Some(fields) if fields.is_empty() => "",
1085 _ => " ",
1086 };
1087 err.span_suggestion(
1088 span,
1089 &format!("use struct {} syntax instead", descr),
1090 format!("{path_str} {{{pad}{fields}{pad}}}"),
1091 applicability,
1092 );
1093 }
1094 _ => {
1095 err.span_label(span, fallback_label);
1096 }
1097 }
1098 };
1099
1100 match (res, source) {
1101 (
1102 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1103 PathSource::Expr(Some(Expr {
1104 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1105 }))
1106 | PathSource::Struct,
1107 ) => {
1108 err.span_label(span, fallback_label);
1109 err.span_suggestion_verbose(
1110 span.shrink_to_hi(),
1111 "use `!` to invoke the macro",
1112 "!",
1113 Applicability::MaybeIncorrect,
1114 );
1115 if path_str == "try" && span.rust_2015() {
1116 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1117 }
1118 }
1119 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1120 err.span_label(span, fallback_label);
1121 }
1122 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1123 err.span_label(span, "type aliases cannot be used as traits");
1124 if self.r.session.is_nightly_build() {
1125 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1126 `type` alias";
1127 if let Some(span) = self.def_span(def_id) {
1128 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1129 // The span contains a type alias so we should be able to
1130 // replace `type` with `trait`.
1131 let snip = snip.replacen("type", "trait", 1);
1132 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1133 } else {
1134 err.span_help(span, msg);
1135 }
1136 } else {
1137 err.help(msg);
1138 }
1139 }
1140 }
1141 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1142 if !path_sep(err, &parent) {
1143 return false;
1144 }
1145 }
1146 (
1147 Res::Def(DefKind::Enum, def_id),
1148 PathSource::TupleStruct(..) | PathSource::Expr(..),
1149 ) => {
1150 if self
1151 .diagnostic_metadata
1152 .current_type_ascription
1153 .last()
1154 .map(|sp| {
1155 self.r
1156 .session
1157 .parse_sess
1158 .type_ascription_path_suggestions
1159 .borrow()
1160 .contains(&sp)
1161 })
1162 .unwrap_or(false)
1163 {
1164 err.downgrade_to_delayed_bug();
1165 // We already suggested changing `:` into `::` during parsing.
1166 return false;
1167 }
1168
1169 self.suggest_using_enum_variant(err, source, def_id, span);
1170 }
1171 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1172 let (ctor_def, ctor_vis, fields) =
1173 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1174 if let PathSource::Expr(Some(parent)) = source {
1175 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1176 bad_struct_syntax_suggestion(def_id);
1177 return true;
1178 }
1179 }
1180 struct_ctor
1181 } else {
1182 bad_struct_syntax_suggestion(def_id);
1183 return true;
1184 };
1185
1186 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1187 if !is_expected(ctor_def) || is_accessible {
1188 return true;
1189 }
1190
1191 let field_spans = match source {
1192 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1193 PathSource::TupleStruct(_, pattern_spans) => {
1194 err.set_primary_message(
1195 "cannot match against a tuple struct which contains private fields",
1196 );
1197
1198 // Use spans of the tuple struct pattern.
1199 Some(Vec::from(pattern_spans))
1200 }
1201 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1202 _ if source.is_call() => {
1203 err.set_primary_message(
1204 "cannot initialize a tuple struct which contains private fields",
1205 );
1206
1207 // Use spans of the tuple struct definition.
1208 self.r
1209 .field_names
1210 .get(&def_id)
1211 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1212 }
1213 _ => None,
1214 };
1215
1216 if let Some(spans) =
1217 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1218 {
1219 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1220 .filter(|(vis, _)| {
1221 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1222 })
1223 .map(|(_, span)| *span)
1224 .collect();
1225
1226 if non_visible_spans.len() > 0 {
1227 let mut m: MultiSpan = non_visible_spans.clone().into();
1228 non_visible_spans
1229 .into_iter()
1230 .for_each(|s| m.push_span_label(s, "private field".to_string()));
1231 err.span_note(m, "constructor is not visible here due to private fields");
1232 }
1233
1234 return true;
1235 }
1236
1237 err.span_label(
1238 span,
1239 "constructor is not visible here due to private fields".to_string(),
1240 );
1241 }
1242 (
1243 Res::Def(
1244 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1245 def_id,
1246 ),
1247 _,
1248 ) if ns == ValueNS => {
1249 bad_struct_syntax_suggestion(def_id);
1250 }
1251 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1252 match source {
1253 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1254 let span = find_span(&source, err);
1255 if let Some(span) = self.def_span(def_id) {
1256 err.span_label(span, &format!("`{}` defined here", path_str));
1257 }
1258 err.span_suggestion(
1259 span,
1260 "use this syntax instead",
1261 path_str,
1262 Applicability::MaybeIncorrect,
1263 );
1264 }
1265 _ => return false,
1266 }
1267 }
1268 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1269 if let Some(span) = self.def_span(def_id) {
1270 err.span_label(span, &format!("`{}` defined here", path_str));
1271 }
1272 let fields = self.r.field_names.get(&def_id).map_or_else(
1273 || "/* fields */".to_string(),
1274 |fields| vec!["_"; fields.len()].join(", "),
1275 );
1276 err.span_suggestion(
1277 span,
1278 "use the tuple variant pattern syntax instead",
1279 format!("{}({})", path_str, fields),
1280 Applicability::HasPlaceholders,
1281 );
1282 }
1283 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1284 err.span_label(span, fallback_label);
1285 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1286 }
1287 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1288 err.note("can't use a type alias as a constructor");
1289 }
1290 _ => return false,
1291 }
1292 true
1293 }
1294
1295 /// Given the target `ident` and `kind`, search for the similarly named associated item
1296 /// in `self.current_trait_ref`.
1297 pub(crate) fn find_similarly_named_assoc_item(
1298 &mut self,
1299 ident: Symbol,
1300 kind: &AssocItemKind,
1301 ) -> Option<Symbol> {
1302 let (module, _) = self.current_trait_ref.as_ref()?;
1303 if ident == kw::Underscore {
1304 // We do nothing for `_`.
1305 return None;
1306 }
1307
1308 let resolutions = self.r.resolutions(module);
1309 let targets = resolutions
1310 .borrow()
1311 .iter()
1312 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1313 .filter(|(_, res)| match (kind, res) {
1314 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1315 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1316 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1317 _ => false,
1318 })
1319 .map(|(key, _)| key.ident.name)
1320 .collect::<Vec<_>>();
1321
1322 find_best_match_for_name(&targets, ident, None)
1323 }
1324
1325 fn lookup_assoc_candidate<FilterFn>(
1326 &mut self,
1327 ident: Ident,
1328 ns: Namespace,
1329 filter_fn: FilterFn,
1330 ) -> Option<AssocSuggestion>
1331 where
1332 FilterFn: Fn(Res) -> bool,
1333 {
1334 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1335 match t.kind {
1336 TyKind::Path(None, _) => Some(t.id),
1337 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1338 // This doesn't handle the remaining `Ty` variants as they are not
1339 // that commonly the self_type, it might be interesting to provide
1340 // support for those in future.
1341 _ => None,
1342 }
1343 }
1344
1345 // Fields are generally expected in the same contexts as locals.
1346 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1347 if let Some(node_id) =
1348 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1349 {
1350 // Look for a field with the same name in the current self_type.
1351 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1352 match resolution.base_res() {
1353 Res::Def(DefKind::Struct | DefKind::Union, did)
1354 if resolution.unresolved_segments() == 0 =>
1355 {
1356 if let Some(field_names) = self.r.field_names.get(&did) {
1357 if field_names
1358 .iter()
1359 .any(|&field_name| ident.name == field_name.node)
1360 {
1361 return Some(AssocSuggestion::Field);
1362 }
1363 }
1364 }
1365 _ => {}
1366 }
1367 }
1368 }
1369 }
1370
1371 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1372 for assoc_item in items {
1373 if assoc_item.ident == ident {
1374 return Some(match &assoc_item.kind {
1375 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1376 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1377 AssocSuggestion::MethodWithSelf
1378 }
1379 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1380 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1381 ast::AssocItemKind::MacCall(_) => continue,
1382 });
1383 }
1384 }
1385 }
1386
1387 // Look for associated items in the current trait.
1388 if let Some((module, _)) = self.current_trait_ref {
1389 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1390 ModuleOrUniformRoot::Module(module),
1391 ident,
1392 ns,
1393 &self.parent_scope,
1394 ) {
1395 let res = binding.res();
1396 if filter_fn(res) {
1397 if self.r.has_self.contains(&res.def_id()) {
1398 return Some(AssocSuggestion::MethodWithSelf);
1399 } else {
1400 match res {
1401 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1402 Res::Def(DefKind::AssocConst, _) => {
1403 return Some(AssocSuggestion::AssocConst);
1404 }
1405 Res::Def(DefKind::AssocTy, _) => {
1406 return Some(AssocSuggestion::AssocType);
1407 }
1408 _ => {}
1409 }
1410 }
1411 }
1412 }
1413 }
1414
1415 None
1416 }
1417
1418 fn lookup_typo_candidate(
1419 &mut self,
1420 path: &[Segment],
1421 ns: Namespace,
1422 filter_fn: &impl Fn(Res) -> bool,
1423 ) -> Option<TypoSuggestion> {
1424 let mut names = Vec::new();
1425 if path.len() == 1 {
1426 // Search in lexical scope.
1427 // Walk backwards up the ribs in scope and collect candidates.
1428 for rib in self.ribs[ns].iter().rev() {
1429 // Locals and type parameters
1430 for (ident, &res) in &rib.bindings {
1431 if filter_fn(res) {
1432 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1433 }
1434 }
1435 // Items in scope
1436 if let RibKind::ModuleRibKind(module) = rib.kind {
1437 // Items from this module
1438 self.r.add_module_candidates(module, &mut names, &filter_fn);
1439
1440 if let ModuleKind::Block(..) = module.kind {
1441 // We can see through blocks
1442 } else {
1443 // Items from the prelude
1444 if !module.no_implicit_prelude {
1445 let extern_prelude = self.r.extern_prelude.clone();
1446 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1447 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1448 |crate_id| {
1449 let crate_mod =
1450 Res::Def(DefKind::Mod, crate_id.as_def_id());
1451
1452 if filter_fn(crate_mod) {
1453 Some(TypoSuggestion::typo_from_res(
1454 ident.name, crate_mod,
1455 ))
1456 } else {
1457 None
1458 }
1459 },
1460 )
1461 }));
1462
1463 if let Some(prelude) = self.r.prelude {
1464 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1465 }
1466 }
1467 break;
1468 }
1469 }
1470 }
1471 // Add primitive types to the mix
1472 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1473 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1474 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1475 }))
1476 }
1477 } else {
1478 // Search in module.
1479 let mod_path = &path[..path.len() - 1];
1480 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1481 self.resolve_path(mod_path, Some(TypeNS), None)
1482 {
1483 self.r.add_module_candidates(module, &mut names, &filter_fn);
1484 }
1485 }
1486
1487 let name = path[path.len() - 1].ident.name;
1488 // Make sure error reporting is deterministic.
1489 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1490
1491 match find_best_match_for_name(
1492 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1493 name,
1494 None,
1495 ) {
1496 Some(found) if found != name => {
1497 names.into_iter().find(|suggestion| suggestion.candidate == found)
1498 }
1499 _ => None,
1500 }
1501 }
1502
1503 // Returns the name of the Rust type approximately corresponding to
1504 // a type name in another programming language.
1505 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1506 let name = path[path.len() - 1].ident.as_str();
1507 // Common Java types
1508 Some(match name {
1509 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1510 "short" => sym::i16,
1511 "boolean" => sym::bool,
1512 "int" => sym::i32,
1513 "long" => sym::i64,
1514 "float" => sym::f32,
1515 "double" => sym::f64,
1516 _ => return None,
1517 })
1518 }
1519
1520 /// Only used in a specific case of type ascription suggestions
1521 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1522 let sm = self.r.session.source_map();
1523 start.to(sm.next_point(start))
1524 }
1525
1526 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1527 let sm = self.r.session.source_map();
1528 let base_snippet = sm.span_to_snippet(base_span);
1529 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1530 if let Ok(snippet) = sm.span_to_snippet(sp) {
1531 let len = snippet.trim_end().len() as u32;
1532 if snippet.trim() == ":" {
1533 let colon_sp =
1534 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1535 let mut show_label = true;
1536 if sm.is_multiline(sp) {
1537 err.span_suggestion_short(
1538 colon_sp,
1539 "maybe you meant to write `;` here",
1540 ";",
1541 Applicability::MaybeIncorrect,
1542 );
1543 } else {
1544 let after_colon_sp =
1545 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1546 if snippet.len() == 1 {
1547 // `foo:bar`
1548 err.span_suggestion(
1549 colon_sp,
1550 "maybe you meant to write a path separator here",
1551 "::",
1552 Applicability::MaybeIncorrect,
1553 );
1554 show_label = false;
1555 if !self
1556 .r
1557 .session
1558 .parse_sess
1559 .type_ascription_path_suggestions
1560 .borrow_mut()
1561 .insert(colon_sp)
1562 {
1563 err.downgrade_to_delayed_bug();
1564 }
1565 }
1566 if let Ok(base_snippet) = base_snippet {
1567 let mut sp = after_colon_sp;
1568 for _ in 0..100 {
1569 // Try to find an assignment
1570 sp = sm.next_point(sp);
1571 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1572 match snippet {
1573 Ok(ref x) if x.as_str() == "=" => {
1574 err.span_suggestion(
1575 base_span,
1576 "maybe you meant to write an assignment here",
1577 format!("let {}", base_snippet),
1578 Applicability::MaybeIncorrect,
1579 );
1580 show_label = false;
1581 break;
1582 }
1583 Ok(ref x) if x.as_str() == "\n" => break,
1584 Err(_) => break,
1585 Ok(_) => {}
1586 }
1587 }
1588 }
1589 }
1590 if show_label {
1591 err.span_label(
1592 base_span,
1593 "expecting a type here because of type ascription",
1594 );
1595 }
1596 return show_label;
1597 }
1598 }
1599 }
1600 false
1601 }
1602
1603 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1604 let mut result = None;
1605 let mut seen_modules = FxHashSet::default();
1606 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1607
1608 while let Some((in_module, path_segments)) = worklist.pop() {
1609 // abort if the module is already found
1610 if result.is_some() {
1611 break;
1612 }
1613
1614 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1615 // abort if the module is already found or if name_binding is private external
1616 if result.is_some() || !name_binding.vis.is_visible_locally() {
1617 return;
1618 }
1619 if let Some(module) = name_binding.module() {
1620 // form the path
1621 let mut path_segments = path_segments.clone();
1622 path_segments.push(ast::PathSegment::from_ident(ident));
1623 let module_def_id = module.def_id();
1624 if module_def_id == def_id {
1625 let path =
1626 Path { span: name_binding.span, segments: path_segments, tokens: None };
1627 result = Some((
1628 module,
1629 ImportSuggestion {
1630 did: Some(def_id),
1631 descr: "module",
1632 path,
1633 accessible: true,
1634 note: None,
1635 },
1636 ));
1637 } else {
1638 // add the module to the lookup
1639 if seen_modules.insert(module_def_id) {
1640 worklist.push((module, path_segments));
1641 }
1642 }
1643 }
1644 });
1645 }
1646
1647 result
1648 }
1649
1650 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1651 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1652 let mut variants = Vec::new();
1653 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1654 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1655 let mut segms = enum_import_suggestion.path.segments.clone();
1656 segms.push(ast::PathSegment::from_ident(ident));
1657 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1658 variants.push((path, def_id, kind));
1659 }
1660 });
1661 variants
1662 })
1663 }
1664
1665 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1666 fn suggest_using_enum_variant(
1667 &mut self,
1668 err: &mut Diagnostic,
1669 source: PathSource<'_>,
1670 def_id: DefId,
1671 span: Span,
1672 ) {
1673 let Some(variants) = self.collect_enum_ctors(def_id) else {
1674 err.note("you might have meant to use one of the enum's variants");
1675 return;
1676 };
1677
1678 let suggest_only_tuple_variants =
1679 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1680 if suggest_only_tuple_variants {
1681 // Suggest only tuple variants regardless of whether they have fields and do not
1682 // suggest path with added parentheses.
1683 let suggestable_variants = variants
1684 .iter()
1685 .filter(|(.., kind)| *kind == CtorKind::Fn)
1686 .map(|(variant, ..)| path_names_to_string(variant))
1687 .collect::<Vec<_>>();
1688
1689 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1690
1691 let source_msg = if source.is_call() {
1692 "to construct"
1693 } else if matches!(source, PathSource::TupleStruct(..)) {
1694 "to match against"
1695 } else {
1696 unreachable!()
1697 };
1698
1699 if !suggestable_variants.is_empty() {
1700 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1701 format!("try {} the enum's variant", source_msg)
1702 } else {
1703 format!("try {} one of the enum's variants", source_msg)
1704 };
1705
1706 err.span_suggestions(
1707 span,
1708 &msg,
1709 suggestable_variants.into_iter(),
1710 Applicability::MaybeIncorrect,
1711 );
1712 }
1713
1714 // If the enum has no tuple variants..
1715 if non_suggestable_variant_count == variants.len() {
1716 err.help(&format!("the enum has no tuple variants {}", source_msg));
1717 }
1718
1719 // If there are also non-tuple variants..
1720 if non_suggestable_variant_count == 1 {
1721 err.help(&format!(
1722 "you might have meant {} the enum's non-tuple variant",
1723 source_msg
1724 ));
1725 } else if non_suggestable_variant_count >= 1 {
1726 err.help(&format!(
1727 "you might have meant {} one of the enum's non-tuple variants",
1728 source_msg
1729 ));
1730 }
1731 } else {
1732 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1733 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1734 match kind {
1735 CtorKind::Const => false,
1736 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1737 _ => true,
1738 }
1739 };
1740
1741 let mut suggestable_variants = variants
1742 .iter()
1743 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1744 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1745 .map(|(variant, kind)| match kind {
1746 CtorKind::Const => variant,
1747 CtorKind::Fn => format!("({}())", variant),
1748 CtorKind::Fictive => format!("({} {{}})", variant),
1749 })
1750 .collect::<Vec<_>>();
1751
1752 if !suggestable_variants.is_empty() {
1753 let msg = if suggestable_variants.len() == 1 {
1754 "you might have meant to use the following enum variant"
1755 } else {
1756 "you might have meant to use one of the following enum variants"
1757 };
1758
1759 err.span_suggestions(
1760 span,
1761 msg,
1762 suggestable_variants.drain(..),
1763 Applicability::MaybeIncorrect,
1764 );
1765 }
1766
1767 let suggestable_variants_with_placeholders = variants
1768 .iter()
1769 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1770 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1771 .filter_map(|(variant, kind)| match kind {
1772 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1773 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1774 _ => None,
1775 })
1776 .collect::<Vec<_>>();
1777
1778 if !suggestable_variants_with_placeholders.is_empty() {
1779 let msg = match (
1780 suggestable_variants.is_empty(),
1781 suggestable_variants_with_placeholders.len(),
1782 ) {
1783 (true, 1) => "the following enum variant is available",
1784 (true, _) => "the following enum variants are available",
1785 (false, 1) => "alternatively, the following enum variant is available",
1786 (false, _) => "alternatively, the following enum variants are also available",
1787 };
1788
1789 err.span_suggestions(
1790 span,
1791 msg,
1792 suggestable_variants_with_placeholders.into_iter(),
1793 Applicability::HasPlaceholders,
1794 );
1795 }
1796 };
1797
1798 if def_id.is_local() {
1799 if let Some(span) = self.def_span(def_id) {
1800 err.span_note(span, "the enum is defined here");
1801 }
1802 }
1803 }
1804
1805 pub(crate) fn report_missing_type_error(
1806 &self,
1807 path: &[Segment],
1808 ) -> Option<(Span, &'static str, String, Applicability)> {
1809 let (ident, span) = match path {
1810 [segment] if !segment.has_generic_args && segment.ident.name != kw::SelfUpper => {
1811 (segment.ident.to_string(), segment.ident.span)
1812 }
1813 _ => return None,
1814 };
1815 let mut iter = ident.chars().map(|c| c.is_uppercase());
1816 let single_uppercase_char =
1817 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1818 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1819 return None;
1820 }
1821 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1822 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1823 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1824 }
1825 (
1826 Some(Item {
1827 kind:
1828 kind @ ItemKind::Fn(..)
1829 | kind @ ItemKind::Enum(..)
1830 | kind @ ItemKind::Struct(..)
1831 | kind @ ItemKind::Union(..),
1832 ..
1833 }),
1834 true, _
1835 )
1836 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1837 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1838 | (Some(Item { kind, .. }), false, _) => {
1839 // Likely missing type parameter.
1840 if let Some(generics) = kind.generics() {
1841 if span.overlaps(generics.span) {
1842 // Avoid the following:
1843 // error[E0405]: cannot find trait `A` in this scope
1844 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1845 // |
1846 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1847 // | ^- help: you might be missing a type parameter: `, A`
1848 // | |
1849 // | not found in this scope
1850 return None;
1851 }
1852 let msg = "you might be missing a type parameter";
1853 let (span, sugg) = if let [.., param] = &generics.params[..] {
1854 let span = if let [.., bound] = &param.bounds[..] {
1855 bound.span()
1856 } else if let GenericParam {
1857 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1858 } = param {
1859 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1860 } else {
1861 param.ident.span
1862 };
1863 (span, format!(", {}", ident))
1864 } else {
1865 (generics.span, format!("<{}>", ident))
1866 };
1867 // Do not suggest if this is coming from macro expansion.
1868 if span.can_be_used_for_suggestions() {
1869 return Some((
1870 span.shrink_to_hi(),
1871 msg,
1872 sugg,
1873 Applicability::MaybeIncorrect,
1874 ));
1875 }
1876 }
1877 }
1878 _ => {}
1879 }
1880 None
1881 }
1882
1883 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1884 /// optionally returning the closest match and whether it is reachable.
1885 pub(crate) fn suggestion_for_label_in_rib(
1886 &self,
1887 rib_index: usize,
1888 label: Ident,
1889 ) -> Option<LabelSuggestion> {
1890 // Are ribs from this `rib_index` within scope?
1891 let within_scope = self.is_label_valid_from_rib(rib_index);
1892
1893 let rib = &self.label_ribs[rib_index];
1894 let names = rib
1895 .bindings
1896 .iter()
1897 .filter(|(id, _)| id.span.eq_ctxt(label.span))
1898 .map(|(id, _)| id.name)
1899 .collect::<Vec<Symbol>>();
1900
1901 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1902 // Upon finding a similar name, get the ident that it was from - the span
1903 // contained within helps make a useful diagnostic. In addition, determine
1904 // whether this candidate is within scope.
1905 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1906 (*ident, within_scope)
1907 })
1908 }
1909
1910 pub(crate) fn maybe_report_lifetime_uses(
1911 &mut self,
1912 generics_span: Span,
1913 params: &[ast::GenericParam],
1914 ) {
1915 for (param_index, param) in params.iter().enumerate() {
1916 let GenericParamKind::Lifetime = param.kind else { continue };
1917
1918 let def_id = self.r.local_def_id(param.id);
1919
1920 let use_set = self.lifetime_uses.remove(&def_id);
1921 debug!(
1922 "Use set for {:?}({:?} at {:?}) is {:?}",
1923 def_id, param.ident, param.ident.span, use_set
1924 );
1925
1926 let deletion_span = || {
1927 if params.len() == 1 {
1928 // if sole lifetime, remove the entire `<>` brackets
1929 generics_span
1930 } else if param_index == 0 {
1931 // if removing within `<>` brackets, we also want to
1932 // delete a leading or trailing comma as appropriate
1933 param.span().to(params[param_index + 1].span().shrink_to_lo())
1934 } else {
1935 // if removing within `<>` brackets, we also want to
1936 // delete a leading or trailing comma as appropriate
1937 params[param_index - 1].span().shrink_to_hi().to(param.span())
1938 }
1939 };
1940 match use_set {
1941 Some(LifetimeUseSet::Many) => {}
1942 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
1943 debug!(?param.ident, ?param.ident.span, ?use_span);
1944
1945 let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
1946
1947 let deletion_span = deletion_span();
1948 self.r.lint_buffer.buffer_lint_with_diagnostic(
1949 lint::builtin::SINGLE_USE_LIFETIMES,
1950 param.id,
1951 param.ident.span,
1952 &format!("lifetime parameter `{}` only used once", param.ident),
1953 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1954 param_span: param.ident.span,
1955 use_span: Some((use_span, elidable)),
1956 deletion_span,
1957 },
1958 );
1959 }
1960 None => {
1961 debug!(?param.ident, ?param.ident.span);
1962
1963 let deletion_span = deletion_span();
1964 self.r.lint_buffer.buffer_lint_with_diagnostic(
1965 lint::builtin::UNUSED_LIFETIMES,
1966 param.id,
1967 param.ident.span,
1968 &format!("lifetime parameter `{}` never used", param.ident),
1969 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1970 param_span: param.ident.span,
1971 use_span: None,
1972 deletion_span,
1973 },
1974 );
1975 }
1976 }
1977 }
1978 }
1979
1980 pub(crate) fn emit_undeclared_lifetime_error(
1981 &self,
1982 lifetime_ref: &ast::Lifetime,
1983 outer_lifetime_ref: Option<Ident>,
1984 ) {
1985 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1986 let mut err = if let Some(outer) = outer_lifetime_ref {
1987 let mut err = struct_span_err!(
1988 self.r.session,
1989 lifetime_ref.ident.span,
1990 E0401,
1991 "can't use generic parameters from outer item",
1992 );
1993 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
1994 err.span_label(outer.span, "lifetime parameter from outer item");
1995 err
1996 } else {
1997 let mut err = struct_span_err!(
1998 self.r.session,
1999 lifetime_ref.ident.span,
2000 E0261,
2001 "use of undeclared lifetime name `{}`",
2002 lifetime_ref.ident
2003 );
2004 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
2005 err
2006 };
2007 let mut suggest_note = true;
2008
2009 for rib in self.lifetime_ribs.iter().rev() {
2010 match rib.kind {
2011 LifetimeRibKind::Generics { binder: _, span, kind } => {
2012 if !span.can_be_used_for_suggestions() && suggest_note {
2013 suggest_note = false; // Avoid displaying the same help multiple times.
2014 err.span_label(
2015 span,
2016 &format!(
2017 "lifetime `{}` is missing in item created through this procedural macro",
2018 lifetime_ref.ident,
2019 ),
2020 );
2021 continue;
2022 }
2023
2024 let higher_ranked = matches!(
2025 kind,
2026 LifetimeBinderKind::BareFnType
2027 | LifetimeBinderKind::PolyTrait
2028 | LifetimeBinderKind::WhereBound
2029 );
2030 let (span, sugg) = if span.is_empty() {
2031 let sugg = format!(
2032 "{}<{}>{}",
2033 if higher_ranked { "for" } else { "" },
2034 lifetime_ref.ident,
2035 if higher_ranked { " " } else { "" },
2036 );
2037 (span, sugg)
2038 } else {
2039 let span =
2040 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
2041 let sugg = format!("{}, ", lifetime_ref.ident);
2042 (span, sugg)
2043 };
2044 if higher_ranked {
2045 err.span_suggestion(
2046 span,
2047 &format!(
2048 "consider making the {} lifetime-generic with a new `{}` lifetime",
2049 kind.descr(),
2050 lifetime_ref
2051 ),
2052 sugg,
2053 Applicability::MaybeIncorrect,
2054 );
2055 err.note_once(
2056 "for more information on higher-ranked polymorphism, visit \
2057 https://doc.rust-lang.org/nomicon/hrtb.html",
2058 );
2059 } else {
2060 err.span_suggestion(
2061 span,
2062 &format!("consider introducing lifetime `{}` here", lifetime_ref.ident),
2063 sugg,
2064 Applicability::MaybeIncorrect,
2065 );
2066 }
2067 }
2068 LifetimeRibKind::Item => break,
2069 _ => {}
2070 }
2071 }
2072
2073 err.emit();
2074 }
2075
2076 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2077 struct_span_err!(
2078 self.r.session,
2079 lifetime_ref.ident.span,
2080 E0771,
2081 "use of non-static lifetime `{}` in const generic",
2082 lifetime_ref.ident
2083 )
2084 .note(
2085 "for more information, see issue #74052 \
2086 <https://github.com/rust-lang/rust/issues/74052>",
2087 )
2088 .emit();
2089 }
2090
2091 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2092 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2093 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2094 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2095 &self,
2096 lifetime_ref: &ast::Lifetime,
2097 ) {
2098 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2099 if !feature_active {
2100 feature_err(
2101 &self.r.session.parse_sess,
2102 sym::generic_const_exprs,
2103 lifetime_ref.ident.span,
2104 "a non-static lifetime is not allowed in a `const`",
2105 )
2106 .emit();
2107 }
2108 }
2109 }
2110
2111 /// Report lifetime/lifetime shadowing as an error.
2112 pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
2113 let mut err = struct_span_err!(
2114 sess,
2115 shadower.span,
2116 E0496,
2117 "lifetime name `{}` shadows a lifetime name that is already in scope",
2118 orig.name,
2119 );
2120 err.span_label(orig.span, "first declared here");
2121 err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name));
2122 err.emit();
2123 }
2124
2125 /// Shadowing involving a label is only a warning for historical reasons.
2126 //FIXME: make this a proper lint.
2127 pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
2128 let name = shadower.name;
2129 let shadower = shadower.span;
2130 let mut err = sess.struct_span_warn(
2131 shadower,
2132 &format!("label name `{}` shadows a label name that is already in scope", name),
2133 );
2134 err.span_label(orig, "first declared here");
2135 err.span_label(shadower, format!("label `{}` already in scope", name));
2136 err.emit();
2137 }
2138
2139 impl<'tcx> LifetimeContext<'_, 'tcx> {
2140 pub(crate) fn report_missing_lifetime_specifiers(
2141 &self,
2142 spans: Vec<Span>,
2143 count: usize,
2144 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2145 struct_span_err!(
2146 self.tcx.sess,
2147 spans,
2148 E0106,
2149 "missing lifetime specifier{}",
2150 pluralize!(count)
2151 )
2152 }
2153
2154 /// Returns whether to add `'static` lifetime to the suggested lifetime list.
2155 pub(crate) fn report_elision_failure(
2156 &self,
2157 diag: &mut Diagnostic,
2158 params: &[ElisionFailureInfo],
2159 ) -> bool {
2160 let mut m = String::new();
2161 let len = params.len();
2162
2163 let elided_params: Vec<_> =
2164 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2165
2166 let elided_len = elided_params.len();
2167
2168 for (i, info) in elided_params.into_iter().enumerate() {
2169 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
2170 info;
2171
2172 diag.span_label(span, "");
2173 let help_name = if let Some(ident) =
2174 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2175 {
2176 format!("`{}`", ident)
2177 } else {
2178 format!("argument {}", index + 1)
2179 };
2180
2181 m.push_str(
2182 &(if n == 1 {
2183 help_name
2184 } else {
2185 format!(
2186 "one of {}'s {} {}lifetimes",
2187 help_name,
2188 n,
2189 if have_bound_regions { "free " } else { "" }
2190 )
2191 })[..],
2192 );
2193
2194 if elided_len == 2 && i == 0 {
2195 m.push_str(" or ");
2196 } else if i + 2 == elided_len {
2197 m.push_str(", or ");
2198 } else if i != elided_len - 1 {
2199 m.push_str(", ");
2200 }
2201 }
2202
2203 if len == 0 {
2204 diag.help(
2205 "this function's return type contains a borrowed value, \
2206 but there is no value for it to be borrowed from",
2207 );
2208 true
2209 } else if elided_len == 0 {
2210 diag.help(
2211 "this function's return type contains a borrowed value with \
2212 an elided lifetime, but the lifetime cannot be derived from \
2213 the arguments",
2214 );
2215 true
2216 } else if elided_len == 1 {
2217 diag.help(&format!(
2218 "this function's return type contains a borrowed value, \
2219 but the signature does not say which {} it is borrowed from",
2220 m
2221 ));
2222 false
2223 } else {
2224 diag.help(&format!(
2225 "this function's return type contains a borrowed value, \
2226 but the signature does not say whether it is borrowed from {}",
2227 m
2228 ));
2229 false
2230 }
2231 }
2232
2233 pub(crate) fn is_trait_ref_fn_scope(
2234 &mut self,
2235 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
2236 ) -> bool {
2237 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
2238 if [
2239 self.tcx.lang_items().fn_once_trait(),
2240 self.tcx.lang_items().fn_trait(),
2241 self.tcx.lang_items().fn_mut_trait(),
2242 ]
2243 .contains(&Some(did))
2244 {
2245 let (span, span_type) = if let Some(bound) =
2246 trait_ref.bound_generic_params.iter().rfind(|param| {
2247 matches!(
2248 param.kind,
2249 hir::GenericParamKind::Lifetime {
2250 kind: hir::LifetimeParamKind::Explicit
2251 }
2252 )
2253 }) {
2254 (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail)
2255 } else {
2256 (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty)
2257 };
2258 self.missing_named_lifetime_spots
2259 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
2260 return true;
2261 }
2262 };
2263 false
2264 }
2265
2266 pub(crate) fn add_missing_lifetime_specifiers_label(
2267 &self,
2268 err: &mut Diagnostic,
2269 mut spans_with_counts: Vec<(Span, usize)>,
2270 in_scope_lifetimes: FxIndexSet<LocalDefId>,
2271 params: Option<&[ElisionFailureInfo]>,
2272 ) {
2273 let (mut lifetime_names, lifetime_spans): (FxHashSet<_>, Vec<_>) = in_scope_lifetimes
2274 .iter()
2275 .filter_map(|def_id| {
2276 let name = self.tcx.item_name(def_id.to_def_id());
2277 let span = self.tcx.def_ident_span(def_id.to_def_id())?;
2278 Some((name, span))
2279 })
2280 .filter(|&(n, _)| n != kw::UnderscoreLifetime)
2281 .unzip();
2282
2283 if let Some(params) = params {
2284 // If there's no lifetime available, suggest `'static`.
2285 if self.report_elision_failure(err, params) && lifetime_names.is_empty() {
2286 lifetime_names.insert(kw::StaticLifetime);
2287 }
2288 }
2289 let params = params.unwrap_or(&[]);
2290
2291 let snippets: Vec<Option<String>> = spans_with_counts
2292 .iter()
2293 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
2294 .collect();
2295
2296 // Empty generics are marked with a span of "<", but since from now on
2297 // that information is in the snippets it can be removed from the spans.
2298 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
2299 if snippet.as_deref() == Some("<") {
2300 *span = span.shrink_to_hi();
2301 }
2302 }
2303
2304 for &(span, count) in &spans_with_counts {
2305 err.span_label(
2306 span,
2307 format!(
2308 "expected {} lifetime parameter{}",
2309 if count == 1 { "named".to_string() } else { count.to_string() },
2310 pluralize!(count),
2311 ),
2312 );
2313 }
2314
2315 let suggest_existing =
2316 |err: &mut Diagnostic,
2317 name: &str,
2318 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
2319 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
2320 self.missing_named_lifetime_spots.iter().rev().next()
2321 {
2322 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
2323 // using `'a`, but also introduce the concept of HRLTs by suggesting
2324 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
2325 let mut introduce_suggestion = vec![];
2326
2327 let a_to_z_repeat_n = |n| {
2328 (b'a'..=b'z').map(move |c| {
2329 let mut s = '\''.to_string();
2330 s.extend(std::iter::repeat(char::from(c)).take(n));
2331 s
2332 })
2333 };
2334
2335 // If all single char lifetime names are present, we wrap around and double the chars.
2336 let lt_name = (1..)
2337 .flat_map(a_to_z_repeat_n)
2338 .find(|lt| !lifetime_names.contains(&Symbol::intern(&lt)))
2339 .unwrap();
2340 let msg = format!(
2341 "consider making the {} lifetime-generic with a new `{}` lifetime",
2342 span_type.descr(),
2343 lt_name,
2344 );
2345 err.note(
2346 "for more information on higher-ranked polymorphism, visit \
2347 https://doc.rust-lang.org/nomicon/hrtb.html",
2348 );
2349 let for_sugg = span_type.suggestion(&lt_name);
2350 for param in params {
2351 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
2352 {
2353 if snippet.starts_with('&') && !snippet.starts_with("&'") {
2354 introduce_suggestion
2355 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
2356 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
2357 introduce_suggestion
2358 .push((param.span, format!("&{} {}", lt_name, stripped)));
2359 }
2360 }
2361 }
2362 introduce_suggestion.push((*for_span, for_sugg));
2363 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
2364 if let Some(formatter) = formatter {
2365 introduce_suggestion.push((*span, formatter(&lt_name)));
2366 }
2367 }
2368 err.multipart_suggestion_verbose(
2369 &msg,
2370 introduce_suggestion,
2371 Applicability::MaybeIncorrect,
2372 );
2373 }
2374
2375 let spans_suggs: Vec<_> = formatters
2376 .into_iter()
2377 .zip(spans_with_counts.iter())
2378 .filter_map(|(formatter, (span, _))| {
2379 if let Some(formatter) = formatter {
2380 Some((*span, formatter(name)))
2381 } else {
2382 None
2383 }
2384 })
2385 .collect();
2386 if spans_suggs.is_empty() {
2387 // If all the spans come from macros, we cannot extract snippets and then
2388 // `formatters` only contains None and `spans_suggs` is empty.
2389 return;
2390 }
2391 err.multipart_suggestion_verbose(
2392 &format!(
2393 "consider using the `{}` lifetime",
2394 lifetime_names.iter().next().unwrap()
2395 ),
2396 spans_suggs,
2397 Applicability::MaybeIncorrect,
2398 );
2399 };
2400 let suggest_new = |err: &mut Diagnostic, suggs: Vec<Option<String>>| {
2401 for missing in self.missing_named_lifetime_spots.iter().rev() {
2402 let mut introduce_suggestion = vec![];
2403 let msg;
2404 let should_break;
2405 introduce_suggestion.push(match missing {
2406 MissingLifetimeSpot::Generics(generics) => {
2407 if generics.span == DUMMY_SP {
2408 // Account for malformed generics in the HIR. This shouldn't happen,
2409 // but if we make a mistake elsewhere, mainly by keeping something in
2410 // `missing_named_lifetime_spots` that we shouldn't, like associated
2411 // `const`s or making a mistake in the AST lowering we would provide
2412 // nonsensical suggestions. Guard against that by skipping these.
2413 // (#74264)
2414 continue;
2415 }
2416 msg = "consider introducing a named lifetime parameter".to_string();
2417 should_break = true;
2418 if let Some(param) = generics.params.iter().find(|p| {
2419 !matches!(
2420 p.kind,
2421 hir::GenericParamKind::Type { synthetic: true, .. }
2422 | hir::GenericParamKind::Lifetime {
2423 kind: hir::LifetimeParamKind::Elided
2424 }
2425 )
2426 }) {
2427 (param.span.shrink_to_lo(), "'a, ".to_string())
2428 } else {
2429 (generics.span, "<'a>".to_string())
2430 }
2431 }
2432 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2433 msg = format!(
2434 "consider making the {} lifetime-generic with a new `'a` lifetime",
2435 span_type.descr(),
2436 );
2437 should_break = false;
2438 err.note(
2439 "for more information on higher-ranked polymorphism, visit \
2440 https://doc.rust-lang.org/nomicon/hrtb.html",
2441 );
2442 (*span, span_type.suggestion("'a"))
2443 }
2444 MissingLifetimeSpot::Static => {
2445 let mut spans_suggs = Vec::new();
2446 for ((span, count), snippet) in
2447 spans_with_counts.iter().copied().zip(snippets.iter())
2448 {
2449 let (span, sugg) = match snippet.as_deref() {
2450 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2451 Some("'_") => (span, "'static".to_owned()),
2452 Some(snippet) if !snippet.ends_with('>') => {
2453 if snippet == "" {
2454 (
2455 span,
2456 std::iter::repeat("'static")
2457 .take(count)
2458 .collect::<Vec<_>>()
2459 .join(", "),
2460 )
2461 } else if snippet == "<" || snippet == "(" {
2462 (
2463 span.shrink_to_hi(),
2464 std::iter::repeat("'static")
2465 .take(count)
2466 .collect::<Vec<_>>()
2467 .join(", "),
2468 )
2469 } else {
2470 (
2471 span.shrink_to_hi(),
2472 format!(
2473 "<{}>",
2474 std::iter::repeat("'static")
2475 .take(count)
2476 .collect::<Vec<_>>()
2477 .join(", "),
2478 ),
2479 )
2480 }
2481 }
2482 _ => continue,
2483 };
2484 spans_suggs.push((span, sugg.to_string()));
2485 }
2486 err.multipart_suggestion_verbose(
2487 "consider using the `'static` lifetime",
2488 spans_suggs,
2489 Applicability::MaybeIncorrect,
2490 );
2491 continue;
2492 }
2493 });
2494
2495 struct Lifetime(Span, String);
2496 impl Lifetime {
2497 fn is_unnamed(&self) -> bool {
2498 self.1.starts_with('&') && !self.1.starts_with("&'")
2499 }
2500 fn is_underscore(&self) -> bool {
2501 self.1.starts_with("&'_ ")
2502 }
2503 fn is_named(&self) -> bool {
2504 self.1.starts_with("&'")
2505 }
2506 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2507 Some(
2508 match (
2509 self.is_unnamed(),
2510 self.is_underscore(),
2511 self.is_named(),
2512 sugg.starts_with('&'),
2513 ) {
2514 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2515 (true, _, _, true) => {
2516 (self.span_unnamed_borrow(), sugg[1..].to_string())
2517 }
2518 (_, true, _, false) => {
2519 (self.span_underscore_borrow(), sugg.trim().to_string())
2520 }
2521 (_, true, _, true) => {
2522 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2523 }
2524 (_, _, true, false) => {
2525 (self.span_named_borrow(), sugg.trim().to_string())
2526 }
2527 (_, _, true, true) => {
2528 (self.span_named_borrow(), sugg[1..].trim().to_string())
2529 }
2530 _ => return None,
2531 },
2532 )
2533 }
2534 fn span_unnamed_borrow(&self) -> Span {
2535 let lo = self.0.lo() + BytePos(1);
2536 self.0.with_lo(lo).with_hi(lo)
2537 }
2538 fn span_named_borrow(&self) -> Span {
2539 let lo = self.0.lo() + BytePos(1);
2540 self.0.with_lo(lo)
2541 }
2542 fn span_underscore_borrow(&self) -> Span {
2543 let lo = self.0.lo() + BytePos(1);
2544 let hi = lo + BytePos(2);
2545 self.0.with_lo(lo).with_hi(hi)
2546 }
2547 }
2548
2549 for param in params {
2550 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2551 if let Some((span, sugg)) =
2552 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2553 {
2554 introduce_suggestion.push((span, sugg));
2555 }
2556 }
2557 }
2558 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2559 |((span, _), sugg)| match &sugg {
2560 Some(sugg) => Some((span, sugg.to_string())),
2561 _ => None,
2562 },
2563 ) {
2564 let (span, sugg) = self
2565 .tcx
2566 .sess
2567 .source_map()
2568 .span_to_snippet(span)
2569 .ok()
2570 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2571 .unwrap_or((span, sugg));
2572 introduce_suggestion.push((span, sugg.to_string()));
2573 }
2574 err.multipart_suggestion_verbose(
2575 &msg,
2576 introduce_suggestion,
2577 Applicability::MaybeIncorrect,
2578 );
2579 if should_break {
2580 break;
2581 }
2582 }
2583 };
2584
2585 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2586 match &lifetime_names[..] {
2587 [name] => {
2588 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2589 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2590 {
2591 suggs.push(match snippet.as_deref() {
2592 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2593 Some("'_") => Some(Box::new(|n| n.to_string())),
2594 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2595 Some("<") => Some(Box::new(move |n| {
2596 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2597 })),
2598 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2599 format!(
2600 "{}<{}>",
2601 snippet,
2602 std::iter::repeat(name.to_string())
2603 .take(count)
2604 .collect::<Vec<_>>()
2605 .join(", ")
2606 )
2607 })),
2608 _ => None,
2609 });
2610 }
2611 suggest_existing(err, name.as_str(), suggs);
2612 }
2613 [] => {
2614 let mut suggs = Vec::new();
2615 for (snippet, (_, count)) in
2616 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2617 {
2618 suggs.push(match snippet.as_deref() {
2619 Some("&") => Some("&'a ".to_string()),
2620 Some("'_") => Some("'a".to_string()),
2621 Some("") => {
2622 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2623 }
2624 Some("<") => {
2625 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2626 }
2627 Some(snippet) => Some(format!(
2628 "{}<{}>",
2629 snippet,
2630 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2631 )),
2632 None => None,
2633 });
2634 }
2635 suggest_new(err, suggs);
2636 }
2637 lts if lts.len() > 1 => {
2638 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2639
2640 let mut spans_suggs: Vec<_> = Vec::new();
2641 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2642 match snippet.as_deref() {
2643 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2644 Some("&") => spans_suggs
2645 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2646 _ => {}
2647 }
2648 }
2649
2650 if spans_suggs.len() > 0 {
2651 // This happens when we have `Foo<T>` where we point at the space before `T`,
2652 // but this can be confusing so we give a suggestion with placeholders.
2653 err.multipart_suggestion_verbose(
2654 "consider using one of the available lifetimes here",
2655 spans_suggs,
2656 Applicability::HasPlaceholders,
2657 );
2658 }
2659 }
2660 _ => unreachable!(),
2661 }
2662 }
2663 }