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