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