]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/late/diagnostics.rs
e04e56cb945af8bd4eb535f2f202b954b7a706e8
[rust.git] / src / librustc_resolve / late / diagnostics.rs
1 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
2 use crate::{PathResult, PathSource, Segment};
3 use crate::path_names_to_string;
4 use crate::diagnostics::{add_typo_suggestion, ImportSuggestion, TypoSuggestion};
5 use crate::late::{LateResolutionVisitor, RibKind};
6
7 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
8 use log::debug;
9 use rustc::hir::def::{self, DefKind, CtorKind};
10 use rustc::hir::def::Namespace::{self, *};
11 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
12 use rustc::hir::PrimTy;
13 use rustc::session::config::nightly_options;
14 use rustc::util::nodemap::FxHashSet;
15 use syntax::ast::{self, Expr, ExprKind, Ident, NodeId, Path, Ty, TyKind};
16 use syntax::ext::base::MacroKind;
17 use syntax::symbol::kw;
18 use syntax::util::lev_distance::find_best_match_for_name;
19 use syntax_pos::Span;
20
21 type Res = def::Res<ast::NodeId>;
22
23 /// A field or associated item from self type suggested in case of resolution failure.
24 enum AssocSuggestion {
25     Field,
26     MethodWithSelf,
27     AssocItem,
28 }
29
30 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
31     namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
32 }
33
34 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
35     namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
36 }
37
38 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
39 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
40     let variant_path = &suggestion.path;
41     let variant_path_string = path_names_to_string(variant_path);
42
43     let path_len = suggestion.path.segments.len();
44     let enum_path = ast::Path {
45         span: suggestion.path.span,
46         segments: suggestion.path.segments[0..path_len - 1].to_vec(),
47     };
48     let enum_path_string = path_names_to_string(&enum_path);
49
50     (variant_path_string, enum_path_string)
51 }
52
53 impl<'a> LateResolutionVisitor<'a, '_> {
54     /// Handles error reporting for `smart_resolve_path_fragment` function.
55     /// Creates base error and amends it with one short label and possibly some longer helps/notes.
56     pub(crate) fn smart_resolve_report_errors(
57         &mut self,
58         path: &[Segment],
59         span: Span,
60         source: PathSource<'_>,
61         res: Option<Res>,
62     ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
63         let ident_span = path.last().map_or(span, |ident| ident.ident.span);
64         let ns = source.namespace();
65         let is_expected = &|res| source.is_expected(res);
66         let is_enum_variant = &|res| {
67             if let Res::Def(DefKind::Variant, _) = res { true } else { false }
68         };
69
70         // Make the base error.
71         let expected = source.descr_expected();
72         let path_str = Segment::names_to_string(path);
73         let item_str = path.last().unwrap().ident;
74         let code = source.error_code(res.is_some());
75         let (base_msg, fallback_label, base_span) = if let Some(res) = res {
76             (format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
77                 format!("not a {}", expected),
78                 span)
79         } else {
80             let item_span = path.last().unwrap().ident.span;
81             let (mod_prefix, mod_str) = if path.len() == 1 {
82                 (String::new(), "this scope".to_string())
83             } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
84                 (String::new(), "the crate root".to_string())
85             } else {
86                 let mod_path = &path[..path.len() - 1];
87                 let mod_prefix = match self.resolve_path(
88                     mod_path, Some(TypeNS), false, span, CrateLint::No
89                 ) {
90                     PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
91                     _ => None,
92                 }.map_or(String::new(), |res| format!("{} ", res.descr()));
93                 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
94             };
95             (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
96                 format!("not found in {}", mod_str),
97                 item_span)
98         };
99
100         let code = DiagnosticId::Error(code.into());
101         let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
102
103         // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
104         if ["this", "my"].contains(&&*item_str.as_str())
105             && self.self_value_is_available(path[0].ident.span, span) {
106             err.span_suggestion(
107                 span,
108                 "did you mean",
109                 "self".to_string(),
110                 Applicability::MaybeIncorrect,
111             );
112         }
113
114         // Emit special messages for unresolved `Self` and `self`.
115         if is_self_type(path, ns) {
116             syntax::diagnostic_used!(E0411);
117             err.code(DiagnosticId::Error("E0411".into()));
118             err.span_label(span, format!("`Self` is only available in impls, traits, \
119                                           and type definitions"));
120             return (err, Vec::new());
121         }
122         if is_self_value(path, ns) {
123             debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
124
125             syntax::diagnostic_used!(E0424);
126             err.code(DiagnosticId::Error("E0424".into()));
127             err.span_label(span, match source {
128                 PathSource::Pat => {
129                     format!("`self` value is a keyword \
130                              and may not be bound to \
131                              variables or shadowed")
132                 }
133                 _ => {
134                     format!("`self` value is a keyword \
135                              only available in methods \
136                              with `self` parameter")
137                 }
138             });
139             return (err, Vec::new());
140         }
141
142         // Try to lookup name in more relaxed fashion for better error reporting.
143         let ident = path.last().unwrap().ident;
144         let candidates = self.r.lookup_import_candidates(ident, ns, is_expected)
145             .drain(..)
146             .filter(|ImportSuggestion { did, .. }| {
147                 match (did, res.and_then(|res| res.opt_def_id())) {
148                     (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
149                     _ => true,
150                 }
151             })
152             .collect::<Vec<_>>();
153         let crate_def_id = DefId::local(CRATE_DEF_INDEX);
154         if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
155             let enum_candidates =
156                 self.r.lookup_import_candidates(ident, ns, is_enum_variant);
157             let mut enum_candidates = enum_candidates.iter()
158                 .map(|suggestion| {
159                     import_candidate_to_enum_paths(&suggestion)
160                 }).collect::<Vec<_>>();
161             enum_candidates.sort();
162
163             if !enum_candidates.is_empty() {
164                 // Contextualize for E0412 "cannot find type", but don't belabor the point
165                 // (that it's a variant) for E0573 "expected type, found variant".
166                 let preamble = if res.is_none() {
167                     let others = match enum_candidates.len() {
168                         1 => String::new(),
169                         2 => " and 1 other".to_owned(),
170                         n => format!(" and {} others", n)
171                     };
172                     format!("there is an enum variant `{}`{}; ",
173                             enum_candidates[0].0, others)
174                 } else {
175                     String::new()
176                 };
177                 let msg = format!("{}try using the variant's enum", preamble);
178
179                 err.span_suggestions(
180                     span,
181                     &msg,
182                     enum_candidates.into_iter()
183                         .map(|(_variant_path, enum_ty_path)| enum_ty_path)
184                         // Variants re-exported in prelude doesn't mean `prelude::v1` is the
185                         // type name!
186                         // FIXME: is there a more principled way to do this that
187                         // would work for other re-exports?
188                         .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
189                         // Also write `Option` rather than `std::prelude::v1::Option`.
190                         .map(|enum_ty_path| {
191                             // FIXME #56861: DRY-er prelude filtering.
192                             enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
193                         }),
194                     Applicability::MachineApplicable,
195                 );
196             }
197         }
198         if path.len() == 1 && self.self_type_is_available(span) {
199             if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
200                 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
201                 match candidate {
202                     AssocSuggestion::Field => {
203                         if self_is_available {
204                             err.span_suggestion(
205                                 span,
206                                 "you might have meant to use the available field",
207                                 format!("self.{}", path_str),
208                                 Applicability::MachineApplicable,
209                             );
210                         } else {
211                             err.span_label(
212                                 span,
213                                 "a field by this name exists in `Self`",
214                             );
215                         }
216                     }
217                     AssocSuggestion::MethodWithSelf if self_is_available => {
218                         err.span_suggestion(
219                             span,
220                             "try",
221                             format!("self.{}", path_str),
222                             Applicability::MachineApplicable,
223                         );
224                     }
225                     AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
226                         err.span_suggestion(
227                             span,
228                             "try",
229                             format!("Self::{}", path_str),
230                             Applicability::MachineApplicable,
231                         );
232                     }
233                 }
234                 return (err, candidates);
235             }
236         }
237
238         // Try Levenshtein algorithm.
239         let levenshtein_worked = add_typo_suggestion(
240             &mut err, self.lookup_typo_candidate(path, ns, is_expected, span), ident_span
241         );
242
243         // Try context-dependent help if relaxed lookup didn't work.
244         if let Some(res) = res {
245             if self.smart_resolve_context_dependent_help(&mut err,
246                                                          span,
247                                                          source,
248                                                          res,
249                                                          &path_str,
250                                                          &fallback_label) {
251                 return (err, candidates);
252             }
253         }
254
255         // Fallback label.
256         if !levenshtein_worked {
257             err.span_label(base_span, fallback_label);
258             self.type_ascription_suggestion(&mut err, base_span);
259         }
260         (err, candidates)
261     }
262
263     fn followed_by_brace(&self, span: Span) -> (bool, Option<(Span, String)>) {
264         // HACK(estebank): find a better way to figure out that this was a
265         // parser issue where a struct literal is being used on an expression
266         // where a brace being opened means a block is being started. Look
267         // ahead for the next text to see if `span` is followed by a `{`.
268         let sm = self.r.session.source_map();
269         let mut sp = span;
270         loop {
271             sp = sm.next_point(sp);
272             match sm.span_to_snippet(sp) {
273                 Ok(ref snippet) => {
274                     if snippet.chars().any(|c| { !c.is_whitespace() }) {
275                         break;
276                     }
277                 }
278                 _ => break,
279             }
280         }
281         let followed_by_brace = match sm.span_to_snippet(sp) {
282             Ok(ref snippet) if snippet == "{" => true,
283             _ => false,
284         };
285         // In case this could be a struct literal that needs to be surrounded
286         // by parenthesis, find the appropriate span.
287         let mut i = 0;
288         let mut closing_brace = None;
289         loop {
290             sp = sm.next_point(sp);
291             match sm.span_to_snippet(sp) {
292                 Ok(ref snippet) => {
293                     if snippet == "}" {
294                         let sp = span.to(sp);
295                         if let Ok(snippet) = sm.span_to_snippet(sp) {
296                             closing_brace = Some((sp, snippet));
297                         }
298                         break;
299                     }
300                 }
301                 _ => break,
302             }
303             i += 1;
304             // The bigger the span, the more likely we're incorrect --
305             // bound it to 100 chars long.
306             if i > 100 {
307                 break;
308             }
309         }
310         return (followed_by_brace, closing_brace)
311     }
312
313     /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
314     /// function.
315     /// Returns `true` if able to provide context-dependent help.
316     fn smart_resolve_context_dependent_help(
317         &mut self,
318         err: &mut DiagnosticBuilder<'a>,
319         span: Span,
320         source: PathSource<'_>,
321         res: Res,
322         path_str: &str,
323         fallback_label: &str,
324     ) -> bool {
325         let ns = source.namespace();
326         let is_expected = &|res| source.is_expected(res);
327
328         let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
329             ExprKind::Field(_, ident) => {
330                 err.span_suggestion(
331                     expr.span,
332                     "use the path separator to refer to an item",
333                     format!("{}::{}", path_str, ident),
334                     Applicability::MaybeIncorrect,
335                 );
336                 true
337             }
338             ExprKind::MethodCall(ref segment, ..) => {
339                 let span = expr.span.with_hi(segment.ident.span.hi());
340                 err.span_suggestion(
341                     span,
342                     "use the path separator to refer to an item",
343                     format!("{}::{}", path_str, segment.ident),
344                     Applicability::MaybeIncorrect,
345                 );
346                 true
347             }
348             _ => false,
349         };
350
351         let mut bad_struct_syntax_suggestion = || {
352             let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
353             let mut suggested = false;
354             match source {
355                 PathSource::Expr(Some(parent)) => {
356                     suggested = path_sep(err, &parent);
357                 }
358                 PathSource::Expr(None) if followed_by_brace == true => {
359                     if let Some((sp, snippet)) = closing_brace {
360                         err.span_suggestion(
361                             sp,
362                             "surround the struct literal with parenthesis",
363                             format!("({})", snippet),
364                             Applicability::MaybeIncorrect,
365                         );
366                     } else {
367                         err.span_label(
368                             span,  // Note the parenthesis surrounding the suggestion below
369                             format!("did you mean `({} {{ /* fields */ }})`?", path_str),
370                         );
371                     }
372                     suggested = true;
373                 },
374                 _ => {}
375             }
376             if !suggested {
377                 err.span_label(
378                     span,
379                     format!("did you mean `{} {{ /* fields */ }}`?", path_str),
380                 );
381             }
382         };
383
384         match (res, source) {
385             (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
386                 err.span_suggestion(
387                     span,
388                     "use `!` to invoke the macro",
389                     format!("{}!", path_str),
390                     Applicability::MaybeIncorrect,
391                 );
392                 if path_str == "try" && span.rust_2015() {
393                     err.note("if you want the `try` keyword, you need to be in the 2018 edition");
394                 }
395             }
396             (Res::Def(DefKind::TyAlias, _), PathSource::Trait(_)) => {
397                 err.span_label(span, "type aliases cannot be used as traits");
398                 if nightly_options::is_nightly_build() {
399                     err.note("did you mean to use a trait alias?");
400                 }
401             }
402             (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
403                 if !path_sep(err, &parent) {
404                     return false;
405                 }
406             }
407             (Res::Def(DefKind::Enum, def_id), PathSource::TupleStruct)
408                 | (Res::Def(DefKind::Enum, def_id), PathSource::Expr(..))  => {
409                 if let Some(variants) = self.collect_enum_variants(def_id) {
410                     if !variants.is_empty() {
411                         let msg = if variants.len() == 1 {
412                             "try using the enum's variant"
413                         } else {
414                             "try using one of the enum's variants"
415                         };
416
417                         err.span_suggestions(
418                             span,
419                             msg,
420                             variants.iter().map(path_names_to_string),
421                             Applicability::MaybeIncorrect,
422                         );
423                     }
424                 } else {
425                     err.note("did you mean to use one of the enum's variants?");
426                 }
427             }
428             (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
429                 if let Some((ctor_def, ctor_vis))
430                         = self.r.struct_constructors.get(&def_id).cloned() {
431                     let accessible_ctor =
432                         self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
433                     if is_expected(ctor_def) && !accessible_ctor {
434                         err.span_label(
435                             span,
436                             format!("constructor is not visible here due to private fields"),
437                         );
438                     }
439                 } else {
440                     bad_struct_syntax_suggestion();
441                 }
442             }
443             (Res::Def(DefKind::Union, _), _) |
444             (Res::Def(DefKind::Variant, _), _) |
445             (Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _), _) if ns == ValueNS => {
446                 bad_struct_syntax_suggestion();
447             }
448             (Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), _) if ns == ValueNS => {
449                 err.span_label(
450                     span,
451                     format!("did you mean `{} ( /* fields */ )`?", path_str),
452                 );
453             }
454             (Res::SelfTy(..), _) if ns == ValueNS => {
455                 err.span_label(span, fallback_label);
456                 err.note("can't use `Self` as a constructor, you must use the implemented struct");
457             }
458             (Res::Def(DefKind::TyAlias, _), _)
459             | (Res::Def(DefKind::AssocTy, _), _) if ns == ValueNS => {
460                 err.note("can't use a type alias as a constructor");
461             }
462             _ => return false,
463         }
464         true
465     }
466
467     fn lookup_assoc_candidate<FilterFn>(&mut self,
468                                         ident: Ident,
469                                         ns: Namespace,
470                                         filter_fn: FilterFn)
471                                         -> Option<AssocSuggestion>
472         where FilterFn: Fn(Res) -> bool
473     {
474         fn extract_node_id(t: &Ty) -> Option<NodeId> {
475             match t.node {
476                 TyKind::Path(None, _) => Some(t.id),
477                 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
478                 // This doesn't handle the remaining `Ty` variants as they are not
479                 // that commonly the self_type, it might be interesting to provide
480                 // support for those in future.
481                 _ => None,
482             }
483         }
484
485         // Fields are generally expected in the same contexts as locals.
486         if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
487             if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
488                 // Look for a field with the same name in the current self_type.
489                 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
490                     match resolution.base_res() {
491                         Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did)
492                                 if resolution.unresolved_segments() == 0 => {
493                             if let Some(field_names) = self.r.field_names.get(&did) {
494                                 if field_names.iter().any(|&field_name| ident.name == field_name) {
495                                     return Some(AssocSuggestion::Field);
496                                 }
497                             }
498                         }
499                         _ => {}
500                     }
501                 }
502             }
503         }
504
505         for assoc_type_ident in &self.current_trait_assoc_types {
506             if *assoc_type_ident == ident {
507                 return Some(AssocSuggestion::AssocItem);
508             }
509         }
510
511         // Look for associated items in the current trait.
512         if let Some((module, _)) = self.current_trait_ref {
513             if let Ok(binding) = self.r.resolve_ident_in_module(
514                     ModuleOrUniformRoot::Module(module),
515                     ident,
516                     ns,
517                     &self.parent_scope,
518                     false,
519                     module.span,
520                 ) {
521                 let res = binding.res();
522                 if filter_fn(res) {
523                     return Some(if self.r.has_self.contains(&res.def_id()) {
524                         AssocSuggestion::MethodWithSelf
525                     } else {
526                         AssocSuggestion::AssocItem
527                     });
528                 }
529             }
530         }
531
532         None
533     }
534
535     fn lookup_typo_candidate(
536         &mut self,
537         path: &[Segment],
538         ns: Namespace,
539         filter_fn: &impl Fn(Res) -> bool,
540         span: Span,
541     ) -> Option<TypoSuggestion> {
542         let mut names = Vec::new();
543         if path.len() == 1 {
544             // Search in lexical scope.
545             // Walk backwards up the ribs in scope and collect candidates.
546             for rib in self.ribs[ns].iter().rev() {
547                 // Locals and type parameters
548                 for (ident, &res) in &rib.bindings {
549                     if filter_fn(res) {
550                         names.push(TypoSuggestion::from_res(ident.name, res));
551                     }
552                 }
553                 // Items in scope
554                 if let RibKind::ModuleRibKind(module) = rib.kind {
555                     // Items from this module
556                     self.r.add_module_candidates(module, &mut names, &filter_fn);
557
558                     if let ModuleKind::Block(..) = module.kind {
559                         // We can see through blocks
560                     } else {
561                         // Items from the prelude
562                         if !module.no_implicit_prelude {
563                             let extern_prelude = self.r.extern_prelude.clone();
564                             names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
565                                 self.r.crate_loader
566                                     .maybe_process_path_extern(ident.name, ident.span)
567                                     .and_then(|crate_id| {
568                                         let crate_mod = Res::Def(
569                                             DefKind::Mod,
570                                             DefId {
571                                                 krate: crate_id,
572                                                 index: CRATE_DEF_INDEX,
573                                             },
574                                         );
575
576                                         if filter_fn(crate_mod) {
577                                             Some(TypoSuggestion::from_res(ident.name, crate_mod))
578                                         } else {
579                                             None
580                                         }
581                                     })
582                             }));
583
584                             if let Some(prelude) = self.r.prelude {
585                                 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
586                             }
587                         }
588                         break;
589                     }
590                 }
591             }
592             // Add primitive types to the mix
593             if filter_fn(Res::PrimTy(PrimTy::Bool)) {
594                 names.extend(
595                     self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
596                         TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
597                     })
598                 )
599             }
600         } else {
601             // Search in module.
602             let mod_path = &path[..path.len() - 1];
603             if let PathResult::Module(module) = self.resolve_path(
604                 mod_path, Some(TypeNS), false, span, CrateLint::No
605             ) {
606                 if let ModuleOrUniformRoot::Module(module) = module {
607                     self.r.add_module_candidates(module, &mut names, &filter_fn);
608                 }
609             }
610         }
611
612         let name = path[path.len() - 1].ident.name;
613         // Make sure error reporting is deterministic.
614         names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
615
616         match find_best_match_for_name(
617             names.iter().map(|suggestion| &suggestion.candidate),
618             &name.as_str(),
619             None,
620         ) {
621             Some(found) if found != name => names
622                 .into_iter()
623                 .find(|suggestion| suggestion.candidate == found),
624             _ => None,
625         }
626     }
627
628     /// Only used in a specific case of type ascription suggestions
629     fn get_colon_suggestion_span(&self, start: Span) -> Span {
630         let cm = self.r.session.source_map();
631         start.to(cm.next_point(start))
632     }
633
634     fn type_ascription_suggestion(
635         &self,
636         err: &mut DiagnosticBuilder<'_>,
637         base_span: Span,
638     ) {
639         debug!("type_ascription_suggetion {:?}", base_span);
640         let cm = self.r.session.source_map();
641         let base_snippet = cm.span_to_snippet(base_span);
642         debug!("self.current_type_ascription {:?}", self.current_type_ascription);
643         if let Some(sp) = self.current_type_ascription.last() {
644             let mut sp = *sp;
645             loop {
646                 // Try to find the `:`; bail on first non-':' / non-whitespace.
647                 sp = cm.next_point(sp);
648                 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
649                     let line_sp = cm.lookup_char_pos(sp.hi()).line;
650                     let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
651                     if snippet == ":" {
652                         let mut show_label = true;
653                         if line_sp != line_base_sp {
654                             err.span_suggestion_short(
655                                 sp,
656                                 "did you mean to use `;` here instead?",
657                                 ";".to_string(),
658                                 Applicability::MaybeIncorrect,
659                             );
660                         } else {
661                             let colon_sp = self.get_colon_suggestion_span(sp);
662                             let after_colon_sp = self.get_colon_suggestion_span(
663                                 colon_sp.shrink_to_hi(),
664                             );
665                             if !cm.span_to_snippet(after_colon_sp).map(|s| s == " ")
666                                 .unwrap_or(false)
667                             {
668                                 err.span_suggestion(
669                                     colon_sp,
670                                     "maybe you meant to write a path separator here",
671                                     "::".to_string(),
672                                     Applicability::MaybeIncorrect,
673                                 );
674                                 show_label = false;
675                             }
676                             if let Ok(base_snippet) = base_snippet {
677                                 let mut sp = after_colon_sp;
678                                 for _ in 0..100 {
679                                     // Try to find an assignment
680                                     sp = cm.next_point(sp);
681                                     let snippet = cm.span_to_snippet(sp.to(cm.next_point(sp)));
682                                     match snippet {
683                                         Ok(ref x) if x.as_str() == "=" => {
684                                             err.span_suggestion(
685                                                 base_span,
686                                                 "maybe you meant to write an assignment here",
687                                                 format!("let {}", base_snippet),
688                                                 Applicability::MaybeIncorrect,
689                                             );
690                                             show_label = false;
691                                             break;
692                                         }
693                                         Ok(ref x) if x.as_str() == "\n" => break,
694                                         Err(_) => break,
695                                         Ok(_) => {}
696                                     }
697                                 }
698                             }
699                         }
700                         if show_label {
701                             err.span_label(base_span,
702                                            "expecting a type here because of type ascription");
703                         }
704                         break;
705                     } else if !snippet.trim().is_empty() {
706                         debug!("tried to find type ascription `:` token, couldn't find it");
707                         break;
708                     }
709                 } else {
710                     break;
711                 }
712             }
713         }
714     }
715
716     fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
717         let mut result = None;
718         let mut seen_modules = FxHashSet::default();
719         let mut worklist = vec![(self.r.graph_root, Vec::new())];
720
721         while let Some((in_module, path_segments)) = worklist.pop() {
722             // abort if the module is already found
723             if result.is_some() { break; }
724
725             in_module.for_each_child_stable(self.r, |_, ident, _, name_binding| {
726                 // abort if the module is already found or if name_binding is private external
727                 if result.is_some() || !name_binding.vis.is_visible_locally() {
728                     return
729                 }
730                 if let Some(module) = name_binding.module() {
731                     // form the path
732                     let mut path_segments = path_segments.clone();
733                     path_segments.push(ast::PathSegment::from_ident(ident));
734                     let module_def_id = module.def_id().unwrap();
735                     if module_def_id == def_id {
736                         let path = Path {
737                             span: name_binding.span,
738                             segments: path_segments,
739                         };
740                         result = Some((module, ImportSuggestion { did: Some(def_id), path }));
741                     } else {
742                         // add the module to the lookup
743                         if seen_modules.insert(module_def_id) {
744                             worklist.push((module, path_segments));
745                         }
746                     }
747                 }
748             });
749         }
750
751         result
752     }
753
754     fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
755         self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
756             let mut variants = Vec::new();
757             enum_module.for_each_child_stable(self.r, |_, ident, _, name_binding| {
758                 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
759                     let mut segms = enum_import_suggestion.path.segments.clone();
760                     segms.push(ast::PathSegment::from_ident(ident));
761                     variants.push(Path {
762                         span: name_binding.span,
763                         segments: segms,
764                     });
765                 }
766             });
767             variants
768         })
769     }
770 }