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