6 use rustc::session::Session;
7 use rustc::ty::{self, DefIdTree};
8 use rustc_ast::ast::{self, Ident, Path};
9 use rustc_ast::util::lev_distance::find_best_match_for_name;
10 use rustc_ast_pretty::pprust;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
13 use rustc_feature::BUILTIN_ATTRIBUTES;
14 use rustc_hir::def::Namespace::{self, *};
15 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind};
16 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
17 use rustc_span::hygiene::MacroKind;
18 use rustc_span::source_map::SourceMap;
19 use rustc_span::symbol::{kw, Symbol};
20 use rustc_span::{BytePos, MultiSpan, Span};
22 use crate::imports::{Import, ImportKind, ImportResolver};
23 use crate::path_names_to_string;
24 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
26 BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot,
28 use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
29 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
31 type Res = def::Res<ast::NodeId>;
33 /// A vector of spans and replacements, a message and applicability.
34 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
36 crate struct TypoSuggestion {
37 pub candidate: Symbol,
42 crate fn from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
43 TypoSuggestion { candidate, res }
47 /// A free importable items suggested in case of resolution failure.
48 crate struct ImportSuggestion {
49 pub did: Option<DefId>,
53 /// Adjust the impl span so that just the `impl` keyword is taken by removing
54 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
55 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
57 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
58 /// parser. If you need to use this function or something similar, please consider updating the
59 /// `source_map` functions and this function to something more robust.
60 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
61 let impl_span = sm.span_until_char(impl_span, '<');
62 let impl_span = sm.span_until_whitespace(impl_span);
66 impl<'a> Resolver<'a> {
67 crate fn add_module_candidates(
70 names: &mut Vec<TypoSuggestion>,
71 filter_fn: &impl Fn(Res) -> bool,
73 for (key, resolution) in self.resolutions(module).borrow().iter() {
74 if let Some(binding) = resolution.borrow().binding {
75 let res = binding.res();
77 names.push(TypoSuggestion::from_res(key.ident.name, res));
83 /// Combines an error with provided span and emits it.
85 /// This takes the error provided, combines it with the span and any additional spans inside the
86 /// error and emits it.
87 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
88 self.into_struct_error(span, resolution_error).emit();
91 crate fn into_struct_error(
94 resolution_error: ResolutionError<'_>,
95 ) -> DiagnosticBuilder<'_> {
96 match resolution_error {
97 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
98 let mut err = struct_span_err!(
102 "can't use generic parameters from outer function",
104 err.span_label(span, "use of generic parameter from outer function".to_string());
106 let sm = self.session.source_map();
108 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
109 if let Some(impl_span) =
110 maybe_impl_defid.and_then(|def_id| self.definitions.opt_span(def_id))
113 reduce_impl_span_to_impl_keyword(sm, impl_span),
114 "`Self` type implicitly declared here, by this `impl`",
117 match (maybe_trait_defid, maybe_impl_defid) {
119 err.span_label(span, "can't use `Self` here");
122 err.span_label(span, "use a type here instead");
124 (None, None) => bug!("`impl` without trait nor type?"),
128 Res::Def(DefKind::TyParam, def_id) => {
129 if let Some(span) = self.definitions.opt_span(def_id) {
130 err.span_label(span, "type parameter from outer function");
133 Res::Def(DefKind::ConstParam, def_id) => {
134 if let Some(span) = self.definitions.opt_span(def_id) {
135 err.span_label(span, "const parameter from outer function");
140 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
146 if has_generic_params == HasGenericParams::Yes {
147 // Try to retrieve the span of the function signature and generate a new
148 // message with a local type or const parameter.
149 let sugg_msg = "try using a local generic parameter instead";
150 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
151 // Suggest the modification to the user
156 Applicability::MachineApplicable,
158 } else if let Some(sp) = sm.generate_fn_name_span(span) {
161 "try adding a local generic parameter in this method instead"
165 err.help("try using a local generic parameter instead");
171 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
172 let mut err = struct_span_err!(
176 "the name `{}` is already used for a generic \
177 parameter in this item's generic parameters",
180 err.span_label(span, "already used");
181 err.span_label(first_use_span, format!("first use of `{}`", name));
184 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
185 let mut err = struct_span_err!(
189 "method `{}` is not a member of trait `{}`",
193 err.span_label(span, format!("not a member of trait `{}`", trait_));
196 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
197 let mut err = struct_span_err!(
201 "type `{}` is not a member of trait `{}`",
205 err.span_label(span, format!("not a member of trait `{}`", trait_));
208 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
209 let mut err = struct_span_err!(
213 "const `{}` is not a member of trait `{}`",
217 err.span_label(span, format!("not a member of trait `{}`", trait_));
220 ResolutionError::VariableNotBoundInPattern(binding_error) => {
221 let BindingError { name, target, origin, could_be_path } = binding_error;
223 let target_sp = target.iter().copied().collect::<Vec<_>>();
224 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
226 let msp = MultiSpan::from_spans(target_sp.clone());
227 let mut err = struct_span_err!(
231 "variable `{}` is not bound in all patterns",
234 for sp in target_sp {
235 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
237 for sp in origin_sp {
238 err.span_label(sp, "variable not in all patterns");
241 let help_msg = format!(
242 "if you meant to match on a variant or a `const` item, consider \
243 making the path in the pattern qualified: `?::{}`",
246 err.span_help(span, &help_msg);
250 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
251 let mut err = struct_span_err!(
255 "variable `{}` is bound inconsistently across alternatives separated by `|`",
258 err.span_label(span, "bound in different ways");
259 err.span_label(first_binding_span, "first binding");
262 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
263 let mut err = struct_span_err!(
267 "identifier `{}` is bound more than once in this parameter list",
270 err.span_label(span, "used as parameter more than once");
273 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
274 let mut err = struct_span_err!(
278 "identifier `{}` is bound more than once in the same pattern",
281 err.span_label(span, "used in a pattern more than once");
284 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
285 let mut err = struct_span_err!(
289 "use of undeclared label `{}`",
292 if let Some(lev_candidate) = lev_candidate {
295 "a label with a similar name exists in this scope",
296 lev_candidate.to_string(),
297 Applicability::MaybeIncorrect,
300 err.span_label(span, format!("undeclared label `{}`", name));
304 ResolutionError::SelfImportsOnlyAllowedWithin => struct_span_err!(
309 "`self` imports are only allowed within a { } list"
311 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
312 let mut err = struct_span_err!(
316 "`self` import can only appear once in an import list"
318 err.span_label(span, "can only appear once in an import list");
321 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
322 let mut err = struct_span_err!(
326 "`self` import can only appear in an import list with \
329 err.span_label(span, "can only appear in an import list with a non-empty prefix");
332 ResolutionError::FailedToResolve { label, suggestion } => {
334 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
335 err.span_label(span, label);
337 if let Some((suggestions, msg, applicability)) = suggestion {
338 err.multipart_suggestion(&msg, suggestions, applicability);
343 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
344 let mut err = struct_span_err!(
349 "can't capture dynamic environment in a fn item"
351 err.help("use the `|| { ... }` closure form instead");
354 ResolutionError::AttemptToUseNonConstantValueInConstant => {
355 let mut err = struct_span_err!(
359 "attempt to use a non-constant value in a constant"
361 err.span_label(span, "non-constant value");
364 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
365 let res = binding.res();
366 let shadows_what = res.descr();
367 let mut err = struct_span_err!(
371 "{}s cannot shadow {}s",
377 format!("cannot be named the same as {} {}", res.article(), shadows_what),
379 let participle = if binding.is_import() { "imported" } else { "defined" };
380 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
381 err.span_label(binding.span, msg);
384 ResolutionError::ForwardDeclaredTyParam => {
385 let mut err = struct_span_err!(
389 "type parameters with a default cannot use \
390 forward declared identifiers"
394 "defaulted type parameters cannot be forward declared".to_string(),
398 ResolutionError::SelfInTyParamDefault => {
399 let mut err = struct_span_err!(
403 "type parameters cannot use `Self` in their defaults"
405 err.span_label(span, "`Self` in type parameter default".to_string());
411 crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
412 match vis_resolution_error {
413 VisResolutionError::Relative2018(span, path) => {
414 let mut err = self.session.struct_span_err(
416 "relative paths are not supported in visibilities on 2018 edition",
421 format!("crate::{}", pprust::path_to_string(&path)),
422 Applicability::MaybeIncorrect,
426 VisResolutionError::AncestorOnly(span) => struct_span_err!(
430 "visibilities can only be restricted to ancestor modules"
432 VisResolutionError::FailedToResolve(span, label, suggestion) => {
433 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
435 VisResolutionError::ExpectedFound(span, path_str, res) => {
436 let mut err = struct_span_err!(
440 "expected module, found {} `{}`",
444 err.span_label(span, "not a module");
447 VisResolutionError::Indeterminate(span) => struct_span_err!(
451 "cannot determine resolution for the visibility"
453 VisResolutionError::ModuleOnly(span) => {
454 self.session.struct_span_err(span, "visibility must resolve to a module")
460 /// Lookup typo candidate in scope for a macro or import.
461 fn early_lookup_typo_candidate(
464 parent_scope: &ParentScope<'a>,
466 filter_fn: &impl Fn(Res) -> bool,
467 ) -> Option<TypoSuggestion> {
468 let mut suggestions = Vec::new();
469 self.visit_scopes(scope_set, parent_scope, ident, |this, scope, use_prelude, _| {
471 Scope::DeriveHelpers(expn_id) => {
472 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
479 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
483 Scope::DeriveHelpersCompat => {
484 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
486 for derive in parent_scope.derives {
487 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
488 if let Ok((Some(ext), _)) = this.resolve_macro_path(
490 Some(MacroKind::Derive),
498 .map(|name| TypoSuggestion::from_res(*name, res)),
504 Scope::MacroRules(macro_rules_scope) => {
505 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope {
506 let res = macro_rules_binding.binding.res();
509 .push(TypoSuggestion::from_res(macro_rules_binding.ident.name, res))
513 Scope::CrateRoot => {
514 let root_ident = Ident::new(kw::PathRoot, ident.span);
515 let root_module = this.resolve_crate_root(root_ident);
516 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
518 Scope::Module(module) => {
519 this.add_module_candidates(module, &mut suggestions, filter_fn);
521 Scope::RegisteredAttrs => {
522 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
525 this.registered_attrs
527 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
531 Scope::MacroUsePrelude => {
532 suggestions.extend(this.macro_use_prelude.iter().filter_map(
534 let res = binding.res();
535 filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
539 Scope::BuiltinAttrs => {
540 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
545 .map(|(name, ..)| TypoSuggestion::from_res(*name, res)),
549 Scope::ExternPrelude => {
550 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
551 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
552 filter_fn(res).then_some(TypoSuggestion::from_res(ident.name, res))
555 Scope::ToolPrelude => {
556 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
558 this.registered_tools
560 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
563 Scope::StdLibPrelude => {
564 if let Some(prelude) = this.prelude {
565 let mut tmp_suggestions = Vec::new();
566 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
570 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
574 Scope::BuiltinTypes => {
575 let primitive_types = &this.primitive_type_table.primitive_types;
576 suggestions.extend(primitive_types.iter().flat_map(|(name, prim_ty)| {
577 let res = Res::PrimTy(*prim_ty);
578 filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
586 // Make sure error reporting is deterministic.
587 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
589 match find_best_match_for_name(
590 suggestions.iter().map(|suggestion| &suggestion.candidate),
594 Some(found) if found != ident.name => {
595 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
601 fn lookup_import_candidates_from_module<FilterFn>(
604 namespace: Namespace,
605 start_module: Module<'a>,
608 ) -> Vec<ImportSuggestion>
610 FilterFn: Fn(Res) -> bool,
612 let mut candidates = Vec::new();
613 let mut seen_modules = FxHashSet::default();
614 let not_local_module = crate_name.name != kw::Crate;
615 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
617 while let Some((in_module, path_segments, in_module_is_extern)) = worklist.pop() {
618 // We have to visit module children in deterministic order to avoid
619 // instabilities in reported imports (#43552).
620 in_module.for_each_child(self, |this, ident, ns, name_binding| {
621 // avoid imports entirely
622 if name_binding.is_import() && !name_binding.is_extern_crate() {
625 // avoid non-importable candidates as well
626 if !name_binding.is_importable() {
630 // collect results based on the filter function
631 if ident.name == lookup_ident.name && ns == namespace {
632 let res = name_binding.res();
635 let mut segms = path_segments.clone();
636 if lookup_ident.span.rust_2018() {
637 // crate-local absolute paths start with `crate::` in edition 2018
638 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
639 segms.insert(0, ast::PathSegment::from_ident(crate_name));
642 segms.push(ast::PathSegment::from_ident(ident));
643 let path = Path { span: name_binding.span, segments: segms };
644 // the entity is accessible in the following cases:
645 // 1. if it's defined in the same crate, it's always
646 // accessible (since private entities can be made public)
647 // 2. if it's defined in another crate, it's accessible
648 // only if both the module is public and the entity is
649 // declared as public (due to pruning, we don't explore
650 // outside crate private modules => no need to check this)
651 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
652 let did = match res {
653 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
654 _ => res.opt_def_id(),
656 candidates.push(ImportSuggestion { did, path });
661 // collect submodules to explore
662 if let Some(module) = name_binding.module() {
664 let mut path_segments = path_segments.clone();
665 path_segments.push(ast::PathSegment::from_ident(ident));
667 let is_extern_crate_that_also_appears_in_prelude =
668 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
670 let is_visible_to_user =
671 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
673 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
674 // add the module to the lookup
675 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
676 if seen_modules.insert(module.def_id().unwrap()) {
677 worklist.push((module, path_segments, is_extern));
687 /// When name resolution fails, this method can be used to look up candidate
688 /// entities with the expected name. It allows filtering them using the
689 /// supplied predicate (which should be used to only accept the types of
690 /// definitions expected, e.g., traits). The lookup spans across all crates.
692 /// N.B., the method does not look into imports, but this is not a problem,
693 /// since we report the definitions (thus, the de-aliased imports).
694 crate fn lookup_import_candidates<FilterFn>(
697 namespace: Namespace,
699 ) -> Vec<ImportSuggestion>
701 FilterFn: Fn(Res) -> bool,
703 let mut suggestions = self.lookup_import_candidates_from_module(
707 Ident::with_dummy_span(kw::Crate),
711 if lookup_ident.span.rust_2018() {
712 let extern_prelude_names = self.extern_prelude.clone();
713 for (ident, _) in extern_prelude_names.into_iter() {
714 if ident.span.from_expansion() {
715 // Idents are adjusted to the root context before being
716 // resolved in the extern prelude, so reporting this to the
717 // user is no help. This skips the injected
718 // `extern crate std` in the 2018 edition, which would
719 // otherwise cause duplicate suggestions.
722 if let Some(crate_id) =
723 self.crate_loader.maybe_process_path_extern(ident.name, ident.span)
726 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
727 suggestions.extend(self.lookup_import_candidates_from_module(
741 crate fn unresolved_macro_suggestions(
743 err: &mut DiagnosticBuilder<'a>,
744 macro_kind: MacroKind,
745 parent_scope: &ParentScope<'a>,
748 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
749 let suggestion = self.early_lookup_typo_candidate(
750 ScopeSet::Macro(macro_kind),
755 self.add_typo_suggestion(err, suggestion, ident.span);
757 if macro_kind == MacroKind::Derive && (ident.as_str() == "Send" || ident.as_str() == "Sync")
759 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
760 err.span_note(ident.span, &msg);
762 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
763 err.help("have you added the `#[macro_use]` on the module/import?");
767 crate fn add_typo_suggestion(
769 err: &mut DiagnosticBuilder<'_>,
770 suggestion: Option<TypoSuggestion>,
773 if let Some(suggestion) = suggestion {
774 // We shouldn't suggest underscore.
775 if suggestion.candidate == kw::Underscore {
780 "{} {} with a similar name exists",
781 suggestion.res.article(),
782 suggestion.res.descr()
787 suggestion.candidate.to_string(),
788 Applicability::MaybeIncorrect,
790 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
791 LOCAL_CRATE => self.definitions.opt_span(def_id),
795 .def_span(self.cstore().get_span_untracked(def_id, self.session)),
798 if let Some(span) = def_span {
802 "similarly named {} `{}` defined here",
803 suggestion.res.descr(),
804 suggestion.candidate.as_str(),
813 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
815 if b.span.is_dummy() {
816 let add_built_in = match b.res() {
817 // These already contain the "built-in" prefix or look bad with it.
818 Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false,
821 let (built_in, from) = if from_prelude {
822 ("", " from prelude")
823 } else if b.is_extern_crate()
825 && self.session.opts.externs.get(&ident.as_str()).is_some()
827 ("", " passed with `--extern`")
828 } else if add_built_in {
834 let article = if built_in.is_empty() { res.article() } else { "a" };
836 "{a}{built_in} {thing}{from}",
843 let introduced = if b.is_import() { "imported" } else { "defined" };
844 format!("the {thing} {introduced} here", thing = res.descr(), introduced = introduced)
848 crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
849 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
850 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
851 // We have to print the span-less alternative first, otherwise formatting looks bad.
852 (b2, b1, misc2, misc1, true)
854 (b1, b2, misc1, misc2, false)
857 let mut err = struct_span_err!(
861 "`{ident}` is ambiguous ({why})",
865 err.span_label(ident.span, "ambiguous name");
867 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
868 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
869 let note_msg = format!(
870 "`{ident}` could{also} refer to {what}",
876 let thing = b.res().descr();
877 let mut help_msgs = Vec::new();
878 if b.is_glob_import()
879 && (kind == AmbiguityKind::GlobVsGlob
880 || kind == AmbiguityKind::GlobVsExpanded
881 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
883 help_msgs.push(format!(
884 "consider adding an explicit import of \
885 `{ident}` to disambiguate",
889 if b.is_extern_crate() && ident.span.rust_2018() {
890 help_msgs.push(format!(
891 "use `::{ident}` to refer to this {thing} unambiguously",
896 if misc == AmbiguityErrorMisc::SuggestCrate {
897 help_msgs.push(format!(
898 "use `crate::{ident}` to refer to this {thing} unambiguously",
902 } else if misc == AmbiguityErrorMisc::SuggestSelf {
903 help_msgs.push(format!(
904 "use `self::{ident}` to refer to this {thing} unambiguously",
910 err.span_note(b.span, ¬e_msg);
911 for (i, help_msg) in help_msgs.iter().enumerate() {
912 let or = if i == 0 { "" } else { "or " };
913 err.help(&format!("{}{}", or, help_msg));
917 could_refer_to(b1, misc1, "");
918 could_refer_to(b2, misc2, " also");
922 /// If the binding refers to a tuple struct constructor with fields,
923 /// returns the span of its fields.
924 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
925 if let NameBindingKind::Res(
926 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
930 let def_id = (&*self).parent(ctor_def_id).expect("no parent for a constructor");
931 if let Some(fields) = self.field_names.get(&def_id) {
932 let first_field = fields.first().expect("empty field list in the map");
933 return Some(fields.iter().fold(first_field.span, |acc, field| acc.to(field.span)));
939 crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
940 let PrivacyError { ident, binding, .. } = *privacy_error;
942 let res = binding.res();
943 let ctor_fields_span = self.ctor_fields_span(binding);
944 let plain_descr = res.descr().to_string();
945 let nonimport_descr =
946 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
947 let import_descr = nonimport_descr.clone() + " import";
949 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
951 // Print the primary message.
952 let descr = get_descr(binding);
954 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
955 err.span_label(ident.span, &format!("this {} is private", descr));
956 if let Some(span) = ctor_fields_span {
957 err.span_label(span, "a constructor is private if any of the fields is private");
960 // Print the whole import chain to make it easier to see what happens.
961 let first_binding = binding;
962 let mut next_binding = Some(binding);
963 let mut next_ident = ident;
964 while let Some(binding) = next_binding {
965 let name = next_ident;
966 next_binding = match binding.kind {
967 _ if res == Res::Err => None,
968 NameBindingKind::Import { binding, import, .. } => match import.kind {
969 _ if binding.span.is_dummy() => None,
970 ImportKind::Single { source, .. } => {
974 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
975 ImportKind::ExternCrate { .. } => None,
980 let first = ptr::eq(binding, first_binding);
981 let descr = get_descr(binding);
983 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
984 and_refers_to = if first { "" } else { "...and refers to " },
987 which = if first { "" } else { " which" },
988 dots = if next_binding.is_some() { "..." } else { "" },
990 let def_span = self.session.source_map().def_span(binding.span);
991 let mut note_span = MultiSpan::from_span(def_span);
992 if !first && binding.vis == ty::Visibility::Public {
993 note_span.push_span_label(def_span, "consider importing it directly".into());
995 err.span_note(note_span, &msg);
1002 impl<'a, 'b> ImportResolver<'a, 'b> {
1003 /// Adds suggestions for a path that cannot be resolved.
1004 pub(crate) fn make_path_suggestion(
1007 mut path: Vec<Segment>,
1008 parent_scope: &ParentScope<'b>,
1009 ) -> Option<(Vec<Segment>, Vec<String>)> {
1010 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1012 match (path.get(0), path.get(1)) {
1013 // `{{root}}::ident::...` on both editions.
1014 // On 2015 `{{root}}` is usually added implicitly.
1015 (Some(fst), Some(snd))
1016 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1017 // `ident::...` on 2018.
1019 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1021 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1022 path.insert(0, Segment::from_ident(Ident::invalid()));
1027 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1028 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1029 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1030 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1033 /// Suggest a missing `self::` if that resolves to an correct module.
1037 /// LL | use foo::Bar;
1038 /// | ^^^ did you mean `self::foo`?
1040 fn make_missing_self_suggestion(
1043 mut path: Vec<Segment>,
1044 parent_scope: &ParentScope<'b>,
1045 ) -> Option<(Vec<Segment>, Vec<String>)> {
1046 // Replace first ident with `self` and check if that is valid.
1047 path[0].ident.name = kw::SelfLower;
1048 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1049 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1050 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1053 /// Suggests a missing `crate::` if that resolves to an correct module.
1057 /// LL | use foo::Bar;
1058 /// | ^^^ did you mean `crate::foo`?
1060 fn make_missing_crate_suggestion(
1063 mut path: Vec<Segment>,
1064 parent_scope: &ParentScope<'b>,
1065 ) -> Option<(Vec<Segment>, Vec<String>)> {
1066 // Replace first ident with `crate` and check if that is valid.
1067 path[0].ident.name = kw::Crate;
1068 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1069 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1070 if let PathResult::Module(..) = result {
1074 "`use` statements changed in Rust 2018; read more at \
1075 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1085 /// Suggests a missing `super::` if that resolves to an correct module.
1089 /// LL | use foo::Bar;
1090 /// | ^^^ did you mean `super::foo`?
1092 fn make_missing_super_suggestion(
1095 mut path: Vec<Segment>,
1096 parent_scope: &ParentScope<'b>,
1097 ) -> Option<(Vec<Segment>, Vec<String>)> {
1098 // Replace first ident with `crate` and check if that is valid.
1099 path[0].ident.name = kw::Super;
1100 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1101 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1102 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1105 /// Suggests a missing external crate name if that resolves to an correct module.
1109 /// LL | use foobar::Baz;
1110 /// | ^^^^^^ did you mean `baz::foobar`?
1113 /// Used when importing a submodule of an external crate but missing that crate's
1114 /// name as the first part of path.
1115 fn make_external_crate_suggestion(
1118 mut path: Vec<Segment>,
1119 parent_scope: &ParentScope<'b>,
1120 ) -> Option<(Vec<Segment>, Vec<String>)> {
1121 if path[1].ident.span.rust_2015() {
1125 // Sort extern crate names in reverse order to get
1126 // 1) some consistent ordering for emitted diagnostics, and
1127 // 2) `std` suggestions before `core` suggestions.
1128 let mut extern_crate_names =
1129 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1130 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
1132 for name in extern_crate_names.into_iter() {
1133 // Replace first ident with a crate name and check if that is valid.
1134 path[0].ident.name = name;
1135 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1137 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1140 if let PathResult::Module(..) = result {
1141 return Some((path, Vec::new()));
1148 /// Suggests importing a macro from the root of the crate rather than a module within
1152 /// help: a macro with this name exists at the root of the crate
1154 /// LL | use issue_59764::makro;
1155 /// | ^^^^^^^^^^^^^^^^^^
1157 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
1158 /// at the root of the crate instead of the module where it is defined
1160 pub(crate) fn check_for_module_export_macro(
1162 import: &'b Import<'b>,
1163 module: ModuleOrUniformRoot<'b>,
1165 ) -> Option<(Option<Suggestion>, Vec<String>)> {
1166 let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
1172 while let Some(parent) = crate_module.parent {
1173 crate_module = parent;
1176 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1177 // Don't make a suggestion if the import was already from the root of the
1182 let resolutions = self.r.resolutions(crate_module).borrow();
1183 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1184 let binding = resolution.borrow().binding()?;
1185 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1186 let module_name = crate_module.kind.name().unwrap();
1187 let import_snippet = match import.kind {
1188 ImportKind::Single { source, target, .. } if source != target => {
1189 format!("{} as {}", source, target)
1191 _ => format!("{}", ident),
1194 let mut corrections: Vec<(Span, String)> = Vec::new();
1195 if !import.is_nested() {
1196 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1197 // intermediate segments.
1198 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1200 // Find the binding span (and any trailing commas and spaces).
1201 // ie. `use a::b::{c, d, e};`
1203 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1209 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1210 found_closing_brace, binding_span
1213 let mut removal_span = binding_span;
1214 if found_closing_brace {
1215 // If the binding span ended with a closing brace, as in the below example:
1216 // ie. `use a::b::{c, d};`
1218 // Then expand the span of characters to remove to include the previous
1219 // binding's trailing comma.
1220 // ie. `use a::b::{c, d};`
1222 if let Some(previous_span) =
1223 extend_span_to_previous_binding(self.r.session, binding_span)
1225 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1226 removal_span = removal_span.with_lo(previous_span.lo());
1229 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1231 // Remove the `removal_span`.
1232 corrections.push((removal_span, "".to_string()));
1234 // Find the span after the crate name and if it has nested imports immediatately
1235 // after the crate name already.
1236 // ie. `use a::b::{c, d};`
1238 // or `use a::{b, c, d}};`
1240 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1246 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1247 has_nested, after_crate_name
1250 let source_map = self.r.session.source_map();
1252 // Add the import to the start, with a `{` if required.
1253 let start_point = source_map.start_point(after_crate_name);
1254 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1258 // In this case, `start_snippet` must equal '{'.
1259 format!("{}{}, ", start_snippet, import_snippet)
1261 // In this case, add a `{`, then the moved import, then whatever
1262 // was there before.
1263 format!("{{{}, {}", import_snippet, start_snippet)
1268 // Add a `};` to the end if nested, matching the `{` added at the start.
1270 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1274 let suggestion = Some((
1276 String::from("a macro with this name exists at the root of the crate"),
1277 Applicability::MaybeIncorrect,
1280 "this could be because a macro annotated with `#[macro_export]` will be exported \
1281 at the root of the crate instead of the module where it is defined"
1284 Some((suggestion, note))
1291 /// Given a `binding_span` of a binding within a use statement:
1294 /// use foo::{a, b, c};
1298 /// then return the span until the next binding or the end of the statement:
1301 /// use foo::{a, b, c};
1304 pub(crate) fn find_span_of_binding_until_next_binding(
1309 let source_map = sess.source_map();
1311 // Find the span of everything after the binding.
1312 // ie. `a, e};` or `a};`
1313 let binding_until_end = binding_span.with_hi(use_span.hi());
1315 // Find everything after the binding but not including the binding.
1316 // ie. `, e};` or `};`
1317 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1319 // Keep characters in the span until we encounter something that isn't a comma or
1323 // Also note whether a closing brace character was encountered. If there
1324 // was, then later go backwards to remove any trailing commas that are left.
1325 let mut found_closing_brace = false;
1326 let after_binding_until_next_binding =
1327 source_map.span_take_while(after_binding_until_end, |&ch| {
1329 found_closing_brace = true;
1331 ch == ' ' || ch == ','
1334 // Combine the two spans.
1335 // ie. `a, ` or `a`.
1337 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1338 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1340 (found_closing_brace, span)
1343 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1347 /// use foo::a::{a, b, c};
1348 /// ^^--- binding span
1352 /// use foo::{a, b, c};
1353 /// --- binding span
1355 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1356 let source_map = sess.source_map();
1358 // `prev_source` will contain all of the source that came before the span.
1359 // Then split based on a command and take the first (ie. closest to our span)
1360 // snippet. In the example, this is a space.
1361 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1363 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1364 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1365 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1369 let prev_comma = prev_comma.first().unwrap();
1370 let prev_starting_brace = prev_starting_brace.first().unwrap();
1372 // If the amount of source code before the comma is greater than
1373 // the amount of source code before the starting brace then we've only
1374 // got one item in the nested item (eg. `issue_52891::{self}`).
1375 if prev_comma.len() > prev_starting_brace.len() {
1379 Some(binding_span.with_lo(BytePos(
1380 // Take away the number of bytes for the characters we've found and an
1381 // extra for the comma.
1382 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1386 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1387 /// it is a nested use tree.
1390 /// use foo::a::{b, c};
1391 /// ^^^^^^^^^^ // false
1393 /// use foo::{a, b, c};
1394 /// ^^^^^^^^^^ // true
1396 /// use foo::{a, b::{c, d}};
1397 /// ^^^^^^^^^^^^^^^ // true
1399 fn find_span_immediately_after_crate_name(
1401 module_name: Symbol,
1405 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1406 module_name, use_span
1408 let source_map = sess.source_map();
1410 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1411 let mut num_colons = 0;
1412 // Find second colon.. `use issue_59764:`
1413 let until_second_colon = source_map.span_take_while(use_span, |c| {
1418 ':' if num_colons == 2 => false,
1422 // Find everything after the second colon.. `foo::{baz, makro};`
1423 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1425 let mut found_a_non_whitespace_character = false;
1426 // Find the first non-whitespace character in `from_second_colon`.. `f`
1427 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1428 if found_a_non_whitespace_character {
1431 if !c.is_whitespace() {
1432 found_a_non_whitespace_character = true;
1437 // Find the first `{` in from_second_colon.. `foo::{`
1438 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1440 (next_left_bracket == after_second_colon, from_second_colon)
1443 /// When an entity with a given name is not available in scope, we search for
1444 /// entities with that name in all crates. This method allows outputting the
1445 /// results of this search in a programmer-friendly way
1446 crate fn show_candidates(
1447 err: &mut DiagnosticBuilder<'_>,
1448 // This is `None` if all placement locations are inside expansions
1450 candidates: &[ImportSuggestion],
1454 if candidates.is_empty() {
1457 // we want consistent results across executions, but candidates are produced
1458 // by iterating through a hash map, so make sure they are ordered:
1459 let mut path_strings: Vec<_> =
1460 candidates.iter().map(|c| path_names_to_string(&c.path)).collect();
1461 path_strings.sort();
1462 path_strings.dedup();
1464 let better = if better { "better " } else { "" };
1465 let msg_diff = match path_strings.len() {
1466 1 => " is found in another module, you can import it",
1467 _ => "s are found in other modules, you can import them",
1469 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
1471 if let Some(span) = span {
1472 for candidate in &mut path_strings {
1473 // produce an additional newline to separate the new use statement
1474 // from the directly following item.
1475 let additional_newline = if found_use { "" } else { "\n" };
1476 *candidate = format!("use {};\n{}", candidate, additional_newline);
1479 err.span_suggestions(span, &msg, path_strings.into_iter(), Applicability::Unspecified);
1483 for candidate in path_strings {
1485 msg.push_str(&candidate);