]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
Refactor generic params loops
[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::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 normalized = super::normalize_projection_type(
207                     &mut selcx,
208                     obligation.param_env,
209                     data.projection_ty,
210                     obligation.cause.clone(),
211                     0
212                 );
213                 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
214                                         .eq(normalized.value, data.ty) {
215                     values = Some(infer::ValuePairs::Types(ExpectedFound {
216                         expected: normalized.value,
217                         found: data.ty,
218                     }));
219                     err_buf = error;
220                     err = &err_buf;
221                 }
222             }
223
224             let msg = format!("type mismatch resolving `{}`", predicate);
225             let error_id = (DiagnosticMessageId::ErrorId(271),
226                             Some(obligation.cause.span), msg.clone());
227             let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
228             if fresh {
229                 let mut diag = struct_span_err!(
230                     self.tcx.sess, obligation.cause.span, E0271,
231                     "type mismatch resolving `{}`", predicate
232                 );
233                 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
234                 self.note_obligation_cause(&mut diag, obligation);
235                 diag.emit();
236             }
237         });
238     }
239
240     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
241         /// returns the fuzzy category of a given type, or None
242         /// if the type can be equated to any type.
243         fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
244             match t.sty {
245                 ty::TyBool => Some(0),
246                 ty::TyChar => Some(1),
247                 ty::TyStr => Some(2),
248                 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
249                 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
250                 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
251                 ty::TyArray(..) | ty::TySlice(..) => Some(6),
252                 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
253                 ty::TyDynamic(..) => Some(8),
254                 ty::TyClosure(..) => Some(9),
255                 ty::TyTuple(..) => Some(10),
256                 ty::TyProjection(..) => Some(11),
257                 ty::TyParam(..) => Some(12),
258                 ty::TyAnon(..) => Some(13),
259                 ty::TyNever => Some(14),
260                 ty::TyAdt(adt, ..) => match adt.adt_kind() {
261                     AdtKind::Struct => Some(15),
262                     AdtKind::Union => Some(16),
263                     AdtKind::Enum => Some(17),
264                 },
265                 ty::TyGenerator(..) => Some(18),
266                 ty::TyForeign(..) => Some(19),
267                 ty::TyGeneratorWitness(..) => Some(20),
268                 ty::TyInfer(..) | ty::TyError => None
269             }
270         }
271
272         match (type_category(a), type_category(b)) {
273             (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
274                 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
275                 _ => cat_a == cat_b
276             },
277             // infer and error can be equated to all types
278             _ => true
279         }
280     }
281
282     fn impl_similar_to(&self,
283                        trait_ref: ty::PolyTraitRef<'tcx>,
284                        obligation: &PredicateObligation<'tcx>)
285                        -> Option<DefId>
286     {
287         let tcx = self.tcx;
288         let param_env = obligation.param_env;
289         let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
290         let trait_self_ty = trait_ref.self_ty();
291
292         let mut self_match_impls = vec![];
293         let mut fuzzy_match_impls = vec![];
294
295         self.tcx.for_each_relevant_impl(
296             trait_ref.def_id, trait_self_ty, |def_id| {
297                 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
298                 let impl_trait_ref = tcx
299                     .impl_trait_ref(def_id)
300                     .unwrap()
301                     .subst(tcx, impl_substs);
302
303                 let impl_self_ty = impl_trait_ref.self_ty();
304
305                 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
306                     self_match_impls.push(def_id);
307
308                     if trait_ref.substs.types().skip(1)
309                         .zip(impl_trait_ref.substs.types().skip(1))
310                         .all(|(u,v)| self.fuzzy_match_tys(u, v))
311                     {
312                         fuzzy_match_impls.push(def_id);
313                     }
314                 }
315             });
316
317         let impl_def_id = if self_match_impls.len() == 1 {
318             self_match_impls[0]
319         } else if fuzzy_match_impls.len() == 1 {
320             fuzzy_match_impls[0]
321         } else {
322             return None
323         };
324
325         if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
326             Some(impl_def_id)
327         } else {
328             None
329         }
330     }
331
332     fn on_unimplemented_note(
333         &self,
334         trait_ref: ty::PolyTraitRef<'tcx>,
335         obligation: &PredicateObligation<'tcx>) ->
336         OnUnimplementedNote
337     {
338         let def_id = self.impl_similar_to(trait_ref, obligation)
339             .unwrap_or(trait_ref.def_id());
340         let trait_ref = *trait_ref.skip_binder();
341
342         let mut flags = vec![];
343         match obligation.cause.code {
344             ObligationCauseCode::BuiltinDerivedObligation(..) |
345             ObligationCauseCode::ImplDerivedObligation(..) => {}
346             _ => {
347                 // this is a "direct", user-specified, rather than derived,
348                 // obligation.
349                 flags.push(("direct".to_string(), None));
350             }
351         }
352
353         if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
354             // FIXME: maybe also have some way of handling methods
355             // from other traits? That would require name resolution,
356             // which we might want to be some sort of hygienic.
357             //
358             // Currently I'm leaving it for what I need for `try`.
359             if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
360                 let method = self.tcx.item_name(item);
361                 flags.push(("from_method".to_string(), None));
362                 flags.push(("from_method".to_string(), Some(method.to_string())));
363             }
364         }
365
366         if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
367             let desugaring = k.as_symbol().as_str();
368             flags.push(("from_desugaring".to_string(), None));
369             flags.push(("from_desugaring".to_string(), Some(desugaring.to_string())));
370         }
371         let generics = self.tcx.generics_of(def_id);
372         let self_ty = trait_ref.self_ty();
373         // This is also included through the generics list as `Self`,
374         // but the parser won't allow you to use it
375         flags.push(("_Self".to_string(), Some(self_ty.to_string())));
376         if let Some(def) = self_ty.ty_adt_def() {
377             // We also want to be able to select self's original
378             // signature with no type arguments resolved
379             flags.push(("_Self".to_string(), Some(self.tcx.type_of(def.did).to_string())));
380         }
381
382         for param in generics.params.iter() {
383             let name = param.name.to_string();
384             let value = match param.kind {
385                 GenericParamDefKind::Type(_) => {
386                     let ty = trait_ref.substs.type_for_def(&param);
387                     ty.to_string()
388                 },
389                 GenericParamDefKind::Lifetime(_) => continue,
390             };
391             flags.push((name.clone(), Some(value.clone())));
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                                 {
655                                     let trait_ref = &mut trait_pred.trait_ref;
656                                     let never_substs = trait_ref.substs;
657                                     let mut unit_substs = Vec::with_capacity(never_substs.len());
658                                     unit_substs.push(self.tcx.mk_nil().into());
659                                     unit_substs.extend(&never_substs[1..]);
660                                     trait_ref.substs = self.tcx.intern_substs(&unit_substs);
661                                 }
662                                 trait_pred
663                             });
664                             let unit_obligation = Obligation {
665                                 predicate: ty::Predicate::Trait(predicate),
666                                 .. obligation.clone()
667                             };
668                             if self.predicate_may_hold(&unit_obligation) {
669                                 err.note("the trait is implemented for `()`. \
670                                          Possibly this error has been caused by changes to \
671                                          Rust's type-inference algorithm \
672                                          (see: https://github.com/rust-lang/rust/issues/48950 \
673                                          for more info). Consider whether you meant to use the \
674                                          type `()` here instead.");
675                             }
676                         }
677
678                         err
679                     }
680
681                     ty::Predicate::Subtype(ref predicate) => {
682                         // Errors for Subtype predicates show up as
683                         // `FulfillmentErrorCode::CodeSubtypeError`,
684                         // not selection error.
685                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
686                     }
687
688                     ty::Predicate::RegionOutlives(ref predicate) => {
689                         let predicate = self.resolve_type_vars_if_possible(predicate);
690                         let err = self.region_outlives_predicate(&obligation.cause,
691                                                                     &predicate).err().unwrap();
692                         struct_span_err!(self.tcx.sess, span, E0279,
693                             "the requirement `{}` is not satisfied (`{}`)",
694                             predicate, err)
695                     }
696
697                     ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
698                         let predicate =
699                             self.resolve_type_vars_if_possible(&obligation.predicate);
700                         struct_span_err!(self.tcx.sess, span, E0280,
701                             "the requirement `{}` is not satisfied",
702                             predicate)
703                     }
704
705                     ty::Predicate::ObjectSafe(trait_def_id) => {
706                         let violations = self.tcx.object_safety_violations(trait_def_id);
707                         self.tcx.report_object_safety_error(span,
708                                                             trait_def_id,
709                                                             violations)
710                     }
711
712                     ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
713                         let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
714                         let closure_span = self.tcx.sess.codemap()
715                             .def_span(self.tcx.hir.span_if_local(closure_def_id).unwrap());
716                         let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
717                         let mut err = struct_span_err!(
718                             self.tcx.sess, closure_span, E0525,
719                             "expected a closure that implements the `{}` trait, \
720                                 but this closure only implements `{}`",
721                             kind,
722                             found_kind);
723
724                         err.span_label(
725                             closure_span,
726                             format!("this closure implements `{}`, not `{}`", found_kind, kind));
727                         err.span_label(
728                             obligation.cause.span,
729                             format!("the requirement to implement `{}` derives from here", kind));
730
731                         // Additional context information explaining why the closure only implements
732                         // a particular trait.
733                         if let Some(tables) = self.in_progress_tables {
734                             let tables = tables.borrow();
735                             let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
736                             match (found_kind, tables.closure_kind_origins().get(closure_hir_id)) {
737                                 (ty::ClosureKind::FnOnce, Some((span, name))) => {
738                                     err.span_label(*span, format!(
739                                         "closure is `FnOnce` because it moves the \
740                                          variable `{}` out of its environment", name));
741                                 },
742                                 (ty::ClosureKind::FnMut, Some((span, name))) => {
743                                     err.span_label(*span, format!(
744                                         "closure is `FnMut` because it mutates the \
745                                          variable `{}` here", name));
746                                 },
747                                 _ => {}
748                             }
749                         }
750
751                         err.emit();
752                         return;
753                     }
754
755                     ty::Predicate::WellFormed(ty) => {
756                         // WF predicates cannot themselves make
757                         // errors. They can only block due to
758                         // ambiguity; otherwise, they always
759                         // degenerate into other obligations
760                         // (which may fail).
761                         span_bug!(span, "WF predicate not satisfied for {:?}", ty);
762                     }
763
764                     ty::Predicate::ConstEvaluatable(..) => {
765                         // Errors for `ConstEvaluatable` predicates show up as
766                         // `SelectionError::ConstEvalFailure`,
767                         // not `Unimplemented`.
768                         span_bug!(span,
769                             "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
770                     }
771                 }
772             }
773
774             OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
775                 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
776                 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
777                 if expected_trait_ref.self_ty().references_error() {
778                     return;
779                 }
780                 let found_trait_ty = found_trait_ref.self_ty();
781
782                 let found_did = found_trait_ty.ty_to_def_id();
783                 let found_span = found_did.and_then(|did| {
784                     self.tcx.hir.span_if_local(did)
785                 }).map(|sp| self.tcx.sess.codemap().def_span(sp)); // the sp could be an fn def
786
787                 let found = match found_trait_ref.skip_binder().substs.type_at(1).sty {
788                     ty::TyTuple(ref tys) => tys.iter()
789                         .map(|_| ArgKind::empty()).collect::<Vec<_>>(),
790                     _ => vec![ArgKind::empty()],
791                 };
792                 let expected = match expected_trait_ref.skip_binder().substs.type_at(1).sty {
793                     ty::TyTuple(ref tys) => tys.iter()
794                         .map(|t| match t.sty {
795                             ty::TypeVariants::TyTuple(ref tys) => ArgKind::Tuple(
796                                 Some(span),
797                                 tys.iter()
798                                     .map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
799                                     .collect::<Vec<_>>()
800                             ),
801                             _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
802                         }).collect(),
803                     ref sty => vec![ArgKind::Arg("_".to_owned(), format!("{}", sty))],
804                 };
805                 if found.len() == expected.len() {
806                     self.report_closure_arg_mismatch(span,
807                                                      found_span,
808                                                      found_trait_ref,
809                                                      expected_trait_ref)
810                 } else {
811                     let (closure_span, found) = found_did
812                         .and_then(|did| self.tcx.hir.get_if_local(did))
813                         .map(|node| {
814                             let (found_span, found) = self.get_fn_like_arguments(node);
815                             (Some(found_span), found)
816                         }).unwrap_or((found_span, found));
817
818                     self.report_arg_count_mismatch(span,
819                                                    closure_span,
820                                                    expected,
821                                                    found,
822                                                    found_trait_ty.is_closure())
823                 }
824             }
825
826             TraitNotObjectSafe(did) => {
827                 let violations = self.tcx.object_safety_violations(did);
828                 self.tcx.report_object_safety_error(span, did,
829                                                     violations)
830             }
831
832             ConstEvalFailure(ref err) => {
833                 if let ::middle::const_val::ErrKind::TypeckError = *err.kind {
834                     return;
835                 }
836                 err.struct_error(self.tcx, span, "constant expression")
837             }
838
839             Overflow => {
840                 bug!("overflow should be handled before the `report_selection_error` path");
841             }
842         };
843         self.note_obligation_cause(&mut err, obligation);
844         err.emit();
845     }
846
847     /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
848     /// suggestion to borrow the initializer in order to use have a slice instead.
849     fn suggest_borrow_on_unsized_slice(&self,
850                                        code: &ObligationCauseCode<'tcx>,
851                                        err: &mut DiagnosticBuilder<'tcx>) {
852         if let &ObligationCauseCode::VariableType(node_id) = code {
853             let parent_node = self.tcx.hir.get_parent_node(node_id);
854             if let Some(hir::map::NodeLocal(ref local)) = self.tcx.hir.find(parent_node) {
855                 if let Some(ref expr) = local.init {
856                     if let hir::ExprIndex(_, _) = expr.node {
857                         if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(expr.span) {
858                             err.span_suggestion(expr.span,
859                                                 "consider borrowing here",
860                                                 format!("&{}", snippet));
861                         }
862                     }
863                 }
864             }
865         }
866     }
867
868     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
869     /// suggest removing these references until we reach a type that implements the trait.
870     fn suggest_remove_reference(&self,
871                                 obligation: &PredicateObligation<'tcx>,
872                                 err: &mut DiagnosticBuilder<'tcx>,
873                                 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>) {
874         let trait_ref = trait_ref.skip_binder();
875         let span = obligation.cause.span;
876
877         if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
878             let refs_number = snippet.chars()
879                 .filter(|c| !c.is_whitespace())
880                 .take_while(|c| *c == '&')
881                 .count();
882
883             let mut trait_type = trait_ref.self_ty();
884
885             for refs_remaining in 0..refs_number {
886                 if let ty::TypeVariants::TyRef(_, t_type, _) = trait_type.sty {
887                     trait_type = t_type;
888
889                     let substs = self.tcx.mk_substs_trait(trait_type, &[]);
890                     let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
891                     let new_obligation = Obligation::new(ObligationCause::dummy(),
892                                                          obligation.param_env,
893                                                          new_trait_ref.to_predicate());
894
895                     if self.predicate_may_hold(&new_obligation) {
896                         let sp = self.tcx.sess.codemap()
897                             .span_take_while(span, |c| c.is_whitespace() || *c == '&');
898
899                         let remove_refs = refs_remaining + 1;
900                         let format_str = format!("consider removing {} leading `&`-references",
901                                                  remove_refs);
902
903                         err.span_suggestion_short(sp, &format_str, String::from(""));
904                         break;
905                     }
906                 } else {
907                     break;
908                 }
909             }
910         }
911     }
912
913     /// Given some node representing a fn-like thing in the HIR map,
914     /// returns a span and `ArgKind` information that describes the
915     /// arguments it expects. This can be supplied to
916     /// `report_arg_count_mismatch`.
917     pub fn get_fn_like_arguments(&self, node: hir::map::Node) -> (Span, Vec<ArgKind>) {
918         match node {
919             hir::map::NodeExpr(&hir::Expr {
920                 node: hir::ExprClosure(_, ref _decl, id, span, _),
921                 ..
922             }) => {
923                 (self.tcx.sess.codemap().def_span(span), self.tcx.hir.body(id).arguments.iter()
924                     .map(|arg| {
925                         if let hir::Pat {
926                             node: hir::PatKind::Tuple(args, _),
927                             span,
928                             ..
929                         } = arg.pat.clone().into_inner() {
930                             ArgKind::Tuple(
931                                 Some(span),
932                                 args.iter().map(|pat| {
933                                     let snippet = self.tcx.sess.codemap()
934                                         .span_to_snippet(pat.span).unwrap();
935                                     (snippet, "_".to_owned())
936                                 }).collect::<Vec<_>>(),
937                             )
938                         } else {
939                             let name = self.tcx.sess.codemap()
940                                 .span_to_snippet(arg.pat.span).unwrap();
941                             ArgKind::Arg(name, "_".to_owned())
942                         }
943                     })
944                     .collect::<Vec<ArgKind>>())
945             }
946             hir::map::NodeItem(&hir::Item {
947                 span,
948                 node: hir::ItemFn(ref decl, ..),
949                 ..
950             }) |
951             hir::map::NodeImplItem(&hir::ImplItem {
952                 span,
953                 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
954                 ..
955             }) |
956             hir::map::NodeTraitItem(&hir::TraitItem {
957                 span,
958                 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
959                 ..
960             }) => {
961                 (self.tcx.sess.codemap().def_span(span), decl.inputs.iter()
962                         .map(|arg| match arg.clone().into_inner().node {
963                     hir::TyTup(ref tys) => ArgKind::Tuple(
964                         Some(arg.span),
965                         tys.iter()
966                             .map(|_| ("_".to_owned(), "_".to_owned()))
967                             .collect::<Vec<_>>(),
968                     ),
969                     _ => ArgKind::Arg("_".to_owned(), "_".to_owned())
970                 }).collect::<Vec<ArgKind>>())
971             }
972             hir::map::NodeVariant(&hir::Variant {
973                 span,
974                 node: hir::Variant_ {
975                     data: hir::VariantData::Tuple(ref fields, _),
976                     ..
977                 },
978                 ..
979             }) => {
980                 (self.tcx.sess.codemap().def_span(span),
981                  fields.iter().map(|field| {
982                      ArgKind::Arg(format!("{}", field.name), "_".to_string())
983                  }).collect::<Vec<_>>())
984             }
985             hir::map::NodeStructCtor(ref variant_data) => {
986                 (self.tcx.sess.codemap().def_span(self.tcx.hir.span(variant_data.id())),
987                  variant_data.fields()
988                     .iter().map(|_| ArgKind::Arg("_".to_owned(), "_".to_owned()))
989                     .collect())
990             }
991             _ => panic!("non-FnLike node found: {:?}", node),
992         }
993     }
994
995     /// Reports an error when the number of arguments needed by a
996     /// trait match doesn't match the number that the expression
997     /// provides.
998     pub fn report_arg_count_mismatch(
999         &self,
1000         span: Span,
1001         found_span: Option<Span>,
1002         expected_args: Vec<ArgKind>,
1003         found_args: Vec<ArgKind>,
1004         is_closure: bool,
1005     ) -> DiagnosticBuilder<'tcx> {
1006         let kind = if is_closure { "closure" } else { "function" };
1007
1008         let args_str = |arguments: &Vec<ArgKind>, other: &Vec<ArgKind>| {
1009             let arg_length = arguments.len();
1010             let distinct = match &other[..] {
1011                 &[ArgKind::Tuple(..)] => true,
1012                 _ => false,
1013             };
1014             match (arg_length, arguments.get(0)) {
1015                 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1016                     format!("a single {}-tuple as argument", fields.len())
1017                 }
1018                 _ => format!("{} {}argument{}",
1019                              arg_length,
1020                              if distinct && arg_length > 1 { "distinct " } else { "" },
1021                              if arg_length == 1 { "" } else { "s" }),
1022             }
1023         };
1024
1025         let expected_str = args_str(&expected_args, &found_args);
1026         let found_str = args_str(&found_args, &expected_args);
1027
1028         let mut err = struct_span_err!(
1029             self.tcx.sess,
1030             span,
1031             E0593,
1032             "{} is expected to take {}, but it takes {}",
1033             kind,
1034             expected_str,
1035             found_str,
1036         );
1037
1038         err.span_label(span, format!( "expected {} that takes {}", kind, expected_str));
1039
1040         if let Some(found_span) = found_span {
1041             err.span_label(found_span, format!("takes {}", found_str));
1042
1043             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1044                 if fields.len() == expected_args.len() {
1045                     let sugg = fields.iter()
1046                         .map(|(name, _)| name.to_owned())
1047                         .collect::<Vec<String>>().join(", ");
1048                     err.span_suggestion(found_span,
1049                                         "change the closure to take multiple arguments instead of \
1050                                          a single tuple",
1051                                         format!("|{}|", sugg));
1052                 }
1053             }
1054             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1055                 if fields.len() == found_args.len() && is_closure {
1056                     let sugg = format!(
1057                         "|({}){}|",
1058                         found_args.iter()
1059                             .map(|arg| match arg {
1060                                 ArgKind::Arg(name, _) => name.to_owned(),
1061                                 _ => "_".to_owned(),
1062                             })
1063                             .collect::<Vec<String>>()
1064                             .join(", "),
1065                         // add type annotations if available
1066                         if found_args.iter().any(|arg| match arg {
1067                             ArgKind::Arg(_, ty) => ty != "_",
1068                             _ => false,
1069                         }) {
1070                             format!(": ({})",
1071                                     fields.iter()
1072                                         .map(|(_, ty)| ty.to_owned())
1073                                         .collect::<Vec<String>>()
1074                                         .join(", "))
1075                         } else {
1076                             "".to_owned()
1077                         },
1078                     );
1079                     err.span_suggestion(found_span,
1080                                         "change the closure to accept a tuple instead of \
1081                                          individual arguments",
1082                                         sugg);
1083                 }
1084             }
1085         }
1086
1087         err
1088     }
1089
1090     fn report_closure_arg_mismatch(&self,
1091                            span: Span,
1092                            found_span: Option<Span>,
1093                            expected_ref: ty::PolyTraitRef<'tcx>,
1094                            found: ty::PolyTraitRef<'tcx>)
1095         -> DiagnosticBuilder<'tcx>
1096     {
1097         fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
1098                                                trait_ref: &ty::TraitRef<'tcx>) -> String {
1099             let inputs = trait_ref.substs.type_at(1);
1100             let sig = if let ty::TyTuple(inputs) = inputs.sty {
1101                 tcx.mk_fn_sig(
1102                     inputs.iter().map(|&x| x),
1103                     tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1104                     false,
1105                     hir::Unsafety::Normal,
1106                     ::rustc_target::spec::abi::Abi::Rust
1107                 )
1108             } else {
1109                 tcx.mk_fn_sig(
1110                     ::std::iter::once(inputs),
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             };
1117             format!("{}", ty::Binder::bind(sig))
1118         }
1119
1120         let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1121         let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1122                                        "type mismatch in {} arguments",
1123                                        if argument_is_closure { "closure" } else { "function" });
1124
1125         let found_str = format!(
1126             "expected signature of `{}`",
1127             build_fn_sig_string(self.tcx, found.skip_binder())
1128         );
1129         err.span_label(span, found_str);
1130
1131         let found_span = found_span.unwrap_or(span);
1132         let expected_str = format!(
1133             "found signature of `{}`",
1134             build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1135         );
1136         err.span_label(found_span, expected_str);
1137
1138         err
1139     }
1140 }
1141
1142 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1143     pub fn recursive_type_with_infinite_size_error(self,
1144                                                    type_def_id: DefId)
1145                                                    -> DiagnosticBuilder<'tcx>
1146     {
1147         assert!(type_def_id.is_local());
1148         let span = self.hir.span_if_local(type_def_id).unwrap();
1149         let span = self.sess.codemap().def_span(span);
1150         let mut err = struct_span_err!(self.sess, span, E0072,
1151                                        "recursive type `{}` has infinite size",
1152                                        self.item_path_str(type_def_id));
1153         err.span_label(span, "recursive type has infinite size");
1154         err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1155                            at some point to make `{}` representable",
1156                           self.item_path_str(type_def_id)));
1157         err
1158     }
1159
1160     pub fn report_object_safety_error(self,
1161                                       span: Span,
1162                                       trait_def_id: DefId,
1163                                       violations: Vec<ObjectSafetyViolation>)
1164                                       -> DiagnosticBuilder<'tcx>
1165     {
1166         let trait_str = self.item_path_str(trait_def_id);
1167         let span = self.sess.codemap().def_span(span);
1168         let mut err = struct_span_err!(
1169             self.sess, span, E0038,
1170             "the trait `{}` cannot be made into an object",
1171             trait_str);
1172         err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1173
1174         let mut reported_violations = FxHashSet();
1175         for violation in violations {
1176             if !reported_violations.insert(violation.clone()) {
1177                 continue;
1178             }
1179             err.note(&violation.error_msg());
1180         }
1181         err
1182     }
1183 }
1184
1185 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1186     fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1187                               body_id: Option<hir::BodyId>) {
1188         // Unable to successfully determine, probably means
1189         // insufficient type information, but could mean
1190         // ambiguous impls. The latter *ought* to be a
1191         // coherence violation, so we don't report it here.
1192
1193         let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1194         let span = obligation.cause.span;
1195
1196         debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1197                predicate,
1198                obligation);
1199
1200         // Ambiguity errors are often caused as fallout from earlier
1201         // errors. So just ignore them if this infcx is tainted.
1202         if self.is_tainted_by_errors() {
1203             return;
1204         }
1205
1206         match predicate {
1207             ty::Predicate::Trait(ref data) => {
1208                 let trait_ref = data.to_poly_trait_ref();
1209                 let self_ty = trait_ref.self_ty();
1210                 if predicate.references_error() {
1211                     return;
1212                 }
1213                 // Typically, this ambiguity should only happen if
1214                 // there are unresolved type inference variables
1215                 // (otherwise it would suggest a coherence
1216                 // failure). But given #21974 that is not necessarily
1217                 // the case -- we can have multiple where clauses that
1218                 // are only distinguished by a region, which results
1219                 // in an ambiguity even when all types are fully
1220                 // known, since we don't dispatch based on region
1221                 // relationships.
1222
1223                 // This is kind of a hack: it frequently happens that some earlier
1224                 // error prevents types from being fully inferred, and then we get
1225                 // a bunch of uninteresting errors saying something like "<generic
1226                 // #0> doesn't implement Sized".  It may even be true that we
1227                 // could just skip over all checks where the self-ty is an
1228                 // inference variable, but I was afraid that there might be an
1229                 // inference variable created, registered as an obligation, and
1230                 // then never forced by writeback, and hence by skipping here we'd
1231                 // be ignoring the fact that we don't KNOW the type works
1232                 // out. Though even that would probably be harmless, given that
1233                 // we're only talking about builtin traits, which are known to be
1234                 // inhabited. But in any case I just threw in this check for
1235                 // has_errors() to be sure that compilation isn't happening
1236                 // anyway. In that case, why inundate the user.
1237                 if !self.tcx.sess.has_errors() {
1238                     if
1239                         self.tcx.lang_items().sized_trait()
1240                         .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1241                     {
1242                         self.need_type_info(body_id, span, self_ty);
1243                     } else {
1244                         let mut err = struct_span_err!(self.tcx.sess,
1245                                                         span, E0283,
1246                                                         "type annotations required: \
1247                                                         cannot resolve `{}`",
1248                                                         predicate);
1249                         self.note_obligation_cause(&mut err, obligation);
1250                         err.emit();
1251                     }
1252                 }
1253             }
1254
1255             ty::Predicate::WellFormed(ty) => {
1256                 // Same hacky approach as above to avoid deluging user
1257                 // with error messages.
1258                 if !ty.references_error() && !self.tcx.sess.has_errors() {
1259                     self.need_type_info(body_id, span, ty);
1260                 }
1261             }
1262
1263             ty::Predicate::Subtype(ref data) => {
1264                 if data.references_error() || self.tcx.sess.has_errors() {
1265                     // no need to overload user in such cases
1266                 } else {
1267                     let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1268                     // both must be type variables, or the other would've been instantiated
1269                     assert!(a.is_ty_var() && b.is_ty_var());
1270                     self.need_type_info(body_id,
1271                                         obligation.cause.span,
1272                                         a);
1273                 }
1274             }
1275
1276             _ => {
1277                 if !self.tcx.sess.has_errors() {
1278                     let mut err = struct_span_err!(self.tcx.sess,
1279                                                    obligation.cause.span, E0284,
1280                                                    "type annotations required: \
1281                                                     cannot resolve `{}`",
1282                                                    predicate);
1283                     self.note_obligation_cause(&mut err, obligation);
1284                     err.emit();
1285                 }
1286             }
1287         }
1288     }
1289
1290     /// Returns whether the trait predicate may apply for *some* assignment
1291     /// to the type parameters.
1292     fn predicate_can_apply(&self,
1293                            param_env: ty::ParamEnv<'tcx>,
1294                            pred: ty::PolyTraitRef<'tcx>)
1295                            -> bool {
1296         struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1297             infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1298             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1299         }
1300
1301         impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1302             fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1303
1304             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1305                 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
1306                     let infcx = self.infcx;
1307                     self.var_map.entry(ty).or_insert_with(||
1308                         infcx.next_ty_var(
1309                             TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1310                 } else {
1311                     ty.super_fold_with(self)
1312                 }
1313             }
1314         }
1315
1316         self.probe(|_| {
1317             let mut selcx = SelectionContext::new(self);
1318
1319             let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1320                 infcx: self,
1321                 var_map: FxHashMap()
1322             });
1323
1324             let cleaned_pred = super::project::normalize(
1325                 &mut selcx,
1326                 param_env,
1327                 ObligationCause::dummy(),
1328                 &cleaned_pred
1329             ).value;
1330
1331             let obligation = Obligation::new(
1332                 ObligationCause::dummy(),
1333                 param_env,
1334                 cleaned_pred.to_predicate()
1335             );
1336
1337             self.predicate_may_hold(&obligation)
1338         })
1339     }
1340
1341     fn note_obligation_cause<T>(&self,
1342                                 err: &mut DiagnosticBuilder,
1343                                 obligation: &Obligation<'tcx, T>)
1344         where T: fmt::Display
1345     {
1346         self.note_obligation_cause_code(err,
1347                                         &obligation.predicate,
1348                                         &obligation.cause.code,
1349                                         &mut vec![]);
1350     }
1351
1352     fn note_obligation_cause_code<T>(&self,
1353                                      err: &mut DiagnosticBuilder,
1354                                      predicate: &T,
1355                                      cause_code: &ObligationCauseCode<'tcx>,
1356                                      obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1357         where T: fmt::Display
1358     {
1359         let tcx = self.tcx;
1360         match *cause_code {
1361             ObligationCauseCode::ExprAssignable |
1362             ObligationCauseCode::MatchExpressionArm { .. } |
1363             ObligationCauseCode::IfExpression |
1364             ObligationCauseCode::IfExpressionWithNoElse |
1365             ObligationCauseCode::MainFunctionType |
1366             ObligationCauseCode::StartFunctionType |
1367             ObligationCauseCode::IntrinsicType |
1368             ObligationCauseCode::MethodReceiver |
1369             ObligationCauseCode::ReturnNoExpression |
1370             ObligationCauseCode::MiscObligation => {
1371             }
1372             ObligationCauseCode::SliceOrArrayElem => {
1373                 err.note("slice and array elements must have `Sized` type");
1374             }
1375             ObligationCauseCode::TupleElem => {
1376                 err.note("only the last element of a tuple may have a dynamically sized type");
1377             }
1378             ObligationCauseCode::ProjectionWf(data) => {
1379                 err.note(&format!("required so that the projection `{}` is well-formed",
1380                                   data));
1381             }
1382             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1383                 err.note(&format!("required so that reference `{}` does not outlive its referent",
1384                                   ref_ty));
1385             }
1386             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1387                 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1388                                    is satisfied",
1389                                   region, object_ty));
1390             }
1391             ObligationCauseCode::ItemObligation(item_def_id) => {
1392                 let item_name = tcx.item_path_str(item_def_id);
1393                 let msg = format!("required by `{}`", item_name);
1394                 if let Some(sp) = tcx.hir.span_if_local(item_def_id) {
1395                     let sp = tcx.sess.codemap().def_span(sp);
1396                     err.span_note(sp, &msg);
1397                 } else {
1398                     err.note(&msg);
1399                 }
1400             }
1401             ObligationCauseCode::ObjectCastObligation(object_ty) => {
1402                 err.note(&format!("required for the cast to the object type `{}`",
1403                                   self.ty_to_string(object_ty)));
1404             }
1405             ObligationCauseCode::RepeatVec => {
1406                 err.note("the `Copy` trait is required because the \
1407                           repeated element will be copied");
1408             }
1409             ObligationCauseCode::VariableType(_) => {
1410                 err.note("all local variables must have a statically known size");
1411             }
1412             ObligationCauseCode::SizedReturnType => {
1413                 err.note("the return type of a function must have a \
1414                           statically known size");
1415             }
1416             ObligationCauseCode::SizedYieldType => {
1417                 err.note("the yield type of a generator must have a \
1418                           statically known size");
1419             }
1420             ObligationCauseCode::AssignmentLhsSized => {
1421                 err.note("the left-hand-side of an assignment must have a statically known size");
1422             }
1423             ObligationCauseCode::TupleInitializerSized => {
1424                 err.note("tuples must have a statically known size to be initialized");
1425             }
1426             ObligationCauseCode::StructInitializerSized => {
1427                 err.note("structs must have a statically known size to be initialized");
1428             }
1429             ObligationCauseCode::FieldSized(ref item) => {
1430                 match *item {
1431                     AdtKind::Struct => {
1432                         err.note("only the last field of a struct may have a dynamically \
1433                                   sized type");
1434                     }
1435                     AdtKind::Union => {
1436                         err.note("no field of a union may have a dynamically sized type");
1437                     }
1438                     AdtKind::Enum => {
1439                         err.note("no field of an enum variant may have a dynamically sized type");
1440                     }
1441                 }
1442             }
1443             ObligationCauseCode::ConstSized => {
1444                 err.note("constant expressions must have a statically known size");
1445             }
1446             ObligationCauseCode::SharedStatic => {
1447                 err.note("shared static variables must have a type that implements `Sync`");
1448             }
1449             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1450                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1451                 let ty = parent_trait_ref.skip_binder().self_ty();
1452                 err.note(&format!("required because it appears within the type `{}`", ty));
1453                 obligated_types.push(ty);
1454
1455                 let parent_predicate = parent_trait_ref.to_predicate();
1456                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1457                     self.note_obligation_cause_code(err,
1458                                                     &parent_predicate,
1459                                                     &data.parent_code,
1460                                                     obligated_types);
1461                 }
1462             }
1463             ObligationCauseCode::ImplDerivedObligation(ref data) => {
1464                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1465                 err.note(
1466                     &format!("required because of the requirements on the impl of `{}` for `{}`",
1467                              parent_trait_ref,
1468                              parent_trait_ref.skip_binder().self_ty()));
1469                 let parent_predicate = parent_trait_ref.to_predicate();
1470                 self.note_obligation_cause_code(err,
1471                                             &parent_predicate,
1472                                             &data.parent_code,
1473                                             obligated_types);
1474             }
1475             ObligationCauseCode::CompareImplMethodObligation { .. } => {
1476                 err.note(
1477                     &format!("the requirement `{}` appears on the impl method \
1478                               but not on the corresponding trait method",
1479                              predicate));
1480             }
1481             ObligationCauseCode::ReturnType(_) |
1482             ObligationCauseCode::BlockTailExpression(_) => (),
1483         }
1484     }
1485
1486     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1487         let current_limit = self.tcx.sess.recursion_limit.get();
1488         let suggested_limit = current_limit * 2;
1489         err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1490                           suggested_limit));
1491     }
1492
1493     fn is_recursive_obligation(&self,
1494                                    obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1495                                    cause_code: &ObligationCauseCode<'tcx>) -> bool {
1496         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1497             let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1498             for obligated_type in obligated_types {
1499                 if obligated_type == &parent_trait_ref.skip_binder().self_ty() {
1500                     return true;
1501                 }
1502             }
1503         }
1504         return false;
1505     }
1506 }
1507
1508 /// Summarizes information
1509 pub enum ArgKind {
1510     /// An argument of non-tuple type. Parameters are (name, ty)
1511     Arg(String, String),
1512
1513     /// An argument of tuple type. For a "found" argument, the span is
1514     /// the locationo in the source of the pattern. For a "expected"
1515     /// argument, it will be None. The vector is a list of (name, ty)
1516     /// strings for the components of the tuple.
1517     Tuple(Option<Span>, Vec<(String, String)>),
1518 }
1519
1520 impl ArgKind {
1521     fn empty() -> ArgKind {
1522         ArgKind::Arg("_".to_owned(), "_".to_owned())
1523     }
1524
1525     /// Creates an `ArgKind` from the expected type of an
1526     /// argument. This has no name (`_`) and no source spans..
1527     pub fn from_expected_ty(t: Ty<'_>) -> ArgKind {
1528         match t.sty {
1529             ty::TyTuple(ref tys) => ArgKind::Tuple(
1530                 None,
1531                 tys.iter()
1532                    .map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
1533                    .collect::<Vec<_>>()
1534             ),
1535             _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
1536         }
1537     }
1538 }