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