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