]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
e5559b7012dc978145a233602ed09f59f6dbd79b
[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     OnUnimplementedDirective,
19     OnUnimplementedNote,
20     OutputTypeParameterMismatch,
21     TraitNotObjectSafe,
22     ConstEvalFailure,
23     PredicateObligation,
24     SelectionContext,
25     SelectionError,
26     ObjectSafetyViolation,
27     Overflow,
28 };
29
30 use errors::{Applicability, DiagnosticBuilder};
31 use hir;
32 use hir::def_id::DefId;
33 use infer::{self, InferCtxt};
34 use infer::type_variable::TypeVariableOrigin;
35 use std::fmt;
36 use syntax::ast;
37 use session::DiagnosticMessageId;
38 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
39 use ty::GenericParamDefKind;
40 use ty::error::ExpectedFound;
41 use ty::fast_reject;
42 use ty::fold::TypeFolder;
43 use ty::subst::Subst;
44 use ty::SubtypePredicate;
45 use util::nodemap::{FxHashMap, FxHashSet};
46
47 use syntax_pos::{DUMMY_SP, Span};
48
49 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
50     pub fn report_fulfillment_errors(&self,
51                                      errors: &Vec<FulfillmentError<'tcx>>,
52                                      body_id: Option<hir::BodyId>,
53                                      fallback_has_occurred: bool) {
54         #[derive(Debug)]
55         struct ErrorDescriptor<'tcx> {
56             predicate: ty::Predicate<'tcx>,
57             index: Option<usize>, // None if this is an old error
58         }
59
60         let mut error_map : FxHashMap<_, _> =
61             self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
62                 (span, predicates.iter().map(|predicate| ErrorDescriptor {
63                     predicate: predicate.clone(),
64                     index: None
65                 }).collect())
66             }).collect();
67
68         for (index, error) in errors.iter().enumerate() {
69             error_map.entry(error.obligation.cause.span).or_insert(Vec::new()).push(
70                 ErrorDescriptor {
71                     predicate: error.obligation.predicate.clone(),
72                     index: Some(index)
73                 });
74
75             self.reported_trait_errors.borrow_mut()
76                 .entry(error.obligation.cause.span).or_insert(Vec::new())
77                 .push(error.obligation.predicate.clone());
78         }
79
80         // We do this in 2 passes because we want to display errors in order, tho
81         // maybe it *is* better to sort errors by span or something.
82         let mut is_suppressed: Vec<bool> = errors.iter().map(|_| false).collect();
83         for (_, error_set) in error_map.iter() {
84             // We want to suppress "duplicate" errors with the same span.
85             for error in error_set {
86                 if let Some(index) = error.index {
87                     // Suppress errors that are either:
88                     // 1) strictly implied by another error.
89                     // 2) implied by an error with a smaller index.
90                     for error2 in error_set {
91                         if error2.index.map_or(false, |index2| is_suppressed[index2]) {
92                             // Avoid errors being suppressed by already-suppressed
93                             // errors, to prevent all errors from being suppressed
94                             // at once.
95                             continue
96                         }
97
98                         if self.error_implies(&error2.predicate, &error.predicate) &&
99                             !(error2.index >= error.index &&
100                               self.error_implies(&error.predicate, &error2.predicate))
101                         {
102                             info!("skipping {:?} (implied by {:?})", error, error2);
103                             is_suppressed[index] = true;
104                             break
105                         }
106                     }
107                 }
108             }
109         }
110
111         for (error, suppressed) in errors.iter().zip(is_suppressed) {
112             if !suppressed {
113                 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
114             }
115         }
116     }
117
118     // returns if `cond` not occurring implies that `error` does not occur - i.e. that
119     // `error` occurring implies that `cond` occurs.
120     fn error_implies(&self,
121                      cond: &ty::Predicate<'tcx>,
122                      error: &ty::Predicate<'tcx>)
123                      -> bool
124     {
125         if cond == error {
126             return true
127         }
128
129         let (cond, error) = match (cond, error) {
130             (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
131                 => (cond, error),
132             _ => {
133                 // FIXME: make this work in other cases too.
134                 return false
135             }
136         };
137
138         for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
139             if let ty::Predicate::Trait(implication) = implication {
140                 let error = error.to_poly_trait_ref();
141                 let implication = implication.to_poly_trait_ref();
142                 // FIXME: I'm just not taking associated types at all here.
143                 // Eventually I'll need to implement param-env-aware
144                 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
145                 let param_env = ty::ParamEnv::empty();
146                 if let Ok(_) = self.can_sub(param_env, error, implication) {
147                     debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
148                     return true
149                 }
150             }
151         }
152
153         false
154     }
155
156     fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
157                                 body_id: Option<hir::BodyId>,
158                                 fallback_has_occurred: bool) {
159         debug!("report_fulfillment_errors({:?})", error);
160         match error.code {
161             FulfillmentErrorCode::CodeSelectionError(ref e) => {
162                 self.report_selection_error(&error.obligation, e, fallback_has_occurred);
163             }
164             FulfillmentErrorCode::CodeProjectionError(ref e) => {
165                 self.report_projection_error(&error.obligation, e);
166             }
167             FulfillmentErrorCode::CodeAmbiguity => {
168                 self.maybe_report_ambiguity(&error.obligation, body_id);
169             }
170             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
171                 self.report_mismatched_types(&error.obligation.cause,
172                                              expected_found.expected,
173                                              expected_found.found,
174                                              err.clone())
175                     .emit();
176             }
177         }
178     }
179
180     fn report_projection_error(&self,
181                                obligation: &PredicateObligation<'tcx>,
182                                error: &MismatchedProjectionTypes<'tcx>)
183     {
184         let predicate =
185             self.resolve_type_vars_if_possible(&obligation.predicate);
186
187         if predicate.references_error() {
188             return
189         }
190
191         self.probe(|_| {
192             let err_buf;
193             let mut err = &error.err;
194             let mut values = None;
195
196             // try to find the mismatched types to report the error with.
197             //
198             // this can fail if the problem was higher-ranked, in which
199             // cause I have no idea for a good error message.
200             if let ty::Predicate::Projection(ref data) = predicate {
201                 let mut selcx = SelectionContext::new(self);
202                 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
203                     obligation.cause.span,
204                     infer::LateBoundRegionConversionTime::HigherRankedType,
205                     data);
206                 let mut obligations = vec![];
207                 let normalized_ty = super::normalize_projection_type(
208                     &mut selcx,
209                     obligation.param_env,
210                     data.projection_ty,
211                     obligation.cause.clone(),
212                     0,
213                     &mut obligations
214                 );
215                 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
216                                         .eq(normalized_ty, data.ty) {
217                     values = Some(infer::ValuePairs::Types(ExpectedFound {
218                         expected: normalized_ty,
219                         found: data.ty,
220                     }));
221                     err_buf = error;
222                     err = &err_buf;
223                 }
224             }
225
226             let msg = format!("type mismatch resolving `{}`", predicate);
227             let error_id = (DiagnosticMessageId::ErrorId(271),
228                             Some(obligation.cause.span), msg.clone());
229             let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
230             if fresh {
231                 let mut diag = struct_span_err!(
232                     self.tcx.sess, obligation.cause.span, E0271,
233                     "type mismatch resolving `{}`", predicate
234                 );
235                 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
236                 self.note_obligation_cause(&mut diag, obligation);
237                 diag.emit();
238             }
239         });
240     }
241
242     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
243         /// returns the fuzzy category of a given type, or None
244         /// if the type can be equated to any type.
245         fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
246             match t.sty {
247                 ty::TyBool => Some(0),
248                 ty::TyChar => Some(1),
249                 ty::TyStr => Some(2),
250                 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
251                 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
252                 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
253                 ty::TyArray(..) | ty::TySlice(..) => Some(6),
254                 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
255                 ty::TyDynamic(..) => Some(8),
256                 ty::TyClosure(..) => Some(9),
257                 ty::TyTuple(..) => Some(10),
258                 ty::TyProjection(..) => Some(11),
259                 ty::TyParam(..) => Some(12),
260                 ty::TyAnon(..) => Some(13),
261                 ty::TyNever => Some(14),
262                 ty::TyAdt(adt, ..) => match adt.adt_kind() {
263                     AdtKind::Struct => Some(15),
264                     AdtKind::Union => Some(16),
265                     AdtKind::Enum => Some(17),
266                 },
267                 ty::TyGenerator(..) => Some(18),
268                 ty::TyForeign(..) => Some(19),
269                 ty::TyGeneratorWitness(..) => Some(20),
270                 ty::TyInfer(..) | ty::TyError => None
271             }
272         }
273
274         match (type_category(a), type_category(b)) {
275             (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
276                 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
277                 _ => cat_a == cat_b
278             },
279             // infer and error can be equated to all types
280             _ => true
281         }
282     }
283
284     fn impl_similar_to(&self,
285                        trait_ref: ty::PolyTraitRef<'tcx>,
286                        obligation: &PredicateObligation<'tcx>)
287                        -> Option<DefId>
288     {
289         let tcx = self.tcx;
290         let param_env = obligation.param_env;
291         let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
292         let trait_self_ty = trait_ref.self_ty();
293
294         let mut self_match_impls = vec![];
295         let mut fuzzy_match_impls = vec![];
296
297         self.tcx.for_each_relevant_impl(
298             trait_ref.def_id, trait_self_ty, |def_id| {
299                 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
300                 let impl_trait_ref = tcx
301                     .impl_trait_ref(def_id)
302                     .unwrap()
303                     .subst(tcx, impl_substs);
304
305                 let impl_self_ty = impl_trait_ref.self_ty();
306
307                 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
308                     self_match_impls.push(def_id);
309
310                     if trait_ref.substs.types().skip(1)
311                         .zip(impl_trait_ref.substs.types().skip(1))
312                         .all(|(u,v)| self.fuzzy_match_tys(u, v))
313                     {
314                         fuzzy_match_impls.push(def_id);
315                     }
316                 }
317             });
318
319         let impl_def_id = if self_match_impls.len() == 1 {
320             self_match_impls[0]
321         } else if fuzzy_match_impls.len() == 1 {
322             fuzzy_match_impls[0]
323         } else {
324             return None
325         };
326
327         if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
328             Some(impl_def_id)
329         } else {
330             None
331         }
332     }
333
334     fn on_unimplemented_note(
335         &self,
336         trait_ref: ty::PolyTraitRef<'tcx>,
337         obligation: &PredicateObligation<'tcx>) ->
338         OnUnimplementedNote
339     {
340         let def_id = self.impl_similar_to(trait_ref, obligation)
341             .unwrap_or(trait_ref.def_id());
342         let trait_ref = *trait_ref.skip_binder();
343
344         let mut flags = vec![];
345         match obligation.cause.code {
346             ObligationCauseCode::BuiltinDerivedObligation(..) |
347             ObligationCauseCode::ImplDerivedObligation(..) => {}
348             _ => {
349                 // this is a "direct", user-specified, rather than derived,
350                 // obligation.
351                 flags.push(("direct".to_string(), None));
352             }
353         }
354
355         if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
356             // FIXME: maybe also have some way of handling methods
357             // from other traits? That would require name resolution,
358             // which we might want to be some sort of hygienic.
359             //
360             // Currently I'm leaving it for what I need for `try`.
361             if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
362                 let method = self.tcx.item_name(item);
363                 flags.push(("from_method".to_string(), None));
364                 flags.push(("from_method".to_string(), Some(method.to_string())));
365             }
366         }
367
368         if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
369             flags.push(("from_desugaring".to_string(), None));
370             flags.push(("from_desugaring".to_string(), Some(k.name().to_string())));
371         }
372         let generics = self.tcx.generics_of(def_id);
373         let self_ty = trait_ref.self_ty();
374         // This is also included through the generics list as `Self`,
375         // but the parser won't allow you to use it
376         flags.push(("_Self".to_string(), Some(self_ty.to_string())));
377         if let Some(def) = self_ty.ty_adt_def() {
378             // We also want to be able to select self's original
379             // signature with no type arguments resolved
380             flags.push(("_Self".to_string(), Some(self.tcx.type_of(def.did).to_string())));
381         }
382
383         for param in generics.params.iter() {
384             let value = match param.kind {
385                 GenericParamDefKind::Type {..} => {
386                     trait_ref.substs[param.index as usize].to_string()
387                 },
388                 GenericParamDefKind::Lifetime => continue,
389             };
390             let name = param.name.to_string();
391             flags.push((name, Some(value)));
392         }
393
394         if let Some(true) = self_ty.ty_to_def_id().map(|def_id| def_id.is_local()) {
395             flags.push(("crate_local".to_string(), None));
396         }
397
398         if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
399             self.tcx, trait_ref.def_id, def_id
400         ) {
401             command.evaluate(self.tcx, trait_ref, &flags[..])
402         } else {
403             OnUnimplementedNote::empty()
404         }
405     }
406
407     fn find_similar_impl_candidates(&self,
408                                     trait_ref: ty::PolyTraitRef<'tcx>)
409                                     -> Vec<ty::TraitRef<'tcx>>
410     {
411         let simp = fast_reject::simplify_type(self.tcx,
412                                               trait_ref.skip_binder().self_ty(),
413                                               true);
414         let mut impl_candidates = Vec::new();
415
416         match simp {
417             Some(simp) => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
418                 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
419                 let imp_simp = fast_reject::simplify_type(self.tcx,
420                                                           imp.self_ty(),
421                                                           true);
422                 if let Some(imp_simp) = imp_simp {
423                     if simp != imp_simp {
424                         return;
425                     }
426                 }
427                 impl_candidates.push(imp);
428             }),
429             None => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
430                 impl_candidates.push(
431                     self.tcx.impl_trait_ref(def_id).unwrap());
432             })
433         };
434         impl_candidates
435     }
436
437     fn report_similar_impl_candidates(&self,
438                                       impl_candidates: Vec<ty::TraitRef<'tcx>>,
439                                       err: &mut DiagnosticBuilder)
440     {
441         if impl_candidates.is_empty() {
442             return;
443         }
444
445         let end = if impl_candidates.len() <= 5 {
446             impl_candidates.len()
447         } else {
448             4
449         };
450
451         let normalize = |candidate| self.tcx.global_tcx().infer_ctxt().enter(|ref infcx| {
452             let normalized = infcx
453                 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
454                 .normalize(candidate)
455                 .ok();
456             match normalized {
457                 Some(normalized) => format!("\n  {:?}", normalized.value),
458                 None => format!("\n  {:?}", candidate),
459             }
460         });
461
462         err.help(&format!("the following implementations were found:{}{}",
463                           &impl_candidates[0..end].iter().map(normalize).collect::<String>(),
464                           if impl_candidates.len() > 5 {
465                               format!("\nand {} others", impl_candidates.len() - 4)
466                           } else {
467                               "".to_owned()
468                           }
469                           ));
470     }
471
472     /// Reports that an overflow has occurred and halts compilation. We
473     /// halt compilation unconditionally because it is important that
474     /// overflows never be masked -- they basically represent computations
475     /// whose result could not be truly determined and thus we can't say
476     /// if the program type checks or not -- and they are unusual
477     /// occurrences in any case.
478     pub fn report_overflow_error<T>(&self,
479                                     obligation: &Obligation<'tcx, T>,
480                                     suggest_increasing_limit: bool) -> !
481         where T: fmt::Display + TypeFoldable<'tcx>
482     {
483         let predicate =
484             self.resolve_type_vars_if_possible(&obligation.predicate);
485         let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
486                                        "overflow evaluating the requirement `{}`",
487                                        predicate);
488
489         if suggest_increasing_limit {
490             self.suggest_new_overflow_limit(&mut err);
491         }
492
493         self.note_obligation_cause(&mut err, obligation);
494
495         err.emit();
496         self.tcx.sess.abort_if_errors();
497         bug!();
498     }
499
500     /// Reports that a cycle was detected which led to overflow and halts
501     /// compilation. This is equivalent to `report_overflow_error` except
502     /// that we can give a more helpful error message (and, in particular,
503     /// we do not suggest increasing the overflow limit, which is not
504     /// going to help).
505     pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
506         let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
507         assert!(cycle.len() > 0);
508
509         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
510
511         self.report_overflow_error(&cycle[0], false);
512     }
513
514     pub fn report_extra_impl_obligation(&self,
515                                         error_span: Span,
516                                         item_name: ast::Name,
517                                         _impl_item_def_id: DefId,
518                                         trait_item_def_id: DefId,
519                                         requirement: &dyn fmt::Display)
520                                         -> DiagnosticBuilder<'tcx>
521     {
522         let msg = "impl has stricter requirements than trait";
523         let sp = self.tcx.sess.codemap().def_span(error_span);
524
525         let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
526
527         if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
528             let span = self.tcx.sess.codemap().def_span(trait_item_span);
529             err.span_label(span, format!("definition of `{}` from trait", item_name));
530         }
531
532         err.span_label(sp, format!("impl has extra requirement {}", requirement));
533
534         err
535     }
536
537
538     /// Get the parent trait chain start
539     fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
540         match code {
541             &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
542                 let parent_trait_ref = self.resolve_type_vars_if_possible(
543                     &data.parent_trait_ref);
544                 match self.get_parent_trait_ref(&data.parent_code) {
545                     Some(t) => Some(t),
546                     None => Some(format!("{}", parent_trait_ref.skip_binder().self_ty())),
547                 }
548             }
549             _ => None,
550         }
551     }
552
553     pub fn report_selection_error(&self,
554                                   obligation: &PredicateObligation<'tcx>,
555                                   error: &SelectionError<'tcx>,
556                                   fallback_has_occurred: bool)
557     {
558         let span = obligation.cause.span;
559
560         let mut err = match *error {
561             SelectionError::Unimplemented => {
562                 if let ObligationCauseCode::CompareImplMethodObligation {
563                     item_name, impl_item_def_id, trait_item_def_id,
564                 } = obligation.cause.code {
565                     self.report_extra_impl_obligation(
566                         span,
567                         item_name,
568                         impl_item_def_id,
569                         trait_item_def_id,
570                         &format!("`{}`", obligation.predicate))
571                         .emit();
572                     return;
573                 }
574                 match obligation.predicate {
575                     ty::Predicate::Trait(ref trait_predicate) => {
576                         let trait_predicate =
577                             self.resolve_type_vars_if_possible(trait_predicate);
578
579                         if self.tcx.sess.has_errors() && trait_predicate.references_error() {
580                             return;
581                         }
582                         let trait_ref = trait_predicate.to_poly_trait_ref();
583                         let (post_message, pre_message) =
584                             self.get_parent_trait_ref(&obligation.cause.code)
585                                 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
586                             .unwrap_or((String::new(), String::new()));
587
588                         let OnUnimplementedNote { message, label, note }
589                             = self.on_unimplemented_note(trait_ref, obligation);
590                         let have_alt_message = message.is_some() || label.is_some();
591
592                         let mut err = struct_span_err!(
593                             self.tcx.sess,
594                             span,
595                             E0277,
596                             "{}",
597                             message.unwrap_or_else(|| {
598                                 format!("the trait bound `{}` is not satisfied{}",
599                                          trait_ref.to_predicate(), post_message)
600                             }));
601
602                         let explanation =
603                             if obligation.cause.code == ObligationCauseCode::MainFunctionType {
604                                 "consider using `()`, or a `Result`".to_owned()
605                             } else {
606                                 format!("{}the trait `{}` is not implemented for `{}`",
607                                         pre_message,
608                                         trait_ref,
609                                         trait_ref.self_ty())
610                             };
611
612                         if let Some(ref s) = label {
613                             // If it has a custom "#[rustc_on_unimplemented]"
614                             // error message, let's display it as the label!
615                             err.span_label(span, s.as_str());
616                             err.help(&explanation);
617                         } else {
618                             err.span_label(span, explanation);
619                         }
620                         if let Some(ref s) = note {
621                             // If it has a custom "#[rustc_on_unimplemented]" note, let's display it
622                             err.note(s.as_str());
623                         }
624
625                         self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
626                         self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
627
628                         // Try to report a help message
629                         if !trait_ref.has_infer_types() &&
630                             self.predicate_can_apply(obligation.param_env, trait_ref) {
631                             // If a where-clause may be useful, remind the
632                             // user that they can add it.
633                             //
634                             // don't display an on-unimplemented note, as
635                             // these notes will often be of the form
636                             //     "the type `T` can't be frobnicated"
637                             // which is somewhat confusing.
638                             err.help(&format!("consider adding a `where {}` bound",
639                                                 trait_ref.to_predicate()));
640                         } else if !have_alt_message {
641                             // Can't show anything else useful, try to find similar impls.
642                             let impl_candidates = self.find_similar_impl_candidates(trait_ref);
643                             self.report_similar_impl_candidates(impl_candidates, &mut err);
644                         }
645
646                         // If this error is due to `!: Trait` not implemented but `(): Trait` is
647                         // implemented, and fallback has occured, then it could be due to a
648                         // variable that used to fallback to `()` now falling back to `!`. Issue a
649                         // note informing about the change in behaviour.
650                         if trait_predicate.skip_binder().self_ty().is_never()
651                             && fallback_has_occurred
652                         {
653                             let predicate = trait_predicate.map_bound(|mut trait_pred| {
654                                 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
655                                     self.tcx.mk_nil(),
656                                     &trait_pred.trait_ref.substs[1..],
657                                 );
658                                 trait_pred
659                             });
660                             let unit_obligation = Obligation {
661                                 predicate: ty::Predicate::Trait(predicate),
662                                 .. obligation.clone()
663                             };
664                             if self.predicate_may_hold(&unit_obligation) {
665                                 err.note("the trait is implemented for `()`. \
666                                          Possibly this error has been caused by changes to \
667                                          Rust's type-inference algorithm \
668                                          (see: https://github.com/rust-lang/rust/issues/48950 \
669                                          for more info). Consider whether you meant to use the \
670                                          type `()` here instead.");
671                             }
672                         }
673
674                         err
675                     }
676
677                     ty::Predicate::Subtype(ref predicate) => {
678                         // Errors for Subtype predicates show up as
679                         // `FulfillmentErrorCode::CodeSubtypeError`,
680                         // not selection error.
681                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
682                     }
683
684                     ty::Predicate::RegionOutlives(ref predicate) => {
685                         let predicate = self.resolve_type_vars_if_possible(predicate);
686                         let err = self.region_outlives_predicate(&obligation.cause,
687                                                                     &predicate).err().unwrap();
688                         struct_span_err!(self.tcx.sess, span, E0279,
689                             "the requirement `{}` is not satisfied (`{}`)",
690                             predicate, err)
691                     }
692
693                     ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
694                         let predicate =
695                             self.resolve_type_vars_if_possible(&obligation.predicate);
696                         struct_span_err!(self.tcx.sess, span, E0280,
697                             "the requirement `{}` is not satisfied",
698                             predicate)
699                     }
700
701                     ty::Predicate::ObjectSafe(trait_def_id) => {
702                         let violations = self.tcx.object_safety_violations(trait_def_id);
703                         self.tcx.report_object_safety_error(span,
704                                                             trait_def_id,
705                                                             violations)
706                     }
707
708                     ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
709                         let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
710                         let closure_span = self.tcx.sess.codemap()
711                             .def_span(self.tcx.hir.span_if_local(closure_def_id).unwrap());
712                         let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
713                         let mut err = struct_span_err!(
714                             self.tcx.sess, closure_span, E0525,
715                             "expected a closure that implements the `{}` trait, \
716                                 but this closure only implements `{}`",
717                             kind,
718                             found_kind);
719
720                         err.span_label(
721                             closure_span,
722                             format!("this closure implements `{}`, not `{}`", found_kind, kind));
723                         err.span_label(
724                             obligation.cause.span,
725                             format!("the requirement to implement `{}` derives from here", kind));
726
727                         // Additional context information explaining why the closure only implements
728                         // a particular trait.
729                         if let Some(tables) = self.in_progress_tables {
730                             let tables = tables.borrow();
731                             let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
732                             match (found_kind, tables.closure_kind_origins().get(closure_hir_id)) {
733                                 (ty::ClosureKind::FnOnce, Some((span, name))) => {
734                                     err.span_label(*span, format!(
735                                         "closure is `FnOnce` because it moves the \
736                                          variable `{}` out of its environment", name));
737                                 },
738                                 (ty::ClosureKind::FnMut, Some((span, name))) => {
739                                     err.span_label(*span, format!(
740                                         "closure is `FnMut` because it mutates the \
741                                          variable `{}` here", name));
742                                 },
743                                 _ => {}
744                             }
745                         }
746
747                         err.emit();
748                         return;
749                     }
750
751                     ty::Predicate::WellFormed(ty) => {
752                         // WF predicates cannot themselves make
753                         // errors. They can only block due to
754                         // ambiguity; otherwise, they always
755                         // degenerate into other obligations
756                         // (which may fail).
757                         span_bug!(span, "WF predicate not satisfied for {:?}", ty);
758                     }
759
760                     ty::Predicate::ConstEvaluatable(..) => {
761                         // Errors for `ConstEvaluatable` predicates show up as
762                         // `SelectionError::ConstEvalFailure`,
763                         // not `Unimplemented`.
764                         span_bug!(span,
765                             "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
766                     }
767                 }
768             }
769
770             OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
771                 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
772                 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
773                 if expected_trait_ref.self_ty().references_error() {
774                     return;
775                 }
776                 let found_trait_ty = found_trait_ref.self_ty();
777
778                 let found_did = found_trait_ty.ty_to_def_id();
779                 let found_span = found_did.and_then(|did| {
780                     self.tcx.hir.span_if_local(did)
781                 }).map(|sp| self.tcx.sess.codemap().def_span(sp)); // the sp could be an fn def
782
783                 let found = match found_trait_ref.skip_binder().substs.type_at(1).sty {
784                     ty::TyTuple(ref tys) => tys.iter()
785                         .map(|_| ArgKind::empty()).collect::<Vec<_>>(),
786                     _ => vec![ArgKind::empty()],
787                 };
788                 let expected = match expected_trait_ref.skip_binder().substs.type_at(1).sty {
789                     ty::TyTuple(ref tys) => tys.iter()
790                         .map(|t| match t.sty {
791                             ty::TypeVariants::TyTuple(ref tys) => ArgKind::Tuple(
792                                 Some(span),
793                                 tys.iter()
794                                     .map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
795                                     .collect::<Vec<_>>()
796                             ),
797                             _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
798                         }).collect(),
799                     ref sty => vec![ArgKind::Arg("_".to_owned(), format!("{}", sty))],
800                 };
801                 if found.len() == expected.len() {
802                     self.report_closure_arg_mismatch(span,
803                                                      found_span,
804                                                      found_trait_ref,
805                                                      expected_trait_ref)
806                 } else {
807                     let (closure_span, found) = found_did
808                         .and_then(|did| self.tcx.hir.get_if_local(did))
809                         .map(|node| {
810                             let (found_span, found) = self.get_fn_like_arguments(node);
811                             (Some(found_span), found)
812                         }).unwrap_or((found_span, found));
813
814                     self.report_arg_count_mismatch(span,
815                                                    closure_span,
816                                                    expected,
817                                                    found,
818                                                    found_trait_ty.is_closure())
819                 }
820             }
821
822             TraitNotObjectSafe(did) => {
823                 let violations = self.tcx.object_safety_violations(did);
824                 self.tcx.report_object_safety_error(span, did,
825                                                     violations)
826             }
827
828             ConstEvalFailure(ref err) => {
829                 match err.struct_error(
830                     self.tcx.at(span),
831                     "could not evaluate constant expression",
832                 ) {
833                     Some(err) => err,
834                     None => return,
835                 }
836             }
837
838             Overflow => {
839                 bug!("overflow should be handled before the `report_selection_error` path");
840             }
841         };
842         self.note_obligation_cause(&mut err, obligation);
843         err.emit();
844     }
845
846     /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
847     /// suggestion to borrow the initializer in order to use have a slice instead.
848     fn suggest_borrow_on_unsized_slice(&self,
849                                        code: &ObligationCauseCode<'tcx>,
850                                        err: &mut DiagnosticBuilder<'tcx>) {
851         if let &ObligationCauseCode::VariableType(node_id) = code {
852             let parent_node = self.tcx.hir.get_parent_node(node_id);
853             if let Some(hir::map::NodeLocal(ref local)) = self.tcx.hir.find(parent_node) {
854                 if let Some(ref expr) = local.init {
855                     if let hir::ExprIndex(_, _) = expr.node {
856                         if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(expr.span) {
857                             err.span_suggestion_with_applicability(
858                                 expr.span,
859                                 "consider borrowing here",
860                                 format!("&{}", snippet),
861                                 Applicability::MachineApplicable
862                             );
863                         }
864                     }
865                 }
866             }
867         }
868     }
869
870     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
871     /// suggest removing these references until we reach a type that implements the trait.
872     fn suggest_remove_reference(&self,
873                                 obligation: &PredicateObligation<'tcx>,
874                                 err: &mut DiagnosticBuilder<'tcx>,
875                                 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>) {
876         let trait_ref = trait_ref.skip_binder();
877         let span = obligation.cause.span;
878
879         if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
880             let refs_number = snippet.chars()
881                 .filter(|c| !c.is_whitespace())
882                 .take_while(|c| *c == '&')
883                 .count();
884
885             let mut trait_type = trait_ref.self_ty();
886
887             for refs_remaining in 0..refs_number {
888                 if let ty::TypeVariants::TyRef(_, t_type, _) = trait_type.sty {
889                     trait_type = t_type;
890
891                     let substs = self.tcx.mk_substs_trait(trait_type, &[]);
892                     let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
893                     let new_obligation = Obligation::new(ObligationCause::dummy(),
894                                                          obligation.param_env,
895                                                          new_trait_ref.to_predicate());
896
897                     if self.predicate_may_hold(&new_obligation) {
898                         let sp = self.tcx.sess.codemap()
899                             .span_take_while(span, |c| c.is_whitespace() || *c == '&');
900
901                         let remove_refs = refs_remaining + 1;
902                         let format_str = format!("consider removing {} leading `&`-references",
903                                                  remove_refs);
904
905                         err.span_suggestion_short_with_applicability(
906                             sp, &format_str, String::from(""), Applicability::MachineApplicable
907                         );
908                         break;
909                     }
910                 } else {
911                     break;
912                 }
913             }
914         }
915     }
916
917     /// Given some node representing a fn-like thing in the HIR map,
918     /// returns a span and `ArgKind` information that describes the
919     /// arguments it expects. This can be supplied to
920     /// `report_arg_count_mismatch`.
921     pub fn get_fn_like_arguments(&self, node: hir::map::Node) -> (Span, Vec<ArgKind>) {
922         match node {
923             hir::map::NodeExpr(&hir::Expr {
924                 node: hir::ExprClosure(_, ref _decl, id, span, _),
925                 ..
926             }) => {
927                 (self.tcx.sess.codemap().def_span(span), self.tcx.hir.body(id).arguments.iter()
928                     .map(|arg| {
929                         if let hir::Pat {
930                             node: hir::PatKind::Tuple(args, _),
931                             span,
932                             ..
933                         } = arg.pat.clone().into_inner() {
934                             ArgKind::Tuple(
935                                 Some(span),
936                                 args.iter().map(|pat| {
937                                     let snippet = self.tcx.sess.codemap()
938                                         .span_to_snippet(pat.span).unwrap();
939                                     (snippet, "_".to_owned())
940                                 }).collect::<Vec<_>>(),
941                             )
942                         } else {
943                             let name = self.tcx.sess.codemap()
944                                 .span_to_snippet(arg.pat.span).unwrap();
945                             ArgKind::Arg(name, "_".to_owned())
946                         }
947                     })
948                     .collect::<Vec<ArgKind>>())
949             }
950             hir::map::NodeItem(&hir::Item {
951                 span,
952                 node: hir::ItemFn(ref decl, ..),
953                 ..
954             }) |
955             hir::map::NodeImplItem(&hir::ImplItem {
956                 span,
957                 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
958                 ..
959             }) |
960             hir::map::NodeTraitItem(&hir::TraitItem {
961                 span,
962                 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
963                 ..
964             }) => {
965                 (self.tcx.sess.codemap().def_span(span), decl.inputs.iter()
966                         .map(|arg| match arg.clone().node {
967                     hir::TyTup(ref tys) => ArgKind::Tuple(
968                         Some(arg.span),
969                         tys.iter()
970                             .map(|_| ("_".to_owned(), "_".to_owned()))
971                             .collect::<Vec<_>>(),
972                     ),
973                     _ => ArgKind::Arg("_".to_owned(), "_".to_owned())
974                 }).collect::<Vec<ArgKind>>())
975             }
976             hir::map::NodeVariant(&hir::Variant {
977                 span,
978                 node: hir::Variant_ {
979                     data: hir::VariantData::Tuple(ref fields, _),
980                     ..
981                 },
982                 ..
983             }) => {
984                 (self.tcx.sess.codemap().def_span(span),
985                  fields.iter().map(|field| {
986                      ArgKind::Arg(format!("{}", field.ident), "_".to_string())
987                  }).collect::<Vec<_>>())
988             }
989             hir::map::NodeStructCtor(ref variant_data) => {
990                 (self.tcx.sess.codemap().def_span(self.tcx.hir.span(variant_data.id())),
991                  variant_data.fields()
992                     .iter().map(|_| ArgKind::Arg("_".to_owned(), "_".to_owned()))
993                     .collect())
994             }
995             _ => panic!("non-FnLike node found: {:?}", node),
996         }
997     }
998
999     /// Reports an error when the number of arguments needed by a
1000     /// trait match doesn't match the number that the expression
1001     /// provides.
1002     pub fn report_arg_count_mismatch(
1003         &self,
1004         span: Span,
1005         found_span: Option<Span>,
1006         expected_args: Vec<ArgKind>,
1007         found_args: Vec<ArgKind>,
1008         is_closure: bool,
1009     ) -> DiagnosticBuilder<'tcx> {
1010         let kind = if is_closure { "closure" } else { "function" };
1011
1012         let args_str = |arguments: &Vec<ArgKind>, other: &Vec<ArgKind>| {
1013             let arg_length = arguments.len();
1014             let distinct = match &other[..] {
1015                 &[ArgKind::Tuple(..)] => true,
1016                 _ => false,
1017             };
1018             match (arg_length, arguments.get(0)) {
1019                 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1020                     format!("a single {}-tuple as argument", fields.len())
1021                 }
1022                 _ => format!("{} {}argument{}",
1023                              arg_length,
1024                              if distinct && arg_length > 1 { "distinct " } else { "" },
1025                              if arg_length == 1 { "" } else { "s" }),
1026             }
1027         };
1028
1029         let expected_str = args_str(&expected_args, &found_args);
1030         let found_str = args_str(&found_args, &expected_args);
1031
1032         let mut err = struct_span_err!(
1033             self.tcx.sess,
1034             span,
1035             E0593,
1036             "{} is expected to take {}, but it takes {}",
1037             kind,
1038             expected_str,
1039             found_str,
1040         );
1041
1042         err.span_label(span, format!( "expected {} that takes {}", kind, expected_str));
1043
1044         if let Some(found_span) = found_span {
1045             err.span_label(found_span, format!("takes {}", found_str));
1046
1047             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1048                 if fields.len() == expected_args.len() {
1049                     let sugg = fields.iter()
1050                         .map(|(name, _)| name.to_owned())
1051                         .collect::<Vec<String>>().join(", ");
1052                     err.span_suggestion_with_applicability(found_span,
1053                                                            "change the closure to take multiple \
1054                                                             arguments instead of a single tuple",
1055                                                            format!("|{}|", sugg),
1056                                                            Applicability::MachineApplicable);
1057                 }
1058             }
1059             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1060                 if fields.len() == found_args.len() && is_closure {
1061                     let sugg = format!(
1062                         "|({}){}|",
1063                         found_args.iter()
1064                             .map(|arg| match arg {
1065                                 ArgKind::Arg(name, _) => name.to_owned(),
1066                                 _ => "_".to_owned(),
1067                             })
1068                             .collect::<Vec<String>>()
1069                             .join(", "),
1070                         // add type annotations if available
1071                         if found_args.iter().any(|arg| match arg {
1072                             ArgKind::Arg(_, ty) => ty != "_",
1073                             _ => false,
1074                         }) {
1075                             format!(": ({})",
1076                                     fields.iter()
1077                                         .map(|(_, ty)| ty.to_owned())
1078                                         .collect::<Vec<String>>()
1079                                         .join(", "))
1080                         } else {
1081                             "".to_owned()
1082                         },
1083                     );
1084                     err.span_suggestion_with_applicability(
1085                         found_span,
1086                         "change the closure to accept a tuple instead of \
1087                          individual arguments",
1088                         sugg,
1089                         Applicability::MachineApplicable
1090                     );
1091                 }
1092             }
1093         }
1094
1095         err
1096     }
1097
1098     fn report_closure_arg_mismatch(&self,
1099                            span: Span,
1100                            found_span: Option<Span>,
1101                            expected_ref: ty::PolyTraitRef<'tcx>,
1102                            found: ty::PolyTraitRef<'tcx>)
1103         -> DiagnosticBuilder<'tcx>
1104     {
1105         fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
1106                                                trait_ref: &ty::TraitRef<'tcx>) -> String {
1107             let inputs = trait_ref.substs.type_at(1);
1108             let sig = if let ty::TyTuple(inputs) = inputs.sty {
1109                 tcx.mk_fn_sig(
1110                     inputs.iter().map(|&x| x),
1111                     tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1112                     false,
1113                     hir::Unsafety::Normal,
1114                     ::rustc_target::spec::abi::Abi::Rust
1115                 )
1116             } else {
1117                 tcx.mk_fn_sig(
1118                     ::std::iter::once(inputs),
1119                     tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1120                     false,
1121                     hir::Unsafety::Normal,
1122                     ::rustc_target::spec::abi::Abi::Rust
1123                 )
1124             };
1125             format!("{}", ty::Binder::bind(sig))
1126         }
1127
1128         let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1129         let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1130                                        "type mismatch in {} arguments",
1131                                        if argument_is_closure { "closure" } else { "function" });
1132
1133         let found_str = format!(
1134             "expected signature of `{}`",
1135             build_fn_sig_string(self.tcx, found.skip_binder())
1136         );
1137         err.span_label(span, found_str);
1138
1139         let found_span = found_span.unwrap_or(span);
1140         let expected_str = format!(
1141             "found signature of `{}`",
1142             build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1143         );
1144         err.span_label(found_span, expected_str);
1145
1146         err
1147     }
1148 }
1149
1150 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1151     pub fn recursive_type_with_infinite_size_error(self,
1152                                                    type_def_id: DefId)
1153                                                    -> DiagnosticBuilder<'tcx>
1154     {
1155         assert!(type_def_id.is_local());
1156         let span = self.hir.span_if_local(type_def_id).unwrap();
1157         let span = self.sess.codemap().def_span(span);
1158         let mut err = struct_span_err!(self.sess, span, E0072,
1159                                        "recursive type `{}` has infinite size",
1160                                        self.item_path_str(type_def_id));
1161         err.span_label(span, "recursive type has infinite size");
1162         err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1163                            at some point to make `{}` representable",
1164                           self.item_path_str(type_def_id)));
1165         err
1166     }
1167
1168     pub fn report_object_safety_error(self,
1169                                       span: Span,
1170                                       trait_def_id: DefId,
1171                                       violations: Vec<ObjectSafetyViolation>)
1172                                       -> DiagnosticBuilder<'tcx>
1173     {
1174         let trait_str = self.item_path_str(trait_def_id);
1175         let span = self.sess.codemap().def_span(span);
1176         let mut err = struct_span_err!(
1177             self.sess, span, E0038,
1178             "the trait `{}` cannot be made into an object",
1179             trait_str);
1180         err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1181
1182         let mut reported_violations = FxHashSet();
1183         for violation in violations {
1184             if !reported_violations.insert(violation.clone()) {
1185                 continue;
1186             }
1187             err.note(&violation.error_msg());
1188         }
1189         err
1190     }
1191 }
1192
1193 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1194     fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1195                               body_id: Option<hir::BodyId>) {
1196         // Unable to successfully determine, probably means
1197         // insufficient type information, but could mean
1198         // ambiguous impls. The latter *ought* to be a
1199         // coherence violation, so we don't report it here.
1200
1201         let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1202         let span = obligation.cause.span;
1203
1204         debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1205                predicate,
1206                obligation);
1207
1208         // Ambiguity errors are often caused as fallout from earlier
1209         // errors. So just ignore them if this infcx is tainted.
1210         if self.is_tainted_by_errors() {
1211             return;
1212         }
1213
1214         match predicate {
1215             ty::Predicate::Trait(ref data) => {
1216                 let trait_ref = data.to_poly_trait_ref();
1217                 let self_ty = trait_ref.self_ty();
1218                 if predicate.references_error() {
1219                     return;
1220                 }
1221                 // Typically, this ambiguity should only happen if
1222                 // there are unresolved type inference variables
1223                 // (otherwise it would suggest a coherence
1224                 // failure). But given #21974 that is not necessarily
1225                 // the case -- we can have multiple where clauses that
1226                 // are only distinguished by a region, which results
1227                 // in an ambiguity even when all types are fully
1228                 // known, since we don't dispatch based on region
1229                 // relationships.
1230
1231                 // This is kind of a hack: it frequently happens that some earlier
1232                 // error prevents types from being fully inferred, and then we get
1233                 // a bunch of uninteresting errors saying something like "<generic
1234                 // #0> doesn't implement Sized".  It may even be true that we
1235                 // could just skip over all checks where the self-ty is an
1236                 // inference variable, but I was afraid that there might be an
1237                 // inference variable created, registered as an obligation, and
1238                 // then never forced by writeback, and hence by skipping here we'd
1239                 // be ignoring the fact that we don't KNOW the type works
1240                 // out. Though even that would probably be harmless, given that
1241                 // we're only talking about builtin traits, which are known to be
1242                 // inhabited. But in any case I just threw in this check for
1243                 // has_errors() to be sure that compilation isn't happening
1244                 // anyway. In that case, why inundate the user.
1245                 if !self.tcx.sess.has_errors() {
1246                     if
1247                         self.tcx.lang_items().sized_trait()
1248                         .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1249                     {
1250                         self.need_type_info_err(body_id, span, self_ty).emit();
1251                     } else {
1252                         let mut err = struct_span_err!(self.tcx.sess,
1253                                                         span, E0283,
1254                                                         "type annotations required: \
1255                                                         cannot resolve `{}`",
1256                                                         predicate);
1257                         self.note_obligation_cause(&mut err, obligation);
1258                         err.emit();
1259                     }
1260                 }
1261             }
1262
1263             ty::Predicate::WellFormed(ty) => {
1264                 // Same hacky approach as above to avoid deluging user
1265                 // with error messages.
1266                 if !ty.references_error() && !self.tcx.sess.has_errors() {
1267                     self.need_type_info_err(body_id, span, ty).emit();
1268                 }
1269             }
1270
1271             ty::Predicate::Subtype(ref data) => {
1272                 if data.references_error() || self.tcx.sess.has_errors() {
1273                     // no need to overload user in such cases
1274                 } else {
1275                     let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1276                     // both must be type variables, or the other would've been instantiated
1277                     assert!(a.is_ty_var() && b.is_ty_var());
1278                     self.need_type_info_err(body_id,
1279                                             obligation.cause.span,
1280                                             a).emit();
1281                 }
1282             }
1283
1284             _ => {
1285                 if !self.tcx.sess.has_errors() {
1286                     let mut err = struct_span_err!(self.tcx.sess,
1287                                                    obligation.cause.span, E0284,
1288                                                    "type annotations required: \
1289                                                     cannot resolve `{}`",
1290                                                    predicate);
1291                     self.note_obligation_cause(&mut err, obligation);
1292                     err.emit();
1293                 }
1294             }
1295         }
1296     }
1297
1298     /// Returns whether the trait predicate may apply for *some* assignment
1299     /// to the type parameters.
1300     fn predicate_can_apply(&self,
1301                            param_env: ty::ParamEnv<'tcx>,
1302                            pred: ty::PolyTraitRef<'tcx>)
1303                            -> bool {
1304         struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1305             infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1306             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1307         }
1308
1309         impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1310             fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1311
1312             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1313                 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
1314                     let infcx = self.infcx;
1315                     self.var_map.entry(ty).or_insert_with(||
1316                         infcx.next_ty_var(
1317                             TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1318                 } else {
1319                     ty.super_fold_with(self)
1320                 }
1321             }
1322         }
1323
1324         self.probe(|_| {
1325             let mut selcx = SelectionContext::new(self);
1326
1327             let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1328                 infcx: self,
1329                 var_map: FxHashMap()
1330             });
1331
1332             let cleaned_pred = super::project::normalize(
1333                 &mut selcx,
1334                 param_env,
1335                 ObligationCause::dummy(),
1336                 &cleaned_pred
1337             ).value;
1338
1339             let obligation = Obligation::new(
1340                 ObligationCause::dummy(),
1341                 param_env,
1342                 cleaned_pred.to_predicate()
1343             );
1344
1345             self.predicate_may_hold(&obligation)
1346         })
1347     }
1348
1349     fn note_obligation_cause<T>(&self,
1350                                 err: &mut DiagnosticBuilder,
1351                                 obligation: &Obligation<'tcx, T>)
1352         where T: fmt::Display
1353     {
1354         self.note_obligation_cause_code(err,
1355                                         &obligation.predicate,
1356                                         &obligation.cause.code,
1357                                         &mut vec![]);
1358     }
1359
1360     fn note_obligation_cause_code<T>(&self,
1361                                      err: &mut DiagnosticBuilder,
1362                                      predicate: &T,
1363                                      cause_code: &ObligationCauseCode<'tcx>,
1364                                      obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1365         where T: fmt::Display
1366     {
1367         let tcx = self.tcx;
1368         match *cause_code {
1369             ObligationCauseCode::ExprAssignable |
1370             ObligationCauseCode::MatchExpressionArm { .. } |
1371             ObligationCauseCode::IfExpression |
1372             ObligationCauseCode::IfExpressionWithNoElse |
1373             ObligationCauseCode::MainFunctionType |
1374             ObligationCauseCode::StartFunctionType |
1375             ObligationCauseCode::IntrinsicType |
1376             ObligationCauseCode::MethodReceiver |
1377             ObligationCauseCode::ReturnNoExpression |
1378             ObligationCauseCode::MiscObligation => {
1379             }
1380             ObligationCauseCode::SliceOrArrayElem => {
1381                 err.note("slice and array elements must have `Sized` type");
1382             }
1383             ObligationCauseCode::TupleElem => {
1384                 err.note("only the last element of a tuple may have a dynamically sized type");
1385             }
1386             ObligationCauseCode::ProjectionWf(data) => {
1387                 err.note(&format!("required so that the projection `{}` is well-formed",
1388                                   data));
1389             }
1390             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1391                 err.note(&format!("required so that reference `{}` does not outlive its referent",
1392                                   ref_ty));
1393             }
1394             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1395                 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1396                                    is satisfied",
1397                                   region, object_ty));
1398             }
1399             ObligationCauseCode::ItemObligation(item_def_id) => {
1400                 let item_name = tcx.item_path_str(item_def_id);
1401                 let msg = format!("required by `{}`", item_name);
1402                 if let Some(sp) = tcx.hir.span_if_local(item_def_id) {
1403                     let sp = tcx.sess.codemap().def_span(sp);
1404                     err.span_note(sp, &msg);
1405                 } else {
1406                     err.note(&msg);
1407                 }
1408             }
1409             ObligationCauseCode::ObjectCastObligation(object_ty) => {
1410                 err.note(&format!("required for the cast to the object type `{}`",
1411                                   self.ty_to_string(object_ty)));
1412             }
1413             ObligationCauseCode::RepeatVec => {
1414                 err.note("the `Copy` trait is required because the \
1415                           repeated element will be copied");
1416             }
1417             ObligationCauseCode::VariableType(_) => {
1418                 err.note("all local variables must have a statically known size");
1419             }
1420             ObligationCauseCode::SizedReturnType => {
1421                 err.note("the return type of a function must have a \
1422                           statically known size");
1423             }
1424             ObligationCauseCode::SizedYieldType => {
1425                 err.note("the yield type of a generator must have a \
1426                           statically known size");
1427             }
1428             ObligationCauseCode::AssignmentLhsSized => {
1429                 err.note("the left-hand-side of an assignment must have a statically known size");
1430             }
1431             ObligationCauseCode::TupleInitializerSized => {
1432                 err.note("tuples must have a statically known size to be initialized");
1433             }
1434             ObligationCauseCode::StructInitializerSized => {
1435                 err.note("structs must have a statically known size to be initialized");
1436             }
1437             ObligationCauseCode::FieldSized(ref item) => {
1438                 match *item {
1439                     AdtKind::Struct => {
1440                         err.note("only the last field of a struct may have a dynamically \
1441                                   sized type");
1442                     }
1443                     AdtKind::Union => {
1444                         err.note("no field of a union may have a dynamically sized type");
1445                     }
1446                     AdtKind::Enum => {
1447                         err.note("no field of an enum variant may have a dynamically sized type");
1448                     }
1449                 }
1450             }
1451             ObligationCauseCode::ConstSized => {
1452                 err.note("constant expressions must have a statically known size");
1453             }
1454             ObligationCauseCode::SharedStatic => {
1455                 err.note("shared static variables must have a type that implements `Sync`");
1456             }
1457             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1458                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1459                 let ty = parent_trait_ref.skip_binder().self_ty();
1460                 err.note(&format!("required because it appears within the type `{}`", ty));
1461                 obligated_types.push(ty);
1462
1463                 let parent_predicate = parent_trait_ref.to_predicate();
1464                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1465                     self.note_obligation_cause_code(err,
1466                                                     &parent_predicate,
1467                                                     &data.parent_code,
1468                                                     obligated_types);
1469                 }
1470             }
1471             ObligationCauseCode::ImplDerivedObligation(ref data) => {
1472                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1473                 err.note(
1474                     &format!("required because of the requirements on the impl of `{}` for `{}`",
1475                              parent_trait_ref,
1476                              parent_trait_ref.skip_binder().self_ty()));
1477                 let parent_predicate = parent_trait_ref.to_predicate();
1478                 self.note_obligation_cause_code(err,
1479                                             &parent_predicate,
1480                                             &data.parent_code,
1481                                             obligated_types);
1482             }
1483             ObligationCauseCode::CompareImplMethodObligation { .. } => {
1484                 err.note(
1485                     &format!("the requirement `{}` appears on the impl method \
1486                               but not on the corresponding trait method",
1487                              predicate));
1488             }
1489             ObligationCauseCode::ReturnType(_) |
1490             ObligationCauseCode::BlockTailExpression(_) => (),
1491             ObligationCauseCode::TrivialBound => {
1492                 err.help("see issue #48214");
1493                 if tcx.sess.opts.unstable_features.is_nightly_build() {
1494                     err.help("add #![feature(trivial_bounds)] to the \
1495                               crate attributes to enable",
1496                     );
1497                 }
1498             }
1499         }
1500     }
1501
1502     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1503         let current_limit = self.tcx.sess.recursion_limit.get();
1504         let suggested_limit = current_limit * 2;
1505         err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1506                           suggested_limit));
1507     }
1508
1509     fn is_recursive_obligation(&self,
1510                                    obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1511                                    cause_code: &ObligationCauseCode<'tcx>) -> bool {
1512         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1513             let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1514             for obligated_type in obligated_types {
1515                 if obligated_type == &parent_trait_ref.skip_binder().self_ty() {
1516                     return true;
1517                 }
1518             }
1519         }
1520         return false;
1521     }
1522 }
1523
1524 /// Summarizes information
1525 pub enum ArgKind {
1526     /// An argument of non-tuple type. Parameters are (name, ty)
1527     Arg(String, String),
1528
1529     /// An argument of tuple type. For a "found" argument, the span is
1530     /// the locationo in the source of the pattern. For a "expected"
1531     /// argument, it will be None. The vector is a list of (name, ty)
1532     /// strings for the components of the tuple.
1533     Tuple(Option<Span>, Vec<(String, String)>),
1534 }
1535
1536 impl ArgKind {
1537     fn empty() -> ArgKind {
1538         ArgKind::Arg("_".to_owned(), "_".to_owned())
1539     }
1540
1541     /// Creates an `ArgKind` from the expected type of an
1542     /// argument. This has no name (`_`) and no source spans..
1543     pub fn from_expected_ty(t: Ty<'_>) -> ArgKind {
1544         match t.sty {
1545             ty::TyTuple(ref tys) => ArgKind::Tuple(
1546                 None,
1547                 tys.iter()
1548                    .map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
1549                    .collect::<Vec<_>>()
1550             ),
1551             _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
1552         }
1553     }
1554 }