4 use rustc_ast
::util
::lev_distance
::find_best_match_for_name
;
5 use rustc_ast
::{self as ast, Path}
;
6 use rustc_ast_pretty
::pprust
;
7 use rustc_data_structures
::fx
::FxHashSet
;
8 use rustc_errors
::{struct_span_err, Applicability, DiagnosticBuilder}
;
9 use rustc_feature
::BUILTIN_ATTRIBUTES
;
10 use rustc_hir
::def
::Namespace
::{self, *}
;
11 use rustc_hir
::def
::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind}
;
12 use rustc_hir
::def_id
::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE}
;
13 use rustc_middle
::bug
;
14 use rustc_middle
::ty
::{self, DefIdTree}
;
15 use rustc_session
::Session
;
16 use rustc_span
::hygiene
::MacroKind
;
17 use rustc_span
::source_map
::SourceMap
;
18 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
19 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 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
37 /// similarly named label and whether or not it is reachable.
38 crate type LabelSuggestion
= (Ident
, bool
);
40 crate struct TypoSuggestion
{
41 pub candidate
: Symbol
,
46 crate fn from_res(candidate
: Symbol
, res
: Res
) -> TypoSuggestion
{
47 TypoSuggestion { candidate, res }
51 /// A free importable items suggested in case of resolution failure.
52 crate struct ImportSuggestion
{
53 pub did
: Option
<DefId
>,
54 pub descr
: &'
static str,
59 /// Adjust the impl span so that just the `impl` keyword is taken by removing
60 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
61 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
63 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
64 /// parser. If you need to use this function or something similar, please consider updating the
65 /// `source_map` functions and this function to something more robust.
66 fn reduce_impl_span_to_impl_keyword(sm
: &SourceMap
, impl_span
: Span
) -> Span
{
67 let impl_span
= sm
.span_until_char(impl_span
, '
<'
);
68 sm
.span_until_whitespace(impl_span
)
71 impl<'a
> Resolver
<'a
> {
72 crate fn add_module_candidates(
75 names
: &mut Vec
<TypoSuggestion
>,
76 filter_fn
: &impl Fn(Res
) -> bool
,
78 for (key
, resolution
) in self.resolutions(module
).borrow().iter() {
79 if let Some(binding
) = resolution
.borrow().binding
{
80 let res
= binding
.res();
82 names
.push(TypoSuggestion
::from_res(key
.ident
.name
, res
));
88 /// Combines an error with provided span and emits it.
90 /// This takes the error provided, combines it with the span and any additional spans inside the
91 /// error and emits it.
92 crate fn report_error(&self, span
: Span
, resolution_error
: ResolutionError
<'_
>) {
93 self.into_struct_error(span
, resolution_error
).emit();
96 crate fn into_struct_error(
99 resolution_error
: ResolutionError
<'_
>,
100 ) -> DiagnosticBuilder
<'_
> {
101 match resolution_error
{
102 ResolutionError
::GenericParamsFromOuterFunction(outer_res
, has_generic_params
) => {
103 let mut err
= struct_span_err
!(
107 "can't use generic parameters from outer function",
109 err
.span_label(span
, "use of generic parameter from outer function".to_string());
111 let sm
= self.session
.source_map();
113 Res
::SelfTy(maybe_trait_defid
, maybe_impl_defid
) => {
114 if let Some(impl_span
) =
115 maybe_impl_defid
.and_then(|(def_id
, _
)| self.opt_span(def_id
))
118 reduce_impl_span_to_impl_keyword(sm
, impl_span
),
119 "`Self` type implicitly declared here, by this `impl`",
122 match (maybe_trait_defid
, maybe_impl_defid
) {
124 err
.span_label(span
, "can't use `Self` here");
127 err
.span_label(span
, "use a type here instead");
129 (None
, None
) => bug
!("`impl` without trait nor type?"),
133 Res
::Def(DefKind
::TyParam
, def_id
) => {
134 if let Some(span
) = self.opt_span(def_id
) {
135 err
.span_label(span
, "type parameter from outer function");
138 Res
::Def(DefKind
::ConstParam
, def_id
) => {
139 if let Some(span
) = self.opt_span(def_id
) {
140 err
.span_label(span
, "const parameter from outer function");
145 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
151 if has_generic_params
== HasGenericParams
::Yes
{
152 // Try to retrieve the span of the function signature and generate a new
153 // message with a local type or const parameter.
154 let sugg_msg
= "try using a local generic parameter instead";
155 if let Some((sugg_span
, snippet
)) = sm
.generate_local_type_param_snippet(span
) {
156 // Suggest the modification to the user
161 Applicability
::MachineApplicable
,
163 } else if let Some(sp
) = sm
.generate_fn_name_span(span
) {
166 "try adding a local generic parameter in this method instead"
170 err
.help("try using a local generic parameter instead");
176 ResolutionError
::NameAlreadyUsedInParameterList(name
, first_use_span
) => {
177 let mut err
= struct_span_err
!(
181 "the name `{}` is already used for a generic \
182 parameter in this item's generic parameters",
185 err
.span_label(span
, "already used");
186 err
.span_label(first_use_span
, format
!("first use of `{}`", name
));
189 ResolutionError
::MethodNotMemberOfTrait(method
, trait_
) => {
190 let mut err
= struct_span_err
!(
194 "method `{}` is not a member of trait `{}`",
198 err
.span_label(span
, format
!("not a member of trait `{}`", trait_
));
201 ResolutionError
::TypeNotMemberOfTrait(type_
, trait_
) => {
202 let mut err
= struct_span_err
!(
206 "type `{}` is not a member of trait `{}`",
210 err
.span_label(span
, format
!("not a member of trait `{}`", trait_
));
213 ResolutionError
::ConstNotMemberOfTrait(const_
, trait_
) => {
214 let mut err
= struct_span_err
!(
218 "const `{}` is not a member of trait `{}`",
222 err
.span_label(span
, format
!("not a member of trait `{}`", trait_
));
225 ResolutionError
::VariableNotBoundInPattern(binding_error
) => {
226 let BindingError { name, target, origin, could_be_path }
= binding_error
;
228 let target_sp
= target
.iter().copied().collect
::<Vec
<_
>>();
229 let origin_sp
= origin
.iter().copied().collect
::<Vec
<_
>>();
231 let msp
= MultiSpan
::from_spans(target_sp
.clone());
232 let mut err
= struct_span_err
!(
236 "variable `{}` is not bound in all patterns",
239 for sp
in target_sp
{
240 err
.span_label(sp
, format
!("pattern doesn't bind `{}`", name
));
242 for sp
in origin_sp
{
243 err
.span_label(sp
, "variable not in all patterns");
246 let help_msg
= format
!(
247 "if you meant to match on a variant or a `const` item, consider \
248 making the path in the pattern qualified: `?::{}`",
251 err
.span_help(span
, &help_msg
);
255 ResolutionError
::VariableBoundWithDifferentMode(variable_name
, first_binding_span
) => {
256 let mut err
= struct_span_err
!(
260 "variable `{}` is bound inconsistently across alternatives separated by `|`",
263 err
.span_label(span
, "bound in different ways");
264 err
.span_label(first_binding_span
, "first binding");
267 ResolutionError
::IdentifierBoundMoreThanOnceInParameterList(identifier
) => {
268 let mut err
= struct_span_err
!(
272 "identifier `{}` is bound more than once in this parameter list",
275 err
.span_label(span
, "used as parameter more than once");
278 ResolutionError
::IdentifierBoundMoreThanOnceInSamePattern(identifier
) => {
279 let mut err
= struct_span_err
!(
283 "identifier `{}` is bound more than once in the same pattern",
286 err
.span_label(span
, "used in a pattern more than once");
289 ResolutionError
::UndeclaredLabel { name, suggestion }
=> {
290 let mut err
= struct_span_err
!(
294 "use of undeclared label `{}`",
298 err
.span_label(span
, format
!("undeclared label `{}`", name
));
301 // A reachable label with a similar name exists.
302 Some((ident
, true)) => {
303 err
.span_label(ident
.span
, "a label with a similar name is reachable");
306 "try using similarly named label",
307 ident
.name
.to_string(),
308 Applicability
::MaybeIncorrect
,
311 // An unreachable label with a similar name exists.
312 Some((ident
, false)) => {
315 "a label with a similar name exists but is unreachable",
318 // No similarly-named labels exist.
324 ResolutionError
::SelfImportsOnlyAllowedWithin { root, span_with_rename }
=> {
325 let mut err
= struct_span_err
!(
330 "`self` imports are only allowed within a { } list"
333 // None of the suggestions below would help with a case like `use self`.
335 // use foo::bar::self -> foo::bar
336 // use foo::bar::self as abc -> foo::bar as abc
339 "consider importing the module directly",
341 Applicability
::MachineApplicable
,
344 // use foo::bar::self -> foo::bar::{self}
345 // use foo::bar::self as abc -> foo::bar::{self as abc}
347 (span_with_rename
.shrink_to_lo(), "{".to_string()),
348 (span_with_rename
.shrink_to_hi(), "}".to_string()),
350 err
.multipart_suggestion(
351 "alternatively, use the multi-path `use` syntax to import `self`",
353 Applicability
::MachineApplicable
,
358 ResolutionError
::SelfImportCanOnlyAppearOnceInTheList
=> {
359 let mut err
= struct_span_err
!(
363 "`self` import can only appear once in an import list"
365 err
.span_label(span
, "can only appear once in an import list");
368 ResolutionError
::SelfImportOnlyInImportListWithNonEmptyPrefix
=> {
369 let mut err
= struct_span_err
!(
373 "`self` import can only appear in an import list with \
376 err
.span_label(span
, "can only appear in an import list with a non-empty prefix");
379 ResolutionError
::FailedToResolve { label, suggestion }
=> {
381 struct_span_err
!(self.session
, span
, E0433
, "failed to resolve: {}", &label
);
382 err
.span_label(span
, label
);
384 if let Some((suggestions
, msg
, applicability
)) = suggestion
{
385 err
.multipart_suggestion(&msg
, suggestions
, applicability
);
390 ResolutionError
::CannotCaptureDynamicEnvironmentInFnItem
=> {
391 let mut err
= struct_span_err
!(
396 "can't capture dynamic environment in a fn item"
398 err
.help("use the `|| { ... }` closure form instead");
401 ResolutionError
::AttemptToUseNonConstantValueInConstant
=> {
402 let mut err
= struct_span_err
!(
406 "attempt to use a non-constant value in a constant"
408 err
.span_label(span
, "non-constant value");
411 ResolutionError
::BindingShadowsSomethingUnacceptable(what_binding
, name
, binding
) => {
412 let res
= binding
.res();
413 let shadows_what
= res
.descr();
414 let mut err
= struct_span_err
!(
418 "{}s cannot shadow {}s",
424 format
!("cannot be named the same as {} {}", res
.article(), shadows_what
),
426 let participle
= if binding
.is_import() { "imported" }
else { "defined" }
;
427 let msg
= format
!("the {} `{}` is {} here", shadows_what
, name
, participle
);
428 err
.span_label(binding
.span
, msg
);
431 ResolutionError
::ForwardDeclaredTyParam
=> {
432 let mut err
= struct_span_err
!(
436 "type parameters with a default cannot use \
437 forward declared identifiers"
441 "defaulted type parameters cannot be forward declared".to_string(),
445 ResolutionError
::ParamInTyOfConstParam(name
) => {
446 let mut err
= struct_span_err
!(
450 "the type of const parameters must not depend on other generic parameters"
454 format
!("the type must not depend on the parameter `{}`", name
),
458 ResolutionError
::ParamInAnonConstInTyDefault(name
) => {
459 let mut err
= self.session
.struct_span_err(
461 "constant values inside of type parameter defaults must not depend on generic parameters",
465 format
!("the anonymous constant must not depend on the parameter `{}`", name
),
469 ResolutionError
::ParamInNonTrivialAnonConst { name, is_type }
=> {
470 let mut err
= self.session
.struct_span_err(
472 "generic parameters must not be used inside of non trivial constant values",
477 "non-trivial anonymous constants must not depend on the parameter `{}`",
483 err
.note("type parameters are currently not permitted in anonymous constants");
486 &format
!("it is currently only allowed to use either `{0}` or `{{ {0} }}` as generic constants",
494 ResolutionError
::SelfInTyParamDefault
=> {
495 let mut err
= struct_span_err
!(
499 "type parameters cannot use `Self` in their defaults"
501 err
.span_label(span
, "`Self` in type parameter default".to_string());
504 ResolutionError
::UnreachableLabel { name, definition_span, suggestion }
=> {
505 let mut err
= struct_span_err
!(
509 "use of unreachable label `{}`",
513 err
.span_label(definition_span
, "unreachable label defined here");
514 err
.span_label(span
, format
!("unreachable label `{}`", name
));
516 "labels are unreachable through functions, closures, async blocks and modules",
520 // A reachable label with a similar name exists.
521 Some((ident
, true)) => {
522 err
.span_label(ident
.span
, "a label with a similar name is reachable");
525 "try using similarly named label",
526 ident
.name
.to_string(),
527 Applicability
::MaybeIncorrect
,
530 // An unreachable label with a similar name exists.
531 Some((ident
, false)) => {
534 "a label with a similar name exists but is also unreachable",
537 // No similarly-named labels exist.
546 crate fn report_vis_error(&self, vis_resolution_error
: VisResolutionError
<'_
>) {
547 match vis_resolution_error
{
548 VisResolutionError
::Relative2018(span
, path
) => {
549 let mut err
= self.session
.struct_span_err(
551 "relative paths are not supported in visibilities on 2018 edition",
556 format
!("crate::{}", pprust
::path_to_string(&path
)),
557 Applicability
::MaybeIncorrect
,
561 VisResolutionError
::AncestorOnly(span
) => struct_span_err
!(
565 "visibilities can only be restricted to ancestor modules"
567 VisResolutionError
::FailedToResolve(span
, label
, suggestion
) => {
568 self.into_struct_error(span
, ResolutionError
::FailedToResolve { label, suggestion }
)
570 VisResolutionError
::ExpectedFound(span
, path_str
, res
) => {
571 let mut err
= struct_span_err
!(
575 "expected module, found {} `{}`",
579 err
.span_label(span
, "not a module");
582 VisResolutionError
::Indeterminate(span
) => struct_span_err
!(
586 "cannot determine resolution for the visibility"
588 VisResolutionError
::ModuleOnly(span
) => {
589 self.session
.struct_span_err(span
, "visibility must resolve to a module")
595 /// Lookup typo candidate in scope for a macro or import.
596 fn early_lookup_typo_candidate(
599 parent_scope
: &ParentScope
<'a
>,
601 filter_fn
: &impl Fn(Res
) -> bool
,
602 ) -> Option
<TypoSuggestion
> {
603 let mut suggestions
= Vec
::new();
604 self.visit_scopes(scope_set
, parent_scope
, ident
, |this
, scope
, use_prelude
, _
| {
606 Scope
::DeriveHelpers(expn_id
) => {
607 let res
= Res
::NonMacroAttr(NonMacroAttrKind
::DeriveHelper
);
614 .map(|ident
| TypoSuggestion
::from_res(ident
.name
, res
)),
618 Scope
::DeriveHelpersCompat
=> {
619 let res
= Res
::NonMacroAttr(NonMacroAttrKind
::DeriveHelper
);
621 for derive
in parent_scope
.derives
{
622 let parent_scope
= &ParentScope { derives: &[], ..*parent_scope }
;
623 if let Ok((Some(ext
), _
)) = this
.resolve_macro_path(
625 Some(MacroKind
::Derive
),
633 .map(|name
| TypoSuggestion
::from_res(*name
, res
)),
639 Scope
::MacroRules(macro_rules_scope
) => {
640 if let MacroRulesScope
::Binding(macro_rules_binding
) = macro_rules_scope
{
641 let res
= macro_rules_binding
.binding
.res();
644 .push(TypoSuggestion
::from_res(macro_rules_binding
.ident
.name
, res
))
648 Scope
::CrateRoot
=> {
649 let root_ident
= Ident
::new(kw
::PathRoot
, ident
.span
);
650 let root_module
= this
.resolve_crate_root(root_ident
);
651 this
.add_module_candidates(root_module
, &mut suggestions
, filter_fn
);
653 Scope
::Module(module
) => {
654 this
.add_module_candidates(module
, &mut suggestions
, filter_fn
);
656 Scope
::RegisteredAttrs
=> {
657 let res
= Res
::NonMacroAttr(NonMacroAttrKind
::Registered
);
660 this
.registered_attrs
662 .map(|ident
| TypoSuggestion
::from_res(ident
.name
, res
)),
666 Scope
::MacroUsePrelude
=> {
667 suggestions
.extend(this
.macro_use_prelude
.iter().filter_map(
669 let res
= binding
.res();
670 filter_fn(res
).then_some(TypoSuggestion
::from_res(*name
, res
))
674 Scope
::BuiltinAttrs
=> {
675 let res
= Res
::NonMacroAttr(NonMacroAttrKind
::Builtin
);
680 .map(|(name
, ..)| TypoSuggestion
::from_res(*name
, res
)),
684 Scope
::ExternPrelude
=> {
685 suggestions
.extend(this
.extern_prelude
.iter().filter_map(|(ident
, _
)| {
686 let res
= Res
::Def(DefKind
::Mod
, DefId
::local(CRATE_DEF_INDEX
));
687 filter_fn(res
).then_some(TypoSuggestion
::from_res(ident
.name
, res
))
690 Scope
::ToolPrelude
=> {
691 let res
= Res
::NonMacroAttr(NonMacroAttrKind
::Tool
);
693 this
.registered_tools
695 .map(|ident
| TypoSuggestion
::from_res(ident
.name
, res
)),
698 Scope
::StdLibPrelude
=> {
699 if let Some(prelude
) = this
.prelude
{
700 let mut tmp_suggestions
= Vec
::new();
701 this
.add_module_candidates(prelude
, &mut tmp_suggestions
, filter_fn
);
705 .filter(|s
| use_prelude
|| this
.is_builtin_macro(s
.res
)),
709 Scope
::BuiltinTypes
=> {
710 let primitive_types
= &this
.primitive_type_table
.primitive_types
;
711 suggestions
.extend(primitive_types
.iter().flat_map(|(name
, prim_ty
)| {
712 let res
= Res
::PrimTy(*prim_ty
);
713 filter_fn(res
).then_some(TypoSuggestion
::from_res(*name
, res
))
721 // Make sure error reporting is deterministic.
722 suggestions
.sort_by_cached_key(|suggestion
| suggestion
.candidate
.as_str());
724 match find_best_match_for_name(
725 suggestions
.iter().map(|suggestion
| &suggestion
.candidate
),
729 Some(found
) if found
!= ident
.name
=> {
730 suggestions
.into_iter().find(|suggestion
| suggestion
.candidate
== found
)
736 fn lookup_import_candidates_from_module
<FilterFn
>(
739 namespace
: Namespace
,
740 parent_scope
: &ParentScope
<'a
>,
741 start_module
: Module
<'a
>,
744 ) -> Vec
<ImportSuggestion
>
746 FilterFn
: Fn(Res
) -> bool
,
748 let mut candidates
= Vec
::new();
749 let mut seen_modules
= FxHashSet
::default();
750 let not_local_module
= crate_name
.name
!= kw
::Crate
;
752 vec
![(start_module
, Vec
::<ast
::PathSegment
>::new(), true, not_local_module
)];
753 let mut worklist_via_import
= vec
![];
755 while let Some((in_module
, path_segments
, accessible
, in_module_is_extern
)) =
756 match worklist
.pop() {
757 None
=> worklist_via_import
.pop(),
761 // We have to visit module children in deterministic order to avoid
762 // instabilities in reported imports (#43552).
763 in_module
.for_each_child(self, |this
, ident
, ns
, name_binding
| {
764 // avoid non-importable candidates
765 if !name_binding
.is_importable() {
769 let child_accessible
=
770 accessible
&& this
.is_accessible_from(name_binding
.vis
, parent_scope
.module
);
772 // do not venture inside inaccessible items of other crates
773 if in_module_is_extern
&& !child_accessible
{
777 let via_import
= name_binding
.is_import() && !name_binding
.is_extern_crate();
779 // There is an assumption elsewhere that paths of variants are in the enum's
780 // declaration and not imported. With this assumption, the variant component is
781 // chopped and the rest of the path is assumed to be the enum's own path. For
782 // errors where a variant is used as the type instead of the enum, this causes
783 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
784 if via_import
&& name_binding
.is_possibly_imported_variant() {
788 // collect results based on the filter function
789 // avoid suggesting anything from the same module in which we are resolving
790 if ident
.name
== lookup_ident
.name
792 && !ptr
::eq(in_module
, parent_scope
.module
)
794 let res
= name_binding
.res();
797 let mut segms
= path_segments
.clone();
798 if lookup_ident
.span
.rust_2018() {
799 // crate-local absolute paths start with `crate::` in edition 2018
800 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
801 segms
.insert(0, ast
::PathSegment
::from_ident(crate_name
));
804 segms
.push(ast
::PathSegment
::from_ident(ident
));
805 let path
= Path { span: name_binding.span, segments: segms, tokens: None }
;
806 let did
= match res
{
807 Res
::Def(DefKind
::Ctor(..), did
) => this
.parent(did
),
808 _
=> res
.opt_def_id(),
811 if child_accessible
{
812 // Remove invisible match if exists
813 if let Some(idx
) = candidates
815 .position(|v
: &ImportSuggestion
| v
.did
== did
&& !v
.accessible
)
817 candidates
.remove(idx
);
821 if candidates
.iter().all(|v
: &ImportSuggestion
| v
.did
!= did
) {
822 candidates
.push(ImportSuggestion
{
826 accessible
: child_accessible
,
832 // collect submodules to explore
833 if let Some(module
) = name_binding
.module() {
835 let mut path_segments
= path_segments
.clone();
836 path_segments
.push(ast
::PathSegment
::from_ident(ident
));
838 let is_extern_crate_that_also_appears_in_prelude
=
839 name_binding
.is_extern_crate() && lookup_ident
.span
.rust_2018();
841 if !is_extern_crate_that_also_appears_in_prelude
{
842 let is_extern
= in_module_is_extern
|| name_binding
.is_extern_crate();
843 // add the module to the lookup
844 if seen_modules
.insert(module
.def_id().unwrap()) {
845 if via_import { &mut worklist_via_import }
else { &mut worklist }
846 .push((module
, path_segments
, child_accessible
, is_extern
));
853 // If only some candidates are accessible, take just them
854 if !candidates
.iter().all(|v
: &ImportSuggestion
| !v
.accessible
) {
855 candidates
= candidates
.into_iter().filter(|x
| x
.accessible
).collect();
861 /// When name resolution fails, this method can be used to look up candidate
862 /// entities with the expected name. It allows filtering them using the
863 /// supplied predicate (which should be used to only accept the types of
864 /// definitions expected, e.g., traits). The lookup spans across all crates.
866 /// N.B., the method does not look into imports, but this is not a problem,
867 /// since we report the definitions (thus, the de-aliased imports).
868 crate fn lookup_import_candidates
<FilterFn
>(
871 namespace
: Namespace
,
872 parent_scope
: &ParentScope
<'a
>,
874 ) -> Vec
<ImportSuggestion
>
876 FilterFn
: Fn(Res
) -> bool
,
878 let mut suggestions
= self.lookup_import_candidates_from_module(
883 Ident
::with_dummy_span(kw
::Crate
),
887 if lookup_ident
.span
.rust_2018() {
888 let extern_prelude_names
= self.extern_prelude
.clone();
889 for (ident
, _
) in extern_prelude_names
.into_iter() {
890 if ident
.span
.from_expansion() {
891 // Idents are adjusted to the root context before being
892 // resolved in the extern prelude, so reporting this to the
893 // user is no help. This skips the injected
894 // `extern crate std` in the 2018 edition, which would
895 // otherwise cause duplicate suggestions.
898 if let Some(crate_id
) = self.crate_loader
.maybe_process_path_extern(ident
.name
) {
900 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX }
);
901 suggestions
.extend(self.lookup_import_candidates_from_module(
916 crate fn unresolved_macro_suggestions(
918 err
: &mut DiagnosticBuilder
<'a
>,
919 macro_kind
: MacroKind
,
920 parent_scope
: &ParentScope
<'a
>,
923 let is_expected
= &|res
: Res
| res
.macro_kind() == Some(macro_kind
);
924 let suggestion
= self.early_lookup_typo_candidate(
925 ScopeSet
::Macro(macro_kind
),
930 self.add_typo_suggestion(err
, suggestion
, ident
.span
);
932 if macro_kind
== MacroKind
::Derive
&& (ident
.name
== sym
::Send
|| ident
.name
== sym
::Sync
) {
933 let msg
= format
!("unsafe traits like `{}` should be implemented explicitly", ident
);
934 err
.span_note(ident
.span
, &msg
);
936 if self.macro_names
.contains(&ident
.normalize_to_macros_2_0()) {
937 err
.help("have you added the `#[macro_use]` on the module/import?");
941 crate fn add_typo_suggestion(
943 err
: &mut DiagnosticBuilder
<'_
>,
944 suggestion
: Option
<TypoSuggestion
>,
947 let suggestion
= match suggestion
{
948 None
=> return false,
949 // We shouldn't suggest underscore.
950 Some(suggestion
) if suggestion
.candidate
== kw
::Underscore
=> return false,
951 Some(suggestion
) => suggestion
,
953 let def_span
= suggestion
.res
.opt_def_id().and_then(|def_id
| match def_id
.krate
{
954 LOCAL_CRATE
=> self.opt_span(def_id
),
958 .guess_head_span(self.cstore().get_span_untracked(def_id
, self.session
)),
961 if let Some(def_span
) = def_span
{
962 if span
.overlaps(def_span
) {
963 // Don't suggest typo suggestion for itself like in the followoing:
964 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
965 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
968 // | ----------- `X` defined here
970 // LL | const Y: X = X("ö");
971 // | -------------^^^^^^- similarly named constant `Y` defined here
973 // help: use struct literal syntax instead
975 // LL | const Y: X = X {};
977 // help: a constant with a similar name exists
979 // LL | const Y: X = Y("ö");
984 self.session
.source_map().guess_head_span(def_span
),
986 "similarly named {} `{}` defined here",
987 suggestion
.res
.descr(),
988 suggestion
.candidate
.as_str(),
993 "{} {} with a similar name exists",
994 suggestion
.res
.article(),
995 suggestion
.res
.descr()
1000 suggestion
.candidate
.to_string(),
1001 Applicability
::MaybeIncorrect
,
1006 fn binding_description(&self, b
: &NameBinding
<'_
>, ident
: Ident
, from_prelude
: bool
) -> String
{
1008 if b
.span
.is_dummy() {
1009 let add_built_in
= match b
.res() {
1010 // These already contain the "built-in" prefix or look bad with it.
1011 Res
::NonMacroAttr(..) | Res
::PrimTy(..) | Res
::ToolMod
=> false,
1014 let (built_in
, from
) = if from_prelude
{
1015 ("", " from prelude")
1016 } else if b
.is_extern_crate()
1018 && self.session
.opts
.externs
.get(&ident
.as_str()).is_some()
1020 ("", " passed with `--extern`")
1021 } else if add_built_in
{
1027 let article
= if built_in
.is_empty() { res.article() }
else { "a" }
;
1029 "{a}{built_in} {thing}{from}",
1031 thing
= res
.descr(),
1032 built_in
= built_in
,
1036 let introduced
= if b
.is_import() { "imported" }
else { "defined" }
;
1037 format
!("the {thing} {introduced} here", thing
= res
.descr(), introduced
= introduced
)
1041 crate fn report_ambiguity_error(&self, ambiguity_error
: &AmbiguityError
<'_
>) {
1042 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 }
= *ambiguity_error
;
1043 let (b1
, b2
, misc1
, misc2
, swapped
) = if b2
.span
.is_dummy() && !b1
.span
.is_dummy() {
1044 // We have to print the span-less alternative first, otherwise formatting looks bad.
1045 (b2
, b1
, misc2
, misc1
, true)
1047 (b1
, b2
, misc1
, misc2
, false)
1050 let mut err
= struct_span_err
!(
1054 "`{ident}` is ambiguous ({why})",
1058 err
.span_label(ident
.span
, "ambiguous name");
1060 let mut could_refer_to
= |b
: &NameBinding
<'_
>, misc
: AmbiguityErrorMisc
, also
: &str| {
1061 let what
= self.binding_description(b
, ident
, misc
== AmbiguityErrorMisc
::FromPrelude
);
1062 let note_msg
= format
!(
1063 "`{ident}` could{also} refer to {what}",
1069 let thing
= b
.res().descr();
1070 let mut help_msgs
= Vec
::new();
1071 if b
.is_glob_import()
1072 && (kind
== AmbiguityKind
::GlobVsGlob
1073 || kind
== AmbiguityKind
::GlobVsExpanded
1074 || kind
== AmbiguityKind
::GlobVsOuter
&& swapped
!= also
.is_empty())
1076 help_msgs
.push(format
!(
1077 "consider adding an explicit import of \
1078 `{ident}` to disambiguate",
1082 if b
.is_extern_crate() && ident
.span
.rust_2018() {
1083 help_msgs
.push(format
!(
1084 "use `::{ident}` to refer to this {thing} unambiguously",
1089 if misc
== AmbiguityErrorMisc
::SuggestCrate
{
1090 help_msgs
.push(format
!(
1091 "use `crate::{ident}` to refer to this {thing} unambiguously",
1095 } else if misc
== AmbiguityErrorMisc
::SuggestSelf
{
1096 help_msgs
.push(format
!(
1097 "use `self::{ident}` to refer to this {thing} unambiguously",
1103 err
.span_note(b
.span
, ¬e_msg
);
1104 for (i
, help_msg
) in help_msgs
.iter().enumerate() {
1105 let or
= if i
== 0 { "" }
else { "or " }
;
1106 err
.help(&format
!("{}{}", or
, help_msg
));
1110 could_refer_to(b1
, misc1
, "");
1111 could_refer_to(b2
, misc2
, " also");
1115 /// If the binding refers to a tuple struct constructor with fields,
1116 /// returns the span of its fields.
1117 fn ctor_fields_span(&self, binding
: &NameBinding
<'_
>) -> Option
<Span
> {
1118 if let NameBindingKind
::Res(
1119 Res
::Def(DefKind
::Ctor(CtorOf
::Struct
, CtorKind
::Fn
), ctor_def_id
),
1123 let def_id
= (&*self).parent(ctor_def_id
).expect("no parent for a constructor");
1124 let fields
= self.field_names
.get(&def_id
)?
;
1125 let first_field
= fields
.first()?
; // Handle `struct Foo()`
1126 return Some(fields
.iter().fold(first_field
.span
, |acc
, field
| acc
.to(field
.span
)));
1131 crate fn report_privacy_error(&self, privacy_error
: &PrivacyError
<'_
>) {
1132 let PrivacyError { ident, binding, .. }
= *privacy_error
;
1134 let res
= binding
.res();
1135 let ctor_fields_span
= self.ctor_fields_span(binding
);
1136 let plain_descr
= res
.descr().to_string();
1137 let nonimport_descr
=
1138 if ctor_fields_span
.is_some() { plain_descr + " constructor" }
else { plain_descr }
;
1139 let import_descr
= nonimport_descr
.clone() + " import";
1141 |b
: &NameBinding
<'_
>| if b
.is_import() { &import_descr }
else { &nonimport_descr }
;
1143 // Print the primary message.
1144 let descr
= get_descr(binding
);
1146 struct_span_err
!(self.session
, ident
.span
, E0603
, "{} `{}` is private", descr
, ident
);
1147 err
.span_label(ident
.span
, &format
!("private {}", descr
));
1148 if let Some(span
) = ctor_fields_span
{
1149 err
.span_label(span
, "a constructor is private if any of the fields is private");
1152 // Print the whole import chain to make it easier to see what happens.
1153 let first_binding
= binding
;
1154 let mut next_binding
= Some(binding
);
1155 let mut next_ident
= ident
;
1156 while let Some(binding
) = next_binding
{
1157 let name
= next_ident
;
1158 next_binding
= match binding
.kind
{
1159 _
if res
== Res
::Err
=> None
,
1160 NameBindingKind
::Import { binding, import, .. }
=> match import
.kind
{
1161 _
if binding
.span
.is_dummy() => None
,
1162 ImportKind
::Single { source, .. }
=> {
1163 next_ident
= source
;
1166 ImportKind
::Glob { .. }
| ImportKind
::MacroUse
=> Some(binding
),
1167 ImportKind
::ExternCrate { .. }
=> None
,
1172 let first
= ptr
::eq(binding
, first_binding
);
1173 let descr
= get_descr(binding
);
1175 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1176 and_refers_to
= if first { "" }
else { "...and refers to " }
,
1179 which
= if first { "" }
else { " which" }
,
1180 dots
= if next_binding
.is_some() { "..." }
else { "" }
,
1182 let def_span
= self.session
.source_map().guess_head_span(binding
.span
);
1183 let mut note_span
= MultiSpan
::from_span(def_span
);
1184 if !first
&& binding
.vis
== ty
::Visibility
::Public
{
1185 note_span
.push_span_label(def_span
, "consider importing it directly".into());
1187 err
.span_note(note_span
, &msg
);
1194 impl<'a
, 'b
> ImportResolver
<'a
, 'b
> {
1195 /// Adds suggestions for a path that cannot be resolved.
1196 pub(crate) fn make_path_suggestion(
1199 mut path
: Vec
<Segment
>,
1200 parent_scope
: &ParentScope
<'b
>,
1201 ) -> Option
<(Vec
<Segment
>, Vec
<String
>)> {
1202 debug
!("make_path_suggestion: span={:?} path={:?}", span
, path
);
1204 match (path
.get(0), path
.get(1)) {
1205 // `{{root}}::ident::...` on both editions.
1206 // On 2015 `{{root}}` is usually added implicitly.
1207 (Some(fst
), Some(snd
))
1208 if fst
.ident
.name
== kw
::PathRoot
&& !snd
.ident
.is_path_segment_keyword() => {}
1209 // `ident::...` on 2018.
1211 if fst
.ident
.span
.rust_2018() && !fst
.ident
.is_path_segment_keyword() =>
1213 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1214 path
.insert(0, Segment
::from_ident(Ident
::invalid()));
1219 self.make_missing_self_suggestion(span
, path
.clone(), parent_scope
)
1220 .or_else(|| self.make_missing_crate_suggestion(span
, path
.clone(), parent_scope
))
1221 .or_else(|| self.make_missing_super_suggestion(span
, path
.clone(), parent_scope
))
1222 .or_else(|| self.make_external_crate_suggestion(span
, path
, parent_scope
))
1225 /// Suggest a missing `self::` if that resolves to an correct module.
1229 /// LL | use foo::Bar;
1230 /// | ^^^ did you mean `self::foo`?
1232 fn make_missing_self_suggestion(
1235 mut path
: Vec
<Segment
>,
1236 parent_scope
: &ParentScope
<'b
>,
1237 ) -> Option
<(Vec
<Segment
>, Vec
<String
>)> {
1238 // Replace first ident with `self` and check if that is valid.
1239 path
[0].ident
.name
= kw
::SelfLower
;
1240 let result
= self.r
.resolve_path(&path
, None
, parent_scope
, false, span
, CrateLint
::No
);
1241 debug
!("make_missing_self_suggestion: path={:?} result={:?}", path
, result
);
1242 if let PathResult
::Module(..) = result { Some((path, Vec::new())) }
else { None }
1245 /// Suggests a missing `crate::` if that resolves to an correct module.
1249 /// LL | use foo::Bar;
1250 /// | ^^^ did you mean `crate::foo`?
1252 fn make_missing_crate_suggestion(
1255 mut path
: Vec
<Segment
>,
1256 parent_scope
: &ParentScope
<'b
>,
1257 ) -> Option
<(Vec
<Segment
>, Vec
<String
>)> {
1258 // Replace first ident with `crate` and check if that is valid.
1259 path
[0].ident
.name
= kw
::Crate
;
1260 let result
= self.r
.resolve_path(&path
, None
, parent_scope
, false, span
, CrateLint
::No
);
1261 debug
!("make_missing_crate_suggestion: path={:?} result={:?}", path
, result
);
1262 if let PathResult
::Module(..) = result
{
1266 "`use` statements changed in Rust 2018; read more at \
1267 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1277 /// Suggests a missing `super::` if that resolves to an correct module.
1281 /// LL | use foo::Bar;
1282 /// | ^^^ did you mean `super::foo`?
1284 fn make_missing_super_suggestion(
1287 mut path
: Vec
<Segment
>,
1288 parent_scope
: &ParentScope
<'b
>,
1289 ) -> Option
<(Vec
<Segment
>, Vec
<String
>)> {
1290 // Replace first ident with `crate` and check if that is valid.
1291 path
[0].ident
.name
= kw
::Super
;
1292 let result
= self.r
.resolve_path(&path
, None
, parent_scope
, false, span
, CrateLint
::No
);
1293 debug
!("make_missing_super_suggestion: path={:?} result={:?}", path
, result
);
1294 if let PathResult
::Module(..) = result { Some((path, Vec::new())) }
else { None }
1297 /// Suggests a missing external crate name if that resolves to an correct module.
1301 /// LL | use foobar::Baz;
1302 /// | ^^^^^^ did you mean `baz::foobar`?
1305 /// Used when importing a submodule of an external crate but missing that crate's
1306 /// name as the first part of path.
1307 fn make_external_crate_suggestion(
1310 mut path
: Vec
<Segment
>,
1311 parent_scope
: &ParentScope
<'b
>,
1312 ) -> Option
<(Vec
<Segment
>, Vec
<String
>)> {
1313 if path
[1].ident
.span
.rust_2015() {
1317 // Sort extern crate names in reverse order to get
1318 // 1) some consistent ordering for emitted diagnostics, and
1319 // 2) `std` suggestions before `core` suggestions.
1320 let mut extern_crate_names
=
1321 self.r
.extern_prelude
.iter().map(|(ident
, _
)| ident
.name
).collect
::<Vec
<_
>>();
1322 extern_crate_names
.sort_by_key(|name
| Reverse(name
.as_str()));
1324 for name
in extern_crate_names
.into_iter() {
1325 // Replace first ident with a crate name and check if that is valid.
1326 path
[0].ident
.name
= name
;
1327 let result
= self.r
.resolve_path(&path
, None
, parent_scope
, false, span
, CrateLint
::No
);
1329 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1332 if let PathResult
::Module(..) = result
{
1333 return Some((path
, Vec
::new()));
1340 /// Suggests importing a macro from the root of the crate rather than a module within
1344 /// help: a macro with this name exists at the root of the crate
1346 /// LL | use issue_59764::makro;
1347 /// | ^^^^^^^^^^^^^^^^^^
1349 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
1350 /// at the root of the crate instead of the module where it is defined
1352 pub(crate) fn check_for_module_export_macro(
1354 import
: &'b Import
<'b
>,
1355 module
: ModuleOrUniformRoot
<'b
>,
1357 ) -> Option
<(Option
<Suggestion
>, Vec
<String
>)> {
1358 let mut crate_module
= if let ModuleOrUniformRoot
::Module(module
) = module
{
1364 while let Some(parent
) = crate_module
.parent
{
1365 crate_module
= parent
;
1368 if ModuleOrUniformRoot
::same_def(ModuleOrUniformRoot
::Module(crate_module
), module
) {
1369 // Don't make a suggestion if the import was already from the root of the
1374 let resolutions
= self.r
.resolutions(crate_module
).borrow();
1375 let resolution
= resolutions
.get(&self.r
.new_key(ident
, MacroNS
))?
;
1376 let binding
= resolution
.borrow().binding()?
;
1377 if let Res
::Def(DefKind
::Macro(MacroKind
::Bang
), _
) = binding
.res() {
1378 let module_name
= crate_module
.kind
.name().unwrap();
1379 let import_snippet
= match import
.kind
{
1380 ImportKind
::Single { source, target, .. }
if source
!= target
=> {
1381 format
!("{} as {}", source
, target
)
1383 _
=> format
!("{}", ident
),
1386 let mut corrections
: Vec
<(Span
, String
)> = Vec
::new();
1387 if !import
.is_nested() {
1388 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1389 // intermediate segments.
1390 corrections
.push((import
.span
, format
!("{}::{}", module_name
, import_snippet
)));
1392 // Find the binding span (and any trailing commas and spaces).
1393 // ie. `use a::b::{c, d, e};`
1395 let (found_closing_brace
, binding_span
) = find_span_of_binding_until_next_binding(
1401 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1402 found_closing_brace
, binding_span
1405 let mut removal_span
= binding_span
;
1406 if found_closing_brace
{
1407 // If the binding span ended with a closing brace, as in the below example:
1408 // ie. `use a::b::{c, d};`
1410 // Then expand the span of characters to remove to include the previous
1411 // binding's trailing comma.
1412 // ie. `use a::b::{c, d};`
1414 if let Some(previous_span
) =
1415 extend_span_to_previous_binding(self.r
.session
, binding_span
)
1417 debug
!("check_for_module_export_macro: previous_span={:?}", previous_span
);
1418 removal_span
= removal_span
.with_lo(previous_span
.lo());
1421 debug
!("check_for_module_export_macro: removal_span={:?}", removal_span
);
1423 // Remove the `removal_span`.
1424 corrections
.push((removal_span
, "".to_string()));
1426 // Find the span after the crate name and if it has nested imports immediatately
1427 // after the crate name already.
1428 // ie. `use a::b::{c, d};`
1430 // or `use a::{b, c, d}};`
1432 let (has_nested
, after_crate_name
) = find_span_immediately_after_crate_name(
1438 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1439 has_nested
, after_crate_name
1442 let source_map
= self.r
.session
.source_map();
1444 // Add the import to the start, with a `{` if required.
1445 let start_point
= source_map
.start_point(after_crate_name
);
1446 if let Ok(start_snippet
) = source_map
.span_to_snippet(start_point
) {
1450 // In this case, `start_snippet` must equal '{'.
1451 format
!("{}{}, ", start_snippet
, import_snippet
)
1453 // In this case, add a `{`, then the moved import, then whatever
1454 // was there before.
1455 format
!("{{{}, {}", import_snippet
, start_snippet
)
1460 // Add a `};` to the end if nested, matching the `{` added at the start.
1462 corrections
.push((source_map
.end_point(after_crate_name
), "};".to_string()));
1466 let suggestion
= Some((
1468 String
::from("a macro with this name exists at the root of the crate"),
1469 Applicability
::MaybeIncorrect
,
1472 "this could be because a macro annotated with `#[macro_export]` will be exported \
1473 at the root of the crate instead of the module where it is defined"
1476 Some((suggestion
, note
))
1483 /// Given a `binding_span` of a binding within a use statement:
1486 /// use foo::{a, b, c};
1490 /// then return the span until the next binding or the end of the statement:
1493 /// use foo::{a, b, c};
1496 pub(crate) fn find_span_of_binding_until_next_binding(
1501 let source_map
= sess
.source_map();
1503 // Find the span of everything after the binding.
1504 // ie. `a, e};` or `a};`
1505 let binding_until_end
= binding_span
.with_hi(use_span
.hi());
1507 // Find everything after the binding but not including the binding.
1508 // ie. `, e};` or `};`
1509 let after_binding_until_end
= binding_until_end
.with_lo(binding_span
.hi());
1511 // Keep characters in the span until we encounter something that isn't a comma or
1515 // Also note whether a closing brace character was encountered. If there
1516 // was, then later go backwards to remove any trailing commas that are left.
1517 let mut found_closing_brace
= false;
1518 let after_binding_until_next_binding
=
1519 source_map
.span_take_while(after_binding_until_end
, |&ch
| {
1521 found_closing_brace
= true;
1523 ch
== ' '
|| ch
== '
,'
1526 // Combine the two spans.
1527 // ie. `a, ` or `a`.
1529 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1530 let span
= binding_span
.with_hi(after_binding_until_next_binding
.hi());
1532 (found_closing_brace
, span
)
1535 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1539 /// use foo::a::{a, b, c};
1540 /// ^^--- binding span
1544 /// use foo::{a, b, c};
1545 /// --- binding span
1547 pub(crate) fn extend_span_to_previous_binding(sess
: &Session
, binding_span
: Span
) -> Option
<Span
> {
1548 let source_map
= sess
.source_map();
1550 // `prev_source` will contain all of the source that came before the span.
1551 // Then split based on a command and take the first (ie. closest to our span)
1552 // snippet. In the example, this is a space.
1553 let prev_source
= source_map
.span_to_prev_source(binding_span
).ok()?
;
1555 let prev_comma
= prev_source
.rsplit('
,'
).collect
::<Vec
<_
>>();
1556 let prev_starting_brace
= prev_source
.rsplit('
{'
).collect
::<Vec
<_
>>();
1557 if prev_comma
.len() <= 1 || prev_starting_brace
.len() <= 1 {
1561 let prev_comma
= prev_comma
.first().unwrap();
1562 let prev_starting_brace
= prev_starting_brace
.first().unwrap();
1564 // If the amount of source code before the comma is greater than
1565 // the amount of source code before the starting brace then we've only
1566 // got one item in the nested item (eg. `issue_52891::{self}`).
1567 if prev_comma
.len() > prev_starting_brace
.len() {
1571 Some(binding_span
.with_lo(BytePos(
1572 // Take away the number of bytes for the characters we've found and an
1573 // extra for the comma.
1574 binding_span
.lo().0 - (prev_comma
.as_bytes().len() as u32) - 1,
1578 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1579 /// it is a nested use tree.
1582 /// use foo::a::{b, c};
1583 /// ^^^^^^^^^^ // false
1585 /// use foo::{a, b, c};
1586 /// ^^^^^^^^^^ // true
1588 /// use foo::{a, b::{c, d}};
1589 /// ^^^^^^^^^^^^^^^ // true
1591 fn find_span_immediately_after_crate_name(
1593 module_name
: Symbol
,
1597 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1598 module_name
, use_span
1600 let source_map
= sess
.source_map();
1602 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1603 let mut num_colons
= 0;
1604 // Find second colon.. `use issue_59764:`
1605 let until_second_colon
= source_map
.span_take_while(use_span
, |c
| {
1610 '
:'
if num_colons
== 2 => false,
1614 // Find everything after the second colon.. `foo::{baz, makro};`
1615 let from_second_colon
= use_span
.with_lo(until_second_colon
.hi() + BytePos(1));
1617 let mut found_a_non_whitespace_character
= false;
1618 // Find the first non-whitespace character in `from_second_colon`.. `f`
1619 let after_second_colon
= source_map
.span_take_while(from_second_colon
, |c
| {
1620 if found_a_non_whitespace_character
{
1623 if !c
.is_whitespace() {
1624 found_a_non_whitespace_character
= true;
1629 // Find the first `{` in from_second_colon.. `foo::{`
1630 let next_left_bracket
= source_map
.span_through_char(from_second_colon
, '
{'
);
1632 (next_left_bracket
== after_second_colon
, from_second_colon
)
1635 /// When an entity with a given name is not available in scope, we search for
1636 /// entities with that name in all crates. This method allows outputting the
1637 /// results of this search in a programmer-friendly way
1638 crate fn show_candidates(
1639 err
: &mut DiagnosticBuilder
<'_
>,
1640 // This is `None` if all placement locations are inside expansions
1641 use_placement_span
: Option
<Span
>,
1642 candidates
: &[ImportSuggestion
],
1646 if candidates
.is_empty() {
1650 // we want consistent results across executions, but candidates are produced
1651 // by iterating through a hash map, so make sure they are ordered:
1652 let mut path_strings
: Vec
<_
> =
1653 candidates
.iter().map(|c
| path_names_to_string(&c
.path
)).collect();
1655 path_strings
.sort();
1656 path_strings
.dedup();
1658 let (determiner
, kind
) = if candidates
.len() == 1 {
1659 ("this", candidates
[0].descr
)
1661 ("one of these", "items")
1664 let instead
= if instead { " instead" }
else { "" }
;
1665 let mut msg
= format
!("consider importing {} {}{}", determiner
, kind
, instead
);
1667 if let Some(span
) = use_placement_span
{
1668 for candidate
in &mut path_strings
{
1669 // produce an additional newline to separate the new use statement
1670 // from the directly following item.
1671 let additional_newline
= if found_use { "" }
else { "\n" }
;
1672 *candidate
= format
!("use {};\n{}", candidate
, additional_newline
);
1675 err
.span_suggestions(span
, &msg
, path_strings
.into_iter(), Applicability
::Unspecified
);
1679 for candidate
in path_strings
{
1681 msg
.push_str(&candidate
);