]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
Auto merge of #60763 - matklad:tt-parser, r=petrochenkov
[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;
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, ExpnFormat};
40
41 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, '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 {
65                 format: ExpnFormat::CompilerDesugaring(_),
66                 def_site: Some(def_span),
67                 ..
68             }) = span.ctxt().outer().expn_info() {
69                 span = def_span;
70             }
71
72             error_map.entry(span).or_default().push(
73                 ErrorDescriptor {
74                     predicate: error.obligation.predicate.clone(),
75                     index: Some(index)
76                 }
77             );
78
79             self.reported_trait_errors.borrow_mut()
80                 .entry(span).or_default()
81                 .push(error.obligation.predicate.clone());
82         }
83
84         // We do this in 2 passes because we want to display errors in order, though
85         // maybe it *is* better to sort errors by span or something.
86         let mut is_suppressed = vec![false; errors.len()];
87         for (_, error_set) in error_map.iter() {
88             // We want to suppress "duplicate" errors with the same span.
89             for error in error_set {
90                 if let Some(index) = error.index {
91                     // Suppress errors that are either:
92                     // 1) strictly implied by another error.
93                     // 2) implied by an error with a smaller index.
94                     for error2 in error_set {
95                         if error2.index.map_or(false, |index2| is_suppressed[index2]) {
96                             // Avoid errors being suppressed by already-suppressed
97                             // errors, to prevent all errors from being suppressed
98                             // at once.
99                             continue
100                         }
101
102                         if self.error_implies(&error2.predicate, &error.predicate) &&
103                             !(error2.index >= error.index &&
104                               self.error_implies(&error.predicate, &error2.predicate))
105                         {
106                             info!("skipping {:?} (implied by {:?})", error, error2);
107                             is_suppressed[index] = true;
108                             break
109                         }
110                     }
111                 }
112             }
113         }
114
115         for (error, suppressed) in errors.iter().zip(is_suppressed) {
116             if !suppressed {
117                 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
118             }
119         }
120     }
121
122     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
123     // `error` occurring implies that `cond` occurs.
124     fn error_implies(&self,
125                      cond: &ty::Predicate<'tcx>,
126                      error: &ty::Predicate<'tcx>)
127                      -> bool
128     {
129         if cond == error {
130             return true
131         }
132
133         let (cond, error) = match (cond, error) {
134             (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
135                 => (cond, error),
136             _ => {
137                 // FIXME: make this work in other cases too.
138                 return false
139             }
140         };
141
142         for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
143             if let ty::Predicate::Trait(implication) = implication {
144                 let error = error.to_poly_trait_ref();
145                 let implication = implication.to_poly_trait_ref();
146                 // FIXME: I'm just not taking associated types at all here.
147                 // Eventually I'll need to implement param-env-aware
148                 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
149                 let param_env = ty::ParamEnv::empty();
150                 if self.can_sub(param_env, error, implication).is_ok() {
151                     debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
152                     return true
153                 }
154             }
155         }
156
157         false
158     }
159
160     fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
161                                 body_id: Option<hir::BodyId>,
162                                 fallback_has_occurred: bool) {
163         debug!("report_fulfillment_errors({:?})", error);
164         match error.code {
165             FulfillmentErrorCode::CodeSelectionError(ref e) => {
166                 self.report_selection_error(&error.obligation, e, fallback_has_occurred);
167             }
168             FulfillmentErrorCode::CodeProjectionError(ref e) => {
169                 self.report_projection_error(&error.obligation, e);
170             }
171             FulfillmentErrorCode::CodeAmbiguity => {
172                 self.maybe_report_ambiguity(&error.obligation, body_id);
173             }
174             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
175                 self.report_mismatched_types(&error.obligation.cause,
176                                              expected_found.expected,
177                                              expected_found.found,
178                                              err.clone())
179                     .emit();
180             }
181         }
182     }
183
184     fn report_projection_error(&self,
185                                obligation: &PredicateObligation<'tcx>,
186                                error: &MismatchedProjectionTypes<'tcx>)
187     {
188         let predicate =
189             self.resolve_type_vars_if_possible(&obligation.predicate);
190
191         if predicate.references_error() {
192             return
193         }
194
195         self.probe(|_| {
196             let err_buf;
197             let mut err = &error.err;
198             let mut values = None;
199
200             // try to find the mismatched types to report the error with.
201             //
202             // this can fail if the problem was higher-ranked, in which
203             // cause I have no idea for a good error message.
204             if let ty::Predicate::Projection(ref data) = predicate {
205                 let mut selcx = SelectionContext::new(self);
206                 let (data, _) = self.replace_bound_vars_with_fresh_vars(
207                     obligation.cause.span,
208                     infer::LateBoundRegionConversionTime::HigherRankedType,
209                     data
210                 );
211                 let mut obligations = vec![];
212                 let normalized_ty = super::normalize_projection_type(
213                     &mut selcx,
214                     obligation.param_env,
215                     data.projection_ty,
216                     obligation.cause.clone(),
217                     0,
218                     &mut obligations
219                 );
220                 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
221                                         .eq(normalized_ty, data.ty) {
222                     values = Some(infer::ValuePairs::Types(ExpectedFound {
223                         expected: normalized_ty,
224                         found: data.ty,
225                     }));
226                     err_buf = error;
227                     err = &err_buf;
228                 }
229             }
230
231             let msg = format!("type mismatch resolving `{}`", predicate);
232             let error_id = (DiagnosticMessageId::ErrorId(271),
233                             Some(obligation.cause.span), msg);
234             let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
235             if fresh {
236                 let mut diag = struct_span_err!(
237                     self.tcx.sess, obligation.cause.span, E0271,
238                     "type mismatch resolving `{}`", predicate
239                 );
240                 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
241                 self.note_obligation_cause(&mut diag, obligation);
242                 diag.emit();
243             }
244         });
245     }
246
247     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
248         /// returns the fuzzy category of a given type, or None
249         /// if the type can be equated to any type.
250         fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
251             match t.sty {
252                 ty::Bool => Some(0),
253                 ty::Char => Some(1),
254                 ty::Str => Some(2),
255                 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
256                 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
257                 ty::Ref(..) | ty::RawPtr(..) => Some(5),
258                 ty::Array(..) | ty::Slice(..) => Some(6),
259                 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
260                 ty::Dynamic(..) => Some(8),
261                 ty::Closure(..) => Some(9),
262                 ty::Tuple(..) => Some(10),
263                 ty::Projection(..) => Some(11),
264                 ty::Param(..) => Some(12),
265                 ty::Opaque(..) => Some(13),
266                 ty::Never => Some(14),
267                 ty::Adt(adt, ..) => match adt.adt_kind() {
268                     AdtKind::Struct => Some(15),
269                     AdtKind::Union => Some(16),
270                     AdtKind::Enum => Some(17),
271                 },
272                 ty::Generator(..) => Some(18),
273                 ty::Foreign(..) => Some(19),
274                 ty::GeneratorWitness(..) => Some(20),
275                 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
276                 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
277             }
278         }
279
280         match (type_category(a), type_category(b)) {
281             (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
282                 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
283                 _ => cat_a == cat_b
284             },
285             // infer and error can be equated to all types
286             _ => true
287         }
288     }
289
290     fn impl_similar_to(&self,
291                        trait_ref: ty::PolyTraitRef<'tcx>,
292                        obligation: &PredicateObligation<'tcx>)
293                        -> Option<DefId>
294     {
295         let tcx = self.tcx;
296         let param_env = obligation.param_env;
297         let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
298         let trait_self_ty = trait_ref.self_ty();
299
300         let mut self_match_impls = vec![];
301         let mut fuzzy_match_impls = vec![];
302
303         self.tcx.for_each_relevant_impl(
304             trait_ref.def_id, trait_self_ty, |def_id| {
305                 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
306                 let impl_trait_ref = tcx
307                     .impl_trait_ref(def_id)
308                     .unwrap()
309                     .subst(tcx, impl_substs);
310
311                 let impl_self_ty = impl_trait_ref.self_ty();
312
313                 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
314                     self_match_impls.push(def_id);
315
316                     if trait_ref.substs.types().skip(1)
317                         .zip(impl_trait_ref.substs.types().skip(1))
318                         .all(|(u,v)| self.fuzzy_match_tys(u, v))
319                     {
320                         fuzzy_match_impls.push(def_id);
321                     }
322                 }
323             });
324
325         let impl_def_id = if self_match_impls.len() == 1 {
326             self_match_impls[0]
327         } else if fuzzy_match_impls.len() == 1 {
328             fuzzy_match_impls[0]
329         } else {
330             return None
331         };
332
333         if tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented) {
334             Some(impl_def_id)
335         } else {
336             None
337         }
338     }
339
340     fn on_unimplemented_note(
341         &self,
342         trait_ref: ty::PolyTraitRef<'tcx>,
343         obligation: &PredicateObligation<'tcx>,
344     ) -> OnUnimplementedNote {
345         let def_id = self.impl_similar_to(trait_ref, obligation)
346             .unwrap_or_else(|| trait_ref.def_id());
347         let trait_ref = *trait_ref.skip_binder();
348
349         let mut flags = vec![];
350         match obligation.cause.code {
351             ObligationCauseCode::BuiltinDerivedObligation(..) |
352             ObligationCauseCode::ImplDerivedObligation(..) => {}
353             _ => {
354                 // this is a "direct", user-specified, rather than derived,
355                 // obligation.
356                 flags.push(("direct".to_owned(), None));
357             }
358         }
359
360         if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
361             // FIXME: maybe also have some way of handling methods
362             // from other traits? That would require name resolution,
363             // which we might want to be some sort of hygienic.
364             //
365             // Currently I'm leaving it for what I need for `try`.
366             if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
367                 let method = self.tcx.item_name(item);
368                 flags.push(("from_method".to_owned(), None));
369                 flags.push(("from_method".to_owned(), Some(method.to_string())));
370             }
371         }
372         if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
373             flags.push(("parent_trait".to_owned(), Some(t)));
374         }
375
376         if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
377             flags.push(("from_desugaring".to_owned(), None));
378             flags.push(("from_desugaring".to_owned(), Some(k.name().to_string())));
379         }
380         let generics = self.tcx.generics_of(def_id);
381         let self_ty = trait_ref.self_ty();
382         // This is also included through the generics list as `Self`,
383         // but the parser won't allow you to use it
384         flags.push(("_Self".to_owned(), Some(self_ty.to_string())));
385         if let Some(def) = self_ty.ty_adt_def() {
386             // We also want to be able to select self's original
387             // signature with no type arguments resolved
388             flags.push(("_Self".to_owned(), Some(self.tcx.type_of(def.did).to_string())));
389         }
390
391         for param in generics.params.iter() {
392             let value = match param.kind {
393                 GenericParamDefKind::Type { .. } |
394                 GenericParamDefKind::Const => {
395                     trait_ref.substs[param.index as usize].to_string()
396                 },
397                 GenericParamDefKind::Lifetime => continue,
398             };
399             let name = param.name.to_string();
400             flags.push((name, Some(value)));
401         }
402
403         if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
404             flags.push(("crate_local".to_owned(), None));
405         }
406
407         // Allow targeting all integers using `{integral}`, even if the exact type was resolved
408         if self_ty.is_integral() {
409             flags.push(("_Self".to_owned(), Some("{integral}".to_owned())));
410         }
411
412         if let ty::Array(aty, len) = self_ty.sty {
413             flags.push(("_Self".to_owned(), Some("[]".to_owned())));
414             flags.push(("_Self".to_owned(), Some(format!("[{}]", aty))));
415             if let Some(def) = aty.ty_adt_def() {
416                 // We also want to be able to select the array's type's original
417                 // signature with no type arguments resolved
418                 flags.push((
419                     "_Self".to_owned(),
420                     Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
421                 ));
422                 let tcx = self.tcx;
423                 if let Some(len) = len.assert_usize(tcx) {
424                     flags.push((
425                         "_Self".to_owned(),
426                         Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
427                     ));
428                 } else {
429                     flags.push((
430                         "_Self".to_owned(),
431                         Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
432                     ));
433                 }
434             }
435         }
436
437         if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
438             self.tcx, trait_ref.def_id, def_id
439         ) {
440             command.evaluate(self.tcx, trait_ref, &flags[..])
441         } else {
442             OnUnimplementedNote::empty()
443         }
444     }
445
446     fn find_similar_impl_candidates(&self,
447                                     trait_ref: ty::PolyTraitRef<'tcx>)
448                                     -> Vec<ty::TraitRef<'tcx>>
449     {
450         let simp = fast_reject::simplify_type(self.tcx,
451                                               trait_ref.skip_binder().self_ty(),
452                                               true);
453         let all_impls = self.tcx.all_impls(trait_ref.def_id());
454
455         match simp {
456             Some(simp) => all_impls.iter().filter_map(|&def_id| {
457                 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
458                 let imp_simp = fast_reject::simplify_type(self.tcx,
459                                                           imp.self_ty(),
460                                                           true);
461                 if let Some(imp_simp) = imp_simp {
462                     if simp != imp_simp {
463                         return None
464                     }
465                 }
466
467                 Some(imp)
468             }).collect(),
469             None => all_impls.iter().map(|&def_id|
470                 self.tcx.impl_trait_ref(def_id).unwrap()
471             ).collect()
472         }
473     }
474
475     fn report_similar_impl_candidates(&self,
476                                       impl_candidates: Vec<ty::TraitRef<'tcx>>,
477                                       err: &mut DiagnosticBuilder<'_>)
478     {
479         if impl_candidates.is_empty() {
480             return;
481         }
482
483         let len = impl_candidates.len();
484         let end = if impl_candidates.len() <= 5 {
485             impl_candidates.len()
486         } else {
487             4
488         };
489
490         let normalize = |candidate| self.tcx.global_tcx().infer_ctxt().enter(|ref infcx| {
491             let normalized = infcx
492                 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
493                 .normalize(candidate)
494                 .ok();
495             match normalized {
496                 Some(normalized) => format!("\n  {:?}", normalized.value),
497                 None => format!("\n  {:?}", candidate),
498             }
499         });
500
501         // Sort impl candidates so that ordering is consistent for UI tests.
502         let mut normalized_impl_candidates = impl_candidates
503             .iter()
504             .map(normalize)
505             .collect::<Vec<String>>();
506
507         // Sort before taking the `..end` range,
508         // because the ordering of `impl_candidates` may not be deterministic:
509         // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
510         normalized_impl_candidates.sort();
511
512         err.help(&format!("the following implementations were found:{}{}",
513                           normalized_impl_candidates[..end].join(""),
514                           if len > 5 {
515                               format!("\nand {} others", len - 4)
516                           } else {
517                               String::new()
518                           }
519                           ));
520     }
521
522     /// Reports that an overflow has occurred and halts compilation. We
523     /// halt compilation unconditionally because it is important that
524     /// overflows never be masked -- they basically represent computations
525     /// whose result could not be truly determined and thus we can't say
526     /// if the program type checks or not -- and they are unusual
527     /// occurrences in any case.
528     pub fn report_overflow_error<T>(&self,
529                                     obligation: &Obligation<'tcx, T>,
530                                     suggest_increasing_limit: bool) -> !
531         where T: fmt::Display + TypeFoldable<'tcx>
532     {
533         let predicate =
534             self.resolve_type_vars_if_possible(&obligation.predicate);
535         let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
536                                        "overflow evaluating the requirement `{}`",
537                                        predicate);
538
539         if suggest_increasing_limit {
540             self.suggest_new_overflow_limit(&mut err);
541         }
542
543         self.note_obligation_cause(&mut err, obligation);
544
545         err.emit();
546         self.tcx.sess.abort_if_errors();
547         bug!();
548     }
549
550     /// Reports that a cycle was detected which led to overflow and halts
551     /// compilation. This is equivalent to `report_overflow_error` except
552     /// that we can give a more helpful error message (and, in particular,
553     /// we do not suggest increasing the overflow limit, which is not
554     /// going to help).
555     pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
556         let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
557         assert!(cycle.len() > 0);
558
559         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
560
561         self.report_overflow_error(&cycle[0], false);
562     }
563
564     pub fn report_extra_impl_obligation(&self,
565                                         error_span: Span,
566                                         item_name: ast::Name,
567                                         _impl_item_def_id: DefId,
568                                         trait_item_def_id: DefId,
569                                         requirement: &dyn fmt::Display)
570                                         -> DiagnosticBuilder<'tcx>
571     {
572         let msg = "impl has stricter requirements than trait";
573         let sp = self.tcx.sess.source_map().def_span(error_span);
574
575         let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
576
577         if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
578             let span = self.tcx.sess.source_map().def_span(trait_item_span);
579             err.span_label(span, format!("definition of `{}` from trait", item_name));
580         }
581
582         err.span_label(sp, format!("impl has extra requirement {}", requirement));
583
584         err
585     }
586
587
588     /// Gets the parent trait chain start
589     fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
590         match code {
591             &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
592                 let parent_trait_ref = self.resolve_type_vars_if_possible(
593                     &data.parent_trait_ref);
594                 match self.get_parent_trait_ref(&data.parent_code) {
595                     Some(t) => Some(t),
596                     None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
597                 }
598             }
599             _ => None,
600         }
601     }
602
603     pub fn report_selection_error(
604         &self,
605         obligation: &PredicateObligation<'tcx>,
606         error: &SelectionError<'tcx>,
607         fallback_has_occurred: bool,
608     ) {
609         let span = obligation.cause.span;
610
611         let mut err = match *error {
612             SelectionError::Unimplemented => {
613                 if let ObligationCauseCode::CompareImplMethodObligation {
614                     item_name, impl_item_def_id, trait_item_def_id,
615                 } = obligation.cause.code {
616                     self.report_extra_impl_obligation(
617                         span,
618                         item_name,
619                         impl_item_def_id,
620                         trait_item_def_id,
621                         &format!("`{}`", obligation.predicate))
622                         .emit();
623                     return;
624                 }
625                 match obligation.predicate {
626                     ty::Predicate::Trait(ref trait_predicate) => {
627                         let trait_predicate =
628                             self.resolve_type_vars_if_possible(trait_predicate);
629
630                         if self.tcx.sess.has_errors() && trait_predicate.references_error() {
631                             return;
632                         }
633                         let trait_ref = trait_predicate.to_poly_trait_ref();
634                         let (post_message, pre_message) =
635                             self.get_parent_trait_ref(&obligation.cause.code)
636                                 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
637                             .unwrap_or_default();
638
639                         let OnUnimplementedNote { message, label, note }
640                             = self.on_unimplemented_note(trait_ref, obligation);
641                         let have_alt_message = message.is_some() || label.is_some();
642                         let is_try = self.tcx.sess.source_map().span_to_snippet(span)
643                             .map(|s| &s == "?")
644                             .unwrap_or(false);
645                         let is_from = format!("{}", trait_ref).starts_with("std::convert::From<");
646                         let message = if is_try && is_from {
647                             Some(format!(
648                                 "`?` couldn't convert the error to `{}`",
649                                 trait_ref.self_ty(),
650                             ))
651                         } else {
652                             message
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_type_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_type_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_type_vars_if_possible(&*found_trait_ref);
853                 let expected_trait_ref = self.resolve_type_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(_) => {
915                 self.tcx.sess.delay_span_bug(span, "constant in type had an ignored error");
916                 return;
917             }
918
919             Overflow => {
920                 bug!("overflow should be handled before the `report_selection_error` path");
921             }
922         };
923         self.note_obligation_cause(&mut err, obligation);
924         err.emit();
925     }
926
927     /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
928     /// suggestion to borrow the initializer in order to use have a slice instead.
929     fn suggest_borrow_on_unsized_slice(
930         &self,
931         code: &ObligationCauseCode<'tcx>,
932         err: &mut DiagnosticBuilder<'tcx>,
933     ) {
934         if let &ObligationCauseCode::VariableType(node_id) = code {
935             let parent_node = self.tcx.hir().get_parent_node(node_id);
936             if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
937                 if let Some(ref expr) = local.init {
938                     if let hir::ExprKind::Index(_, _) = expr.node {
939                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
940                             err.span_suggestion(
941                                 expr.span,
942                                 "consider borrowing here",
943                                 format!("&{}", snippet),
944                                 Applicability::MachineApplicable
945                             );
946                         }
947                     }
948                 }
949             }
950         }
951     }
952
953     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
954     /// suggest removing these references until we reach a type that implements the trait.
955     fn suggest_remove_reference(
956         &self,
957         obligation: &PredicateObligation<'tcx>,
958         err: &mut DiagnosticBuilder<'tcx>,
959         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
960     ) {
961         let trait_ref = trait_ref.skip_binder();
962         let span = obligation.cause.span;
963
964         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
965             let refs_number = snippet.chars()
966                 .filter(|c| !c.is_whitespace())
967                 .take_while(|c| *c == '&')
968                 .count();
969
970             let mut trait_type = trait_ref.self_ty();
971
972             for refs_remaining in 0..refs_number {
973                 if let ty::Ref(_, t_type, _) = trait_type.sty {
974                     trait_type = t_type;
975
976                     let substs = self.tcx.mk_substs_trait(trait_type, &[]);
977                     let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
978                     let new_obligation = Obligation::new(ObligationCause::dummy(),
979                                                          obligation.param_env,
980                                                          new_trait_ref.to_predicate());
981
982                     if self.predicate_may_hold(&new_obligation) {
983                         let sp = self.tcx.sess.source_map()
984                             .span_take_while(span, |c| c.is_whitespace() || *c == '&');
985
986                         let remove_refs = refs_remaining + 1;
987                         let format_str = format!("consider removing {} leading `&`-references",
988                                                  remove_refs);
989
990                         err.span_suggestion_short(
991                             sp, &format_str, String::new(), Applicability::MachineApplicable
992                         );
993                         break;
994                     }
995                 } else {
996                     break;
997                 }
998             }
999         }
1000     }
1001
1002     fn suggest_semicolon_removal(
1003         &self,
1004         obligation: &PredicateObligation<'tcx>,
1005         err: &mut DiagnosticBuilder<'tcx>,
1006         span: Span,
1007         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1008     ) {
1009         let hir = self.tcx.hir();
1010         let parent_node = hir.get_parent_node(
1011             hir.hir_to_node_id(obligation.cause.body_id),
1012         );
1013         let node = hir.find(parent_node);
1014         if let Some(hir::Node::Item(hir::Item {
1015             node: hir::ItemKind::Fn(decl, _, _, body_id),
1016             ..
1017         })) = node {
1018             let body = hir.body(*body_id);
1019             if let hir::ExprKind::Block(blk, _) = &body.value.node {
1020                 if decl.output.span().overlaps(span) && blk.expr.is_none() &&
1021                     "()" == &trait_ref.self_ty().to_string()
1022                 {
1023                     // FIXME(estebank): When encountering a method with a trait
1024                     // bound not satisfied in the return type with a body that has
1025                     // no return, suggest removal of semicolon on last statement.
1026                     // Once that is added, close #54771.
1027                     if let Some(ref stmt) = blk.stmts.last() {
1028                         let sp = self.tcx.sess.source_map().end_point(stmt.span);
1029                         err.span_label(sp, "consider removing this semicolon");
1030                     }
1031                 }
1032             }
1033         }
1034     }
1035
1036     /// Given some node representing a fn-like thing in the HIR map,
1037     /// returns a span and `ArgKind` information that describes the
1038     /// arguments it expects. This can be supplied to
1039     /// `report_arg_count_mismatch`.
1040     pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1041         match node {
1042             Node::Expr(&hir::Expr {
1043                 node: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1044                 ..
1045             }) => {
1046                 (self.tcx.sess.source_map().def_span(span), self.tcx.hir().body(id).arguments.iter()
1047                     .map(|arg| {
1048                         if let hir::Pat {
1049                             node: hir::PatKind::Tuple(args, _),
1050                             span,
1051                             ..
1052                         } = arg.pat.clone().into_inner() {
1053                             ArgKind::Tuple(
1054                                 Some(span),
1055                                 args.iter().map(|pat| {
1056                                     let snippet = self.tcx.sess.source_map()
1057                                         .span_to_snippet(pat.span).unwrap();
1058                                     (snippet, "_".to_owned())
1059                                 }).collect::<Vec<_>>(),
1060                             )
1061                         } else {
1062                             let name = self.tcx.sess.source_map()
1063                                 .span_to_snippet(arg.pat.span).unwrap();
1064                             ArgKind::Arg(name, "_".to_owned())
1065                         }
1066                     })
1067                     .collect::<Vec<ArgKind>>())
1068             }
1069             Node::Item(&hir::Item {
1070                 span,
1071                 node: hir::ItemKind::Fn(ref decl, ..),
1072                 ..
1073             }) |
1074             Node::ImplItem(&hir::ImplItem {
1075                 span,
1076                 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1077                 ..
1078             }) |
1079             Node::TraitItem(&hir::TraitItem {
1080                 span,
1081                 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1082                 ..
1083             }) => {
1084                 (self.tcx.sess.source_map().def_span(span), decl.inputs.iter()
1085                         .map(|arg| match arg.clone().node {
1086                     hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1087                         Some(arg.span),
1088                         vec![("_".to_owned(), "_".to_owned()); tys.len()]
1089                     ),
1090                     _ => ArgKind::empty()
1091                 }).collect::<Vec<ArgKind>>())
1092             }
1093             Node::Ctor(ref variant_data) => {
1094                 let span = variant_data.ctor_hir_id()
1095                     .map(|hir_id| self.tcx.hir().span_by_hir_id(hir_id))
1096                     .unwrap_or(DUMMY_SP);
1097                 let span = self.tcx.sess.source_map().def_span(span);
1098
1099                 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1100             }
1101             _ => panic!("non-FnLike node found: {:?}", node),
1102         }
1103     }
1104
1105     /// Reports an error when the number of arguments needed by a
1106     /// trait match doesn't match the number that the expression
1107     /// provides.
1108     pub fn report_arg_count_mismatch(
1109         &self,
1110         span: Span,
1111         found_span: Option<Span>,
1112         expected_args: Vec<ArgKind>,
1113         found_args: Vec<ArgKind>,
1114         is_closure: bool,
1115     ) -> DiagnosticBuilder<'tcx> {
1116         let kind = if is_closure { "closure" } else { "function" };
1117
1118         let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1119             let arg_length = arguments.len();
1120             let distinct = match &other[..] {
1121                 &[ArgKind::Tuple(..)] => true,
1122                 _ => false,
1123             };
1124             match (arg_length, arguments.get(0)) {
1125                 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1126                     format!("a single {}-tuple as argument", fields.len())
1127                 }
1128                 _ => format!("{} {}argument{}",
1129                              arg_length,
1130                              if distinct && arg_length > 1 { "distinct " } else { "" },
1131                              if arg_length == 1 { "" } else { "s" }),
1132             }
1133         };
1134
1135         let expected_str = args_str(&expected_args, &found_args);
1136         let found_str = args_str(&found_args, &expected_args);
1137
1138         let mut err = struct_span_err!(
1139             self.tcx.sess,
1140             span,
1141             E0593,
1142             "{} is expected to take {}, but it takes {}",
1143             kind,
1144             expected_str,
1145             found_str,
1146         );
1147
1148         err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1149
1150         if let Some(found_span) = found_span {
1151             err.span_label(found_span, format!("takes {}", found_str));
1152
1153             // move |_| { ... }
1154             // ^^^^^^^^-- def_span
1155             //
1156             // move |_| { ... }
1157             // ^^^^^-- prefix
1158             let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1159             // move |_| { ... }
1160             //      ^^^-- pipe_span
1161             let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1162                 span
1163             } else {
1164                 found_span
1165             };
1166
1167             // Suggest to take and ignore the arguments with expected_args_length `_`s if
1168             // found arguments is empty (assume the user just wants to ignore args in this case).
1169             // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1170             if found_args.is_empty() && is_closure {
1171                 let underscores = vec!["_"; expected_args.len()].join(", ");
1172                 err.span_suggestion(
1173                     pipe_span,
1174                     &format!(
1175                         "consider changing the closure to take and ignore the expected argument{}",
1176                         if expected_args.len() < 2 {
1177                             ""
1178                         } else {
1179                             "s"
1180                         }
1181                     ),
1182                     format!("|{}|", underscores),
1183                     Applicability::MachineApplicable,
1184                 );
1185             }
1186
1187             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1188                 if fields.len() == expected_args.len() {
1189                     let sugg = fields.iter()
1190                         .map(|(name, _)| name.to_owned())
1191                         .collect::<Vec<String>>()
1192                         .join(", ");
1193                     err.span_suggestion(
1194                         found_span,
1195                         "change the closure to take multiple arguments instead of a single tuple",
1196                         format!("|{}|", sugg),
1197                         Applicability::MachineApplicable,
1198                     );
1199                 }
1200             }
1201             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1202                 if fields.len() == found_args.len() && is_closure {
1203                     let sugg = format!(
1204                         "|({}){}|",
1205                         found_args.iter()
1206                             .map(|arg| match arg {
1207                                 ArgKind::Arg(name, _) => name.to_owned(),
1208                                 _ => "_".to_owned(),
1209                             })
1210                             .collect::<Vec<String>>()
1211                             .join(", "),
1212                         // add type annotations if available
1213                         if found_args.iter().any(|arg| match arg {
1214                             ArgKind::Arg(_, ty) => ty != "_",
1215                             _ => false,
1216                         }) {
1217                             format!(": ({})",
1218                                     fields.iter()
1219                                         .map(|(_, ty)| ty.to_owned())
1220                                         .collect::<Vec<String>>()
1221                                         .join(", "))
1222                         } else {
1223                             String::new()
1224                         },
1225                     );
1226                     err.span_suggestion(
1227                         found_span,
1228                         "change the closure to accept a tuple instead of individual arguments",
1229                         sugg,
1230                         Applicability::MachineApplicable,
1231                     );
1232                 }
1233             }
1234         }
1235
1236         err
1237     }
1238
1239     fn report_closure_arg_mismatch(&self,
1240                            span: Span,
1241                            found_span: Option<Span>,
1242                            expected_ref: ty::PolyTraitRef<'tcx>,
1243                            found: ty::PolyTraitRef<'tcx>)
1244         -> DiagnosticBuilder<'tcx>
1245     {
1246         fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1247                                                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<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, '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, 'gcx, 'tcx> InferCtxt<'a, 'gcx, '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_type_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(&self,
1445                            param_env: ty::ParamEnv<'tcx>,
1446                            pred: ty::PolyTraitRef<'tcx>)
1447                            -> bool {
1448         struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1449             infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1450             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1451         }
1452
1453         impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1454             fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1455
1456             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1457                 if let ty::Param(ty::ParamTy {name, .. }) = ty.sty {
1458                     let infcx = self.infcx;
1459                     self.var_map.entry(ty).or_insert_with(||
1460                         infcx.next_ty_var(
1461                             TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1462                 } else {
1463                     ty.super_fold_with(self)
1464                 }
1465             }
1466         }
1467
1468         self.probe(|_| {
1469             let mut selcx = SelectionContext::new(self);
1470
1471             let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1472                 infcx: self,
1473                 var_map: Default::default()
1474             });
1475
1476             let cleaned_pred = super::project::normalize(
1477                 &mut selcx,
1478                 param_env,
1479                 ObligationCause::dummy(),
1480                 &cleaned_pred
1481             ).value;
1482
1483             let obligation = Obligation::new(
1484                 ObligationCause::dummy(),
1485                 param_env,
1486                 cleaned_pred.to_predicate()
1487             );
1488
1489             self.predicate_may_hold(&obligation)
1490         })
1491     }
1492
1493     fn note_obligation_cause<T>(&self,
1494                                 err: &mut DiagnosticBuilder<'_>,
1495                                 obligation: &Obligation<'tcx, T>)
1496         where T: fmt::Display
1497     {
1498         self.note_obligation_cause_code(err,
1499                                         &obligation.predicate,
1500                                         &obligation.cause.code,
1501                                         &mut vec![]);
1502     }
1503
1504     fn note_obligation_cause_code<T>(&self,
1505                                      err: &mut DiagnosticBuilder<'_>,
1506                                      predicate: &T,
1507                                      cause_code: &ObligationCauseCode<'tcx>,
1508                                      obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1509         where T: fmt::Display
1510     {
1511         let tcx = self.tcx;
1512         match *cause_code {
1513             ObligationCauseCode::ExprAssignable |
1514             ObligationCauseCode::MatchExpressionArm { .. } |
1515             ObligationCauseCode::MatchExpressionArmPattern { .. } |
1516             ObligationCauseCode::IfExpression { .. } |
1517             ObligationCauseCode::IfExpressionWithNoElse |
1518             ObligationCauseCode::MainFunctionType |
1519             ObligationCauseCode::StartFunctionType |
1520             ObligationCauseCode::IntrinsicType |
1521             ObligationCauseCode::MethodReceiver |
1522             ObligationCauseCode::ReturnNoExpression |
1523             ObligationCauseCode::MiscObligation => {}
1524             ObligationCauseCode::SliceOrArrayElem => {
1525                 err.note("slice and array elements must have `Sized` type");
1526             }
1527             ObligationCauseCode::TupleElem => {
1528                 err.note("only the last element of a tuple may have a dynamically sized type");
1529             }
1530             ObligationCauseCode::ProjectionWf(data) => {
1531                 err.note(&format!("required so that the projection `{}` is well-formed",
1532                                   data));
1533             }
1534             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1535                 err.note(&format!("required so that reference `{}` does not outlive its referent",
1536                                   ref_ty));
1537             }
1538             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1539                 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1540                                    is satisfied",
1541                                   region, object_ty));
1542             }
1543             ObligationCauseCode::ItemObligation(item_def_id) => {
1544                 let item_name = tcx.def_path_str(item_def_id);
1545                 let msg = format!("required by `{}`", item_name);
1546
1547                 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1548                     let sp = tcx.sess.source_map().def_span(sp);
1549                     err.span_note(sp, &msg);
1550                 } else {
1551                     err.note(&msg);
1552                 }
1553             }
1554             ObligationCauseCode::ObjectCastObligation(object_ty) => {
1555                 err.note(&format!("required for the cast to the object type `{}`",
1556                                   self.ty_to_string(object_ty)));
1557             }
1558             ObligationCauseCode::RepeatVec => {
1559                 err.note("the `Copy` trait is required because the \
1560                           repeated element will be copied");
1561             }
1562             ObligationCauseCode::VariableType(_) => {
1563                 err.note("all local variables must have a statically known size");
1564                 if !self.tcx.features().unsized_locals {
1565                     err.help("unsized locals are gated as an unstable feature");
1566                 }
1567             }
1568             ObligationCauseCode::SizedArgumentType => {
1569                 err.note("all function arguments 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::SizedReturnType => {
1575                 err.note("the return type of a function must have a \
1576                           statically known size");
1577             }
1578             ObligationCauseCode::SizedYieldType => {
1579                 err.note("the yield type of a generator must have a \
1580                           statically known size");
1581             }
1582             ObligationCauseCode::AssignmentLhsSized => {
1583                 err.note("the left-hand-side of an assignment must have a statically known size");
1584             }
1585             ObligationCauseCode::TupleInitializerSized => {
1586                 err.note("tuples must have a statically known size to be initialized");
1587             }
1588             ObligationCauseCode::StructInitializerSized => {
1589                 err.note("structs must have a statically known size to be initialized");
1590             }
1591             ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
1592                 match *item {
1593                     AdtKind::Struct => {
1594                         if last {
1595                             err.note("the last field of a packed struct may only have a \
1596                                       dynamically sized type if it does not need drop to be run");
1597                         } else {
1598                             err.note("only the last field of a struct may have a dynamically \
1599                                       sized type");
1600                         }
1601                     }
1602                     AdtKind::Union => {
1603                         err.note("no field of a union may have a dynamically sized type");
1604                     }
1605                     AdtKind::Enum => {
1606                         err.note("no field of an enum variant may have a dynamically sized type");
1607                     }
1608                 }
1609             }
1610             ObligationCauseCode::ConstSized => {
1611                 err.note("constant expressions must have a statically known size");
1612             }
1613             ObligationCauseCode::SharedStatic => {
1614                 err.note("shared static variables must have a type that implements `Sync`");
1615             }
1616             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1617                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1618                 let ty = parent_trait_ref.skip_binder().self_ty();
1619                 err.note(&format!("required because it appears within the type `{}`", ty));
1620                 obligated_types.push(ty);
1621
1622                 let parent_predicate = parent_trait_ref.to_predicate();
1623                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1624                     self.note_obligation_cause_code(err,
1625                                                     &parent_predicate,
1626                                                     &data.parent_code,
1627                                                     obligated_types);
1628                 }
1629             }
1630             ObligationCauseCode::ImplDerivedObligation(ref data) => {
1631                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1632                 err.note(
1633                     &format!("required because of the requirements on the impl of `{}` for `{}`",
1634                              parent_trait_ref,
1635                              parent_trait_ref.skip_binder().self_ty()));
1636                 let parent_predicate = parent_trait_ref.to_predicate();
1637                 self.note_obligation_cause_code(err,
1638                                                 &parent_predicate,
1639                                                 &data.parent_code,
1640                                                 obligated_types);
1641             }
1642             ObligationCauseCode::CompareImplMethodObligation { .. } => {
1643                 err.note(
1644                     &format!("the requirement `{}` appears on the impl method \
1645                               but not on the corresponding trait method",
1646                              predicate));
1647             }
1648             ObligationCauseCode::ReturnType(_) |
1649             ObligationCauseCode::BlockTailExpression(_) => (),
1650             ObligationCauseCode::TrivialBound => {
1651                 err.help("see issue #48214");
1652                 if tcx.sess.opts.unstable_features.is_nightly_build() {
1653                     err.help("add #![feature(trivial_bounds)] to the \
1654                               crate attributes to enable",
1655                     );
1656                 }
1657             }
1658         }
1659     }
1660
1661     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1662         let current_limit = self.tcx.sess.recursion_limit.get();
1663         let suggested_limit = current_limit * 2;
1664         err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1665                           suggested_limit));
1666     }
1667
1668     fn is_recursive_obligation(&self,
1669                                obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1670                                cause_code: &ObligationCauseCode<'tcx>) -> bool {
1671         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1672             let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1673
1674             if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1675                 return true;
1676             }
1677         }
1678         false
1679     }
1680 }
1681
1682 /// Summarizes information
1683 #[derive(Clone)]
1684 pub enum ArgKind {
1685     /// An argument of non-tuple type. Parameters are (name, ty)
1686     Arg(String, String),
1687
1688     /// An argument of tuple type. For a "found" argument, the span is
1689     /// the locationo in the source of the pattern. For a "expected"
1690     /// argument, it will be None. The vector is a list of (name, ty)
1691     /// strings for the components of the tuple.
1692     Tuple(Option<Span>, Vec<(String, String)>),
1693 }
1694
1695 impl ArgKind {
1696     fn empty() -> ArgKind {
1697         ArgKind::Arg("_".to_owned(), "_".to_owned())
1698     }
1699
1700     /// Creates an `ArgKind` from the expected type of an
1701     /// argument. It has no name (`_`) and an optional source span.
1702     pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1703         match t.sty {
1704             ty::Tuple(ref tys) => ArgKind::Tuple(
1705                 span,
1706                 tys.iter()
1707                    .map(|ty| ("_".to_owned(), ty.to_string()))
1708                    .collect::<Vec<_>>()
1709             ),
1710             _ => ArgKind::Arg("_".to_owned(), t.to_string()),
1711         }
1712     }
1713 }