1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{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::ast::{self, Expr, ExprKind, Item, ItemKind, NodeId, Path, Ty, TyKind};
9 use rustc_ast::util::lev_distance::find_best_match_for_name;
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
13 use rustc_hir::def::Namespace::{self, *};
14 use rustc_hir::def::{self, CtorKind, DefKind};
15 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
16 use rustc_hir::PrimTy;
17 use rustc_session::config::nightly_options;
18 use rustc_span::hygiene::MacroKind;
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
20 use rustc_span::{BytePos, Span, DUMMY_SP};
24 type Res = def::Res<ast::NodeId>;
26 /// A field or associated item from self type suggested in case of resolution failure.
27 enum AssocSuggestion {
33 crate enum MissingLifetimeSpot<'tcx> {
34 Generics(&'tcx hir::Generics<'tcx>),
35 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
39 crate enum ForLifetimeSpanType {
46 impl ForLifetimeSpanType {
47 crate fn descr(&self) -> &'static str {
49 Self::BoundEmpty | Self::BoundTail => "bound",
50 Self::TypeEmpty | Self::TypeTail => "type",
54 crate fn suggestion(&self, sugg: &str) -> String {
56 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
57 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
62 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
63 fn into(self) -> MissingLifetimeSpot<'tcx> {
64 MissingLifetimeSpot::Generics(self)
68 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
69 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
72 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
73 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
76 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
77 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
78 let variant_path = &suggestion.path;
79 let variant_path_string = path_names_to_string(variant_path);
81 let path_len = suggestion.path.segments.len();
82 let enum_path = ast::Path {
83 span: suggestion.path.span,
84 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
86 let enum_path_string = path_names_to_string(&enum_path);
88 (variant_path_string, enum_path_string)
91 impl<'a> LateResolutionVisitor<'a, '_, '_> {
92 fn def_span(&self, def_id: DefId) -> Option<Span> {
94 LOCAL_CRATE => self.r.opt_span(def_id),
99 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
104 /// Handles error reporting for `smart_resolve_path_fragment` function.
105 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
106 pub(crate) fn smart_resolve_report_errors(
110 source: PathSource<'_>,
112 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
113 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
114 let ns = source.namespace();
115 let is_expected = &|res| source.is_expected(res);
116 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
118 // Make the base error.
119 let expected = source.descr_expected();
120 let path_str = Segment::names_to_string(path);
121 let item_str = path.last().unwrap().ident;
122 let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
124 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
125 format!("not a {}", expected),
128 Res::Def(DefKind::Fn, _) => {
129 // Verify whether this is a fn call or an Fn used as a type.
133 .span_to_snippet(span)
134 .map(|snippet| snippet.ends_with(')'))
138 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
143 | Res::Local(_) => true,
148 let item_span = path.last().unwrap().ident.span;
149 let (mod_prefix, mod_str) = if path.len() == 1 {
150 (String::new(), "this scope".to_string())
151 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
152 (String::new(), "the crate root".to_string())
154 let mod_path = &path[..path.len() - 1];
156 match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
157 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
160 .map_or(String::new(), |res| format!("{} ", res.descr()));
161 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
164 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
165 if path_str == "async" && expected.starts_with("struct") {
166 "`async` blocks are only allowed in the 2018 edition".to_string()
168 format!("not found in {}", mod_str)
175 let code = source.error_code(res.is_some());
176 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
178 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
179 if ["this", "my"].contains(&&*item_str.as_str())
180 && self.self_value_is_available(path[0].ident.span, span)
182 err.span_suggestion_short(
184 "you might have meant to use `self` here instead",
186 Applicability::MaybeIncorrect,
190 // Emit special messages for unresolved `Self` and `self`.
191 if is_self_type(path, ns) {
192 err.code(rustc_errors::error_code!(E0411));
195 "`Self` is only available in impls, traits, and type definitions".to_string(),
197 return (err, Vec::new());
199 if is_self_value(path, ns) {
200 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
202 err.code(rustc_errors::error_code!(E0424));
203 err.span_label(span, match source {
204 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
206 _ => "`self` value is a keyword only available in methods with a `self` parameter"
209 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
210 // The current function has a `self' parameter, but we were unable to resolve
211 // a reference to `self`. This can only happen if the `self` identifier we
212 // are resolving came from a different hygiene context.
213 if fn_kind.decl().inputs.get(0).map(|p| p.is_self()).unwrap_or(false) {
214 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
216 err.span_label(*span, "this function doesn't have a `self` parameter");
219 return (err, Vec::new());
222 // Try to lookup name in more relaxed fashion for better error reporting.
223 let ident = path.last().unwrap().ident;
224 let candidates = self
226 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
228 .filter(|ImportSuggestion { did, .. }| {
229 match (did, res.and_then(|res| res.opt_def_id())) {
230 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
234 .collect::<Vec<_>>();
235 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
236 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
237 let enum_candidates =
238 self.r.lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant);
240 if !enum_candidates.is_empty() {
241 if let (PathSource::Type, Some(span)) =
242 (source, self.diagnostic_metadata.current_type_ascription.last())
248 .type_ascription_path_suggestions
252 // Already reported this issue on the lhs of the type ascription.
254 return (err, candidates);
258 let mut enum_candidates = enum_candidates
260 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
261 .collect::<Vec<_>>();
262 enum_candidates.sort();
264 // Contextualize for E0412 "cannot find type", but don't belabor the point
265 // (that it's a variant) for E0573 "expected type, found variant".
266 let preamble = if res.is_none() {
267 let others = match enum_candidates.len() {
269 2 => " and 1 other".to_owned(),
270 n => format!(" and {} others", n),
272 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
276 let msg = format!("{}try using the variant's enum", preamble);
278 err.span_suggestions(
283 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
284 // Variants re-exported in prelude doesn't mean `prelude::v1` is the
286 // FIXME: is there a more principled way to do this that
287 // would work for other re-exports?
288 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
289 // Also write `Option` rather than `std::prelude::v1::Option`.
290 .map(|enum_ty_path| {
291 // FIXME #56861: DRY-er prelude filtering.
292 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
294 Applicability::MachineApplicable,
298 if path.len() == 1 && self.self_type_is_available(span) {
299 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
300 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
302 AssocSuggestion::Field => {
303 if self_is_available {
306 "you might have meant to use the available field",
307 format!("self.{}", path_str),
308 Applicability::MachineApplicable,
311 err.span_label(span, "a field by this name exists in `Self`");
314 AssocSuggestion::MethodWithSelf if self_is_available => {
318 format!("self.{}", path_str),
319 Applicability::MachineApplicable,
322 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
326 format!("Self::{}", path_str),
327 Applicability::MachineApplicable,
331 return (err, candidates);
334 // If the first argument in call is `self` suggest calling a method.
335 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
336 let mut args_snippet = String::new();
337 if let Some(args_span) = args_span {
338 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
339 args_snippet = snippet;
345 &format!("try calling `{}` as a method", ident),
346 format!("self.{}({})", path_str, args_snippet),
347 Applicability::MachineApplicable,
349 return (err, candidates);
353 // Try Levenshtein algorithm.
354 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
355 // Try context-dependent help if relaxed lookup didn't work.
356 if let Some(res) = res {
357 if self.smart_resolve_context_dependent_help(
365 // We do this to avoid losing a secondary span when we override the main error span.
366 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
367 return (err, candidates);
371 if !self.type_ascription_suggestion(&mut err, base_span)
372 && !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span)
375 err.span_label(base_span, fallback_label);
377 match self.diagnostic_metadata.current_let_binding {
378 Some((pat_sp, Some(ty_sp), None)) if ty_sp.contains(base_span) && could_be_expr => {
379 err.span_suggestion_short(
380 pat_sp.between(ty_sp),
381 "use `=` if you meant to assign",
383 Applicability::MaybeIncorrect,
392 /// Check if the source is call expression and the first argument is `self`. If true,
393 /// return the span of whole call and the span for all arguments expect the first one (`self`).
394 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
395 let mut has_self_arg = None;
396 if let PathSource::Expr(Some(parent)) = source {
398 ExprKind::Call(_, args) if !args.is_empty() => {
399 let mut expr_kind = &args[0].kind;
402 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
403 if arg_name.segments[0].ident.name == kw::SelfLower {
404 let call_span = parent.span;
405 let tail_args_span = if args.len() > 1 {
408 args.last().unwrap().span.hi(),
414 has_self_arg = Some((call_span, tail_args_span));
418 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
429 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
430 // HACK(estebank): find a better way to figure out that this was a
431 // parser issue where a struct literal is being used on an expression
432 // where a brace being opened means a block is being started. Look
433 // ahead for the next text to see if `span` is followed by a `{`.
434 let sm = self.r.session.source_map();
437 sp = sm.next_point(sp);
438 match sm.span_to_snippet(sp) {
440 if snippet.chars().any(|c| !c.is_whitespace()) {
447 let followed_by_brace = match sm.span_to_snippet(sp) {
448 Ok(ref snippet) if snippet == "{" => true,
451 // In case this could be a struct literal that needs to be surrounded
452 // by parentheses, find the appropriate span.
454 let mut closing_brace = None;
456 sp = sm.next_point(sp);
457 match sm.span_to_snippet(sp) {
460 closing_brace = Some(span.to(sp));
467 // The bigger the span, the more likely we're incorrect --
468 // bound it to 100 chars long.
473 (followed_by_brace, closing_brace)
476 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
478 /// Returns `true` if able to provide context-dependent help.
479 fn smart_resolve_context_dependent_help(
481 err: &mut DiagnosticBuilder<'a>,
483 source: PathSource<'_>,
486 fallback_label: &str,
488 let ns = source.namespace();
489 let is_expected = &|res| source.is_expected(res);
491 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
492 ExprKind::Field(_, ident) => {
495 "use the path separator to refer to an item",
496 format!("{}::{}", path_str, ident),
497 Applicability::MaybeIncorrect,
501 ExprKind::MethodCall(ref segment, ..) => {
502 let span = expr.span.with_hi(segment.ident.span.hi());
505 "use the path separator to refer to an item",
506 format!("{}::{}", path_str, segment.ident),
507 Applicability::MaybeIncorrect,
514 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
515 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
518 PathSource::Expr(Some(
519 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
520 )) if path_sep(err, &parent) => {}
526 | ExprKind::Binary(..)
527 | ExprKind::Unary(..)
529 | ExprKind::While(..)
530 | ExprKind::ForLoop(..)
531 | ExprKind::Match(..),
534 ) if followed_by_brace => {
535 if let Some(sp) = closing_brace {
536 err.span_label(span, fallback_label);
537 err.multipart_suggestion(
538 "surround the struct literal with parentheses",
540 (sp.shrink_to_lo(), "(".to_string()),
541 (sp.shrink_to_hi(), ")".to_string()),
543 Applicability::MaybeIncorrect,
547 span, // Note the parentheses surrounding the suggestion below
549 "you might want to surround a struct literal with parentheses: \
550 `({} {{ /* fields */ }})`?",
556 PathSource::Expr(_) | PathSource::TupleStruct(_) | PathSource::Pat => {
557 let span = match &source {
558 PathSource::Expr(Some(Expr {
559 span, kind: ExprKind::Call(_, _), ..
561 | PathSource::TupleStruct(span) => {
562 // We want the main underline to cover the suggested code as well for
569 if let Some(span) = self.def_span(def_id) {
570 err.span_label(span, &format!("`{}` defined here", path_str));
572 let (tail, descr, applicability) = match source {
573 PathSource::Pat | PathSource::TupleStruct(_) => {
574 ("", "pattern", Applicability::MachineApplicable)
576 _ => (": val", "literal", Applicability::HasPlaceholders),
578 let (fields, applicability) = match self.r.field_names.get(&def_id) {
582 .map(|f| format!("{}{}", f.node, tail))
583 .collect::<Vec<String>>()
587 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
589 let pad = match self.r.field_names.get(&def_id) {
590 Some(fields) if fields.is_empty() => "",
595 &format!("use struct {} syntax instead", descr),
596 format!("{} {{{pad}{}{pad}}}", path_str, fields, pad = pad),
601 err.span_label(span, fallback_label);
606 match (res, source) {
607 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
608 err.span_label(span, fallback_label);
609 err.span_suggestion_verbose(
611 "use `!` to invoke the macro",
613 Applicability::MaybeIncorrect,
615 if path_str == "try" && span.rust_2015() {
616 err.note("if you want the `try` keyword, you need to be in the 2018 edition");
619 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
620 err.span_label(span, "type aliases cannot be used as traits");
621 if nightly_options::is_nightly_build() {
622 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
624 if let Some(span) = self.def_span(def_id) {
625 err.span_help(span, msg);
631 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
632 if !path_sep(err, &parent) {
637 Res::Def(DefKind::Enum, def_id),
638 PathSource::TupleStruct(_) | PathSource::Expr(..),
642 .current_type_ascription
648 .type_ascription_path_suggestions
655 // We already suggested changing `:` into `::` during parsing.
658 if let Some(variants) = self.collect_enum_variants(def_id) {
659 if !variants.is_empty() {
660 let msg = if variants.len() == 1 {
661 "try using the enum's variant"
663 "try using one of the enum's variants"
666 err.span_suggestions(
669 variants.iter().map(path_names_to_string),
670 Applicability::MaybeIncorrect,
674 err.note("you might have meant to use one of the enum's variants");
677 (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
678 if let Some((ctor_def, ctor_vis)) = self.r.struct_constructors.get(&def_id).cloned()
680 let accessible_ctor =
681 self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
682 if is_expected(ctor_def) && !accessible_ctor {
685 "constructor is not visible here due to private fields".to_string(),
689 bad_struct_syntax_suggestion(def_id);
694 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
698 ) if ns == ValueNS => {
699 bad_struct_syntax_suggestion(def_id);
701 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
702 if let Some(span) = self.def_span(def_id) {
703 err.span_label(span, &format!("`{}` defined here", path_str));
706 self.r.field_names.get(&def_id).map_or("/* fields */".to_string(), |fields| {
707 vec!["_"; fields.len()].join(", ")
711 "use the tuple variant pattern syntax instead",
712 format!("{}({})", path_str, fields),
713 Applicability::HasPlaceholders,
716 (Res::SelfTy(..), _) if ns == ValueNS => {
717 err.span_label(span, fallback_label);
718 err.note("can't use `Self` as a constructor, you must use the implemented struct");
720 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
721 err.note("can't use a type alias as a constructor");
728 fn lookup_assoc_candidate<FilterFn>(
733 ) -> Option<AssocSuggestion>
735 FilterFn: Fn(Res) -> bool,
737 fn extract_node_id(t: &Ty) -> Option<NodeId> {
739 TyKind::Path(None, _) => Some(t.id),
740 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
741 // This doesn't handle the remaining `Ty` variants as they are not
742 // that commonly the self_type, it might be interesting to provide
743 // support for those in future.
748 // Fields are generally expected in the same contexts as locals.
749 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
750 if let Some(node_id) =
751 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
753 // Look for a field with the same name in the current self_type.
754 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
755 match resolution.base_res() {
756 Res::Def(DefKind::Struct | DefKind::Union, did)
757 if resolution.unresolved_segments() == 0 =>
759 if let Some(field_names) = self.r.field_names.get(&did) {
762 .any(|&field_name| ident.name == field_name.node)
764 return Some(AssocSuggestion::Field);
774 for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
775 if *assoc_type_ident == ident {
776 return Some(AssocSuggestion::AssocItem);
780 // Look for associated items in the current trait.
781 if let Some((module, _)) = self.current_trait_ref {
782 if let Ok(binding) = self.r.resolve_ident_in_module(
783 ModuleOrUniformRoot::Module(module),
790 let res = binding.res();
792 return Some(if self.r.has_self.contains(&res.def_id()) {
793 AssocSuggestion::MethodWithSelf
795 AssocSuggestion::AssocItem
804 fn lookup_typo_candidate(
808 filter_fn: &impl Fn(Res) -> bool,
810 ) -> Option<TypoSuggestion> {
811 let mut names = Vec::new();
813 // Search in lexical scope.
814 // Walk backwards up the ribs in scope and collect candidates.
815 for rib in self.ribs[ns].iter().rev() {
816 // Locals and type parameters
817 for (ident, &res) in &rib.bindings {
819 names.push(TypoSuggestion::from_res(ident.name, res));
823 if let RibKind::ModuleRibKind(module) = rib.kind {
824 // Items from this module
825 self.r.add_module_candidates(module, &mut names, &filter_fn);
827 if let ModuleKind::Block(..) = module.kind {
828 // We can see through blocks
830 // Items from the prelude
831 if !module.no_implicit_prelude {
832 let extern_prelude = self.r.extern_prelude.clone();
833 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
834 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
836 let crate_mod = Res::Def(
838 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
841 if filter_fn(crate_mod) {
842 Some(TypoSuggestion::from_res(ident.name, crate_mod))
850 if let Some(prelude) = self.r.prelude {
851 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
858 // Add primitive types to the mix
859 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
861 self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
862 TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
868 let mod_path = &path[..path.len() - 1];
869 if let PathResult::Module(module) =
870 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
872 if let ModuleOrUniformRoot::Module(module) = module {
873 self.r.add_module_candidates(module, &mut names, &filter_fn);
878 let name = path[path.len() - 1].ident.name;
879 // Make sure error reporting is deterministic.
880 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
882 match find_best_match_for_name(
883 names.iter().map(|suggestion| &suggestion.candidate),
887 Some(found) if found != name => {
888 names.into_iter().find(|suggestion| suggestion.candidate == found)
894 /// Only used in a specific case of type ascription suggestions
895 fn get_colon_suggestion_span(&self, start: Span) -> Span {
896 let sm = self.r.session.source_map();
897 start.to(sm.next_point(start))
900 fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool {
901 let sm = self.r.session.source_map();
902 let base_snippet = sm.span_to_snippet(base_span);
903 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
904 if let Ok(snippet) = sm.span_to_snippet(sp) {
905 let len = snippet.trim_end().len() as u32;
906 if snippet.trim() == ":" {
908 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
909 let mut show_label = true;
910 if sm.is_multiline(sp) {
911 err.span_suggestion_short(
913 "maybe you meant to write `;` here",
915 Applicability::MaybeIncorrect,
919 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
920 if snippet.len() == 1 {
924 "maybe you meant to write a path separator here",
926 Applicability::MaybeIncorrect,
933 .type_ascription_path_suggestions
940 if let Ok(base_snippet) = base_snippet {
941 let mut sp = after_colon_sp;
943 // Try to find an assignment
944 sp = sm.next_point(sp);
945 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
947 Ok(ref x) if x.as_str() == "=" => {
950 "maybe you meant to write an assignment here",
951 format!("let {}", base_snippet),
952 Applicability::MaybeIncorrect,
957 Ok(ref x) if x.as_str() == "\n" => break,
967 "expecting a type here because of type ascription",
977 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
978 let mut result = None;
979 let mut seen_modules = FxHashSet::default();
980 let mut worklist = vec![(self.r.graph_root, Vec::new())];
982 while let Some((in_module, path_segments)) = worklist.pop() {
983 // abort if the module is already found
984 if result.is_some() {
988 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
989 // abort if the module is already found or if name_binding is private external
990 if result.is_some() || !name_binding.vis.is_visible_locally() {
993 if let Some(module) = name_binding.module() {
995 let mut path_segments = path_segments.clone();
996 path_segments.push(ast::PathSegment::from_ident(ident));
997 let module_def_id = module.def_id().unwrap();
998 if module_def_id == def_id {
999 let path = Path { span: name_binding.span, segments: path_segments };
1010 // add the module to the lookup
1011 if seen_modules.insert(module_def_id) {
1012 worklist.push((module, path_segments));
1022 fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
1023 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1024 let mut variants = Vec::new();
1025 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1026 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
1027 let mut segms = enum_import_suggestion.path.segments.clone();
1028 segms.push(ast::PathSegment::from_ident(ident));
1029 variants.push(Path { span: name_binding.span, segments: segms });
1036 crate fn report_missing_type_error(
1039 ) -> Option<(Span, &'static str, String, Applicability)> {
1040 let (ident, span) = match path {
1041 [segment] if !segment.has_generic_args => {
1042 (segment.ident.to_string(), segment.ident.span)
1046 let mut iter = ident.chars().map(|c| c.is_uppercase());
1047 let single_uppercase_char =
1048 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1049 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1052 match (self.diagnostic_metadata.current_item, single_uppercase_char) {
1053 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _) if ident.name == sym::main => {
1054 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1059 kind @ ItemKind::Fn(..)
1060 | kind @ ItemKind::Enum(..)
1061 | kind @ ItemKind::Struct(..)
1062 | kind @ ItemKind::Union(..),
1067 | (Some(Item { kind, .. }), false) => {
1068 // Likely missing type parameter.
1069 if let Some(generics) = kind.generics() {
1070 if span.overlaps(generics.span) {
1071 // Avoid the following:
1072 // error[E0405]: cannot find trait `A` in this scope
1073 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1075 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1076 // | ^- help: you might be missing a type parameter: `, A`
1078 // | not found in this scope
1081 let msg = "you might be missing a type parameter";
1082 let (span, sugg) = if let [.., param] = &generics.params[..] {
1083 let span = if let [.., bound] = ¶m.bounds[..] {
1088 (span, format!(", {}", ident))
1090 (generics.span, format!("<{}>", ident))
1092 // Do not suggest if this is coming from macro expansion.
1093 if !span.from_expansion() {
1095 span.shrink_to_hi(),
1098 Applicability::MaybeIncorrect,
1108 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1109 /// optionally returning the closest match and whether it is reachable.
1110 crate fn suggestion_for_label_in_rib(
1114 ) -> Option<LabelSuggestion> {
1115 // Are ribs from this `rib_index` within scope?
1116 let within_scope = self.is_label_valid_from_rib(rib_index);
1118 let rib = &self.label_ribs[rib_index];
1122 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1123 .map(|(id, _)| &id.name);
1125 find_best_match_for_name(names, label.name, None).map(|symbol| {
1126 // Upon finding a similar name, get the ident that it was from - the span
1127 // contained within helps make a useful diagnostic. In addition, determine
1128 // whether this candidate is within scope.
1129 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1130 (*ident, within_scope)
1135 impl<'tcx> LifetimeContext<'_, 'tcx> {
1136 crate fn report_missing_lifetime_specifiers(
1140 ) -> DiagnosticBuilder<'tcx> {
1145 "missing lifetime specifier{}",
1150 crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
1151 let mut err = struct_span_err!(
1155 "use of undeclared lifetime name `{}`",
1158 err.span_label(lifetime_ref.span, "undeclared lifetime");
1159 let mut suggests_in_band = false;
1160 for missing in &self.missing_named_lifetime_spots {
1162 MissingLifetimeSpot::Generics(generics) => {
1163 let (span, sugg) = if let Some(param) =
1164 generics.params.iter().find(|p| match p.kind {
1165 hir::GenericParamKind::Type {
1166 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1171 (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
1173 suggests_in_band = true;
1174 (generics.span, format!("<{}>", lifetime_ref))
1176 err.span_suggestion(
1178 &format!("consider introducing lifetime `{}` here", lifetime_ref),
1180 Applicability::MaybeIncorrect,
1183 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1184 err.span_suggestion(
1187 "consider making the {} lifetime-generic with a new `{}` lifetime",
1191 span_type.suggestion(&lifetime_ref.to_string()),
1192 Applicability::MaybeIncorrect,
1195 "for more information on higher-ranked polymorphism, visit \
1196 https://doc.rust-lang.org/nomicon/hrtb.html",
1202 if nightly_options::is_nightly_build()
1203 && !self.tcx.features().in_band_lifetimes
1207 "if you want to experiment with in-band lifetime bindings, \
1208 add `#![feature(in_band_lifetimes)]` to the crate attributes",
1214 // FIXME(const_generics): This patches over a ICE caused by non-'static lifetimes in const
1215 // generics. We are disallowing this until we can decide on how we want to handle non-'static
1216 // lifetimes in const generics. See issue #74052 for discussion.
1217 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1218 let mut err = struct_span_err!(
1222 "use of non-static lifetime `{}` in const generic",
1226 "for more information, see issue #74052 \
1227 <https://github.com/rust-lang/rust/issues/74052>",
1232 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
1233 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
1235 self.tcx.lang_items().fn_once_trait(),
1236 self.tcx.lang_items().fn_trait(),
1237 self.tcx.lang_items().fn_mut_trait(),
1239 .contains(&Some(did))
1241 let (span, span_type) = match &trait_ref.bound_generic_params {
1242 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
1243 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
1245 self.missing_named_lifetime_spots
1246 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
1253 crate fn add_missing_lifetime_specifiers_label(
1255 err: &mut DiagnosticBuilder<'_>,
1258 lifetime_names: &FxHashSet<Symbol>,
1259 lifetime_spans: Vec<Span>,
1260 params: &[ElisionFailureInfo],
1262 let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok();
1267 "expected {} lifetime parameter{}",
1268 if count == 1 { "named".to_string() } else { count.to_string() },
1273 let suggest_existing = |err: &mut DiagnosticBuilder<'_>,
1275 formatter: &dyn Fn(&str) -> String| {
1276 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
1277 self.missing_named_lifetime_spots.iter().rev().next()
1279 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
1280 // using `'a`, but also introduce the concept of HRLTs by suggesting
1281 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
1282 let mut introduce_suggestion = vec![];
1284 let a_to_z_repeat_n = |n| {
1285 (b'a'..=b'z').map(move |c| {
1286 let mut s = '\''.to_string();
1287 s.extend(std::iter::repeat(char::from(c)).take(n));
1292 // If all single char lifetime names are present, we wrap around and double the chars.
1294 .flat_map(a_to_z_repeat_n)
1295 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
1298 "consider making the {} lifetime-generic with a new `{}` lifetime",
1303 "for more information on higher-ranked polymorphism, visit \
1304 https://doc.rust-lang.org/nomicon/hrtb.html",
1306 let for_sugg = span_type.suggestion(<_name);
1307 for param in params {
1308 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
1309 if snippet.starts_with('&') && !snippet.starts_with("&'") {
1310 introduce_suggestion
1311 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
1312 } else if snippet.starts_with("&'_ ") {
1313 introduce_suggestion
1314 .push((param.span, format!("&{} {}", lt_name, &snippet[4..])));
1318 introduce_suggestion.push((*for_span, for_sugg.to_string()));
1319 introduce_suggestion.push((span, formatter(<_name)));
1320 err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
1323 err.span_suggestion_verbose(
1325 &format!("consider using the `{}` lifetime", lifetime_names.iter().next().unwrap()),
1327 Applicability::MaybeIncorrect,
1330 let suggest_new = |err: &mut DiagnosticBuilder<'_>, sugg: &str| {
1331 for missing in self.missing_named_lifetime_spots.iter().rev() {
1332 let mut introduce_suggestion = vec![];
1335 introduce_suggestion.push(match missing {
1336 MissingLifetimeSpot::Generics(generics) => {
1337 if generics.span == DUMMY_SP {
1338 // Account for malformed generics in the HIR. This shouldn't happen,
1339 // but if we make a mistake elsewhere, mainly by keeping something in
1340 // `missing_named_lifetime_spots` that we shouldn't, like associated
1341 // `const`s or making a mistake in the AST lowering we would provide
1342 // non-sensical suggestions. Guard against that by skipping these.
1346 msg = "consider introducing a named lifetime parameter".to_string();
1347 should_break = true;
1348 if let Some(param) = generics.params.iter().find(|p| match p.kind {
1349 hir::GenericParamKind::Type {
1350 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1355 (param.span.shrink_to_lo(), "'a, ".to_string())
1357 (generics.span, "<'a>".to_string())
1360 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1362 "consider making the {} lifetime-generic with a new `'a` lifetime",
1365 should_break = false;
1367 "for more information on higher-ranked polymorphism, visit \
1368 https://doc.rust-lang.org/nomicon/hrtb.html",
1370 (*span, span_type.suggestion("'a"))
1372 MissingLifetimeSpot::Static => {
1373 let (span, sugg) = match snippet.as_deref() {
1374 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
1375 Some("'_") => (span, "'static".to_owned()),
1376 Some(snippet) if !snippet.ends_with('>') => {
1380 std::iter::repeat("'static")
1382 .collect::<Vec<_>>()
1387 span.shrink_to_hi(),
1390 std::iter::repeat("'static")
1392 .collect::<Vec<_>>()
1400 err.span_suggestion_verbose(
1402 "consider using the `'static` lifetime",
1404 Applicability::MaybeIncorrect,
1409 for param in params {
1410 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
1411 if snippet.starts_with('&') && !snippet.starts_with("&'") {
1412 introduce_suggestion
1413 .push((param.span, format!("&'a {}", &snippet[1..])));
1414 } else if snippet.starts_with("&'_ ") {
1415 introduce_suggestion
1416 .push((param.span, format!("&'a {}", &snippet[4..])));
1420 introduce_suggestion.push((span, sugg.to_string()));
1421 err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
1428 let lifetime_names: Vec<_> = lifetime_names.into_iter().collect();
1429 match (&lifetime_names[..], snippet.as_deref()) {
1430 ([name], Some("&")) => {
1431 suggest_existing(err, &name.as_str()[..], &|name| format!("&{} ", name));
1433 ([name], Some("'_")) => {
1434 suggest_existing(err, &name.as_str()[..], &|n| n.to_string());
1436 ([name], Some("")) => {
1437 suggest_existing(err, &name.as_str()[..], &|n| format!("{}, ", n).repeat(count));
1439 ([name], Some(snippet)) if !snippet.ends_with('>') => {
1440 let f = |name: &str| {
1444 std::iter::repeat(name.to_string())
1446 .collect::<Vec<_>>()
1450 suggest_existing(err, &name.as_str()[..], &f);
1452 ([], Some("&")) if count == 1 => {
1453 suggest_new(err, "&'a ");
1455 ([], Some("'_")) if count == 1 => {
1456 suggest_new(err, "'a");
1458 ([], Some(snippet)) if !snippet.ends_with('>') => {
1460 // This happens when we have `type Bar<'a> = Foo<T>` where we point at the space
1461 // before `T`. We will suggest `type Bar<'a> = Foo<'a, T>`.
1464 &std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""),
1472 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", ")
1477 (lts, ..) if lts.len() > 1 => {
1478 err.span_note(lifetime_spans, "these named lifetimes are available to use");
1479 if Some("") == snippet.as_deref() {
1480 // This happens when we have `Foo<T>` where we point at the space before `T`,
1481 // but this can be confusing so we give a suggestion with placeholders.
1482 err.span_suggestion_verbose(
1484 "consider using one of the available lifetimes here",
1485 "'lifetime, ".repeat(count),
1486 Applicability::HasPlaceholders,