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