]> git.lizzy.rs Git - rust.git/blob - src/librustc_trait_selection/traits/error_reporting/mod.rs
ad6e81ed3e8893610295f83885fcb680308f4312
[rust.git] / src / librustc_trait_selection / traits / error_reporting / mod.rs
1 pub mod on_unimplemented;
2 pub mod suggestions;
3
4 use super::{
5     ConstEvalFailure, EvaluationResult, FulfillmentError, FulfillmentErrorCode,
6     MismatchedProjectionTypes, Obligation, ObligationCause, ObligationCauseCode,
7     OnUnimplementedDirective, OnUnimplementedNote, OutputTypeParameterMismatch, Overflow,
8     PredicateObligation, SelectionContext, SelectionError, TraitNotObjectSafe,
9 };
10
11 use crate::infer::error_reporting::{TyCategory, TypeAnnotationNeeded as ErrorCode};
12 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
13 use crate::infer::{self, InferCtxt, TyCtxtInferExt};
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorReported};
16 use rustc_hir as hir;
17 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
18 use rustc_hir::intravisit::Visitor;
19 use rustc_hir::Node;
20 use rustc_middle::mir::interpret::ErrorHandled;
21 use rustc_middle::ty::error::ExpectedFound;
22 use rustc_middle::ty::fold::TypeFolder;
23 use rustc_middle::ty::subst::GenericArgKind;
24 use rustc_middle::ty::{
25     self, fast_reject, AdtKind, SubtypePredicate, ToPolyTraitRef, ToPredicate, Ty, TyCtxt,
26     TypeFoldable, WithConstness,
27 };
28 use rustc_session::DiagnosticMessageId;
29 use rustc_span::{ExpnKind, MultiSpan, Span, DUMMY_SP};
30 use std::fmt;
31
32 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
33 use crate::traits::query::normalize::AtExt as _;
34 use on_unimplemented::InferCtxtExt as _;
35 use suggestions::InferCtxtExt as _;
36
37 pub use rustc_infer::traits::error_reporting::*;
38
39 pub trait InferCtxtExt<'tcx> {
40     fn report_fulfillment_errors(
41         &self,
42         errors: &[FulfillmentError<'tcx>],
43         body_id: Option<hir::BodyId>,
44         fallback_has_occurred: bool,
45     );
46
47     fn report_overflow_error<T>(
48         &self,
49         obligation: &Obligation<'tcx, T>,
50         suggest_increasing_limit: bool,
51     ) -> !
52     where
53         T: fmt::Display + TypeFoldable<'tcx>;
54
55     fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !;
56
57     fn report_selection_error(
58         &self,
59         obligation: &PredicateObligation<'tcx>,
60         error: &SelectionError<'tcx>,
61         fallback_has_occurred: bool,
62         points_at_arg: bool,
63     );
64
65     /// Given some node representing a fn-like thing in the HIR map,
66     /// returns a span and `ArgKind` information that describes the
67     /// arguments it expects. This can be supplied to
68     /// `report_arg_count_mismatch`.
69     fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)>;
70
71     /// Reports an error when the number of arguments needed by a
72     /// trait match doesn't match the number that the expression
73     /// provides.
74     fn report_arg_count_mismatch(
75         &self,
76         span: Span,
77         found_span: Option<Span>,
78         expected_args: Vec<ArgKind>,
79         found_args: Vec<ArgKind>,
80         is_closure: bool,
81     ) -> DiagnosticBuilder<'tcx>;
82 }
83
84 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
85     fn report_fulfillment_errors(
86         &self,
87         errors: &[FulfillmentError<'tcx>],
88         body_id: Option<hir::BodyId>,
89         fallback_has_occurred: bool,
90     ) {
91         #[derive(Debug)]
92         struct ErrorDescriptor<'tcx> {
93             predicate: ty::Predicate<'tcx>,
94             index: Option<usize>, // None if this is an old error
95         }
96
97         let mut error_map: FxHashMap<_, Vec<_>> = self
98             .reported_trait_errors
99             .borrow()
100             .iter()
101             .map(|(&span, predicates)| {
102                 (
103                     span,
104                     predicates
105                         .iter()
106                         .map(|&predicate| ErrorDescriptor { predicate, index: None })
107                         .collect(),
108                 )
109             })
110             .collect();
111
112         for (index, error) in errors.iter().enumerate() {
113             // We want to ignore desugarings here: spans are equivalent even
114             // if one is the result of a desugaring and the other is not.
115             let mut span = error.obligation.cause.span;
116             let expn_data = span.ctxt().outer_expn_data();
117             if let ExpnKind::Desugaring(_) = expn_data.kind {
118                 span = expn_data.call_site;
119             }
120
121             error_map.entry(span).or_default().push(ErrorDescriptor {
122                 predicate: error.obligation.predicate,
123                 index: Some(index),
124             });
125
126             self.reported_trait_errors
127                 .borrow_mut()
128                 .entry(span)
129                 .or_default()
130                 .push(error.obligation.predicate);
131         }
132
133         // We do this in 2 passes because we want to display errors in order, though
134         // maybe it *is* better to sort errors by span or something.
135         let mut is_suppressed = vec![false; errors.len()];
136         for (_, error_set) in error_map.iter() {
137             // We want to suppress "duplicate" errors with the same span.
138             for error in error_set {
139                 if let Some(index) = error.index {
140                     // Suppress errors that are either:
141                     // 1) strictly implied by another error.
142                     // 2) implied by an error with a smaller index.
143                     for error2 in error_set {
144                         if error2.index.map_or(false, |index2| is_suppressed[index2]) {
145                             // Avoid errors being suppressed by already-suppressed
146                             // errors, to prevent all errors from being suppressed
147                             // at once.
148                             continue;
149                         }
150
151                         if self.error_implies(error2.predicate, error.predicate)
152                             && !(error2.index >= error.index
153                                 && self.error_implies(error.predicate, error2.predicate))
154                         {
155                             info!("skipping {:?} (implied by {:?})", error, error2);
156                             is_suppressed[index] = true;
157                             break;
158                         }
159                     }
160                 }
161             }
162         }
163
164         for (error, suppressed) in errors.iter().zip(is_suppressed) {
165             if !suppressed {
166                 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
167             }
168         }
169     }
170
171     /// Reports that an overflow has occurred and halts compilation. We
172     /// halt compilation unconditionally because it is important that
173     /// overflows never be masked -- they basically represent computations
174     /// whose result could not be truly determined and thus we can't say
175     /// if the program type checks or not -- and they are unusual
176     /// occurrences in any case.
177     fn report_overflow_error<T>(
178         &self,
179         obligation: &Obligation<'tcx, T>,
180         suggest_increasing_limit: bool,
181     ) -> !
182     where
183         T: fmt::Display + TypeFoldable<'tcx>,
184     {
185         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
186         let mut err = struct_span_err!(
187             self.tcx.sess,
188             obligation.cause.span,
189             E0275,
190             "overflow evaluating the requirement `{}`",
191             predicate
192         );
193
194         if suggest_increasing_limit {
195             self.suggest_new_overflow_limit(&mut err);
196         }
197
198         self.note_obligation_cause_code(
199             &mut err,
200             &obligation.predicate,
201             &obligation.cause.code,
202             &mut vec![],
203         );
204
205         err.emit();
206         self.tcx.sess.abort_if_errors();
207         bug!();
208     }
209
210     /// Reports that a cycle was detected which led to overflow and halts
211     /// compilation. This is equivalent to `report_overflow_error` except
212     /// that we can give a more helpful error message (and, in particular,
213     /// we do not suggest increasing the overflow limit, which is not
214     /// going to help).
215     fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
216         let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
217         assert!(!cycle.is_empty());
218
219         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
220
221         self.report_overflow_error(&cycle[0], false);
222     }
223
224     fn report_selection_error(
225         &self,
226         obligation: &PredicateObligation<'tcx>,
227         error: &SelectionError<'tcx>,
228         fallback_has_occurred: bool,
229         points_at_arg: bool,
230     ) {
231         let tcx = self.tcx;
232         let span = obligation.cause.span;
233
234         let mut err = match *error {
235             SelectionError::Unimplemented => {
236                 if let ObligationCauseCode::CompareImplMethodObligation {
237                     item_name,
238                     impl_item_def_id,
239                     trait_item_def_id,
240                 }
241                 | ObligationCauseCode::CompareImplTypeObligation {
242                     item_name,
243                     impl_item_def_id,
244                     trait_item_def_id,
245                 } = obligation.cause.code
246                 {
247                     self.report_extra_impl_obligation(
248                         span,
249                         item_name,
250                         impl_item_def_id,
251                         trait_item_def_id,
252                         &format!("`{}`", obligation.predicate),
253                     )
254                     .emit();
255                     return;
256                 }
257                 match obligation.predicate.kind() {
258                     ty::PredicateKind::Trait(ref trait_predicate, _) => {
259                         let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
260
261                         if self.tcx.sess.has_errors() && trait_predicate.references_error() {
262                             return;
263                         }
264                         let trait_ref = trait_predicate.to_poly_trait_ref();
265                         let (post_message, pre_message, type_def) = self
266                             .get_parent_trait_ref(&obligation.cause.code)
267                             .map(|(t, s)| {
268                                 (
269                                     format!(" in `{}`", t),
270                                     format!("within `{}`, ", t),
271                                     s.map(|s| (format!("within this `{}`", t), s)),
272                                 )
273                             })
274                             .unwrap_or_default();
275
276                         let OnUnimplementedNote { message, label, note, enclosing_scope } =
277                             self.on_unimplemented_note(trait_ref, obligation);
278                         let have_alt_message = message.is_some() || label.is_some();
279                         let is_try = self
280                             .tcx
281                             .sess
282                             .source_map()
283                             .span_to_snippet(span)
284                             .map(|s| &s == "?")
285                             .unwrap_or(false);
286                         let is_from = format!("{}", trait_ref.print_only_trait_path())
287                             .starts_with("std::convert::From<");
288                         let is_unsize =
289                             { Some(trait_ref.def_id()) == self.tcx.lang_items().unsize_trait() };
290                         let (message, note) = if is_try && is_from {
291                             (
292                                 Some(format!(
293                                     "`?` couldn't convert the error to `{}`",
294                                     trait_ref.skip_binder().self_ty(),
295                                 )),
296                                 Some(
297                                     "the question mark operation (`?`) implicitly performs a \
298                                         conversion on the error value using the `From` trait"
299                                         .to_owned(),
300                                 ),
301                             )
302                         } else {
303                             (message, note)
304                         };
305
306                         let mut err = struct_span_err!(
307                             self.tcx.sess,
308                             span,
309                             E0277,
310                             "{}",
311                             message.unwrap_or_else(|| format!(
312                                 "the trait bound `{}` is not satisfied{}",
313                                 trait_ref.without_const().to_predicate(tcx),
314                                 post_message,
315                             ))
316                         );
317
318                         let should_convert_option_to_result =
319                             format!("{}", trait_ref.print_only_trait_path())
320                                 .starts_with("std::convert::From<std::option::NoneError");
321                         let should_convert_result_to_option = format!("{}", trait_ref)
322                             .starts_with("<std::option::NoneError as std::convert::From<");
323                         if is_try && is_from {
324                             if should_convert_option_to_result {
325                                 err.span_suggestion_verbose(
326                                     span.shrink_to_lo(),
327                                     "consider converting the `Option<T>` into a `Result<T, _>` \
328                                      using `Option::ok_or` or `Option::ok_or_else`",
329                                     ".ok_or_else(|| /* error value */)".to_string(),
330                                     Applicability::HasPlaceholders,
331                                 );
332                             } else if should_convert_result_to_option {
333                                 err.span_suggestion_verbose(
334                                     span.shrink_to_lo(),
335                                     "consider converting the `Result<T, _>` into an `Option<T>` \
336                                      using `Result::ok`",
337                                     ".ok()".to_string(),
338                                     Applicability::MachineApplicable,
339                                 );
340                             }
341                             if let Some(ret_span) = self.return_type_span(obligation) {
342                                 err.span_label(
343                                     ret_span,
344                                     &format!(
345                                         "expected `{}` because of this",
346                                         trait_ref.skip_binder().self_ty()
347                                     ),
348                                 );
349                             }
350                         }
351
352                         let explanation =
353                             if obligation.cause.code == ObligationCauseCode::MainFunctionType {
354                                 "consider using `()`, or a `Result`".to_owned()
355                             } else {
356                                 format!(
357                                     "{}the trait `{}` is not implemented for `{}`",
358                                     pre_message,
359                                     trait_ref.print_only_trait_path(),
360                                     trait_ref.skip_binder().self_ty(),
361                                 )
362                             };
363
364                         if self.suggest_add_reference_to_arg(
365                             &obligation,
366                             &mut err,
367                             &trait_ref,
368                             points_at_arg,
369                             have_alt_message,
370                         ) {
371                             self.note_obligation_cause(&mut err, obligation);
372                             err.emit();
373                             return;
374                         }
375                         if let Some(ref s) = label {
376                             // If it has a custom `#[rustc_on_unimplemented]`
377                             // error message, let's display it as the label!
378                             err.span_label(span, s.as_str());
379                             err.help(&explanation);
380                         } else {
381                             err.span_label(span, explanation);
382                         }
383                         if let Some((msg, span)) = type_def {
384                             err.span_label(span, &msg);
385                         }
386                         if let Some(ref s) = note {
387                             // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
388                             err.note(s.as_str());
389                         }
390                         if let Some(ref s) = enclosing_scope {
391                             let enclosing_scope_span = tcx.def_span(
392                                 tcx.hir()
393                                     .opt_local_def_id(obligation.cause.body_id)
394                                     .unwrap_or_else(|| {
395                                         tcx.hir().body_owner_def_id(hir::BodyId {
396                                             hir_id: obligation.cause.body_id,
397                                         })
398                                     })
399                                     .to_def_id(),
400                             );
401
402                             err.span_label(enclosing_scope_span, s.as_str());
403                         }
404
405                         self.suggest_dereferences(&obligation, &mut err, &trait_ref, points_at_arg);
406                         self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
407                         self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
408                         self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
409                         self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
410                         self.note_version_mismatch(&mut err, &trait_ref);
411
412                         if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() {
413                             self.suggest_await_before_try(&mut err, &obligation, &trait_ref, span);
414                         }
415
416                         if self.suggest_impl_trait(&mut err, span, &obligation, &trait_ref) {
417                             err.emit();
418                             return;
419                         }
420
421                         if is_unsize {
422                             // If the obligation failed due to a missing implementation of the
423                             // `Unsize` trait, give a pointer to why that might be the case
424                             err.note(
425                                 "all implementations of `Unsize` are provided \
426                                 automatically by the compiler, see \
427                                 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
428                                 for more information",
429                             );
430                         }
431
432                         let is_fn_trait = [
433                             self.tcx.lang_items().fn_trait(),
434                             self.tcx.lang_items().fn_mut_trait(),
435                             self.tcx.lang_items().fn_once_trait(),
436                         ]
437                         .contains(&Some(trait_ref.def_id()));
438                         let is_target_feature_fn =
439                             if let ty::FnDef(def_id, _) = trait_ref.skip_binder().self_ty().kind {
440                                 !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
441                             } else {
442                                 false
443                             };
444                         if is_fn_trait && is_target_feature_fn {
445                             err.note(
446                                 "`#[target_feature]` functions do not implement the `Fn` traits",
447                             );
448                         }
449
450                         // Try to report a help message
451                         if !trait_ref.has_infer_types_or_consts()
452                             && self.predicate_can_apply(obligation.param_env, trait_ref)
453                         {
454                             // If a where-clause may be useful, remind the
455                             // user that they can add it.
456                             //
457                             // don't display an on-unimplemented note, as
458                             // these notes will often be of the form
459                             //     "the type `T` can't be frobnicated"
460                             // which is somewhat confusing.
461                             self.suggest_restricting_param_bound(
462                                 &mut err,
463                                 trait_ref,
464                                 obligation.cause.body_id,
465                             );
466                         } else {
467                             if !have_alt_message {
468                                 // Can't show anything else useful, try to find similar impls.
469                                 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
470                                 self.report_similar_impl_candidates(impl_candidates, &mut err);
471                             }
472                             // Changing mutability doesn't make a difference to whether we have
473                             // an `Unsize` impl (Fixes ICE in #71036)
474                             if !is_unsize {
475                                 self.suggest_change_mut(
476                                     &obligation,
477                                     &mut err,
478                                     &trait_ref,
479                                     points_at_arg,
480                                 );
481                             }
482                         }
483
484                         // If this error is due to `!: Trait` not implemented but `(): Trait` is
485                         // implemented, and fallback has occurred, then it could be due to a
486                         // variable that used to fallback to `()` now falling back to `!`. Issue a
487                         // note informing about the change in behaviour.
488                         if trait_predicate.skip_binder().self_ty().is_never()
489                             && fallback_has_occurred
490                         {
491                             let predicate = trait_predicate.map_bound(|mut trait_pred| {
492                                 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
493                                     self.tcx.mk_unit(),
494                                     &trait_pred.trait_ref.substs[1..],
495                                 );
496                                 trait_pred
497                             });
498                             let unit_obligation = Obligation {
499                                 predicate: ty::PredicateKind::Trait(
500                                     predicate,
501                                     hir::Constness::NotConst,
502                                 )
503                                 .to_predicate(self.tcx),
504                                 ..obligation.clone()
505                             };
506                             if self.predicate_may_hold(&unit_obligation) {
507                                 err.note(
508                                     "the trait is implemented for `()`. \
509                                      Possibly this error has been caused by changes to \
510                                      Rust's type-inference algorithm (see issue #48950 \
511                                      <https://github.com/rust-lang/rust/issues/48950> \
512                                      for more information). Consider whether you meant to use \
513                                      the type `()` here instead.",
514                                 );
515                             }
516                         }
517
518                         err
519                     }
520
521                     ty::PredicateKind::Subtype(ref predicate) => {
522                         // Errors for Subtype predicates show up as
523                         // `FulfillmentErrorCode::CodeSubtypeError`,
524                         // not selection error.
525                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
526                     }
527
528                     ty::PredicateKind::RegionOutlives(ref predicate) => {
529                         let predicate = self.resolve_vars_if_possible(predicate);
530                         let err = self
531                             .region_outlives_predicate(&obligation.cause, predicate)
532                             .err()
533                             .unwrap();
534                         struct_span_err!(
535                             self.tcx.sess,
536                             span,
537                             E0279,
538                             "the requirement `{}` is not satisfied (`{}`)",
539                             predicate,
540                             err,
541                         )
542                     }
543
544                     ty::PredicateKind::Projection(..) | ty::PredicateKind::TypeOutlives(..) => {
545                         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
546                         struct_span_err!(
547                             self.tcx.sess,
548                             span,
549                             E0280,
550                             "the requirement `{}` is not satisfied",
551                             predicate
552                         )
553                     }
554
555                     &ty::PredicateKind::ObjectSafe(trait_def_id) => {
556                         let violations = self.tcx.object_safety_violations(trait_def_id);
557                         report_object_safety_error(self.tcx, span, trait_def_id, violations)
558                     }
559
560                     &ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
561                         let found_kind = self.closure_kind(closure_substs).unwrap();
562                         let closure_span =
563                             self.tcx.sess.source_map().guess_head_span(
564                                 self.tcx.hir().span_if_local(closure_def_id).unwrap(),
565                             );
566                         let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id.expect_local());
567                         let mut err = struct_span_err!(
568                             self.tcx.sess,
569                             closure_span,
570                             E0525,
571                             "expected a closure that implements the `{}` trait, \
572                              but this closure only implements `{}`",
573                             kind,
574                             found_kind
575                         );
576
577                         err.span_label(
578                             closure_span,
579                             format!("this closure implements `{}`, not `{}`", found_kind, kind),
580                         );
581                         err.span_label(
582                             obligation.cause.span,
583                             format!("the requirement to implement `{}` derives from here", kind),
584                         );
585
586                         // Additional context information explaining why the closure only implements
587                         // a particular trait.
588                         if let Some(tables) = self.in_progress_tables {
589                             let tables = tables.borrow();
590                             match (found_kind, tables.closure_kind_origins().get(hir_id)) {
591                                 (ty::ClosureKind::FnOnce, Some((span, name))) => {
592                                     err.span_label(
593                                         *span,
594                                         format!(
595                                             "closure is `FnOnce` because it moves the \
596                                          variable `{}` out of its environment",
597                                             name
598                                         ),
599                                     );
600                                 }
601                                 (ty::ClosureKind::FnMut, Some((span, name))) => {
602                                     err.span_label(
603                                         *span,
604                                         format!(
605                                             "closure is `FnMut` because it mutates the \
606                                          variable `{}` here",
607                                             name
608                                         ),
609                                     );
610                                 }
611                                 _ => {}
612                             }
613                         }
614
615                         err.emit();
616                         return;
617                     }
618
619                     ty::PredicateKind::WellFormed(ty) => {
620                         if !self.tcx.sess.opts.debugging_opts.chalk {
621                             // WF predicates cannot themselves make
622                             // errors. They can only block due to
623                             // ambiguity; otherwise, they always
624                             // degenerate into other obligations
625                             // (which may fail).
626                             span_bug!(span, "WF predicate not satisfied for {:?}", ty);
627                         } else {
628                             // FIXME: we'll need a better message which takes into account
629                             // which bounds actually failed to hold.
630                             self.tcx.sess.struct_span_err(
631                                 span,
632                                 &format!("the type `{}` is not well-formed (chalk)", ty),
633                             )
634                         }
635                     }
636
637                     ty::PredicateKind::ConstEvaluatable(..) => {
638                         // Errors for `ConstEvaluatable` predicates show up as
639                         // `SelectionError::ConstEvalFailure`,
640                         // not `Unimplemented`.
641                         span_bug!(
642                             span,
643                             "const-evaluatable requirement gave wrong error: `{:?}`",
644                             obligation
645                         )
646                     }
647
648                     ty::PredicateKind::ConstEquate(..) => {
649                         // Errors for `ConstEquate` predicates show up as
650                         // `SelectionError::ConstEvalFailure`,
651                         // not `Unimplemented`.
652                         span_bug!(
653                             span,
654                             "const-equate requirement gave wrong error: `{:?}`",
655                             obligation
656                         )
657                     }
658                 }
659             }
660
661             OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
662                 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
663                 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
664
665                 if expected_trait_ref.self_ty().references_error() {
666                     return;
667                 }
668
669                 let found_trait_ty = match found_trait_ref.self_ty().no_bound_vars() {
670                     Some(ty) => ty,
671                     None => return,
672                 };
673
674                 let found_did = match found_trait_ty.kind {
675                     ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
676                     ty::Adt(def, _) => Some(def.did),
677                     _ => None,
678                 };
679
680                 let found_span = found_did
681                     .and_then(|did| self.tcx.hir().span_if_local(did))
682                     .map(|sp| self.tcx.sess.source_map().guess_head_span(sp)); // the sp could be an fn def
683
684                 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
685                     // We check closures twice, with obligations flowing in different directions,
686                     // but we want to complain about them only once.
687                     return;
688                 }
689
690                 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
691
692                 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
693                     ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
694                     _ => vec![ArgKind::empty()],
695                 };
696
697                 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
698                 let expected = match expected_ty.kind {
699                     ty::Tuple(ref tys) => tys
700                         .iter()
701                         .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
702                         .collect(),
703                     _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
704                 };
705
706                 if found.len() == expected.len() {
707                     self.report_closure_arg_mismatch(
708                         span,
709                         found_span,
710                         found_trait_ref,
711                         expected_trait_ref,
712                     )
713                 } else {
714                     let (closure_span, found) = found_did
715                         .and_then(|did| {
716                             let node = self.tcx.hir().get_if_local(did)?;
717                             let (found_span, found) = self.get_fn_like_arguments(node)?;
718                             Some((Some(found_span), found))
719                         })
720                         .unwrap_or((found_span, found));
721
722                     self.report_arg_count_mismatch(
723                         span,
724                         closure_span,
725                         expected,
726                         found,
727                         found_trait_ty.is_closure(),
728                     )
729                 }
730             }
731
732             TraitNotObjectSafe(did) => {
733                 let violations = self.tcx.object_safety_violations(did);
734                 report_object_safety_error(self.tcx, span, did, violations)
735             }
736
737             ConstEvalFailure(ErrorHandled::TooGeneric) => {
738                 // In this instance, we have a const expression containing an unevaluated
739                 // generic parameter. We have no idea whether this expression is valid or
740                 // not (e.g. it might result in an error), but we don't want to just assume
741                 // that it's okay, because that might result in post-monomorphisation time
742                 // errors. The onus is really on the caller to provide values that it can
743                 // prove are well-formed.
744                 let mut err = self
745                     .tcx
746                     .sess
747                     .struct_span_err(span, "constant expression depends on a generic parameter");
748                 // FIXME(const_generics): we should suggest to the user how they can resolve this
749                 // issue. However, this is currently not actually possible
750                 // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
751                 err.note("this may fail depending on what value the parameter takes");
752                 err
753             }
754
755             // Already reported in the query.
756             ConstEvalFailure(ErrorHandled::Reported(ErrorReported)) => {
757                 // FIXME(eddyb) remove this once `ErrorReported` becomes a proof token.
758                 self.tcx.sess.delay_span_bug(span, "`ErrorReported` without an error");
759                 return;
760             }
761
762             // Already reported in the query, but only as a lint.
763             // This shouldn't actually happen for constants used in types, modulo
764             // bugs. The `delay_span_bug` here ensures it won't be ignored.
765             ConstEvalFailure(ErrorHandled::Linted) => {
766                 self.tcx.sess.delay_span_bug(span, "constant in type had error reported as lint");
767                 return;
768             }
769
770             Overflow => {
771                 bug!("overflow should be handled before the `report_selection_error` path");
772             }
773         };
774
775         self.note_obligation_cause(&mut err, obligation);
776         self.point_at_returns_when_relevant(&mut err, &obligation);
777
778         err.emit();
779     }
780
781     /// Given some node representing a fn-like thing in the HIR map,
782     /// returns a span and `ArgKind` information that describes the
783     /// arguments it expects. This can be supplied to
784     /// `report_arg_count_mismatch`.
785     fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)> {
786         let sm = self.tcx.sess.source_map();
787         let hir = self.tcx.hir();
788         Some(match node {
789             Node::Expr(&hir::Expr {
790                 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
791                 ..
792             }) => (
793                 sm.guess_head_span(span),
794                 hir.body(id)
795                     .params
796                     .iter()
797                     .map(|arg| {
798                         if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
799                             *arg.pat
800                         {
801                             Some(ArgKind::Tuple(
802                                 Some(span),
803                                 args.iter()
804                                     .map(|pat| {
805                                         sm.span_to_snippet(pat.span)
806                                             .ok()
807                                             .map(|snippet| (snippet, "_".to_owned()))
808                                     })
809                                     .collect::<Option<Vec<_>>>()?,
810                             ))
811                         } else {
812                             let name = sm.span_to_snippet(arg.pat.span).ok()?;
813                             Some(ArgKind::Arg(name, "_".to_owned()))
814                         }
815                     })
816                     .collect::<Option<Vec<ArgKind>>>()?,
817             ),
818             Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
819             | Node::ImplItem(&hir::ImplItem {
820                 span,
821                 kind: hir::ImplItemKind::Fn(ref sig, _),
822                 ..
823             })
824             | Node::TraitItem(&hir::TraitItem {
825                 span,
826                 kind: hir::TraitItemKind::Fn(ref sig, _),
827                 ..
828             }) => (
829                 sm.guess_head_span(span),
830                 sig.decl
831                     .inputs
832                     .iter()
833                     .map(|arg| match arg.clone().kind {
834                         hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
835                             Some(arg.span),
836                             vec![("_".to_owned(), "_".to_owned()); tys.len()],
837                         ),
838                         _ => ArgKind::empty(),
839                     })
840                     .collect::<Vec<ArgKind>>(),
841             ),
842             Node::Ctor(ref variant_data) => {
843                 let span = variant_data.ctor_hir_id().map(|id| hir.span(id)).unwrap_or(DUMMY_SP);
844                 let span = sm.guess_head_span(span);
845                 (span, vec![ArgKind::empty(); variant_data.fields().len()])
846             }
847             _ => panic!("non-FnLike node found: {:?}", node),
848         })
849     }
850
851     /// Reports an error when the number of arguments needed by a
852     /// trait match doesn't match the number that the expression
853     /// provides.
854     fn report_arg_count_mismatch(
855         &self,
856         span: Span,
857         found_span: Option<Span>,
858         expected_args: Vec<ArgKind>,
859         found_args: Vec<ArgKind>,
860         is_closure: bool,
861     ) -> DiagnosticBuilder<'tcx> {
862         let kind = if is_closure { "closure" } else { "function" };
863
864         let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
865             let arg_length = arguments.len();
866             let distinct = match &other[..] {
867                 &[ArgKind::Tuple(..)] => true,
868                 _ => false,
869             };
870             match (arg_length, arguments.get(0)) {
871                 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
872                     format!("a single {}-tuple as argument", fields.len())
873                 }
874                 _ => format!(
875                     "{} {}argument{}",
876                     arg_length,
877                     if distinct && arg_length > 1 { "distinct " } else { "" },
878                     pluralize!(arg_length)
879                 ),
880             }
881         };
882
883         let expected_str = args_str(&expected_args, &found_args);
884         let found_str = args_str(&found_args, &expected_args);
885
886         let mut err = struct_span_err!(
887             self.tcx.sess,
888             span,
889             E0593,
890             "{} is expected to take {}, but it takes {}",
891             kind,
892             expected_str,
893             found_str,
894         );
895
896         err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
897
898         if let Some(found_span) = found_span {
899             err.span_label(found_span, format!("takes {}", found_str));
900
901             // move |_| { ... }
902             // ^^^^^^^^-- def_span
903             //
904             // move |_| { ... }
905             // ^^^^^-- prefix
906             let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
907             // move |_| { ... }
908             //      ^^^-- pipe_span
909             let pipe_span =
910                 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
911
912             // Suggest to take and ignore the arguments with expected_args_length `_`s if
913             // found arguments is empty (assume the user just wants to ignore args in this case).
914             // For example, if `expected_args_length` is 2, suggest `|_, _|`.
915             if found_args.is_empty() && is_closure {
916                 let underscores = vec!["_"; expected_args.len()].join(", ");
917                 err.span_suggestion_verbose(
918                     pipe_span,
919                     &format!(
920                         "consider changing the closure to take and ignore the expected argument{}",
921                         pluralize!(expected_args.len())
922                     ),
923                     format!("|{}|", underscores),
924                     Applicability::MachineApplicable,
925                 );
926             }
927
928             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
929                 if fields.len() == expected_args.len() {
930                     let sugg = fields
931                         .iter()
932                         .map(|(name, _)| name.to_owned())
933                         .collect::<Vec<String>>()
934                         .join(", ");
935                     err.span_suggestion_verbose(
936                         found_span,
937                         "change the closure to take multiple arguments instead of a single tuple",
938                         format!("|{}|", sugg),
939                         Applicability::MachineApplicable,
940                     );
941                 }
942             }
943             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
944                 if fields.len() == found_args.len() && is_closure {
945                     let sugg = format!(
946                         "|({}){}|",
947                         found_args
948                             .iter()
949                             .map(|arg| match arg {
950                                 ArgKind::Arg(name, _) => name.to_owned(),
951                                 _ => "_".to_owned(),
952                             })
953                             .collect::<Vec<String>>()
954                             .join(", "),
955                         // add type annotations if available
956                         if found_args.iter().any(|arg| match arg {
957                             ArgKind::Arg(_, ty) => ty != "_",
958                             _ => false,
959                         }) {
960                             format!(
961                                 ": ({})",
962                                 fields
963                                     .iter()
964                                     .map(|(_, ty)| ty.to_owned())
965                                     .collect::<Vec<String>>()
966                                     .join(", ")
967                             )
968                         } else {
969                             String::new()
970                         },
971                     );
972                     err.span_suggestion_verbose(
973                         found_span,
974                         "change the closure to accept a tuple instead of individual arguments",
975                         sugg,
976                         Applicability::MachineApplicable,
977                     );
978                 }
979             }
980         }
981
982         err
983     }
984 }
985
986 trait InferCtxtPrivExt<'tcx> {
987     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
988     // `error` occurring implies that `cond` occurs.
989     fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool;
990
991     fn report_fulfillment_error(
992         &self,
993         error: &FulfillmentError<'tcx>,
994         body_id: Option<hir::BodyId>,
995         fallback_has_occurred: bool,
996     );
997
998     fn report_projection_error(
999         &self,
1000         obligation: &PredicateObligation<'tcx>,
1001         error: &MismatchedProjectionTypes<'tcx>,
1002     );
1003
1004     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool;
1005
1006     fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>;
1007
1008     fn find_similar_impl_candidates(
1009         &self,
1010         trait_ref: ty::PolyTraitRef<'tcx>,
1011     ) -> Vec<ty::TraitRef<'tcx>>;
1012
1013     fn report_similar_impl_candidates(
1014         &self,
1015         impl_candidates: Vec<ty::TraitRef<'tcx>>,
1016         err: &mut DiagnosticBuilder<'_>,
1017     );
1018
1019     /// Gets the parent trait chain start
1020     fn get_parent_trait_ref(
1021         &self,
1022         code: &ObligationCauseCode<'tcx>,
1023     ) -> Option<(String, Option<Span>)>;
1024
1025     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1026     /// with the same path as `trait_ref`, a help message about
1027     /// a probable version mismatch is added to `err`
1028     fn note_version_mismatch(
1029         &self,
1030         err: &mut DiagnosticBuilder<'_>,
1031         trait_ref: &ty::PolyTraitRef<'tcx>,
1032     );
1033
1034     /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
1035     /// `trait_ref`.
1036     ///
1037     /// For this to work, `new_self_ty` must have no escaping bound variables.
1038     fn mk_trait_obligation_with_new_self_ty(
1039         &self,
1040         param_env: ty::ParamEnv<'tcx>,
1041         trait_ref: &ty::PolyTraitRef<'tcx>,
1042         new_self_ty: Ty<'tcx>,
1043     ) -> PredicateObligation<'tcx>;
1044
1045     fn maybe_report_ambiguity(
1046         &self,
1047         obligation: &PredicateObligation<'tcx>,
1048         body_id: Option<hir::BodyId>,
1049     );
1050
1051     fn predicate_can_apply(
1052         &self,
1053         param_env: ty::ParamEnv<'tcx>,
1054         pred: ty::PolyTraitRef<'tcx>,
1055     ) -> bool;
1056
1057     fn note_obligation_cause(
1058         &self,
1059         err: &mut DiagnosticBuilder<'tcx>,
1060         obligation: &PredicateObligation<'tcx>,
1061     );
1062
1063     fn suggest_unsized_bound_if_applicable(
1064         &self,
1065         err: &mut DiagnosticBuilder<'tcx>,
1066         obligation: &PredicateObligation<'tcx>,
1067     );
1068
1069     fn is_recursive_obligation(
1070         &self,
1071         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1072         cause_code: &ObligationCauseCode<'tcx>,
1073     ) -> bool;
1074 }
1075
1076 impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> {
1077     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1078     // `error` occurring implies that `cond` occurs.
1079     fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool {
1080         if cond == error {
1081             return true;
1082         }
1083
1084         let (cond, error) = match (cond.kind(), error.kind()) {
1085             (ty::PredicateKind::Trait(..), ty::PredicateKind::Trait(error, _)) => (cond, error),
1086             _ => {
1087                 // FIXME: make this work in other cases too.
1088                 return false;
1089             }
1090         };
1091
1092         for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) {
1093             if let ty::PredicateKind::Trait(implication, _) = obligation.predicate.kind() {
1094                 let error = error.to_poly_trait_ref();
1095                 let implication = implication.to_poly_trait_ref();
1096                 // FIXME: I'm just not taking associated types at all here.
1097                 // Eventually I'll need to implement param-env-aware
1098                 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
1099                 let param_env = ty::ParamEnv::empty();
1100                 if self.can_sub(param_env, error, implication).is_ok() {
1101                     debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
1102                     return true;
1103                 }
1104             }
1105         }
1106
1107         false
1108     }
1109
1110     fn report_fulfillment_error(
1111         &self,
1112         error: &FulfillmentError<'tcx>,
1113         body_id: Option<hir::BodyId>,
1114         fallback_has_occurred: bool,
1115     ) {
1116         debug!("report_fulfillment_error({:?})", error);
1117         match error.code {
1118             FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
1119                 self.report_selection_error(
1120                     &error.obligation,
1121                     selection_error,
1122                     fallback_has_occurred,
1123                     error.points_at_arg_span,
1124                 );
1125             }
1126             FulfillmentErrorCode::CodeProjectionError(ref e) => {
1127                 self.report_projection_error(&error.obligation, e);
1128             }
1129             FulfillmentErrorCode::CodeAmbiguity => {
1130                 self.maybe_report_ambiguity(&error.obligation, body_id);
1131             }
1132             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
1133                 self.report_mismatched_types(
1134                     &error.obligation.cause,
1135                     expected_found.expected,
1136                     expected_found.found,
1137                     err.clone(),
1138                 )
1139                 .emit();
1140             }
1141             FulfillmentErrorCode::CodeConstEquateError(ref expected_found, ref err) => {
1142                 self.report_mismatched_consts(
1143                     &error.obligation.cause,
1144                     expected_found.expected,
1145                     expected_found.found,
1146                     err.clone(),
1147                 )
1148                 .emit();
1149             }
1150         }
1151     }
1152
1153     fn report_projection_error(
1154         &self,
1155         obligation: &PredicateObligation<'tcx>,
1156         error: &MismatchedProjectionTypes<'tcx>,
1157     ) {
1158         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1159
1160         if predicate.references_error() {
1161             return;
1162         }
1163
1164         self.probe(|_| {
1165             let err_buf;
1166             let mut err = &error.err;
1167             let mut values = None;
1168
1169             // try to find the mismatched types to report the error with.
1170             //
1171             // this can fail if the problem was higher-ranked, in which
1172             // cause I have no idea for a good error message.
1173             if let ty::PredicateKind::Projection(ref data) = predicate.kind() {
1174                 let mut selcx = SelectionContext::new(self);
1175                 let (data, _) = self.replace_bound_vars_with_fresh_vars(
1176                     obligation.cause.span,
1177                     infer::LateBoundRegionConversionTime::HigherRankedType,
1178                     data,
1179                 );
1180                 let mut obligations = vec![];
1181                 let normalized_ty = super::normalize_projection_type(
1182                     &mut selcx,
1183                     obligation.param_env,
1184                     data.projection_ty,
1185                     obligation.cause.clone(),
1186                     0,
1187                     &mut obligations,
1188                 );
1189
1190                 debug!(
1191                     "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
1192                     obligation.cause, obligation.param_env
1193                 );
1194
1195                 debug!(
1196                     "report_projection_error normalized_ty={:?} data.ty={:?}",
1197                     normalized_ty, data.ty
1198                 );
1199
1200                 let is_normalized_ty_expected = match &obligation.cause.code {
1201                     ObligationCauseCode::ItemObligation(_)
1202                     | ObligationCauseCode::BindingObligation(_, _)
1203                     | ObligationCauseCode::ObjectCastObligation(_) => false,
1204                     _ => true,
1205                 };
1206
1207                 if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
1208                     is_normalized_ty_expected,
1209                     normalized_ty,
1210                     data.ty,
1211                 ) {
1212                     values = Some(infer::ValuePairs::Types(ExpectedFound::new(
1213                         is_normalized_ty_expected,
1214                         normalized_ty,
1215                         data.ty,
1216                     )));
1217
1218                     err_buf = error;
1219                     err = &err_buf;
1220                 }
1221             }
1222
1223             let msg = format!("type mismatch resolving `{}`", predicate);
1224             let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
1225             let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
1226             if fresh {
1227                 let mut diag = struct_span_err!(
1228                     self.tcx.sess,
1229                     obligation.cause.span,
1230                     E0271,
1231                     "type mismatch resolving `{}`",
1232                     predicate
1233                 );
1234                 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
1235                 self.note_obligation_cause(&mut diag, obligation);
1236                 diag.emit();
1237             }
1238         });
1239     }
1240
1241     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1242         /// returns the fuzzy category of a given type, or None
1243         /// if the type can be equated to any type.
1244         fn type_category(t: Ty<'_>) -> Option<u32> {
1245             match t.kind {
1246                 ty::Bool => Some(0),
1247                 ty::Char => Some(1),
1248                 ty::Str => Some(2),
1249                 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
1250                 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
1251                 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1252                 ty::Array(..) | ty::Slice(..) => Some(6),
1253                 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1254                 ty::Dynamic(..) => Some(8),
1255                 ty::Closure(..) => Some(9),
1256                 ty::Tuple(..) => Some(10),
1257                 ty::Projection(..) => Some(11),
1258                 ty::Param(..) => Some(12),
1259                 ty::Opaque(..) => Some(13),
1260                 ty::Never => Some(14),
1261                 ty::Adt(adt, ..) => match adt.adt_kind() {
1262                     AdtKind::Struct => Some(15),
1263                     AdtKind::Union => Some(16),
1264                     AdtKind::Enum => Some(17),
1265                 },
1266                 ty::Generator(..) => Some(18),
1267                 ty::Foreign(..) => Some(19),
1268                 ty::GeneratorWitness(..) => Some(20),
1269                 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1270             }
1271         }
1272
1273         match (type_category(a), type_category(b)) {
1274             (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
1275                 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
1276                 _ => cat_a == cat_b,
1277             },
1278             // infer and error can be equated to all types
1279             _ => true,
1280         }
1281     }
1282
1283     fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
1284         self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
1285             hir::GeneratorKind::Gen => "a generator",
1286             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
1287             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
1288             hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
1289         })
1290     }
1291
1292     fn find_similar_impl_candidates(
1293         &self,
1294         trait_ref: ty::PolyTraitRef<'tcx>,
1295     ) -> Vec<ty::TraitRef<'tcx>> {
1296         let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
1297         let all_impls = self.tcx.all_impls(trait_ref.def_id());
1298
1299         match simp {
1300             Some(simp) => all_impls
1301                 .filter_map(|def_id| {
1302                     let imp = self.tcx.impl_trait_ref(def_id).unwrap();
1303                     let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
1304                     if let Some(imp_simp) = imp_simp {
1305                         if simp != imp_simp {
1306                             return None;
1307                         }
1308                     }
1309                     Some(imp)
1310                 })
1311                 .collect(),
1312             None => all_impls.map(|def_id| self.tcx.impl_trait_ref(def_id).unwrap()).collect(),
1313         }
1314     }
1315
1316     fn report_similar_impl_candidates(
1317         &self,
1318         impl_candidates: Vec<ty::TraitRef<'tcx>>,
1319         err: &mut DiagnosticBuilder<'_>,
1320     ) {
1321         if impl_candidates.is_empty() {
1322             return;
1323         }
1324
1325         let len = impl_candidates.len();
1326         let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
1327
1328         let normalize = |candidate| {
1329             self.tcx.infer_ctxt().enter(|ref infcx| {
1330                 let normalized = infcx
1331                     .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
1332                     .normalize(candidate)
1333                     .ok();
1334                 match normalized {
1335                     Some(normalized) => format!("\n  {:?}", normalized.value),
1336                     None => format!("\n  {:?}", candidate),
1337                 }
1338             })
1339         };
1340
1341         // Sort impl candidates so that ordering is consistent for UI tests.
1342         let mut normalized_impl_candidates =
1343             impl_candidates.iter().map(normalize).collect::<Vec<String>>();
1344
1345         // Sort before taking the `..end` range,
1346         // because the ordering of `impl_candidates` may not be deterministic:
1347         // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
1348         normalized_impl_candidates.sort();
1349
1350         err.help(&format!(
1351             "the following implementations were found:{}{}",
1352             normalized_impl_candidates[..end].join(""),
1353             if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
1354         ));
1355     }
1356
1357     /// Gets the parent trait chain start
1358     fn get_parent_trait_ref(
1359         &self,
1360         code: &ObligationCauseCode<'tcx>,
1361     ) -> Option<(String, Option<Span>)> {
1362         match code {
1363             &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1364                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1365                 match self.get_parent_trait_ref(&data.parent_code) {
1366                     Some(t) => Some(t),
1367                     None => {
1368                         let ty = parent_trait_ref.skip_binder().self_ty();
1369                         let span =
1370                             TyCategory::from_ty(ty).map(|(_, def_id)| self.tcx.def_span(def_id));
1371                         Some((ty.to_string(), span))
1372                     }
1373                 }
1374             }
1375             _ => None,
1376         }
1377     }
1378
1379     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1380     /// with the same path as `trait_ref`, a help message about
1381     /// a probable version mismatch is added to `err`
1382     fn note_version_mismatch(
1383         &self,
1384         err: &mut DiagnosticBuilder<'_>,
1385         trait_ref: &ty::PolyTraitRef<'tcx>,
1386     ) {
1387         let get_trait_impl = |trait_def_id| {
1388             let mut trait_impl = None;
1389             self.tcx.for_each_relevant_impl(
1390                 trait_def_id,
1391                 trait_ref.skip_binder().self_ty(),
1392                 |impl_def_id| {
1393                     if trait_impl.is_none() {
1394                         trait_impl = Some(impl_def_id);
1395                     }
1396                 },
1397             );
1398             trait_impl
1399         };
1400         let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1401         let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1402         let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1403             .iter()
1404             .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1405             .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1406             .collect();
1407         for trait_with_same_path in traits_with_same_path {
1408             if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1409                 let impl_span = self.tcx.def_span(impl_def_id);
1410                 err.span_help(impl_span, "trait impl with same name found");
1411                 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1412                 let crate_msg = format!(
1413                     "perhaps two different versions of crate `{}` are being used?",
1414                     trait_crate
1415                 );
1416                 err.note(&crate_msg);
1417             }
1418         }
1419     }
1420
1421     fn mk_trait_obligation_with_new_self_ty(
1422         &self,
1423         param_env: ty::ParamEnv<'tcx>,
1424         trait_ref: &ty::PolyTraitRef<'tcx>,
1425         new_self_ty: Ty<'tcx>,
1426     ) -> PredicateObligation<'tcx> {
1427         assert!(!new_self_ty.has_escaping_bound_vars());
1428
1429         let trait_ref = trait_ref.map_bound_ref(|tr| ty::TraitRef {
1430             substs: self.tcx.mk_substs_trait(new_self_ty, &tr.substs[1..]),
1431             ..*tr
1432         });
1433
1434         Obligation::new(
1435             ObligationCause::dummy(),
1436             param_env,
1437             trait_ref.without_const().to_predicate(self.tcx),
1438         )
1439     }
1440
1441     fn maybe_report_ambiguity(
1442         &self,
1443         obligation: &PredicateObligation<'tcx>,
1444         body_id: Option<hir::BodyId>,
1445     ) {
1446         // Unable to successfully determine, probably means
1447         // insufficient type information, but could mean
1448         // ambiguous impls. The latter *ought* to be a
1449         // coherence violation, so we don't report it here.
1450
1451         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1452         let span = obligation.cause.span;
1453
1454         debug!(
1455             "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1456             predicate, obligation, body_id, obligation.cause.code,
1457         );
1458
1459         // Ambiguity errors are often caused as fallout from earlier
1460         // errors. So just ignore them if this infcx is tainted.
1461         if self.is_tainted_by_errors() {
1462             return;
1463         }
1464
1465         let mut err = match predicate.kind() {
1466             ty::PredicateKind::Trait(ref data, _) => {
1467                 let trait_ref = data.to_poly_trait_ref();
1468                 let self_ty = trait_ref.skip_binder().self_ty();
1469                 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1470
1471                 if predicate.references_error() {
1472                     return;
1473                 }
1474                 // Typically, this ambiguity should only happen if
1475                 // there are unresolved type inference variables
1476                 // (otherwise it would suggest a coherence
1477                 // failure). But given #21974 that is not necessarily
1478                 // the case -- we can have multiple where clauses that
1479                 // are only distinguished by a region, which results
1480                 // in an ambiguity even when all types are fully
1481                 // known, since we don't dispatch based on region
1482                 // relationships.
1483
1484                 // This is kind of a hack: it frequently happens that some earlier
1485                 // error prevents types from being fully inferred, and then we get
1486                 // a bunch of uninteresting errors saying something like "<generic
1487                 // #0> doesn't implement Sized".  It may even be true that we
1488                 // could just skip over all checks where the self-ty is an
1489                 // inference variable, but I was afraid that there might be an
1490                 // inference variable created, registered as an obligation, and
1491                 // then never forced by writeback, and hence by skipping here we'd
1492                 // be ignoring the fact that we don't KNOW the type works
1493                 // out. Though even that would probably be harmless, given that
1494                 // we're only talking about builtin traits, which are known to be
1495                 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1496                 // avoid inundating the user with unnecessary errors, but we now
1497                 // check upstream for type errors and don't add the obligations to
1498                 // begin with in those cases.
1499                 if self
1500                     .tcx
1501                     .lang_items()
1502                     .sized_trait()
1503                     .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1504                 {
1505                     self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
1506                     return;
1507                 }
1508                 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
1509                 err.note(&format!("cannot satisfy `{}`", predicate));
1510                 if let ObligationCauseCode::ItemObligation(def_id) = obligation.cause.code {
1511                     self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
1512                 } else if let (
1513                     Ok(ref snippet),
1514                     ObligationCauseCode::BindingObligation(ref def_id, _),
1515                 ) =
1516                     (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
1517                 {
1518                     let generics = self.tcx.generics_of(*def_id);
1519                     if generics.params.iter().any(|p| p.name.as_str() != "Self")
1520                         && !snippet.ends_with('>')
1521                     {
1522                         // FIXME: To avoid spurious suggestions in functions where type arguments
1523                         // where already supplied, we check the snippet to make sure it doesn't
1524                         // end with a turbofish. Ideally we would have access to a `PathSegment`
1525                         // instead. Otherwise we would produce the following output:
1526                         //
1527                         // error[E0283]: type annotations needed
1528                         //   --> $DIR/issue-54954.rs:3:24
1529                         //    |
1530                         // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
1531                         //    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^
1532                         //    |                        |
1533                         //    |                        cannot infer type
1534                         //    |                        help: consider specifying the type argument
1535                         //    |                        in the function call:
1536                         //    |                        `Tt::const_val::<[i8; 123]>::<T>`
1537                         // ...
1538                         // LL |     const fn const_val<T: Sized>() -> usize {
1539                         //    |                        - required by this bound in `Tt::const_val`
1540                         //    |
1541                         //    = note: cannot satisfy `_: Tt`
1542
1543                         err.span_suggestion_verbose(
1544                             span.shrink_to_hi(),
1545                             &format!(
1546                                 "consider specifying the type argument{} in the function call",
1547                                 pluralize!(generics.params.len()),
1548                             ),
1549                             format!(
1550                                 "::<{}>",
1551                                 generics
1552                                     .params
1553                                     .iter()
1554                                     .map(|p| p.name.to_string())
1555                                     .collect::<Vec<String>>()
1556                                     .join(", ")
1557                             ),
1558                             Applicability::HasPlaceholders,
1559                         );
1560                     }
1561                 }
1562                 err
1563             }
1564
1565             ty::PredicateKind::WellFormed(arg) => {
1566                 // Same hacky approach as above to avoid deluging user
1567                 // with error messages.
1568                 if arg.references_error() || self.tcx.sess.has_errors() {
1569                     return;
1570                 }
1571
1572                 match arg.unpack() {
1573                     GenericArgKind::Lifetime(lt) => {
1574                         span_bug!(span, "unexpected well formed predicate: {:?}", lt)
1575                     }
1576                     GenericArgKind::Type(ty) => {
1577                         self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
1578                     }
1579                     GenericArgKind::Const(ct) => {
1580                         self.need_type_info_err_const(body_id, span, ct, ErrorCode::E0282)
1581                     }
1582                 }
1583             }
1584
1585             ty::PredicateKind::Subtype(ref data) => {
1586                 if data.references_error() || self.tcx.sess.has_errors() {
1587                     // no need to overload user in such cases
1588                     return;
1589                 }
1590                 let SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1591                 // both must be type variables, or the other would've been instantiated
1592                 assert!(a.is_ty_var() && b.is_ty_var());
1593                 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
1594             }
1595             ty::PredicateKind::Projection(ref data) => {
1596                 let trait_ref = data.to_poly_trait_ref(self.tcx);
1597                 let self_ty = trait_ref.skip_binder().self_ty();
1598                 let ty = data.skip_binder().ty;
1599                 if predicate.references_error() {
1600                     return;
1601                 }
1602                 if self_ty.needs_infer() && ty.needs_infer() {
1603                     // We do this for the `foo.collect()?` case to produce a suggestion.
1604                     let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
1605                     err.note(&format!("cannot satisfy `{}`", predicate));
1606                     err
1607                 } else {
1608                     let mut err = struct_span_err!(
1609                         self.tcx.sess,
1610                         span,
1611                         E0284,
1612                         "type annotations needed: cannot satisfy `{}`",
1613                         predicate,
1614                     );
1615                     err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1616                     err
1617                 }
1618             }
1619
1620             _ => {
1621                 if self.tcx.sess.has_errors() {
1622                     return;
1623                 }
1624                 let mut err = struct_span_err!(
1625                     self.tcx.sess,
1626                     span,
1627                     E0284,
1628                     "type annotations needed: cannot satisfy `{}`",
1629                     predicate,
1630                 );
1631                 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1632                 err
1633             }
1634         };
1635         self.note_obligation_cause(&mut err, obligation);
1636         err.emit();
1637     }
1638
1639     /// Returns `true` if the trait predicate may apply for *some* assignment
1640     /// to the type parameters.
1641     fn predicate_can_apply(
1642         &self,
1643         param_env: ty::ParamEnv<'tcx>,
1644         pred: ty::PolyTraitRef<'tcx>,
1645     ) -> bool {
1646         struct ParamToVarFolder<'a, 'tcx> {
1647             infcx: &'a InferCtxt<'a, 'tcx>,
1648             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1649         }
1650
1651         impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1652             fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1653                 self.infcx.tcx
1654             }
1655
1656             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1657                 if let ty::Param(ty::ParamTy { name, .. }) = ty.kind {
1658                     let infcx = self.infcx;
1659                     self.var_map.entry(ty).or_insert_with(|| {
1660                         infcx.next_ty_var(TypeVariableOrigin {
1661                             kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
1662                             span: DUMMY_SP,
1663                         })
1664                     })
1665                 } else {
1666                     ty.super_fold_with(self)
1667                 }
1668             }
1669         }
1670
1671         self.probe(|_| {
1672             let mut selcx = SelectionContext::new(self);
1673
1674             let cleaned_pred =
1675                 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
1676
1677             let cleaned_pred = super::project::normalize(
1678                 &mut selcx,
1679                 param_env,
1680                 ObligationCause::dummy(),
1681                 &cleaned_pred,
1682             )
1683             .value;
1684
1685             let obligation = Obligation::new(
1686                 ObligationCause::dummy(),
1687                 param_env,
1688                 cleaned_pred.without_const().to_predicate(selcx.tcx()),
1689             );
1690
1691             self.predicate_may_hold(&obligation)
1692         })
1693     }
1694
1695     fn note_obligation_cause(
1696         &self,
1697         err: &mut DiagnosticBuilder<'tcx>,
1698         obligation: &PredicateObligation<'tcx>,
1699     ) {
1700         // First, attempt to add note to this error with an async-await-specific
1701         // message, and fall back to regular note otherwise.
1702         if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
1703             self.note_obligation_cause_code(
1704                 err,
1705                 &obligation.predicate,
1706                 &obligation.cause.code,
1707                 &mut vec![],
1708             );
1709             self.suggest_unsized_bound_if_applicable(err, obligation);
1710         }
1711     }
1712
1713     fn suggest_unsized_bound_if_applicable(
1714         &self,
1715         err: &mut DiagnosticBuilder<'tcx>,
1716         obligation: &PredicateObligation<'tcx>,
1717     ) {
1718         let (pred, item_def_id, span) =
1719             match (obligation.predicate.kind(), &obligation.cause.code.peel_derives()) {
1720                 (
1721                     ty::PredicateKind::Trait(pred, _),
1722                     ObligationCauseCode::BindingObligation(item_def_id, span),
1723                 ) => (pred, item_def_id, span),
1724                 _ => return,
1725             };
1726
1727         let node = match (
1728             self.tcx.hir().get_if_local(*item_def_id),
1729             Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
1730         ) {
1731             (Some(node), true) => node,
1732             _ => return,
1733         };
1734         let generics = match node.generics() {
1735             Some(generics) => generics,
1736             None => return,
1737         };
1738         for param in generics.params {
1739             if param.span != *span
1740                 || param.bounds.iter().any(|bound| {
1741                     bound.trait_ref().and_then(|trait_ref| trait_ref.trait_def_id())
1742                         == self.tcx.lang_items().sized_trait()
1743                 })
1744             {
1745                 continue;
1746             }
1747             match node {
1748                 hir::Node::Item(
1749                     item
1750                     @
1751                     hir::Item {
1752                         kind:
1753                             hir::ItemKind::Enum(..)
1754                             | hir::ItemKind::Struct(..)
1755                             | hir::ItemKind::Union(..),
1756                         ..
1757                     },
1758                 ) => {
1759                     // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
1760                     // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
1761                     // is not.
1762                     let mut visitor = FindTypeParam {
1763                         param: param.name.ident().name,
1764                         invalid_spans: vec![],
1765                         nested: false,
1766                     };
1767                     visitor.visit_item(item);
1768                     if !visitor.invalid_spans.is_empty() {
1769                         let mut multispan: MultiSpan = param.span.into();
1770                         multispan.push_span_label(
1771                             param.span,
1772                             format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
1773                         );
1774                         for sp in visitor.invalid_spans {
1775                             multispan.push_span_label(
1776                                 sp,
1777                                 format!(
1778                                     "...if indirection was used here: `Box<{}>`",
1779                                     param.name.ident(),
1780                                 ),
1781                             );
1782                         }
1783                         err.span_help(
1784                             multispan,
1785                             &format!(
1786                                 "you could relax the implicit `Sized` bound on `{T}` if it were \
1787                                  used through indirection like `&{T}` or `Box<{T}>`",
1788                                 T = param.name.ident(),
1789                             ),
1790                         );
1791                         return;
1792                     }
1793                 }
1794                 _ => {}
1795             }
1796             let (span, separator) = match param.bounds {
1797                 [] => (span.shrink_to_hi(), ":"),
1798                 [.., bound] => (bound.span().shrink_to_hi(), " +"),
1799             };
1800             err.span_suggestion_verbose(
1801                 span,
1802                 "consider relaxing the implicit `Sized` restriction",
1803                 format!("{} ?Sized", separator),
1804                 Applicability::MachineApplicable,
1805             );
1806             return;
1807         }
1808     }
1809
1810     fn is_recursive_obligation(
1811         &self,
1812         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1813         cause_code: &ObligationCauseCode<'tcx>,
1814     ) -> bool {
1815         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1816             let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1817
1818             if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1819                 return true;
1820             }
1821         }
1822         false
1823     }
1824 }
1825
1826 /// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
1827 /// `param: ?Sized` would be a valid constraint.
1828 struct FindTypeParam {
1829     param: rustc_span::Symbol,
1830     invalid_spans: Vec<Span>,
1831     nested: bool,
1832 }
1833
1834 impl<'v> Visitor<'v> for FindTypeParam {
1835     type Map = rustc_hir::intravisit::ErasedMap<'v>;
1836
1837     fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1838         hir::intravisit::NestedVisitorMap::None
1839     }
1840
1841     fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1842         // We collect the spans of all uses of the "bare" type param, like in `field: T` or
1843         // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
1844         // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
1845         // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
1846         // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
1847         // in that case should make what happened clear enough.
1848         match ty.kind {
1849             hir::TyKind::Ptr(_) | hir::TyKind::Rptr(..) | hir::TyKind::TraitObject(..) => {}
1850             hir::TyKind::Path(hir::QPath::Resolved(None, path))
1851                 if path.segments.len() == 1 && path.segments[0].ident.name == self.param =>
1852             {
1853                 if !self.nested {
1854                     self.invalid_spans.push(ty.span);
1855                 }
1856             }
1857             hir::TyKind::Path(_) => {
1858                 let prev = self.nested;
1859                 self.nested = true;
1860                 hir::intravisit::walk_ty(self, ty);
1861                 self.nested = prev;
1862             }
1863             _ => {
1864                 hir::intravisit::walk_ty(self, ty);
1865             }
1866         }
1867     }
1868 }
1869
1870 pub fn recursive_type_with_infinite_size_error(
1871     tcx: TyCtxt<'tcx>,
1872     type_def_id: DefId,
1873     spans: Vec<Span>,
1874 ) {
1875     assert!(type_def_id.is_local());
1876     let span = tcx.hir().span_if_local(type_def_id).unwrap();
1877     let span = tcx.sess.source_map().guess_head_span(span);
1878     let path = tcx.def_path_str(type_def_id);
1879     let mut err =
1880         struct_span_err!(tcx.sess, span, E0072, "recursive type `{}` has infinite size", path);
1881     err.span_label(span, "recursive type has infinite size");
1882     for &span in &spans {
1883         err.span_label(span, "recursive without indirection");
1884     }
1885     let msg = format!(
1886         "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `{}` representable",
1887         path,
1888     );
1889     if spans.len() <= 4 {
1890         err.multipart_suggestion(
1891             &msg,
1892             spans
1893                 .iter()
1894                 .flat_map(|&span| {
1895                     vec![
1896                         (span.shrink_to_lo(), "Box<".to_string()),
1897                         (span.shrink_to_hi(), ">".to_string()),
1898                     ]
1899                     .into_iter()
1900                 })
1901                 .collect(),
1902             Applicability::HasPlaceholders,
1903         );
1904     } else {
1905         err.help(&msg);
1906     }
1907     err.emit();
1908 }
1909
1910 /// Summarizes information
1911 #[derive(Clone)]
1912 pub enum ArgKind {
1913     /// An argument of non-tuple type. Parameters are (name, ty)
1914     Arg(String, String),
1915
1916     /// An argument of tuple type. For a "found" argument, the span is
1917     /// the locationo in the source of the pattern. For a "expected"
1918     /// argument, it will be None. The vector is a list of (name, ty)
1919     /// strings for the components of the tuple.
1920     Tuple(Option<Span>, Vec<(String, String)>),
1921 }
1922
1923 impl ArgKind {
1924     fn empty() -> ArgKind {
1925         ArgKind::Arg("_".to_owned(), "_".to_owned())
1926     }
1927
1928     /// Creates an `ArgKind` from the expected type of an
1929     /// argument. It has no name (`_`) and an optional source span.
1930     pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1931         match t.kind {
1932             ty::Tuple(ref tys) => ArgKind::Tuple(
1933                 span,
1934                 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
1935             ),
1936             _ => ArgKind::Arg("_".to_owned(), t.to_string()),
1937         }
1938     }
1939 }