]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
Rollup merge of #41249 - GuillaumeGomez:rustdoc-render, r=steveklabnik,frewsxcv
[rust.git] / src / librustc / traits / error_reporting.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use super::{
12     FulfillmentError,
13     FulfillmentErrorCode,
14     MismatchedProjectionTypes,
15     Obligation,
16     ObligationCause,
17     ObligationCauseCode,
18     OutputTypeParameterMismatch,
19     TraitNotObjectSafe,
20     PredicateObligation,
21     SelectionContext,
22     SelectionError,
23     ObjectSafetyViolation,
24 };
25
26 use errors::DiagnosticBuilder;
27 use fmt_macros::{Parser, Piece, Position};
28 use hir::{intravisit, Local, Pat};
29 use hir::intravisit::{Visitor, NestedVisitorMap};
30 use hir::map::NodeExpr;
31 use hir::def_id::DefId;
32 use infer::{self, InferCtxt};
33 use infer::type_variable::TypeVariableOrigin;
34 use rustc::lint::builtin::EXTRA_REQUIREMENT_IN_IMPL;
35 use std::fmt;
36 use syntax::ast;
37 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
38 use ty::error::ExpectedFound;
39 use ty::fast_reject;
40 use ty::fold::TypeFolder;
41 use ty::subst::Subst;
42 use ty::SubtypePredicate;
43 use util::nodemap::{FxHashMap, FxHashSet};
44
45 use syntax_pos::{DUMMY_SP, Span};
46
47
48 #[derive(Debug, PartialEq, Eq, Hash)]
49 pub struct TraitErrorKey<'tcx> {
50     span: Span,
51     predicate: ty::Predicate<'tcx>
52 }
53
54 impl<'a, 'gcx, 'tcx> TraitErrorKey<'tcx> {
55     fn from_error(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
56                   e: &FulfillmentError<'tcx>) -> Self {
57         let predicate =
58             infcx.resolve_type_vars_if_possible(&e.obligation.predicate);
59         TraitErrorKey {
60             span: e.obligation.cause.span,
61             predicate: infcx.tcx.erase_regions(&predicate)
62         }
63     }
64 }
65
66 struct FindLocalByTypeVisitor<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
67     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
68     target_ty: &'a Ty<'tcx>,
69     found_pattern: Option<&'a Pat>,
70 }
71
72 impl<'a, 'gcx, 'tcx> FindLocalByTypeVisitor<'a, 'gcx, 'tcx> {
73     fn is_match(&self, ty: Ty<'tcx>) -> bool {
74         ty == *self.target_ty || match (&ty.sty, &self.target_ty.sty) {
75             (&ty::TyInfer(ty::TyVar(a_vid)), &ty::TyInfer(ty::TyVar(b_vid))) =>
76                 self.infcx.type_variables
77                           .borrow_mut()
78                           .sub_unified(a_vid, b_vid),
79
80             _ => false,
81         }
82     }
83 }
84
85 impl<'a, 'gcx, 'tcx> Visitor<'a> for FindLocalByTypeVisitor<'a, 'gcx, 'tcx> {
86     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'a> {
87         NestedVisitorMap::None
88     }
89
90     fn visit_local(&mut self, local: &'a Local) {
91         if let Some(&ty) = self.infcx.tables.borrow().node_types.get(&local.id) {
92             let ty = self.infcx.resolve_type_vars_if_possible(&ty);
93             let is_match = ty.walk().any(|t| self.is_match(t));
94
95             if is_match && self.found_pattern.is_none() {
96                 self.found_pattern = Some(&*local.pat);
97             }
98         }
99         intravisit::walk_local(self, local);
100     }
101 }
102
103 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
104     pub fn report_fulfillment_errors(&self, errors: &Vec<FulfillmentError<'tcx>>) {
105         for error in errors {
106             self.report_fulfillment_error(error);
107         }
108     }
109
110     fn report_fulfillment_error(&self,
111                                 error: &FulfillmentError<'tcx>) {
112         let error_key = TraitErrorKey::from_error(self, error);
113         debug!("report_fulfillment_errors({:?}) - key={:?}",
114                error, error_key);
115         if !self.reported_trait_errors.borrow_mut().insert(error_key) {
116             debug!("report_fulfillment_errors: skipping duplicate");
117             return;
118         }
119         match error.code {
120             FulfillmentErrorCode::CodeSelectionError(ref e) => {
121                 self.report_selection_error(&error.obligation, e);
122             }
123             FulfillmentErrorCode::CodeProjectionError(ref e) => {
124                 self.report_projection_error(&error.obligation, e);
125             }
126             FulfillmentErrorCode::CodeAmbiguity => {
127                 self.maybe_report_ambiguity(&error.obligation);
128             }
129             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
130                 self.report_mismatched_types(&error.obligation.cause,
131                                              expected_found.expected,
132                                              expected_found.found,
133                                              err.clone())
134                     .emit();
135             }
136         }
137     }
138
139     fn report_projection_error(&self,
140                                obligation: &PredicateObligation<'tcx>,
141                                error: &MismatchedProjectionTypes<'tcx>)
142     {
143         let predicate =
144             self.resolve_type_vars_if_possible(&obligation.predicate);
145
146         if predicate.references_error() {
147             return
148         }
149
150         self.probe(|_| {
151             let err_buf;
152             let mut err = &error.err;
153             let mut values = None;
154
155             // try to find the mismatched types to report the error with.
156             //
157             // this can fail if the problem was higher-ranked, in which
158             // cause I have no idea for a good error message.
159             if let ty::Predicate::Projection(ref data) = predicate {
160                 let mut selcx = SelectionContext::new(self);
161                 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
162                     obligation.cause.span,
163                     infer::LateBoundRegionConversionTime::HigherRankedType,
164                     data);
165                 let normalized = super::normalize_projection_type(
166                     &mut selcx,
167                     data.projection_ty,
168                     obligation.cause.clone(),
169                     0
170                 );
171                 if let Err(error) = self.eq_types(
172                     false, &obligation.cause,
173                     data.ty, normalized.value
174                 ) {
175                     values = Some(infer::ValuePairs::Types(ExpectedFound {
176                         expected: normalized.value,
177                         found: data.ty,
178                     }));
179                     err_buf = error;
180                     err = &err_buf;
181                 }
182             }
183
184             let mut diag = struct_span_err!(
185                 self.tcx.sess, obligation.cause.span, E0271,
186                 "type mismatch resolving `{}`", predicate
187             );
188             self.note_type_err(&mut diag, &obligation.cause, None, values, err);
189             self.note_obligation_cause(&mut diag, obligation);
190             diag.emit();
191         });
192     }
193
194     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
195         /// returns the fuzzy category of a given type, or None
196         /// if the type can be equated to any type.
197         fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
198             match t.sty {
199                 ty::TyBool => Some(0),
200                 ty::TyChar => Some(1),
201                 ty::TyStr => Some(2),
202                 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
203                 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
204                 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
205                 ty::TyArray(..) | ty::TySlice(..) => Some(6),
206                 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
207                 ty::TyDynamic(..) => Some(8),
208                 ty::TyClosure(..) => Some(9),
209                 ty::TyTuple(..) => Some(10),
210                 ty::TyProjection(..) => Some(11),
211                 ty::TyParam(..) => Some(12),
212                 ty::TyAnon(..) => Some(13),
213                 ty::TyNever => Some(14),
214                 ty::TyAdt(adt, ..) => match adt.adt_kind() {
215                     AdtKind::Struct => Some(15),
216                     AdtKind::Union => Some(16),
217                     AdtKind::Enum => Some(17),
218                 },
219                 ty::TyInfer(..) | ty::TyError => None
220             }
221         }
222
223         match (type_category(a), type_category(b)) {
224             (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
225                 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
226                 _ => cat_a == cat_b
227             },
228             // infer and error can be equated to all types
229             _ => true
230         }
231     }
232
233     fn impl_similar_to(&self,
234                        trait_ref: ty::PolyTraitRef<'tcx>,
235                        obligation: &PredicateObligation<'tcx>)
236                        -> Option<DefId>
237     {
238         let tcx = self.tcx;
239
240         let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
241         let trait_self_ty = trait_ref.self_ty();
242
243         let mut self_match_impls = vec![];
244         let mut fuzzy_match_impls = vec![];
245
246         self.tcx.lookup_trait_def(trait_ref.def_id)
247             .for_each_relevant_impl(self.tcx, trait_self_ty, |def_id| {
248                 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
249                 let impl_trait_ref = tcx
250                     .impl_trait_ref(def_id)
251                     .unwrap()
252                     .subst(tcx, impl_substs);
253
254                 let impl_self_ty = impl_trait_ref.self_ty();
255
256                 if let Ok(..) = self.can_equate(&trait_self_ty, &impl_self_ty) {
257                     self_match_impls.push(def_id);
258
259                     if trait_ref.substs.types().skip(1)
260                         .zip(impl_trait_ref.substs.types().skip(1))
261                         .all(|(u,v)| self.fuzzy_match_tys(u, v))
262                     {
263                         fuzzy_match_impls.push(def_id);
264                     }
265                 }
266             });
267
268         let impl_def_id = if self_match_impls.len() == 1 {
269             self_match_impls[0]
270         } else if fuzzy_match_impls.len() == 1 {
271             fuzzy_match_impls[0]
272         } else {
273             return None
274         };
275
276         if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
277             Some(impl_def_id)
278         } else {
279             None
280         }
281     }
282
283     fn on_unimplemented_note(&self,
284                              trait_ref: ty::PolyTraitRef<'tcx>,
285                              obligation: &PredicateObligation<'tcx>) -> Option<String> {
286         let def_id = self.impl_similar_to(trait_ref, obligation)
287             .unwrap_or(trait_ref.def_id());
288         let trait_ref = trait_ref.skip_binder();
289
290         let span = obligation.cause.span;
291         let mut report = None;
292         if let Some(item) = self.tcx
293             .get_attrs(def_id)
294             .into_iter()
295             .filter(|a| a.check_name("rustc_on_unimplemented"))
296             .next()
297         {
298             let err_sp = item.span.substitute_dummy(span);
299             let trait_str = self.tcx.item_path_str(trait_ref.def_id);
300             if let Some(istring) = item.value_str() {
301                 let istring = &*istring.as_str();
302                 let generics = self.tcx.item_generics(trait_ref.def_id);
303                 let generic_map = generics.types.iter().map(|param| {
304                     (param.name.as_str().to_string(),
305                         trait_ref.substs.type_for_def(param).to_string())
306                 }).collect::<FxHashMap<String, String>>();
307                 let parser = Parser::new(istring);
308                 let mut errored = false;
309                 let err: String = parser.filter_map(|p| {
310                     match p {
311                         Piece::String(s) => Some(s),
312                         Piece::NextArgument(a) => match a.position {
313                             Position::ArgumentNamed(s) => match generic_map.get(s) {
314                                 Some(val) => Some(val),
315                                 None => {
316                                     span_err!(self.tcx.sess, err_sp, E0272,
317                                                     "the #[rustc_on_unimplemented] \
318                                                             attribute on \
319                                                             trait definition for {} refers to \
320                                                             non-existent type parameter {}",
321                                                             trait_str, s);
322                                     errored = true;
323                                     None
324                                 }
325                             },
326                             _ => {
327                                 span_err!(self.tcx.sess, err_sp, E0273,
328                                             "the #[rustc_on_unimplemented] attribute \
329                                             on trait definition for {} must have \
330                                             named format arguments, eg \
331                                             `#[rustc_on_unimplemented = \
332                                             \"foo {{T}}\"]`", trait_str);
333                                 errored = true;
334                                 None
335                             }
336                         }
337                     }
338                 }).collect();
339                 // Report only if the format string checks out
340                 if !errored {
341                     report = Some(err);
342                 }
343             } else {
344                 span_err!(self.tcx.sess, err_sp, E0274,
345                                         "the #[rustc_on_unimplemented] attribute on \
346                                                     trait definition for {} must have a value, \
347                                                     eg `#[rustc_on_unimplemented = \"foo\"]`",
348                                                     trait_str);
349             }
350         }
351         report
352     }
353
354     fn find_similar_impl_candidates(&self,
355                                     trait_ref: ty::PolyTraitRef<'tcx>)
356                                     -> Vec<ty::TraitRef<'tcx>>
357     {
358         let simp = fast_reject::simplify_type(self.tcx,
359                                               trait_ref.skip_binder().self_ty(),
360                                               true);
361         let mut impl_candidates = Vec::new();
362         let trait_def = self.tcx.lookup_trait_def(trait_ref.def_id());
363
364         match simp {
365             Some(simp) => trait_def.for_each_impl(self.tcx, |def_id| {
366                 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
367                 let imp_simp = fast_reject::simplify_type(self.tcx,
368                                                           imp.self_ty(),
369                                                           true);
370                 if let Some(imp_simp) = imp_simp {
371                     if simp != imp_simp {
372                         return;
373                     }
374                 }
375                 impl_candidates.push(imp);
376             }),
377             None => trait_def.for_each_impl(self.tcx, |def_id| {
378                 impl_candidates.push(
379                     self.tcx.impl_trait_ref(def_id).unwrap());
380             })
381         };
382         impl_candidates
383     }
384
385     fn report_similar_impl_candidates(&self,
386                                       impl_candidates: Vec<ty::TraitRef<'tcx>>,
387                                       err: &mut DiagnosticBuilder)
388     {
389         if impl_candidates.is_empty() {
390             return;
391         }
392
393         let end = if impl_candidates.len() <= 5 {
394             impl_candidates.len()
395         } else {
396             4
397         };
398         err.help(&format!("the following implementations were found:{}{}",
399                           &impl_candidates[0..end].iter().map(|candidate| {
400                               format!("\n  {:?}", candidate)
401                           }).collect::<String>(),
402                           if impl_candidates.len() > 5 {
403                               format!("\nand {} others", impl_candidates.len() - 4)
404                           } else {
405                               "".to_owned()
406                           }
407                           ));
408     }
409
410     /// Reports that an overflow has occurred and halts compilation. We
411     /// halt compilation unconditionally because it is important that
412     /// overflows never be masked -- they basically represent computations
413     /// whose result could not be truly determined and thus we can't say
414     /// if the program type checks or not -- and they are unusual
415     /// occurrences in any case.
416     pub fn report_overflow_error<T>(&self,
417                                     obligation: &Obligation<'tcx, T>,
418                                     suggest_increasing_limit: bool) -> !
419         where T: fmt::Display + TypeFoldable<'tcx>
420     {
421         let predicate =
422             self.resolve_type_vars_if_possible(&obligation.predicate);
423         let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
424                                        "overflow evaluating the requirement `{}`",
425                                        predicate);
426
427         if suggest_increasing_limit {
428             self.suggest_new_overflow_limit(&mut err);
429         }
430
431         self.note_obligation_cause(&mut err, obligation);
432
433         err.emit();
434         self.tcx.sess.abort_if_errors();
435         bug!();
436     }
437
438     /// Reports that a cycle was detected which led to overflow and halts
439     /// compilation. This is equivalent to `report_overflow_error` except
440     /// that we can give a more helpful error message (and, in particular,
441     /// we do not suggest increasing the overflow limit, which is not
442     /// going to help).
443     pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
444         let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
445         assert!(cycle.len() > 0);
446
447         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
448
449         self.report_overflow_error(&cycle[0], false);
450     }
451
452     pub fn report_extra_impl_obligation(&self,
453                                         error_span: Span,
454                                         item_name: ast::Name,
455                                         _impl_item_def_id: DefId,
456                                         trait_item_def_id: DefId,
457                                         requirement: &fmt::Display,
458                                         lint_id: Option<ast::NodeId>) // (*)
459                                         -> DiagnosticBuilder<'tcx>
460     {
461         // (*) This parameter is temporary and used only for phasing
462         // in the bug fix to #18937. If it is `Some`, it has a kind of
463         // weird effect -- the diagnostic is reported as a lint, and
464         // the builder which is returned is marked as canceled.
465
466         let mut err =
467             struct_span_err!(self.tcx.sess,
468                              error_span,
469                              E0276,
470                              "impl has stricter requirements than trait");
471
472         if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
473             err.span_label(trait_item_span,
474                            &format!("definition of `{}` from trait", item_name));
475         }
476
477         err.span_label(
478             error_span,
479             &format!("impl has extra requirement {}", requirement));
480
481         if let Some(node_id) = lint_id {
482             self.tcx.sess.add_lint_diagnostic(EXTRA_REQUIREMENT_IN_IMPL,
483                                               node_id,
484                                               (*err).clone());
485             err.cancel();
486         }
487
488         err
489     }
490
491
492     /// Get the parent trait chain start
493     fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
494         match code {
495             &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
496                 let parent_trait_ref = self.resolve_type_vars_if_possible(
497                     &data.parent_trait_ref);
498                 match self.get_parent_trait_ref(&data.parent_code) {
499                     Some(t) => Some(t),
500                     None => Some(format!("{}", parent_trait_ref.0.self_ty())),
501                 }
502             }
503             _ => None,
504         }
505     }
506
507     pub fn report_selection_error(&self,
508                                   obligation: &PredicateObligation<'tcx>,
509                                   error: &SelectionError<'tcx>)
510     {
511         let span = obligation.cause.span;
512
513         let mut err = match *error {
514             SelectionError::Unimplemented => {
515                 if let ObligationCauseCode::CompareImplMethodObligation {
516                     item_name, impl_item_def_id, trait_item_def_id, lint_id
517                 } = obligation.cause.code {
518                     self.report_extra_impl_obligation(
519                         span,
520                         item_name,
521                         impl_item_def_id,
522                         trait_item_def_id,
523                         &format!("`{}`", obligation.predicate),
524                         lint_id)
525                         .emit();
526                     return;
527                 }
528                 match obligation.predicate {
529                     ty::Predicate::Trait(ref trait_predicate) => {
530                         let trait_predicate =
531                             self.resolve_type_vars_if_possible(trait_predicate);
532
533                         if self.tcx.sess.has_errors() && trait_predicate.references_error() {
534                             return;
535                         }
536                         let trait_ref = trait_predicate.to_poly_trait_ref();
537                         let (post_message, pre_message) =
538                             self.get_parent_trait_ref(&obligation.cause.code)
539                                 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
540                                 .unwrap_or((String::new(), String::new()));
541                         let mut err = struct_span_err!(
542                             self.tcx.sess,
543                             span,
544                             E0277,
545                             "the trait bound `{}` is not satisfied{}",
546                             trait_ref.to_predicate(),
547                             post_message);
548
549                         // Try to report a help message
550                         if !trait_ref.has_infer_types() &&
551                             self.predicate_can_apply(trait_ref) {
552                             // If a where-clause may be useful, remind the
553                             // user that they can add it.
554                             //
555                             // don't display an on-unimplemented note, as
556                             // these notes will often be of the form
557                             //     "the type `T` can't be frobnicated"
558                             // which is somewhat confusing.
559                             err.help(&format!("consider adding a `where {}` bound",
560                                                 trait_ref.to_predicate()));
561                         } else if let Some(s) = self.on_unimplemented_note(trait_ref, obligation) {
562                             // If it has a custom "#[rustc_on_unimplemented]"
563                             // error message, let's display it!
564                             err.note(&s);
565                         } else {
566                             // Can't show anything else useful, try to find similar impls.
567                             let impl_candidates = self.find_similar_impl_candidates(trait_ref);
568                             self.report_similar_impl_candidates(impl_candidates, &mut err);
569                         }
570
571                         err.span_label(span,
572                                        &format!("{}the trait `{}` is not implemented for `{}`",
573                                                 pre_message,
574                                                 trait_ref,
575                                                 trait_ref.self_ty()));
576                         err
577                     }
578
579                     ty::Predicate::Subtype(ref predicate) => {
580                         // Errors for Subtype predicates show up as
581                         // `FulfillmentErrorCode::CodeSubtypeError`,
582                         // not selection error.
583                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
584                     }
585
586                     ty::Predicate::Equate(ref predicate) => {
587                         let predicate = self.resolve_type_vars_if_possible(predicate);
588                         let err = self.equality_predicate(&obligation.cause,
589                                                             &predicate).err().unwrap();
590                         struct_span_err!(self.tcx.sess, span, E0278,
591                             "the requirement `{}` is not satisfied (`{}`)",
592                             predicate, err)
593                     }
594
595                     ty::Predicate::RegionOutlives(ref predicate) => {
596                         let predicate = self.resolve_type_vars_if_possible(predicate);
597                         let err = self.region_outlives_predicate(&obligation.cause,
598                                                                     &predicate).err().unwrap();
599                         struct_span_err!(self.tcx.sess, span, E0279,
600                             "the requirement `{}` is not satisfied (`{}`)",
601                             predicate, err)
602                     }
603
604                     ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
605                         let predicate =
606                             self.resolve_type_vars_if_possible(&obligation.predicate);
607                         struct_span_err!(self.tcx.sess, span, E0280,
608                             "the requirement `{}` is not satisfied",
609                             predicate)
610                     }
611
612                     ty::Predicate::ObjectSafe(trait_def_id) => {
613                         let violations = self.tcx.object_safety_violations(trait_def_id);
614                         self.tcx.report_object_safety_error(span,
615                                                             trait_def_id,
616                                                             violations)
617                     }
618
619                     ty::Predicate::ClosureKind(closure_def_id, kind) => {
620                         let found_kind = self.closure_kind(closure_def_id).unwrap();
621                         let closure_span = self.tcx.hir.span_if_local(closure_def_id).unwrap();
622                         let mut err = struct_span_err!(
623                             self.tcx.sess, closure_span, E0525,
624                             "expected a closure that implements the `{}` trait, \
625                                 but this closure only implements `{}`",
626                             kind,
627                             found_kind);
628                         err.span_note(
629                             obligation.cause.span,
630                             &format!("the requirement to implement \
631                                         `{}` derives from here", kind));
632                         err.emit();
633                         return;
634                     }
635
636                     ty::Predicate::WellFormed(ty) => {
637                         // WF predicates cannot themselves make
638                         // errors. They can only block due to
639                         // ambiguity; otherwise, they always
640                         // degenerate into other obligations
641                         // (which may fail).
642                         span_bug!(span, "WF predicate not satisfied for {:?}", ty);
643                     }
644                 }
645             }
646
647             OutputTypeParameterMismatch(ref expected_trait_ref, ref actual_trait_ref, ref e) => {
648                 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
649                 let actual_trait_ref = self.resolve_type_vars_if_possible(&*actual_trait_ref);
650                 if actual_trait_ref.self_ty().references_error() {
651                     return;
652                 }
653                 struct_span_err!(self.tcx.sess, span, E0281,
654                     "type mismatch: the type `{}` implements the trait `{}`, \
655                      but the trait `{}` is required ({})",
656                     expected_trait_ref.self_ty(),
657                     expected_trait_ref,
658                     actual_trait_ref,
659                     e)
660             }
661
662             TraitNotObjectSafe(did) => {
663                 let violations = self.tcx.object_safety_violations(did);
664                 self.tcx.report_object_safety_error(span, did,
665                                                     violations)
666             }
667         };
668         self.note_obligation_cause(&mut err, obligation);
669         err.emit();
670     }
671 }
672
673 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
674     pub fn recursive_type_with_infinite_size_error(self,
675                                                    type_def_id: DefId)
676                                                    -> DiagnosticBuilder<'tcx>
677     {
678         assert!(type_def_id.is_local());
679         let span = self.hir.span_if_local(type_def_id).unwrap();
680         let mut err = struct_span_err!(self.sess, span, E0072,
681                                        "recursive type `{}` has infinite size",
682                                        self.item_path_str(type_def_id));
683         err.span_label(span, &format!("recursive type has infinite size"));
684         err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
685                            at some point to make `{}` representable",
686                           self.item_path_str(type_def_id)));
687         err
688     }
689
690     pub fn report_object_safety_error(self,
691                                       span: Span,
692                                       trait_def_id: DefId,
693                                       violations: Vec<ObjectSafetyViolation>)
694                                       -> DiagnosticBuilder<'tcx>
695     {
696         let trait_str = self.item_path_str(trait_def_id);
697         let mut err = struct_span_err!(
698             self.sess, span, E0038,
699             "the trait `{}` cannot be made into an object",
700             trait_str);
701         err.span_label(span, &format!(
702             "the trait `{}` cannot be made into an object", trait_str
703         ));
704
705         let mut reported_violations = FxHashSet();
706         for violation in violations {
707             if !reported_violations.insert(violation.clone()) {
708                 continue;
709             }
710             err.note(&violation.error_msg());
711         }
712         err
713     }
714 }
715
716 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
717     fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>) {
718         // Unable to successfully determine, probably means
719         // insufficient type information, but could mean
720         // ambiguous impls. The latter *ought* to be a
721         // coherence violation, so we don't report it here.
722
723         let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
724
725         debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
726                predicate,
727                obligation);
728
729         // Ambiguity errors are often caused as fallout from earlier
730         // errors. So just ignore them if this infcx is tainted.
731         if self.is_tainted_by_errors() {
732             return;
733         }
734
735         match predicate {
736             ty::Predicate::Trait(ref data) => {
737                 let trait_ref = data.to_poly_trait_ref();
738                 let self_ty = trait_ref.self_ty();
739                 if predicate.references_error() {
740                     return;
741                 }
742                 // Typically, this ambiguity should only happen if
743                 // there are unresolved type inference variables
744                 // (otherwise it would suggest a coherence
745                 // failure). But given #21974 that is not necessarily
746                 // the case -- we can have multiple where clauses that
747                 // are only distinguished by a region, which results
748                 // in an ambiguity even when all types are fully
749                 // known, since we don't dispatch based on region
750                 // relationships.
751
752                 // This is kind of a hack: it frequently happens that some earlier
753                 // error prevents types from being fully inferred, and then we get
754                 // a bunch of uninteresting errors saying something like "<generic
755                 // #0> doesn't implement Sized".  It may even be true that we
756                 // could just skip over all checks where the self-ty is an
757                 // inference variable, but I was afraid that there might be an
758                 // inference variable created, registered as an obligation, and
759                 // then never forced by writeback, and hence by skipping here we'd
760                 // be ignoring the fact that we don't KNOW the type works
761                 // out. Though even that would probably be harmless, given that
762                 // we're only talking about builtin traits, which are known to be
763                 // inhabited. But in any case I just threw in this check for
764                 // has_errors() to be sure that compilation isn't happening
765                 // anyway. In that case, why inundate the user.
766                 if !self.tcx.sess.has_errors() {
767                     if
768                         self.tcx.lang_items.sized_trait()
769                         .map_or(false, |sized_id| sized_id == trait_ref.def_id())
770                     {
771                         self.need_type_info(obligation, self_ty);
772                     } else {
773                         let mut err = struct_span_err!(self.tcx.sess,
774                                                         obligation.cause.span, E0283,
775                                                         "type annotations required: \
776                                                         cannot resolve `{}`",
777                                                         predicate);
778                         self.note_obligation_cause(&mut err, obligation);
779                         err.emit();
780                     }
781                 }
782             }
783
784             ty::Predicate::WellFormed(ty) => {
785                 // Same hacky approach as above to avoid deluging user
786                 // with error messages.
787                 if !ty.references_error() && !self.tcx.sess.has_errors() {
788                     self.need_type_info(obligation, ty);
789                 }
790             }
791
792             ty::Predicate::Subtype(ref data) => {
793                 if data.references_error() || self.tcx.sess.has_errors() {
794                     // no need to overload user in such cases
795                 } else {
796                     let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
797                     // both must be type variables, or the other would've been instantiated
798                     assert!(a.is_ty_var() && b.is_ty_var());
799                     self.need_type_info(obligation, a);
800                 }
801             }
802
803             _ => {
804                 if !self.tcx.sess.has_errors() {
805                     let mut err = struct_span_err!(self.tcx.sess,
806                                                    obligation.cause.span, E0284,
807                                                    "type annotations required: \
808                                                     cannot resolve `{}`",
809                                                    predicate);
810                     self.note_obligation_cause(&mut err, obligation);
811                     err.emit();
812                 }
813             }
814         }
815     }
816
817     /// Returns whether the trait predicate may apply for *some* assignment
818     /// to the type parameters.
819     fn predicate_can_apply(&self, pred: ty::PolyTraitRef<'tcx>) -> bool {
820         struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
821             infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
822             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
823         }
824
825         impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
826             fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
827
828             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
829                 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
830                     let infcx = self.infcx;
831                     self.var_map.entry(ty).or_insert_with(||
832                         infcx.next_ty_var(
833                             TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
834                 } else {
835                     ty.super_fold_with(self)
836                 }
837             }
838         }
839
840         self.probe(|_| {
841             let mut selcx = SelectionContext::new(self);
842
843             let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
844                 infcx: self,
845                 var_map: FxHashMap()
846             });
847
848             let cleaned_pred = super::project::normalize(
849                 &mut selcx,
850                 ObligationCause::dummy(),
851                 &cleaned_pred
852             ).value;
853
854             let obligation = Obligation::new(
855                 ObligationCause::dummy(),
856                 cleaned_pred.to_predicate()
857             );
858
859             selcx.evaluate_obligation(&obligation)
860         })
861     }
862
863     fn extract_type_name(&self, ty: &'a Ty<'tcx>) -> String {
864         if let ty::TyInfer(ty::TyVar(ty_vid)) = (*ty).sty {
865             let ty_vars = self.type_variables.borrow();
866             if let TypeVariableOrigin::TypeParameterDefinition(_, name) =
867                 *ty_vars.var_origin(ty_vid) {
868                 name.to_string()
869             } else {
870                 ty.to_string()
871             }
872         } else {
873             ty.to_string()
874         }
875     }
876
877     fn need_type_info(&self, obligation: &PredicateObligation<'tcx>, ty: Ty<'tcx>) {
878         let ty = self.resolve_type_vars_if_possible(&ty);
879         let name = self.extract_type_name(&ty);
880         let ref cause = obligation.cause;
881
882         let mut err = struct_span_err!(self.tcx.sess,
883                                        cause.span,
884                                        E0282,
885                                        "type annotations needed");
886
887         err.span_label(cause.span, &format!("cannot infer type for `{}`", name));
888
889         let mut local_visitor = FindLocalByTypeVisitor {
890             infcx: &self,
891             target_ty: &ty,
892             found_pattern: None,
893         };
894
895         // #40294: cause.body_id can also be a fn declaration.
896         // Currently, if it's anything other than NodeExpr, we just ignore it
897         match self.tcx.hir.find(cause.body_id) {
898             Some(NodeExpr(expr)) => local_visitor.visit_expr(expr),
899             _ => ()
900         }
901
902         if let Some(pattern) = local_visitor.found_pattern {
903             let pattern_span = pattern.span;
904             if let Some(simple_name) = pattern.simple_name() {
905                 err.span_label(pattern_span,
906                                &format!("consider giving `{}` a type",
907                                         simple_name));
908             } else {
909                 err.span_label(pattern_span, &format!("consider giving a type to pattern"));
910             }
911         }
912
913         err.emit();
914     }
915
916     fn note_obligation_cause<T>(&self,
917                                 err: &mut DiagnosticBuilder,
918                                 obligation: &Obligation<'tcx, T>)
919         where T: fmt::Display
920     {
921         self.note_obligation_cause_code(err,
922                                         &obligation.predicate,
923                                         &obligation.cause.code);
924     }
925
926     fn note_obligation_cause_code<T>(&self,
927                                      err: &mut DiagnosticBuilder,
928                                      predicate: &T,
929                                      cause_code: &ObligationCauseCode<'tcx>)
930         where T: fmt::Display
931     {
932         let tcx = self.tcx;
933         match *cause_code {
934             ObligationCauseCode::ExprAssignable |
935             ObligationCauseCode::MatchExpressionArm { .. } |
936             ObligationCauseCode::IfExpression |
937             ObligationCauseCode::IfExpressionWithNoElse |
938             ObligationCauseCode::EquatePredicate |
939             ObligationCauseCode::MainFunctionType |
940             ObligationCauseCode::StartFunctionType |
941             ObligationCauseCode::IntrinsicType |
942             ObligationCauseCode::MethodReceiver |
943             ObligationCauseCode::ReturnNoExpression |
944             ObligationCauseCode::MiscObligation => {
945             }
946             ObligationCauseCode::SliceOrArrayElem => {
947                 err.note("slice and array elements must have `Sized` type");
948             }
949             ObligationCauseCode::TupleElem => {
950                 err.note("tuple elements must have `Sized` type");
951             }
952             ObligationCauseCode::ProjectionWf(data) => {
953                 err.note(&format!("required so that the projection `{}` is well-formed",
954                                   data));
955             }
956             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
957                 err.note(&format!("required so that reference `{}` does not outlive its referent",
958                                   ref_ty));
959             }
960             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
961                 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
962                                    is satisfied",
963                                   region, object_ty));
964             }
965             ObligationCauseCode::ItemObligation(item_def_id) => {
966                 let item_name = tcx.item_path_str(item_def_id);
967                 err.note(&format!("required by `{}`", item_name));
968             }
969             ObligationCauseCode::ObjectCastObligation(object_ty) => {
970                 err.note(&format!("required for the cast to the object type `{}`",
971                                   self.ty_to_string(object_ty)));
972             }
973             ObligationCauseCode::RepeatVec => {
974                 err.note("the `Copy` trait is required because the \
975                           repeated element will be copied");
976             }
977             ObligationCauseCode::VariableType(_) => {
978                 err.note("all local variables must have a statically known size");
979             }
980             ObligationCauseCode::ReturnType => {
981                 err.note("the return type of a function must have a \
982                           statically known size");
983             }
984             ObligationCauseCode::AssignmentLhsSized => {
985                 err.note("the left-hand-side of an assignment must have a statically known size");
986             }
987             ObligationCauseCode::StructInitializerSized => {
988                 err.note("structs must have a statically known size to be initialized");
989             }
990             ObligationCauseCode::FieldSized => {
991                 err.note("only the last field of a struct may have a dynamically sized type");
992             }
993             ObligationCauseCode::ConstSized => {
994                 err.note("constant expressions must have a statically known size");
995             }
996             ObligationCauseCode::SharedStatic => {
997                 err.note("shared static variables must have a type that implements `Sync`");
998             }
999             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1000                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1001                 err.note(&format!("required because it appears within the type `{}`",
1002                                   parent_trait_ref.0.self_ty()));
1003                 let parent_predicate = parent_trait_ref.to_predicate();
1004                 self.note_obligation_cause_code(err,
1005                                                 &parent_predicate,
1006                                                 &data.parent_code);
1007             }
1008             ObligationCauseCode::ImplDerivedObligation(ref data) => {
1009                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1010                 err.note(
1011                     &format!("required because of the requirements on the impl of `{}` for `{}`",
1012                              parent_trait_ref,
1013                              parent_trait_ref.0.self_ty()));
1014                 let parent_predicate = parent_trait_ref.to_predicate();
1015                 self.note_obligation_cause_code(err,
1016                                                 &parent_predicate,
1017                                                 &data.parent_code);
1018             }
1019             ObligationCauseCode::CompareImplMethodObligation { .. } => {
1020                 err.note(
1021                     &format!("the requirement `{}` appears on the impl method \
1022                               but not on the corresponding trait method",
1023                              predicate));
1024             }
1025         }
1026     }
1027
1028     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1029         let current_limit = self.tcx.sess.recursion_limit.get();
1030         let suggested_limit = current_limit * 2;
1031         err.help(&format!(
1032                           "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1033                           suggested_limit));
1034     }
1035 }
1036