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