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};
5 use crate::path_names_to_string;
6 use crate::{Module, ModuleKind, ModuleOrUniformRoot};
7 use crate::{PathResult, PathSource, Segment};
9 use rustc_ast::visit::{FnCtxt, FnKind};
11 self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
12 NodeId, Path, Ty, TyKind,
14 use rustc_ast_pretty::pprust::path_segment_to_string;
15 use rustc_data_structures::fx::FxHashSet;
17 pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
21 use rustc_hir::def::Namespace::{self, *};
22 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
23 use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE};
24 use rustc_hir::PrimTy;
25 use rustc_session::parse::feature_err;
26 use rustc_span::edition::Edition;
27 use rustc_span::hygiene::MacroKind;
28 use rustc_span::lev_distance::find_best_match_for_name;
29 use rustc_span::symbol::{kw, sym, Ident, Symbol};
30 use rustc_span::{BytePos, Span, DUMMY_SP};
37 type Res = def::Res<ast::NodeId>;
39 /// A field or associated item from self type suggested in case of resolution failure.
40 enum AssocSuggestion {
48 impl AssocSuggestion {
49 fn action(&self) -> &'static str {
51 AssocSuggestion::Field => "use the available field",
52 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
53 AssocSuggestion::AssocFn => "call the associated function",
54 AssocSuggestion::AssocConst => "use the associated `const`",
55 AssocSuggestion::AssocType => "use the associated type",
60 crate enum MissingLifetimeSpot<'tcx> {
61 Generics(&'tcx hir::Generics<'tcx>),
62 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
66 crate enum ForLifetimeSpanType {
73 impl ForLifetimeSpanType {
74 crate fn descr(&self) -> &'static str {
76 Self::BoundEmpty | Self::BoundTail => "bound",
77 Self::TypeEmpty | Self::TypeTail => "type",
81 crate fn suggestion(&self, sugg: &str) -> String {
83 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
84 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
89 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &&'tcx hir::Generics<'tcx> {
90 fn into(self) -> MissingLifetimeSpot<'tcx> {
91 MissingLifetimeSpot::Generics(self)
95 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
96 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
99 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
100 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
103 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
104 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
105 let variant_path = &suggestion.path;
106 let variant_path_string = path_names_to_string(variant_path);
108 let path_len = suggestion.path.segments.len();
109 let enum_path = ast::Path {
110 span: suggestion.path.span,
111 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
114 let enum_path_string = path_names_to_string(&enum_path);
116 (variant_path_string, enum_path_string)
119 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
120 fn def_span(&self, def_id: DefId) -> Option<Span> {
122 LOCAL_CRATE => self.r.opt_span(def_id),
127 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
132 /// Handles error reporting for `smart_resolve_path_fragment` function.
133 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
134 pub(crate) fn smart_resolve_report_errors(
138 source: PathSource<'_>,
140 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
141 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
142 let ns = source.namespace();
143 let is_expected = &|res| source.is_expected(res);
144 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
146 // Make the base error.
147 struct BaseError<'a> {
149 fallback_label: String,
152 suggestion: Option<(Span, &'a str, String)>,
154 let mut expected = source.descr_expected();
155 let path_str = Segment::names_to_string(path);
156 let item_str = path.last().unwrap().ident;
157 let base_error = if let Some(res) = res {
159 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
160 fallback_label: format!("not a {expected}"),
162 could_be_expr: match res {
163 Res::Def(DefKind::Fn, _) => {
164 // Verify whether this is a fn call or an Fn used as a type.
168 .span_to_snippet(span)
169 .map(|snippet| snippet.ends_with(')'))
173 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
178 | Res::Local(_) => true,
184 let item_span = path.last().unwrap().ident.span;
185 let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
186 debug!(?self.diagnostic_metadata.current_impl_items);
187 debug!(?self.diagnostic_metadata.current_function);
188 let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
189 && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
190 && self.current_trait_ref.is_none()
191 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
192 && let Some(item) = items.iter().find(|i| {
193 if let AssocItemKind::Fn(fn_) = &i.kind
194 && !fn_.sig.decl.has_self()
195 && i.ident.name == item_str.name
197 debug!(?item_str.name);
198 debug!(?fn_.sig.decl.inputs);
206 "consider using the associated function",
207 format!("Self::{}", item.ident)
212 (String::new(), "this scope".to_string(), suggestion)
213 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
214 if self.r.session.edition() > Edition::Edition2015 {
215 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
216 // which overrides all other expectations of item type
218 (String::new(), "the list of imported crates".to_string(), None)
220 (String::new(), "the crate root".to_string(), None)
222 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
223 (String::new(), "the crate root".to_string(), None)
225 let mod_path = &path[..path.len() - 1];
226 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
227 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
230 .map_or_else(String::new, |res| format!("{} ", res.descr()));
231 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
234 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
235 fallback_label: if path_str == "async" && expected.starts_with("struct") {
236 "`async` blocks are only allowed in Rust 2018 or later".to_string()
238 format!("not found in {mod_str}")
241 could_be_expr: false,
246 let code = source.error_code(res.is_some());
248 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
250 if let Some(sugg) = base_error.suggestion {
251 err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
254 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
255 err.multipart_suggestion(
256 "you might have meant to write a `struct` literal",
258 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
259 (span.shrink_to_hi(), "}".to_string()),
261 Applicability::HasPlaceholders,
264 match (source, self.diagnostic_metadata.in_if_condition) {
265 (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => {
266 err.span_suggestion_verbose(
268 "you might have meant to use pattern matching",
270 Applicability::MaybeIncorrect,
276 let is_assoc_fn = self.self_type_is_available();
277 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
278 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
279 err.span_suggestion_short(
281 "you might have meant to use `self` here instead",
283 Applicability::MaybeIncorrect,
285 if !self.self_value_is_available(path[0].ident.span) {
286 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
287 &self.diagnostic_metadata.current_function
289 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
290 (param.span.shrink_to_lo(), "&self, ")
296 .span_through_char(*fn_span, '(')
301 err.span_suggestion_verbose(
303 "if you meant to use `self`, you are also missing a `self` receiver \
306 Applicability::MaybeIncorrect,
312 self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
314 // Emit special messages for unresolved `Self` and `self`.
315 if is_self_type(path, ns) {
316 err.code(rustc_errors::error_code!(E0411));
319 "`Self` is only available in impls, traits, and type definitions".to_string(),
321 return (err, Vec::new());
323 if is_self_value(path, ns) {
324 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
326 err.code(rustc_errors::error_code!(E0424));
327 err.span_label(span, match source {
328 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
330 _ => "`self` value is a keyword only available in methods with a `self` parameter"
333 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
334 // The current function has a `self' parameter, but we were unable to resolve
335 // a reference to `self`. This can only happen if the `self` identifier we
336 // are resolving came from a different hygiene context.
337 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
338 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
340 let doesnt = if is_assoc_fn {
341 let (span, sugg) = fn_kind
345 .map(|p| (p.span.shrink_to_lo(), "&self, "))
347 // Try to look for the "(" after the function name, if possible.
348 // This avoids placing the suggestion into the visibility specifier.
351 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
356 .span_through_char(span, '(')
361 err.span_suggestion_verbose(
363 "add a `self` receiver parameter to make the associated `fn` a method",
365 Applicability::MaybeIncorrect,
371 if let Some(ident) = fn_kind.ident() {
374 &format!("this function {} have a `self` parameter", doesnt),
379 return (err, Vec::new());
382 // Try to lookup name in more relaxed fashion for better error reporting.
383 let ident = path.last().unwrap().ident;
384 let candidates = self
386 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
388 .filter(|ImportSuggestion { did, .. }| {
389 match (did, res.and_then(|res| res.opt_def_id())) {
390 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
394 .collect::<Vec<_>>();
395 let crate_def_id = CRATE_DEF_ID.to_def_id();
396 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
397 let mut enum_candidates: Vec<_> = self
399 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
401 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
402 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
404 if !enum_candidates.is_empty() {
405 if let (PathSource::Type, Some(span)) =
406 (source, self.diagnostic_metadata.current_type_ascription.last())
412 .type_ascription_path_suggestions
416 // Already reported this issue on the lhs of the type ascription.
418 return (err, candidates);
422 enum_candidates.sort();
424 // Contextualize for E0412 "cannot find type", but don't belabor the point
425 // (that it's a variant) for E0573 "expected type, found variant".
426 let preamble = if res.is_none() {
427 let others = match enum_candidates.len() {
429 2 => " and 1 other".to_owned(),
430 n => format!(" and {} others", n),
432 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
436 let msg = format!("{}try using the variant's enum", preamble);
438 err.span_suggestions(
441 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
442 Applicability::MachineApplicable,
446 if path.len() == 1 && self.self_type_is_available() {
447 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
448 let self_is_available = self.self_value_is_available(path[0].ident.span);
450 AssocSuggestion::Field => {
451 if self_is_available {
454 "you might have meant to use the available field",
455 format!("self.{}", path_str),
456 Applicability::MachineApplicable,
459 err.span_label(span, "a field by this name exists in `Self`");
462 AssocSuggestion::MethodWithSelf if self_is_available => {
465 "you might have meant to call the method",
466 format!("self.{}", path_str),
467 Applicability::MachineApplicable,
470 AssocSuggestion::MethodWithSelf
471 | AssocSuggestion::AssocFn
472 | AssocSuggestion::AssocConst
473 | AssocSuggestion::AssocType => {
476 &format!("you might have meant to {}", candidate.action()),
477 format!("Self::{}", path_str),
478 Applicability::MachineApplicable,
482 return (err, candidates);
485 // If the first argument in call is `self` suggest calling a method.
486 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
487 let mut args_snippet = String::new();
488 if let Some(args_span) = args_span {
489 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
490 args_snippet = snippet;
496 &format!("try calling `{}` as a method", ident),
497 format!("self.{}({})", path_str, args_snippet),
498 Applicability::MachineApplicable,
500 return (err, candidates);
504 // Try Levenshtein algorithm.
505 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
506 // Try context-dependent help if relaxed lookup didn't work.
507 if let Some(res) = res {
508 if self.smart_resolve_context_dependent_help(
514 &base_error.fallback_label,
516 // We do this to avoid losing a secondary span when we override the main error span.
517 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
518 return (err, candidates);
523 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
524 if !self.type_ascription_suggestion(&mut err, base_error.span) {
525 let mut fallback = false;
527 PathSource::Trait(AliasPossibility::Maybe),
528 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
530 ) = (source, res, is_macro)
532 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
534 let spans: Vec<Span> = bounds
536 .map(|bound| bound.span())
537 .filter(|&sp| sp != base_error.span)
540 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
541 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
542 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
543 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
544 let last_bound_span = spans.last().cloned().unwrap();
545 let mut multi_span: MultiSpan = spans.clone().into();
547 let msg = if sp == last_bound_span {
549 "...because of {these} bound{s}",
550 these = pluralize!("this", bounds.len() - 1),
551 s = pluralize!(bounds.len() - 1),
556 multi_span.push_span_label(sp, msg);
558 multi_span.push_span_label(
560 "expected this type to be a trait...".to_string(),
564 "`+` is used to constrain a \"trait object\" type with lifetimes or \
565 auto-traits; structs and enums can't be bound in that way",
567 if bounds.iter().all(|bound| match bound {
568 ast::GenericBound::Outlives(_) => true,
569 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
571 let mut sugg = vec![];
572 if base_error.span != start_span {
573 sugg.push((start_span.until(base_error.span), String::new()));
575 if base_error.span != end_span {
576 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
579 err.multipart_suggestion(
580 "if you meant to use a type and not a trait here, remove the bounds",
582 Applicability::MaybeIncorrect,
588 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
590 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
592 match self.diagnostic_metadata.current_let_binding {
593 Some((pat_sp, Some(ty_sp), None))
594 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
596 err.span_suggestion_short(
597 pat_sp.between(ty_sp),
598 "use `=` if you meant to assign",
600 Applicability::MaybeIncorrect,
606 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
607 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
608 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
612 err.span_label(base_error.span, base_error.fallback_label);
615 if let Some(err_code) = &err.code {
616 if err_code == &rustc_errors::error_code!(E0425) {
617 for label_rib in &self.label_ribs {
618 for (label_ident, node_id) in &label_rib.bindings {
619 if format!("'{}", ident) == label_ident.to_string() {
620 err.span_label(label_ident.span, "a label with a similar name exists");
621 if let PathSource::Expr(Some(Expr {
622 kind: ExprKind::Break(None, Some(_)),
628 "use the similarly named label",
629 label_ident.name.to_string(),
630 Applicability::MaybeIncorrect,
632 // Do not lint against unused label when we suggest them.
633 self.diagnostic_metadata.unused_labels.remove(node_id);
638 } else if err_code == &rustc_errors::error_code!(E0412) {
639 if let Some(correct) = Self::likely_rust_type(path) {
642 "perhaps you intended to use this type",
644 Applicability::MaybeIncorrect,
653 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
654 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
655 let TyKind::Path(_, path) = &ty.kind else { return; };
656 for segment in &path.segments {
657 let Some(params) = &segment.args else { continue; };
658 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
659 for param in ¶ms.args {
660 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
661 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
664 for bound in bounds {
665 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
670 if base_span == trait_ref.span {
671 err.span_suggestion_verbose(
672 constraint.ident.span.between(trait_ref.span),
673 "you might have meant to write a path instead of an associated type bound",
675 Applicability::MachineApplicable,
683 fn get_single_associated_item(
686 source: &PathSource<'_>,
687 filter_fn: &impl Fn(Res) -> bool,
688 ) -> Option<TypoSuggestion> {
689 if let crate::PathSource::TraitItem(_) = source {
690 let mod_path = &path[..path.len() - 1];
691 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
692 self.resolve_path(mod_path, None, None)
694 let resolutions = self.r.resolutions(module).borrow();
695 let targets: Vec<_> =
698 .filter_map(|(key, resolution)| {
699 resolution.borrow().binding.map(|binding| binding.res()).and_then(
700 |res| if filter_fn(res) { Some((key, res)) } else { None },
704 if targets.len() == 1 {
705 let target = targets[0];
706 return Some(TypoSuggestion::single_item_from_res(
716 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
717 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
718 // Detect that we are actually in a `where` predicate.
719 let (bounded_ty, bounds, where_span) =
720 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
722 bound_generic_params,
725 })) = self.diagnostic_metadata.current_where_predicate
727 if !bound_generic_params.is_empty() {
730 (bounded_ty, bounds, span)
735 // Confirm that the target is an associated type.
736 let (ty, position, path) = if let ast::TyKind::Path(
737 Some(ast::QSelf { ty, position, .. }),
741 // use this to verify that ident is a type param.
742 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
746 partial_res.base_res(),
747 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
748 ) && partial_res.unresolved_segments() == 0)
757 let peeled_ty = ty.peel_refs();
758 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
759 // Confirm that the `SelfTy` is a type parameter.
760 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
764 partial_res.base_res(),
765 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
766 ) && partial_res.unresolved_segments() == 0)
771 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
772 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
773 ) = (&type_param_path.segments[..], &bounds[..])
775 if let [ast::PathSegment { ident, args: None, .. }] =
776 &poly_trait_ref.trait_ref.path.segments[..]
778 if ident.span == span {
779 err.span_suggestion_verbose(
781 &format!("constrain the associated type to `{}`", ident),
787 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
788 .unwrap_or_else(|_| constrain_ident.to_string()),
789 path.segments[..*position]
791 .map(|segment| path_segment_to_string(segment))
794 path.segments[*position..]
796 .map(|segment| path_segment_to_string(segment))
801 Applicability::MaybeIncorrect,
811 /// Check if the source is call expression and the first argument is `self`. If true,
812 /// return the span of whole call and the span for all arguments expect the first one (`self`).
813 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
814 let mut has_self_arg = None;
815 if let PathSource::Expr(Some(parent)) = source {
817 ExprKind::Call(_, args) if !args.is_empty() => {
818 let mut expr_kind = &args[0].kind;
821 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
822 if arg_name.segments[0].ident.name == kw::SelfLower {
823 let call_span = parent.span;
824 let tail_args_span = if args.len() > 1 {
827 args.last().unwrap().span.hi(),
834 has_self_arg = Some((call_span, tail_args_span));
838 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
849 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
850 // HACK(estebank): find a better way to figure out that this was a
851 // parser issue where a struct literal is being used on an expression
852 // where a brace being opened means a block is being started. Look
853 // ahead for the next text to see if `span` is followed by a `{`.
854 let sm = self.r.session.source_map();
857 sp = sm.next_point(sp);
858 match sm.span_to_snippet(sp) {
860 if snippet.chars().any(|c| !c.is_whitespace()) {
867 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
868 // In case this could be a struct literal that needs to be surrounded
869 // by parentheses, find the appropriate span.
871 let mut closing_brace = None;
873 sp = sm.next_point(sp);
874 match sm.span_to_snippet(sp) {
877 closing_brace = Some(span.to(sp));
884 // The bigger the span, the more likely we're incorrect --
885 // bound it to 100 chars long.
890 (followed_by_brace, closing_brace)
893 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
895 /// Returns `true` if able to provide context-dependent help.
896 fn smart_resolve_context_dependent_help(
898 err: &mut Diagnostic,
900 source: PathSource<'_>,
903 fallback_label: &str,
905 let ns = source.namespace();
906 let is_expected = &|res| source.is_expected(res);
908 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
909 ExprKind::Field(_, ident) => {
912 "use the path separator to refer to an item",
913 format!("{}::{}", path_str, ident),
914 Applicability::MaybeIncorrect,
918 ExprKind::MethodCall(ref segment, ..) => {
919 let span = expr.span.with_hi(segment.ident.span.hi());
922 "use the path separator to refer to an item",
923 format!("{}::{}", path_str, segment.ident),
924 Applicability::MaybeIncorrect,
931 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
933 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
934 | PathSource::TupleStruct(span, _) => {
935 // We want the main underline to cover the suggested code as well for
944 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
945 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
948 PathSource::Expr(Some(
949 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
950 )) if path_sep(err, &parent) => {}
956 | ExprKind::Binary(..)
957 | ExprKind::Unary(..)
959 | ExprKind::While(..)
960 | ExprKind::ForLoop(..)
961 | ExprKind::Match(..),
964 ) if followed_by_brace => {
965 if let Some(sp) = closing_brace {
966 err.span_label(span, fallback_label);
967 err.multipart_suggestion(
968 "surround the struct literal with parentheses",
970 (sp.shrink_to_lo(), "(".to_string()),
971 (sp.shrink_to_hi(), ")".to_string()),
973 Applicability::MaybeIncorrect,
977 span, // Note the parentheses surrounding the suggestion below
979 "you might want to surround a struct literal with parentheses: \
980 `({} {{ /* fields */ }})`?",
986 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
987 let span = find_span(&source, err);
988 if let Some(span) = self.def_span(def_id) {
989 err.span_label(span, &format!("`{}` defined here", path_str));
991 let (tail, descr, applicability) = match source {
992 PathSource::Pat | PathSource::TupleStruct(..) => {
993 ("", "pattern", Applicability::MachineApplicable)
995 _ => (": val", "literal", Applicability::HasPlaceholders),
997 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1001 .map(|f| format!("{}{}", f.node, tail))
1002 .collect::<Vec<String>>()
1006 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1008 let pad = match self.r.field_names.get(&def_id) {
1009 Some(fields) if fields.is_empty() => "",
1012 err.span_suggestion(
1014 &format!("use struct {} syntax instead", descr),
1015 format!("{path_str} {{{pad}{fields}{pad}}}"),
1020 err.span_label(span, fallback_label);
1025 match (res, source) {
1027 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1028 PathSource::Expr(Some(Expr {
1029 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1031 | PathSource::Struct,
1033 err.span_label(span, fallback_label);
1034 err.span_suggestion_verbose(
1035 span.shrink_to_hi(),
1036 "use `!` to invoke the macro",
1038 Applicability::MaybeIncorrect,
1040 if path_str == "try" && span.rust_2015() {
1041 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1044 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1045 err.span_label(span, fallback_label);
1047 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1048 err.span_label(span, "type aliases cannot be used as traits");
1049 if self.r.session.is_nightly_build() {
1050 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1052 if let Some(span) = self.def_span(def_id) {
1053 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1054 // The span contains a type alias so we should be able to
1055 // replace `type` with `trait`.
1056 let snip = snip.replacen("type", "trait", 1);
1057 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1059 err.span_help(span, msg);
1066 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1067 if !path_sep(err, &parent) {
1072 Res::Def(DefKind::Enum, def_id),
1073 PathSource::TupleStruct(..) | PathSource::Expr(..),
1076 .diagnostic_metadata
1077 .current_type_ascription
1083 .type_ascription_path_suggestions
1089 err.downgrade_to_delayed_bug();
1090 // We already suggested changing `:` into `::` during parsing.
1094 self.suggest_using_enum_variant(err, source, def_id, span);
1096 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1097 let (ctor_def, ctor_vis, fields) =
1098 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1099 if let PathSource::Expr(Some(parent)) = source {
1100 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1101 bad_struct_syntax_suggestion(def_id);
1107 bad_struct_syntax_suggestion(def_id);
1111 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1112 if !is_expected(ctor_def) || is_accessible {
1116 let field_spans = match source {
1117 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1118 PathSource::TupleStruct(_, pattern_spans) => {
1119 err.set_primary_message(
1120 "cannot match against a tuple struct which contains private fields",
1123 // Use spans of the tuple struct pattern.
1124 Some(Vec::from(pattern_spans))
1126 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1127 _ if source.is_call() => {
1128 err.set_primary_message(
1129 "cannot initialize a tuple struct which contains private fields",
1132 // Use spans of the tuple struct definition.
1136 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1141 if let Some(spans) =
1142 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1144 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1145 .filter(|(vis, _)| {
1146 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1148 .map(|(_, span)| *span)
1151 if non_visible_spans.len() > 0 {
1152 let mut m: MultiSpan = non_visible_spans.clone().into();
1155 .for_each(|s| m.push_span_label(s, "private field".to_string()));
1156 err.span_note(m, "constructor is not visible here due to private fields");
1164 "constructor is not visible here due to private fields".to_string(),
1169 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1173 ) if ns == ValueNS => {
1174 bad_struct_syntax_suggestion(def_id);
1176 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1178 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1179 let span = find_span(&source, err);
1180 if let Some(span) = self.def_span(def_id) {
1181 err.span_label(span, &format!("`{}` defined here", path_str));
1183 err.span_suggestion(
1185 "use this syntax instead",
1186 path_str.to_string(),
1187 Applicability::MaybeIncorrect,
1193 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1194 if let Some(span) = self.def_span(def_id) {
1195 err.span_label(span, &format!("`{}` defined here", path_str));
1197 let fields = self.r.field_names.get(&def_id).map_or_else(
1198 || "/* fields */".to_string(),
1199 |fields| vec!["_"; fields.len()].join(", "),
1201 err.span_suggestion(
1203 "use the tuple variant pattern syntax instead",
1204 format!("{}({})", path_str, fields),
1205 Applicability::HasPlaceholders,
1208 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1209 err.span_label(span, fallback_label);
1210 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1212 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1213 err.note("can't use a type alias as a constructor");
1220 /// Given the target `ident` and `kind`, search for the similarly named associated item
1221 /// in `self.current_trait_ref`.
1222 crate fn find_similarly_named_assoc_item(
1225 kind: &AssocItemKind,
1226 ) -> Option<Symbol> {
1227 let (module, _) = self.current_trait_ref.as_ref()?;
1228 if ident == kw::Underscore {
1229 // We do nothing for `_`.
1233 let resolutions = self.r.resolutions(module);
1234 let targets = resolutions
1237 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1238 .filter(|(_, res)| match (kind, res) {
1239 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1240 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1241 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1244 .map(|(key, _)| key.ident.name)
1245 .collect::<Vec<_>>();
1247 find_best_match_for_name(&targets, ident, None)
1250 fn lookup_assoc_candidate<FilterFn>(
1254 filter_fn: FilterFn,
1255 ) -> Option<AssocSuggestion>
1257 FilterFn: Fn(Res) -> bool,
1259 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1261 TyKind::Path(None, _) => Some(t.id),
1262 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1263 // This doesn't handle the remaining `Ty` variants as they are not
1264 // that commonly the self_type, it might be interesting to provide
1265 // support for those in future.
1270 // Fields are generally expected in the same contexts as locals.
1271 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1272 if let Some(node_id) =
1273 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1275 // Look for a field with the same name in the current self_type.
1276 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1277 match resolution.base_res() {
1278 Res::Def(DefKind::Struct | DefKind::Union, did)
1279 if resolution.unresolved_segments() == 0 =>
1281 if let Some(field_names) = self.r.field_names.get(&did) {
1284 .any(|&field_name| ident.name == field_name.node)
1286 return Some(AssocSuggestion::Field);
1296 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1297 for assoc_item in items {
1298 if assoc_item.ident == ident {
1299 return Some(match &assoc_item.kind {
1300 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1301 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1302 AssocSuggestion::MethodWithSelf
1304 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1305 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1306 ast::AssocItemKind::MacCall(_) => continue,
1312 // Look for associated items in the current trait.
1313 if let Some((module, _)) = self.current_trait_ref {
1314 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1315 ModuleOrUniformRoot::Module(module),
1320 let res = binding.res();
1322 if self.r.has_self.contains(&res.def_id()) {
1323 return Some(AssocSuggestion::MethodWithSelf);
1326 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1327 Res::Def(DefKind::AssocConst, _) => {
1328 return Some(AssocSuggestion::AssocConst);
1330 Res::Def(DefKind::AssocTy, _) => {
1331 return Some(AssocSuggestion::AssocType);
1343 fn lookup_typo_candidate(
1347 filter_fn: &impl Fn(Res) -> bool,
1348 ) -> Option<TypoSuggestion> {
1349 let mut names = Vec::new();
1350 if path.len() == 1 {
1351 // Search in lexical scope.
1352 // Walk backwards up the ribs in scope and collect candidates.
1353 for rib in self.ribs[ns].iter().rev() {
1354 // Locals and type parameters
1355 for (ident, &res) in &rib.bindings {
1357 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1361 if let RibKind::ModuleRibKind(module) = rib.kind {
1362 // Items from this module
1363 self.r.add_module_candidates(module, &mut names, &filter_fn);
1365 if let ModuleKind::Block(..) = module.kind {
1366 // We can see through blocks
1368 // Items from the prelude
1369 if !module.no_implicit_prelude {
1370 let extern_prelude = self.r.extern_prelude.clone();
1371 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1372 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1375 Res::Def(DefKind::Mod, crate_id.as_def_id());
1377 if filter_fn(crate_mod) {
1378 Some(TypoSuggestion::typo_from_res(
1379 ident.name, crate_mod,
1388 if let Some(prelude) = self.r.prelude {
1389 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1396 // Add primitive types to the mix
1397 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1398 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1399 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1403 // Search in module.
1404 let mod_path = &path[..path.len() - 1];
1405 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1406 self.resolve_path(mod_path, Some(TypeNS), None)
1408 self.r.add_module_candidates(module, &mut names, &filter_fn);
1412 let name = path[path.len() - 1].ident.name;
1413 // Make sure error reporting is deterministic.
1414 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1416 match find_best_match_for_name(
1417 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1421 Some(found) if found != name => {
1422 names.into_iter().find(|suggestion| suggestion.candidate == found)
1428 // Returns the name of the Rust type approximately corresponding to
1429 // a type name in another programming language.
1430 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1431 let name = path[path.len() - 1].ident.as_str();
1432 // Common Java types
1434 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1435 "short" => sym::i16,
1436 "boolean" => sym::bool,
1439 "float" => sym::f32,
1440 "double" => sym::f64,
1445 /// Only used in a specific case of type ascription suggestions
1446 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1447 let sm = self.r.session.source_map();
1448 start.to(sm.next_point(start))
1451 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1452 let sm = self.r.session.source_map();
1453 let base_snippet = sm.span_to_snippet(base_span);
1454 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1455 if let Ok(snippet) = sm.span_to_snippet(sp) {
1456 let len = snippet.trim_end().len() as u32;
1457 if snippet.trim() == ":" {
1459 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1460 let mut show_label = true;
1461 if sm.is_multiline(sp) {
1462 err.span_suggestion_short(
1464 "maybe you meant to write `;` here",
1466 Applicability::MaybeIncorrect,
1469 let after_colon_sp =
1470 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1471 if snippet.len() == 1 {
1473 err.span_suggestion(
1475 "maybe you meant to write a path separator here",
1477 Applicability::MaybeIncorrect,
1484 .type_ascription_path_suggestions
1488 err.downgrade_to_delayed_bug();
1491 if let Ok(base_snippet) = base_snippet {
1492 let mut sp = after_colon_sp;
1494 // Try to find an assignment
1495 sp = sm.next_point(sp);
1496 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1498 Ok(ref x) if x.as_str() == "=" => {
1499 err.span_suggestion(
1501 "maybe you meant to write an assignment here",
1502 format!("let {}", base_snippet),
1503 Applicability::MaybeIncorrect,
1508 Ok(ref x) if x.as_str() == "\n" => break,
1518 "expecting a type here because of type ascription",
1528 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1529 let mut result = None;
1530 let mut seen_modules = FxHashSet::default();
1531 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1533 while let Some((in_module, path_segments)) = worklist.pop() {
1534 // abort if the module is already found
1535 if result.is_some() {
1539 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1540 // abort if the module is already found or if name_binding is private external
1541 if result.is_some() || !name_binding.vis.is_visible_locally() {
1544 if let Some(module) = name_binding.module() {
1546 let mut path_segments = path_segments.clone();
1547 path_segments.push(ast::PathSegment::from_ident(ident));
1548 let module_def_id = module.def_id();
1549 if module_def_id == def_id {
1551 Path { span: name_binding.span, segments: path_segments, tokens: None };
1563 // add the module to the lookup
1564 if seen_modules.insert(module_def_id) {
1565 worklist.push((module, path_segments));
1575 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1576 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1577 let mut variants = Vec::new();
1578 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1579 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1580 let mut segms = enum_import_suggestion.path.segments.clone();
1581 segms.push(ast::PathSegment::from_ident(ident));
1582 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1583 variants.push((path, def_id, kind));
1590 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1591 fn suggest_using_enum_variant(
1593 err: &mut Diagnostic,
1594 source: PathSource<'_>,
1598 let Some(variants) = self.collect_enum_ctors(def_id) else {
1599 err.note("you might have meant to use one of the enum's variants");
1603 let suggest_only_tuple_variants =
1604 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1605 if suggest_only_tuple_variants {
1606 // Suggest only tuple variants regardless of whether they have fields and do not
1607 // suggest path with added parentheses.
1608 let suggestable_variants = variants
1610 .filter(|(.., kind)| *kind == CtorKind::Fn)
1611 .map(|(variant, ..)| path_names_to_string(variant))
1612 .collect::<Vec<_>>();
1614 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1616 let source_msg = if source.is_call() {
1618 } else if matches!(source, PathSource::TupleStruct(..)) {
1624 if !suggestable_variants.is_empty() {
1625 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1626 format!("try {} the enum's variant", source_msg)
1628 format!("try {} one of the enum's variants", source_msg)
1631 err.span_suggestions(
1634 suggestable_variants.into_iter(),
1635 Applicability::MaybeIncorrect,
1639 // If the enum has no tuple variants..
1640 if non_suggestable_variant_count == variants.len() {
1641 err.help(&format!("the enum has no tuple variants {}", source_msg));
1644 // If there are also non-tuple variants..
1645 if non_suggestable_variant_count == 1 {
1647 "you might have meant {} the enum's non-tuple variant",
1650 } else if non_suggestable_variant_count >= 1 {
1652 "you might have meant {} one of the enum's non-tuple variants",
1657 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1658 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1660 CtorKind::Const => false,
1661 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1666 let mut suggestable_variants = variants
1668 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1669 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1670 .map(|(variant, kind)| match kind {
1671 CtorKind::Const => variant,
1672 CtorKind::Fn => format!("({}())", variant),
1673 CtorKind::Fictive => format!("({} {{}})", variant),
1675 .collect::<Vec<_>>();
1677 if !suggestable_variants.is_empty() {
1678 let msg = if suggestable_variants.len() == 1 {
1679 "you might have meant to use the following enum variant"
1681 "you might have meant to use one of the following enum variants"
1684 err.span_suggestions(
1687 suggestable_variants.drain(..),
1688 Applicability::MaybeIncorrect,
1692 let suggestable_variants_with_placeholders = variants
1694 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1695 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1696 .filter_map(|(variant, kind)| match kind {
1697 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1698 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1701 .collect::<Vec<_>>();
1703 if !suggestable_variants_with_placeholders.is_empty() {
1705 suggestable_variants.is_empty(),
1706 suggestable_variants_with_placeholders.len(),
1708 (true, 1) => "the following enum variant is available",
1709 (true, _) => "the following enum variants are available",
1710 (false, 1) => "alternatively, the following enum variant is available",
1711 (false, _) => "alternatively, the following enum variants are also available",
1714 err.span_suggestions(
1717 suggestable_variants_with_placeholders.into_iter(),
1718 Applicability::HasPlaceholders,
1723 if def_id.is_local() {
1724 if let Some(span) = self.def_span(def_id) {
1725 err.span_note(span, "the enum is defined here");
1730 crate fn report_missing_type_error(
1733 ) -> Option<(Span, &'static str, String, Applicability)> {
1734 let (ident, span) = match path {
1735 [segment] if !segment.has_generic_args => {
1736 (segment.ident.to_string(), segment.ident.span)
1740 let mut iter = ident.chars().map(|c| c.is_uppercase());
1741 let single_uppercase_char =
1742 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1743 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1746 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1747 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1748 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1753 kind @ ItemKind::Fn(..)
1754 | kind @ ItemKind::Enum(..)
1755 | kind @ ItemKind::Struct(..)
1756 | kind @ ItemKind::Union(..),
1761 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1762 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1763 | (Some(Item { kind, .. }), false, _) => {
1764 // Likely missing type parameter.
1765 if let Some(generics) = kind.generics() {
1766 if span.overlaps(generics.span) {
1767 // Avoid the following:
1768 // error[E0405]: cannot find trait `A` in this scope
1769 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1771 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1772 // | ^- help: you might be missing a type parameter: `, A`
1774 // | not found in this scope
1777 let msg = "you might be missing a type parameter";
1778 let (span, sugg) = if let [.., param] = &generics.params[..] {
1779 let span = if let [.., bound] = ¶m.bounds[..] {
1781 } else if let GenericParam {
1782 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1784 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1788 (span, format!(", {}", ident))
1790 (generics.span, format!("<{}>", ident))
1792 // Do not suggest if this is coming from macro expansion.
1793 if span.can_be_used_for_suggestions() {
1795 span.shrink_to_hi(),
1798 Applicability::MaybeIncorrect,
1808 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1809 /// optionally returning the closest match and whether it is reachable.
1810 crate fn suggestion_for_label_in_rib(
1814 ) -> Option<LabelSuggestion> {
1815 // Are ribs from this `rib_index` within scope?
1816 let within_scope = self.is_label_valid_from_rib(rib_index);
1818 let rib = &self.label_ribs[rib_index];
1822 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1823 .map(|(id, _)| id.name)
1824 .collect::<Vec<Symbol>>();
1826 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1827 // Upon finding a similar name, get the ident that it was from - the span
1828 // contained within helps make a useful diagnostic. In addition, determine
1829 // whether this candidate is within scope.
1830 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1831 (*ident, within_scope)
1835 crate fn emit_undeclared_lifetime_error(
1837 lifetime_ref: &ast::Lifetime,
1838 outer_lifetime_ref: Option<Ident>,
1840 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1841 let mut err = if let Some(outer) = outer_lifetime_ref {
1842 let mut err = struct_span_err!(
1844 lifetime_ref.ident.span,
1846 "can't use generic parameters from outer item",
1848 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
1849 err.span_label(outer.span, "lifetime parameter from outer item");
1852 let mut err = struct_span_err!(
1854 lifetime_ref.ident.span,
1856 "use of undeclared lifetime name `{}`",
1859 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
1862 let mut suggest_note = true;
1864 for rib in self.lifetime_ribs.iter().rev() {
1866 LifetimeRibKind::Generics { parent: _, span, kind } => {
1867 if !span.can_be_used_for_suggestions() && suggest_note {
1868 suggest_note = false; // Avoid displaying the same help multiple times.
1872 "lifetime `{}` is missing in item created through this procedural macro",
1879 let higher_ranked = matches!(
1881 LifetimeBinderKind::BareFnType
1882 | LifetimeBinderKind::PolyTrait
1883 | LifetimeBinderKind::WhereBound
1885 let (span, sugg) = if span.is_empty() {
1888 if higher_ranked { "for" } else { "" },
1890 if higher_ranked { " " } else { "" },
1895 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
1896 let sugg = format!("{}, ", lifetime_ref.ident);
1900 err.span_suggestion(
1903 "consider making the {} lifetime-generic with a new `{}` lifetime",
1908 Applicability::MaybeIncorrect,
1911 "for more information on higher-ranked polymorphism, visit \
1912 https://doc.rust-lang.org/nomicon/hrtb.html",
1915 err.span_suggestion(
1917 &format!("consider introducing lifetime `{}` here", lifetime_ref.ident),
1919 Applicability::MaybeIncorrect,
1923 LifetimeRibKind::Item => break,
1931 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
1934 lifetime_ref.ident.span,
1936 "use of non-static lifetime `{}` in const generic",
1940 "for more information, see issue #74052 \
1941 <https://github.com/rust-lang/rust/issues/74052>",
1946 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
1947 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
1948 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
1949 crate fn maybe_emit_forbidden_non_static_lifetime_error(&self, lifetime_ref: &ast::Lifetime) {
1950 let feature_active = self.r.session.features_untracked().generic_const_exprs;
1951 if !feature_active {
1953 &self.r.session.parse_sess,
1954 sym::generic_const_exprs,
1955 lifetime_ref.ident.span,
1956 "a non-static lifetime is not allowed in a `const`",
1963 impl<'tcx> LifetimeContext<'_, 'tcx> {
1964 crate fn report_missing_lifetime_specifiers(
1968 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1973 "missing lifetime specifier{}",
1978 /// Returns whether to add `'static` lifetime to the suggested lifetime list.
1979 crate fn report_elision_failure(
1981 diag: &mut Diagnostic,
1982 params: &[ElisionFailureInfo],
1984 let mut m = String::new();
1985 let len = params.len();
1987 let elided_params: Vec<_> =
1988 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
1990 let elided_len = elided_params.len();
1992 for (i, info) in elided_params.into_iter().enumerate() {
1993 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
1996 diag.span_label(span, "");
1997 let help_name = if let Some(ident) =
1998 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2000 format!("`{}`", ident)
2002 format!("argument {}", index + 1)
2010 "one of {}'s {} {}lifetimes",
2013 if have_bound_regions { "free " } else { "" }
2018 if elided_len == 2 && i == 0 {
2020 } else if i + 2 == elided_len {
2021 m.push_str(", or ");
2022 } else if i != elided_len - 1 {
2029 "this function's return type contains a borrowed value, \
2030 but there is no value for it to be borrowed from",
2033 } else if elided_len == 0 {
2035 "this function's return type contains a borrowed value with \
2036 an elided lifetime, but the lifetime cannot be derived from \
2040 } else if elided_len == 1 {
2042 "this function's return type contains a borrowed value, \
2043 but the signature does not say which {} it is borrowed from",
2049 "this function's return type contains a borrowed value, \
2050 but the signature does not say whether it is borrowed from {}",
2057 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
2058 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
2060 self.tcx.lang_items().fn_once_trait(),
2061 self.tcx.lang_items().fn_trait(),
2062 self.tcx.lang_items().fn_mut_trait(),
2064 .contains(&Some(did))
2066 let (span, span_type) = match &trait_ref.bound_generic_params {
2067 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
2068 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
2070 self.missing_named_lifetime_spots
2071 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
2078 crate fn add_missing_lifetime_specifiers_label(
2080 err: &mut Diagnostic,
2081 mut spans_with_counts: Vec<(Span, usize)>,
2082 lifetime_names: &FxHashSet<Symbol>,
2083 lifetime_spans: Vec<Span>,
2084 params: &[ElisionFailureInfo],
2086 let snippets: Vec<Option<String>> = spans_with_counts
2088 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
2091 // Empty generics are marked with a span of "<", but since from now on
2092 // that information is in the snippets it can be removed from the spans.
2093 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
2094 if snippet.as_deref() == Some("<") {
2095 *span = span.shrink_to_hi();
2099 for &(span, count) in &spans_with_counts {
2103 "expected {} lifetime parameter{}",
2104 if count == 1 { "named".to_string() } else { count.to_string() },
2110 let suggest_existing =
2111 |err: &mut Diagnostic,
2113 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
2114 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
2115 self.missing_named_lifetime_spots.iter().rev().next()
2117 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
2118 // using `'a`, but also introduce the concept of HRLTs by suggesting
2119 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
2120 let mut introduce_suggestion = vec![];
2122 let a_to_z_repeat_n = |n| {
2123 (b'a'..=b'z').map(move |c| {
2124 let mut s = '\''.to_string();
2125 s.extend(std::iter::repeat(char::from(c)).take(n));
2130 // If all single char lifetime names are present, we wrap around and double the chars.
2132 .flat_map(a_to_z_repeat_n)
2133 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
2136 "consider making the {} lifetime-generic with a new `{}` lifetime",
2141 "for more information on higher-ranked polymorphism, visit \
2142 https://doc.rust-lang.org/nomicon/hrtb.html",
2144 let for_sugg = span_type.suggestion(<_name);
2145 for param in params {
2146 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
2148 if snippet.starts_with('&') && !snippet.starts_with("&'") {
2149 introduce_suggestion
2150 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
2151 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
2152 introduce_suggestion
2153 .push((param.span, format!("&{} {}", lt_name, stripped)));
2157 introduce_suggestion.push((*for_span, for_sugg));
2158 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
2159 if let Some(formatter) = formatter {
2160 introduce_suggestion.push((*span, formatter(<_name)));
2163 err.multipart_suggestion_verbose(
2165 introduce_suggestion,
2166 Applicability::MaybeIncorrect,
2170 let spans_suggs: Vec<_> = formatters
2172 .zip(spans_with_counts.iter())
2173 .filter_map(|(formatter, (span, _))| {
2174 if let Some(formatter) = formatter {
2175 Some((*span, formatter(name)))
2181 if spans_suggs.is_empty() {
2182 // If all the spans come from macros, we cannot extract snippets and then
2183 // `formatters` only contains None and `spans_suggs` is empty.
2186 err.multipart_suggestion_verbose(
2188 "consider using the `{}` lifetime",
2189 lifetime_names.iter().next().unwrap()
2192 Applicability::MaybeIncorrect,
2195 let suggest_new = |err: &mut Diagnostic, suggs: Vec<Option<String>>| {
2196 for missing in self.missing_named_lifetime_spots.iter().rev() {
2197 let mut introduce_suggestion = vec![];
2200 introduce_suggestion.push(match missing {
2201 MissingLifetimeSpot::Generics(generics) => {
2202 if generics.span == DUMMY_SP {
2203 // Account for malformed generics in the HIR. This shouldn't happen,
2204 // but if we make a mistake elsewhere, mainly by keeping something in
2205 // `missing_named_lifetime_spots` that we shouldn't, like associated
2206 // `const`s or making a mistake in the AST lowering we would provide
2207 // nonsensical suggestions. Guard against that by skipping these.
2211 msg = "consider introducing a named lifetime parameter".to_string();
2212 should_break = true;
2213 if let Some(param) = generics.params.iter().find(|p| {
2216 hir::GenericParamKind::Type { synthetic: true, .. }
2217 | hir::GenericParamKind::Lifetime {
2218 kind: hir::LifetimeParamKind::Elided
2222 (param.span.shrink_to_lo(), "'a, ".to_string())
2224 (generics.span, "<'a>".to_string())
2227 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2229 "consider making the {} lifetime-generic with a new `'a` lifetime",
2232 should_break = false;
2234 "for more information on higher-ranked polymorphism, visit \
2235 https://doc.rust-lang.org/nomicon/hrtb.html",
2237 (*span, span_type.suggestion("'a"))
2239 MissingLifetimeSpot::Static => {
2240 let mut spans_suggs = Vec::new();
2241 for ((span, count), snippet) in
2242 spans_with_counts.iter().copied().zip(snippets.iter())
2244 let (span, sugg) = match snippet.as_deref() {
2245 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2246 Some("'_") => (span, "'static".to_owned()),
2247 Some(snippet) if !snippet.ends_with('>') => {
2251 std::iter::repeat("'static")
2253 .collect::<Vec<_>>()
2256 } else if snippet == "<" || snippet == "(" {
2258 span.shrink_to_hi(),
2259 std::iter::repeat("'static")
2261 .collect::<Vec<_>>()
2266 span.shrink_to_hi(),
2269 std::iter::repeat("'static")
2271 .collect::<Vec<_>>()
2279 spans_suggs.push((span, sugg.to_string()));
2281 err.multipart_suggestion_verbose(
2282 "consider using the `'static` lifetime",
2284 Applicability::MaybeIncorrect,
2290 struct Lifetime(Span, String);
2292 fn is_unnamed(&self) -> bool {
2293 self.1.starts_with('&') && !self.1.starts_with("&'")
2295 fn is_underscore(&self) -> bool {
2296 self.1.starts_with("&'_ ")
2298 fn is_named(&self) -> bool {
2299 self.1.starts_with("&'")
2301 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2305 self.is_underscore(),
2307 sugg.starts_with('&'),
2309 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2310 (true, _, _, true) => {
2311 (self.span_unnamed_borrow(), sugg[1..].to_string())
2313 (_, true, _, false) => {
2314 (self.span_underscore_borrow(), sugg.trim().to_string())
2316 (_, true, _, true) => {
2317 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2319 (_, _, true, false) => {
2320 (self.span_named_borrow(), sugg.trim().to_string())
2322 (_, _, true, true) => {
2323 (self.span_named_borrow(), sugg[1..].trim().to_string())
2329 fn span_unnamed_borrow(&self) -> Span {
2330 let lo = self.0.lo() + BytePos(1);
2331 self.0.with_lo(lo).with_hi(lo)
2333 fn span_named_borrow(&self) -> Span {
2334 let lo = self.0.lo() + BytePos(1);
2337 fn span_underscore_borrow(&self) -> Span {
2338 let lo = self.0.lo() + BytePos(1);
2339 let hi = lo + BytePos(2);
2340 self.0.with_lo(lo).with_hi(hi)
2344 for param in params {
2345 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2346 if let Some((span, sugg)) =
2347 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2349 introduce_suggestion.push((span, sugg));
2353 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2354 |((span, _), sugg)| match &sugg {
2355 Some(sugg) => Some((span, sugg.to_string())),
2359 let (span, sugg) = self
2363 .span_to_snippet(span)
2365 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2366 .unwrap_or((span, sugg));
2367 introduce_suggestion.push((span, sugg.to_string()));
2369 err.multipart_suggestion_verbose(
2371 introduce_suggestion,
2372 Applicability::MaybeIncorrect,
2380 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2381 match &lifetime_names[..] {
2383 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2384 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2386 suggs.push(match snippet.as_deref() {
2387 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2388 Some("'_") => Some(Box::new(|n| n.to_string())),
2389 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2390 Some("<") => Some(Box::new(move |n| {
2391 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2393 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2397 std::iter::repeat(name.to_string())
2399 .collect::<Vec<_>>()
2406 suggest_existing(err, name.as_str(), suggs);
2409 let mut suggs = Vec::new();
2410 for (snippet, (_, count)) in
2411 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2413 suggs.push(match snippet.as_deref() {
2414 Some("&") => Some("&'a ".to_string()),
2415 Some("'_") => Some("'a".to_string()),
2417 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2420 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2422 Some(snippet) => Some(format!(
2425 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2430 suggest_new(err, suggs);
2432 lts if lts.len() > 1 => {
2433 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2435 let mut spans_suggs: Vec<_> = Vec::new();
2436 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2437 match snippet.as_deref() {
2438 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2439 Some("&") => spans_suggs
2440 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2445 if spans_suggs.len() > 0 {
2446 // This happens when we have `Foo<T>` where we point at the space before `T`,
2447 // but this can be confusing so we give a suggestion with placeholders.
2448 err.multipart_suggestion_verbose(
2449 "consider using one of the available lifetimes here",
2451 Applicability::HasPlaceholders,
2455 _ => unreachable!(),