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