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_ast::visit::FnKind;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
14 use rustc_hir::def::Namespace::{self, *};
15 use rustc_hir::def::{self, CtorKind, DefKind};
16 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
17 use rustc_hir::PrimTy;
18 use rustc_session::config::nightly_options;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::symbol::{kw, sym, Ident, Symbol};
21 use rustc_span::{BytePos, Span, DUMMY_SP};
25 type Res = def::Res<ast::NodeId>;
27 /// A field or associated item from self type suggested in case of resolution failure.
28 enum AssocSuggestion {
34 crate enum MissingLifetimeSpot<'tcx> {
35 Generics(&'tcx hir::Generics<'tcx>),
36 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
40 crate enum ForLifetimeSpanType {
47 impl ForLifetimeSpanType {
48 crate fn descr(&self) -> &'static str {
50 Self::BoundEmpty | Self::BoundTail => "bound",
51 Self::TypeEmpty | Self::TypeTail => "type",
55 crate fn suggestion(&self, sugg: &str) -> String {
57 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
58 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
63 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
64 fn into(self) -> MissingLifetimeSpot<'tcx> {
65 MissingLifetimeSpot::Generics(self)
69 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
70 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
73 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
74 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
77 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
78 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
79 let variant_path = &suggestion.path;
80 let variant_path_string = path_names_to_string(variant_path);
82 let path_len = suggestion.path.segments.len();
83 let enum_path = ast::Path {
84 span: suggestion.path.span,
85 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
87 let enum_path_string = path_names_to_string(&enum_path);
89 (variant_path_string, enum_path_string)
92 impl<'a> LateResolutionVisitor<'a, '_, '_> {
93 fn def_span(&self, def_id: DefId) -> Option<Span> {
95 LOCAL_CRATE => self.r.opt_span(def_id),
100 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
105 /// Handles error reporting for `smart_resolve_path_fragment` function.
106 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
107 pub(crate) fn smart_resolve_report_errors(
111 source: PathSource<'_>,
113 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
114 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
115 let ns = source.namespace();
116 let is_expected = &|res| source.is_expected(res);
117 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
119 // Make the base error.
120 let expected = source.descr_expected();
121 let path_str = Segment::names_to_string(path);
122 let item_str = path.last().unwrap().ident;
123 let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
125 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
126 format!("not a {}", expected),
129 Res::Def(DefKind::Fn, _) => {
130 // Verify whether this is a fn call or an Fn used as a type.
134 .span_to_snippet(span)
135 .map(|snippet| snippet.ends_with(')'))
139 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
144 | Res::Local(_) => true,
149 let item_span = path.last().unwrap().ident.span;
150 let (mod_prefix, mod_str) = if path.len() == 1 {
151 (String::new(), "this scope".to_string())
152 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
153 (String::new(), "the crate root".to_string())
155 let mod_path = &path[..path.len() - 1];
157 match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
158 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
161 .map_or(String::new(), |res| format!("{} ", res.descr()));
162 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
165 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
166 if path_str == "async" && expected.starts_with("struct") {
167 "`async` blocks are only allowed in the 2018 edition".to_string()
169 format!("not found in {}", mod_str)
176 let code = source.error_code(res.is_some());
177 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
179 let is_assoc_fn = self.self_type_is_available(span);
180 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
181 if ["this", "my"].contains(&&*item_str.as_str()) && is_assoc_fn {
182 err.span_suggestion_short(
184 "you might have meant to use `self` here instead",
186 Applicability::MaybeIncorrect,
188 if !self.self_value_is_available(path[0].ident.span, span) {
189 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
190 &self.diagnostic_metadata.current_function
192 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
193 (param.span.shrink_to_lo(), "&self, ")
199 .span_through_char(*fn_span, '(')
204 err.span_suggestion_verbose(
206 "if you meant to use `self`, you are also missing a `self` receiver \
209 Applicability::MaybeIncorrect,
215 // Emit special messages for unresolved `Self` and `self`.
216 if is_self_type(path, ns) {
217 err.code(rustc_errors::error_code!(E0411));
220 "`Self` is only available in impls, traits, and type definitions".to_string(),
222 return (err, Vec::new());
224 if is_self_value(path, ns) {
225 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
227 err.code(rustc_errors::error_code!(E0424));
228 err.span_label(span, match source {
229 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
231 _ => "`self` value is a keyword only available in methods with a `self` parameter"
234 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
235 // The current function has a `self' parameter, but we were unable to resolve
236 // a reference to `self`. This can only happen if the `self` identifier we
237 // are resolving came from a different hygiene context.
238 if fn_kind.decl().inputs.get(0).map(|p| p.is_self()).unwrap_or(false) {
239 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
241 let doesnt = if is_assoc_fn {
242 let (span, sugg) = fn_kind
246 .map(|p| (p.span.shrink_to_lo(), "&self, "))
252 .span_through_char(*span, '(')
257 err.span_suggestion_verbose(
259 "add a `self` receiver parameter to make the associated `fn` a method",
261 Applicability::MaybeIncorrect,
267 if let Some(ident) = fn_kind.ident() {
270 &format!("this function {} have a `self` parameter", doesnt),
275 return (err, Vec::new());
278 // Try to lookup name in more relaxed fashion for better error reporting.
279 let ident = path.last().unwrap().ident;
280 let candidates = self
282 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
284 .filter(|ImportSuggestion { did, .. }| {
285 match (did, res.and_then(|res| res.opt_def_id())) {
286 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
290 .collect::<Vec<_>>();
291 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
292 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
293 let enum_candidates =
294 self.r.lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant);
296 if !enum_candidates.is_empty() {
297 if let (PathSource::Type, Some(span)) =
298 (source, self.diagnostic_metadata.current_type_ascription.last())
304 .type_ascription_path_suggestions
308 // Already reported this issue on the lhs of the type ascription.
310 return (err, candidates);
314 let mut enum_candidates = enum_candidates
316 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
317 .collect::<Vec<_>>();
318 enum_candidates.sort();
320 // Contextualize for E0412 "cannot find type", but don't belabor the point
321 // (that it's a variant) for E0573 "expected type, found variant".
322 let preamble = if res.is_none() {
323 let others = match enum_candidates.len() {
325 2 => " and 1 other".to_owned(),
326 n => format!(" and {} others", n),
328 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
332 let msg = format!("{}try using the variant's enum", preamble);
334 err.span_suggestions(
339 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
340 // Variants re-exported in prelude doesn't mean `prelude::v1` is the
342 // FIXME: is there a more principled way to do this that
343 // would work for other re-exports?
344 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
345 // Also write `Option` rather than `std::prelude::v1::Option`.
346 .map(|enum_ty_path| {
347 // FIXME #56861: DRY-er prelude filtering.
348 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
350 Applicability::MachineApplicable,
354 if path.len() == 1 && self.self_type_is_available(span) {
355 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
356 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
358 AssocSuggestion::Field => {
359 if self_is_available {
362 "you might have meant to use the available field",
363 format!("self.{}", path_str),
364 Applicability::MachineApplicable,
367 err.span_label(span, "a field by this name exists in `Self`");
370 AssocSuggestion::MethodWithSelf if self_is_available => {
374 format!("self.{}", path_str),
375 Applicability::MachineApplicable,
378 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
382 format!("Self::{}", path_str),
383 Applicability::MachineApplicable,
387 return (err, candidates);
390 // If the first argument in call is `self` suggest calling a method.
391 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
392 let mut args_snippet = String::new();
393 if let Some(args_span) = args_span {
394 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
395 args_snippet = snippet;
401 &format!("try calling `{}` as a method", ident),
402 format!("self.{}({})", path_str, args_snippet),
403 Applicability::MachineApplicable,
405 return (err, candidates);
409 // Try Levenshtein algorithm.
410 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
411 // Try context-dependent help if relaxed lookup didn't work.
412 if let Some(res) = res {
413 if self.smart_resolve_context_dependent_help(
421 // We do this to avoid losing a secondary span when we override the main error span.
422 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
423 return (err, candidates);
427 if !self.type_ascription_suggestion(&mut err, base_span)
428 && !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span)
431 err.span_label(base_span, fallback_label);
433 match self.diagnostic_metadata.current_let_binding {
434 Some((pat_sp, Some(ty_sp), None)) if ty_sp.contains(base_span) && could_be_expr => {
435 err.span_suggestion_short(
436 pat_sp.between(ty_sp),
437 "use `=` if you meant to assign",
439 Applicability::MaybeIncorrect,
448 /// Check if the source is call expression and the first argument is `self`. If true,
449 /// return the span of whole call and the span for all arguments expect the first one (`self`).
450 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
451 let mut has_self_arg = None;
452 if let PathSource::Expr(Some(parent)) = source {
454 ExprKind::Call(_, args) if !args.is_empty() => {
455 let mut expr_kind = &args[0].kind;
458 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
459 if arg_name.segments[0].ident.name == kw::SelfLower {
460 let call_span = parent.span;
461 let tail_args_span = if args.len() > 1 {
464 args.last().unwrap().span.hi(),
470 has_self_arg = Some((call_span, tail_args_span));
474 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
485 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
486 // HACK(estebank): find a better way to figure out that this was a
487 // parser issue where a struct literal is being used on an expression
488 // where a brace being opened means a block is being started. Look
489 // ahead for the next text to see if `span` is followed by a `{`.
490 let sm = self.r.session.source_map();
493 sp = sm.next_point(sp);
494 match sm.span_to_snippet(sp) {
496 if snippet.chars().any(|c| !c.is_whitespace()) {
503 let followed_by_brace = match sm.span_to_snippet(sp) {
504 Ok(ref snippet) if snippet == "{" => true,
507 // In case this could be a struct literal that needs to be surrounded
508 // by parentheses, find the appropriate span.
510 let mut closing_brace = None;
512 sp = sm.next_point(sp);
513 match sm.span_to_snippet(sp) {
516 closing_brace = Some(span.to(sp));
523 // The bigger the span, the more likely we're incorrect --
524 // bound it to 100 chars long.
529 (followed_by_brace, closing_brace)
532 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
534 /// Returns `true` if able to provide context-dependent help.
535 fn smart_resolve_context_dependent_help(
537 err: &mut DiagnosticBuilder<'a>,
539 source: PathSource<'_>,
542 fallback_label: &str,
544 let ns = source.namespace();
545 let is_expected = &|res| source.is_expected(res);
547 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
548 ExprKind::Field(_, ident) => {
551 "use the path separator to refer to an item",
552 format!("{}::{}", path_str, ident),
553 Applicability::MaybeIncorrect,
557 ExprKind::MethodCall(ref segment, ..) => {
558 let span = expr.span.with_hi(segment.ident.span.hi());
561 "use the path separator to refer to an item",
562 format!("{}::{}", path_str, segment.ident),
563 Applicability::MaybeIncorrect,
570 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
571 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
574 PathSource::Expr(Some(
575 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
576 )) if path_sep(err, &parent) => {}
582 | ExprKind::Binary(..)
583 | ExprKind::Unary(..)
585 | ExprKind::While(..)
586 | ExprKind::ForLoop(..)
587 | ExprKind::Match(..),
590 ) if followed_by_brace => {
591 if let Some(sp) = closing_brace {
592 err.span_label(span, fallback_label);
593 err.multipart_suggestion(
594 "surround the struct literal with parentheses",
596 (sp.shrink_to_lo(), "(".to_string()),
597 (sp.shrink_to_hi(), ")".to_string()),
599 Applicability::MaybeIncorrect,
603 span, // Note the parentheses surrounding the suggestion below
605 "you might want to surround a struct literal with parentheses: \
606 `({} {{ /* fields */ }})`?",
612 PathSource::Expr(_) | PathSource::TupleStruct(_) | PathSource::Pat => {
613 let span = match &source {
614 PathSource::Expr(Some(Expr {
615 span, kind: ExprKind::Call(_, _), ..
617 | PathSource::TupleStruct(span) => {
618 // We want the main underline to cover the suggested code as well for
625 if let Some(span) = self.def_span(def_id) {
626 err.span_label(span, &format!("`{}` defined here", path_str));
628 let (tail, descr, applicability) = match source {
629 PathSource::Pat | PathSource::TupleStruct(_) => {
630 ("", "pattern", Applicability::MachineApplicable)
632 _ => (": val", "literal", Applicability::HasPlaceholders),
634 let (fields, applicability) = match self.r.field_names.get(&def_id) {
638 .map(|f| format!("{}{}", f.node, tail))
639 .collect::<Vec<String>>()
643 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
645 let pad = match self.r.field_names.get(&def_id) {
646 Some(fields) if fields.is_empty() => "",
651 &format!("use struct {} syntax instead", descr),
652 format!("{} {{{pad}{}{pad}}}", path_str, fields, pad = pad),
657 err.span_label(span, fallback_label);
662 match (res, source) {
663 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
664 err.span_label(span, fallback_label);
665 err.span_suggestion_verbose(
667 "use `!` to invoke the macro",
669 Applicability::MaybeIncorrect,
671 if path_str == "try" && span.rust_2015() {
672 err.note("if you want the `try` keyword, you need to be in the 2018 edition");
675 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
676 err.span_label(span, "type aliases cannot be used as traits");
677 if nightly_options::is_nightly_build() {
678 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
680 if let Some(span) = self.def_span(def_id) {
681 err.span_help(span, msg);
687 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
688 if !path_sep(err, &parent) {
693 Res::Def(DefKind::Enum, def_id),
694 PathSource::TupleStruct(_) | PathSource::Expr(..),
698 .current_type_ascription
704 .type_ascription_path_suggestions
711 // We already suggested changing `:` into `::` during parsing.
714 if let Some(variants) = self.collect_enum_variants(def_id) {
715 if !variants.is_empty() {
716 let msg = if variants.len() == 1 {
717 "try using the enum's variant"
719 "try using one of the enum's variants"
722 err.span_suggestions(
725 variants.iter().map(path_names_to_string),
726 Applicability::MaybeIncorrect,
730 err.note("you might have meant to use one of the enum's variants");
733 (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
734 if let Some((ctor_def, ctor_vis)) = self.r.struct_constructors.get(&def_id).cloned()
736 let accessible_ctor =
737 self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
738 if is_expected(ctor_def) && !accessible_ctor {
741 "constructor is not visible here due to private fields".to_string(),
745 bad_struct_syntax_suggestion(def_id);
750 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
754 ) if ns == ValueNS => {
755 bad_struct_syntax_suggestion(def_id);
757 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
758 if let Some(span) = self.def_span(def_id) {
759 err.span_label(span, &format!("`{}` defined here", path_str));
762 self.r.field_names.get(&def_id).map_or("/* fields */".to_string(), |fields| {
763 vec!["_"; fields.len()].join(", ")
767 "use the tuple variant pattern syntax instead",
768 format!("{}({})", path_str, fields),
769 Applicability::HasPlaceholders,
772 (Res::SelfTy(..), _) if ns == ValueNS => {
773 err.span_label(span, fallback_label);
774 err.note("can't use `Self` as a constructor, you must use the implemented struct");
776 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
777 err.note("can't use a type alias as a constructor");
784 fn lookup_assoc_candidate<FilterFn>(
789 ) -> Option<AssocSuggestion>
791 FilterFn: Fn(Res) -> bool,
793 fn extract_node_id(t: &Ty) -> Option<NodeId> {
795 TyKind::Path(None, _) => Some(t.id),
796 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
797 // This doesn't handle the remaining `Ty` variants as they are not
798 // that commonly the self_type, it might be interesting to provide
799 // support for those in future.
804 // Fields are generally expected in the same contexts as locals.
805 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
806 if let Some(node_id) =
807 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
809 // Look for a field with the same name in the current self_type.
810 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
811 match resolution.base_res() {
812 Res::Def(DefKind::Struct | DefKind::Union, did)
813 if resolution.unresolved_segments() == 0 =>
815 if let Some(field_names) = self.r.field_names.get(&did) {
818 .any(|&field_name| ident.name == field_name.node)
820 return Some(AssocSuggestion::Field);
830 for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
831 if *assoc_type_ident == ident {
832 return Some(AssocSuggestion::AssocItem);
836 // Look for associated items in the current trait.
837 if let Some((module, _)) = self.current_trait_ref {
838 if let Ok(binding) = self.r.resolve_ident_in_module(
839 ModuleOrUniformRoot::Module(module),
846 let res = binding.res();
848 return Some(if self.r.has_self.contains(&res.def_id()) {
849 AssocSuggestion::MethodWithSelf
851 AssocSuggestion::AssocItem
860 fn lookup_typo_candidate(
864 filter_fn: &impl Fn(Res) -> bool,
866 ) -> Option<TypoSuggestion> {
867 let mut names = Vec::new();
869 // Search in lexical scope.
870 // Walk backwards up the ribs in scope and collect candidates.
871 for rib in self.ribs[ns].iter().rev() {
872 // Locals and type parameters
873 for (ident, &res) in &rib.bindings {
875 names.push(TypoSuggestion::from_res(ident.name, res));
879 if let RibKind::ModuleRibKind(module) = rib.kind {
880 // Items from this module
881 self.r.add_module_candidates(module, &mut names, &filter_fn);
883 if let ModuleKind::Block(..) = module.kind {
884 // We can see through blocks
886 // Items from the prelude
887 if !module.no_implicit_prelude {
888 let extern_prelude = self.r.extern_prelude.clone();
889 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
890 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
892 let crate_mod = Res::Def(
894 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
897 if filter_fn(crate_mod) {
898 Some(TypoSuggestion::from_res(ident.name, crate_mod))
906 if let Some(prelude) = self.r.prelude {
907 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
914 // Add primitive types to the mix
915 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
917 self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
918 TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
924 let mod_path = &path[..path.len() - 1];
925 if let PathResult::Module(module) =
926 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
928 if let ModuleOrUniformRoot::Module(module) = module {
929 self.r.add_module_candidates(module, &mut names, &filter_fn);
934 let name = path[path.len() - 1].ident.name;
935 // Make sure error reporting is deterministic.
936 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
938 match find_best_match_for_name(
939 names.iter().map(|suggestion| &suggestion.candidate),
943 Some(found) if found != name => {
944 names.into_iter().find(|suggestion| suggestion.candidate == found)
950 /// Only used in a specific case of type ascription suggestions
951 fn get_colon_suggestion_span(&self, start: Span) -> Span {
952 let sm = self.r.session.source_map();
953 start.to(sm.next_point(start))
956 fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool {
957 let sm = self.r.session.source_map();
958 let base_snippet = sm.span_to_snippet(base_span);
959 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
960 if let Ok(snippet) = sm.span_to_snippet(sp) {
961 let len = snippet.trim_end().len() as u32;
962 if snippet.trim() == ":" {
964 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
965 let mut show_label = true;
966 if sm.is_multiline(sp) {
967 err.span_suggestion_short(
969 "maybe you meant to write `;` here",
971 Applicability::MaybeIncorrect,
975 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
976 if snippet.len() == 1 {
980 "maybe you meant to write a path separator here",
982 Applicability::MaybeIncorrect,
989 .type_ascription_path_suggestions
996 if let Ok(base_snippet) = base_snippet {
997 let mut sp = after_colon_sp;
999 // Try to find an assignment
1000 sp = sm.next_point(sp);
1001 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1003 Ok(ref x) if x.as_str() == "=" => {
1004 err.span_suggestion(
1006 "maybe you meant to write an assignment here",
1007 format!("let {}", base_snippet),
1008 Applicability::MaybeIncorrect,
1013 Ok(ref x) if x.as_str() == "\n" => break,
1023 "expecting a type here because of type ascription",
1033 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1034 let mut result = None;
1035 let mut seen_modules = FxHashSet::default();
1036 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1038 while let Some((in_module, path_segments)) = worklist.pop() {
1039 // abort if the module is already found
1040 if result.is_some() {
1044 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1045 // abort if the module is already found or if name_binding is private external
1046 if result.is_some() || !name_binding.vis.is_visible_locally() {
1049 if let Some(module) = name_binding.module() {
1051 let mut path_segments = path_segments.clone();
1052 path_segments.push(ast::PathSegment::from_ident(ident));
1053 let module_def_id = module.def_id().unwrap();
1054 if module_def_id == def_id {
1055 let path = Path { span: name_binding.span, segments: path_segments };
1066 // add the module to the lookup
1067 if seen_modules.insert(module_def_id) {
1068 worklist.push((module, path_segments));
1078 fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
1079 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1080 let mut variants = Vec::new();
1081 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1082 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
1083 let mut segms = enum_import_suggestion.path.segments.clone();
1084 segms.push(ast::PathSegment::from_ident(ident));
1085 variants.push(Path { span: name_binding.span, segments: segms });
1092 crate fn report_missing_type_error(
1095 ) -> Option<(Span, &'static str, String, Applicability)> {
1096 let (ident, span) = match path {
1097 [segment] if !segment.has_generic_args => {
1098 (segment.ident.to_string(), segment.ident.span)
1102 let mut iter = ident.chars().map(|c| c.is_uppercase());
1103 let single_uppercase_char =
1104 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1105 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1108 match (self.diagnostic_metadata.current_item, single_uppercase_char) {
1109 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _) if ident.name == sym::main => {
1110 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1115 kind @ ItemKind::Fn(..)
1116 | kind @ ItemKind::Enum(..)
1117 | kind @ ItemKind::Struct(..)
1118 | kind @ ItemKind::Union(..),
1123 | (Some(Item { kind, .. }), false) => {
1124 // Likely missing type parameter.
1125 if let Some(generics) = kind.generics() {
1126 if span.overlaps(generics.span) {
1127 // Avoid the following:
1128 // error[E0405]: cannot find trait `A` in this scope
1129 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1131 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1132 // | ^- help: you might be missing a type parameter: `, A`
1134 // | not found in this scope
1137 let msg = "you might be missing a type parameter";
1138 let (span, sugg) = if let [.., param] = &generics.params[..] {
1139 let span = if let [.., bound] = ¶m.bounds[..] {
1144 (span, format!(", {}", ident))
1146 (generics.span, format!("<{}>", ident))
1148 // Do not suggest if this is coming from macro expansion.
1149 if !span.from_expansion() {
1151 span.shrink_to_hi(),
1154 Applicability::MaybeIncorrect,
1164 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1165 /// optionally returning the closest match and whether it is reachable.
1166 crate fn suggestion_for_label_in_rib(
1170 ) -> Option<LabelSuggestion> {
1171 // Are ribs from this `rib_index` within scope?
1172 let within_scope = self.is_label_valid_from_rib(rib_index);
1174 let rib = &self.label_ribs[rib_index];
1178 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1179 .map(|(id, _)| &id.name);
1181 find_best_match_for_name(names, label.name, None).map(|symbol| {
1182 // Upon finding a similar name, get the ident that it was from - the span
1183 // contained within helps make a useful diagnostic. In addition, determine
1184 // whether this candidate is within scope.
1185 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1186 (*ident, within_scope)
1191 impl<'tcx> LifetimeContext<'_, 'tcx> {
1192 crate fn report_missing_lifetime_specifiers(
1196 ) -> DiagnosticBuilder<'tcx> {
1201 "missing lifetime specifier{}",
1206 crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
1207 let mut err = struct_span_err!(
1211 "use of undeclared lifetime name `{}`",
1214 err.span_label(lifetime_ref.span, "undeclared lifetime");
1215 let mut suggests_in_band = false;
1216 for missing in &self.missing_named_lifetime_spots {
1218 MissingLifetimeSpot::Generics(generics) => {
1219 let (span, sugg) = if let Some(param) =
1220 generics.params.iter().find(|p| match p.kind {
1221 hir::GenericParamKind::Type {
1222 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1227 (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
1229 suggests_in_band = true;
1230 (generics.span, format!("<{}>", lifetime_ref))
1232 err.span_suggestion(
1234 &format!("consider introducing lifetime `{}` here", lifetime_ref),
1236 Applicability::MaybeIncorrect,
1239 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1240 err.span_suggestion(
1243 "consider making the {} lifetime-generic with a new `{}` lifetime",
1247 span_type.suggestion(&lifetime_ref.to_string()),
1248 Applicability::MaybeIncorrect,
1251 "for more information on higher-ranked polymorphism, visit \
1252 https://doc.rust-lang.org/nomicon/hrtb.html",
1258 if nightly_options::is_nightly_build()
1259 && !self.tcx.features().in_band_lifetimes
1263 "if you want to experiment with in-band lifetime bindings, \
1264 add `#![feature(in_band_lifetimes)]` to the crate attributes",
1270 // FIXME(const_generics): This patches over a ICE caused by non-'static lifetimes in const
1271 // generics. We are disallowing this until we can decide on how we want to handle non-'static
1272 // lifetimes in const generics. See issue #74052 for discussion.
1273 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1274 let mut err = struct_span_err!(
1278 "use of non-static lifetime `{}` in const generic",
1282 "for more information, see issue #74052 \
1283 <https://github.com/rust-lang/rust/issues/74052>",
1288 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
1289 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
1291 self.tcx.lang_items().fn_once_trait(),
1292 self.tcx.lang_items().fn_trait(),
1293 self.tcx.lang_items().fn_mut_trait(),
1295 .contains(&Some(did))
1297 let (span, span_type) = match &trait_ref.bound_generic_params {
1298 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
1299 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
1301 self.missing_named_lifetime_spots
1302 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
1309 crate fn add_missing_lifetime_specifiers_label(
1311 err: &mut DiagnosticBuilder<'_>,
1314 lifetime_names: &FxHashSet<Symbol>,
1315 lifetime_spans: Vec<Span>,
1316 params: &[ElisionFailureInfo],
1318 let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok();
1323 "expected {} lifetime parameter{}",
1324 if count == 1 { "named".to_string() } else { count.to_string() },
1329 let suggest_existing = |err: &mut DiagnosticBuilder<'_>,
1331 formatter: &dyn Fn(&str) -> String| {
1332 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
1333 self.missing_named_lifetime_spots.iter().rev().next()
1335 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
1336 // using `'a`, but also introduce the concept of HRLTs by suggesting
1337 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
1338 let mut introduce_suggestion = vec![];
1340 let a_to_z_repeat_n = |n| {
1341 (b'a'..=b'z').map(move |c| {
1342 let mut s = '\''.to_string();
1343 s.extend(std::iter::repeat(char::from(c)).take(n));
1348 // If all single char lifetime names are present, we wrap around and double the chars.
1350 .flat_map(a_to_z_repeat_n)
1351 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
1354 "consider making the {} lifetime-generic with a new `{}` lifetime",
1359 "for more information on higher-ranked polymorphism, visit \
1360 https://doc.rust-lang.org/nomicon/hrtb.html",
1362 let for_sugg = span_type.suggestion(<_name);
1363 for param in params {
1364 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
1365 if snippet.starts_with('&') && !snippet.starts_with("&'") {
1366 introduce_suggestion
1367 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
1368 } else if snippet.starts_with("&'_ ") {
1369 introduce_suggestion
1370 .push((param.span, format!("&{} {}", lt_name, &snippet[4..])));
1374 introduce_suggestion.push((*for_span, for_sugg.to_string()));
1375 introduce_suggestion.push((span, formatter(<_name)));
1376 err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
1379 err.span_suggestion_verbose(
1381 &format!("consider using the `{}` lifetime", lifetime_names.iter().next().unwrap()),
1383 Applicability::MaybeIncorrect,
1386 let suggest_new = |err: &mut DiagnosticBuilder<'_>, sugg: &str| {
1387 for missing in self.missing_named_lifetime_spots.iter().rev() {
1388 let mut introduce_suggestion = vec![];
1391 introduce_suggestion.push(match missing {
1392 MissingLifetimeSpot::Generics(generics) => {
1393 if generics.span == DUMMY_SP {
1394 // Account for malformed generics in the HIR. This shouldn't happen,
1395 // but if we make a mistake elsewhere, mainly by keeping something in
1396 // `missing_named_lifetime_spots` that we shouldn't, like associated
1397 // `const`s or making a mistake in the AST lowering we would provide
1398 // non-sensical suggestions. Guard against that by skipping these.
1402 msg = "consider introducing a named lifetime parameter".to_string();
1403 should_break = true;
1404 if let Some(param) = generics.params.iter().find(|p| match p.kind {
1405 hir::GenericParamKind::Type {
1406 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1411 (param.span.shrink_to_lo(), "'a, ".to_string())
1413 (generics.span, "<'a>".to_string())
1416 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1418 "consider making the {} lifetime-generic with a new `'a` lifetime",
1421 should_break = false;
1423 "for more information on higher-ranked polymorphism, visit \
1424 https://doc.rust-lang.org/nomicon/hrtb.html",
1426 (*span, span_type.suggestion("'a"))
1428 MissingLifetimeSpot::Static => {
1429 let (span, sugg) = match snippet.as_deref() {
1430 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
1431 Some("'_") => (span, "'static".to_owned()),
1432 Some(snippet) if !snippet.ends_with('>') => {
1436 std::iter::repeat("'static")
1438 .collect::<Vec<_>>()
1443 span.shrink_to_hi(),
1446 std::iter::repeat("'static")
1448 .collect::<Vec<_>>()
1456 err.span_suggestion_verbose(
1458 "consider using the `'static` lifetime",
1460 Applicability::MaybeIncorrect,
1465 for param in params {
1466 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
1467 if snippet.starts_with('&') && !snippet.starts_with("&'") {
1468 introduce_suggestion
1469 .push((param.span, format!("&'a {}", &snippet[1..])));
1470 } else if snippet.starts_with("&'_ ") {
1471 introduce_suggestion
1472 .push((param.span, format!("&'a {}", &snippet[4..])));
1476 introduce_suggestion.push((span, sugg.to_string()));
1477 err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
1484 let lifetime_names: Vec<_> = lifetime_names.into_iter().collect();
1485 match (&lifetime_names[..], snippet.as_deref()) {
1486 ([name], Some("&")) => {
1487 suggest_existing(err, &name.as_str()[..], &|name| format!("&{} ", name));
1489 ([name], Some("'_")) => {
1490 suggest_existing(err, &name.as_str()[..], &|n| n.to_string());
1492 ([name], Some("")) => {
1493 suggest_existing(err, &name.as_str()[..], &|n| format!("{}, ", n).repeat(count));
1495 ([name], Some(snippet)) if !snippet.ends_with('>') => {
1496 let f = |name: &str| {
1500 std::iter::repeat(name.to_string())
1502 .collect::<Vec<_>>()
1506 suggest_existing(err, &name.as_str()[..], &f);
1508 ([], Some("&")) if count == 1 => {
1509 suggest_new(err, "&'a ");
1511 ([], Some("'_")) if count == 1 => {
1512 suggest_new(err, "'a");
1514 ([], Some(snippet)) if !snippet.ends_with('>') => {
1516 // This happens when we have `type Bar<'a> = Foo<T>` where we point at the space
1517 // before `T`. We will suggest `type Bar<'a> = Foo<'a, T>`.
1520 &std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""),
1528 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", ")
1533 (lts, ..) if lts.len() > 1 => {
1534 err.span_note(lifetime_spans, "these named lifetimes are available to use");
1535 if Some("") == snippet.as_deref() {
1536 // This happens when we have `Foo<T>` where we point at the space before `T`,
1537 // but this can be confusing so we give a suggestion with placeholders.
1538 err.span_suggestion_verbose(
1540 "consider using one of the available lifetimes here",
1541 "'lifetime, ".repeat(count),
1542 Applicability::HasPlaceholders,