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