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