4 use rustc_ast::visit::{self, Visitor};
5 use rustc_ast::{self as ast, Crate, ItemKind, ModKind, NodeId, Path, CRATE_NODE_ID};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::struct_span_err;
9 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan};
10 use rustc_feature::BUILTIN_ATTRIBUTES;
11 use rustc_hir::def::Namespace::{self, *};
12 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
13 use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE};
14 use rustc_hir::PrimTy;
15 use rustc_middle::bug;
16 use rustc_middle::ty::DefIdTree;
17 use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE;
18 use rustc_session::lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS;
19 use rustc_session::lint::BuiltinLintDiagnostics;
20 use rustc_session::Session;
21 use rustc_span::edition::Edition;
22 use rustc_span::hygiene::MacroKind;
23 use rustc_span::lev_distance::find_best_match_for_name;
24 use rustc_span::source_map::SourceMap;
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, Span};
29 use crate::imports::{Import, ImportKind, ImportResolver};
31 use crate::path_names_to_string;
32 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
33 use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot};
34 use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
35 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet};
36 use crate::{Segment, UseError};
38 type Res = def::Res<ast::NodeId>;
40 /// A vector of spans and replacements, a message and applicability.
41 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
43 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
44 /// similarly named label and whether or not it is reachable.
45 crate type LabelSuggestion = (Ident, bool);
47 crate enum SuggestionTarget {
48 /// The target has a similar name as the name used by the programmer (probably a typo)
50 /// The target is the only valid item that can be used in the corresponding context
54 crate struct TypoSuggestion {
55 pub candidate: Symbol,
57 pub target: SuggestionTarget,
61 crate fn typo_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
62 Self { candidate, res, target: SuggestionTarget::SimilarlyNamed }
64 crate fn single_item_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
65 Self { candidate, res, target: SuggestionTarget::SingleItem }
69 /// A free importable items suggested in case of resolution failure.
70 crate struct ImportSuggestion {
71 pub did: Option<DefId>,
72 pub descr: &'static str,
75 /// An extra note that should be issued if this item is suggested
76 pub note: Option<String>,
79 /// Adjust the impl span so that just the `impl` keyword is taken by removing
80 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
81 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
83 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
84 /// parser. If you need to use this function or something similar, please consider updating the
85 /// `source_map` functions and this function to something more robust.
86 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
87 let impl_span = sm.span_until_char(impl_span, '<');
88 sm.span_until_whitespace(impl_span)
91 impl<'a> Resolver<'a> {
92 crate fn report_errors(&mut self, krate: &Crate) {
93 self.report_with_use_injections(krate);
95 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
96 let msg = "macro-expanded `macro_export` macros from the current crate \
97 cannot be referred to by absolute paths";
98 self.lint_buffer.buffer_lint_with_diagnostic(
99 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
103 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
107 for ambiguity_error in &self.ambiguity_errors {
108 self.report_ambiguity_error(ambiguity_error);
111 let mut reported_spans = FxHashSet::default();
112 for error in &self.privacy_errors {
113 if reported_spans.insert(error.dedup_span) {
114 self.report_privacy_error(error);
119 fn report_with_use_injections(&mut self, krate: &Crate) {
120 for UseError { mut err, candidates, def_id, instead, suggestion } in
121 self.use_injections.drain(..)
123 let (span, found_use) = if let Some(def_id) = def_id.as_local() {
124 UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id])
128 if !candidates.is_empty() {
138 } else if let Some((span, msg, sugg, appl)) = suggestion {
139 err.span_suggestion(span, msg, sugg, appl);
145 crate fn report_conflict<'b>(
150 new_binding: &NameBinding<'b>,
151 old_binding: &NameBinding<'b>,
153 // Error on the second of two conflicting names
154 if old_binding.span.lo() > new_binding.span.lo() {
155 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
158 let container = match parent.kind {
159 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
160 ModuleKind::Block(..) => "block",
163 let old_noun = match old_binding.is_import() {
165 false => "definition",
168 let new_participle = match new_binding.is_import() {
174 (ident.name, self.session.source_map().guess_head_span(new_binding.span));
176 if let Some(s) = self.name_already_seen.get(&name) {
182 let old_kind = match (ns, old_binding.module()) {
183 (ValueNS, _) => "value",
184 (MacroNS, _) => "macro",
185 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
186 (TypeNS, Some(module)) if module.is_normal() => "module",
187 (TypeNS, Some(module)) if module.is_trait() => "trait",
188 (TypeNS, _) => "type",
191 let msg = format!("the name `{}` is defined multiple times", name);
193 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
194 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
195 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
196 true => struct_span_err!(self.session, span, E0254, "{}", msg),
197 false => struct_span_err!(self.session, span, E0260, "{}", msg),
199 _ => match (old_binding.is_import(), new_binding.is_import()) {
200 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
201 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
202 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
207 "`{}` must be defined only once in the {} namespace of this {}",
213 err.span_label(span, format!("`{}` re{} here", name, new_participle));
215 self.session.source_map().guess_head_span(old_binding.span),
216 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
219 // See https://github.com/rust-lang/rust/issues/32354
220 use NameBindingKind::Import;
221 let import = match (&new_binding.kind, &old_binding.kind) {
222 // If there are two imports where one or both have attributes then prefer removing the
223 // import without attributes.
224 (Import { import: new, .. }, Import { import: old, .. })
226 !new_binding.span.is_dummy()
227 && !old_binding.span.is_dummy()
228 && (new.has_attributes || old.has_attributes)
231 if old.has_attributes {
232 Some((new, new_binding.span, true))
234 Some((old, old_binding.span, true))
237 // Otherwise prioritize the new binding.
238 (Import { import, .. }, other) if !new_binding.span.is_dummy() => {
239 Some((import, new_binding.span, other.is_import()))
241 (other, Import { import, .. }) if !old_binding.span.is_dummy() => {
242 Some((import, old_binding.span, other.is_import()))
247 // Check if the target of the use for both bindings is the same.
248 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
249 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
251 self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item);
252 // Only suggest removing an import if both bindings are to the same def, if both spans
253 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
254 // been introduced by an item.
255 let should_remove_import = duplicate
257 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
260 Some((import, span, true)) if should_remove_import && import.is_nested() => {
261 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span)
263 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
264 // Simple case - remove the entire import. Due to the above match arm, this can
265 // only be a single use so just remove it entirely.
266 err.tool_only_span_suggestion(
267 import.use_span_with_attributes,
268 "remove unnecessary import",
270 Applicability::MaybeIncorrect,
273 Some((import, span, _)) => {
274 self.add_suggestion_for_rename_of_use(&mut err, name, import, span)
280 self.name_already_seen.insert(name, span);
283 /// This function adds a suggestion to change the binding name of a new import that conflicts
284 /// with an existing import.
286 /// ```text,ignore (diagnostic)
287 /// help: you can use `as` to change the binding name of the import
289 /// LL | use foo::bar as other_bar;
290 /// | ^^^^^^^^^^^^^^^^^^^^^
292 fn add_suggestion_for_rename_of_use(
294 err: &mut Diagnostic,
299 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
300 format!("Other{}", name)
302 format!("other_{}", name)
305 let mut suggestion = None;
307 ImportKind::Single { type_ns_only: true, .. } => {
308 suggestion = Some(format!("self as {}", suggested_name))
310 ImportKind::Single { source, .. } => {
312 source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
314 if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) {
315 if pos <= snippet.len() {
316 suggestion = Some(format!(
320 if snippet.ends_with(';') { ";" } else { "" }
326 ImportKind::ExternCrate { source, target } => {
327 suggestion = Some(format!(
328 "extern crate {} as {};",
329 source.unwrap_or(target.name),
336 let rename_msg = "you can use `as` to change the binding name of the import";
337 if let Some(suggestion) = suggestion {
342 Applicability::MaybeIncorrect,
345 err.span_label(binding_span, rename_msg);
349 /// This function adds a suggestion to remove an unnecessary binding from an import that is
350 /// nested. In the following example, this function will be invoked to remove the `a` binding
351 /// in the second use statement:
353 /// ```ignore (diagnostic)
354 /// use issue_52891::a;
355 /// use issue_52891::{d, a, e};
358 /// The following suggestion will be added:
360 /// ```ignore (diagnostic)
361 /// use issue_52891::{d, a, e};
362 /// ^-- help: remove unnecessary import
365 /// If the nested use contains only one import then the suggestion will remove the entire
368 /// It is expected that the provided import is nested - this isn't checked by the
369 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
370 /// as characters expected by span manipulations won't be present.
371 fn add_suggestion_for_duplicate_nested_use(
373 err: &mut Diagnostic,
377 assert!(import.is_nested());
378 let message = "remove unnecessary import";
380 // Two examples will be used to illustrate the span manipulations we're doing:
382 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
383 // `a` and `import.use_span` is `issue_52891::{d, a, e};`.
384 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
385 // `a` and `import.use_span` is `issue_52891::{d, e, a};`.
387 let (found_closing_brace, span) =
388 find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span);
390 // If there was a closing brace then identify the span to remove any trailing commas from
392 if found_closing_brace {
393 if let Some(span) = extend_span_to_previous_binding(self.session, span) {
394 err.tool_only_span_suggestion(
398 Applicability::MaybeIncorrect,
401 // Remove the entire line if we cannot extend the span back, this indicates an
402 // `issue_52891::{self}` case.
404 import.use_span_with_attributes,
407 Applicability::MaybeIncorrect,
414 err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
417 crate fn lint_if_path_starts_with_module(
421 second_binding: Option<&NameBinding<'_>>,
423 let (diag_id, diag_span) = match finalize {
424 Finalize::No => return,
425 Finalize::SimplePath(id, path_span) => (id, path_span),
426 Finalize::UsePath { root_id, root_span, .. } => (root_id, root_span),
427 Finalize::QPathTrait { qpath_id, qpath_span, .. } => (qpath_id, qpath_span),
430 let first_name = match path.get(0) {
431 // In the 2018 edition this lint is a hard error, so nothing to do
432 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
436 // We're only interested in `use` paths which should start with
437 // `{{root}}` currently.
438 if first_name != kw::PathRoot {
443 // If this import looks like `crate::...` it's already good
444 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
445 // Otherwise go below to see if it's an extern crate
447 // If the path has length one (and it's `PathRoot` most likely)
448 // then we don't know whether we're gonna be importing a crate or an
449 // item in our crate. Defer this lint to elsewhere
453 // If the first element of our path was actually resolved to an
454 // `ExternCrate` (also used for `crate::...`) then no need to issue a
455 // warning, this looks all good!
456 if let Some(binding) = second_binding {
457 if let NameBindingKind::Import { import, .. } = binding.kind {
458 // Careful: we still want to rewrite paths from renamed extern crates.
459 if let ImportKind::ExternCrate { source: None, .. } = import.kind {
465 let diag = BuiltinLintDiagnostics::AbsPathWithModule(diag_span);
466 self.lint_buffer.buffer_lint_with_diagnostic(
467 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
470 "absolute paths must start with `self`, `super`, \
471 `crate`, or an external crate name in the 2018 edition",
476 crate fn add_module_candidates(
479 names: &mut Vec<TypoSuggestion>,
480 filter_fn: &impl Fn(Res) -> bool,
482 for (key, resolution) in self.resolutions(module).borrow().iter() {
483 if let Some(binding) = resolution.borrow().binding {
484 let res = binding.res();
486 names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
492 /// Combines an error with provided span and emits it.
494 /// This takes the error provided, combines it with the span and any additional spans inside the
495 /// error and emits it.
496 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
497 self.into_struct_error(span, resolution_error).emit();
500 crate fn into_struct_error(
503 resolution_error: ResolutionError<'_>,
504 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
505 match resolution_error {
506 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
507 let mut err = struct_span_err!(
511 "can't use generic parameters from outer function",
513 err.span_label(span, "use of generic parameter from outer function".to_string());
515 let sm = self.session.source_map();
517 Res::SelfTy { trait_: maybe_trait_defid, alias_to: maybe_impl_defid } => {
518 if let Some(impl_span) =
519 maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
522 reduce_impl_span_to_impl_keyword(sm, impl_span),
523 "`Self` type implicitly declared here, by this `impl`",
526 match (maybe_trait_defid, maybe_impl_defid) {
528 err.span_label(span, "can't use `Self` here");
531 err.span_label(span, "use a type here instead");
533 (None, None) => bug!("`impl` without trait nor type?"),
537 Res::Def(DefKind::TyParam, def_id) => {
538 if let Some(span) = self.opt_span(def_id) {
539 err.span_label(span, "type parameter from outer function");
542 Res::Def(DefKind::ConstParam, def_id) => {
543 if let Some(span) = self.opt_span(def_id) {
544 err.span_label(span, "const parameter from outer function");
549 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
550 DefKind::TyParam or DefKind::ConstParam"
555 if has_generic_params == HasGenericParams::Yes {
556 // Try to retrieve the span of the function signature and generate a new
557 // message with a local type or const parameter.
558 let sugg_msg = "try using a local generic parameter instead";
559 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
560 // Suggest the modification to the user
565 Applicability::MachineApplicable,
567 } else if let Some(sp) = sm.generate_fn_name_span(span) {
570 "try adding a local generic parameter in this method instead"
574 err.help("try using a local generic parameter instead");
580 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
581 let mut err = struct_span_err!(
585 "the name `{}` is already used for a generic \
586 parameter in this item's generic parameters",
589 err.span_label(span, "already used");
590 err.span_label(first_use_span, format!("first use of `{}`", name));
593 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
594 let mut err = struct_span_err!(
598 "method `{}` is not a member of trait `{}`",
602 err.span_label(span, format!("not a member of trait `{}`", trait_));
603 if let Some(candidate) = candidate {
606 "there is an associated function with a similar name",
607 candidate.to_ident_string(),
608 Applicability::MaybeIncorrect,
613 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
614 let mut err = struct_span_err!(
618 "type `{}` is not a member of trait `{}`",
622 err.span_label(span, format!("not a member of trait `{}`", trait_));
623 if let Some(candidate) = candidate {
626 "there is an associated type with a similar name",
627 candidate.to_ident_string(),
628 Applicability::MaybeIncorrect,
633 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
634 let mut err = struct_span_err!(
638 "const `{}` is not a member of trait `{}`",
642 err.span_label(span, format!("not a member of trait `{}`", trait_));
643 if let Some(candidate) = candidate {
646 "there is an associated constant with a similar name",
647 candidate.to_ident_string(),
648 Applicability::MaybeIncorrect,
653 ResolutionError::VariableNotBoundInPattern(binding_error) => {
654 let BindingError { name, target, origin, could_be_path } = binding_error;
656 let target_sp = target.iter().copied().collect::<Vec<_>>();
657 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
659 let msp = MultiSpan::from_spans(target_sp.clone());
660 let mut err = struct_span_err!(
664 "variable `{}` is not bound in all patterns",
667 for sp in target_sp {
668 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
670 for sp in origin_sp {
671 err.span_label(sp, "variable not in all patterns");
674 let help_msg = format!(
675 "if you meant to match on a variant or a `const` item, consider \
676 making the path in the pattern qualified: `?::{}`",
679 err.span_help(span, &help_msg);
683 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
684 let mut err = struct_span_err!(
688 "variable `{}` is bound inconsistently across alternatives separated by `|`",
691 err.span_label(span, "bound in different ways");
692 err.span_label(first_binding_span, "first binding");
695 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
696 let mut err = struct_span_err!(
700 "identifier `{}` is bound more than once in this parameter list",
703 err.span_label(span, "used as parameter more than once");
706 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
707 let mut err = struct_span_err!(
711 "identifier `{}` is bound more than once in the same pattern",
714 err.span_label(span, "used in a pattern more than once");
717 ResolutionError::UndeclaredLabel { name, suggestion } => {
718 let mut err = struct_span_err!(
722 "use of undeclared label `{}`",
726 err.span_label(span, format!("undeclared label `{}`", name));
729 // A reachable label with a similar name exists.
730 Some((ident, true)) => {
731 err.span_label(ident.span, "a label with a similar name is reachable");
734 "try using similarly named label",
735 ident.name.to_string(),
736 Applicability::MaybeIncorrect,
739 // An unreachable label with a similar name exists.
740 Some((ident, false)) => {
743 "a label with a similar name exists but is unreachable",
746 // No similarly-named labels exist.
752 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
753 let mut err = struct_span_err!(
758 "`self` imports are only allowed within a { } list"
761 // None of the suggestions below would help with a case like `use self`.
763 // use foo::bar::self -> foo::bar
764 // use foo::bar::self as abc -> foo::bar as abc
767 "consider importing the module directly",
769 Applicability::MachineApplicable,
772 // use foo::bar::self -> foo::bar::{self}
773 // use foo::bar::self as abc -> foo::bar::{self as abc}
775 (span_with_rename.shrink_to_lo(), "{".to_string()),
776 (span_with_rename.shrink_to_hi(), "}".to_string()),
778 err.multipart_suggestion(
779 "alternatively, use the multi-path `use` syntax to import `self`",
781 Applicability::MachineApplicable,
786 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
787 let mut err = struct_span_err!(
791 "`self` import can only appear once in an import list"
793 err.span_label(span, "can only appear once in an import list");
796 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
797 let mut err = struct_span_err!(
801 "`self` import can only appear in an import list with \
804 err.span_label(span, "can only appear in an import list with a non-empty prefix");
807 ResolutionError::FailedToResolve { label, suggestion } => {
809 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
810 err.span_label(span, label);
812 if let Some((suggestions, msg, applicability)) = suggestion {
813 if suggestions.is_empty() {
817 err.multipart_suggestion(&msg, suggestions, applicability);
822 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
823 let mut err = struct_span_err!(
828 "can't capture dynamic environment in a fn item"
830 err.help("use the `|| { ... }` closure form instead");
833 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
834 let mut err = struct_span_err!(
838 "attempt to use a non-constant value in a constant"
841 // ^^^ given this Span
842 // ------- get this Span to have an applicable suggestion
845 // only do this if the const and usage of the non-constant value are on the same line
846 // the further the two are apart, the higher the chance of the suggestion being wrong
851 .span_extend_to_prev_str(ident.span, current, true, false);
854 Some(sp) if !self.session.source_map().is_multiline(sp) => {
855 let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
858 &format!("consider using `{}` instead of `{}`", sugg, current),
859 format!("{} {}", sugg, ident),
860 Applicability::MaybeIncorrect,
862 err.span_label(span, "non-constant value");
865 err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
871 ResolutionError::BindingShadowsSomethingUnacceptable {
872 shadowing_binding_descr,
876 shadowed_binding_descr,
877 shadowed_binding_span,
879 let mut err = struct_span_err!(
883 "{}s cannot shadow {}s",
884 shadowing_binding_descr,
885 shadowed_binding_descr,
889 format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
892 format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
893 err.span_label(shadowed_binding_span, msg);
896 ResolutionError::ForwardDeclaredGenericParam => {
897 let mut err = struct_span_err!(
901 "generic parameters with a default cannot use \
902 forward declared identifiers"
906 "defaulted generic parameters cannot be forward declared".to_string(),
910 ResolutionError::ParamInTyOfConstParam(name) => {
911 let mut err = struct_span_err!(
915 "the type of const parameters must not depend on other generic parameters"
919 format!("the type must not depend on the parameter `{}`", name),
923 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
924 let mut err = self.session.struct_span_err(
926 "generic parameters may not be used in const operations",
928 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
931 err.note("type parameters may not be used in const expressions");
934 "const parameters may only be used as standalone arguments, i.e. `{}`",
939 if self.session.is_nightly_build() {
941 "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
947 ResolutionError::SelfInGenericParamDefault => {
948 let mut err = struct_span_err!(
952 "generic parameters cannot use `Self` in their defaults"
954 err.span_label(span, "`Self` in generic parameter default".to_string());
957 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
958 let mut err = struct_span_err!(
962 "use of unreachable label `{}`",
966 err.span_label(definition_span, "unreachable label defined here");
967 err.span_label(span, format!("unreachable label `{}`", name));
969 "labels are unreachable through functions, closures, async blocks and modules",
973 // A reachable label with a similar name exists.
974 Some((ident, true)) => {
975 err.span_label(ident.span, "a label with a similar name is reachable");
978 "try using similarly named label",
979 ident.name.to_string(),
980 Applicability::MaybeIncorrect,
983 // An unreachable label with a similar name exists.
984 Some((ident, false)) => {
987 "a label with a similar name exists but is also unreachable",
990 // No similarly-named labels exist.
996 ResolutionError::TraitImplMismatch {
1003 let mut err = self.session.struct_span_err_with_code(
1006 "item `{}` is an associated {}, which doesn't match its trait `{}`",
1007 name, kind, trait_path,
1011 err.span_label(span, "does not match trait");
1012 err.span_label(trait_item_span, "item in trait");
1015 ResolutionError::InvalidAsmSym => {
1016 let mut err = self.session.struct_span_err(span, "invalid `sym` operand");
1017 err.span_label(span, "is a local variable");
1018 err.help("`sym` operands must refer to either a function or a static");
1024 crate fn report_vis_error(
1026 vis_resolution_error: VisResolutionError<'_>,
1027 ) -> ErrorGuaranteed {
1028 match vis_resolution_error {
1029 VisResolutionError::Relative2018(span, path) => {
1030 let mut err = self.session.struct_span_err(
1032 "relative paths are not supported in visibilities in 2018 edition or later",
1034 err.span_suggestion(
1037 format!("crate::{}", pprust::path_to_string(&path)),
1038 Applicability::MaybeIncorrect,
1042 VisResolutionError::AncestorOnly(span) => struct_span_err!(
1046 "visibilities can only be restricted to ancestor modules"
1048 VisResolutionError::FailedToResolve(span, label, suggestion) => {
1049 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
1051 VisResolutionError::ExpectedFound(span, path_str, res) => {
1052 let mut err = struct_span_err!(
1056 "expected module, found {} `{}`",
1060 err.span_label(span, "not a module");
1063 VisResolutionError::Indeterminate(span) => struct_span_err!(
1067 "cannot determine resolution for the visibility"
1069 VisResolutionError::ModuleOnly(span) => {
1070 self.session.struct_span_err(span, "visibility must resolve to a module")
1076 /// Lookup typo candidate in scope for a macro or import.
1077 fn early_lookup_typo_candidate(
1079 scope_set: ScopeSet<'a>,
1080 parent_scope: &ParentScope<'a>,
1082 filter_fn: &impl Fn(Res) -> bool,
1083 ) -> Option<TypoSuggestion> {
1084 let mut suggestions = Vec::new();
1085 let ctxt = ident.span.ctxt();
1086 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
1088 Scope::DeriveHelpers(expn_id) => {
1089 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1096 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1100 Scope::DeriveHelpersCompat => {
1101 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1103 for derive in parent_scope.derives {
1104 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1105 if let Ok((Some(ext), _)) = this.resolve_macro_path(
1107 Some(MacroKind::Derive),
1115 .map(|name| TypoSuggestion::typo_from_res(*name, res)),
1121 Scope::MacroRules(macro_rules_scope) => {
1122 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1123 let res = macro_rules_binding.binding.res();
1125 suggestions.push(TypoSuggestion::typo_from_res(
1126 macro_rules_binding.ident.name,
1132 Scope::CrateRoot => {
1133 let root_ident = Ident::new(kw::PathRoot, ident.span);
1134 let root_module = this.resolve_crate_root(root_ident);
1135 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
1137 Scope::Module(module, _) => {
1138 this.add_module_candidates(module, &mut suggestions, filter_fn);
1140 Scope::RegisteredAttrs => {
1141 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
1144 this.registered_attrs
1146 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1150 Scope::MacroUsePrelude => {
1151 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1153 let res = binding.res();
1154 filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
1158 Scope::BuiltinAttrs => {
1159 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1164 .map(|attr| TypoSuggestion::typo_from_res(attr.name, res)),
1168 Scope::ExternPrelude => {
1169 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1170 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1171 filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
1174 Scope::ToolPrelude => {
1175 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1177 this.registered_tools
1179 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1182 Scope::StdLibPrelude => {
1183 if let Some(prelude) = this.prelude {
1184 let mut tmp_suggestions = Vec::new();
1185 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
1189 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
1193 Scope::BuiltinTypes => {
1194 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1195 let res = Res::PrimTy(*prim_ty);
1196 filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
1204 // Make sure error reporting is deterministic.
1205 suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1207 match find_best_match_for_name(
1208 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1212 Some(found) if found != ident.name => {
1213 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1219 fn lookup_import_candidates_from_module<FilterFn>(
1221 lookup_ident: Ident,
1222 namespace: Namespace,
1223 parent_scope: &ParentScope<'a>,
1224 start_module: Module<'a>,
1226 filter_fn: FilterFn,
1227 ) -> Vec<ImportSuggestion>
1229 FilterFn: Fn(Res) -> bool,
1231 let mut candidates = Vec::new();
1232 let mut seen_modules = FxHashSet::default();
1233 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
1234 let mut worklist_via_import = vec![];
1236 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
1237 None => worklist_via_import.pop(),
1240 let in_module_is_extern = !in_module.def_id().is_local();
1241 // We have to visit module children in deterministic order to avoid
1242 // instabilities in reported imports (#43552).
1243 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1244 // avoid non-importable candidates
1245 if !name_binding.is_importable() {
1249 let child_accessible =
1250 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1252 // do not venture inside inaccessible items of other crates
1253 if in_module_is_extern && !child_accessible {
1257 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1259 // There is an assumption elsewhere that paths of variants are in the enum's
1260 // declaration and not imported. With this assumption, the variant component is
1261 // chopped and the rest of the path is assumed to be the enum's own path. For
1262 // errors where a variant is used as the type instead of the enum, this causes
1263 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1264 if via_import && name_binding.is_possibly_imported_variant() {
1268 // #90113: Do not count an inaccessible reexported item as a candidate.
1269 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
1270 if this.is_accessible_from(binding.vis, parent_scope.module)
1271 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1277 // collect results based on the filter function
1278 // avoid suggesting anything from the same module in which we are resolving
1279 // avoid suggesting anything with a hygienic name
1280 if ident.name == lookup_ident.name
1282 && !ptr::eq(in_module, parent_scope.module)
1283 && !ident.span.normalize_to_macros_2_0().from_expansion()
1285 let res = name_binding.res();
1288 let mut segms = path_segments.clone();
1289 if lookup_ident.span.rust_2018() {
1290 // crate-local absolute paths start with `crate::` in edition 2018
1291 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1292 segms.insert(0, ast::PathSegment::from_ident(crate_name));
1295 segms.push(ast::PathSegment::from_ident(ident));
1296 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1297 let did = match res {
1298 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
1299 _ => res.opt_def_id(),
1302 if child_accessible {
1303 // Remove invisible match if exists
1304 if let Some(idx) = candidates
1306 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1308 candidates.remove(idx);
1312 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1313 // See if we're recommending TryFrom, TryInto, or FromIterator and add
1314 // a note about editions
1315 let note = if let Some(did) = did {
1316 let requires_note = !did.is_local()
1317 && this.cstore().item_attrs_untracked(did, this.session).any(
1319 if attr.has_name(sym::rustc_diagnostic_item) {
1320 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1322 .contains(&attr.value_str())
1329 requires_note.then(|| {
1331 "'{}' is included in the prelude starting in Edition 2021",
1332 path_names_to_string(&path)
1339 candidates.push(ImportSuggestion {
1343 accessible: child_accessible,
1350 // collect submodules to explore
1351 if let Some(module) = name_binding.module() {
1353 let mut path_segments = path_segments.clone();
1354 path_segments.push(ast::PathSegment::from_ident(ident));
1356 let is_extern_crate_that_also_appears_in_prelude =
1357 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
1359 if !is_extern_crate_that_also_appears_in_prelude {
1360 // add the module to the lookup
1361 if seen_modules.insert(module.def_id()) {
1362 if via_import { &mut worklist_via_import } else { &mut worklist }
1363 .push((module, path_segments, child_accessible));
1370 // If only some candidates are accessible, take just them
1371 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1372 candidates = candidates.into_iter().filter(|x| x.accessible).collect();
1378 /// When name resolution fails, this method can be used to look up candidate
1379 /// entities with the expected name. It allows filtering them using the
1380 /// supplied predicate (which should be used to only accept the types of
1381 /// definitions expected, e.g., traits). The lookup spans across all crates.
1383 /// N.B., the method does not look into imports, but this is not a problem,
1384 /// since we report the definitions (thus, the de-aliased imports).
1385 crate fn lookup_import_candidates<FilterFn>(
1387 lookup_ident: Ident,
1388 namespace: Namespace,
1389 parent_scope: &ParentScope<'a>,
1390 filter_fn: FilterFn,
1391 ) -> Vec<ImportSuggestion>
1393 FilterFn: Fn(Res) -> bool,
1395 let mut suggestions = self.lookup_import_candidates_from_module(
1400 Ident::with_dummy_span(kw::Crate),
1404 if lookup_ident.span.rust_2018() {
1405 let extern_prelude_names = self.extern_prelude.clone();
1406 for (ident, _) in extern_prelude_names.into_iter() {
1407 if ident.span.from_expansion() {
1408 // Idents are adjusted to the root context before being
1409 // resolved in the extern prelude, so reporting this to the
1410 // user is no help. This skips the injected
1411 // `extern crate std` in the 2018 edition, which would
1412 // otherwise cause duplicate suggestions.
1415 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
1416 let crate_root = self.expect_module(crate_id.as_def_id());
1417 suggestions.extend(self.lookup_import_candidates_from_module(
1432 crate fn unresolved_macro_suggestions(
1434 err: &mut Diagnostic,
1435 macro_kind: MacroKind,
1436 parent_scope: &ParentScope<'a>,
1439 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1440 let suggestion = self.early_lookup_typo_candidate(
1441 ScopeSet::Macro(macro_kind),
1446 self.add_typo_suggestion(err, suggestion, ident.span);
1448 let import_suggestions =
1449 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1455 &import_suggestions,
1460 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1461 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1462 err.span_note(ident.span, &msg);
1465 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1466 err.help("have you added the `#[macro_use]` on the module/import?");
1469 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1470 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1472 ScopeSet::All(ns, false),
1479 let desc = match binding.res() {
1480 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1481 "a function-like macro".to_string()
1483 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1484 format!("an attribute: `#[{}]`", ident)
1486 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1487 format!("a derive macro: `#[derive({})]`", ident)
1490 // Don't confuse the user with tool modules.
1493 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1494 "only a trait, without a derive macro".to_string()
1500 macro_kind.article(),
1501 macro_kind.descr_expected(),
1504 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1505 if !import.span.is_dummy() {
1508 &format!("`{}` is imported here, but it is {}", ident, desc),
1510 // Silence the 'unused import' warning we might get,
1511 // since this diagnostic already covers that import.
1512 self.record_use(ident, binding, false);
1516 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1522 crate fn add_typo_suggestion(
1524 err: &mut Diagnostic,
1525 suggestion: Option<TypoSuggestion>,
1528 let suggestion = match suggestion {
1529 None => return false,
1530 // We shouldn't suggest underscore.
1531 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1532 Some(suggestion) => suggestion,
1534 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1535 LOCAL_CRATE => self.opt_span(def_id),
1539 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1542 if let Some(def_span) = def_span {
1543 if span.overlaps(def_span) {
1544 // Don't suggest typo suggestion for itself like in the following:
1545 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1546 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1549 // | ----------- `X` defined here
1551 // LL | const Y: X = X("ö");
1552 // | -------------^^^^^^- similarly named constant `Y` defined here
1554 // help: use struct literal syntax instead
1556 // LL | const Y: X = X {};
1558 // help: a constant with a similar name exists
1560 // LL | const Y: X = Y("ö");
1564 let prefix = match suggestion.target {
1565 SuggestionTarget::SimilarlyNamed => "similarly named ",
1566 SuggestionTarget::SingleItem => "",
1570 self.session.source_map().guess_head_span(def_span),
1572 "{}{} `{}` defined here",
1574 suggestion.res.descr(),
1575 suggestion.candidate.as_str(),
1579 let msg = match suggestion.target {
1580 SuggestionTarget::SimilarlyNamed => format!(
1581 "{} {} with a similar name exists",
1582 suggestion.res.article(),
1583 suggestion.res.descr()
1585 SuggestionTarget::SingleItem => {
1586 format!("maybe you meant this {}", suggestion.res.descr())
1589 err.span_suggestion(
1592 suggestion.candidate.to_string(),
1593 Applicability::MaybeIncorrect,
1598 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1600 if b.span.is_dummy() || self.session.source_map().span_to_snippet(b.span).is_err() {
1601 // These already contain the "built-in" prefix or look bad with it.
1603 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1604 let (built_in, from) = if from_prelude {
1605 ("", " from prelude")
1606 } else if b.is_extern_crate()
1608 && self.session.opts.externs.get(ident.as_str()).is_some()
1610 ("", " passed with `--extern`")
1611 } else if add_built_in {
1617 let a = if built_in.is_empty() { res.article() } else { "a" };
1618 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1620 let introduced = if b.is_import() { "imported" } else { "defined" };
1621 format!("the {thing} {introduced} here", thing = res.descr())
1625 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1626 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1627 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1628 // We have to print the span-less alternative first, otherwise formatting looks bad.
1629 (b2, b1, misc2, misc1, true)
1631 (b1, b2, misc1, misc2, false)
1634 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1635 err.span_label(ident.span, "ambiguous name");
1636 err.note(&format!("ambiguous because of {}", kind.descr()));
1638 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1639 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1640 let note_msg = format!("`{ident}` could{also} refer to {what}");
1642 let thing = b.res().descr();
1643 let mut help_msgs = Vec::new();
1644 if b.is_glob_import()
1645 && (kind == AmbiguityKind::GlobVsGlob
1646 || kind == AmbiguityKind::GlobVsExpanded
1647 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1649 help_msgs.push(format!(
1650 "consider adding an explicit import of `{ident}` to disambiguate"
1653 if b.is_extern_crate() && ident.span.rust_2018() {
1654 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1656 if misc == AmbiguityErrorMisc::SuggestCrate {
1658 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1659 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1661 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1664 err.span_note(b.span, ¬e_msg);
1665 for (i, help_msg) in help_msgs.iter().enumerate() {
1666 let or = if i == 0 { "" } else { "or " };
1667 err.help(&format!("{}{}", or, help_msg));
1671 could_refer_to(b1, misc1, "");
1672 could_refer_to(b2, misc2, " also");
1676 /// If the binding refers to a tuple struct constructor with fields,
1677 /// returns the span of its fields.
1678 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1679 if let NameBindingKind::Res(
1680 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1684 let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1685 let fields = self.field_names.get(&def_id)?;
1686 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1691 fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1692 let PrivacyError { ident, binding, .. } = *privacy_error;
1694 let res = binding.res();
1695 let ctor_fields_span = self.ctor_fields_span(binding);
1696 let plain_descr = res.descr().to_string();
1697 let nonimport_descr =
1698 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1699 let import_descr = nonimport_descr.clone() + " import";
1701 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1703 // Print the primary message.
1704 let descr = get_descr(binding);
1706 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1707 err.span_label(ident.span, &format!("private {}", descr));
1708 if let Some(span) = ctor_fields_span {
1709 err.span_label(span, "a constructor is private if any of the fields is private");
1712 // Print the whole import chain to make it easier to see what happens.
1713 let first_binding = binding;
1714 let mut next_binding = Some(binding);
1715 let mut next_ident = ident;
1716 while let Some(binding) = next_binding {
1717 let name = next_ident;
1718 next_binding = match binding.kind {
1719 _ if res == Res::Err => None,
1720 NameBindingKind::Import { binding, import, .. } => match import.kind {
1721 _ if binding.span.is_dummy() => None,
1722 ImportKind::Single { source, .. } => {
1723 next_ident = source;
1726 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1727 ImportKind::ExternCrate { .. } => None,
1732 let first = ptr::eq(binding, first_binding);
1734 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1735 and_refers_to = if first { "" } else { "...and refers to " },
1736 item = get_descr(binding),
1737 which = if first { "" } else { " which" },
1738 dots = if next_binding.is_some() { "..." } else { "" },
1740 let def_span = self.session.source_map().guess_head_span(binding.span);
1741 let mut note_span = MultiSpan::from_span(def_span);
1742 if !first && binding.vis.is_public() {
1743 note_span.push_span_label(def_span, "consider importing it directly");
1745 err.span_note(note_span, &msg);
1751 crate fn find_similarly_named_module_or_crate(
1754 current_module: &Module<'a>,
1755 ) -> Option<Symbol> {
1756 let mut candidates = self
1759 .map(|(ident, _)| ident.name)
1763 .filter(|(_, module)| {
1764 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1766 .flat_map(|(_, module)| module.kind.name()),
1768 .filter(|c| !c.to_string().is_empty())
1769 .collect::<Vec<_>>();
1772 match find_best_match_for_name(&candidates, ident, None) {
1773 Some(sugg) if sugg == ident => None,
1778 crate fn report_path_resolution_error(
1781 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1782 parent_scope: &ParentScope<'a>,
1783 ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1784 unusable_binding: Option<&'a NameBinding<'a>>,
1785 module: Option<ModuleOrUniformRoot<'a>>,
1788 ) -> (String, Option<Suggestion>) {
1789 let is_last = i == path.len() - 1;
1790 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1791 let module_res = match module {
1792 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1795 if module_res == self.graph_root.res() {
1796 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1797 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1799 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1800 if let Some(candidate) = candidates.get(0) {
1802 String::from("unresolved import"),
1804 vec![(ident.span, pprust::path_to_string(&candidate.path))],
1805 String::from("a similar path exists"),
1806 Applicability::MaybeIncorrect,
1809 } else if self.session.edition() == Edition::Edition2015 {
1810 (format!("maybe a missing crate `{}`?", ident), None)
1812 (format!("could not find `{}` in the crate root", ident), None)
1815 let parent = path[i - 1].ident.name;
1816 let parent = match parent {
1817 // ::foo is mounted at the crate root for 2015, and is the extern
1818 // prelude for 2018+
1819 kw::PathRoot if self.session.edition() > Edition::Edition2015 => {
1820 "the list of imported crates".to_owned()
1822 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1823 _ => format!("`{}`", parent),
1826 let mut msg = format!("could not find `{}` in {}", ident, parent);
1827 if ns == TypeNS || ns == ValueNS {
1828 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1829 let binding = if let Some(module) = module {
1830 self.resolve_ident_in_module(
1839 } else if let Some(ribs) = ribs
1840 && let Some(TypeNS | ValueNS) = opt_ns
1842 match self.resolve_ident_in_lexical_scope(
1850 // we found a locally-imported or available item/module
1851 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1855 let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none());
1856 self.early_resolve_ident_in_lexical_scope(
1866 if let Some(binding) = binding {
1867 let mut found = |what| {
1869 "expected {}, found {} `{}` in {}",
1876 if binding.module().is_some() {
1879 match binding.res() {
1880 Res::Def(kind, id) => found(kind.descr(id)),
1881 _ => found(ns_to_try.descr()),
1887 } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) {
1888 // Check whether the name refers to an item in the value namespace.
1889 let binding = if let Some(ribs) = ribs {
1890 self.resolve_ident_in_lexical_scope(
1901 let match_span = match binding {
1902 // Name matches a local variable. For example:
1905 // let Foo: &str = "";
1906 // println!("{}", Foo::Bar); // Name refers to local
1907 // // variable `Foo`.
1910 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1911 Some(*self.pat_span_map.get(&id).unwrap())
1913 // Name matches item from a local name binding
1914 // created by `use` declaration. For example:
1916 // pub Foo: &str = "";
1920 // println!("{}", Foo::Bar); // Name refers to local
1921 // // binding `Foo`.
1924 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1927 let suggestion = if let Some(span) = match_span {
1929 vec![(span, String::from(""))],
1930 format!("`{}` is defined here, but is not a type", ident),
1931 Applicability::MaybeIncorrect,
1937 (format!("use of undeclared type `{}`", ident), suggestion)
1939 let suggestion = if ident.name == sym::alloc {
1942 String::from("add `extern crate alloc` to use the `alloc` crate"),
1943 Applicability::MaybeIncorrect,
1946 self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
1949 vec![(ident.span, sugg.to_string())],
1950 String::from("there is a crate or module with a similar name"),
1951 Applicability::MaybeIncorrect,
1956 (format!("use of undeclared crate or module `{}`", ident), suggestion)
1961 impl<'a, 'b> ImportResolver<'a, 'b> {
1962 /// Adds suggestions for a path that cannot be resolved.
1963 pub(crate) fn make_path_suggestion(
1966 mut path: Vec<Segment>,
1967 parent_scope: &ParentScope<'b>,
1968 ) -> Option<(Vec<Segment>, Vec<String>)> {
1969 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1971 match (path.get(0), path.get(1)) {
1972 // `{{root}}::ident::...` on both editions.
1973 // On 2015 `{{root}}` is usually added implicitly.
1974 (Some(fst), Some(snd))
1975 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1976 // `ident::...` on 2018.
1978 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1980 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1981 path.insert(0, Segment::from_ident(Ident::empty()));
1986 self.make_missing_self_suggestion(path.clone(), parent_scope)
1987 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
1988 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
1989 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
1992 /// Suggest a missing `self::` if that resolves to an correct module.
1996 /// LL | use foo::Bar;
1997 /// | ^^^ did you mean `self::foo`?
1999 fn make_missing_self_suggestion(
2001 mut path: Vec<Segment>,
2002 parent_scope: &ParentScope<'b>,
2003 ) -> Option<(Vec<Segment>, Vec<String>)> {
2004 // Replace first ident with `self` and check if that is valid.
2005 path[0].ident.name = kw::SelfLower;
2006 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2007 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
2008 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2011 /// Suggests a missing `crate::` if that resolves to an correct module.
2015 /// LL | use foo::Bar;
2016 /// | ^^^ did you mean `crate::foo`?
2018 fn make_missing_crate_suggestion(
2020 mut path: Vec<Segment>,
2021 parent_scope: &ParentScope<'b>,
2022 ) -> Option<(Vec<Segment>, Vec<String>)> {
2023 // Replace first ident with `crate` and check if that is valid.
2024 path[0].ident.name = kw::Crate;
2025 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2026 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
2027 if let PathResult::Module(..) = result {
2031 "`use` statements changed in Rust 2018; read more at \
2032 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2042 /// Suggests a missing `super::` if that resolves to an correct module.
2046 /// LL | use foo::Bar;
2047 /// | ^^^ did you mean `super::foo`?
2049 fn make_missing_super_suggestion(
2051 mut path: Vec<Segment>,
2052 parent_scope: &ParentScope<'b>,
2053 ) -> Option<(Vec<Segment>, Vec<String>)> {
2054 // Replace first ident with `crate` and check if that is valid.
2055 path[0].ident.name = kw::Super;
2056 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2057 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
2058 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2061 /// Suggests a missing external crate name if that resolves to an correct module.
2065 /// LL | use foobar::Baz;
2066 /// | ^^^^^^ did you mean `baz::foobar`?
2069 /// Used when importing a submodule of an external crate but missing that crate's
2070 /// name as the first part of path.
2071 fn make_external_crate_suggestion(
2073 mut path: Vec<Segment>,
2074 parent_scope: &ParentScope<'b>,
2075 ) -> Option<(Vec<Segment>, Vec<String>)> {
2076 if path[1].ident.span.rust_2015() {
2080 // Sort extern crate names in *reverse* order to get
2081 // 1) some consistent ordering for emitted diagnostics, and
2082 // 2) `std` suggestions before `core` suggestions.
2083 let mut extern_crate_names =
2084 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
2085 extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
2087 for name in extern_crate_names.into_iter() {
2088 // Replace first ident with a crate name and check if that is valid.
2089 path[0].ident.name = name;
2090 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2092 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
2095 if let PathResult::Module(..) = result {
2096 return Some((path, Vec::new()));
2103 /// Suggests importing a macro from the root of the crate rather than a module within
2107 /// help: a macro with this name exists at the root of the crate
2109 /// LL | use issue_59764::makro;
2110 /// | ^^^^^^^^^^^^^^^^^^
2112 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
2113 /// at the root of the crate instead of the module where it is defined
2115 pub(crate) fn check_for_module_export_macro(
2117 import: &'b Import<'b>,
2118 module: ModuleOrUniformRoot<'b>,
2120 ) -> Option<(Option<Suggestion>, Vec<String>)> {
2121 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2125 while let Some(parent) = crate_module.parent {
2126 crate_module = parent;
2129 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
2130 // Don't make a suggestion if the import was already from the root of the
2135 let resolutions = self.r.resolutions(crate_module).borrow();
2136 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
2137 let binding = resolution.borrow().binding()?;
2138 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2139 let module_name = crate_module.kind.name().unwrap();
2140 let import_snippet = match import.kind {
2141 ImportKind::Single { source, target, .. } if source != target => {
2142 format!("{} as {}", source, target)
2144 _ => format!("{}", ident),
2147 let mut corrections: Vec<(Span, String)> = Vec::new();
2148 if !import.is_nested() {
2149 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2150 // intermediate segments.
2151 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2153 // Find the binding span (and any trailing commas and spaces).
2154 // ie. `use a::b::{c, d, e};`
2156 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2162 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2163 found_closing_brace, binding_span
2166 let mut removal_span = binding_span;
2167 if found_closing_brace {
2168 // If the binding span ended with a closing brace, as in the below example:
2169 // ie. `use a::b::{c, d};`
2171 // Then expand the span of characters to remove to include the previous
2172 // binding's trailing comma.
2173 // ie. `use a::b::{c, d};`
2175 if let Some(previous_span) =
2176 extend_span_to_previous_binding(self.r.session, binding_span)
2178 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2179 removal_span = removal_span.with_lo(previous_span.lo());
2182 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2184 // Remove the `removal_span`.
2185 corrections.push((removal_span, "".to_string()));
2187 // Find the span after the crate name and if it has nested imports immediately
2188 // after the crate name already.
2189 // ie. `use a::b::{c, d};`
2191 // or `use a::{b, c, d}};`
2193 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2199 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2200 has_nested, after_crate_name
2203 let source_map = self.r.session.source_map();
2205 // Add the import to the start, with a `{` if required.
2206 let start_point = source_map.start_point(after_crate_name);
2207 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2211 // In this case, `start_snippet` must equal '{'.
2212 format!("{}{}, ", start_snippet, import_snippet)
2214 // In this case, add a `{`, then the moved import, then whatever
2215 // was there before.
2216 format!("{{{}, {}", import_snippet, start_snippet)
2221 // Add a `};` to the end if nested, matching the `{` added at the start.
2223 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2227 let suggestion = Some((
2229 String::from("a macro with this name exists at the root of the crate"),
2230 Applicability::MaybeIncorrect,
2233 "this could be because a macro annotated with `#[macro_export]` will be exported \
2234 at the root of the crate instead of the module where it is defined"
2237 Some((suggestion, note))
2244 /// Given a `binding_span` of a binding within a use statement:
2247 /// use foo::{a, b, c};
2251 /// then return the span until the next binding or the end of the statement:
2254 /// use foo::{a, b, c};
2257 fn find_span_of_binding_until_next_binding(
2262 let source_map = sess.source_map();
2264 // Find the span of everything after the binding.
2265 // ie. `a, e};` or `a};`
2266 let binding_until_end = binding_span.with_hi(use_span.hi());
2268 // Find everything after the binding but not including the binding.
2269 // ie. `, e};` or `};`
2270 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2272 // Keep characters in the span until we encounter something that isn't a comma or
2276 // Also note whether a closing brace character was encountered. If there
2277 // was, then later go backwards to remove any trailing commas that are left.
2278 let mut found_closing_brace = false;
2279 let after_binding_until_next_binding =
2280 source_map.span_take_while(after_binding_until_end, |&ch| {
2282 found_closing_brace = true;
2284 ch == ' ' || ch == ','
2287 // Combine the two spans.
2288 // ie. `a, ` or `a`.
2290 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2291 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2293 (found_closing_brace, span)
2296 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2300 /// use foo::a::{a, b, c};
2301 /// ^^--- binding span
2305 /// use foo::{a, b, c};
2306 /// --- binding span
2308 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2309 let source_map = sess.source_map();
2311 // `prev_source` will contain all of the source that came before the span.
2312 // Then split based on a command and take the first (ie. closest to our span)
2313 // snippet. In the example, this is a space.
2314 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2316 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2317 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2318 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2322 let prev_comma = prev_comma.first().unwrap();
2323 let prev_starting_brace = prev_starting_brace.first().unwrap();
2325 // If the amount of source code before the comma is greater than
2326 // the amount of source code before the starting brace then we've only
2327 // got one item in the nested item (eg. `issue_52891::{self}`).
2328 if prev_comma.len() > prev_starting_brace.len() {
2332 Some(binding_span.with_lo(BytePos(
2333 // Take away the number of bytes for the characters we've found and an
2334 // extra for the comma.
2335 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2339 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2340 /// it is a nested use tree.
2343 /// use foo::a::{b, c};
2344 /// ^^^^^^^^^^ // false
2346 /// use foo::{a, b, c};
2347 /// ^^^^^^^^^^ // true
2349 /// use foo::{a, b::{c, d}};
2350 /// ^^^^^^^^^^^^^^^ // true
2352 fn find_span_immediately_after_crate_name(
2354 module_name: Symbol,
2358 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2359 module_name, use_span
2361 let source_map = sess.source_map();
2363 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2364 let mut num_colons = 0;
2365 // Find second colon.. `use issue_59764:`
2366 let until_second_colon = source_map.span_take_while(use_span, |c| {
2370 !matches!(c, ':' if num_colons == 2)
2372 // Find everything after the second colon.. `foo::{baz, makro};`
2373 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2375 let mut found_a_non_whitespace_character = false;
2376 // Find the first non-whitespace character in `from_second_colon`.. `f`
2377 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2378 if found_a_non_whitespace_character {
2381 if !c.is_whitespace() {
2382 found_a_non_whitespace_character = true;
2387 // Find the first `{` in from_second_colon.. `foo::{`
2388 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2390 (next_left_bracket == after_second_colon, from_second_colon)
2393 /// When an entity with a given name is not available in scope, we search for
2394 /// entities with that name in all crates. This method allows outputting the
2395 /// results of this search in a programmer-friendly way
2397 definitions: &rustc_hir::definitions::Definitions,
2399 err: &mut Diagnostic,
2400 // This is `None` if all placement locations are inside expansions
2401 use_placement_span: Option<Span>,
2402 candidates: &[ImportSuggestion],
2406 if candidates.is_empty() {
2410 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2412 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2415 candidates.iter().for_each(|c| {
2416 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2417 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
2420 // we want consistent results across executions, but candidates are produced
2421 // by iterating through a hash map, so make sure they are ordered:
2422 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2423 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2424 let core_path_strings =
2425 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2426 path_strings.extend(core_path_strings);
2427 path_strings.dedup_by(|a, b| a.0 == b.0);
2430 if !accessible_path_strings.is_empty() {
2431 let (determiner, kind) = if accessible_path_strings.len() == 1 {
2432 ("this", accessible_path_strings[0].1)
2434 ("one of these", "items")
2437 let instead = if instead { " instead" } else { "" };
2438 let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
2440 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2444 if let Some(span) = use_placement_span {
2445 for candidate in &mut accessible_path_strings {
2446 // produce an additional newline to separate the new use statement
2447 // from the directly following item.
2448 let additional_newline = if found_use { "" } else { "\n" };
2449 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
2452 err.span_suggestions(
2455 accessible_path_strings.into_iter().map(|a| a.0),
2456 Applicability::Unspecified,
2461 for candidate in accessible_path_strings {
2463 msg.push_str(&candidate.0);
2469 assert!(!inaccessible_path_strings.is_empty());
2471 if inaccessible_path_strings.len() == 1 {
2472 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
2473 let msg = format!("{} `{}` exists but is inaccessible", descr, name);
2475 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2476 let span = definitions.def_span(local_def_id);
2477 let span = session.source_map().guess_head_span(span);
2478 let mut multi_span = MultiSpan::from_span(span);
2479 multi_span.push_span_label(span, "not accessible".to_string());
2480 err.span_note(multi_span, &msg);
2484 if let Some(note) = (*note).as_deref() {
2488 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
2489 let descr = if inaccessible_path_strings
2492 .all(|(_, descr, _, _)| descr == descr_first)
2494 descr_first.to_string()
2499 let mut msg = format!("these {}s exist but are inaccessible", descr);
2500 let mut has_colon = false;
2502 let mut spans = Vec::new();
2503 for (name, _, def_id, _) in &inaccessible_path_strings {
2504 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2505 let span = definitions.def_span(local_def_id);
2506 let span = session.source_map().guess_head_span(span);
2507 spans.push((name, span));
2518 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2519 for (name, span) in spans {
2520 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2523 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2527 err.span_note(multi_span, &msg);
2533 struct UsePlacementFinder {
2534 target_module: NodeId,
2535 first_legal_span: Option<Span>,
2536 first_use_span: Option<Span>,
2539 impl UsePlacementFinder {
2540 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
2542 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2543 finder.visit_crate(krate);
2544 if let Some(use_span) = finder.first_use_span {
2545 (Some(use_span), true)
2547 (finder.first_legal_span, false)
2552 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
2553 fn visit_crate(&mut self, c: &Crate) {
2554 if self.target_module == CRATE_NODE_ID {
2555 let inject = c.spans.inject_use_span;
2556 if is_span_suitable_for_use_injection(inject) {
2557 self.first_legal_span = Some(inject);
2559 self.first_use_span = search_for_any_use_in_items(&c.items);
2562 visit::walk_crate(self, c);
2566 fn visit_item(&mut self, item: &'tcx ast::Item) {
2567 if self.target_module == item.id {
2568 if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2569 let inject = mod_spans.inject_use_span;
2570 if is_span_suitable_for_use_injection(inject) {
2571 self.first_legal_span = Some(inject);
2573 self.first_use_span = search_for_any_use_in_items(items);
2577 visit::walk_item(self, item);
2582 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2584 if let ItemKind::Use(..) = item.kind {
2585 if is_span_suitable_for_use_injection(item.span) {
2586 return Some(item.span.shrink_to_lo());
2593 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2594 // don't suggest placing a use before the prelude
2595 // import or other generated ones