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