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