1 //! Error Reporting Code for the inference engine
3 //! Because of the way inference, and in particular region inference,
4 //! works, it often happens that errors are not detected until far after
5 //! the relevant line of code has been type-checked. Therefore, there is
6 //! an elaborate system to track why a particular constraint in the
7 //! inference graph arose so that we can explain to the user what gave
8 //! rise to a particular error.
10 //! The system is based around a set of "origin" types. An "origin" is the
11 //! reason that a constraint or inference variable arose. There are
12 //! different "origin" enums for different kinds of constraints/variables
13 //! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
14 //! a span, but also more information so that we can generate a meaningful
17 //! Having a catalog of all the different reasons an error can arise is
18 //! also useful for other reasons, like cross-referencing FAQs etc, though
19 //! we are not really taking advantage of this yet.
21 //! # Region Inference
23 //! Region inference is particularly tricky because it always succeeds "in
24 //! the moment" and simply registers a constraint. Then, at the end, we
25 //! can compute the full graph and report errors, so we need to be able to
26 //! store and later report what gave rise to the conflicting constraints.
30 //! Determining whether `T1 <: T2` often involves a number of subtypes and
31 //! subconstraints along the way. A "TypeTrace" is an extended version
32 //! of an origin that traces the types and other values that were being
33 //! compared. It is not necessarily comprehensive (in fact, at the time of
34 //! this writing it only tracks the root values being compared) but I'd
35 //! like to extend it to include significant "waypoints". For example, if
36 //! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
37 //! <: T4` fails, I'd like the trace to include enough information to say
38 //! "in the 2nd element of the tuple". Similarly, failures when comparing
39 //! arguments or return types in fn types should be able to cite the
40 //! specific position, etc.
44 //! Of course, there is still a LOT of code in typeck that has yet to be
45 //! ported to this system, and which relies on string concatenation at the
46 //! time of error detection.
48 use super::lexical_region_resolve::RegionResolutionError;
49 use super::region_constraints::GenericKind;
50 use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
53 use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
54 use crate::infer::ExpectedFound;
55 use crate::traits::error_reporting::report_object_safety_error;
57 IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
58 StatementAsExpression,
61 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
62 use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed, IntoDiagnosticArg};
63 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString, MultiSpan};
65 use rustc_hir::def::DefKind;
66 use rustc_hir::def_id::{DefId, LocalDefId};
67 use rustc_hir::lang_items::LangItem;
69 use rustc_middle::dep_graph::DepContext;
70 use rustc_middle::ty::print::with_no_trimmed_paths;
71 use rustc_middle::ty::relate::{self, RelateResult, TypeRelation};
72 use rustc_middle::ty::{
73 self, error::TypeError, Binder, List, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
76 use rustc_span::{sym, symbol::kw, BytePos, DesugaringKind, Pos, Span};
77 use rustc_target::spec::abi;
78 use std::ops::ControlFlow;
79 use std::{cmp, fmt, iter};
83 pub(crate) mod need_type_info;
84 pub use need_type_info::TypeAnnotationNeeded;
86 pub mod nice_region_error;
88 pub(super) fn note_and_explain_region<'tcx>(
92 region: ty::Region<'tcx>,
94 alt_span: Option<Span>,
96 let (description, span) = match *region {
97 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
98 msg_span_from_free_region(tcx, region, alt_span)
101 ty::RePlaceholder(_) => return,
103 // FIXME(#13998) RePlaceholder should probably print like
104 // ReFree rather than dumping Debug output on the user.
106 // We shouldn't really be having unification failures with ReVar
107 // and ReLateBound though.
108 ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
109 (format!("lifetime {:?}", region), alt_span)
113 emit_msg_span(err, prefix, description, span, suffix);
116 fn explain_free_region<'tcx>(
118 err: &mut Diagnostic,
120 region: ty::Region<'tcx>,
123 let (description, span) = msg_span_from_free_region(tcx, region, None);
125 label_msg_span(err, prefix, description, span, suffix);
128 fn msg_span_from_free_region<'tcx>(
130 region: ty::Region<'tcx>,
131 alt_span: Option<Span>,
132 ) -> (String, Option<Span>) {
134 ty::ReEarlyBound(_) | ty::ReFree(_) => {
135 let (msg, span) = msg_span_from_early_bound_and_free_regions(tcx, region);
138 ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
139 _ => bug!("{:?}", region),
143 fn msg_span_from_early_bound_and_free_regions<'tcx>(
145 region: ty::Region<'tcx>,
146 ) -> (String, Span) {
147 let scope = region.free_region_binding_scope(tcx).expect_local();
149 ty::ReEarlyBound(ref br) => {
150 let mut sp = tcx.def_span(scope);
152 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
156 let text = if br.has_name() {
157 format!("the lifetime `{}` as defined here", br.name)
159 format!("the anonymous lifetime as defined here")
163 ty::ReFree(ref fr) => {
164 if !fr.bound_region.is_named()
165 && let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region)
167 ("the anonymous lifetime defined here".to_string(), ty.span)
169 match fr.bound_region {
170 ty::BoundRegionKind::BrNamed(_, name) => {
171 let mut sp = tcx.def_span(scope);
173 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
177 let text = if name == kw::UnderscoreLifetime {
178 format!("the anonymous lifetime as defined here")
180 format!("the lifetime `{}` as defined here", name)
185 format!("the anonymous lifetime #{} defined here", idx + 1),
189 format!("the lifetime `{}` as defined here", region),
200 err: &mut Diagnostic,
206 let message = format!("{}{}{}", prefix, description, suffix);
208 if let Some(span) = span {
209 err.span_note(span, &message);
216 err: &mut Diagnostic,
222 let message = format!("{}{}{}", prefix, description, suffix);
224 if let Some(span) = span {
225 err.span_label(span, &message);
231 pub fn unexpected_hidden_region_diagnostic<'tcx>(
235 hidden_region: ty::Region<'tcx>,
236 opaque_ty: ty::OpaqueTypeKey<'tcx>,
237 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
238 let opaque_ty = tcx.mk_opaque(opaque_ty.def_id.to_def_id(), opaque_ty.substs);
239 let mut err = struct_span_err!(
243 "hidden type for `{opaque_ty}` captures lifetime that does not appear in bounds",
246 // Explain the region we are capturing.
247 match *hidden_region {
248 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
249 // Assuming regionck succeeded (*), we ought to always be
250 // capturing *some* region from the fn header, and hence it
251 // ought to be free. So under normal circumstances, we will go
252 // down this path which gives a decent human readable
255 // (*) if not, the `tainted_by_errors` field would be set to
256 // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
260 &format!("hidden type `{}` captures ", hidden_ty),
264 if let Some(reg_info) = tcx.is_suitable_region(hidden_region) {
265 let fn_returns = tcx.return_type_impl_or_dyn_traits(reg_info.def_id);
266 nice_region_error::suggest_new_region_bound(
270 hidden_region.to_string(),
272 format!("captures `{}`", hidden_region),
278 // Ugh. This is a painful case: the hidden region is not one
279 // that we can easily summarize or explain. This can happen
281 // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
284 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
285 // if condition() { a } else { b }
289 // Here the captured lifetime is the intersection of `'a` and
290 // `'b`, which we can't quite express.
292 // We can at least report a really cryptic error for now.
293 note_and_explain_region(
296 &format!("hidden type `{}` captures ", hidden_ty),
307 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
308 pub fn report_region_errors(
310 generic_param_scope: LocalDefId,
311 errors: &[RegionResolutionError<'tcx>],
313 debug!("report_region_errors(): {} errors to start", errors.len());
315 // try to pre-process the errors, which will group some of them
316 // together into a `ProcessedErrors` group:
317 let errors = self.process_errors(errors);
319 debug!("report_region_errors: {} errors after preprocessing", errors.len());
321 for error in errors {
322 debug!("report_region_errors: error = {:?}", error);
324 if !self.try_report_nice_region_error(&error) {
325 match error.clone() {
326 // These errors could indicate all manner of different
327 // problems with many different solutions. Rather
328 // than generate a "one size fits all" error, what we
329 // attempt to do is go through a number of specific
330 // scenarios and try to find the best way to present
331 // the error. If all of these fails, we fall back to a rather
332 // general bit of code that displays the error information
333 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
334 if sub.is_placeholder() || sup.is_placeholder() {
335 self.report_placeholder_failure(origin, sub, sup).emit();
337 self.report_concrete_failure(origin, sub, sup).emit();
341 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
342 self.report_generic_bound_failure(
351 RegionResolutionError::SubSupConflict(
360 if sub_r.is_placeholder() {
361 self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
362 } else if sup_r.is_placeholder() {
363 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
365 self.report_sub_sup_conflict(
366 var_origin, sub_origin, sub_r, sup_origin, sup_r,
371 RegionResolutionError::UpperBoundUniverseConflict(
378 assert!(sup_r.is_placeholder());
380 // Make a dummy value for the "sub region" --
381 // this is the initial value of the
382 // placeholder. In practice, we expect more
383 // tailored errors that don't really use this
385 let sub_r = self.tcx.lifetimes.re_erased;
387 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
394 // This method goes through all the errors and try to group certain types
395 // of error together, for the purpose of suggesting explicit lifetime
396 // parameters to the user. This is done so that we can have a more
397 // complete view of what lifetimes should be the same.
398 // If the return value is an empty vector, it means that processing
399 // failed (so the return value of this method should not be used).
401 // The method also attempts to weed out messages that seem like
402 // duplicates that will be unhelpful to the end-user. But
403 // obviously it never weeds out ALL errors.
406 errors: &[RegionResolutionError<'tcx>],
407 ) -> Vec<RegionResolutionError<'tcx>> {
408 debug!("process_errors()");
410 // We want to avoid reporting generic-bound failures if we can
411 // avoid it: these have a very high rate of being unhelpful in
412 // practice. This is because they are basically secondary
413 // checks that test the state of the region graph after the
414 // rest of inference is done, and the other kinds of errors
415 // indicate that the region constraint graph is internally
416 // inconsistent, so these test results are likely to be
419 // Therefore, we filter them out of the list unless they are
420 // the only thing in the list.
422 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
423 RegionResolutionError::GenericBoundFailure(..) => true,
424 RegionResolutionError::ConcreteFailure(..)
425 | RegionResolutionError::SubSupConflict(..)
426 | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
429 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
432 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
435 // sort the errors by span, for better error message stability.
436 errors.sort_by_key(|u| match *u {
437 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
438 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
439 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
440 RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
445 /// Adds a note if the types come from similarly named crates
446 fn check_and_note_conflicting_crates(&self, err: &mut Diagnostic, terr: TypeError<'tcx>) {
447 use hir::def_id::CrateNum;
448 use rustc_hir::definitions::DisambiguatedDefPathData;
449 use ty::print::Printer;
450 use ty::subst::GenericArg;
452 struct AbsolutePathPrinter<'tcx> {
456 struct NonTrivialPath;
458 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
459 type Error = NonTrivialPath;
461 type Path = Vec<String>;
464 type DynExistential = !;
467 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
471 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
475 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
479 fn print_dyn_existential(
481 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
482 ) -> Result<Self::DynExistential, Self::Error> {
486 fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
490 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
491 Ok(vec![self.tcx.crate_name(cnum).to_string()])
496 _trait_ref: Option<ty::TraitRef<'tcx>>,
497 ) -> Result<Self::Path, Self::Error> {
503 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
504 _disambiguated_data: &DisambiguatedDefPathData,
506 _trait_ref: Option<ty::TraitRef<'tcx>>,
507 ) -> Result<Self::Path, Self::Error> {
512 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
513 disambiguated_data: &DisambiguatedDefPathData,
514 ) -> Result<Self::Path, Self::Error> {
515 let mut path = print_prefix(self)?;
516 path.push(disambiguated_data.to_string());
519 fn path_generic_args(
521 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
522 _args: &[GenericArg<'tcx>],
523 ) -> Result<Self::Path, Self::Error> {
528 let report_path_match = |err: &mut Diagnostic, did1: DefId, did2: DefId| {
529 // Only external crates, if either is from a local
530 // module we could have false positives
531 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
533 |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
535 // We compare strings because DefPath can be different
536 // for imported and non-imported crates
537 let same_path = || -> Result<_, NonTrivialPath> {
538 Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
539 || abs_path(did1)? == abs_path(did2)?)
541 if same_path().unwrap_or(false) {
542 let crate_name = self.tcx.crate_name(did1.krate);
544 "perhaps two different versions of crate `{}` are being used?",
551 TypeError::Sorts(ref exp_found) => {
552 // if they are both "path types", there's a chance of ambiguity
553 // due to different versions of the same crate
554 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
555 (exp_found.expected.kind(), exp_found.found.kind())
557 report_path_match(err, exp_adt.did(), found_adt.did());
560 TypeError::Traits(ref exp_found) => {
561 report_path_match(err, exp_found.expected, exp_found.found);
563 _ => (), // FIXME(#22750) handle traits and stuff
567 fn note_error_origin(
569 err: &mut Diagnostic,
570 cause: &ObligationCause<'tcx>,
571 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
572 terr: TypeError<'tcx>,
574 match *cause.code() {
575 ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
576 let ty = self.resolve_vars_if_possible(root_ty);
577 if !matches!(ty.kind(), ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)))
579 // don't show type `_`
580 if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
581 && let ty::Adt(def, substs) = ty.kind()
582 && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
584 err.span_label(span, format!("this is an iterator with items of type `{}`", substs.type_at(0)));
586 err.span_label(span, format!("this expression has type `{}`", ty));
589 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
590 && ty.is_box() && ty.boxed_ty() == found
591 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
595 "consider dereferencing the boxed value",
596 format!("*{}", snippet),
597 Applicability::MachineApplicable,
601 ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
602 err.span_label(span, "expected due to this");
604 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
614 opt_suggest_box_span,
618 hir::MatchSource::TryDesugar => {
619 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
620 let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
621 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
622 let arg_expr = args.first().expect("try desugaring call w/out arg");
623 self.in_progress_typeck_results.and_then(|typeck_results| {
624 typeck_results.borrow().expr_ty_opt(arg_expr)
627 bug!("try desugaring w/out call expr as scrutinee");
631 Some(ty) if expected == ty => {
632 let source_map = self.tcx.sess.source_map();
634 source_map.end_point(cause.span),
635 "try removing this `?`",
637 Applicability::MachineApplicable,
645 // `prior_arm_ty` can be `!`, `expected` will have better info when present.
646 let t = self.resolve_vars_if_possible(match exp_found {
647 Some(ty::error::ExpectedFound { expected, .. }) => expected,
650 let source_map = self.tcx.sess.source_map();
651 let mut any_multiline_arm = source_map.is_multiline(arm_span);
652 if prior_arms.len() <= 4 {
653 for sp in prior_arms {
654 any_multiline_arm |= source_map.is_multiline(*sp);
655 err.span_label(*sp, format!("this is found to be of type `{}`", t));
657 } else if let Some(sp) = prior_arms.last() {
658 any_multiline_arm |= source_map.is_multiline(*sp);
661 format!("this and all prior arms are found to be of type `{}`", t),
664 let outer_error_span = if any_multiline_arm {
665 // Cover just `match` and the scrutinee expression, not
666 // the entire match body, to reduce diagram noise.
667 cause.span.shrink_to_lo().to(scrut_span)
671 let msg = "`match` arms have incompatible types";
672 err.span_label(outer_error_span, msg);
673 self.suggest_remove_semi_or_return_binding(
682 if let Some(ret_sp) = opt_suggest_box_span {
683 // Get return type span and point to it.
684 self.suggest_boxing_for_return_impl_trait(
687 prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
692 ObligationCauseCode::IfExpression(box IfExpressionCause {
698 opt_suggest_box_span,
700 let then_span = self.find_block_span_from_hir_id(then_id);
701 let else_span = self.find_block_span_from_hir_id(else_id);
702 err.span_label(then_span, "expected because of this");
703 if let Some(sp) = outer_span {
704 err.span_label(sp, "`if` and `else` have incompatible types");
706 self.suggest_remove_semi_or_return_binding(
715 if let Some(ret_sp) = opt_suggest_box_span {
716 self.suggest_boxing_for_return_impl_trait(
719 [then_span, else_span].into_iter(),
723 ObligationCauseCode::LetElse => {
724 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
725 err.help("...or use `match` instead of `let...else`");
728 if let ObligationCauseCode::BindingObligation(_, span)
729 | ObligationCauseCode::ExprBindingObligation(_, span, ..)
730 = cause.code().peel_derives()
731 && let TypeError::RegionsPlaceholderMismatch = terr
733 err.span_note(*span, "the lifetime requirement is introduced here");
739 fn suggest_remove_semi_or_return_binding(
741 err: &mut Diagnostic,
742 first_id: Option<hir::HirId>,
745 second_id: Option<hir::HirId>,
749 let remove_semicolon = [
750 (first_id, self.resolve_vars_if_possible(second_ty)),
751 (second_id, self.resolve_vars_if_possible(first_ty)),
754 .find_map(|(id, ty)| {
755 let hir::Node::Block(blk) = self.tcx.hir().get(id?) else { return None };
756 self.could_remove_semicolon(blk, ty)
758 match remove_semicolon {
759 Some((sp, StatementAsExpression::NeedsBoxing)) => {
760 err.multipart_suggestion(
761 "consider removing this semicolon and boxing the expressions",
763 (first_span.shrink_to_lo(), "Box::new(".to_string()),
764 (first_span.shrink_to_hi(), ")".to_string()),
765 (second_span.shrink_to_lo(), "Box::new(".to_string()),
766 (second_span.shrink_to_hi(), ")".to_string()),
769 Applicability::MachineApplicable,
772 Some((sp, StatementAsExpression::CorrectType)) => {
773 err.span_suggestion_short(
775 "consider removing this semicolon",
777 Applicability::MachineApplicable,
781 for (id, ty) in [(first_id, second_ty), (second_id, first_ty)] {
783 && let hir::Node::Block(blk) = self.tcx.hir().get(id)
784 && self.consider_returning_binding(blk, ty, err)
793 fn suggest_boxing_for_return_impl_trait(
795 err: &mut Diagnostic,
797 arm_spans: impl Iterator<Item = Span>,
799 err.multipart_suggestion(
800 "you could change the return type to be a boxed trait object",
802 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
803 (return_sp.shrink_to_hi(), ">".to_string()),
805 Applicability::MaybeIncorrect,
809 [(sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string())]
812 .collect::<Vec<_>>();
813 err.multipart_suggestion(
814 "if you change the return type to expect trait objects, box the returned expressions",
816 Applicability::MaybeIncorrect,
820 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
821 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
822 /// populate `other_value` with `other_ty`.
826 /// ^^^^--------^ this is highlighted
828 /// | this type argument is exactly the same as the other type, not highlighted
829 /// this is highlighted
831 /// -------- this type is the same as a type argument in the other type, not highlighted
835 value: &mut DiagnosticStyledString,
836 other_value: &mut DiagnosticStyledString,
838 sub: ty::subst::SubstsRef<'tcx>,
842 // `value` and `other_value` hold two incomplete type representation for display.
843 // `name` is the path of both types being compared. `sub`
844 value.push_highlighted(name);
847 value.push_highlighted("<");
850 // Output the lifetimes for the first type
854 let s = lifetime.to_string();
855 if s.is_empty() { "'_".to_string() } else { s }
859 if !lifetimes.is_empty() {
860 if sub.regions().count() < len {
861 value.push_normal(lifetimes + ", ");
863 value.push_normal(lifetimes);
867 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
868 // `pos` and `other_ty`.
869 for (i, type_arg) in sub.types().enumerate() {
871 let values = self.cmp(type_arg, other_ty);
872 value.0.extend((values.0).0);
873 other_value.0.extend((values.1).0);
875 value.push_highlighted(type_arg.to_string());
878 if len > 0 && i != len - 1 {
879 value.push_normal(", ");
883 value.push_highlighted(">");
887 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
888 /// as that is the difference to the other type.
890 /// For the following code:
892 /// ```ignore (illustrative)
893 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
896 /// The type error output will behave in the following way:
900 /// ^^^^--------^ this is highlighted
902 /// | this type argument is exactly the same as the other type, not highlighted
903 /// this is highlighted
905 /// -------- this type is the same as a type argument in the other type, not highlighted
909 mut t1_out: &mut DiagnosticStyledString,
910 mut t2_out: &mut DiagnosticStyledString,
912 sub: &'tcx [ty::GenericArg<'tcx>],
916 // FIXME/HACK: Go back to `SubstsRef` to use its inherent methods,
917 // ideally that shouldn't be necessary.
918 let sub = self.tcx.intern_substs(sub);
919 for (i, ta) in sub.types().enumerate() {
921 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
924 if let ty::Adt(def, _) = ta.kind() {
925 let path_ = self.tcx.def_path_str(def.did());
926 if path_ == other_path {
927 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
935 /// Adds a `,` to the type representation only if it is appropriate.
938 value: &mut DiagnosticStyledString,
939 other_value: &mut DiagnosticStyledString,
943 if len > 0 && pos != len - 1 {
944 value.push_normal(", ");
945 other_value.push_normal(", ");
949 fn normalize_fn_sig_for_diagnostic(&self, sig: ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx> {
950 if let Some(normalize) = &self.normalize_fn_sig_for_diagnostic {
957 /// Given two `fn` signatures highlight only sub-parts that are different.
960 sig1: &ty::PolyFnSig<'tcx>,
961 sig2: &ty::PolyFnSig<'tcx>,
962 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
963 let sig1 = &self.normalize_fn_sig_for_diagnostic(*sig1);
964 let sig2 = &self.normalize_fn_sig_for_diagnostic(*sig2);
966 let get_lifetimes = |sig| {
967 use rustc_hir::def::Namespace;
968 let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
969 .name_all_regions(sig)
971 let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
972 (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
975 let (lt1, sig1) = get_lifetimes(sig1);
976 let (lt2, sig2) = get_lifetimes(sig2);
978 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
980 DiagnosticStyledString::normal("".to_string()),
981 DiagnosticStyledString::normal("".to_string()),
984 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
986 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
987 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
989 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
991 if sig1.abi != abi::Abi::Rust {
992 values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
994 if sig2.abi != abi::Abi::Rust {
995 values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
998 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1000 let lifetime_diff = lt1 != lt2;
1001 values.0.push(lt1, lifetime_diff);
1002 values.1.push(lt2, lifetime_diff);
1004 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1006 values.0.push_normal("fn(");
1007 values.1.push_normal("fn(");
1009 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1011 let len1 = sig1.inputs().len();
1012 let len2 = sig2.inputs().len();
1014 for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1015 let (x1, x2) = self.cmp(*l, *r);
1016 (values.0).0.extend(x1.0);
1017 (values.1).0.extend(x2.0);
1018 self.push_comma(&mut values.0, &mut values.1, len1, i);
1021 for (i, l) in sig1.inputs().iter().enumerate() {
1022 values.0.push_highlighted(l.to_string());
1024 values.0.push_highlighted(", ");
1027 for (i, r) in sig2.inputs().iter().enumerate() {
1028 values.1.push_highlighted(r.to_string());
1030 values.1.push_highlighted(", ");
1035 if sig1.c_variadic {
1037 values.0.push_normal(", ");
1039 values.0.push("...", !sig2.c_variadic);
1041 if sig2.c_variadic {
1043 values.1.push_normal(", ");
1045 values.1.push("...", !sig1.c_variadic);
1048 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1050 values.0.push_normal(")");
1051 values.1.push_normal(")");
1053 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1055 let output1 = sig1.output();
1056 let output2 = sig2.output();
1057 let (x1, x2) = self.cmp(output1, output2);
1058 if !output1.is_unit() {
1059 values.0.push_normal(" -> ");
1060 (values.0).0.extend(x1.0);
1062 if !output2.is_unit() {
1063 values.1.push_normal(" -> ");
1064 (values.1).0.extend(x2.0);
1069 /// Compares two given types, eliding parts that are the same between them and highlighting
1070 /// relevant differences, and return two representation of those types for highlighted printing.
1075 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1076 debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1079 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1080 match (a.kind(), b.kind()) {
1081 (a, b) if *a == *b => true,
1082 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1084 &ty::Infer(ty::InferTy::IntVar(_)),
1085 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1087 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1089 &ty::Infer(ty::InferTy::FloatVar(_)),
1090 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1096 fn push_ty_ref<'tcx>(
1097 region: ty::Region<'tcx>,
1099 mutbl: hir::Mutability,
1100 s: &mut DiagnosticStyledString,
1102 let mut r = region.to_string();
1108 s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1109 s.push_normal(ty.to_string());
1112 // process starts here
1113 match (t1.kind(), t2.kind()) {
1114 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1115 let did1 = def1.did();
1116 let did2 = def2.did();
1117 let sub_no_defaults_1 =
1118 self.tcx.generics_of(did1).own_substs_no_defaults(self.tcx, sub1);
1119 let sub_no_defaults_2 =
1120 self.tcx.generics_of(did2).own_substs_no_defaults(self.tcx, sub2);
1121 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1122 let path1 = self.tcx.def_path_str(did1);
1123 let path2 = self.tcx.def_path_str(did2);
1125 // Easy case. Replace same types with `_` to shorten the output and highlight
1126 // the differing ones.
1127 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1130 // --- ^ type argument elided
1132 // highlighted in output
1133 values.0.push_normal(path1);
1134 values.1.push_normal(path2);
1136 // Avoid printing out default generic parameters that are common to both
1138 let len1 = sub_no_defaults_1.len();
1139 let len2 = sub_no_defaults_2.len();
1140 let common_len = cmp::min(len1, len2);
1141 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1142 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1143 let common_default_params =
1144 iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1145 .filter(|(a, b)| a == b)
1147 let len = sub1.len() - common_default_params;
1148 let consts_offset = len - sub1.consts().count();
1150 // Only draw `<...>` if there are lifetime/type arguments.
1152 values.0.push_normal("<");
1153 values.1.push_normal("<");
1156 fn lifetime_display(lifetime: Region<'_>) -> String {
1157 let s = lifetime.to_string();
1158 if s.is_empty() { "'_".to_string() } else { s }
1160 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1161 // all diagnostics that use this output
1165 // ^^ ^^ --- type arguments are not elided
1167 // | elided as they were the same
1168 // not elided, they were different, but irrelevant
1170 // For bound lifetimes, keep the names of the lifetimes,
1171 // even if they are the same so that it's clear what's happening
1172 // if we have something like
1174 // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1175 // for<'r> fn(Inv<'r>, Inv<'r>)
1176 let lifetimes = sub1.regions().zip(sub2.regions());
1177 for (i, lifetimes) in lifetimes.enumerate() {
1178 let l1 = lifetime_display(lifetimes.0);
1179 let l2 = lifetime_display(lifetimes.1);
1180 if lifetimes.0 != lifetimes.1 {
1181 values.0.push_highlighted(l1);
1182 values.1.push_highlighted(l2);
1183 } else if lifetimes.0.is_late_bound() {
1184 values.0.push_normal(l1);
1185 values.1.push_normal(l2);
1187 values.0.push_normal("'_");
1188 values.1.push_normal("'_");
1190 self.push_comma(&mut values.0, &mut values.1, len, i);
1193 // We're comparing two types with the same path, so we compare the type
1194 // arguments for both. If they are the same, do not highlight and elide from the
1198 // ^ elided type as this type argument was the same in both sides
1199 let type_arguments = sub1.types().zip(sub2.types());
1200 let regions_len = sub1.regions().count();
1201 let num_display_types = consts_offset - regions_len;
1202 for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1203 let i = i + regions_len;
1205 values.0.push_normal("_");
1206 values.1.push_normal("_");
1208 let (x1, x2) = self.cmp(ta1, ta2);
1209 (values.0).0.extend(x1.0);
1210 (values.1).0.extend(x2.0);
1212 self.push_comma(&mut values.0, &mut values.1, len, i);
1215 // Do the same for const arguments, if they are equal, do not highlight and
1216 // elide them from the output.
1217 let const_arguments = sub1.consts().zip(sub2.consts());
1218 for (i, (ca1, ca2)) in const_arguments.enumerate() {
1219 let i = i + consts_offset;
1221 values.0.push_normal("_");
1222 values.1.push_normal("_");
1224 values.0.push_highlighted(ca1.to_string());
1225 values.1.push_highlighted(ca2.to_string());
1227 self.push_comma(&mut values.0, &mut values.1, len, i);
1230 // Close the type argument bracket.
1231 // Only draw `<...>` if there are lifetime/type arguments.
1233 values.0.push_normal(">");
1234 values.1.push_normal(">");
1239 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1241 // ------- this type argument is exactly the same as the other type
1257 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1260 // ------- this type argument is exactly the same as the other type
1275 // We can't find anything in common, highlight relevant part of type path.
1276 // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1277 // foo::bar::Baz<Qux>
1278 // foo::bar::Bar<Zar>
1279 // -------- this part of the path is different
1281 let t1_str = t1.to_string();
1282 let t2_str = t2.to_string();
1283 let min_len = t1_str.len().min(t2_str.len());
1285 const SEPARATOR: &str = "::";
1286 let separator_len = SEPARATOR.len();
1287 let split_idx: usize =
1288 iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1289 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1290 .map(|(mod_str, _)| mod_str.len() + separator_len)
1294 "cmp: separator_len={}, split_idx={}, min_len={}",
1295 separator_len, split_idx, min_len
1298 if split_idx >= min_len {
1299 // paths are identical, highlight everything
1301 DiagnosticStyledString::highlighted(t1_str),
1302 DiagnosticStyledString::highlighted(t2_str),
1305 let (common, uniq1) = t1_str.split_at(split_idx);
1306 let (_, uniq2) = t2_str.split_at(split_idx);
1307 debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1309 values.0.push_normal(common);
1310 values.0.push_highlighted(uniq1);
1311 values.1.push_normal(common);
1312 values.1.push_highlighted(uniq2);
1319 // When finding T != &T, highlight only the borrow
1320 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(ref_ty1, t2) => {
1321 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1322 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1323 values.1.push_normal(t2.to_string());
1326 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(t1, ref_ty2) => {
1327 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1328 values.0.push_normal(t1.to_string());
1329 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1333 // When encountering &T != &mut T, highlight only the borrow
1334 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1335 if equals(ref_ty1, ref_ty2) =>
1337 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1338 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1339 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1343 // When encountering tuples of the same size, highlight only the differing types
1344 (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1346 (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1347 let len = substs1.len();
1348 for (i, (left, right)) in substs1.iter().zip(substs2).enumerate() {
1349 let (x1, x2) = self.cmp(left, right);
1350 (values.0).0.extend(x1.0);
1351 (values.1).0.extend(x2.0);
1352 self.push_comma(&mut values.0, &mut values.1, len, i);
1355 // Keep the output for single element tuples as `(ty,)`.
1356 values.0.push_normal(",");
1357 values.1.push_normal(",");
1359 values.0.push_normal(")");
1360 values.1.push_normal(")");
1364 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1365 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1366 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1367 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1368 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1369 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1370 let same_path = path1 == path2;
1371 values.0.push(path1, !same_path);
1372 values.1.push(path2, !same_path);
1376 (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1377 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1378 let mut values = self.cmp_fn_sig(&sig1, sig2);
1379 values.0.push_highlighted(format!(
1381 self.tcx.def_path_str_with_substs(*did1, substs1)
1386 (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1387 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1388 let mut values = self.cmp_fn_sig(sig1, &sig2);
1389 values.1.push_normal(format!(
1391 self.tcx.def_path_str_with_substs(*did2, substs2)
1396 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1400 // The two types are the same, elide and don't highlight.
1401 (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1403 // We couldn't find anything in common, highlight everything.
1405 DiagnosticStyledString::highlighted(t1.to_string()),
1406 DiagnosticStyledString::highlighted(t2.to_string()),
1413 /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1414 /// the return type of `async fn`s.
1416 /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1418 /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1419 /// the message in `secondary_span` as the primary label, and apply the message that would
1420 /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1421 /// E0271, like `src/test/ui/issues/issue-39970.stderr`.
1424 skip(self, diag, secondary_span, swap_secondary_and_primary, prefer_label)
1426 pub fn note_type_err(
1428 diag: &mut Diagnostic,
1429 cause: &ObligationCause<'tcx>,
1430 secondary_span: Option<(Span, String)>,
1431 mut values: Option<ValuePairs<'tcx>>,
1432 terr: TypeError<'tcx>,
1433 swap_secondary_and_primary: bool,
1436 let span = cause.span();
1438 // For some types of errors, expected-found does not make
1439 // sense, so just ignore the values we were given.
1440 if let TypeError::CyclicTy(_) = terr {
1443 struct OpaqueTypesVisitor<'tcx> {
1444 types: FxHashMap<TyCategory, FxHashSet<Span>>,
1445 expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1446 found: FxHashMap<TyCategory, FxHashSet<Span>>,
1451 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1452 fn visit_expected_found(
1458 let mut types_visitor = OpaqueTypesVisitor {
1459 types: Default::default(),
1460 expected: Default::default(),
1461 found: Default::default(),
1465 // The visitor puts all the relevant encountered types in `self.types`, but in
1466 // here we want to visit two separate types with no relation to each other, so we
1467 // move the results from `types` to `expected` or `found` as appropriate.
1468 expected.visit_with(&mut types_visitor);
1469 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1470 found.visit_with(&mut types_visitor);
1471 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1475 fn report(&self, err: &mut Diagnostic) {
1476 self.add_labels_for_types(err, "expected", &self.expected);
1477 self.add_labels_for_types(err, "found", &self.found);
1480 fn add_labels_for_types(
1482 err: &mut Diagnostic,
1484 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1486 for (key, values) in types.iter() {
1487 let count = values.len();
1488 let kind = key.descr();
1489 let mut returned_async_output_error = false;
1491 if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
1492 if [sp] != err.span.primary_spans() {
1493 let mut span: MultiSpan = sp.into();
1494 span.push_span_label(
1497 "checked the `Output` of this `async fn`, {}{} {}{}",
1498 if count > 1 { "one of the " } else { "" },
1506 "while checking the return type of the `async fn`",
1512 "checked the `Output` of this `async fn`, {}{} {}{}",
1513 if count > 1 { "one of the " } else { "" },
1519 err.note("while checking the return type of the `async fn`");
1521 returned_async_output_error = true;
1527 if count == 1 { "the " } else { "one of the " },
1539 impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1540 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1541 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1542 let span = self.tcx.def_span(def_id);
1543 // Avoid cluttering the output when the "found" and error span overlap:
1545 // error[E0308]: mismatched types
1546 // --> $DIR/issue-20862.rs:2:5
1551 // | the found closure
1552 // | expected `()`, found closure
1554 // = note: expected unit type `()`
1555 // found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1556 if !self.ignore_span.overlaps(span) {
1557 self.types.entry(kind).or_default().insert(span);
1560 t.super_visit_with(self)
1564 debug!("note_type_err(diag={:?})", diag);
1566 Variable(ty::error::ExpectedFound<Ty<'a>>),
1567 Fixed(&'static str),
1569 let (expected_found, exp_found, is_simple_error, values) = match values {
1570 None => (None, Mismatch::Fixed("type"), false, None),
1572 let values = self.resolve_vars_if_possible(values);
1573 let (is_simple_error, exp_found) = match values {
1574 ValuePairs::Terms(infer::ExpectedFound { expected, found }) => {
1575 match (expected.unpack(), found.unpack()) {
1576 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
1578 expected.is_simple_text() && found.is_simple_text();
1579 OpaqueTypesVisitor::visit_expected_found(
1580 self.tcx, expected, found, span,
1586 Mismatch::Variable(infer::ExpectedFound { expected, found }),
1589 (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1590 (false, Mismatch::Fixed("constant"))
1592 _ => (false, Mismatch::Fixed("type")),
1595 ValuePairs::TraitRefs(_) | ValuePairs::PolyTraitRefs(_) => {
1596 (false, Mismatch::Fixed("trait"))
1598 ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime")),
1600 let vals = match self.values_str(values) {
1601 Some((expected, found)) => Some((expected, found)),
1603 // Derived error. Cancel the emitter.
1604 // NOTE(eddyb) this was `.cancel()`, but `diag`
1605 // is borrowed, so we can't fully defuse it.
1606 diag.downgrade_to_delayed_bug();
1610 (vals, exp_found, is_simple_error, Some(values))
1615 // Ignore msg for object safe coercion
1616 // since E0038 message will be printed
1617 TypeError::ObjectUnsafeCoercion(_) => {}
1619 let mut label_or_note = |span: Span, msg: &str| {
1620 if (prefer_label && is_simple_error) || &[span] == diag.span.primary_spans() {
1621 diag.span_label(span, msg);
1623 diag.span_note(span, msg);
1626 if let Some((sp, msg)) = secondary_span {
1627 if swap_secondary_and_primary {
1628 let terr = if let Some(infer::ValuePairs::Terms(infer::ExpectedFound {
1633 format!("expected this to be `{}`", expected)
1637 label_or_note(sp, &terr);
1638 label_or_note(span, &msg);
1640 label_or_note(span, &terr.to_string());
1641 label_or_note(sp, &msg);
1644 label_or_note(span, &terr.to_string());
1648 if let Some((expected, found)) = expected_found {
1649 let (expected_label, found_label, exp_found) = match exp_found {
1650 Mismatch::Variable(ef) => (
1651 ef.expected.prefix_string(self.tcx),
1652 ef.found.prefix_string(self.tcx),
1655 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1658 enum Similar<'tcx> {
1659 Adts { expected: ty::AdtDef<'tcx>, found: ty::AdtDef<'tcx> },
1660 PrimitiveFound { expected: ty::AdtDef<'tcx>, found: Ty<'tcx> },
1661 PrimitiveExpected { expected: Ty<'tcx>, found: ty::AdtDef<'tcx> },
1664 let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1665 if let ty::Adt(expected, _) = expected.kind() && let Some(primitive) = found.primitive_symbol() {
1666 let path = self.tcx.def_path(expected.did()).data;
1667 let name = path.last().unwrap().data.get_opt_name();
1668 if name == Some(primitive) {
1669 return Some(Similar::PrimitiveFound { expected: *expected, found });
1671 } else if let Some(primitive) = expected.primitive_symbol() && let ty::Adt(found, _) = found.kind() {
1672 let path = self.tcx.def_path(found.did()).data;
1673 let name = path.last().unwrap().data.get_opt_name();
1674 if name == Some(primitive) {
1675 return Some(Similar::PrimitiveExpected { expected, found: *found });
1677 } else if let ty::Adt(expected, _) = expected.kind() && let ty::Adt(found, _) = found.kind() {
1678 if !expected.did().is_local() && expected.did().krate == found.did().krate {
1679 // Most likely types from different versions of the same crate
1680 // are in play, in which case this message isn't so helpful.
1681 // A "perhaps two different versions..." error is already emitted for that.
1684 let f_path = self.tcx.def_path(found.did()).data;
1685 let e_path = self.tcx.def_path(expected.did()).data;
1687 if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last()) && e_last == f_last {
1688 return Some(Similar::Adts{expected: *expected, found: *found});
1695 // If two types mismatch but have similar names, mention that specifically.
1696 TypeError::Sorts(values) if let Some(s) = similarity(values) => {
1697 let diagnose_primitive =
1701 diagnostic: &mut Diagnostic| {
1702 let name = shadow.sort_string(self.tcx);
1703 diagnostic.note(format!(
1704 "{prim} and {name} have similar names, but are actually distinct types"
1707 .note(format!("{prim} is a primitive defined by the language"));
1708 let def_span = self.tcx.def_span(defid);
1709 let msg = if defid.is_local() {
1710 format!("{name} is defined in the current crate")
1712 let crate_name = self.tcx.crate_name(defid.krate);
1713 format!("{name} is defined in crate `{crate_name}")
1715 diagnostic.span_note(def_span, msg);
1719 |expected_adt : ty::AdtDef<'tcx>,
1720 found_adt: ty::AdtDef<'tcx>,
1721 diagnostic: &mut Diagnostic| {
1722 let found_name = values.found.sort_string(self.tcx);
1723 let expected_name = values.expected.sort_string(self.tcx);
1725 let found_defid = found_adt.did();
1726 let expected_defid = expected_adt.did();
1728 diagnostic.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types"));
1729 for (defid, name) in
1730 [(found_defid, found_name), (expected_defid, expected_name)]
1732 let def_span = self.tcx.def_span(defid);
1734 let msg = if found_defid.is_local() && expected_defid.is_local() {
1737 .parent_module_from_def_id(defid.expect_local())
1739 let module_name = self.tcx.def_path(module).to_string_no_crate_verbose();
1740 format!("{name} is defined in module `crate{module_name}` of the current crate")
1741 } else if defid.is_local() {
1742 format!("{name} is defined in the current crate")
1744 let crate_name = self.tcx.crate_name(defid.krate);
1745 format!("{name} is defined in crate `{crate_name}`")
1747 diagnostic.span_note(def_span, msg);
1752 Similar::Adts{expected, found} => {
1753 diagnose_adts(expected, found, diag)
1755 Similar::PrimitiveFound{expected, found: prim} => {
1756 diagnose_primitive(prim, values.expected, expected.did(), diag)
1758 Similar::PrimitiveExpected{expected: prim, found} => {
1759 diagnose_primitive(prim, values.found, found.did(), diag)
1763 TypeError::Sorts(values) => {
1764 let extra = expected == found;
1765 let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1766 (true, ty::Opaque(def_id, _)) => {
1767 let sm = self.tcx.sess.source_map();
1768 let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1770 " (opaque type at <{}:{}:{}>)",
1771 sm.filename_for_diagnostics(&pos.file.name),
1773 pos.col.to_usize() + 1,
1776 (true, ty::Projection(proj))
1777 if self.tcx.def_kind(proj.item_def_id)
1778 == DefKind::ImplTraitPlaceholder =>
1780 let sm = self.tcx.sess.source_map();
1781 let pos = sm.lookup_char_pos(self.tcx.def_span(proj.item_def_id).lo());
1783 " (trait associated opaque type at <{}:{}:{}>)",
1784 sm.filename_for_diagnostics(&pos.file.name),
1786 pos.col.to_usize() + 1,
1789 (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1790 (false, _) => "".to_string(),
1792 if !(values.expected.is_simple_text() && values.found.is_simple_text())
1793 || (exp_found.map_or(false, |ef| {
1794 // This happens when the type error is a subset of the expectation,
1795 // like when you have two references but one is `usize` and the other
1796 // is `f32`. In those cases we still want to show the `note`. If the
1797 // value from `ef` is `Infer(_)`, then we ignore it.
1798 if !ef.expected.is_ty_infer() {
1799 ef.expected != values.expected
1800 } else if !ef.found.is_ty_infer() {
1801 ef.found != values.found
1807 diag.note_expected_found_extra(
1812 &sort_string(values.expected),
1813 &sort_string(values.found),
1817 TypeError::ObjectUnsafeCoercion(_) => {
1818 diag.note_unsuccessful_coercion(found, expected);
1822 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1823 exp_found, expected, found
1825 if !is_simple_error || terr.must_include_note() {
1826 diag.note_expected_found(&expected_label, expected, &found_label, found);
1831 let exp_found = match exp_found {
1832 Mismatch::Variable(exp_found) => Some(exp_found),
1833 Mismatch::Fixed(_) => None,
1835 let exp_found = match terr {
1836 // `terr` has more accurate type information than `exp_found` in match expressions.
1837 ty::error::TypeError::Sorts(terr)
1838 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1844 debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1845 if let Some(exp_found) = exp_found {
1846 let should_suggest_fixes =
1847 if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
1848 // Skip if the root_ty of the pattern is not the same as the expected_ty.
1849 // If these types aren't equal then we've probably peeled off a layer of arrays.
1850 self.same_type_modulo_infer(*root_ty, exp_found.expected)
1855 if should_suggest_fixes {
1856 self.suggest_tuple_pattern(cause, &exp_found, diag);
1857 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1858 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1859 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1863 // In some (most?) cases cause.body_id points to actual body, but in some cases
1864 // it's an actual definition. According to the comments (e.g. in
1865 // rustc_hir_analysis/check/compare_method.rs:compare_predicate_entailment) the latter
1866 // is relied upon by some other code. This might (or might not) need cleanup.
1867 let body_owner_def_id =
1868 self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1869 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1871 self.check_and_note_conflicting_crates(diag, terr);
1872 self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1874 if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
1875 && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
1876 && let Some(def_id) = def_id.as_local()
1877 && terr.involves_regions()
1879 let span = self.tcx.def_span(def_id);
1880 diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1883 // It reads better to have the error origin as the final
1885 self.note_error_origin(diag, cause, exp_found, terr);
1890 fn suggest_tuple_pattern(
1892 cause: &ObligationCause<'tcx>,
1893 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1894 diag: &mut Diagnostic,
1896 // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with
1897 // some modifications due to that being in typeck and this being in infer.
1898 if let ObligationCauseCode::Pattern { .. } = cause.code() {
1899 if let ty::Adt(expected_adt, substs) = exp_found.expected.kind() {
1900 let compatible_variants: Vec<_> = expected_adt
1904 variant.fields.len() == 1 && variant.ctor_kind == hir::def::CtorKind::Fn
1906 .filter_map(|variant| {
1907 let sole_field = &variant.fields[0];
1908 let sole_field_ty = sole_field.ty(self.tcx, substs);
1909 if self.same_type_modulo_infer(sole_field_ty, exp_found.found) {
1911 with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
1912 // FIXME #56861: DRYer prelude filtering
1913 if let Some(path) = variant_path.strip_prefix("std::prelude::") {
1914 if let Some((_, path)) = path.split_once("::") {
1915 return Some(path.to_string());
1924 match &compatible_variants[..] {
1927 diag.multipart_suggestion_verbose(
1928 &format!("try wrapping the pattern in `{}`", variant),
1930 (cause.span.shrink_to_lo(), format!("{}(", variant)),
1931 (cause.span.shrink_to_hi(), ")".to_string()),
1933 Applicability::MaybeIncorrect,
1937 // More than one matching variant.
1938 diag.multipart_suggestions(
1940 "try wrapping the pattern in a variant of `{}`",
1941 self.tcx.def_path_str(expected_adt.did())
1943 compatible_variants.into_iter().map(|variant| {
1945 (cause.span.shrink_to_lo(), format!("{}(", variant)),
1946 (cause.span.shrink_to_hi(), ")".to_string()),
1949 Applicability::MaybeIncorrect,
1957 pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Binder<'tcx, Ty<'tcx>>> {
1958 if let ty::Opaque(def_id, substs) = ty.kind() {
1959 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
1961 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
1963 let bounds = self.tcx.bound_explicit_item_bounds(*def_id);
1965 for predicate in bounds.transpose_iter().map(|e| e.map_bound(|(p, _)| *p)) {
1966 let predicate = predicate.subst(self.tcx, substs);
1967 let output = predicate
1969 .map_bound(|kind| match kind {
1970 ty::PredicateKind::Projection(projection_predicate)
1971 if projection_predicate.projection_ty.item_def_id == item_def_id =>
1973 projection_predicate.term.ty()
1978 if output.is_some() {
1979 // We don't account for multiple `Future::Output = Ty` constraints.
1987 /// A possible error is to forget to add `.await` when using futures:
1989 /// ```compile_fail,E0308
1990 /// async fn make_u32() -> u32 {
1994 /// fn take_u32(x: u32) {}
1996 /// async fn foo() {
1997 /// let x = make_u32();
2002 /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
2003 /// expected type. If this is the case, and we are inside of an async body, it suggests adding
2004 /// `.await` to the tail of the expression.
2005 fn suggest_await_on_expect_found(
2007 cause: &ObligationCause<'tcx>,
2009 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2010 diag: &mut Diagnostic,
2013 "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
2014 exp_span, exp_found.expected, exp_found.found,
2017 if let ObligationCauseCode::CompareImplItemObligation { .. } = cause.code() {
2022 self.get_impl_future_output_ty(exp_found.expected).map(Binder::skip_binder),
2023 self.get_impl_future_output_ty(exp_found.found).map(Binder::skip_binder),
2025 (Some(exp), Some(found)) if self.same_type_modulo_infer(exp, found) => match cause
2028 ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => {
2029 let then_span = self.find_block_span_from_hir_id(*then_id);
2030 diag.multipart_suggestion(
2031 "consider `await`ing on both `Future`s",
2033 (then_span.shrink_to_hi(), ".await".to_string()),
2034 (exp_span.shrink_to_hi(), ".await".to_string()),
2036 Applicability::MaybeIncorrect,
2039 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
2043 if let [.., arm_span] = &prior_arms[..] {
2044 diag.multipart_suggestion(
2045 "consider `await`ing on both `Future`s",
2047 (arm_span.shrink_to_hi(), ".await".to_string()),
2048 (exp_span.shrink_to_hi(), ".await".to_string()),
2050 Applicability::MaybeIncorrect,
2053 diag.help("consider `await`ing on both `Future`s");
2057 diag.help("consider `await`ing on both `Future`s");
2060 (_, Some(ty)) if self.same_type_modulo_infer(exp_found.expected, ty) => {
2061 diag.span_suggestion_verbose(
2062 exp_span.shrink_to_hi(),
2063 "consider `await`ing on the `Future`",
2065 Applicability::MaybeIncorrect,
2068 (Some(ty), _) if self.same_type_modulo_infer(ty, exp_found.found) => match cause.code()
2070 ObligationCauseCode::Pattern { span: Some(then_span), .. } => {
2071 diag.span_suggestion_verbose(
2072 then_span.shrink_to_hi(),
2073 "consider `await`ing on the `Future`",
2075 Applicability::MaybeIncorrect,
2078 ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => {
2079 let then_span = self.find_block_span_from_hir_id(*then_id);
2080 diag.span_suggestion_verbose(
2081 then_span.shrink_to_hi(),
2082 "consider `await`ing on the `Future`",
2084 Applicability::MaybeIncorrect,
2087 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
2091 diag.multipart_suggestion_verbose(
2092 "consider `await`ing on the `Future`",
2095 .map(|arm| (arm.shrink_to_hi(), ".await".to_string()))
2097 Applicability::MaybeIncorrect,
2106 fn suggest_accessing_field_where_appropriate(
2108 cause: &ObligationCause<'tcx>,
2109 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2110 diag: &mut Diagnostic,
2113 "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
2116 if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
2117 if expected_def.is_enum() {
2121 if let Some((name, ty)) = expected_def
2125 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
2126 .map(|field| (field.name, field.ty(self.tcx, expected_substs)))
2127 .find(|(_, ty)| self.same_type_modulo_infer(*ty, exp_found.found))
2129 if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() {
2130 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2131 let suggestion = if expected_def.is_struct() {
2132 format!("{}.{}", snippet, name)
2133 } else if expected_def.is_union() {
2134 format!("unsafe {{ {}.{} }}", snippet, name)
2138 diag.span_suggestion(
2141 "you might have meant to use field `{}` whose type is `{}`",
2145 Applicability::MaybeIncorrect,
2153 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
2155 fn suggest_as_ref_where_appropriate(
2158 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2159 diag: &mut Diagnostic,
2161 if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
2162 (exp_found.expected.kind(), exp_found.found.kind())
2164 if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
2165 if exp_def == &found_def {
2166 let have_as_ref = &[
2169 "you can convert from `&Option<T>` to `Option<&T>` using \
2174 "you can convert from `&Result<T, E>` to \
2175 `Result<&T, &E>` using `.as_ref()`",
2178 if let Some(msg) = have_as_ref.iter().find_map(|(name, msg)| {
2179 self.tcx.is_diagnostic_item(*name, exp_def.did()).then_some(msg)
2181 let mut show_suggestion = true;
2182 for (exp_ty, found_ty) in
2183 iter::zip(exp_substs.types(), found_substs.types())
2185 match *exp_ty.kind() {
2186 ty::Ref(_, exp_ty, _) => {
2187 match (exp_ty.kind(), found_ty.kind()) {
2191 | (ty::Infer(_), _) => {}
2192 _ if self.same_type_modulo_infer(exp_ty, found_ty) => {}
2193 _ => show_suggestion = false,
2196 ty::Param(_) | ty::Infer(_) => {}
2197 _ => show_suggestion = false,
2200 if let (Ok(snippet), true) =
2201 (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
2203 diag.span_suggestion(
2206 // HACK: fix issue# 100605, suggesting convert from &Option<T> to Option<&T>, remove the extra `&`
2207 format!("{}.as_ref()", snippet.trim_start_matches('&')),
2208 Applicability::MachineApplicable,
2217 pub fn report_and_explain_type_error(
2219 trace: TypeTrace<'tcx>,
2220 terr: TypeError<'tcx>,
2221 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2222 use crate::traits::ObligationCauseCode::MatchExpressionArm;
2224 debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2226 let span = trace.cause.span();
2227 let failure_code = trace.cause.as_failure_code(terr);
2228 let mut diag = match failure_code {
2229 FailureCode::Error0038(did) => {
2230 let violations = self.tcx.object_safety_violations(did);
2231 report_object_safety_error(self.tcx, span, did, violations)
2233 FailureCode::Error0317(failure_str) => {
2234 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
2236 FailureCode::Error0580(failure_str) => {
2237 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
2239 FailureCode::Error0308(failure_str) => {
2240 let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
2241 if let Some((expected, found)) = trace.values.ty() {
2242 match (expected.kind(), found.kind()) {
2243 (ty::Tuple(_), ty::Tuple(_)) => {}
2244 // If a tuple of length one was expected and the found expression has
2245 // parentheses around it, perhaps the user meant to write `(expr,)` to
2246 // build a tuple (issue #86100)
2247 (ty::Tuple(fields), _) => {
2248 self.emit_tuple_wrap_err(&mut err, span, found, fields)
2250 // If a character was expected and the found expression is a string literal
2251 // containing a single character, perhaps the user meant to write `'c'` to
2252 // specify a character literal (issue #92479)
2253 (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2254 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2255 && let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
2256 && code.chars().count() == 1
2258 err.span_suggestion(
2260 "if you meant to write a `char` literal, use single quotes",
2261 format!("'{}'", code),
2262 Applicability::MachineApplicable,
2266 // If a string was expected and the found expression is a character literal,
2267 // perhaps the user meant to write `"s"` to specify a string literal.
2268 (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2269 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2271 code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2273 err.span_suggestion(
2275 "if you meant to write a `str` literal, use double quotes",
2276 format!("\"{}\"", code),
2277 Applicability::MachineApplicable,
2285 let code = trace.cause.code();
2286 if let &MatchExpressionArm(box MatchExpressionArmCause { source, .. }) = code
2287 && let hir::MatchSource::TryDesugar = source
2288 && let Some((expected_ty, found_ty)) = self.values_str(trace.values)
2291 "`?` operator cannot convert from `{}` to `{}`",
2293 expected_ty.content(),
2298 FailureCode::Error0644(failure_str) => {
2299 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
2302 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false, false);
2306 fn emit_tuple_wrap_err(
2308 err: &mut Diagnostic,
2311 expected_fields: &List<Ty<'tcx>>,
2313 let [expected_tup_elem] = expected_fields[..] else { return };
2315 if !self.same_type_modulo_infer(expected_tup_elem, found) {
2319 let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2322 let msg = "use a trailing comma to create a tuple with one element";
2323 if code.starts_with('(') && code.ends_with(')') {
2324 let before_close = span.hi() - BytePos::from_u32(1);
2325 err.span_suggestion(
2326 span.with_hi(before_close).shrink_to_hi(),
2329 Applicability::MachineApplicable,
2332 err.multipart_suggestion(
2334 vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
2335 Applicability::MachineApplicable,
2342 values: ValuePairs<'tcx>,
2343 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2345 infer::Regions(exp_found) => self.expected_found_str(exp_found),
2346 infer::Terms(exp_found) => self.expected_found_str_term(exp_found),
2347 infer::TraitRefs(exp_found) => {
2348 let pretty_exp_found = ty::error::ExpectedFound {
2349 expected: exp_found.expected.print_only_trait_path(),
2350 found: exp_found.found.print_only_trait_path(),
2352 match self.expected_found_str(pretty_exp_found) {
2353 Some((expected, found)) if expected == found => {
2354 self.expected_found_str(exp_found)
2359 infer::PolyTraitRefs(exp_found) => {
2360 let pretty_exp_found = ty::error::ExpectedFound {
2361 expected: exp_found.expected.print_only_trait_path(),
2362 found: exp_found.found.print_only_trait_path(),
2364 match self.expected_found_str(pretty_exp_found) {
2365 Some((expected, found)) if expected == found => {
2366 self.expected_found_str(exp_found)
2374 fn expected_found_str_term(
2376 exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2377 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2378 let exp_found = self.resolve_vars_if_possible(exp_found);
2379 if exp_found.references_error() {
2383 Some(match (exp_found.expected.unpack(), exp_found.found.unpack()) {
2384 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => self.cmp(expected, found),
2386 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2387 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2392 /// Returns a string of the form "expected `{}`, found `{}`".
2393 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
2395 exp_found: ty::error::ExpectedFound<T>,
2396 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2397 let exp_found = self.resolve_vars_if_possible(exp_found);
2398 if exp_found.references_error() {
2403 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2404 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2408 pub fn report_generic_bound_failure(
2410 generic_param_scope: LocalDefId,
2412 origin: Option<SubregionOrigin<'tcx>>,
2413 bound_kind: GenericKind<'tcx>,
2416 self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
2420 pub fn construct_generic_bound_failure(
2422 generic_param_scope: LocalDefId,
2424 origin: Option<SubregionOrigin<'tcx>>,
2425 bound_kind: GenericKind<'tcx>,
2427 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2428 // Attempt to obtain the span of the parameter so we can
2429 // suggest adding an explicit lifetime bound to it.
2430 let generics = self.tcx.generics_of(generic_param_scope);
2431 // type_param_span is (span, has_bounds)
2432 let type_param_span = match bound_kind {
2433 GenericKind::Param(ref param) => {
2434 // Account for the case where `param` corresponds to `Self`,
2435 // which doesn't have the expected type argument.
2436 if !(generics.has_self && param.index == 0) {
2437 let type_param = generics.type_param(param, self.tcx);
2438 type_param.def_id.as_local().map(|def_id| {
2439 // Get the `hir::Param` to verify whether it already has any bounds.
2440 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2441 // instead we suggest `T: 'a + 'b` in that case.
2442 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2443 let ast_generics = self.tcx.hir().get_generics(hir_id.owner.def_id);
2445 ast_generics.and_then(|g| g.bounds_span_for_suggestions(def_id));
2446 // `sp` only covers `T`, change it so that it covers
2447 // `T:` when appropriate
2448 if let Some(span) = bounds {
2451 let sp = self.tcx.def_span(def_id);
2452 (sp.shrink_to_hi(), false)
2463 let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
2465 iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
2466 .flat_map(|g| &g.params)
2467 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2468 .map(|p| p.name.as_str())
2469 .collect::<Vec<_>>();
2471 .find(|candidate| !lts_names.contains(&&candidate[..]))
2472 .unwrap_or("'lt".to_string())
2475 let add_lt_sugg = generics
2478 .and_then(|param| param.def_id.as_local())
2479 .map(|def_id| (self.tcx.def_span(def_id).shrink_to_lo(), format!("{}, ", new_lt)));
2481 let labeled_user_string = match bound_kind {
2482 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2483 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
2484 GenericKind::Opaque(def_id, substs) => {
2485 format!("the opaque type `{}`", self.tcx.def_path_str_with_substs(def_id, substs))
2489 if let Some(SubregionOrigin::CompareImplItemObligation {
2495 return self.report_extra_impl_obligation(
2499 &format!("`{}: {}`", bound_kind, sub),
2503 fn binding_suggestion<'tcx, S: fmt::Display>(
2504 err: &mut Diagnostic,
2505 type_param_span: Option<(Span, bool)>,
2506 bound_kind: GenericKind<'tcx>,
2508 add_lt_sugg: Option<(Span, String)>,
2510 let msg = "consider adding an explicit lifetime bound";
2511 if let Some((sp, has_lifetimes)) = type_param_span {
2513 if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) };
2514 let mut suggestions = vec![(sp, suggestion)];
2515 if let Some(add_lt_sugg) = add_lt_sugg {
2516 suggestions.push(add_lt_sugg);
2518 err.multipart_suggestion_verbose(
2519 format!("{msg}..."),
2521 Applicability::MaybeIncorrect, // Issue #41966
2524 let consider = format!("{} `{}: {}`...", msg, bound_kind, sub);
2525 err.help(&consider);
2529 let new_binding_suggestion =
2530 |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| {
2531 let msg = "consider introducing an explicit lifetime bound";
2532 if let Some((sp, has_lifetimes)) = type_param_span {
2533 let suggestion = if has_lifetimes {
2534 format!(" + {}", new_lt)
2536 format!(": {}", new_lt)
2539 vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {}", new_lt))];
2540 if let Some(lt) = add_lt_sugg.clone() {
2542 sugg.rotate_right(1);
2544 // `MaybeIncorrect` due to issue #41966.
2545 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2550 enum SubOrigin<'hir> {
2551 GAT(&'hir hir::Generics<'hir>),
2557 let sub_origin = 'origin: {
2559 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
2560 let node = self.tcx.hir().get_if_local(def_id).unwrap();
2562 Node::GenericParam(param) => {
2563 for h in self.tcx.hir().parent_iter(param.hir_id) {
2564 break 'origin match h.1 {
2565 Node::ImplItem(hir::ImplItem {
2566 kind: hir::ImplItemKind::TyAlias(..),
2570 | Node::TraitItem(hir::TraitItem {
2571 kind: hir::TraitItemKind::Type(..),
2574 }) => SubOrigin::GAT(generics),
2575 Node::ImplItem(hir::ImplItem {
2576 kind: hir::ImplItemKind::Fn(..),
2579 | Node::TraitItem(hir::TraitItem {
2580 kind: hir::TraitItemKind::Fn(..),
2583 | Node::Item(hir::Item {
2584 kind: hir::ItemKind::Fn(..), ..
2585 }) => SubOrigin::Fn,
2586 Node::Item(hir::Item {
2587 kind: hir::ItemKind::Trait(..),
2589 }) => SubOrigin::Trait,
2590 Node::Item(hir::Item {
2591 kind: hir::ItemKind::Impl(..), ..
2592 }) => SubOrigin::Impl,
2604 debug!(?sub_origin);
2606 let mut err = match (*sub, sub_origin) {
2607 // In the case of GATs, we have to be careful. If we a type parameter `T` on an impl,
2608 // but a lifetime `'a` on an associated type, then we might need to suggest adding
2609 // `where T: 'a`. Importantly, this is on the GAT span, not on the `T` declaration.
2610 (ty::ReEarlyBound(ty::EarlyBoundRegion { name: _, .. }), SubOrigin::GAT(generics)) => {
2611 // Does the required lifetime have a nice name we can print?
2612 let mut err = struct_span_err!(
2616 "{} may not live long enough",
2619 let pred = format!("{}: {}", bound_kind, sub);
2620 let suggestion = format!("{} {}", generics.add_where_or_trailing_comma(), pred,);
2621 err.span_suggestion(
2622 generics.tail_span_for_predicate_suggestion(),
2623 "consider adding a where clause",
2625 Applicability::MaybeIncorrect,
2630 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2631 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }),
2633 ) if name != kw::UnderscoreLifetime => {
2634 // Does the required lifetime have a nice name we can print?
2635 let mut err = struct_span_err!(
2639 "{} may not live long enough",
2642 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2643 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2644 // uses `Debug` output, so we handle it specially here so that suggestions are
2646 binding_suggestion(&mut err, type_param_span, bound_kind, name, None);
2650 (ty::ReStatic, _) => {
2651 // Does the required lifetime have a nice name we can print?
2652 let mut err = struct_span_err!(
2656 "{} may not live long enough",
2659 binding_suggestion(&mut err, type_param_span, bound_kind, "'static", None);
2664 // If not, be less specific.
2665 let mut err = struct_span_err!(
2669 "{} may not live long enough",
2672 note_and_explain_region(
2675 &format!("{} must be valid for ", labeled_user_string),
2680 if let Some(infer::RelateParamBound(_, t, _)) = origin {
2681 let return_impl_trait =
2682 self.tcx.return_type_impl_trait(generic_param_scope).is_some();
2683 let t = self.resolve_vars_if_possible(t);
2686 // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2688 // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2689 ty::Closure(_, _substs) | ty::Opaque(_, _substs) if return_impl_trait => {
2690 new_binding_suggestion(&mut err, type_param_span);
2707 if let Some(origin) = origin {
2708 self.note_region_origin(&mut err, &origin);
2713 fn report_sub_sup_conflict(
2715 var_origin: RegionVariableOrigin,
2716 sub_origin: SubregionOrigin<'tcx>,
2717 sub_region: Region<'tcx>,
2718 sup_origin: SubregionOrigin<'tcx>,
2719 sup_region: Region<'tcx>,
2721 let mut err = self.report_inference_failure(var_origin);
2723 note_and_explain_region(
2726 "first, the lifetime cannot outlive ",
2732 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2733 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2734 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2735 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2736 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2738 if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2739 (&sup_origin, &sub_origin)
2741 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
2742 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
2743 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
2744 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
2746 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2747 (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
2749 if sub_expected == sup_expected && sub_found == sup_found {
2750 note_and_explain_region(
2753 "...but the lifetime must also be valid for ",
2759 sup_trace.cause.span,
2760 &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2763 err.note_expected_found(&"", sup_expected, &"", sup_found);
2770 self.note_region_origin(&mut err, &sup_origin);
2772 note_and_explain_region(
2775 "but, the lifetime must be valid for ",
2781 self.note_region_origin(&mut err, &sub_origin);
2785 /// Determine whether an error associated with the given span and definition
2786 /// should be treated as being caused by the implicit `From` conversion
2787 /// within `?` desugaring.
2788 pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2789 span.is_desugaring(DesugaringKind::QuestionMark)
2790 && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2793 /// Structurally compares two types, modulo any inference variables.
2795 /// Returns `true` if two types are equal, or if one type is an inference variable compatible
2796 /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
2797 /// FloatVar inference type are compatible with themselves or their concrete types (Int and
2798 /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
2799 pub fn same_type_modulo_infer(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
2800 let (a, b) = self.resolve_vars_if_possible((a, b));
2801 SameTypeModuloInfer(self).relate(a, b).is_ok()
2805 struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'a, 'tcx>);
2807 impl<'tcx> TypeRelation<'tcx> for SameTypeModuloInfer<'_, 'tcx> {
2808 fn tcx(&self) -> TyCtxt<'tcx> {
2812 fn param_env(&self) -> ty::ParamEnv<'tcx> {
2813 // Unused, only for consts which we treat as always equal
2814 ty::ParamEnv::empty()
2817 fn tag(&self) -> &'static str {
2818 "SameTypeModuloInfer"
2821 fn a_is_expected(&self) -> bool {
2825 fn relate_with_variance<T: relate::Relate<'tcx>>(
2827 _variance: ty::Variance,
2828 _info: ty::VarianceDiagInfo<'tcx>,
2831 ) -> relate::RelateResult<'tcx, T> {
2835 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
2836 match (a.kind(), b.kind()) {
2837 (ty::Int(_) | ty::Uint(_), ty::Infer(ty::InferTy::IntVar(_)))
2839 ty::Infer(ty::InferTy::IntVar(_)),
2840 ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2842 | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2844 ty::Infer(ty::InferTy::FloatVar(_)),
2845 ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2847 | (ty::Infer(ty::InferTy::TyVar(_)), _)
2848 | (_, ty::Infer(ty::InferTy::TyVar(_))) => Ok(a),
2849 (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Mismatch),
2850 _ => relate::super_relate_tys(self, a, b),
2856 a: ty::Region<'tcx>,
2857 b: ty::Region<'tcx>,
2858 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
2859 if (a.is_var() && b.is_free_or_static())
2860 || (b.is_var() && a.is_free_or_static())
2861 || (a.is_var() && b.is_var())
2866 Err(TypeError::Mismatch)
2872 a: ty::Binder<'tcx, T>,
2873 b: ty::Binder<'tcx, T>,
2874 ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2876 T: relate::Relate<'tcx>,
2878 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2884 _b: ty::Const<'tcx>,
2885 ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2886 // FIXME(compiler-errors): This could at least do some first-order
2892 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2893 fn report_inference_failure(
2895 var_origin: RegionVariableOrigin,
2896 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2897 let br_string = |br: ty::BoundRegionKind| {
2898 let mut s = match br {
2899 ty::BrNamed(_, name) => name.to_string(),
2907 let var_description = match var_origin {
2908 infer::MiscVariable(_) => String::new(),
2909 infer::PatternRegion(_) => " for pattern".to_string(),
2910 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2911 infer::Autoref(_) => " for autoref".to_string(),
2912 infer::Coercion(_) => " for automatic coercion".to_string(),
2913 infer::LateBoundRegion(_, br, infer::FnCall) => {
2914 format!(" for lifetime parameter {}in function call", br_string(br))
2916 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2917 format!(" for lifetime parameter {}in generic type", br_string(br))
2919 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2920 " for lifetime parameter {}in trait containing associated type `{}`",
2922 self.tcx.associated_item(def_id).name
2924 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2925 infer::UpvarRegion(ref upvar_id, _) => {
2926 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2927 format!(" for capture of `{}` by closure", var_name)
2929 infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2936 "cannot infer an appropriate lifetime{} due to conflicting requirements",
2942 pub enum FailureCode {
2944 Error0317(&'static str),
2945 Error0580(&'static str),
2946 Error0308(&'static str),
2947 Error0644(&'static str),
2950 pub trait ObligationCauseExt<'tcx> {
2951 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode;
2952 fn as_requirement_str(&self) -> &'static str;
2955 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2956 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
2957 use self::FailureCode::*;
2958 use crate::traits::ObligationCauseCode::*;
2960 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
2961 Error0308("method not compatible with trait")
2963 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
2964 Error0308("type not compatible with trait")
2966 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
2967 Error0308("const not compatible with trait")
2969 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2970 Error0308(match source {
2971 hir::MatchSource::TryDesugar => "`?` operator has incompatible types",
2972 _ => "`match` arms have incompatible types",
2975 IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2976 IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2977 LetElse => Error0308("`else` clause of `let...else` does not diverge"),
2978 MainFunctionType => Error0580("`main` function has wrong type"),
2979 StartFunctionType => Error0308("`#[start]` function has wrong type"),
2980 IntrinsicType => Error0308("intrinsic has wrong type"),
2981 MethodReceiver => Error0308("mismatched `self` parameter type"),
2983 // In the case where we have no more specific thing to
2984 // say, also take a look at the error code, maybe we can
2987 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2988 Error0644("closure/generator type that references itself")
2990 TypeError::IntrinsicCast => {
2991 Error0308("cannot coerce intrinsics to function pointers")
2993 TypeError::ObjectUnsafeCoercion(did) => Error0038(did),
2994 _ => Error0308("mismatched types"),
2999 fn as_requirement_str(&self) -> &'static str {
3000 use crate::traits::ObligationCauseCode::*;
3002 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
3003 "method type is compatible with trait"
3005 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
3006 "associated type is compatible with trait"
3008 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
3009 "const is compatible with trait"
3011 ExprAssignable => "expression is assignable",
3012 IfExpression { .. } => "`if` and `else` have incompatible types",
3013 IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
3014 MainFunctionType => "`main` function has the correct type",
3015 StartFunctionType => "`#[start]` function has the correct type",
3016 IntrinsicType => "intrinsic has the correct type",
3017 MethodReceiver => "method receiver has the correct type",
3018 _ => "types are compatible",
3023 /// Newtype to allow implementing IntoDiagnosticArg
3024 pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
3026 impl IntoDiagnosticArg for ObligationCauseAsDiagArg<'_> {
3027 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
3028 use crate::traits::ObligationCauseCode::*;
3029 let kind = match self.0.code() {
3030 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => "method_compat",
3031 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => "type_compat",
3032 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => "const_compat",
3033 ExprAssignable => "expr_assignable",
3034 IfExpression { .. } => "if_else_different",
3035 IfExpressionWithNoElse => "no_else",
3036 MainFunctionType => "fn_main_correct_type",
3037 StartFunctionType => "fn_start_correct_type",
3038 IntrinsicType => "intristic_correct_type",
3039 MethodReceiver => "method_correct_type",
3043 rustc_errors::DiagnosticArgValue::Str(kind)
3047 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
3048 /// extra information about each type, but we only care about the category.
3049 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
3050 pub enum TyCategory {
3053 Generator(hir::GeneratorKind),
3058 fn descr(&self) -> &'static str {
3060 Self::Closure => "closure",
3061 Self::Opaque => "opaque type",
3062 Self::Generator(gk) => gk.descr(),
3063 Self::Foreign => "foreign type",
3067 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
3069 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
3070 ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
3071 ty::Generator(def_id, ..) => {
3072 Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
3074 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
3080 impl<'tcx> InferCtxt<'_, 'tcx> {
3081 /// Given a [`hir::Block`], get the span of its last expression or
3082 /// statement, peeling off any inner blocks.
3083 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
3084 let block = block.innermost_block();
3085 if let Some(expr) = &block.expr {
3087 } else if let Some(stmt) = block.stmts.last() {
3088 // possibly incorrect trailing `;` in the else arm
3091 // empty block; point at its entirety
3096 /// Given a [`hir::HirId`] for a block, get the span of its last expression
3097 /// or statement, peeling off any inner blocks.
3098 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
3099 match self.tcx.hir().get(hir_id) {
3100 hir::Node::Block(blk) => self.find_block_span(blk),
3101 // The parser was in a weird state if either of these happen, but
3102 // it's better not to panic.
3103 hir::Node::Expr(e) => e.span,
3104 _ => rustc_span::DUMMY_SP,
3108 /// Be helpful when the user wrote `{... expr; }` and taking the `;` off
3109 /// is enough to fix the error.
3110 pub fn could_remove_semicolon(
3112 blk: &'tcx hir::Block<'tcx>,
3113 expected_ty: Ty<'tcx>,
3114 ) -> Option<(Span, StatementAsExpression)> {
3115 let blk = blk.innermost_block();
3116 // Do not suggest if we have a tail expr.
3117 if blk.expr.is_some() {
3120 let last_stmt = blk.stmts.last()?;
3121 let hir::StmtKind::Semi(ref last_expr) = last_stmt.kind else {
3124 let last_expr_ty = self.in_progress_typeck_results?.borrow().expr_ty_opt(*last_expr)?;
3125 let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) {
3126 _ if last_expr_ty.references_error() => return None,
3127 _ if self.same_type_modulo_infer(last_expr_ty, expected_ty) => {
3128 StatementAsExpression::CorrectType
3130 (ty::Opaque(last_def_id, _), ty::Opaque(exp_def_id, _))
3131 if last_def_id == exp_def_id =>
3133 StatementAsExpression::CorrectType
3135 (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => {
3137 "both opaque, likely future {:?} {:?} {:?} {:?}",
3138 last_def_id, last_bounds, exp_def_id, exp_bounds
3141 let last_local_id = last_def_id.as_local()?;
3142 let exp_local_id = exp_def_id.as_local()?;
3145 &self.tcx.hir().expect_item(last_local_id).kind,
3146 &self.tcx.hir().expect_item(exp_local_id).kind,
3149 hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: last_bounds, .. }),
3150 hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: exp_bounds, .. }),
3151 ) if iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| {
3152 match (left, right) {
3154 hir::GenericBound::Trait(tl, ml),
3155 hir::GenericBound::Trait(tr, mr),
3156 ) if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
3162 hir::GenericBound::LangItemTrait(langl, _, _, argsl),
3163 hir::GenericBound::LangItemTrait(langr, _, _, argsr),
3164 ) if langl == langr => {
3165 // FIXME: consider the bounds!
3166 debug!("{:?} {:?}", argsl, argsr);
3173 StatementAsExpression::NeedsBoxing
3175 _ => StatementAsExpression::CorrectType,
3180 let span = if last_stmt.span.from_expansion() {
3181 let mac_call = rustc_span::source_map::original_sp(last_stmt.span, blk.span);
3182 self.tcx.sess.source_map().mac_call_stmt_semi_span(mac_call)?
3184 last_stmt.span.with_lo(last_stmt.span.hi() - BytePos(1))
3186 Some((span, needs_box))
3189 /// Suggest returning a local binding with a compatible type if the block
3190 /// has no return expression.
3191 pub fn consider_returning_binding(
3193 blk: &'tcx hir::Block<'tcx>,
3194 expected_ty: Ty<'tcx>,
3195 err: &mut Diagnostic,
3197 let blk = blk.innermost_block();
3198 // Do not suggest if we have a tail expr.
3199 if blk.expr.is_some() {
3202 let mut shadowed = FxHashSet::default();
3203 let mut candidate_idents = vec![];
3204 let mut find_compatible_candidates = |pat: &hir::Pat<'_>| {
3205 if let hir::PatKind::Binding(_, hir_id, ident, _) = &pat.kind
3206 && let Some(pat_ty) = self
3207 .in_progress_typeck_results
3208 .and_then(|typeck_results| typeck_results.borrow().node_type_opt(*hir_id))
3210 let pat_ty = self.resolve_vars_if_possible(pat_ty);
3211 if self.same_type_modulo_infer(pat_ty, expected_ty)
3212 && !(pat_ty, expected_ty).references_error()
3213 && shadowed.insert(ident.name)
3215 candidate_idents.push((*ident, pat_ty));
3221 let hir = self.tcx.hir();
3222 for stmt in blk.stmts.iter().rev() {
3223 let hir::StmtKind::Local(local) = &stmt.kind else { continue; };
3224 local.pat.walk(&mut find_compatible_candidates);
3226 match hir.find(hir.get_parent_node(blk.hir_id)) {
3227 Some(hir::Node::Expr(hir::Expr { hir_id, .. })) => {
3228 match hir.find(hir.get_parent_node(*hir_id)) {
3229 Some(hir::Node::Arm(hir::Arm { pat, .. })) => {
3230 pat.walk(&mut find_compatible_candidates);
3233 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body), .. })
3234 | hir::Node::ImplItem(hir::ImplItem {
3235 kind: hir::ImplItemKind::Fn(_, body),
3238 | hir::Node::TraitItem(hir::TraitItem {
3239 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body)),
3242 | hir::Node::Expr(hir::Expr {
3243 kind: hir::ExprKind::Closure(hir::Closure { body, .. }),
3247 for param in hir.body(*body).params {
3248 param.pat.walk(&mut find_compatible_candidates);
3251 Some(hir::Node::Expr(hir::Expr {
3254 hir::Expr { kind: hir::ExprKind::Let(let_), .. },
3259 })) if then_block.hir_id == *hir_id => {
3260 let_.pat.walk(&mut find_compatible_candidates);
3268 match &candidate_idents[..] {
3270 let sm = self.tcx.sess.source_map();
3271 if let Some(stmt) = blk.stmts.last() {
3272 let stmt_span = sm.stmt_span(stmt.span, blk.span);
3273 let sugg = if sm.is_multiline(blk.span)
3274 && let Some(spacing) = sm.indentation_before(stmt_span)
3276 format!("\n{spacing}{ident}")
3280 err.span_suggestion_verbose(
3281 stmt_span.shrink_to_hi(),
3282 format!("consider returning the local binding `{ident}`"),
3284 Applicability::MaybeIncorrect,
3287 let sugg = if sm.is_multiline(blk.span)
3288 && let Some(spacing) = sm.indentation_before(blk.span.shrink_to_lo())
3290 format!("\n{spacing} {ident}\n{spacing}")
3292 format!(" {ident} ")
3294 let left_span = sm.span_through_char(blk.span, '{').shrink_to_hi();
3295 err.span_suggestion_verbose(
3296 sm.span_extend_while(left_span, |c| c.is_whitespace()).unwrap_or(left_span),
3297 format!("consider returning the local binding `{ident}`"),
3299 Applicability::MaybeIncorrect,
3304 values if (1..3).contains(&values.len()) => {
3305 let spans = values.iter().map(|(ident, _)| ident.span).collect::<Vec<_>>();
3306 err.span_note(spans, "consider returning one of these bindings");