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