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