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