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