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