1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
4 use crate::path_names_to_string;
5 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
6 use crate::{PathResult, PathSource, Segment};
8 use rustc_ast::visit::FnKind;
10 self as ast, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind, NodeId, Path, Ty,
13 use rustc_ast_pretty::pprust::path_segment_to_string;
14 use rustc_data_structures::fx::FxHashSet;
15 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, SuggestionStyle};
17 use rustc_hir::def::Namespace::{self, *};
18 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
19 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
20 use rustc_hir::PrimTy;
21 use rustc_session::parse::feature_err;
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::MacroKind;
24 use rustc_span::lev_distance::find_best_match_for_name;
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
32 type Res = def::Res<ast::NodeId>;
34 /// A field or associated item from self type suggested in case of resolution failure.
35 enum AssocSuggestion {
43 impl AssocSuggestion {
44 fn action(&self) -> &'static str {
46 AssocSuggestion::Field => "use the available field",
47 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
48 AssocSuggestion::AssocFn => "call the associated function",
49 AssocSuggestion::AssocConst => "use the associated `const`",
50 AssocSuggestion::AssocType => "use the associated type",
55 crate enum MissingLifetimeSpot<'tcx> {
56 Generics(&'tcx hir::Generics<'tcx>),
57 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
61 crate enum ForLifetimeSpanType {
68 impl ForLifetimeSpanType {
69 crate fn descr(&self) -> &'static str {
71 Self::BoundEmpty | Self::BoundTail => "bound",
72 Self::TypeEmpty | Self::TypeTail => "type",
76 crate fn suggestion(&self, sugg: &str) -> String {
78 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
79 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
84 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
85 fn into(self) -> MissingLifetimeSpot<'tcx> {
86 MissingLifetimeSpot::Generics(self)
90 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
91 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
94 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
95 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
98 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
99 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
100 let variant_path = &suggestion.path;
101 let variant_path_string = path_names_to_string(variant_path);
103 let path_len = suggestion.path.segments.len();
104 let enum_path = ast::Path {
105 span: suggestion.path.span,
106 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
109 let enum_path_string = path_names_to_string(&enum_path);
111 (variant_path_string, enum_path_string)
114 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
115 fn def_span(&self, def_id: DefId) -> Option<Span> {
117 LOCAL_CRATE => self.r.opt_span(def_id),
122 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
127 /// Handles error reporting for `smart_resolve_path_fragment` function.
128 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
129 pub(crate) fn smart_resolve_report_errors(
133 source: PathSource<'_>,
135 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
136 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
137 let ns = source.namespace();
138 let is_expected = &|res| source.is_expected(res);
139 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
141 // Make the base error.
142 let mut expected = source.descr_expected();
143 let path_str = Segment::names_to_string(path);
144 let item_str = path.last().unwrap().ident;
145 let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
147 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
148 format!("not a {}", expected),
151 Res::Def(DefKind::Fn, _) => {
152 // Verify whether this is a fn call or an Fn used as a type.
156 .span_to_snippet(span)
157 .map(|snippet| snippet.ends_with(')'))
161 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
166 | Res::Local(_) => true,
171 let item_span = path.last().unwrap().ident.span;
172 let (mod_prefix, mod_str) = if path.len() == 1 {
173 (String::new(), "this scope".to_string())
174 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
175 if self.r.session.edition() > Edition::Edition2015 {
176 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
177 // which overrides all other expectations of item type
179 (String::new(), "the list of imported crates".to_string())
181 (String::new(), "the crate root".to_string())
183 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
184 (String::new(), "the crate root".to_string())
186 let mod_path = &path[..path.len() - 1];
188 match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
189 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
192 .map_or_else(String::new, |res| format!("{} ", res.descr()));
193 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
196 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
197 if path_str == "async" && expected.starts_with("struct") {
198 "`async` blocks are only allowed in Rust 2018 or later".to_string()
200 format!("not found in {}", mod_str)
207 let code = source.error_code(res.is_some());
208 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
210 match (source, self.diagnostic_metadata.in_if_condition) {
211 (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => {
212 err.span_suggestion_verbose(
214 "you might have meant to use pattern matching",
216 Applicability::MaybeIncorrect,
222 let is_assoc_fn = self.self_type_is_available(span);
223 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
224 if ["this", "my"].contains(&&*item_str.as_str()) && is_assoc_fn {
225 err.span_suggestion_short(
227 "you might have meant to use `self` here instead",
229 Applicability::MaybeIncorrect,
231 if !self.self_value_is_available(path[0].ident.span, span) {
232 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
233 &self.diagnostic_metadata.current_function
235 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
236 (param.span.shrink_to_lo(), "&self, ")
242 .span_through_char(*fn_span, '(')
247 err.span_suggestion_verbose(
249 "if you meant to use `self`, you are also missing a `self` receiver \
252 Applicability::MaybeIncorrect,
258 // Emit special messages for unresolved `Self` and `self`.
259 if is_self_type(path, ns) {
260 err.code(rustc_errors::error_code!(E0411));
263 "`Self` is only available in impls, traits, and type definitions".to_string(),
265 return (err, Vec::new());
267 if is_self_value(path, ns) {
268 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
270 err.code(rustc_errors::error_code!(E0424));
271 err.span_label(span, match source {
272 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
274 _ => "`self` value is a keyword only available in methods with a `self` parameter"
277 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
278 // The current function has a `self' parameter, but we were unable to resolve
279 // a reference to `self`. This can only happen if the `self` identifier we
280 // are resolving came from a different hygiene context.
281 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
282 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
284 let doesnt = if is_assoc_fn {
285 let (span, sugg) = fn_kind
289 .map(|p| (p.span.shrink_to_lo(), "&self, "))
295 .span_through_char(*span, '(')
300 err.span_suggestion_verbose(
302 "add a `self` receiver parameter to make the associated `fn` a method",
304 Applicability::MaybeIncorrect,
310 if let Some(ident) = fn_kind.ident() {
313 &format!("this function {} have a `self` parameter", doesnt),
318 return (err, Vec::new());
321 // Try to lookup name in more relaxed fashion for better error reporting.
322 let ident = path.last().unwrap().ident;
323 let candidates = self
325 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
327 .filter(|ImportSuggestion { did, .. }| {
328 match (did, res.and_then(|res| res.opt_def_id())) {
329 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
333 .collect::<Vec<_>>();
334 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
335 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
336 let mut enum_candidates: Vec<_> = self
338 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
340 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
341 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
343 if !enum_candidates.is_empty() {
344 if let (PathSource::Type, Some(span)) =
345 (source, self.diagnostic_metadata.current_type_ascription.last())
351 .type_ascription_path_suggestions
355 // Already reported this issue on the lhs of the type ascription.
357 return (err, candidates);
361 enum_candidates.sort();
363 // Contextualize for E0412 "cannot find type", but don't belabor the point
364 // (that it's a variant) for E0573 "expected type, found variant".
365 let preamble = if res.is_none() {
366 let others = match enum_candidates.len() {
368 2 => " and 1 other".to_owned(),
369 n => format!(" and {} others", n),
371 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
375 let msg = format!("{}try using the variant's enum", preamble);
377 err.span_suggestions(
380 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
381 Applicability::MachineApplicable,
385 if path.len() == 1 && self.self_type_is_available(span) {
386 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
387 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
389 AssocSuggestion::Field => {
390 if self_is_available {
393 "you might have meant to use the available field",
394 format!("self.{}", path_str),
395 Applicability::MachineApplicable,
398 err.span_label(span, "a field by this name exists in `Self`");
401 AssocSuggestion::MethodWithSelf if self_is_available => {
404 "you might have meant to call the method",
405 format!("self.{}", path_str),
406 Applicability::MachineApplicable,
409 AssocSuggestion::MethodWithSelf
410 | AssocSuggestion::AssocFn
411 | AssocSuggestion::AssocConst
412 | AssocSuggestion::AssocType => {
415 &format!("you might have meant to {}", candidate.action()),
416 format!("Self::{}", path_str),
417 Applicability::MachineApplicable,
421 return (err, candidates);
424 // If the first argument in call is `self` suggest calling a method.
425 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
426 let mut args_snippet = String::new();
427 if let Some(args_span) = args_span {
428 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
429 args_snippet = snippet;
435 &format!("try calling `{}` as a method", ident),
436 format!("self.{}({})", path_str, args_snippet),
437 Applicability::MachineApplicable,
439 return (err, candidates);
443 // Try Levenshtein algorithm.
444 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
445 // Try context-dependent help if relaxed lookup didn't work.
446 if let Some(res) = res {
447 if self.smart_resolve_context_dependent_help(
455 // We do this to avoid losing a secondary span when we override the main error span.
456 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
457 return (err, candidates);
461 let is_macro = base_span.from_expansion() && base_span.desugaring_kind().is_none();
462 if !self.type_ascription_suggestion(&mut err, base_span) {
463 let mut fallback = false;
465 PathSource::Trait(AliasPossibility::Maybe),
466 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
468 ) = (source, res, is_macro)
470 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
472 let spans: Vec<Span> = bounds
474 .map(|bound| bound.span())
475 .filter(|&sp| sp != base_span)
478 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
479 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
480 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
481 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
482 let last_bound_span = spans.last().cloned().unwrap();
483 let mut multi_span: MultiSpan = spans.clone().into();
485 let msg = if sp == last_bound_span {
487 "...because of {} bound{}",
488 if bounds.len() <= 2 { "this" } else { "these" },
489 if bounds.len() <= 2 { "" } else { "s" },
494 multi_span.push_span_label(sp, msg);
496 multi_span.push_span_label(
498 "expected this type to be a trait...".to_string(),
502 "`+` is used to constrain a \"trait object\" type with lifetimes or \
503 auto-traits; structs and enums can't be bound in that way",
505 if bounds.iter().all(|bound| match bound {
506 ast::GenericBound::Outlives(_) => true,
507 ast::GenericBound::Trait(tr, _) => tr.span == base_span,
509 let mut sugg = vec![];
510 if base_span != start_span {
511 sugg.push((start_span.until(base_span), String::new()));
513 if base_span != end_span {
514 sugg.push((base_span.shrink_to_hi().to(end_span), String::new()));
517 err.multipart_suggestion(
518 "if you meant to use a type and not a trait here, remove the bounds",
520 Applicability::MaybeIncorrect,
526 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
528 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
530 match self.diagnostic_metadata.current_let_binding {
531 Some((pat_sp, Some(ty_sp), None))
532 if ty_sp.contains(base_span) && could_be_expr =>
534 err.span_suggestion_short(
535 pat_sp.between(ty_sp),
536 "use `=` if you meant to assign",
538 Applicability::MaybeIncorrect,
544 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
545 let suggestion = self.get_single_associated_item(&path, span, &source, is_expected);
546 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
550 err.span_label(base_span, fallback_label);
553 if let Some(err_code) = &err.code {
554 if err_code == &rustc_errors::error_code!(E0425) {
555 for label_rib in &self.label_ribs {
556 for (label_ident, node_id) in &label_rib.bindings {
557 if format!("'{}", ident) == label_ident.to_string() {
558 err.span_label(label_ident.span, "a label with a similar name exists");
559 if let PathSource::Expr(Some(Expr {
560 kind: ExprKind::Break(None, Some(_)),
566 "use the similarly named label",
567 label_ident.name.to_string(),
568 Applicability::MaybeIncorrect,
570 // Do not lint against unused label when we suggest them.
571 self.diagnostic_metadata.unused_labels.remove(node_id);
576 } else if err_code == &rustc_errors::error_code!(E0412) {
577 if let Some(correct) = Self::likely_rust_type(path) {
580 "perhaps you intended to use this type",
582 Applicability::MaybeIncorrect,
591 fn get_single_associated_item(
595 source: &PathSource<'_>,
596 filter_fn: &impl Fn(Res) -> bool,
597 ) -> Option<TypoSuggestion> {
598 if let crate::PathSource::TraitItem(_) = source {
599 let mod_path = &path[..path.len() - 1];
600 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
601 self.resolve_path(mod_path, None, false, span, CrateLint::No)
603 let resolutions = self.r.resolutions(module).borrow();
604 let targets: Vec<_> =
607 .filter_map(|(key, resolution)| {
608 resolution.borrow().binding.map(|binding| binding.res()).and_then(
609 |res| if filter_fn(res) { Some((key, res)) } else { None },
613 if targets.len() == 1 {
614 let target = targets[0];
615 return Some(TypoSuggestion::single_item_from_res(
625 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
626 fn restrict_assoc_type_in_where_clause(
629 err: &mut DiagnosticBuilder<'_>,
631 // Detect that we are actually in a `where` predicate.
632 let (bounded_ty, bounds, where_span) =
633 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
635 bound_generic_params,
638 })) = self.diagnostic_metadata.current_where_predicate
640 if !bound_generic_params.is_empty() {
643 (bounded_ty, bounds, span)
648 // Confirm that the target is an associated type.
649 let (ty, position, path) = if let ast::TyKind::Path(
650 Some(ast::QSelf { ty, position, .. }),
654 // use this to verify that ident is a type param.
655 let partial_res = if let Ok(Some(partial_res)) = self.resolve_qpath_anywhere(
658 &Segment::from_path(path),
669 partial_res.base_res(),
670 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
671 ) && partial_res.unresolved_segments() == 0)
680 if let ast::TyKind::Path(None, type_param_path) = &ty.peel_refs().kind {
681 // Confirm that the `SelfTy` is a type parameter.
682 let partial_res = if let Ok(Some(partial_res)) = self.resolve_qpath_anywhere(
685 &Segment::from_path(type_param_path),
696 partial_res.base_res(),
697 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
698 ) && partial_res.unresolved_segments() == 0)
703 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
704 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
705 ) = (&type_param_path.segments[..], &bounds[..])
707 if let [ast::PathSegment { ident, args: None, .. }] =
708 &poly_trait_ref.trait_ref.path.segments[..]
710 if ident.span == span {
711 err.span_suggestion_verbose(
713 &format!("constrain the associated type to `{}`", ident),
719 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
720 .unwrap_or_else(|_| constrain_ident.to_string()),
721 path.segments[..*position]
723 .map(|segment| path_segment_to_string(segment))
726 path.segments[*position..]
728 .map(|segment| path_segment_to_string(segment))
733 Applicability::MaybeIncorrect,
743 /// Check if the source is call expression and the first argument is `self`. If true,
744 /// return the span of whole call and the span for all arguments expect the first one (`self`).
745 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
746 let mut has_self_arg = None;
747 if let PathSource::Expr(Some(parent)) = source {
749 ExprKind::Call(_, args) if !args.is_empty() => {
750 let mut expr_kind = &args[0].kind;
753 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
754 if arg_name.segments[0].ident.name == kw::SelfLower {
755 let call_span = parent.span;
756 let tail_args_span = if args.len() > 1 {
759 args.last().unwrap().span.hi(),
765 has_self_arg = Some((call_span, tail_args_span));
769 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
780 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
781 // HACK(estebank): find a better way to figure out that this was a
782 // parser issue where a struct literal is being used on an expression
783 // where a brace being opened means a block is being started. Look
784 // ahead for the next text to see if `span` is followed by a `{`.
785 let sm = self.r.session.source_map();
788 sp = sm.next_point(sp);
789 match sm.span_to_snippet(sp) {
791 if snippet.chars().any(|c| !c.is_whitespace()) {
798 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
799 // In case this could be a struct literal that needs to be surrounded
800 // by parentheses, find the appropriate span.
802 let mut closing_brace = None;
804 sp = sm.next_point(sp);
805 match sm.span_to_snippet(sp) {
808 closing_brace = Some(span.to(sp));
815 // The bigger the span, the more likely we're incorrect --
816 // bound it to 100 chars long.
821 (followed_by_brace, closing_brace)
824 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
826 /// Returns `true` if able to provide context-dependent help.
827 fn smart_resolve_context_dependent_help(
829 err: &mut DiagnosticBuilder<'a>,
831 source: PathSource<'_>,
834 fallback_label: &str,
836 let ns = source.namespace();
837 let is_expected = &|res| source.is_expected(res);
839 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
840 ExprKind::Field(_, ident) => {
843 "use the path separator to refer to an item",
844 format!("{}::{}", path_str, ident),
845 Applicability::MaybeIncorrect,
849 ExprKind::MethodCall(ref segment, ..) => {
850 let span = expr.span.with_hi(segment.ident.span.hi());
853 "use the path separator to refer to an item",
854 format!("{}::{}", path_str, segment.ident),
855 Applicability::MaybeIncorrect,
862 let find_span = |source: &PathSource<'_>, err: &mut DiagnosticBuilder<'_>| {
864 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
865 | PathSource::TupleStruct(span, _) => {
866 // We want the main underline to cover the suggested code as well for
875 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
876 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
879 PathSource::Expr(Some(
880 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
881 )) if path_sep(err, &parent) => {}
887 | ExprKind::Binary(..)
888 | ExprKind::Unary(..)
890 | ExprKind::While(..)
891 | ExprKind::ForLoop(..)
892 | ExprKind::Match(..),
895 ) if followed_by_brace => {
896 if let Some(sp) = closing_brace {
897 err.span_label(span, fallback_label);
898 err.multipart_suggestion(
899 "surround the struct literal with parentheses",
901 (sp.shrink_to_lo(), "(".to_string()),
902 (sp.shrink_to_hi(), ")".to_string()),
904 Applicability::MaybeIncorrect,
908 span, // Note the parentheses surrounding the suggestion below
910 "you might want to surround a struct literal with parentheses: \
911 `({} {{ /* fields */ }})`?",
917 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
918 let span = find_span(&source, err);
919 if let Some(span) = self.def_span(def_id) {
920 err.span_label(span, &format!("`{}` defined here", path_str));
922 let (tail, descr, applicability) = match source {
923 PathSource::Pat | PathSource::TupleStruct(..) => {
924 ("", "pattern", Applicability::MachineApplicable)
926 _ => (": val", "literal", Applicability::HasPlaceholders),
928 let (fields, applicability) = match self.r.field_names.get(&def_id) {
932 .map(|f| format!("{}{}", f.node, tail))
933 .collect::<Vec<String>>()
937 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
939 let pad = match self.r.field_names.get(&def_id) {
940 Some(fields) if fields.is_empty() => "",
945 &format!("use struct {} syntax instead", descr),
946 format!("{path_str} {{{pad}{fields}{pad}}}"),
951 err.span_label(span, fallback_label);
956 match (res, source) {
957 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
958 err.span_label(span, fallback_label);
959 err.span_suggestion_verbose(
961 "use `!` to invoke the macro",
963 Applicability::MaybeIncorrect,
965 if path_str == "try" && span.rust_2015() {
966 err.note("if you want the `try` keyword, you need Rust 2018 or later");
969 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
970 err.span_label(span, "type aliases cannot be used as traits");
971 if self.r.session.is_nightly_build() {
972 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
974 if let Some(span) = self.def_span(def_id) {
975 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
976 // The span contains a type alias so we should be able to
977 // replace `type` with `trait`.
978 let snip = snip.replacen("type", "trait", 1);
979 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
981 err.span_help(span, msg);
988 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
989 if !path_sep(err, &parent) {
994 Res::Def(DefKind::Enum, def_id),
995 PathSource::TupleStruct(..) | PathSource::Expr(..),
999 .current_type_ascription
1005 .type_ascription_path_suggestions
1012 // We already suggested changing `:` into `::` during parsing.
1016 self.suggest_using_enum_variant(err, source, def_id, span);
1018 (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
1019 let (ctor_def, ctor_vis, fields) =
1020 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1023 bad_struct_syntax_suggestion(def_id);
1027 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1028 if !is_expected(ctor_def) || is_accessible {
1032 let field_spans = match source {
1033 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1034 PathSource::TupleStruct(_, pattern_spans) => {
1035 err.set_primary_message(
1036 "cannot match against a tuple struct which contains private fields",
1039 // Use spans of the tuple struct pattern.
1040 Some(Vec::from(pattern_spans))
1042 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1043 _ if source.is_call() => {
1044 err.set_primary_message(
1045 "cannot initialize a tuple struct which contains private fields",
1048 // Use spans of the tuple struct definition.
1052 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1057 if let Some(spans) =
1058 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1060 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1061 .filter(|(vis, _)| {
1062 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1064 .map(|(_, span)| *span)
1067 if non_visible_spans.len() > 0 {
1068 let mut m: rustc_span::MultiSpan = non_visible_spans.clone().into();
1071 .for_each(|s| m.push_span_label(s, "private field".to_string()));
1072 err.span_note(m, "constructor is not visible here due to private fields");
1080 "constructor is not visible here due to private fields".to_string(),
1085 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1089 ) if ns == ValueNS => {
1090 bad_struct_syntax_suggestion(def_id);
1092 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1094 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1095 let span = find_span(&source, err);
1096 if let Some(span) = self.def_span(def_id) {
1097 err.span_label(span, &format!("`{}` defined here", path_str));
1099 err.span_suggestion(
1101 &"use this syntax instead",
1102 format!("{path_str}"),
1103 Applicability::MaybeIncorrect,
1109 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1110 if let Some(span) = self.def_span(def_id) {
1111 err.span_label(span, &format!("`{}` defined here", path_str));
1113 let fields = self.r.field_names.get(&def_id).map_or_else(
1114 || "/* fields */".to_string(),
1115 |fields| vec!["_"; fields.len()].join(", "),
1117 err.span_suggestion(
1119 "use the tuple variant pattern syntax instead",
1120 format!("{}({})", path_str, fields),
1121 Applicability::HasPlaceholders,
1124 (Res::SelfTy(..), _) if ns == ValueNS => {
1125 err.span_label(span, fallback_label);
1126 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1128 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1129 err.note("can't use a type alias as a constructor");
1136 fn lookup_assoc_candidate<FilterFn>(
1140 filter_fn: FilterFn,
1141 ) -> Option<AssocSuggestion>
1143 FilterFn: Fn(Res) -> bool,
1145 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1147 TyKind::Path(None, _) => Some(t.id),
1148 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1149 // This doesn't handle the remaining `Ty` variants as they are not
1150 // that commonly the self_type, it might be interesting to provide
1151 // support for those in future.
1156 // Fields are generally expected in the same contexts as locals.
1157 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1158 if let Some(node_id) =
1159 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1161 // Look for a field with the same name in the current self_type.
1162 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1163 match resolution.base_res() {
1164 Res::Def(DefKind::Struct | DefKind::Union, did)
1165 if resolution.unresolved_segments() == 0 =>
1167 if let Some(field_names) = self.r.field_names.get(&did) {
1170 .any(|&field_name| ident.name == field_name.node)
1172 return Some(AssocSuggestion::Field);
1182 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1183 for assoc_item in items {
1184 if assoc_item.ident == ident {
1185 return Some(match &assoc_item.kind {
1186 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1187 ast::AssocItemKind::Fn(box ast::FnKind(_, sig, ..))
1188 if sig.decl.has_self() =>
1190 AssocSuggestion::MethodWithSelf
1192 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1193 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1194 ast::AssocItemKind::MacCall(_) => continue,
1200 // Look for associated items in the current trait.
1201 if let Some((module, _)) = self.current_trait_ref {
1202 if let Ok(binding) = self.r.resolve_ident_in_module(
1203 ModuleOrUniformRoot::Module(module),
1210 let res = binding.res();
1212 if self.r.has_self.contains(&res.def_id()) {
1213 return Some(AssocSuggestion::MethodWithSelf);
1216 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1217 Res::Def(DefKind::AssocConst, _) => {
1218 return Some(AssocSuggestion::AssocConst);
1220 Res::Def(DefKind::AssocTy, _) => {
1221 return Some(AssocSuggestion::AssocType);
1233 fn lookup_typo_candidate(
1237 filter_fn: &impl Fn(Res) -> bool,
1239 ) -> Option<TypoSuggestion> {
1240 let mut names = Vec::new();
1241 if path.len() == 1 {
1242 // Search in lexical scope.
1243 // Walk backwards up the ribs in scope and collect candidates.
1244 for rib in self.ribs[ns].iter().rev() {
1245 // Locals and type parameters
1246 for (ident, &res) in &rib.bindings {
1248 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1252 if let RibKind::ModuleRibKind(module) = rib.kind {
1253 // Items from this module
1254 self.r.add_module_candidates(module, &mut names, &filter_fn);
1256 if let ModuleKind::Block(..) = module.kind {
1257 // We can see through blocks
1259 // Items from the prelude
1260 if !module.no_implicit_prelude {
1261 let extern_prelude = self.r.extern_prelude.clone();
1262 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1263 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1265 let crate_mod = Res::Def(
1267 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
1270 if filter_fn(crate_mod) {
1271 Some(TypoSuggestion::typo_from_res(
1272 ident.name, crate_mod,
1281 if let Some(prelude) = self.r.prelude {
1282 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1289 // Add primitive types to the mix
1290 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1291 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1292 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1296 // Search in module.
1297 let mod_path = &path[..path.len() - 1];
1298 if let PathResult::Module(module) =
1299 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
1301 if let ModuleOrUniformRoot::Module(module) = module {
1302 self.r.add_module_candidates(module, &mut names, &filter_fn);
1307 let name = path[path.len() - 1].ident.name;
1308 // Make sure error reporting is deterministic.
1309 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
1311 match find_best_match_for_name(
1312 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1316 Some(found) if found != name => {
1317 names.into_iter().find(|suggestion| suggestion.candidate == found)
1323 // Returns the name of the Rust type approximately corresponding to
1324 // a type name in another programming language.
1325 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1326 let name = path[path.len() - 1].ident.as_str();
1327 // Common Java types
1329 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1330 "short" => sym::i16,
1331 "boolean" => sym::bool,
1334 "float" => sym::f32,
1335 "double" => sym::f64,
1340 /// Only used in a specific case of type ascription suggestions
1341 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1342 let sm = self.r.session.source_map();
1343 start.to(sm.next_point(start))
1346 fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool {
1347 let sm = self.r.session.source_map();
1348 let base_snippet = sm.span_to_snippet(base_span);
1349 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1350 if let Ok(snippet) = sm.span_to_snippet(sp) {
1351 let len = snippet.trim_end().len() as u32;
1352 if snippet.trim() == ":" {
1354 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1355 let mut show_label = true;
1356 if sm.is_multiline(sp) {
1357 err.span_suggestion_short(
1359 "maybe you meant to write `;` here",
1361 Applicability::MaybeIncorrect,
1364 let after_colon_sp =
1365 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1366 if snippet.len() == 1 {
1368 err.span_suggestion(
1370 "maybe you meant to write a path separator here",
1372 Applicability::MaybeIncorrect,
1379 .type_ascription_path_suggestions
1386 if let Ok(base_snippet) = base_snippet {
1387 let mut sp = after_colon_sp;
1389 // Try to find an assignment
1390 sp = sm.next_point(sp);
1391 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1393 Ok(ref x) if x.as_str() == "=" => {
1394 err.span_suggestion(
1396 "maybe you meant to write an assignment here",
1397 format!("let {}", base_snippet),
1398 Applicability::MaybeIncorrect,
1403 Ok(ref x) if x.as_str() == "\n" => break,
1413 "expecting a type here because of type ascription",
1423 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1424 let mut result = None;
1425 let mut seen_modules = FxHashSet::default();
1426 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1428 while let Some((in_module, path_segments)) = worklist.pop() {
1429 // abort if the module is already found
1430 if result.is_some() {
1434 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1435 // abort if the module is already found or if name_binding is private external
1436 if result.is_some() || !name_binding.vis.is_visible_locally() {
1439 if let Some(module) = name_binding.module() {
1441 let mut path_segments = path_segments.clone();
1442 path_segments.push(ast::PathSegment::from_ident(ident));
1443 let module_def_id = module.def_id().unwrap();
1444 if module_def_id == def_id {
1446 Path { span: name_binding.span, segments: path_segments, tokens: None };
1457 // add the module to the lookup
1458 if seen_modules.insert(module_def_id) {
1459 worklist.push((module, path_segments));
1469 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1470 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1471 let mut variants = Vec::new();
1472 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1473 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1474 let mut segms = enum_import_suggestion.path.segments.clone();
1475 segms.push(ast::PathSegment::from_ident(ident));
1476 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1477 variants.push((path, def_id, kind));
1484 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1485 fn suggest_using_enum_variant(
1487 err: &mut DiagnosticBuilder<'a>,
1488 source: PathSource<'_>,
1492 let variants = match self.collect_enum_ctors(def_id) {
1493 Some(variants) => variants,
1495 err.note("you might have meant to use one of the enum's variants");
1500 let suggest_only_tuple_variants =
1501 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1502 if suggest_only_tuple_variants {
1503 // Suggest only tuple variants regardless of whether they have fields and do not
1504 // suggest path with added parenthesis.
1505 let mut suggestable_variants = variants
1507 .filter(|(.., kind)| *kind == CtorKind::Fn)
1508 .map(|(variant, ..)| path_names_to_string(variant))
1509 .collect::<Vec<_>>();
1511 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1513 let source_msg = if source.is_call() {
1515 } else if matches!(source, PathSource::TupleStruct(..)) {
1521 if !suggestable_variants.is_empty() {
1522 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1523 format!("try {} the enum's variant", source_msg)
1525 format!("try {} one of the enum's variants", source_msg)
1528 err.span_suggestions(
1531 suggestable_variants.drain(..),
1532 Applicability::MaybeIncorrect,
1536 // If the enum has no tuple variants..
1537 if non_suggestable_variant_count == variants.len() {
1538 err.help(&format!("the enum has no tuple variants {}", source_msg));
1541 // If there are also non-tuple variants..
1542 if non_suggestable_variant_count == 1 {
1544 "you might have meant {} the enum's non-tuple variant",
1547 } else if non_suggestable_variant_count >= 1 {
1549 "you might have meant {} one of the enum's non-tuple variants",
1554 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1555 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1557 CtorKind::Const => false,
1558 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1563 let mut suggestable_variants = variants
1565 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1566 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1567 .map(|(variant, kind)| match kind {
1568 CtorKind::Const => variant,
1569 CtorKind::Fn => format!("({}())", variant),
1570 CtorKind::Fictive => format!("({} {{}})", variant),
1572 .collect::<Vec<_>>();
1574 if !suggestable_variants.is_empty() {
1575 let msg = if suggestable_variants.len() == 1 {
1576 "you might have meant to use the following enum variant"
1578 "you might have meant to use one of the following enum variants"
1581 err.span_suggestions(
1584 suggestable_variants.drain(..),
1585 Applicability::MaybeIncorrect,
1589 let mut suggestable_variants_with_placeholders = variants
1591 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1592 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1593 .filter_map(|(variant, kind)| match kind {
1594 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1595 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1598 .collect::<Vec<_>>();
1600 if !suggestable_variants_with_placeholders.is_empty() {
1602 suggestable_variants.is_empty(),
1603 suggestable_variants_with_placeholders.len(),
1605 (true, 1) => "the following enum variant is available",
1606 (true, _) => "the following enum variants are available",
1607 (false, 1) => "alternatively, the following enum variant is available",
1608 (false, _) => "alternatively, the following enum variants are also available",
1611 err.span_suggestions(
1614 suggestable_variants_with_placeholders.drain(..),
1615 Applicability::HasPlaceholders,
1620 if def_id.is_local() {
1621 if let Some(span) = self.def_span(def_id) {
1622 err.span_note(span, "the enum is defined here");
1627 crate fn report_missing_type_error(
1630 ) -> Option<(Span, &'static str, String, Applicability)> {
1631 let (ident, span) = match path {
1632 [segment] if !segment.has_generic_args => {
1633 (segment.ident.to_string(), segment.ident.span)
1637 let mut iter = ident.chars().map(|c| c.is_uppercase());
1638 let single_uppercase_char =
1639 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1640 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1643 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1644 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1645 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1650 kind @ ItemKind::Fn(..)
1651 | kind @ ItemKind::Enum(..)
1652 | kind @ ItemKind::Struct(..)
1653 | kind @ ItemKind::Union(..),
1658 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1659 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1660 | (Some(Item { kind, .. }), false, _) => {
1661 // Likely missing type parameter.
1662 if let Some(generics) = kind.generics() {
1663 if span.overlaps(generics.span) {
1664 // Avoid the following:
1665 // error[E0405]: cannot find trait `A` in this scope
1666 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1668 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1669 // | ^- help: you might be missing a type parameter: `, A`
1671 // | not found in this scope
1674 let msg = "you might be missing a type parameter";
1675 let (span, sugg) = if let [.., param] = &generics.params[..] {
1676 let span = if let [.., bound] = ¶m.bounds[..] {
1678 } else if let GenericParam {
1679 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1681 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1685 (span, format!(", {}", ident))
1687 (generics.span, format!("<{}>", ident))
1689 // Do not suggest if this is coming from macro expansion.
1690 if !span.from_expansion() {
1692 span.shrink_to_hi(),
1695 Applicability::MaybeIncorrect,
1705 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1706 /// optionally returning the closest match and whether it is reachable.
1707 crate fn suggestion_for_label_in_rib(
1711 ) -> Option<LabelSuggestion> {
1712 // Are ribs from this `rib_index` within scope?
1713 let within_scope = self.is_label_valid_from_rib(rib_index);
1715 let rib = &self.label_ribs[rib_index];
1719 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1720 .map(|(id, _)| id.name)
1721 .collect::<Vec<Symbol>>();
1723 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1724 // Upon finding a similar name, get the ident that it was from - the span
1725 // contained within helps make a useful diagnostic. In addition, determine
1726 // whether this candidate is within scope.
1727 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1728 (*ident, within_scope)
1733 impl<'tcx> LifetimeContext<'_, 'tcx> {
1734 crate fn report_missing_lifetime_specifiers(
1738 ) -> DiagnosticBuilder<'tcx> {
1743 "missing lifetime specifier{}",
1748 crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
1749 let mut err = struct_span_err!(
1753 "use of undeclared lifetime name `{}`",
1756 err.span_label(lifetime_ref.span, "undeclared lifetime");
1757 let mut suggests_in_band = false;
1758 let mut suggest_note = true;
1759 for missing in &self.missing_named_lifetime_spots {
1761 MissingLifetimeSpot::Generics(generics) => {
1762 let (span, sugg) = if let Some(param) = generics.params.iter().find(|p| {
1765 hir::GenericParamKind::Type {
1766 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1768 } | hir::GenericParamKind::Lifetime {
1769 kind: hir::LifetimeParamKind::Elided,
1773 (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
1775 suggests_in_band = true;
1776 (generics.span, format!("<{}>", lifetime_ref))
1778 if !span.from_expansion() {
1779 err.span_suggestion(
1781 &format!("consider introducing lifetime `{}` here", lifetime_ref),
1783 Applicability::MaybeIncorrect,
1785 } else if suggest_note {
1786 suggest_note = false; // Avoid displaying the same help multiple times.
1790 "lifetime `{}` is missing in item created through this procedural \
1797 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1798 err.span_suggestion(
1801 "consider making the {} lifetime-generic with a new `{}` lifetime",
1805 span_type.suggestion(&lifetime_ref.to_string()),
1806 Applicability::MaybeIncorrect,
1809 "for more information on higher-ranked polymorphism, visit \
1810 https://doc.rust-lang.org/nomicon/hrtb.html",
1816 if self.tcx.sess.is_nightly_build()
1817 && !self.tcx.features().in_band_lifetimes
1821 "if you want to experiment with in-band lifetime bindings, \
1822 add `#![feature(in_band_lifetimes)]` to the crate attributes",
1828 // FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
1829 // generics. We are disallowing this until we can decide on how we want to handle non-'static
1830 // lifetimes in const generics. See issue #74052 for discussion.
1831 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1832 let mut err = struct_span_err!(
1836 "use of non-static lifetime `{}` in const generic",
1840 "for more information, see issue #74052 \
1841 <https://github.com/rust-lang/rust/issues/74052>",
1846 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
1847 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
1849 self.tcx.lang_items().fn_once_trait(),
1850 self.tcx.lang_items().fn_trait(),
1851 self.tcx.lang_items().fn_mut_trait(),
1853 .contains(&Some(did))
1855 let (span, span_type) = match &trait_ref.bound_generic_params {
1856 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
1857 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
1859 self.missing_named_lifetime_spots
1860 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
1867 crate fn add_missing_lifetime_specifiers_label(
1869 err: &mut DiagnosticBuilder<'_>,
1870 mut spans_with_counts: Vec<(Span, usize)>,
1871 lifetime_names: &FxHashSet<Symbol>,
1872 lifetime_spans: Vec<Span>,
1873 params: &[ElisionFailureInfo],
1875 let snippets: Vec<Option<String>> = spans_with_counts
1877 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
1880 // Empty generics are marked with a span of "<", but since from now on
1881 // that information is in the snippets it can be removed from the spans.
1882 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
1883 if snippet.as_deref() == Some("<") {
1884 *span = span.shrink_to_hi();
1888 for &(span, count) in &spans_with_counts {
1892 "expected {} lifetime parameter{}",
1893 if count == 1 { "named".to_string() } else { count.to_string() },
1899 let suggest_existing =
1900 |err: &mut DiagnosticBuilder<'_>,
1902 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
1903 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
1904 self.missing_named_lifetime_spots.iter().rev().next()
1906 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
1907 // using `'a`, but also introduce the concept of HRLTs by suggesting
1908 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
1909 let mut introduce_suggestion = vec![];
1911 let a_to_z_repeat_n = |n| {
1912 (b'a'..=b'z').map(move |c| {
1913 let mut s = '\''.to_string();
1914 s.extend(std::iter::repeat(char::from(c)).take(n));
1919 // If all single char lifetime names are present, we wrap around and double the chars.
1921 .flat_map(a_to_z_repeat_n)
1922 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
1925 "consider making the {} lifetime-generic with a new `{}` lifetime",
1930 "for more information on higher-ranked polymorphism, visit \
1931 https://doc.rust-lang.org/nomicon/hrtb.html",
1933 let for_sugg = span_type.suggestion(<_name);
1934 for param in params {
1935 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
1937 if snippet.starts_with('&') && !snippet.starts_with("&'") {
1938 introduce_suggestion
1939 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
1940 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
1941 introduce_suggestion
1942 .push((param.span, format!("&{} {}", lt_name, stripped)));
1946 introduce_suggestion.push((*for_span, for_sugg));
1947 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
1948 if let Some(formatter) = formatter {
1949 introduce_suggestion.push((*span, formatter(<_name)));
1952 err.multipart_suggestion_with_style(
1954 introduce_suggestion,
1955 Applicability::MaybeIncorrect,
1956 SuggestionStyle::ShowAlways,
1960 let spans_suggs: Vec<_> = formatters
1962 .zip(spans_with_counts.iter())
1963 .filter_map(|(fmt, (span, _))| {
1964 if let Some(formatter) = fmt { Some((formatter, span)) } else { None }
1966 .map(|(formatter, span)| (*span, formatter(name)))
1968 err.multipart_suggestion_with_style(
1970 "consider using the `{}` lifetime",
1971 lifetime_names.iter().next().unwrap()
1974 Applicability::MaybeIncorrect,
1975 SuggestionStyle::ShowAlways,
1978 let suggest_new = |err: &mut DiagnosticBuilder<'_>, suggs: Vec<Option<String>>| {
1979 for missing in self.missing_named_lifetime_spots.iter().rev() {
1980 let mut introduce_suggestion = vec![];
1983 introduce_suggestion.push(match missing {
1984 MissingLifetimeSpot::Generics(generics) => {
1985 if generics.span == DUMMY_SP {
1986 // Account for malformed generics in the HIR. This shouldn't happen,
1987 // but if we make a mistake elsewhere, mainly by keeping something in
1988 // `missing_named_lifetime_spots` that we shouldn't, like associated
1989 // `const`s or making a mistake in the AST lowering we would provide
1990 // non-sensical suggestions. Guard against that by skipping these.
1994 msg = "consider introducing a named lifetime parameter".to_string();
1995 should_break = true;
1996 if let Some(param) = generics.params.iter().find(|p| {
1999 hir::GenericParamKind::Type {
2000 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
2002 } | hir::GenericParamKind::Lifetime {
2003 kind: hir::LifetimeParamKind::Elided
2007 (param.span.shrink_to_lo(), "'a, ".to_string())
2009 (generics.span, "<'a>".to_string())
2012 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2014 "consider making the {} lifetime-generic with a new `'a` lifetime",
2017 should_break = false;
2019 "for more information on higher-ranked polymorphism, visit \
2020 https://doc.rust-lang.org/nomicon/hrtb.html",
2022 (*span, span_type.suggestion("'a"))
2024 MissingLifetimeSpot::Static => {
2025 let mut spans_suggs = Vec::new();
2026 for ((span, count), snippet) in
2027 spans_with_counts.iter().copied().zip(snippets.iter())
2029 let (span, sugg) = match snippet.as_deref() {
2030 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2031 Some("'_") => (span, "'static".to_owned()),
2032 Some(snippet) if !snippet.ends_with('>') => {
2036 std::iter::repeat("'static")
2038 .collect::<Vec<_>>()
2041 } else if snippet == "<" || snippet == "(" {
2043 span.shrink_to_hi(),
2044 std::iter::repeat("'static")
2046 .collect::<Vec<_>>()
2051 span.shrink_to_hi(),
2054 std::iter::repeat("'static")
2056 .collect::<Vec<_>>()
2064 spans_suggs.push((span, sugg.to_string()));
2066 err.multipart_suggestion_with_style(
2067 "consider using the `'static` lifetime",
2069 Applicability::MaybeIncorrect,
2070 SuggestionStyle::ShowAlways,
2076 struct Lifetime(Span, String);
2078 fn is_unnamed(&self) -> bool {
2079 self.1.starts_with('&') && !self.1.starts_with("&'")
2081 fn is_underscore(&self) -> bool {
2082 self.1.starts_with("&'_ ")
2084 fn is_named(&self) -> bool {
2085 self.1.starts_with("&'")
2087 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2091 self.is_underscore(),
2093 sugg.starts_with("&"),
2095 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2096 (true, _, _, true) => {
2097 (self.span_unnamed_borrow(), sugg[1..].to_string())
2099 (_, true, _, false) => {
2100 (self.span_underscore_borrow(), sugg.trim().to_string())
2102 (_, true, _, true) => {
2103 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2105 (_, _, true, false) => {
2106 (self.span_named_borrow(), sugg.trim().to_string())
2108 (_, _, true, true) => {
2109 (self.span_named_borrow(), sugg[1..].trim().to_string())
2115 fn span_unnamed_borrow(&self) -> Span {
2116 let lo = self.0.lo() + BytePos(1);
2117 self.0.with_lo(lo).with_hi(lo)
2119 fn span_named_borrow(&self) -> Span {
2120 let lo = self.0.lo() + BytePos(1);
2123 fn span_underscore_borrow(&self) -> Span {
2124 let lo = self.0.lo() + BytePos(1);
2125 let hi = lo + BytePos(2);
2126 self.0.with_lo(lo).with_hi(hi)
2130 for param in params {
2131 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2132 if let Some((span, sugg)) =
2133 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2135 introduce_suggestion.push((span, sugg));
2139 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2140 |((span, _), sugg)| match &sugg {
2141 Some(sugg) => Some((span, sugg.to_string())),
2145 let (span, sugg) = self
2149 .span_to_snippet(span)
2151 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2152 .unwrap_or((span, sugg));
2153 introduce_suggestion.push((span, sugg.to_string()));
2155 err.multipart_suggestion_with_style(
2157 introduce_suggestion,
2158 Applicability::MaybeIncorrect,
2159 SuggestionStyle::ShowAlways,
2167 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2168 match &lifetime_names[..] {
2170 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2171 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2173 suggs.push(match snippet.as_deref() {
2174 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2175 Some("'_") => Some(Box::new(|n| n.to_string())),
2176 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2177 Some("<") => Some(Box::new(move |n| {
2178 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2180 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2184 std::iter::repeat(name.to_string())
2186 .collect::<Vec<_>>()
2193 suggest_existing(err, &name.as_str()[..], suggs);
2196 let mut suggs = Vec::new();
2197 for (snippet, (_, count)) in
2198 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2200 suggs.push(match snippet.as_deref() {
2201 Some("&") => Some("&'a ".to_string()),
2202 Some("'_") => Some("'a".to_string()),
2204 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2207 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2209 Some(snippet) => Some(format!(
2212 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2217 suggest_new(err, suggs);
2219 lts if lts.len() > 1 => {
2220 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2222 let mut spans_suggs: Vec<_> = Vec::new();
2223 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2224 match snippet.as_deref() {
2225 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2226 Some("&") => spans_suggs
2227 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2232 if spans_suggs.len() > 0 {
2233 // This happens when we have `Foo<T>` where we point at the space before `T`,
2234 // but this can be confusing so we give a suggestion with placeholders.
2235 err.multipart_suggestion_with_style(
2236 "consider using one of the available lifetimes here",
2238 Applicability::HasPlaceholders,
2239 SuggestionStyle::ShowAlways,
2243 _ => unreachable!(),
2247 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2248 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2249 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2250 crate fn maybe_emit_forbidden_non_static_lifetime_error(
2252 body_id: hir::BodyId,
2253 lifetime_ref: &'tcx hir::Lifetime,
2255 let is_anon_const = matches!(
2256 self.tcx.def_kind(self.tcx.hir().body_owner_def_id(body_id)),
2257 hir::def::DefKind::AnonConst
2259 let is_allowed_lifetime = matches!(
2261 hir::LifetimeName::Implicit | hir::LifetimeName::Static | hir::LifetimeName::Underscore
2264 if !self.tcx.lazy_normalization() && is_anon_const && !is_allowed_lifetime {
2266 &self.tcx.sess.parse_sess,
2267 sym::generic_const_exprs,
2269 "a non-static lifetime is not allowed in a `const`",