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