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