]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/error_reporting.rs
Rollup merge of #58301 - RalfJung:fat-ptr-eq, r=oli-obk
[rust.git] / src / librustc_resolve / error_reporting.rs
1 use std::cmp::Reverse;
2
3 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
4 use log::debug;
5 use rustc::hir::def::*;
6 use rustc::hir::def::Namespace::*;
7 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
8 use rustc::session::config::nightly_options;
9 use syntax::ast::{ExprKind};
10 use syntax::symbol::keywords;
11 use syntax_pos::Span;
12
13 use crate::macros::ParentScope;
14 use crate::resolve_imports::ImportResolver;
15 use crate::{import_candidate_to_enum_paths, is_self_type, is_self_value, path_names_to_string};
16 use crate::{AssocSuggestion, CrateLint, ImportSuggestion, ModuleOrUniformRoot, PathResult,
17             PathSource, Resolver, Segment};
18
19 impl<'a> Resolver<'a> {
20     /// Handles error reporting for `smart_resolve_path_fragment` function.
21     /// Creates base error and amends it with one short label and possibly some longer helps/notes.
22     pub(crate) fn smart_resolve_report_errors(
23         &mut self,
24         path: &[Segment],
25         span: Span,
26         source: PathSource<'_>,
27         def: Option<Def>,
28     ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
29         let ident_span = path.last().map_or(span, |ident| ident.ident.span);
30         let ns = source.namespace();
31         let is_expected = &|def| source.is_expected(def);
32         let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
33
34         // Make the base error.
35         let expected = source.descr_expected();
36         let path_str = Segment::names_to_string(path);
37         let item_str = path.last().unwrap().ident;
38         let code = source.error_code(def.is_some());
39         let (base_msg, fallback_label, base_span) = if let Some(def) = def {
40             (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
41                 format!("not a {}", expected),
42                 span)
43         } else {
44             let item_span = path.last().unwrap().ident.span;
45             let (mod_prefix, mod_str) = if path.len() == 1 {
46                 (String::new(), "this scope".to_string())
47             } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() {
48                 (String::new(), "the crate root".to_string())
49             } else {
50                 let mod_path = &path[..path.len() - 1];
51                 let mod_prefix = match self.resolve_path_without_parent_scope(
52                     mod_path, Some(TypeNS), false, span, CrateLint::No
53                 ) {
54                     PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
55                         module.def(),
56                     _ => None,
57                 }.map_or(String::new(), |def| format!("{} ", def.kind_name()));
58                 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
59             };
60             (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
61                 format!("not found in {}", mod_str),
62                 item_span)
63         };
64
65         let code = DiagnosticId::Error(code.into());
66         let mut err = self.session.struct_span_err_with_code(base_span, &base_msg, code);
67
68         // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
69         if ["this", "my"].contains(&&*item_str.as_str())
70             && self.self_value_is_available(path[0].ident.span, span) {
71             err.span_suggestion(
72                 span,
73                 "did you mean",
74                 "self".to_string(),
75                 Applicability::MaybeIncorrect,
76             );
77         }
78
79         // Emit special messages for unresolved `Self` and `self`.
80         if is_self_type(path, ns) {
81             __diagnostic_used!(E0411);
82             err.code(DiagnosticId::Error("E0411".into()));
83             err.span_label(span, format!("`Self` is only available in impls, traits, \
84                                           and type definitions"));
85             return (err, Vec::new());
86         }
87         if is_self_value(path, ns) {
88             debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
89
90             __diagnostic_used!(E0424);
91             err.code(DiagnosticId::Error("E0424".into()));
92             err.span_label(span, match source {
93                 PathSource::Pat => {
94                     format!("`self` value is a keyword \
95                              and may not be bound to \
96                              variables or shadowed")
97                 }
98                 _ => {
99                     format!("`self` value is a keyword \
100                              only available in methods \
101                              with `self` parameter")
102                 }
103             });
104             return (err, Vec::new());
105         }
106
107         // Try to lookup name in more relaxed fashion for better error reporting.
108         let ident = path.last().unwrap().ident;
109         let candidates = self.lookup_import_candidates(ident, ns, is_expected)
110             .drain(..)
111             .filter(|ImportSuggestion { did, .. }| {
112                 match (did, def.and_then(|def| def.opt_def_id())) {
113                     (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
114                     _ => true,
115                 }
116             })
117             .collect::<Vec<_>>();
118         if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
119             let enum_candidates =
120                 self.lookup_import_candidates(ident, ns, is_enum_variant);
121             let mut enum_candidates = enum_candidates.iter()
122                 .map(|suggestion| {
123                     import_candidate_to_enum_paths(&suggestion)
124                 }).collect::<Vec<_>>();
125             enum_candidates.sort();
126
127             if !enum_candidates.is_empty() {
128                 // Contextualize for E0412 "cannot find type", but don't belabor the point
129                 // (that it's a variant) for E0573 "expected type, found variant".
130                 let preamble = if def.is_none() {
131                     let others = match enum_candidates.len() {
132                         1 => String::new(),
133                         2 => " and 1 other".to_owned(),
134                         n => format!(" and {} others", n)
135                     };
136                     format!("there is an enum variant `{}`{}; ",
137                             enum_candidates[0].0, others)
138                 } else {
139                     String::new()
140                 };
141                 let msg = format!("{}try using the variant's enum", preamble);
142
143                 err.span_suggestions(
144                     span,
145                     &msg,
146                     enum_candidates.into_iter()
147                         .map(|(_variant_path, enum_ty_path)| enum_ty_path)
148                         // Variants re-exported in prelude doesn't mean `prelude::v1` is the
149                         // type name!
150                         // FIXME: is there a more principled way to do this that
151                         // would work for other re-exports?
152                         .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
153                         // Also write `Option` rather than `std::prelude::v1::Option`.
154                         .map(|enum_ty_path| {
155                             // FIXME #56861: DRY-er prelude filtering.
156                             enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
157                         }),
158                     Applicability::MachineApplicable,
159                 );
160             }
161         }
162         if path.len() == 1 && self.self_type_is_available(span) {
163             if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
164                 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
165                 match candidate {
166                     AssocSuggestion::Field => {
167                         err.span_suggestion(
168                             span,
169                             "try",
170                             format!("self.{}", path_str),
171                             Applicability::MachineApplicable,
172                         );
173                         if !self_is_available {
174                             err.span_label(span, format!("`self` value is a keyword \
175                                                          only available in \
176                                                          methods with `self` parameter"));
177                         }
178                     }
179                     AssocSuggestion::MethodWithSelf if self_is_available => {
180                         err.span_suggestion(
181                             span,
182                             "try",
183                             format!("self.{}", path_str),
184                             Applicability::MachineApplicable,
185                         );
186                     }
187                     AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
188                         err.span_suggestion(
189                             span,
190                             "try",
191                             format!("Self::{}", path_str),
192                             Applicability::MachineApplicable,
193                         );
194                     }
195                 }
196                 return (err, candidates);
197             }
198         }
199
200         let mut levenshtein_worked = false;
201
202         // Try Levenshtein algorithm.
203         let suggestion = self.lookup_typo_candidate(path, ns, is_expected, span);
204         if let Some(suggestion) = suggestion {
205             let msg = format!(
206                 "{} {} with a similar name exists",
207                 suggestion.article, suggestion.kind
208             );
209             err.span_suggestion(
210                 ident_span,
211                 &msg,
212                 suggestion.candidate.to_string(),
213                 Applicability::MaybeIncorrect,
214             );
215
216             levenshtein_worked = true;
217         }
218
219         // Try context-dependent help if relaxed lookup didn't work.
220         if let Some(def) = def {
221             if self.smart_resolve_context_dependent_help(&mut err,
222                                                          span,
223                                                          source,
224                                                          def,
225                                                          &path_str,
226                                                          &fallback_label) {
227                 return (err, candidates);
228             }
229         }
230
231         // Fallback label.
232         if !levenshtein_worked {
233             err.span_label(base_span, fallback_label);
234             self.type_ascription_suggestion(&mut err, base_span);
235         }
236         (err, candidates)
237     }
238
239     /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
240     /// function.
241     /// Returns `true` if able to provide context-dependent help.
242     fn smart_resolve_context_dependent_help(
243         &mut self,
244         err: &mut DiagnosticBuilder<'a>,
245         span: Span,
246         source: PathSource<'_>,
247         def: Def,
248         path_str: &str,
249         fallback_label: &str,
250     ) -> bool {
251         let ns = source.namespace();
252         let is_expected = &|def| source.is_expected(def);
253
254         match (def, source) {
255             (Def::Macro(..), _) => {
256                 err.span_suggestion(
257                     span,
258                     "use `!` to invoke the macro",
259                     format!("{}!", path_str),
260                     Applicability::MaybeIncorrect,
261                 );
262             }
263             (Def::TyAlias(..), PathSource::Trait(_)) => {
264                 err.span_label(span, "type aliases cannot be used as traits");
265                 if nightly_options::is_nightly_build() {
266                     err.note("did you mean to use a trait alias?");
267                 }
268             }
269             (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
270                 ExprKind::Field(_, ident) => {
271                     err.span_suggestion(
272                         parent.span,
273                         "use the path separator to refer to an item",
274                         format!("{}::{}", path_str, ident),
275                         Applicability::MaybeIncorrect,
276                     );
277                 }
278                 ExprKind::MethodCall(ref segment, ..) => {
279                     let span = parent.span.with_hi(segment.ident.span.hi());
280                     err.span_suggestion(
281                         span,
282                         "use the path separator to refer to an item",
283                         format!("{}::{}", path_str, segment.ident),
284                         Applicability::MaybeIncorrect,
285                     );
286                 }
287                 _ => return false,
288             },
289             (Def::Enum(..), PathSource::TupleStruct)
290                 | (Def::Enum(..), PathSource::Expr(..))  => {
291                 if let Some(variants) = self.collect_enum_variants(def) {
292                     err.note(&format!("did you mean to use one \
293                                        of the following variants?\n{}",
294                         variants.iter()
295                             .map(|suggestion| path_names_to_string(suggestion))
296                             .map(|suggestion| format!("- `{}`", suggestion))
297                             .collect::<Vec<_>>()
298                             .join("\n")));
299                 } else {
300                     err.note("did you mean to use one of the enum's variants?");
301                 }
302             },
303             (Def::Struct(def_id), _) if ns == ValueNS => {
304                 if let Some((ctor_def, ctor_vis))
305                         = self.struct_constructors.get(&def_id).cloned() {
306                     let accessible_ctor = self.is_accessible(ctor_vis);
307                     if is_expected(ctor_def) && !accessible_ctor {
308                         err.span_label(span, format!("constructor is not visible \
309                                                       here due to private fields"));
310                     }
311                 } else {
312                     // HACK(estebank): find a better way to figure out that this was a
313                     // parser issue where a struct literal is being used on an expression
314                     // where a brace being opened means a block is being started. Look
315                     // ahead for the next text to see if `span` is followed by a `{`.
316                     let sm = self.session.source_map();
317                     let mut sp = span;
318                     loop {
319                         sp = sm.next_point(sp);
320                         match sm.span_to_snippet(sp) {
321                             Ok(ref snippet) => {
322                                 if snippet.chars().any(|c| { !c.is_whitespace() }) {
323                                     break;
324                                 }
325                             }
326                             _ => break,
327                         }
328                     }
329                     let followed_by_brace = match sm.span_to_snippet(sp) {
330                         Ok(ref snippet) if snippet == "{" => true,
331                         _ => false,
332                     };
333                     // In case this could be a struct literal that needs to be surrounded
334                     // by parenthesis, find the appropriate span.
335                     let mut i = 0;
336                     let mut closing_brace = None;
337                     loop {
338                         sp = sm.next_point(sp);
339                         match sm.span_to_snippet(sp) {
340                             Ok(ref snippet) => {
341                                 if snippet == "}" {
342                                     let sp = span.to(sp);
343                                     if let Ok(snippet) = sm.span_to_snippet(sp) {
344                                         closing_brace = Some((sp, snippet));
345                                     }
346                                     break;
347                                 }
348                             }
349                             _ => break,
350                         }
351                         i += 1;
352                         // The bigger the span, the more likely we're incorrect --
353                         // bound it to 100 chars long.
354                         if i > 100 {
355                             break;
356                         }
357                     }
358                     match source {
359                         PathSource::Expr(Some(parent)) => {
360                             match parent.node {
361                                 ExprKind::MethodCall(ref path_assignment, _)  => {
362                                     err.span_suggestion(
363                                         sm.start_point(parent.span)
364                                             .to(path_assignment.ident.span),
365                                         "use `::` to access an associated function",
366                                         format!("{}::{}",
367                                                 path_str,
368                                                 path_assignment.ident),
369                                         Applicability::MaybeIncorrect
370                                     );
371                                 },
372                                 _ => {
373                                     err.span_label(
374                                         span,
375                                         format!("did you mean `{} {{ /* fields */ }}`?",
376                                                 path_str),
377                                     );
378                                 },
379                             }
380                         },
381                         PathSource::Expr(None) if followed_by_brace == true => {
382                             if let Some((sp, snippet)) = closing_brace {
383                                 err.span_suggestion(
384                                     sp,
385                                     "surround the struct literal with parenthesis",
386                                     format!("({})", snippet),
387                                     Applicability::MaybeIncorrect,
388                                 );
389                             } else {
390                                 err.span_label(
391                                     span,
392                                     format!("did you mean `({} {{ /* fields */ }})`?",
393                                             path_str),
394                                 );
395                             }
396                         },
397                         _ => {
398                             err.span_label(
399                                 span,
400                                 format!("did you mean `{} {{ /* fields */ }}`?",
401                                         path_str),
402                             );
403                         },
404                     }
405                 }
406             }
407             (Def::Union(..), _) |
408             (Def::Variant(..), _) |
409             (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
410                 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
411                                              path_str));
412             }
413             (Def::SelfTy(..), _) if ns == ValueNS => {
414                 err.span_label(span, fallback_label);
415                 err.note("can't use `Self` as a constructor, you must use the \
416                           implemented struct");
417             }
418             (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
419                 err.note("can't use a type alias as a constructor");
420             }
421             _ => return false,
422         }
423         true
424     }
425 }
426
427 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
428     /// Adds suggestions for a path that cannot be resolved.
429     pub(crate) fn make_path_suggestion(
430         &mut self,
431         span: Span,
432         mut path: Vec<Segment>,
433         parent_scope: &ParentScope<'b>,
434     ) -> Option<(Vec<Segment>, Option<String>)> {
435         debug!("make_path_suggestion: span={:?} path={:?}", span, path);
436
437         match (path.get(0), path.get(1)) {
438             // `{{root}}::ident::...` on both editions.
439             // On 2015 `{{root}}` is usually added implicitly.
440             (Some(fst), Some(snd)) if fst.ident.name == keywords::PathRoot.name() &&
441                                       !snd.ident.is_path_segment_keyword() => {}
442             // `ident::...` on 2018.
443             (Some(fst), _) if fst.ident.span.rust_2018() &&
444                               !fst.ident.is_path_segment_keyword() => {
445                 // Insert a placeholder that's later replaced by `self`/`super`/etc.
446                 path.insert(0, Segment::from_ident(keywords::Invalid.ident()));
447             }
448             _ => return None,
449         }
450
451         self.make_missing_self_suggestion(span, path.clone(), parent_scope)
452             .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
453             .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
454             .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
455     }
456
457     /// Suggest a missing `self::` if that resolves to an correct module.
458     ///
459     /// ```
460     ///    |
461     /// LL | use foo::Bar;
462     ///    |     ^^^ did you mean `self::foo`?
463     /// ```
464     fn make_missing_self_suggestion(
465         &mut self,
466         span: Span,
467         mut path: Vec<Segment>,
468         parent_scope: &ParentScope<'b>,
469     ) -> Option<(Vec<Segment>, Option<String>)> {
470         // Replace first ident with `self` and check if that is valid.
471         path[0].ident.name = keywords::SelfLower.name();
472         let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
473         debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
474         if let PathResult::Module(..) = result {
475             Some((path, None))
476         } else {
477             None
478         }
479     }
480
481     /// Suggests a missing `crate::` if that resolves to an correct module.
482     ///
483     /// ```
484     ///    |
485     /// LL | use foo::Bar;
486     ///    |     ^^^ did you mean `crate::foo`?
487     /// ```
488     fn make_missing_crate_suggestion(
489         &mut self,
490         span: Span,
491         mut path: Vec<Segment>,
492         parent_scope: &ParentScope<'b>,
493     ) -> Option<(Vec<Segment>, Option<String>)> {
494         // Replace first ident with `crate` and check if that is valid.
495         path[0].ident.name = keywords::Crate.name();
496         let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
497         debug!("make_missing_crate_suggestion:  path={:?} result={:?}", path, result);
498         if let PathResult::Module(..) = result {
499             Some((
500                 path,
501                 Some(
502                     "`use` statements changed in Rust 2018; read more at \
503                      <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
504                      clarity.html>".to_string()
505                 ),
506             ))
507         } else {
508             None
509         }
510     }
511
512     /// Suggests a missing `super::` if that resolves to an correct module.
513     ///
514     /// ```
515     ///    |
516     /// LL | use foo::Bar;
517     ///    |     ^^^ did you mean `super::foo`?
518     /// ```
519     fn make_missing_super_suggestion(
520         &mut self,
521         span: Span,
522         mut path: Vec<Segment>,
523         parent_scope: &ParentScope<'b>,
524     ) -> Option<(Vec<Segment>, Option<String>)> {
525         // Replace first ident with `crate` and check if that is valid.
526         path[0].ident.name = keywords::Super.name();
527         let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
528         debug!("make_missing_super_suggestion:  path={:?} result={:?}", path, result);
529         if let PathResult::Module(..) = result {
530             Some((path, None))
531         } else {
532             None
533         }
534     }
535
536     /// Suggests a missing external crate name if that resolves to an correct module.
537     ///
538     /// ```
539     ///    |
540     /// LL | use foobar::Baz;
541     ///    |     ^^^^^^ did you mean `baz::foobar`?
542     /// ```
543     ///
544     /// Used when importing a submodule of an external crate but missing that crate's
545     /// name as the first part of path.
546     fn make_external_crate_suggestion(
547         &mut self,
548         span: Span,
549         mut path: Vec<Segment>,
550         parent_scope: &ParentScope<'b>,
551     ) -> Option<(Vec<Segment>, Option<String>)> {
552         if path[1].ident.span.rust_2015() {
553             return None;
554         }
555
556         // Sort extern crate names in reverse order to get
557         // 1) some consistent ordering for emitted dignostics, and
558         // 2) `std` suggestions before `core` suggestions.
559         let mut extern_crate_names =
560             self.resolver.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
561         extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
562
563         for name in extern_crate_names.into_iter() {
564             // Replace first ident with a crate name and check if that is valid.
565             path[0].ident.name = name;
566             let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
567             debug!("make_external_crate_suggestion: name={:?} path={:?} result={:?}",
568                     name, path, result);
569             if let PathResult::Module(..) = result {
570                 return Some((path, None));
571             }
572         }
573
574         None
575     }
576 }