]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_resolve/src/diagnostics.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_resolve / src / diagnostics.rs
1 use std::cmp::Reverse;
2 use std::ptr;
3
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};
20 use tracing::debug;
21
22 use crate::imports::{Import, ImportKind, ImportResolver};
23 use crate::path_names_to_string;
24 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
25 use crate::{
26 BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot,
27 };
28 use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
29 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
30
31 type Res = def::Res<ast::NodeId>;
32
33 /// A vector of spans and replacements, a message and applicability.
34 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
35
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);
39
40 crate struct TypoSuggestion {
41 pub candidate: Symbol,
42 pub res: Res,
43 }
44
45 impl TypoSuggestion {
46 crate fn from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
47 TypoSuggestion { candidate, res }
48 }
49 }
50
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,
55 pub path: Path,
56 pub accessible: bool,
57 }
58
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"`).
62 ///
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)
69 }
70
71 impl<'a> Resolver<'a> {
72 crate fn add_module_candidates(
73 &mut self,
74 module: Module<'a>,
75 names: &mut Vec<TypoSuggestion>,
76 filter_fn: &impl Fn(Res) -> bool,
77 ) {
78 for (key, resolution) in self.resolutions(module).borrow().iter() {
79 if let Some(binding) = resolution.borrow().binding {
80 let res = binding.res();
81 if filter_fn(res) {
82 names.push(TypoSuggestion::from_res(key.ident.name, res));
83 }
84 }
85 }
86 }
87
88 /// Combines an error with provided span and emits it.
89 ///
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();
94 }
95
96 crate fn into_struct_error(
97 &self,
98 span: Span,
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!(
104 self.session,
105 span,
106 E0401,
107 "can't use generic parameters from outer function",
108 );
109 err.span_label(span, "use of generic parameter from outer function".to_string());
110
111 let sm = self.session.source_map();
112 match outer_res {
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))
116 {
117 err.span_label(
118 reduce_impl_span_to_impl_keyword(sm, impl_span),
119 "`Self` type implicitly declared here, by this `impl`",
120 );
121 }
122 match (maybe_trait_defid, maybe_impl_defid) {
123 (Some(_), None) => {
124 err.span_label(span, "can't use `Self` here");
125 }
126 (_, Some(_)) => {
127 err.span_label(span, "use a type here instead");
128 }
129 (None, None) => bug!("`impl` without trait nor type?"),
130 }
131 return err;
132 }
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");
136 }
137 }
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");
141 }
142 }
143 _ => {
144 bug!(
145 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
146 DefKind::TyParam"
147 );
148 }
149 }
150
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
157 err.span_suggestion(
158 sugg_span,
159 sugg_msg,
160 snippet,
161 Applicability::MachineApplicable,
162 );
163 } else if let Some(sp) = sm.generate_fn_name_span(span) {
164 err.span_label(
165 sp,
166 "try adding a local generic parameter in this method instead"
167 .to_string(),
168 );
169 } else {
170 err.help("try using a local generic parameter instead");
171 }
172 }
173
174 err
175 }
176 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
177 let mut err = struct_span_err!(
178 self.session,
179 span,
180 E0403,
181 "the name `{}` is already used for a generic \
182 parameter in this item's generic parameters",
183 name,
184 );
185 err.span_label(span, "already used");
186 err.span_label(first_use_span, format!("first use of `{}`", name));
187 err
188 }
189 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
190 let mut err = struct_span_err!(
191 self.session,
192 span,
193 E0407,
194 "method `{}` is not a member of trait `{}`",
195 method,
196 trait_
197 );
198 err.span_label(span, format!("not a member of trait `{}`", trait_));
199 err
200 }
201 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
202 let mut err = struct_span_err!(
203 self.session,
204 span,
205 E0437,
206 "type `{}` is not a member of trait `{}`",
207 type_,
208 trait_
209 );
210 err.span_label(span, format!("not a member of trait `{}`", trait_));
211 err
212 }
213 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
214 let mut err = struct_span_err!(
215 self.session,
216 span,
217 E0438,
218 "const `{}` is not a member of trait `{}`",
219 const_,
220 trait_
221 );
222 err.span_label(span, format!("not a member of trait `{}`", trait_));
223 err
224 }
225 ResolutionError::VariableNotBoundInPattern(binding_error) => {
226 let BindingError { name, target, origin, could_be_path } = binding_error;
227
228 let target_sp = target.iter().copied().collect::<Vec<_>>();
229 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
230
231 let msp = MultiSpan::from_spans(target_sp.clone());
232 let mut err = struct_span_err!(
233 self.session,
234 msp,
235 E0408,
236 "variable `{}` is not bound in all patterns",
237 name,
238 );
239 for sp in target_sp {
240 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
241 }
242 for sp in origin_sp {
243 err.span_label(sp, "variable not in all patterns");
244 }
245 if *could_be_path {
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: `?::{}`",
249 name,
250 );
251 err.span_help(span, &help_msg);
252 }
253 err
254 }
255 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
256 let mut err = struct_span_err!(
257 self.session,
258 span,
259 E0409,
260 "variable `{}` is bound inconsistently across alternatives separated by `|`",
261 variable_name
262 );
263 err.span_label(span, "bound in different ways");
264 err.span_label(first_binding_span, "first binding");
265 err
266 }
267 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
268 let mut err = struct_span_err!(
269 self.session,
270 span,
271 E0415,
272 "identifier `{}` is bound more than once in this parameter list",
273 identifier
274 );
275 err.span_label(span, "used as parameter more than once");
276 err
277 }
278 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
279 let mut err = struct_span_err!(
280 self.session,
281 span,
282 E0416,
283 "identifier `{}` is bound more than once in the same pattern",
284 identifier
285 );
286 err.span_label(span, "used in a pattern more than once");
287 err
288 }
289 ResolutionError::UndeclaredLabel { name, suggestion } => {
290 let mut err = struct_span_err!(
291 self.session,
292 span,
293 E0426,
294 "use of undeclared label `{}`",
295 name
296 );
297
298 err.span_label(span, format!("undeclared label `{}`", name));
299
300 match suggestion {
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");
304 err.span_suggestion(
305 span,
306 "try using similarly named label",
307 ident.name.to_string(),
308 Applicability::MaybeIncorrect,
309 );
310 }
311 // An unreachable label with a similar name exists.
312 Some((ident, false)) => {
313 err.span_label(
314 ident.span,
315 "a label with a similar name exists but is unreachable",
316 );
317 }
318 // No similarly-named labels exist.
319 None => (),
320 }
321
322 err
323 }
324 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
325 let mut err = struct_span_err!(
326 self.session,
327 span,
328 E0429,
329 "{}",
330 "`self` imports are only allowed within a { } list"
331 );
332
333 // None of the suggestions below would help with a case like `use self`.
334 if !root {
335 // use foo::bar::self -> foo::bar
336 // use foo::bar::self as abc -> foo::bar as abc
337 err.span_suggestion(
338 span,
339 "consider importing the module directly",
340 "".to_string(),
341 Applicability::MachineApplicable,
342 );
343
344 // use foo::bar::self -> foo::bar::{self}
345 // use foo::bar::self as abc -> foo::bar::{self as abc}
346 let braces = vec![
347 (span_with_rename.shrink_to_lo(), "{".to_string()),
348 (span_with_rename.shrink_to_hi(), "}".to_string()),
349 ];
350 err.multipart_suggestion(
351 "alternatively, use the multi-path `use` syntax to import `self`",
352 braces,
353 Applicability::MachineApplicable,
354 );
355 }
356 err
357 }
358 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
359 let mut err = struct_span_err!(
360 self.session,
361 span,
362 E0430,
363 "`self` import can only appear once in an import list"
364 );
365 err.span_label(span, "can only appear once in an import list");
366 err
367 }
368 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
369 let mut err = struct_span_err!(
370 self.session,
371 span,
372 E0431,
373 "`self` import can only appear in an import list with \
374 a non-empty prefix"
375 );
376 err.span_label(span, "can only appear in an import list with a non-empty prefix");
377 err
378 }
379 ResolutionError::FailedToResolve { label, suggestion } => {
380 let mut err =
381 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
382 err.span_label(span, label);
383
384 if let Some((suggestions, msg, applicability)) = suggestion {
385 err.multipart_suggestion(&msg, suggestions, applicability);
386 }
387
388 err
389 }
390 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
391 let mut err = struct_span_err!(
392 self.session,
393 span,
394 E0434,
395 "{}",
396 "can't capture dynamic environment in a fn item"
397 );
398 err.help("use the `|| { ... }` closure form instead");
399 err
400 }
401 ResolutionError::AttemptToUseNonConstantValueInConstant => {
402 let mut err = struct_span_err!(
403 self.session,
404 span,
405 E0435,
406 "attempt to use a non-constant value in a constant"
407 );
408 err.span_label(span, "non-constant value");
409 err
410 }
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!(
415 self.session,
416 span,
417 E0530,
418 "{}s cannot shadow {}s",
419 what_binding,
420 shadows_what
421 );
422 err.span_label(
423 span,
424 format!("cannot be named the same as {} {}", res.article(), shadows_what),
425 );
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);
429 err
430 }
431 ResolutionError::ForwardDeclaredTyParam => {
432 let mut err = struct_span_err!(
433 self.session,
434 span,
435 E0128,
436 "type parameters with a default cannot use \
437 forward declared identifiers"
438 );
439 err.span_label(
440 span,
441 "defaulted type parameters cannot be forward declared".to_string(),
442 );
443 err
444 }
445 ResolutionError::ParamInTyOfConstParam(name) => {
446 let mut err = struct_span_err!(
447 self.session,
448 span,
449 E0770,
450 "the type of const parameters must not depend on other generic parameters"
451 );
452 err.span_label(
453 span,
454 format!("the type must not depend on the parameter `{}`", name),
455 );
456 err
457 }
458 ResolutionError::ParamInAnonConstInTyDefault(name) => {
459 let mut err = self.session.struct_span_err(
460 span,
461 "constant values inside of type parameter defaults must not depend on generic parameters",
462 );
463 err.span_label(
464 span,
465 format!("the anonymous constant must not depend on the parameter `{}`", name),
466 );
467 err
468 }
469 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
470 let mut err = self.session.struct_span_err(
471 span,
472 "generic parameters may not be used in const operations",
473 );
474 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
475
476 if is_type {
477 err.note("type parameters may not be used in const expressions");
478 } else {
479 err.help(&format!(
480 "const parameters may only be used as standalone arguments, i.e. `{}`",
481 name
482 ));
483 }
484
485 err
486 }
487 ResolutionError::SelfInTyParamDefault => {
488 let mut err = struct_span_err!(
489 self.session,
490 span,
491 E0735,
492 "type parameters cannot use `Self` in their defaults"
493 );
494 err.span_label(span, "`Self` in type parameter default".to_string());
495 err
496 }
497 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
498 let mut err = struct_span_err!(
499 self.session,
500 span,
501 E0767,
502 "use of unreachable label `{}`",
503 name,
504 );
505
506 err.span_label(definition_span, "unreachable label defined here");
507 err.span_label(span, format!("unreachable label `{}`", name));
508 err.note(
509 "labels are unreachable through functions, closures, async blocks and modules",
510 );
511
512 match suggestion {
513 // A reachable label with a similar name exists.
514 Some((ident, true)) => {
515 err.span_label(ident.span, "a label with a similar name is reachable");
516 err.span_suggestion(
517 span,
518 "try using similarly named label",
519 ident.name.to_string(),
520 Applicability::MaybeIncorrect,
521 );
522 }
523 // An unreachable label with a similar name exists.
524 Some((ident, false)) => {
525 err.span_label(
526 ident.span,
527 "a label with a similar name exists but is also unreachable",
528 );
529 }
530 // No similarly-named labels exist.
531 None => (),
532 }
533
534 err
535 }
536 }
537 }
538
539 crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
540 match vis_resolution_error {
541 VisResolutionError::Relative2018(span, path) => {
542 let mut err = self.session.struct_span_err(
543 span,
544 "relative paths are not supported in visibilities on 2018 edition",
545 );
546 err.span_suggestion(
547 path.span,
548 "try",
549 format!("crate::{}", pprust::path_to_string(&path)),
550 Applicability::MaybeIncorrect,
551 );
552 err
553 }
554 VisResolutionError::AncestorOnly(span) => struct_span_err!(
555 self.session,
556 span,
557 E0742,
558 "visibilities can only be restricted to ancestor modules"
559 ),
560 VisResolutionError::FailedToResolve(span, label, suggestion) => {
561 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
562 }
563 VisResolutionError::ExpectedFound(span, path_str, res) => {
564 let mut err = struct_span_err!(
565 self.session,
566 span,
567 E0577,
568 "expected module, found {} `{}`",
569 res.descr(),
570 path_str
571 );
572 err.span_label(span, "not a module");
573 err
574 }
575 VisResolutionError::Indeterminate(span) => struct_span_err!(
576 self.session,
577 span,
578 E0578,
579 "cannot determine resolution for the visibility"
580 ),
581 VisResolutionError::ModuleOnly(span) => {
582 self.session.struct_span_err(span, "visibility must resolve to a module")
583 }
584 }
585 .emit()
586 }
587
588 /// Lookup typo candidate in scope for a macro or import.
589 fn early_lookup_typo_candidate(
590 &mut self,
591 scope_set: ScopeSet,
592 parent_scope: &ParentScope<'a>,
593 ident: Ident,
594 filter_fn: &impl Fn(Res) -> bool,
595 ) -> Option<TypoSuggestion> {
596 let mut suggestions = Vec::new();
597 self.visit_scopes(scope_set, parent_scope, ident, |this, scope, use_prelude, _| {
598 match scope {
599 Scope::DeriveHelpers(expn_id) => {
600 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
601 if filter_fn(res) {
602 suggestions.extend(
603 this.helper_attrs
604 .get(&expn_id)
605 .into_iter()
606 .flatten()
607 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
608 );
609 }
610 }
611 Scope::DeriveHelpersCompat => {
612 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
613 if filter_fn(res) {
614 for derive in parent_scope.derives {
615 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
616 if let Ok((Some(ext), _)) = this.resolve_macro_path(
617 derive,
618 Some(MacroKind::Derive),
619 parent_scope,
620 false,
621 false,
622 ) {
623 suggestions.extend(
624 ext.helper_attrs
625 .iter()
626 .map(|name| TypoSuggestion::from_res(*name, res)),
627 );
628 }
629 }
630 }
631 }
632 Scope::MacroRules(macro_rules_scope) => {
633 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
634 let res = macro_rules_binding.binding.res();
635 if filter_fn(res) {
636 suggestions
637 .push(TypoSuggestion::from_res(macro_rules_binding.ident.name, res))
638 }
639 }
640 }
641 Scope::CrateRoot => {
642 let root_ident = Ident::new(kw::PathRoot, ident.span);
643 let root_module = this.resolve_crate_root(root_ident);
644 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
645 }
646 Scope::Module(module) => {
647 this.add_module_candidates(module, &mut suggestions, filter_fn);
648 }
649 Scope::RegisteredAttrs => {
650 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
651 if filter_fn(res) {
652 suggestions.extend(
653 this.registered_attrs
654 .iter()
655 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
656 );
657 }
658 }
659 Scope::MacroUsePrelude => {
660 suggestions.extend(this.macro_use_prelude.iter().filter_map(
661 |(name, binding)| {
662 let res = binding.res();
663 filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
664 },
665 ));
666 }
667 Scope::BuiltinAttrs => {
668 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
669 if filter_fn(res) {
670 suggestions.extend(
671 BUILTIN_ATTRIBUTES
672 .iter()
673 .map(|(name, ..)| TypoSuggestion::from_res(*name, res)),
674 );
675 }
676 }
677 Scope::ExternPrelude => {
678 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
679 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
680 filter_fn(res).then_some(TypoSuggestion::from_res(ident.name, res))
681 }));
682 }
683 Scope::ToolPrelude => {
684 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
685 suggestions.extend(
686 this.registered_tools
687 .iter()
688 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
689 );
690 }
691 Scope::StdLibPrelude => {
692 if let Some(prelude) = this.prelude {
693 let mut tmp_suggestions = Vec::new();
694 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
695 suggestions.extend(
696 tmp_suggestions
697 .into_iter()
698 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
699 );
700 }
701 }
702 Scope::BuiltinTypes => {
703 let primitive_types = &this.primitive_type_table.primitive_types;
704 suggestions.extend(primitive_types.iter().flat_map(|(name, prim_ty)| {
705 let res = Res::PrimTy(*prim_ty);
706 filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
707 }))
708 }
709 }
710
711 None::<()>
712 });
713
714 // Make sure error reporting is deterministic.
715 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
716
717 match find_best_match_for_name(
718 suggestions.iter().map(|suggestion| &suggestion.candidate),
719 ident.name,
720 None,
721 ) {
722 Some(found) if found != ident.name => {
723 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
724 }
725 _ => None,
726 }
727 }
728
729 fn lookup_import_candidates_from_module<FilterFn>(
730 &mut self,
731 lookup_ident: Ident,
732 namespace: Namespace,
733 parent_scope: &ParentScope<'a>,
734 start_module: Module<'a>,
735 crate_name: Ident,
736 filter_fn: FilterFn,
737 ) -> Vec<ImportSuggestion>
738 where
739 FilterFn: Fn(Res) -> bool,
740 {
741 let mut candidates = Vec::new();
742 let mut seen_modules = FxHashSet::default();
743 let not_local_module = crate_name.name != kw::Crate;
744 let mut worklist =
745 vec![(start_module, Vec::<ast::PathSegment>::new(), true, not_local_module)];
746 let mut worklist_via_import = vec![];
747
748 while let Some((in_module, path_segments, accessible, in_module_is_extern)) =
749 match worklist.pop() {
750 None => worklist_via_import.pop(),
751 Some(x) => Some(x),
752 }
753 {
754 // We have to visit module children in deterministic order to avoid
755 // instabilities in reported imports (#43552).
756 in_module.for_each_child(self, |this, ident, ns, name_binding| {
757 // avoid non-importable candidates
758 if !name_binding.is_importable() {
759 return;
760 }
761
762 let child_accessible =
763 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
764
765 // do not venture inside inaccessible items of other crates
766 if in_module_is_extern && !child_accessible {
767 return;
768 }
769
770 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
771
772 // There is an assumption elsewhere that paths of variants are in the enum's
773 // declaration and not imported. With this assumption, the variant component is
774 // chopped and the rest of the path is assumed to be the enum's own path. For
775 // errors where a variant is used as the type instead of the enum, this causes
776 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
777 if via_import && name_binding.is_possibly_imported_variant() {
778 return;
779 }
780
781 // collect results based on the filter function
782 // avoid suggesting anything from the same module in which we are resolving
783 if ident.name == lookup_ident.name
784 && ns == namespace
785 && !ptr::eq(in_module, parent_scope.module)
786 {
787 let res = name_binding.res();
788 if filter_fn(res) {
789 // create the path
790 let mut segms = path_segments.clone();
791 if lookup_ident.span.rust_2018() {
792 // crate-local absolute paths start with `crate::` in edition 2018
793 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
794 segms.insert(0, ast::PathSegment::from_ident(crate_name));
795 }
796
797 segms.push(ast::PathSegment::from_ident(ident));
798 let path = Path { span: name_binding.span, segments: segms, tokens: None };
799 let did = match res {
800 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
801 _ => res.opt_def_id(),
802 };
803
804 if child_accessible {
805 // Remove invisible match if exists
806 if let Some(idx) = candidates
807 .iter()
808 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
809 {
810 candidates.remove(idx);
811 }
812 }
813
814 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
815 candidates.push(ImportSuggestion {
816 did,
817 descr: res.descr(),
818 path,
819 accessible: child_accessible,
820 });
821 }
822 }
823 }
824
825 // collect submodules to explore
826 if let Some(module) = name_binding.module() {
827 // form the path
828 let mut path_segments = path_segments.clone();
829 path_segments.push(ast::PathSegment::from_ident(ident));
830
831 let is_extern_crate_that_also_appears_in_prelude =
832 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
833
834 if !is_extern_crate_that_also_appears_in_prelude {
835 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
836 // add the module to the lookup
837 if seen_modules.insert(module.def_id().unwrap()) {
838 if via_import { &mut worklist_via_import } else { &mut worklist }
839 .push((module, path_segments, child_accessible, is_extern));
840 }
841 }
842 }
843 })
844 }
845
846 // If only some candidates are accessible, take just them
847 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
848 candidates = candidates.into_iter().filter(|x| x.accessible).collect();
849 }
850
851 candidates
852 }
853
854 /// When name resolution fails, this method can be used to look up candidate
855 /// entities with the expected name. It allows filtering them using the
856 /// supplied predicate (which should be used to only accept the types of
857 /// definitions expected, e.g., traits). The lookup spans across all crates.
858 ///
859 /// N.B., the method does not look into imports, but this is not a problem,
860 /// since we report the definitions (thus, the de-aliased imports).
861 crate fn lookup_import_candidates<FilterFn>(
862 &mut self,
863 lookup_ident: Ident,
864 namespace: Namespace,
865 parent_scope: &ParentScope<'a>,
866 filter_fn: FilterFn,
867 ) -> Vec<ImportSuggestion>
868 where
869 FilterFn: Fn(Res) -> bool,
870 {
871 let mut suggestions = self.lookup_import_candidates_from_module(
872 lookup_ident,
873 namespace,
874 parent_scope,
875 self.graph_root,
876 Ident::with_dummy_span(kw::Crate),
877 &filter_fn,
878 );
879
880 if lookup_ident.span.rust_2018() {
881 let extern_prelude_names = self.extern_prelude.clone();
882 for (ident, _) in extern_prelude_names.into_iter() {
883 if ident.span.from_expansion() {
884 // Idents are adjusted to the root context before being
885 // resolved in the extern prelude, so reporting this to the
886 // user is no help. This skips the injected
887 // `extern crate std` in the 2018 edition, which would
888 // otherwise cause duplicate suggestions.
889 continue;
890 }
891 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
892 let crate_root =
893 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
894 suggestions.extend(self.lookup_import_candidates_from_module(
895 lookup_ident,
896 namespace,
897 parent_scope,
898 crate_root,
899 ident,
900 &filter_fn,
901 ));
902 }
903 }
904 }
905
906 suggestions
907 }
908
909 crate fn unresolved_macro_suggestions(
910 &mut self,
911 err: &mut DiagnosticBuilder<'a>,
912 macro_kind: MacroKind,
913 parent_scope: &ParentScope<'a>,
914 ident: Ident,
915 ) {
916 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
917 let suggestion = self.early_lookup_typo_candidate(
918 ScopeSet::Macro(macro_kind),
919 parent_scope,
920 ident,
921 is_expected,
922 );
923 self.add_typo_suggestion(err, suggestion, ident.span);
924
925 let import_suggestions =
926 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, |res| {
927 matches!(res, Res::Def(DefKind::Macro(MacroKind::Bang), _))
928 });
929 show_candidates(err, None, &import_suggestions, false, true);
930
931 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
932 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
933 err.span_note(ident.span, &msg);
934 }
935 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
936 err.help("have you added the `#[macro_use]` on the module/import?");
937 }
938 }
939
940 crate fn add_typo_suggestion(
941 &self,
942 err: &mut DiagnosticBuilder<'_>,
943 suggestion: Option<TypoSuggestion>,
944 span: Span,
945 ) -> bool {
946 let suggestion = match suggestion {
947 None => return false,
948 // We shouldn't suggest underscore.
949 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
950 Some(suggestion) => suggestion,
951 };
952 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
953 LOCAL_CRATE => self.opt_span(def_id),
954 _ => Some(
955 self.session
956 .source_map()
957 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
958 ),
959 });
960 if let Some(def_span) = def_span {
961 if span.overlaps(def_span) {
962 // Don't suggest typo suggestion for itself like in the followoing:
963 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
964 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
965 // |
966 // LL | struct X {}
967 // | ----------- `X` defined here
968 // LL |
969 // LL | const Y: X = X("ö");
970 // | -------------^^^^^^- similarly named constant `Y` defined here
971 // |
972 // help: use struct literal syntax instead
973 // |
974 // LL | const Y: X = X {};
975 // | ^^^^
976 // help: a constant with a similar name exists
977 // |
978 // LL | const Y: X = Y("ö");
979 // | ^
980 return false;
981 }
982 err.span_label(
983 self.session.source_map().guess_head_span(def_span),
984 &format!(
985 "similarly named {} `{}` defined here",
986 suggestion.res.descr(),
987 suggestion.candidate.as_str(),
988 ),
989 );
990 }
991 let msg = format!(
992 "{} {} with a similar name exists",
993 suggestion.res.article(),
994 suggestion.res.descr()
995 );
996 err.span_suggestion(
997 span,
998 &msg,
999 suggestion.candidate.to_string(),
1000 Applicability::MaybeIncorrect,
1001 );
1002 true
1003 }
1004
1005 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1006 let res = b.res();
1007 if b.span.is_dummy() {
1008 // These already contain the "built-in" prefix or look bad with it.
1009 let add_built_in =
1010 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1011 let (built_in, from) = if from_prelude {
1012 ("", " from prelude")
1013 } else if b.is_extern_crate()
1014 && !b.is_import()
1015 && self.session.opts.externs.get(&ident.as_str()).is_some()
1016 {
1017 ("", " passed with `--extern`")
1018 } else if add_built_in {
1019 (" built-in", "")
1020 } else {
1021 ("", "")
1022 };
1023
1024 let a = if built_in.is_empty() { res.article() } else { "a" };
1025 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1026 } else {
1027 let introduced = if b.is_import() { "imported" } else { "defined" };
1028 format!("the {thing} {introduced} here", thing = res.descr())
1029 }
1030 }
1031
1032 crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1033 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1034 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1035 // We have to print the span-less alternative first, otherwise formatting looks bad.
1036 (b2, b1, misc2, misc1, true)
1037 } else {
1038 (b1, b2, misc1, misc2, false)
1039 };
1040
1041 let mut err = struct_span_err!(
1042 self.session,
1043 ident.span,
1044 E0659,
1045 "`{ident}` is ambiguous ({why})",
1046 why = kind.descr()
1047 );
1048 err.span_label(ident.span, "ambiguous name");
1049
1050 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1051 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1052 let note_msg = format!("`{ident}` could{also} refer to {what}");
1053
1054 let thing = b.res().descr();
1055 let mut help_msgs = Vec::new();
1056 if b.is_glob_import()
1057 && (kind == AmbiguityKind::GlobVsGlob
1058 || kind == AmbiguityKind::GlobVsExpanded
1059 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1060 {
1061 help_msgs.push(format!(
1062 "consider adding an explicit import of `{ident}` to disambiguate"
1063 ))
1064 }
1065 if b.is_extern_crate() && ident.span.rust_2018() {
1066 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1067 }
1068 if misc == AmbiguityErrorMisc::SuggestCrate {
1069 help_msgs
1070 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1071 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1072 help_msgs
1073 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1074 }
1075
1076 err.span_note(b.span, &note_msg);
1077 for (i, help_msg) in help_msgs.iter().enumerate() {
1078 let or = if i == 0 { "" } else { "or " };
1079 err.help(&format!("{}{}", or, help_msg));
1080 }
1081 };
1082
1083 could_refer_to(b1, misc1, "");
1084 could_refer_to(b2, misc2, " also");
1085 err.emit();
1086 }
1087
1088 /// If the binding refers to a tuple struct constructor with fields,
1089 /// returns the span of its fields.
1090 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1091 if let NameBindingKind::Res(
1092 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1093 _,
1094 ) = binding.kind
1095 {
1096 let def_id = (&*self).parent(ctor_def_id).expect("no parent for a constructor");
1097 let fields = self.field_names.get(&def_id)?;
1098 let first_field = fields.first()?; // Handle `struct Foo()`
1099 return Some(fields.iter().fold(first_field.span, |acc, field| acc.to(field.span)));
1100 }
1101 None
1102 }
1103
1104 crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1105 let PrivacyError { ident, binding, .. } = *privacy_error;
1106
1107 let res = binding.res();
1108 let ctor_fields_span = self.ctor_fields_span(binding);
1109 let plain_descr = res.descr().to_string();
1110 let nonimport_descr =
1111 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1112 let import_descr = nonimport_descr.clone() + " import";
1113 let get_descr =
1114 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1115
1116 // Print the primary message.
1117 let descr = get_descr(binding);
1118 let mut err =
1119 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1120 err.span_label(ident.span, &format!("private {}", descr));
1121 if let Some(span) = ctor_fields_span {
1122 err.span_label(span, "a constructor is private if any of the fields is private");
1123 }
1124
1125 // Print the whole import chain to make it easier to see what happens.
1126 let first_binding = binding;
1127 let mut next_binding = Some(binding);
1128 let mut next_ident = ident;
1129 while let Some(binding) = next_binding {
1130 let name = next_ident;
1131 next_binding = match binding.kind {
1132 _ if res == Res::Err => None,
1133 NameBindingKind::Import { binding, import, .. } => match import.kind {
1134 _ if binding.span.is_dummy() => None,
1135 ImportKind::Single { source, .. } => {
1136 next_ident = source;
1137 Some(binding)
1138 }
1139 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1140 ImportKind::ExternCrate { .. } => None,
1141 },
1142 _ => None,
1143 };
1144
1145 let first = ptr::eq(binding, first_binding);
1146 let msg = format!(
1147 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1148 and_refers_to = if first { "" } else { "...and refers to " },
1149 item = get_descr(binding),
1150 which = if first { "" } else { " which" },
1151 dots = if next_binding.is_some() { "..." } else { "" },
1152 );
1153 let def_span = self.session.source_map().guess_head_span(binding.span);
1154 let mut note_span = MultiSpan::from_span(def_span);
1155 if !first && binding.vis == ty::Visibility::Public {
1156 note_span.push_span_label(def_span, "consider importing it directly".into());
1157 }
1158 err.span_note(note_span, &msg);
1159 }
1160
1161 err.emit();
1162 }
1163 }
1164
1165 impl<'a, 'b> ImportResolver<'a, 'b> {
1166 /// Adds suggestions for a path that cannot be resolved.
1167 pub(crate) fn make_path_suggestion(
1168 &mut self,
1169 span: Span,
1170 mut path: Vec<Segment>,
1171 parent_scope: &ParentScope<'b>,
1172 ) -> Option<(Vec<Segment>, Vec<String>)> {
1173 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1174
1175 match (path.get(0), path.get(1)) {
1176 // `{{root}}::ident::...` on both editions.
1177 // On 2015 `{{root}}` is usually added implicitly.
1178 (Some(fst), Some(snd))
1179 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1180 // `ident::...` on 2018.
1181 (Some(fst), _)
1182 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1183 {
1184 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1185 path.insert(0, Segment::from_ident(Ident::invalid()));
1186 }
1187 _ => return None,
1188 }
1189
1190 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1191 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1192 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1193 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1194 }
1195
1196 /// Suggest a missing `self::` if that resolves to an correct module.
1197 ///
1198 /// ```text
1199 /// |
1200 /// LL | use foo::Bar;
1201 /// | ^^^ did you mean `self::foo`?
1202 /// ```
1203 fn make_missing_self_suggestion(
1204 &mut self,
1205 span: Span,
1206 mut path: Vec<Segment>,
1207 parent_scope: &ParentScope<'b>,
1208 ) -> Option<(Vec<Segment>, Vec<String>)> {
1209 // Replace first ident with `self` and check if that is valid.
1210 path[0].ident.name = kw::SelfLower;
1211 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1212 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1213 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1214 }
1215
1216 /// Suggests a missing `crate::` if that resolves to an correct module.
1217 ///
1218 /// ```text
1219 /// |
1220 /// LL | use foo::Bar;
1221 /// | ^^^ did you mean `crate::foo`?
1222 /// ```
1223 fn make_missing_crate_suggestion(
1224 &mut self,
1225 span: Span,
1226 mut path: Vec<Segment>,
1227 parent_scope: &ParentScope<'b>,
1228 ) -> Option<(Vec<Segment>, Vec<String>)> {
1229 // Replace first ident with `crate` and check if that is valid.
1230 path[0].ident.name = kw::Crate;
1231 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1232 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1233 if let PathResult::Module(..) = result {
1234 Some((
1235 path,
1236 vec![
1237 "`use` statements changed in Rust 2018; read more at \
1238 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1239 clarity.html>"
1240 .to_string(),
1241 ],
1242 ))
1243 } else {
1244 None
1245 }
1246 }
1247
1248 /// Suggests a missing `super::` if that resolves to an correct module.
1249 ///
1250 /// ```text
1251 /// |
1252 /// LL | use foo::Bar;
1253 /// | ^^^ did you mean `super::foo`?
1254 /// ```
1255 fn make_missing_super_suggestion(
1256 &mut self,
1257 span: Span,
1258 mut path: Vec<Segment>,
1259 parent_scope: &ParentScope<'b>,
1260 ) -> Option<(Vec<Segment>, Vec<String>)> {
1261 // Replace first ident with `crate` and check if that is valid.
1262 path[0].ident.name = kw::Super;
1263 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1264 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1265 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1266 }
1267
1268 /// Suggests a missing external crate name if that resolves to an correct module.
1269 ///
1270 /// ```text
1271 /// |
1272 /// LL | use foobar::Baz;
1273 /// | ^^^^^^ did you mean `baz::foobar`?
1274 /// ```
1275 ///
1276 /// Used when importing a submodule of an external crate but missing that crate's
1277 /// name as the first part of path.
1278 fn make_external_crate_suggestion(
1279 &mut self,
1280 span: Span,
1281 mut path: Vec<Segment>,
1282 parent_scope: &ParentScope<'b>,
1283 ) -> Option<(Vec<Segment>, Vec<String>)> {
1284 if path[1].ident.span.rust_2015() {
1285 return None;
1286 }
1287
1288 // Sort extern crate names in reverse order to get
1289 // 1) some consistent ordering for emitted diagnostics, and
1290 // 2) `std` suggestions before `core` suggestions.
1291 let mut extern_crate_names =
1292 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1293 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
1294
1295 for name in extern_crate_names.into_iter() {
1296 // Replace first ident with a crate name and check if that is valid.
1297 path[0].ident.name = name;
1298 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1299 debug!(
1300 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1301 name, path, result
1302 );
1303 if let PathResult::Module(..) = result {
1304 return Some((path, Vec::new()));
1305 }
1306 }
1307
1308 None
1309 }
1310
1311 /// Suggests importing a macro from the root of the crate rather than a module within
1312 /// the crate.
1313 ///
1314 /// ```text
1315 /// help: a macro with this name exists at the root of the crate
1316 /// |
1317 /// LL | use issue_59764::makro;
1318 /// | ^^^^^^^^^^^^^^^^^^
1319 /// |
1320 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
1321 /// at the root of the crate instead of the module where it is defined
1322 /// ```
1323 pub(crate) fn check_for_module_export_macro(
1324 &mut self,
1325 import: &'b Import<'b>,
1326 module: ModuleOrUniformRoot<'b>,
1327 ident: Ident,
1328 ) -> Option<(Option<Suggestion>, Vec<String>)> {
1329 let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
1330 module
1331 } else {
1332 return None;
1333 };
1334
1335 while let Some(parent) = crate_module.parent {
1336 crate_module = parent;
1337 }
1338
1339 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1340 // Don't make a suggestion if the import was already from the root of the
1341 // crate.
1342 return None;
1343 }
1344
1345 let resolutions = self.r.resolutions(crate_module).borrow();
1346 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1347 let binding = resolution.borrow().binding()?;
1348 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1349 let module_name = crate_module.kind.name().unwrap();
1350 let import_snippet = match import.kind {
1351 ImportKind::Single { source, target, .. } if source != target => {
1352 format!("{} as {}", source, target)
1353 }
1354 _ => format!("{}", ident),
1355 };
1356
1357 let mut corrections: Vec<(Span, String)> = Vec::new();
1358 if !import.is_nested() {
1359 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1360 // intermediate segments.
1361 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1362 } else {
1363 // Find the binding span (and any trailing commas and spaces).
1364 // ie. `use a::b::{c, d, e};`
1365 // ^^^
1366 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1367 self.r.session,
1368 import.span,
1369 import.use_span,
1370 );
1371 debug!(
1372 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1373 found_closing_brace, binding_span
1374 );
1375
1376 let mut removal_span = binding_span;
1377 if found_closing_brace {
1378 // If the binding span ended with a closing brace, as in the below example:
1379 // ie. `use a::b::{c, d};`
1380 // ^
1381 // Then expand the span of characters to remove to include the previous
1382 // binding's trailing comma.
1383 // ie. `use a::b::{c, d};`
1384 // ^^^
1385 if let Some(previous_span) =
1386 extend_span_to_previous_binding(self.r.session, binding_span)
1387 {
1388 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1389 removal_span = removal_span.with_lo(previous_span.lo());
1390 }
1391 }
1392 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1393
1394 // Remove the `removal_span`.
1395 corrections.push((removal_span, "".to_string()));
1396
1397 // Find the span after the crate name and if it has nested imports immediatately
1398 // after the crate name already.
1399 // ie. `use a::b::{c, d};`
1400 // ^^^^^^^^^
1401 // or `use a::{b, c, d}};`
1402 // ^^^^^^^^^^^
1403 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1404 self.r.session,
1405 module_name,
1406 import.use_span,
1407 );
1408 debug!(
1409 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1410 has_nested, after_crate_name
1411 );
1412
1413 let source_map = self.r.session.source_map();
1414
1415 // Add the import to the start, with a `{` if required.
1416 let start_point = source_map.start_point(after_crate_name);
1417 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1418 corrections.push((
1419 start_point,
1420 if has_nested {
1421 // In this case, `start_snippet` must equal '{'.
1422 format!("{}{}, ", start_snippet, import_snippet)
1423 } else {
1424 // In this case, add a `{`, then the moved import, then whatever
1425 // was there before.
1426 format!("{{{}, {}", import_snippet, start_snippet)
1427 },
1428 ));
1429 }
1430
1431 // Add a `};` to the end if nested, matching the `{` added at the start.
1432 if !has_nested {
1433 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1434 }
1435 }
1436
1437 let suggestion = Some((
1438 corrections,
1439 String::from("a macro with this name exists at the root of the crate"),
1440 Applicability::MaybeIncorrect,
1441 ));
1442 let note = vec![
1443 "this could be because a macro annotated with `#[macro_export]` will be exported \
1444 at the root of the crate instead of the module where it is defined"
1445 .to_string(),
1446 ];
1447 Some((suggestion, note))
1448 } else {
1449 None
1450 }
1451 }
1452 }
1453
1454 /// Given a `binding_span` of a binding within a use statement:
1455 ///
1456 /// ```
1457 /// use foo::{a, b, c};
1458 /// ^
1459 /// ```
1460 ///
1461 /// then return the span until the next binding or the end of the statement:
1462 ///
1463 /// ```
1464 /// use foo::{a, b, c};
1465 /// ^^^
1466 /// ```
1467 pub(crate) fn find_span_of_binding_until_next_binding(
1468 sess: &Session,
1469 binding_span: Span,
1470 use_span: Span,
1471 ) -> (bool, Span) {
1472 let source_map = sess.source_map();
1473
1474 // Find the span of everything after the binding.
1475 // ie. `a, e};` or `a};`
1476 let binding_until_end = binding_span.with_hi(use_span.hi());
1477
1478 // Find everything after the binding but not including the binding.
1479 // ie. `, e};` or `};`
1480 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1481
1482 // Keep characters in the span until we encounter something that isn't a comma or
1483 // whitespace.
1484 // ie. `, ` or ``.
1485 //
1486 // Also note whether a closing brace character was encountered. If there
1487 // was, then later go backwards to remove any trailing commas that are left.
1488 let mut found_closing_brace = false;
1489 let after_binding_until_next_binding =
1490 source_map.span_take_while(after_binding_until_end, |&ch| {
1491 if ch == '}' {
1492 found_closing_brace = true;
1493 }
1494 ch == ' ' || ch == ','
1495 });
1496
1497 // Combine the two spans.
1498 // ie. `a, ` or `a`.
1499 //
1500 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1501 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1502
1503 (found_closing_brace, span)
1504 }
1505
1506 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1507 /// binding.
1508 ///
1509 /// ```
1510 /// use foo::a::{a, b, c};
1511 /// ^^--- binding span
1512 /// |
1513 /// returned span
1514 ///
1515 /// use foo::{a, b, c};
1516 /// --- binding span
1517 /// ```
1518 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1519 let source_map = sess.source_map();
1520
1521 // `prev_source` will contain all of the source that came before the span.
1522 // Then split based on a command and take the first (ie. closest to our span)
1523 // snippet. In the example, this is a space.
1524 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1525
1526 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1527 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1528 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1529 return None;
1530 }
1531
1532 let prev_comma = prev_comma.first().unwrap();
1533 let prev_starting_brace = prev_starting_brace.first().unwrap();
1534
1535 // If the amount of source code before the comma is greater than
1536 // the amount of source code before the starting brace then we've only
1537 // got one item in the nested item (eg. `issue_52891::{self}`).
1538 if prev_comma.len() > prev_starting_brace.len() {
1539 return None;
1540 }
1541
1542 Some(binding_span.with_lo(BytePos(
1543 // Take away the number of bytes for the characters we've found and an
1544 // extra for the comma.
1545 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1546 )))
1547 }
1548
1549 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1550 /// it is a nested use tree.
1551 ///
1552 /// ```
1553 /// use foo::a::{b, c};
1554 /// ^^^^^^^^^^ // false
1555 ///
1556 /// use foo::{a, b, c};
1557 /// ^^^^^^^^^^ // true
1558 ///
1559 /// use foo::{a, b::{c, d}};
1560 /// ^^^^^^^^^^^^^^^ // true
1561 /// ```
1562 fn find_span_immediately_after_crate_name(
1563 sess: &Session,
1564 module_name: Symbol,
1565 use_span: Span,
1566 ) -> (bool, Span) {
1567 debug!(
1568 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1569 module_name, use_span
1570 );
1571 let source_map = sess.source_map();
1572
1573 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1574 let mut num_colons = 0;
1575 // Find second colon.. `use issue_59764:`
1576 let until_second_colon = source_map.span_take_while(use_span, |c| {
1577 if *c == ':' {
1578 num_colons += 1;
1579 }
1580 !matches!(c, ':' if num_colons == 2)
1581 });
1582 // Find everything after the second colon.. `foo::{baz, makro};`
1583 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1584
1585 let mut found_a_non_whitespace_character = false;
1586 // Find the first non-whitespace character in `from_second_colon`.. `f`
1587 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1588 if found_a_non_whitespace_character {
1589 return false;
1590 }
1591 if !c.is_whitespace() {
1592 found_a_non_whitespace_character = true;
1593 }
1594 true
1595 });
1596
1597 // Find the first `{` in from_second_colon.. `foo::{`
1598 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1599
1600 (next_left_bracket == after_second_colon, from_second_colon)
1601 }
1602
1603 /// When an entity with a given name is not available in scope, we search for
1604 /// entities with that name in all crates. This method allows outputting the
1605 /// results of this search in a programmer-friendly way
1606 crate fn show_candidates(
1607 err: &mut DiagnosticBuilder<'_>,
1608 // This is `None` if all placement locations are inside expansions
1609 use_placement_span: Option<Span>,
1610 candidates: &[ImportSuggestion],
1611 instead: bool,
1612 found_use: bool,
1613 ) {
1614 if candidates.is_empty() {
1615 return;
1616 }
1617
1618 // we want consistent results across executions, but candidates are produced
1619 // by iterating through a hash map, so make sure they are ordered:
1620 let mut path_strings: Vec<_> =
1621 candidates.iter().map(|c| path_names_to_string(&c.path)).collect();
1622
1623 path_strings.sort();
1624 path_strings.dedup();
1625
1626 let (determiner, kind) = if candidates.len() == 1 {
1627 ("this", candidates[0].descr)
1628 } else {
1629 ("one of these", "items")
1630 };
1631
1632 let instead = if instead { " instead" } else { "" };
1633 let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
1634
1635 if let Some(span) = use_placement_span {
1636 for candidate in &mut path_strings {
1637 // produce an additional newline to separate the new use statement
1638 // from the directly following item.
1639 let additional_newline = if found_use { "" } else { "\n" };
1640 *candidate = format!("use {};\n{}", candidate, additional_newline);
1641 }
1642
1643 err.span_suggestions(span, &msg, path_strings.into_iter(), Applicability::Unspecified);
1644 } else {
1645 msg.push(':');
1646
1647 for candidate in path_strings {
1648 msg.push('\n');
1649 msg.push_str(&candidate);
1650 }
1651
1652 err.note(&msg);
1653 }
1654 }