]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/diagnostics.rs
rustc: use DefKind instead of Def, where possible.
[rust.git] / src / librustc_resolve / diagnostics.rs
1 use std::cmp::Reverse;
2
3 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
4 use log::debug;
5 use rustc::hir::def::{self, DefKind, CtorKind, Namespace::*};
6 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
7 use rustc::session::{Session, config::nightly_options};
8 use syntax::ast::{self, Expr, ExprKind, Ident};
9 use syntax::ext::base::MacroKind;
10 use syntax::symbol::{Symbol, keywords};
11 use syntax_pos::{BytePos, Span};
12
13 type Def = def::Def<ast::NodeId>;
14
15 use crate::macros::ParentScope;
16 use crate::resolve_imports::{ImportDirective, ImportDirectiveSubclass, ImportResolver};
17 use crate::{import_candidate_to_enum_paths, is_self_type, is_self_value, path_names_to_string};
18 use crate::{AssocSuggestion, CrateLint, ImportSuggestion, ModuleOrUniformRoot, PathResult,
19             PathSource, Resolver, Segment, Suggestion};
20
21 impl<'a> Resolver<'a> {
22     /// Handles error reporting for `smart_resolve_path_fragment` function.
23     /// Creates base error and amends it with one short label and possibly some longer helps/notes.
24     pub(crate) fn smart_resolve_report_errors(
25         &mut self,
26         path: &[Segment],
27         span: Span,
28         source: PathSource<'_>,
29         def: Option<Def>,
30     ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
31         let ident_span = path.last().map_or(span, |ident| ident.ident.span);
32         let ns = source.namespace();
33         let is_expected = &|def| source.is_expected(def);
34         let is_enum_variant = &|def| {
35             if let Def::Def(DefKind::Variant, _) = def { true } else { false }
36         };
37
38         // Make the base error.
39         let expected = source.descr_expected();
40         let path_str = Segment::names_to_string(path);
41         let item_str = path.last().unwrap().ident;
42         let code = source.error_code(def.is_some());
43         let (base_msg, fallback_label, base_span) = if let Some(def) = def {
44             (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
45                 format!("not a {}", expected),
46                 span)
47         } else {
48             let item_span = path.last().unwrap().ident.span;
49             let (mod_prefix, mod_str) = if path.len() == 1 {
50                 (String::new(), "this scope".to_string())
51             } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() {
52                 (String::new(), "the crate root".to_string())
53             } else {
54                 let mod_path = &path[..path.len() - 1];
55                 let mod_prefix = match self.resolve_path_without_parent_scope(
56                     mod_path, Some(TypeNS), false, span, CrateLint::No
57                 ) {
58                     PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
59                         module.def_kind(),
60                     _ => None,
61                 }.map_or(String::new(), |kind| format!("{} ", kind.descr()));
62                 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
63             };
64             (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
65                 format!("not found in {}", mod_str),
66                 item_span)
67         };
68
69         let code = DiagnosticId::Error(code.into());
70         let mut err = self.session.struct_span_err_with_code(base_span, &base_msg, code);
71
72         // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
73         if ["this", "my"].contains(&&*item_str.as_str())
74             && self.self_value_is_available(path[0].ident.span, span) {
75             err.span_suggestion(
76                 span,
77                 "did you mean",
78                 "self".to_string(),
79                 Applicability::MaybeIncorrect,
80             );
81         }
82
83         // Emit special messages for unresolved `Self` and `self`.
84         if is_self_type(path, ns) {
85             __diagnostic_used!(E0411);
86             err.code(DiagnosticId::Error("E0411".into()));
87             err.span_label(span, format!("`Self` is only available in impls, traits, \
88                                           and type definitions"));
89             return (err, Vec::new());
90         }
91         if is_self_value(path, ns) {
92             debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
93
94             __diagnostic_used!(E0424);
95             err.code(DiagnosticId::Error("E0424".into()));
96             err.span_label(span, match source {
97                 PathSource::Pat => {
98                     format!("`self` value is a keyword \
99                              and may not be bound to \
100                              variables or shadowed")
101                 }
102                 _ => {
103                     format!("`self` value is a keyword \
104                              only available in methods \
105                              with `self` parameter")
106                 }
107             });
108             return (err, Vec::new());
109         }
110
111         // Try to lookup name in more relaxed fashion for better error reporting.
112         let ident = path.last().unwrap().ident;
113         let candidates = self.lookup_import_candidates(ident, ns, is_expected)
114             .drain(..)
115             .filter(|ImportSuggestion { did, .. }| {
116                 match (did, def.and_then(|def| def.opt_def_id())) {
117                     (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
118                     _ => true,
119                 }
120             })
121             .collect::<Vec<_>>();
122         let crate_def_id = DefId::local(CRATE_DEF_INDEX);
123         if candidates.is_empty() && is_expected(Def::Def(DefKind::Enum, crate_def_id)) {
124             let enum_candidates =
125                 self.lookup_import_candidates(ident, ns, is_enum_variant);
126             let mut enum_candidates = enum_candidates.iter()
127                 .map(|suggestion| {
128                     import_candidate_to_enum_paths(&suggestion)
129                 }).collect::<Vec<_>>();
130             enum_candidates.sort();
131
132             if !enum_candidates.is_empty() {
133                 // Contextualize for E0412 "cannot find type", but don't belabor the point
134                 // (that it's a variant) for E0573 "expected type, found variant".
135                 let preamble = if def.is_none() {
136                     let others = match enum_candidates.len() {
137                         1 => String::new(),
138                         2 => " and 1 other".to_owned(),
139                         n => format!(" and {} others", n)
140                     };
141                     format!("there is an enum variant `{}`{}; ",
142                             enum_candidates[0].0, others)
143                 } else {
144                     String::new()
145                 };
146                 let msg = format!("{}try using the variant's enum", preamble);
147
148                 err.span_suggestions(
149                     span,
150                     &msg,
151                     enum_candidates.into_iter()
152                         .map(|(_variant_path, enum_ty_path)| enum_ty_path)
153                         // Variants re-exported in prelude doesn't mean `prelude::v1` is the
154                         // type name!
155                         // FIXME: is there a more principled way to do this that
156                         // would work for other re-exports?
157                         .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
158                         // Also write `Option` rather than `std::prelude::v1::Option`.
159                         .map(|enum_ty_path| {
160                             // FIXME #56861: DRY-er prelude filtering.
161                             enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
162                         }),
163                     Applicability::MachineApplicable,
164                 );
165             }
166         }
167         if path.len() == 1 && self.self_type_is_available(span) {
168             if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
169                 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
170                 match candidate {
171                     AssocSuggestion::Field => {
172                         if self_is_available {
173                             err.span_suggestion(
174                                 span,
175                                 "you might have meant to use the available field",
176                                 format!("self.{}", path_str),
177                                 Applicability::MachineApplicable,
178                             );
179                         } else {
180                             err.span_label(
181                                 span,
182                                 "a field by this name exists in `Self`",
183                             );
184                         }
185                     }
186                     AssocSuggestion::MethodWithSelf if self_is_available => {
187                         err.span_suggestion(
188                             span,
189                             "try",
190                             format!("self.{}", path_str),
191                             Applicability::MachineApplicable,
192                         );
193                     }
194                     AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
195                         err.span_suggestion(
196                             span,
197                             "try",
198                             format!("Self::{}", path_str),
199                             Applicability::MachineApplicable,
200                         );
201                     }
202                 }
203                 return (err, candidates);
204             }
205         }
206
207         let mut levenshtein_worked = false;
208
209         // Try Levenshtein algorithm.
210         let suggestion = self.lookup_typo_candidate(path, ns, is_expected, span);
211         if let Some(suggestion) = suggestion {
212             let msg = format!(
213                 "{} {} with a similar name exists",
214                 suggestion.article, suggestion.kind
215             );
216             err.span_suggestion(
217                 ident_span,
218                 &msg,
219                 suggestion.candidate.to_string(),
220                 Applicability::MaybeIncorrect,
221             );
222
223             levenshtein_worked = true;
224         }
225
226         // Try context-dependent help if relaxed lookup didn't work.
227         if let Some(def) = def {
228             if self.smart_resolve_context_dependent_help(&mut err,
229                                                          span,
230                                                          source,
231                                                          def,
232                                                          &path_str,
233                                                          &fallback_label) {
234                 return (err, candidates);
235             }
236         }
237
238         // Fallback label.
239         if !levenshtein_worked {
240             err.span_label(base_span, fallback_label);
241             self.type_ascription_suggestion(&mut err, base_span);
242         }
243         (err, candidates)
244     }
245
246     fn followed_by_brace(&self, span: Span) -> (bool, Option<(Span, String)>) {
247         // HACK(estebank): find a better way to figure out that this was a
248         // parser issue where a struct literal is being used on an expression
249         // where a brace being opened means a block is being started. Look
250         // ahead for the next text to see if `span` is followed by a `{`.
251         let sm = self.session.source_map();
252         let mut sp = span;
253         loop {
254             sp = sm.next_point(sp);
255             match sm.span_to_snippet(sp) {
256                 Ok(ref snippet) => {
257                     if snippet.chars().any(|c| { !c.is_whitespace() }) {
258                         break;
259                     }
260                 }
261                 _ => break,
262             }
263         }
264         let followed_by_brace = match sm.span_to_snippet(sp) {
265             Ok(ref snippet) if snippet == "{" => true,
266             _ => false,
267         };
268         // In case this could be a struct literal that needs to be surrounded
269         // by parenthesis, find the appropriate span.
270         let mut i = 0;
271         let mut closing_brace = None;
272         loop {
273             sp = sm.next_point(sp);
274             match sm.span_to_snippet(sp) {
275                 Ok(ref snippet) => {
276                     if snippet == "}" {
277                         let sp = span.to(sp);
278                         if let Ok(snippet) = sm.span_to_snippet(sp) {
279                             closing_brace = Some((sp, snippet));
280                         }
281                         break;
282                     }
283                 }
284                 _ => break,
285             }
286             i += 1;
287             // The bigger the span, the more likely we're incorrect --
288             // bound it to 100 chars long.
289             if i > 100 {
290                 break;
291             }
292         }
293         return (followed_by_brace, closing_brace)
294     }
295
296     /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
297     /// function.
298     /// Returns `true` if able to provide context-dependent help.
299     fn smart_resolve_context_dependent_help(
300         &mut self,
301         err: &mut DiagnosticBuilder<'a>,
302         span: Span,
303         source: PathSource<'_>,
304         def: Def,
305         path_str: &str,
306         fallback_label: &str,
307     ) -> bool {
308         let ns = source.namespace();
309         let is_expected = &|def| source.is_expected(def);
310
311         let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.node {
312             ExprKind::Field(_, ident) => {
313                 err.span_suggestion(
314                     expr.span,
315                     "use the path separator to refer to an item",
316                     format!("{}::{}", path_str, ident),
317                     Applicability::MaybeIncorrect,
318                 );
319                 true
320             }
321             ExprKind::MethodCall(ref segment, ..) => {
322                 let span = expr.span.with_hi(segment.ident.span.hi());
323                 err.span_suggestion(
324                     span,
325                     "use the path separator to refer to an item",
326                     format!("{}::{}", path_str, segment.ident),
327                     Applicability::MaybeIncorrect,
328                 );
329                 true
330             }
331             _ => false,
332         };
333
334         let mut bad_struct_syntax_suggestion = || {
335             let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
336             let mut suggested = false;
337             match source {
338                 PathSource::Expr(Some(parent)) => {
339                     suggested = path_sep(err, &parent);
340                 }
341                 PathSource::Expr(None) if followed_by_brace == true => {
342                     if let Some((sp, snippet)) = closing_brace {
343                         err.span_suggestion(
344                             sp,
345                             "surround the struct literal with parenthesis",
346                             format!("({})", snippet),
347                             Applicability::MaybeIncorrect,
348                         );
349                     } else {
350                         err.span_label(
351                             span,  // Note the parenthesis surrounding the suggestion below
352                             format!("did you mean `({} {{ /* fields */ }})`?", path_str),
353                         );
354                     }
355                     suggested = true;
356                 },
357                 _ => {}
358             }
359             if !suggested {
360                 err.span_label(
361                     span,
362                     format!("did you mean `{} {{ /* fields */ }}`?", path_str),
363                 );
364             }
365         };
366
367         match (def, source) {
368             (Def::Def(DefKind::Macro(..), _), _) => {
369                 err.span_suggestion(
370                     span,
371                     "use `!` to invoke the macro",
372                     format!("{}!", path_str),
373                     Applicability::MaybeIncorrect,
374                 );
375                 if path_str == "try" && span.rust_2015() {
376                     err.note("if you want the `try` keyword, you need to be in the 2018 edition");
377                 }
378             }
379             (Def::Def(DefKind::TyAlias, _), PathSource::Trait(_)) => {
380                 err.span_label(span, "type aliases cannot be used as traits");
381                 if nightly_options::is_nightly_build() {
382                     err.note("did you mean to use a trait alias?");
383                 }
384             }
385             (Def::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
386                 if !path_sep(err, &parent) {
387                     return false;
388                 }
389             }
390             (Def::Def(DefKind::Enum, def_id), PathSource::TupleStruct)
391                 | (Def::Def(DefKind::Enum, def_id), PathSource::Expr(..))  => {
392                 if let Some(variants) = self.collect_enum_variants(def_id) {
393                     if !variants.is_empty() {
394                         let msg = if variants.len() == 1 {
395                             "try using the enum's variant"
396                         } else {
397                             "try using one of the enum's variants"
398                         };
399
400                         err.span_suggestions(
401                             span,
402                             msg,
403                             variants.iter().map(path_names_to_string),
404                             Applicability::MaybeIncorrect,
405                         );
406                     }
407                 } else {
408                     err.note("did you mean to use one of the enum's variants?");
409                 }
410             },
411             (Def::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
412                 if let Some((ctor_def, ctor_vis))
413                         = self.struct_constructors.get(&def_id).cloned() {
414                     let accessible_ctor = self.is_accessible(ctor_vis);
415                     if is_expected(ctor_def) && !accessible_ctor {
416                         err.span_label(
417                             span,
418                             format!("constructor is not visible here due to private fields"),
419                         );
420                     }
421                 } else {
422                     bad_struct_syntax_suggestion();
423                 }
424             }
425             (Def::Def(DefKind::Union, _), _) |
426             (Def::Def(DefKind::Variant, _), _) |
427             (Def::Def(DefKind::Ctor(_, CtorKind::Fictive), _), _) if ns == ValueNS => {
428                 bad_struct_syntax_suggestion();
429             }
430             (Def::SelfTy(..), _) if ns == ValueNS => {
431                 err.span_label(span, fallback_label);
432                 err.note("can't use `Self` as a constructor, you must use the implemented struct");
433             }
434             (Def::Def(DefKind::TyAlias, _), _)
435             | (Def::Def(DefKind::AssociatedTy, _), _) if ns == ValueNS => {
436                 err.note("can't use a type alias as a constructor");
437             }
438             _ => return false,
439         }
440         true
441     }
442 }
443
444 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
445     /// Adds suggestions for a path that cannot be resolved.
446     pub(crate) fn make_path_suggestion(
447         &mut self,
448         span: Span,
449         mut path: Vec<Segment>,
450         parent_scope: &ParentScope<'b>,
451     ) -> Option<(Vec<Segment>, Vec<String>)> {
452         debug!("make_path_suggestion: span={:?} path={:?}", span, path);
453
454         match (path.get(0), path.get(1)) {
455             // `{{root}}::ident::...` on both editions.
456             // On 2015 `{{root}}` is usually added implicitly.
457             (Some(fst), Some(snd)) if fst.ident.name == keywords::PathRoot.name() &&
458                                       !snd.ident.is_path_segment_keyword() => {}
459             // `ident::...` on 2018.
460             (Some(fst), _) if fst.ident.span.rust_2018() &&
461                               !fst.ident.is_path_segment_keyword() => {
462                 // Insert a placeholder that's later replaced by `self`/`super`/etc.
463                 path.insert(0, Segment::from_ident(keywords::Invalid.ident()));
464             }
465             _ => return None,
466         }
467
468         self.make_missing_self_suggestion(span, path.clone(), parent_scope)
469             .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
470             .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
471             .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
472     }
473
474     /// Suggest a missing `self::` if that resolves to an correct module.
475     ///
476     /// ```
477     ///    |
478     /// LL | use foo::Bar;
479     ///    |     ^^^ did you mean `self::foo`?
480     /// ```
481     fn make_missing_self_suggestion(
482         &mut self,
483         span: Span,
484         mut path: Vec<Segment>,
485         parent_scope: &ParentScope<'b>,
486     ) -> Option<(Vec<Segment>, Vec<String>)> {
487         // Replace first ident with `self` and check if that is valid.
488         path[0].ident.name = keywords::SelfLower.name();
489         let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
490         debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
491         if let PathResult::Module(..) = result {
492             Some((path, Vec::new()))
493         } else {
494             None
495         }
496     }
497
498     /// Suggests a missing `crate::` if that resolves to an correct module.
499     ///
500     /// ```
501     ///    |
502     /// LL | use foo::Bar;
503     ///    |     ^^^ did you mean `crate::foo`?
504     /// ```
505     fn make_missing_crate_suggestion(
506         &mut self,
507         span: Span,
508         mut path: Vec<Segment>,
509         parent_scope: &ParentScope<'b>,
510     ) -> Option<(Vec<Segment>, Vec<String>)> {
511         // Replace first ident with `crate` and check if that is valid.
512         path[0].ident.name = keywords::Crate.name();
513         let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
514         debug!("make_missing_crate_suggestion:  path={:?} result={:?}", path, result);
515         if let PathResult::Module(..) = result {
516             Some((
517                 path,
518                 vec![
519                     "`use` statements changed in Rust 2018; read more at \
520                      <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
521                      clarity.html>".to_string()
522                 ],
523             ))
524         } else {
525             None
526         }
527     }
528
529     /// Suggests a missing `super::` if that resolves to an correct module.
530     ///
531     /// ```
532     ///    |
533     /// LL | use foo::Bar;
534     ///    |     ^^^ did you mean `super::foo`?
535     /// ```
536     fn make_missing_super_suggestion(
537         &mut self,
538         span: Span,
539         mut path: Vec<Segment>,
540         parent_scope: &ParentScope<'b>,
541     ) -> Option<(Vec<Segment>, Vec<String>)> {
542         // Replace first ident with `crate` and check if that is valid.
543         path[0].ident.name = keywords::Super.name();
544         let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
545         debug!("make_missing_super_suggestion:  path={:?} result={:?}", path, result);
546         if let PathResult::Module(..) = result {
547             Some((path, Vec::new()))
548         } else {
549             None
550         }
551     }
552
553     /// Suggests a missing external crate name if that resolves to an correct module.
554     ///
555     /// ```
556     ///    |
557     /// LL | use foobar::Baz;
558     ///    |     ^^^^^^ did you mean `baz::foobar`?
559     /// ```
560     ///
561     /// Used when importing a submodule of an external crate but missing that crate's
562     /// name as the first part of path.
563     fn make_external_crate_suggestion(
564         &mut self,
565         span: Span,
566         mut path: Vec<Segment>,
567         parent_scope: &ParentScope<'b>,
568     ) -> Option<(Vec<Segment>, Vec<String>)> {
569         if path[1].ident.span.rust_2015() {
570             return None;
571         }
572
573         // Sort extern crate names in reverse order to get
574         // 1) some consistent ordering for emitted dignostics, and
575         // 2) `std` suggestions before `core` suggestions.
576         let mut extern_crate_names =
577             self.resolver.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
578         extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
579
580         for name in extern_crate_names.into_iter() {
581             // Replace first ident with a crate name and check if that is valid.
582             path[0].ident.name = name;
583             let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
584             debug!("make_external_crate_suggestion: name={:?} path={:?} result={:?}",
585                     name, path, result);
586             if let PathResult::Module(..) = result {
587                 return Some((path, Vec::new()));
588             }
589         }
590
591         None
592     }
593
594     /// Suggests importing a macro from the root of the crate rather than a module within
595     /// the crate.
596     ///
597     /// ```
598     /// help: a macro with this name exists at the root of the crate
599     ///    |
600     /// LL | use issue_59764::makro;
601     ///    |     ^^^^^^^^^^^^^^^^^^
602     ///    |
603     ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
604     ///            at the root of the crate instead of the module where it is defined
605     /// ```
606     pub(crate) fn check_for_module_export_macro(
607         &self,
608         directive: &'b ImportDirective<'b>,
609         module: ModuleOrUniformRoot<'b>,
610         ident: Ident,
611     ) -> Option<(Option<Suggestion>, Vec<String>)> {
612         let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
613             module
614         } else {
615             return None;
616         };
617
618         while let Some(parent) = crate_module.parent {
619             crate_module = parent;
620         }
621
622         if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
623             // Don't make a suggestion if the import was already from the root of the
624             // crate.
625             return None;
626         }
627
628         let resolutions = crate_module.resolutions.borrow();
629         let resolution = resolutions.get(&(ident, MacroNS))?;
630         let binding = resolution.borrow().binding()?;
631         if let Def::Def(DefKind::Macro(MacroKind::Bang), _) = binding.def() {
632             let module_name = crate_module.kind.name().unwrap();
633             let import = match directive.subclass {
634                 ImportDirectiveSubclass::SingleImport { source, target, .. } if source != target =>
635                     format!("{} as {}", source, target),
636                 _ => format!("{}", ident),
637             };
638
639             let mut corrections: Vec<(Span, String)> = Vec::new();
640             if !directive.is_nested() {
641                 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
642                 // intermediate segments.
643                 corrections.push((directive.span, format!("{}::{}", module_name, import)));
644             } else {
645                 // Find the binding span (and any trailing commas and spaces).
646                 //   ie. `use a::b::{c, d, e};`
647                 //                      ^^^
648                 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
649                     self.resolver.session, directive.span, directive.use_span,
650                 );
651                 debug!("check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
652                        found_closing_brace, binding_span);
653
654                 let mut removal_span = binding_span;
655                 if found_closing_brace {
656                     // If the binding span ended with a closing brace, as in the below example:
657                     //   ie. `use a::b::{c, d};`
658                     //                      ^
659                     // Then expand the span of characters to remove to include the previous
660                     // binding's trailing comma.
661                     //   ie. `use a::b::{c, d};`
662                     //                    ^^^
663                     if let Some(previous_span) = extend_span_to_previous_binding(
664                         self.resolver.session, binding_span,
665                     ) {
666                         debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
667                         removal_span = removal_span.with_lo(previous_span.lo());
668                     }
669                 }
670                 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
671
672                 // Remove the `removal_span`.
673                 corrections.push((removal_span, "".to_string()));
674
675                 // Find the span after the crate name and if it has nested imports immediatately
676                 // after the crate name already.
677                 //   ie. `use a::b::{c, d};`
678                 //               ^^^^^^^^^
679                 //   or  `use a::{b, c, d}};`
680                 //               ^^^^^^^^^^^
681                 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
682                     self.resolver.session, module_name, directive.use_span,
683                 );
684                 debug!("check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
685                        has_nested, after_crate_name);
686
687                 let source_map = self.resolver.session.source_map();
688
689                 // Add the import to the start, with a `{` if required.
690                 let start_point = source_map.start_point(after_crate_name);
691                 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
692                     corrections.push((
693                         start_point,
694                         if has_nested {
695                             // In this case, `start_snippet` must equal '{'.
696                             format!("{}{}, ", start_snippet, import)
697                         } else {
698                             // In this case, add a `{`, then the moved import, then whatever
699                             // was there before.
700                             format!("{{{}, {}", import, start_snippet)
701                         }
702                     ));
703                 }
704
705                 // Add a `};` to the end if nested, matching the `{` added at the start.
706                 if !has_nested {
707                     corrections.push((source_map.end_point(after_crate_name),
708                                      "};".to_string()));
709                 }
710             }
711
712             let suggestion = Some((
713                 corrections,
714                 String::from("a macro with this name exists at the root of the crate"),
715                 Applicability::MaybeIncorrect,
716             ));
717             let note = vec![
718                 "this could be because a macro annotated with `#[macro_export]` will be exported \
719                  at the root of the crate instead of the module where it is defined".to_string(),
720             ];
721             Some((suggestion, note))
722         } else {
723             None
724         }
725     }
726 }
727
728 /// Given a `binding_span` of a binding within a use statement:
729 ///
730 /// ```
731 /// use foo::{a, b, c};
732 ///              ^
733 /// ```
734 ///
735 /// then return the span until the next binding or the end of the statement:
736 ///
737 /// ```
738 /// use foo::{a, b, c};
739 ///              ^^^
740 /// ```
741 pub(crate) fn find_span_of_binding_until_next_binding(
742     sess: &Session,
743     binding_span: Span,
744     use_span: Span,
745 ) -> (bool, Span) {
746     let source_map = sess.source_map();
747
748     // Find the span of everything after the binding.
749     //   ie. `a, e};` or `a};`
750     let binding_until_end = binding_span.with_hi(use_span.hi());
751
752     // Find everything after the binding but not including the binding.
753     //   ie. `, e};` or `};`
754     let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
755
756     // Keep characters in the span until we encounter something that isn't a comma or
757     // whitespace.
758     //   ie. `, ` or ``.
759     //
760     // Also note whether a closing brace character was encountered. If there
761     // was, then later go backwards to remove any trailing commas that are left.
762     let mut found_closing_brace = false;
763     let after_binding_until_next_binding = source_map.span_take_while(
764         after_binding_until_end,
765         |&ch| {
766             if ch == '}' { found_closing_brace = true; }
767             ch == ' ' || ch == ','
768         }
769     );
770
771     // Combine the two spans.
772     //   ie. `a, ` or `a`.
773     //
774     // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
775     let span = binding_span.with_hi(after_binding_until_next_binding.hi());
776
777     (found_closing_brace, span)
778 }
779
780 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
781 /// binding.
782 ///
783 /// ```
784 /// use foo::a::{a, b, c};
785 ///               ^^--- binding span
786 ///               |
787 ///               returned span
788 ///
789 /// use foo::{a, b, c};
790 ///           --- binding span
791 /// ```
792 pub(crate) fn extend_span_to_previous_binding(
793     sess: &Session,
794     binding_span: Span,
795 ) -> Option<Span> {
796     let source_map = sess.source_map();
797
798     // `prev_source` will contain all of the source that came before the span.
799     // Then split based on a command and take the first (ie. closest to our span)
800     // snippet. In the example, this is a space.
801     let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
802
803     let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
804     let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
805     if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
806         return None;
807     }
808
809     let prev_comma = prev_comma.first().unwrap();
810     let prev_starting_brace = prev_starting_brace.first().unwrap();
811
812     // If the amount of source code before the comma is greater than
813     // the amount of source code before the starting brace then we've only
814     // got one item in the nested item (eg. `issue_52891::{self}`).
815     if prev_comma.len() > prev_starting_brace.len() {
816         return None;
817     }
818
819     Some(binding_span.with_lo(BytePos(
820         // Take away the number of bytes for the characters we've found and an
821         // extra for the comma.
822         binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1
823     )))
824 }
825
826 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
827 /// it is a nested use tree.
828 ///
829 /// ```
830 /// use foo::a::{b, c};
831 ///          ^^^^^^^^^^ // false
832 ///
833 /// use foo::{a, b, c};
834 ///          ^^^^^^^^^^ // true
835 ///
836 /// use foo::{a, b::{c, d}};
837 ///          ^^^^^^^^^^^^^^^ // true
838 /// ```
839 fn find_span_immediately_after_crate_name(
840     sess: &Session,
841     module_name: Symbol,
842     use_span: Span,
843 ) -> (bool, Span) {
844     debug!("find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
845            module_name, use_span);
846     let source_map = sess.source_map();
847
848     // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
849     let mut num_colons = 0;
850     // Find second colon.. `use issue_59764:`
851     let until_second_colon = source_map.span_take_while(use_span, |c| {
852         if *c == ':' { num_colons += 1; }
853         match c {
854             ':' if num_colons == 2 => false,
855             _ => true,
856         }
857     });
858     // Find everything after the second colon.. `foo::{baz, makro};`
859     let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
860
861     let mut found_a_non_whitespace_character = false;
862     // Find the first non-whitespace character in `from_second_colon`.. `f`
863     let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
864         if found_a_non_whitespace_character { return false; }
865         if !c.is_whitespace() { found_a_non_whitespace_character = true; }
866         true
867     });
868
869     // Find the first `{` in from_second_colon.. `foo::{`
870     let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
871
872     (next_left_bracket == after_second_colon, from_second_colon)
873 }