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