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::{FxIndexMap, FxIndexSet};
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, Deref};
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 /// A helper for building type related errors. The `typeck_results`
89 /// field is only populated during an in-progress typeck.
90 /// Get an instance by calling `InferCtxt::err` or `FnCtxt::infer_err`.
91 pub struct TypeErrCtxt<'a, 'tcx> {
92 pub infcx: &'a InferCtxt<'tcx>,
93 pub typeck_results: Option<std::cell::Ref<'a, ty::TypeckResults<'tcx>>>,
94 pub fallback_has_occurred: bool,
97 impl TypeErrCtxt<'_, '_> {
98 /// This is just to avoid a potential footgun of accidentally
99 /// dropping `typeck_results` by calling `InferCtxt::err_ctxt`
100 #[deprecated(note = "you already have a `TypeErrCtxt`")]
102 pub fn err_ctxt(&self) -> ! {
103 bug!("called `err_ctxt` on `TypeErrCtxt`. Try removing the call");
107 impl<'tcx> Deref for TypeErrCtxt<'_, 'tcx> {
108 type Target = InferCtxt<'tcx>;
109 fn deref(&self) -> &InferCtxt<'tcx> {
114 pub(super) fn note_and_explain_region<'tcx>(
116 err: &mut Diagnostic,
118 region: ty::Region<'tcx>,
120 alt_span: Option<Span>,
122 let (description, span) = match *region {
123 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
124 msg_span_from_free_region(tcx, region, alt_span)
127 ty::RePlaceholder(_) => return,
129 // FIXME(#13998) RePlaceholder should probably print like
130 // ReFree rather than dumping Debug output on the user.
132 // We shouldn't really be having unification failures with ReVar
133 // and ReLateBound though.
134 ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
135 (format!("lifetime {:?}", region), alt_span)
139 emit_msg_span(err, prefix, description, span, suffix);
142 fn explain_free_region<'tcx>(
144 err: &mut Diagnostic,
146 region: ty::Region<'tcx>,
149 let (description, span) = msg_span_from_free_region(tcx, region, None);
151 label_msg_span(err, prefix, description, span, suffix);
154 fn msg_span_from_free_region<'tcx>(
156 region: ty::Region<'tcx>,
157 alt_span: Option<Span>,
158 ) -> (String, Option<Span>) {
160 ty::ReEarlyBound(_) | ty::ReFree(_) => {
161 let (msg, span) = msg_span_from_early_bound_and_free_regions(tcx, region);
164 ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
165 _ => bug!("{:?}", region),
169 fn msg_span_from_early_bound_and_free_regions<'tcx>(
171 region: ty::Region<'tcx>,
172 ) -> (String, Span) {
173 let scope = region.free_region_binding_scope(tcx).expect_local();
175 ty::ReEarlyBound(ref br) => {
176 let mut sp = tcx.def_span(scope);
178 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
182 let text = if br.has_name() {
183 format!("the lifetime `{}` as defined here", br.name)
185 format!("the anonymous lifetime as defined here")
189 ty::ReFree(ref fr) => {
190 if !fr.bound_region.is_named()
191 && let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region)
193 ("the anonymous lifetime defined here".to_string(), ty.span)
195 match fr.bound_region {
196 ty::BoundRegionKind::BrNamed(_, name) => {
197 let mut sp = tcx.def_span(scope);
199 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
203 let text = if name == kw::UnderscoreLifetime {
204 format!("the anonymous lifetime as defined here")
206 format!("the lifetime `{}` as defined here", name)
210 ty::BrAnon(idx, span) => (
211 format!("the anonymous lifetime #{} defined here", idx + 1),
214 None => tcx.def_span(scope)
218 format!("the lifetime `{}` as defined here", region),
229 err: &mut Diagnostic,
235 let message = format!("{}{}{}", prefix, description, suffix);
237 if let Some(span) = span {
238 err.span_note(span, &message);
245 err: &mut Diagnostic,
251 let message = format!("{}{}{}", prefix, description, suffix);
253 if let Some(span) = span {
254 err.span_label(span, &message);
260 pub fn unexpected_hidden_region_diagnostic<'tcx>(
264 hidden_region: ty::Region<'tcx>,
265 opaque_ty: ty::OpaqueTypeKey<'tcx>,
266 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
267 let opaque_ty = tcx.mk_opaque(opaque_ty.def_id.to_def_id(), opaque_ty.substs);
268 let mut err = struct_span_err!(
272 "hidden type for `{opaque_ty}` captures lifetime that does not appear in bounds",
275 // Explain the region we are capturing.
276 match *hidden_region {
277 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
278 // Assuming regionck succeeded (*), we ought to always be
279 // capturing *some* region from the fn header, and hence it
280 // ought to be free. So under normal circumstances, we will go
281 // down this path which gives a decent human readable
284 // (*) if not, the `tainted_by_errors` field would be set to
285 // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
289 &format!("hidden type `{}` captures ", hidden_ty),
293 if let Some(reg_info) = tcx.is_suitable_region(hidden_region) {
294 let fn_returns = tcx.return_type_impl_or_dyn_traits(reg_info.def_id);
295 nice_region_error::suggest_new_region_bound(
299 hidden_region.to_string(),
301 format!("captures `{}`", hidden_region),
307 // Ugh. This is a painful case: the hidden region is not one
308 // that we can easily summarize or explain. This can happen
310 // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
313 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
314 // if condition() { a } else { b }
318 // Here the captured lifetime is the intersection of `'a` and
319 // `'b`, which we can't quite express.
321 // We can at least report a really cryptic error for now.
322 note_and_explain_region(
325 &format!("hidden type `{}` captures ", hidden_ty),
336 impl<'tcx> InferCtxt<'tcx> {
337 pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Binder<'tcx, Ty<'tcx>>> {
338 if let ty::Opaque(def_id, substs) = ty.kind() {
339 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
341 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
343 let bounds = self.tcx.bound_explicit_item_bounds(*def_id);
345 for (predicate, _) in bounds.subst_iter_copied(self.tcx, substs) {
346 let output = predicate
348 .map_bound(|kind| match kind {
349 ty::PredicateKind::Projection(projection_predicate)
350 if projection_predicate.projection_ty.item_def_id == item_def_id =>
352 projection_predicate.term.ty()
357 if output.is_some() {
358 // We don't account for multiple `Future::Output = Ty` constraints.
367 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
368 pub fn report_region_errors(
370 generic_param_scope: LocalDefId,
371 errors: &[RegionResolutionError<'tcx>],
373 debug!("report_region_errors(): {} errors to start", errors.len());
375 // try to pre-process the errors, which will group some of them
376 // together into a `ProcessedErrors` group:
377 let errors = self.process_errors(errors);
379 debug!("report_region_errors: {} errors after preprocessing", errors.len());
381 for error in errors {
382 debug!("report_region_errors: error = {:?}", error);
384 if !self.try_report_nice_region_error(&error) {
385 match error.clone() {
386 // These errors could indicate all manner of different
387 // problems with many different solutions. Rather
388 // than generate a "one size fits all" error, what we
389 // attempt to do is go through a number of specific
390 // scenarios and try to find the best way to present
391 // the error. If all of these fails, we fall back to a rather
392 // general bit of code that displays the error information
393 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
394 if sub.is_placeholder() || sup.is_placeholder() {
395 self.report_placeholder_failure(origin, sub, sup).emit();
397 self.report_concrete_failure(origin, sub, sup).emit();
401 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
402 self.report_generic_bound_failure(
411 RegionResolutionError::SubSupConflict(
420 if sub_r.is_placeholder() {
421 self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
422 } else if sup_r.is_placeholder() {
423 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
425 self.report_sub_sup_conflict(
426 var_origin, sub_origin, sub_r, sup_origin, sup_r,
431 RegionResolutionError::UpperBoundUniverseConflict(
438 assert!(sup_r.is_placeholder());
440 // Make a dummy value for the "sub region" --
441 // this is the initial value of the
442 // placeholder. In practice, we expect more
443 // tailored errors that don't really use this
445 let sub_r = self.tcx.lifetimes.re_erased;
447 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
454 // This method goes through all the errors and try to group certain types
455 // of error together, for the purpose of suggesting explicit lifetime
456 // parameters to the user. This is done so that we can have a more
457 // complete view of what lifetimes should be the same.
458 // If the return value is an empty vector, it means that processing
459 // failed (so the return value of this method should not be used).
461 // The method also attempts to weed out messages that seem like
462 // duplicates that will be unhelpful to the end-user. But
463 // obviously it never weeds out ALL errors.
466 errors: &[RegionResolutionError<'tcx>],
467 ) -> Vec<RegionResolutionError<'tcx>> {
468 debug!("process_errors()");
470 // We want to avoid reporting generic-bound failures if we can
471 // avoid it: these have a very high rate of being unhelpful in
472 // practice. This is because they are basically secondary
473 // checks that test the state of the region graph after the
474 // rest of inference is done, and the other kinds of errors
475 // indicate that the region constraint graph is internally
476 // inconsistent, so these test results are likely to be
479 // Therefore, we filter them out of the list unless they are
480 // the only thing in the list.
482 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
483 RegionResolutionError::GenericBoundFailure(..) => true,
484 RegionResolutionError::ConcreteFailure(..)
485 | RegionResolutionError::SubSupConflict(..)
486 | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
489 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
492 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
495 // sort the errors by span, for better error message stability.
496 errors.sort_by_key(|u| match *u {
497 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
498 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
499 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
500 RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
505 /// Adds a note if the types come from similarly named crates
506 fn check_and_note_conflicting_crates(&self, err: &mut Diagnostic, terr: TypeError<'tcx>) {
507 use hir::def_id::CrateNum;
508 use rustc_hir::definitions::DisambiguatedDefPathData;
509 use ty::print::Printer;
510 use ty::subst::GenericArg;
512 struct AbsolutePathPrinter<'tcx> {
516 struct NonTrivialPath;
518 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
519 type Error = NonTrivialPath;
521 type Path = Vec<String>;
524 type DynExistential = !;
527 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
531 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
535 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
539 fn print_dyn_existential(
541 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
542 ) -> Result<Self::DynExistential, Self::Error> {
546 fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
550 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
551 Ok(vec![self.tcx.crate_name(cnum).to_string()])
556 _trait_ref: Option<ty::TraitRef<'tcx>>,
557 ) -> Result<Self::Path, Self::Error> {
563 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
564 _disambiguated_data: &DisambiguatedDefPathData,
566 _trait_ref: Option<ty::TraitRef<'tcx>>,
567 ) -> Result<Self::Path, Self::Error> {
572 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
573 disambiguated_data: &DisambiguatedDefPathData,
574 ) -> Result<Self::Path, Self::Error> {
575 let mut path = print_prefix(self)?;
576 path.push(disambiguated_data.to_string());
579 fn path_generic_args(
581 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
582 _args: &[GenericArg<'tcx>],
583 ) -> Result<Self::Path, Self::Error> {
588 let report_path_match = |err: &mut Diagnostic, did1: DefId, did2: DefId| {
589 // Only external crates, if either is from a local
590 // module we could have false positives
591 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
593 |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
595 // We compare strings because DefPath can be different
596 // for imported and non-imported crates
597 let same_path = || -> Result<_, NonTrivialPath> {
598 Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
599 || abs_path(did1)? == abs_path(did2)?)
601 if same_path().unwrap_or(false) {
602 let crate_name = self.tcx.crate_name(did1.krate);
604 "perhaps two different versions of crate `{}` are being used?",
611 TypeError::Sorts(ref exp_found) => {
612 // if they are both "path types", there's a chance of ambiguity
613 // due to different versions of the same crate
614 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
615 (exp_found.expected.kind(), exp_found.found.kind())
617 report_path_match(err, exp_adt.did(), found_adt.did());
620 TypeError::Traits(ref exp_found) => {
621 report_path_match(err, exp_found.expected, exp_found.found);
623 _ => (), // FIXME(#22750) handle traits and stuff
627 fn note_error_origin(
629 err: &mut Diagnostic,
630 cause: &ObligationCause<'tcx>,
631 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
632 terr: TypeError<'tcx>,
634 match *cause.code() {
635 ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
636 let ty = self.resolve_vars_if_possible(root_ty);
637 if !matches!(ty.kind(), ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)))
639 // don't show type `_`
640 if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
641 && let ty::Adt(def, substs) = ty.kind()
642 && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
644 err.span_label(span, format!("this is an iterator with items of type `{}`", substs.type_at(0)));
646 err.span_label(span, format!("this expression has type `{}`", ty));
649 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
650 && ty.is_box() && ty.boxed_ty() == found
651 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
655 "consider dereferencing the boxed value",
656 format!("*{}", snippet),
657 Applicability::MachineApplicable,
661 ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
662 err.span_label(span, "expected due to this");
664 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
674 opt_suggest_box_span,
678 hir::MatchSource::TryDesugar => {
679 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
680 let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
681 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
682 let arg_expr = args.first().expect("try desugaring call w/out arg");
683 self.typeck_results.as_ref().and_then(|typeck_results| {
684 typeck_results.expr_ty_opt(arg_expr)
687 bug!("try desugaring w/out call expr as scrutinee");
691 Some(ty) if expected == ty => {
692 let source_map = self.tcx.sess.source_map();
694 source_map.end_point(cause.span),
695 "try removing this `?`",
697 Applicability::MachineApplicable,
705 // `prior_arm_ty` can be `!`, `expected` will have better info when present.
706 let t = self.resolve_vars_if_possible(match exp_found {
707 Some(ty::error::ExpectedFound { expected, .. }) => expected,
710 let source_map = self.tcx.sess.source_map();
711 let mut any_multiline_arm = source_map.is_multiline(arm_span);
712 if prior_arms.len() <= 4 {
713 for sp in prior_arms {
714 any_multiline_arm |= source_map.is_multiline(*sp);
715 err.span_label(*sp, format!("this is found to be of type `{}`", t));
717 } else if let Some(sp) = prior_arms.last() {
718 any_multiline_arm |= source_map.is_multiline(*sp);
721 format!("this and all prior arms are found to be of type `{}`", t),
724 let outer_error_span = if any_multiline_arm {
725 // Cover just `match` and the scrutinee expression, not
726 // the entire match body, to reduce diagram noise.
727 cause.span.shrink_to_lo().to(scrut_span)
731 let msg = "`match` arms have incompatible types";
732 err.span_label(outer_error_span, msg);
733 self.suggest_remove_semi_or_return_binding(
742 if let Some(ret_sp) = opt_suggest_box_span {
743 // Get return type span and point to it.
744 self.suggest_boxing_for_return_impl_trait(
747 prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
752 ObligationCauseCode::IfExpression(box IfExpressionCause {
758 opt_suggest_box_span,
760 let then_span = self.find_block_span_from_hir_id(then_id);
761 let else_span = self.find_block_span_from_hir_id(else_id);
762 err.span_label(then_span, "expected because of this");
763 if let Some(sp) = outer_span {
764 err.span_label(sp, "`if` and `else` have incompatible types");
766 self.suggest_remove_semi_or_return_binding(
775 if let Some(ret_sp) = opt_suggest_box_span {
776 self.suggest_boxing_for_return_impl_trait(
779 [then_span, else_span].into_iter(),
783 ObligationCauseCode::LetElse => {
784 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
785 err.help("...or use `match` instead of `let...else`");
788 if let ObligationCauseCode::BindingObligation(_, span)
789 | ObligationCauseCode::ExprBindingObligation(_, span, ..)
790 = cause.code().peel_derives()
791 && let TypeError::RegionsPlaceholderMismatch = terr
793 err.span_note( * span,
794 "the lifetime requirement is introduced here");
800 fn suggest_remove_semi_or_return_binding(
802 err: &mut Diagnostic,
803 first_id: Option<hir::HirId>,
806 second_id: Option<hir::HirId>,
810 let remove_semicolon = [
811 (first_id, self.resolve_vars_if_possible(second_ty)),
812 (second_id, self.resolve_vars_if_possible(first_ty)),
815 .find_map(|(id, ty)| {
816 let hir::Node::Block(blk) = self.tcx.hir().get(id?) else { return None };
817 self.could_remove_semicolon(blk, ty)
819 match remove_semicolon {
820 Some((sp, StatementAsExpression::NeedsBoxing)) => {
821 err.multipart_suggestion(
822 "consider removing this semicolon and boxing the expressions",
824 (first_span.shrink_to_lo(), "Box::new(".to_string()),
825 (first_span.shrink_to_hi(), ")".to_string()),
826 (second_span.shrink_to_lo(), "Box::new(".to_string()),
827 (second_span.shrink_to_hi(), ")".to_string()),
830 Applicability::MachineApplicable,
833 Some((sp, StatementAsExpression::CorrectType)) => {
834 err.span_suggestion_short(
836 "consider removing this semicolon",
838 Applicability::MachineApplicable,
842 for (id, ty) in [(first_id, second_ty), (second_id, first_ty)] {
844 && let hir::Node::Block(blk) = self.tcx.hir().get(id)
845 && self.consider_returning_binding(blk, ty, err)
854 fn suggest_boxing_for_return_impl_trait(
856 err: &mut Diagnostic,
858 arm_spans: impl Iterator<Item = Span>,
860 err.multipart_suggestion(
861 "you could change the return type to be a boxed trait object",
863 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
864 (return_sp.shrink_to_hi(), ">".to_string()),
866 Applicability::MaybeIncorrect,
870 [(sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string())]
873 .collect::<Vec<_>>();
874 err.multipart_suggestion(
875 "if you change the return type to expect trait objects, box the returned expressions",
877 Applicability::MaybeIncorrect,
881 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
882 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
883 /// populate `other_value` with `other_ty`.
887 /// ^^^^--------^ this is highlighted
889 /// | this type argument is exactly the same as the other type, not highlighted
890 /// this is highlighted
892 /// -------- this type is the same as a type argument in the other type, not highlighted
896 value: &mut DiagnosticStyledString,
897 other_value: &mut DiagnosticStyledString,
899 sub: ty::subst::SubstsRef<'tcx>,
903 // `value` and `other_value` hold two incomplete type representation for display.
904 // `name` is the path of both types being compared. `sub`
905 value.push_highlighted(name);
908 value.push_highlighted("<");
911 // Output the lifetimes for the first type
915 let s = lifetime.to_string();
916 if s.is_empty() { "'_".to_string() } else { s }
920 if !lifetimes.is_empty() {
921 if sub.regions().count() < len {
922 value.push_normal(lifetimes + ", ");
924 value.push_normal(lifetimes);
928 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
929 // `pos` and `other_ty`.
930 for (i, type_arg) in sub.types().enumerate() {
932 let values = self.cmp(type_arg, other_ty);
933 value.0.extend((values.0).0);
934 other_value.0.extend((values.1).0);
936 value.push_highlighted(type_arg.to_string());
939 if len > 0 && i != len - 1 {
940 value.push_normal(", ");
944 value.push_highlighted(">");
948 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
949 /// as that is the difference to the other type.
951 /// For the following code:
953 /// ```ignore (illustrative)
954 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
957 /// The type error output will behave in the following way:
961 /// ^^^^--------^ this is highlighted
963 /// | this type argument is exactly the same as the other type, not highlighted
964 /// this is highlighted
966 /// -------- this type is the same as a type argument in the other type, not highlighted
970 mut t1_out: &mut DiagnosticStyledString,
971 mut t2_out: &mut DiagnosticStyledString,
973 sub: &'tcx [ty::GenericArg<'tcx>],
977 // FIXME/HACK: Go back to `SubstsRef` to use its inherent methods,
978 // ideally that shouldn't be necessary.
979 let sub = self.tcx.intern_substs(sub);
980 for (i, ta) in sub.types().enumerate() {
982 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
985 if let ty::Adt(def, _) = ta.kind() {
986 let path_ = self.tcx.def_path_str(def.did());
987 if path_ == other_path {
988 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
996 /// Adds a `,` to the type representation only if it is appropriate.
999 value: &mut DiagnosticStyledString,
1000 other_value: &mut DiagnosticStyledString,
1004 if len > 0 && pos != len - 1 {
1005 value.push_normal(", ");
1006 other_value.push_normal(", ");
1010 fn normalize_fn_sig_for_diagnostic(&self, sig: ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx> {
1011 if let Some(normalize) = &self.normalize_fn_sig_for_diagnostic {
1012 normalize(self, sig)
1018 /// Given two `fn` signatures highlight only sub-parts that are different.
1021 sig1: &ty::PolyFnSig<'tcx>,
1022 sig2: &ty::PolyFnSig<'tcx>,
1023 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1024 let sig1 = &self.normalize_fn_sig_for_diagnostic(*sig1);
1025 let sig2 = &self.normalize_fn_sig_for_diagnostic(*sig2);
1027 let get_lifetimes = |sig| {
1028 use rustc_hir::def::Namespace;
1029 let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
1030 .name_all_regions(sig)
1032 let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
1033 (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
1036 let (lt1, sig1) = get_lifetimes(sig1);
1037 let (lt2, sig2) = get_lifetimes(sig2);
1039 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1041 DiagnosticStyledString::normal("".to_string()),
1042 DiagnosticStyledString::normal("".to_string()),
1045 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1047 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1048 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1050 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1052 if sig1.abi != abi::Abi::Rust {
1053 values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
1055 if sig2.abi != abi::Abi::Rust {
1056 values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
1059 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1061 let lifetime_diff = lt1 != lt2;
1062 values.0.push(lt1, lifetime_diff);
1063 values.1.push(lt2, lifetime_diff);
1065 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1067 values.0.push_normal("fn(");
1068 values.1.push_normal("fn(");
1070 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1072 let len1 = sig1.inputs().len();
1073 let len2 = sig2.inputs().len();
1075 for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1076 let (x1, x2) = self.cmp(*l, *r);
1077 (values.0).0.extend(x1.0);
1078 (values.1).0.extend(x2.0);
1079 self.push_comma(&mut values.0, &mut values.1, len1, i);
1082 for (i, l) in sig1.inputs().iter().enumerate() {
1083 values.0.push_highlighted(l.to_string());
1085 values.0.push_highlighted(", ");
1088 for (i, r) in sig2.inputs().iter().enumerate() {
1089 values.1.push_highlighted(r.to_string());
1091 values.1.push_highlighted(", ");
1096 if sig1.c_variadic {
1098 values.0.push_normal(", ");
1100 values.0.push("...", !sig2.c_variadic);
1102 if sig2.c_variadic {
1104 values.1.push_normal(", ");
1106 values.1.push("...", !sig1.c_variadic);
1109 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1111 values.0.push_normal(")");
1112 values.1.push_normal(")");
1114 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1116 let output1 = sig1.output();
1117 let output2 = sig2.output();
1118 let (x1, x2) = self.cmp(output1, output2);
1119 if !output1.is_unit() {
1120 values.0.push_normal(" -> ");
1121 (values.0).0.extend(x1.0);
1123 if !output2.is_unit() {
1124 values.1.push_normal(" -> ");
1125 (values.1).0.extend(x2.0);
1130 /// Compares two given types, eliding parts that are the same between them and highlighting
1131 /// relevant differences, and return two representation of those types for highlighted printing.
1136 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1137 debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1140 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1141 match (a.kind(), b.kind()) {
1142 (a, b) if *a == *b => true,
1143 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1145 &ty::Infer(ty::InferTy::IntVar(_)),
1146 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1148 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1150 &ty::Infer(ty::InferTy::FloatVar(_)),
1151 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1157 fn push_ty_ref<'tcx>(
1158 region: ty::Region<'tcx>,
1160 mutbl: hir::Mutability,
1161 s: &mut DiagnosticStyledString,
1163 let mut r = region.to_string();
1169 s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1170 s.push_normal(ty.to_string());
1173 // process starts here
1174 match (t1.kind(), t2.kind()) {
1175 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1176 let did1 = def1.did();
1177 let did2 = def2.did();
1178 let sub_no_defaults_1 =
1179 self.tcx.generics_of(did1).own_substs_no_defaults(self.tcx, sub1);
1180 let sub_no_defaults_2 =
1181 self.tcx.generics_of(did2).own_substs_no_defaults(self.tcx, sub2);
1182 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1183 let path1 = self.tcx.def_path_str(did1);
1184 let path2 = self.tcx.def_path_str(did2);
1186 // Easy case. Replace same types with `_` to shorten the output and highlight
1187 // the differing ones.
1188 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1191 // --- ^ type argument elided
1193 // highlighted in output
1194 values.0.push_normal(path1);
1195 values.1.push_normal(path2);
1197 // Avoid printing out default generic parameters that are common to both
1199 let len1 = sub_no_defaults_1.len();
1200 let len2 = sub_no_defaults_2.len();
1201 let common_len = cmp::min(len1, len2);
1202 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1203 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1204 let common_default_params =
1205 iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1206 .filter(|(a, b)| a == b)
1208 let len = sub1.len() - common_default_params;
1209 let consts_offset = len - sub1.consts().count();
1211 // Only draw `<...>` if there are lifetime/type arguments.
1213 values.0.push_normal("<");
1214 values.1.push_normal("<");
1217 fn lifetime_display(lifetime: Region<'_>) -> String {
1218 let s = lifetime.to_string();
1219 if s.is_empty() { "'_".to_string() } else { s }
1221 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1222 // all diagnostics that use this output
1226 // ^^ ^^ --- type arguments are not elided
1228 // | elided as they were the same
1229 // not elided, they were different, but irrelevant
1231 // For bound lifetimes, keep the names of the lifetimes,
1232 // even if they are the same so that it's clear what's happening
1233 // if we have something like
1235 // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1236 // for<'r> fn(Inv<'r>, Inv<'r>)
1237 let lifetimes = sub1.regions().zip(sub2.regions());
1238 for (i, lifetimes) in lifetimes.enumerate() {
1239 let l1 = lifetime_display(lifetimes.0);
1240 let l2 = lifetime_display(lifetimes.1);
1241 if lifetimes.0 != lifetimes.1 {
1242 values.0.push_highlighted(l1);
1243 values.1.push_highlighted(l2);
1244 } else if lifetimes.0.is_late_bound() {
1245 values.0.push_normal(l1);
1246 values.1.push_normal(l2);
1248 values.0.push_normal("'_");
1249 values.1.push_normal("'_");
1251 self.push_comma(&mut values.0, &mut values.1, len, i);
1254 // We're comparing two types with the same path, so we compare the type
1255 // arguments for both. If they are the same, do not highlight and elide from the
1259 // ^ elided type as this type argument was the same in both sides
1260 let type_arguments = sub1.types().zip(sub2.types());
1261 let regions_len = sub1.regions().count();
1262 let num_display_types = consts_offset - regions_len;
1263 for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1264 let i = i + regions_len;
1266 values.0.push_normal("_");
1267 values.1.push_normal("_");
1269 let (x1, x2) = self.cmp(ta1, ta2);
1270 (values.0).0.extend(x1.0);
1271 (values.1).0.extend(x2.0);
1273 self.push_comma(&mut values.0, &mut values.1, len, i);
1276 // Do the same for const arguments, if they are equal, do not highlight and
1277 // elide them from the output.
1278 let const_arguments = sub1.consts().zip(sub2.consts());
1279 for (i, (ca1, ca2)) in const_arguments.enumerate() {
1280 let i = i + consts_offset;
1282 values.0.push_normal("_");
1283 values.1.push_normal("_");
1285 values.0.push_highlighted(ca1.to_string());
1286 values.1.push_highlighted(ca2.to_string());
1288 self.push_comma(&mut values.0, &mut values.1, len, i);
1291 // Close the type argument bracket.
1292 // Only draw `<...>` if there are lifetime/type arguments.
1294 values.0.push_normal(">");
1295 values.1.push_normal(">");
1300 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1302 // ------- this type argument is exactly the same as the other type
1318 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1321 // ------- this type argument is exactly the same as the other type
1336 // We can't find anything in common, highlight relevant part of type path.
1337 // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1338 // foo::bar::Baz<Qux>
1339 // foo::bar::Bar<Zar>
1340 // -------- this part of the path is different
1342 let t1_str = t1.to_string();
1343 let t2_str = t2.to_string();
1344 let min_len = t1_str.len().min(t2_str.len());
1346 const SEPARATOR: &str = "::";
1347 let separator_len = SEPARATOR.len();
1348 let split_idx: usize =
1349 iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1350 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1351 .map(|(mod_str, _)| mod_str.len() + separator_len)
1355 "cmp: separator_len={}, split_idx={}, min_len={}",
1356 separator_len, split_idx, min_len
1359 if split_idx >= min_len {
1360 // paths are identical, highlight everything
1362 DiagnosticStyledString::highlighted(t1_str),
1363 DiagnosticStyledString::highlighted(t2_str),
1366 let (common, uniq1) = t1_str.split_at(split_idx);
1367 let (_, uniq2) = t2_str.split_at(split_idx);
1368 debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1370 values.0.push_normal(common);
1371 values.0.push_highlighted(uniq1);
1372 values.1.push_normal(common);
1373 values.1.push_highlighted(uniq2);
1380 // When finding T != &T, highlight only the borrow
1381 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(ref_ty1, t2) => {
1382 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1383 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1384 values.1.push_normal(t2.to_string());
1387 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(t1, ref_ty2) => {
1388 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1389 values.0.push_normal(t1.to_string());
1390 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1394 // When encountering &T != &mut T, highlight only the borrow
1395 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1396 if equals(ref_ty1, ref_ty2) =>
1398 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1399 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1400 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1404 // When encountering tuples of the same size, highlight only the differing types
1405 (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1407 (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1408 let len = substs1.len();
1409 for (i, (left, right)) in substs1.iter().zip(substs2).enumerate() {
1410 let (x1, x2) = self.cmp(left, right);
1411 (values.0).0.extend(x1.0);
1412 (values.1).0.extend(x2.0);
1413 self.push_comma(&mut values.0, &mut values.1, len, i);
1416 // Keep the output for single element tuples as `(ty,)`.
1417 values.0.push_normal(",");
1418 values.1.push_normal(",");
1420 values.0.push_normal(")");
1421 values.1.push_normal(")");
1425 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1426 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1427 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1428 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1429 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1430 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1431 let same_path = path1 == path2;
1432 values.0.push(path1, !same_path);
1433 values.1.push(path2, !same_path);
1437 (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1438 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1439 let mut values = self.cmp_fn_sig(&sig1, sig2);
1440 values.0.push_highlighted(format!(
1442 self.tcx.def_path_str_with_substs(*did1, substs1)
1447 (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1448 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1449 let mut values = self.cmp_fn_sig(sig1, &sig2);
1450 values.1.push_normal(format!(
1452 self.tcx.def_path_str_with_substs(*did2, substs2)
1457 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1461 // The two types are the same, elide and don't highlight.
1462 (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1464 // We couldn't find anything in common, highlight everything.
1466 DiagnosticStyledString::highlighted(t1.to_string()),
1467 DiagnosticStyledString::highlighted(t2.to_string()),
1474 /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1475 /// the return type of `async fn`s.
1477 /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1479 /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1480 /// the message in `secondary_span` as the primary label, and apply the message that would
1481 /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1482 /// E0271, like `src/test/ui/issues/issue-39970.stderr`.
1485 skip(self, diag, secondary_span, swap_secondary_and_primary, prefer_label)
1487 pub fn note_type_err(
1489 diag: &mut Diagnostic,
1490 cause: &ObligationCause<'tcx>,
1491 secondary_span: Option<(Span, String)>,
1492 mut values: Option<ValuePairs<'tcx>>,
1493 terr: TypeError<'tcx>,
1494 swap_secondary_and_primary: bool,
1497 let span = cause.span();
1499 // For some types of errors, expected-found does not make
1500 // sense, so just ignore the values we were given.
1501 if let TypeError::CyclicTy(_) = terr {
1504 struct OpaqueTypesVisitor<'tcx> {
1505 types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1506 expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1507 found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1512 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1513 fn visit_expected_found(
1519 let mut types_visitor = OpaqueTypesVisitor {
1520 types: Default::default(),
1521 expected: Default::default(),
1522 found: Default::default(),
1526 // The visitor puts all the relevant encountered types in `self.types`, but in
1527 // here we want to visit two separate types with no relation to each other, so we
1528 // move the results from `types` to `expected` or `found` as appropriate.
1529 expected.visit_with(&mut types_visitor);
1530 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1531 found.visit_with(&mut types_visitor);
1532 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1536 fn report(&self, err: &mut Diagnostic) {
1537 self.add_labels_for_types(err, "expected", &self.expected);
1538 self.add_labels_for_types(err, "found", &self.found);
1541 fn add_labels_for_types(
1543 err: &mut Diagnostic,
1545 types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
1547 for (key, values) in types.iter() {
1548 let count = values.len();
1549 let kind = key.descr();
1550 let mut returned_async_output_error = false;
1552 if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
1553 if [sp] != err.span.primary_spans() {
1554 let mut span: MultiSpan = sp.into();
1555 span.push_span_label(
1558 "checked the `Output` of this `async fn`, {}{} {}{}",
1559 if count > 1 { "one of the " } else { "" },
1567 "while checking the return type of the `async fn`",
1573 "checked the `Output` of this `async fn`, {}{} {}{}",
1574 if count > 1 { "one of the " } else { "" },
1580 err.note("while checking the return type of the `async fn`");
1582 returned_async_output_error = true;
1588 if count == 1 { "the " } else { "one of the " },
1600 impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1601 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1602 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1603 let span = self.tcx.def_span(def_id);
1604 // Avoid cluttering the output when the "found" and error span overlap:
1606 // error[E0308]: mismatched types
1607 // --> $DIR/issue-20862.rs:2:5
1612 // | the found closure
1613 // | expected `()`, found closure
1615 // = note: expected unit type `()`
1616 // found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1617 if !self.ignore_span.overlaps(span) {
1618 self.types.entry(kind).or_default().insert(span);
1621 t.super_visit_with(self)
1625 debug!("note_type_err(diag={:?})", diag);
1627 Variable(ty::error::ExpectedFound<Ty<'a>>),
1628 Fixed(&'static str),
1630 let (expected_found, exp_found, is_simple_error, values) = match values {
1631 None => (None, Mismatch::Fixed("type"), false, None),
1633 let values = self.resolve_vars_if_possible(values);
1634 let (is_simple_error, exp_found) = match values {
1635 ValuePairs::Terms(infer::ExpectedFound { expected, found }) => {
1636 match (expected.unpack(), found.unpack()) {
1637 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
1639 expected.is_simple_text() && found.is_simple_text();
1640 OpaqueTypesVisitor::visit_expected_found(
1641 self.tcx, expected, found, span,
1647 Mismatch::Variable(infer::ExpectedFound { expected, found }),
1650 (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1651 (false, Mismatch::Fixed("constant"))
1653 _ => (false, Mismatch::Fixed("type")),
1656 ValuePairs::TraitRefs(_) | ValuePairs::PolyTraitRefs(_) => {
1657 (false, Mismatch::Fixed("trait"))
1659 ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime")),
1661 let vals = match self.values_str(values) {
1662 Some((expected, found)) => Some((expected, found)),
1664 // Derived error. Cancel the emitter.
1665 // NOTE(eddyb) this was `.cancel()`, but `diag`
1666 // is borrowed, so we can't fully defuse it.
1667 diag.downgrade_to_delayed_bug();
1671 (vals, exp_found, is_simple_error, Some(values))
1676 // Ignore msg for object safe coercion
1677 // since E0038 message will be printed
1678 TypeError::ObjectUnsafeCoercion(_) => {}
1680 let mut label_or_note = |span: Span, msg: &str| {
1681 if (prefer_label && is_simple_error) || &[span] == diag.span.primary_spans() {
1682 diag.span_label(span, msg);
1684 diag.span_note(span, msg);
1687 if let Some((sp, msg)) = secondary_span {
1688 if swap_secondary_and_primary {
1689 let terr = if let Some(infer::ValuePairs::Terms(infer::ExpectedFound {
1694 format!("expected this to be `{}`", expected)
1698 label_or_note(sp, &terr);
1699 label_or_note(span, &msg);
1701 label_or_note(span, &terr.to_string());
1702 label_or_note(sp, &msg);
1705 label_or_note(span, &terr.to_string());
1709 if let Some((expected, found)) = expected_found {
1710 let (expected_label, found_label, exp_found) = match exp_found {
1711 Mismatch::Variable(ef) => (
1712 ef.expected.prefix_string(self.tcx),
1713 ef.found.prefix_string(self.tcx),
1716 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1719 enum Similar<'tcx> {
1720 Adts { expected: ty::AdtDef<'tcx>, found: ty::AdtDef<'tcx> },
1721 PrimitiveFound { expected: ty::AdtDef<'tcx>, found: Ty<'tcx> },
1722 PrimitiveExpected { expected: Ty<'tcx>, found: ty::AdtDef<'tcx> },
1725 let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1726 if let ty::Adt(expected, _) = expected.kind() && let Some(primitive) = found.primitive_symbol() {
1727 let path = self.tcx.def_path(expected.did()).data;
1728 let name = path.last().unwrap().data.get_opt_name();
1729 if name == Some(primitive) {
1730 return Some(Similar::PrimitiveFound { expected: *expected, found });
1732 } else if let Some(primitive) = expected.primitive_symbol() && let ty::Adt(found, _) = found.kind() {
1733 let path = self.tcx.def_path(found.did()).data;
1734 let name = path.last().unwrap().data.get_opt_name();
1735 if name == Some(primitive) {
1736 return Some(Similar::PrimitiveExpected { expected, found: *found });
1738 } else if let ty::Adt(expected, _) = expected.kind() && let ty::Adt(found, _) = found.kind() {
1739 if !expected.did().is_local() && expected.did().krate == found.did().krate {
1740 // Most likely types from different versions of the same crate
1741 // are in play, in which case this message isn't so helpful.
1742 // A "perhaps two different versions..." error is already emitted for that.
1745 let f_path = self.tcx.def_path(found.did()).data;
1746 let e_path = self.tcx.def_path(expected.did()).data;
1748 if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last()) && e_last == f_last {
1749 return Some(Similar::Adts{expected: *expected, found: *found});
1756 // If two types mismatch but have similar names, mention that specifically.
1757 TypeError::Sorts(values) if let Some(s) = similarity(values) => {
1758 let diagnose_primitive =
1762 diagnostic: &mut Diagnostic| {
1763 let name = shadow.sort_string(self.tcx);
1764 diagnostic.note(format!(
1765 "{prim} and {name} have similar names, but are actually distinct types"
1768 .note(format!("{prim} is a primitive defined by the language"));
1769 let def_span = self.tcx.def_span(defid);
1770 let msg = if defid.is_local() {
1771 format!("{name} is defined in the current crate")
1773 let crate_name = self.tcx.crate_name(defid.krate);
1774 format!("{name} is defined in crate `{crate_name}")
1776 diagnostic.span_note(def_span, msg);
1780 |expected_adt : ty::AdtDef<'tcx>,
1781 found_adt: ty::AdtDef<'tcx>,
1782 diagnostic: &mut Diagnostic| {
1783 let found_name = values.found.sort_string(self.tcx);
1784 let expected_name = values.expected.sort_string(self.tcx);
1786 let found_defid = found_adt.did();
1787 let expected_defid = expected_adt.did();
1789 diagnostic.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types"));
1790 for (defid, name) in
1791 [(found_defid, found_name), (expected_defid, expected_name)]
1793 let def_span = self.tcx.def_span(defid);
1795 let msg = if found_defid.is_local() && expected_defid.is_local() {
1798 .parent_module_from_def_id(defid.expect_local())
1800 let module_name = self.tcx.def_path(module).to_string_no_crate_verbose();
1801 format!("{name} is defined in module `crate{module_name}` of the current crate")
1802 } else if defid.is_local() {
1803 format!("{name} is defined in the current crate")
1805 let crate_name = self.tcx.crate_name(defid.krate);
1806 format!("{name} is defined in crate `{crate_name}`")
1808 diagnostic.span_note(def_span, msg);
1813 Similar::Adts{expected, found} => {
1814 diagnose_adts(expected, found, diag)
1816 Similar::PrimitiveFound{expected, found: prim} => {
1817 diagnose_primitive(prim, values.expected, expected.did(), diag)
1819 Similar::PrimitiveExpected{expected: prim, found} => {
1820 diagnose_primitive(prim, values.found, found.did(), diag)
1824 TypeError::Sorts(values) => {
1825 let extra = expected == found;
1826 let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1827 (true, ty::Opaque(def_id, _)) => {
1828 let sm = self.tcx.sess.source_map();
1829 let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1831 " (opaque type at <{}:{}:{}>)",
1832 sm.filename_for_diagnostics(&pos.file.name),
1834 pos.col.to_usize() + 1,
1837 (true, ty::Projection(proj))
1838 if self.tcx.def_kind(proj.item_def_id)
1839 == DefKind::ImplTraitPlaceholder =>
1841 let sm = self.tcx.sess.source_map();
1842 let pos = sm.lookup_char_pos(self.tcx.def_span(proj.item_def_id).lo());
1844 " (trait associated opaque type at <{}:{}:{}>)",
1845 sm.filename_for_diagnostics(&pos.file.name),
1847 pos.col.to_usize() + 1,
1850 (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1851 (false, _) => "".to_string(),
1853 if !(values.expected.is_simple_text() && values.found.is_simple_text())
1854 || (exp_found.map_or(false, |ef| {
1855 // This happens when the type error is a subset of the expectation,
1856 // like when you have two references but one is `usize` and the other
1857 // is `f32`. In those cases we still want to show the `note`. If the
1858 // value from `ef` is `Infer(_)`, then we ignore it.
1859 if !ef.expected.is_ty_infer() {
1860 ef.expected != values.expected
1861 } else if !ef.found.is_ty_infer() {
1862 ef.found != values.found
1868 diag.note_expected_found_extra(
1873 &sort_string(values.expected),
1874 &sort_string(values.found),
1878 TypeError::ObjectUnsafeCoercion(_) => {
1879 diag.note_unsuccessful_coercion(found, expected);
1883 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1884 exp_found, expected, found
1886 if !is_simple_error || terr.must_include_note() {
1887 diag.note_expected_found(&expected_label, expected, &found_label, found);
1892 let exp_found = match exp_found {
1893 Mismatch::Variable(exp_found) => Some(exp_found),
1894 Mismatch::Fixed(_) => None,
1896 let exp_found = match terr {
1897 // `terr` has more accurate type information than `exp_found` in match expressions.
1898 ty::error::TypeError::Sorts(terr)
1899 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1905 debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1906 if let Some(exp_found) = exp_found {
1907 let should_suggest_fixes =
1908 if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
1909 // Skip if the root_ty of the pattern is not the same as the expected_ty.
1910 // If these types aren't equal then we've probably peeled off a layer of arrays.
1911 self.same_type_modulo_infer(*root_ty, exp_found.expected)
1916 if should_suggest_fixes {
1917 self.suggest_tuple_pattern(cause, &exp_found, diag);
1918 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1919 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1920 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1924 // In some (most?) cases cause.body_id points to actual body, but in some cases
1925 // it's an actual definition. According to the comments (e.g. in
1926 // rustc_hir_analysis/check/compare_method.rs:compare_predicate_entailment) the latter
1927 // is relied upon by some other code. This might (or might not) need cleanup.
1928 let body_owner_def_id =
1929 self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1930 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1932 self.check_and_note_conflicting_crates(diag, terr);
1933 self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1935 if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
1936 && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
1937 && let Some(def_id) = def_id.as_local()
1938 && terr.involves_regions()
1940 let span = self.tcx.def_span(def_id);
1941 diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1944 // It reads better to have the error origin as the final
1946 self.note_error_origin(diag, cause, exp_found, terr);
1951 fn suggest_tuple_pattern(
1953 cause: &ObligationCause<'tcx>,
1954 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1955 diag: &mut Diagnostic,
1957 // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with
1958 // some modifications due to that being in typeck and this being in infer.
1959 if let ObligationCauseCode::Pattern { .. } = cause.code() {
1960 if let ty::Adt(expected_adt, substs) = exp_found.expected.kind() {
1961 let compatible_variants: Vec<_> = expected_adt
1965 variant.fields.len() == 1 && variant.ctor_kind == hir::def::CtorKind::Fn
1967 .filter_map(|variant| {
1968 let sole_field = &variant.fields[0];
1969 let sole_field_ty = sole_field.ty(self.tcx, substs);
1970 if self.same_type_modulo_infer(sole_field_ty, exp_found.found) {
1972 with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
1973 // FIXME #56861: DRYer prelude filtering
1974 if let Some(path) = variant_path.strip_prefix("std::prelude::") {
1975 if let Some((_, path)) = path.split_once("::") {
1976 return Some(path.to_string());
1985 match &compatible_variants[..] {
1988 diag.multipart_suggestion_verbose(
1989 &format!("try wrapping the pattern in `{}`", variant),
1991 (cause.span.shrink_to_lo(), format!("{}(", variant)),
1992 (cause.span.shrink_to_hi(), ")".to_string()),
1994 Applicability::MaybeIncorrect,
1998 // More than one matching variant.
1999 diag.multipart_suggestions(
2001 "try wrapping the pattern in a variant of `{}`",
2002 self.tcx.def_path_str(expected_adt.did())
2004 compatible_variants.into_iter().map(|variant| {
2006 (cause.span.shrink_to_lo(), format!("{}(", variant)),
2007 (cause.span.shrink_to_hi(), ")".to_string()),
2010 Applicability::MaybeIncorrect,
2018 /// A possible error is to forget to add `.await` when using futures:
2020 /// ```compile_fail,E0308
2021 /// async fn make_u32() -> u32 {
2025 /// fn take_u32(x: u32) {}
2027 /// async fn foo() {
2028 /// let x = make_u32();
2033 /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
2034 /// expected type. If this is the case, and we are inside of an async body, it suggests adding
2035 /// `.await` to the tail of the expression.
2036 fn suggest_await_on_expect_found(
2038 cause: &ObligationCause<'tcx>,
2040 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2041 diag: &mut Diagnostic,
2044 "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
2045 exp_span, exp_found.expected, exp_found.found,
2048 if let ObligationCauseCode::CompareImplItemObligation { .. } = cause.code() {
2053 self.get_impl_future_output_ty(exp_found.expected).map(Binder::skip_binder),
2054 self.get_impl_future_output_ty(exp_found.found).map(Binder::skip_binder),
2056 (Some(exp), Some(found)) if self.same_type_modulo_infer(exp, found) => match cause
2059 ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => {
2060 let then_span = self.find_block_span_from_hir_id(*then_id);
2061 diag.multipart_suggestion(
2062 "consider `await`ing on both `Future`s",
2064 (then_span.shrink_to_hi(), ".await".to_string()),
2065 (exp_span.shrink_to_hi(), ".await".to_string()),
2067 Applicability::MaybeIncorrect,
2070 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
2074 if let [.., arm_span] = &prior_arms[..] {
2075 diag.multipart_suggestion(
2076 "consider `await`ing on both `Future`s",
2078 (arm_span.shrink_to_hi(), ".await".to_string()),
2079 (exp_span.shrink_to_hi(), ".await".to_string()),
2081 Applicability::MaybeIncorrect,
2084 diag.help("consider `await`ing on both `Future`s");
2088 diag.help("consider `await`ing on both `Future`s");
2091 (_, Some(ty)) if self.same_type_modulo_infer(exp_found.expected, ty) => {
2092 diag.span_suggestion_verbose(
2093 exp_span.shrink_to_hi(),
2094 "consider `await`ing on the `Future`",
2096 Applicability::MaybeIncorrect,
2099 (Some(ty), _) if self.same_type_modulo_infer(ty, exp_found.found) => match cause.code()
2101 ObligationCauseCode::Pattern { span: Some(then_span), .. } => {
2102 diag.span_suggestion_verbose(
2103 then_span.shrink_to_hi(),
2104 "consider `await`ing on the `Future`",
2106 Applicability::MaybeIncorrect,
2109 ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => {
2110 let then_span = self.find_block_span_from_hir_id(*then_id);
2111 diag.span_suggestion_verbose(
2112 then_span.shrink_to_hi(),
2113 "consider `await`ing on the `Future`",
2115 Applicability::MaybeIncorrect,
2118 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
2122 diag.multipart_suggestion_verbose(
2123 "consider `await`ing on the `Future`",
2126 .map(|arm| (arm.shrink_to_hi(), ".await".to_string()))
2128 Applicability::MaybeIncorrect,
2137 fn suggest_accessing_field_where_appropriate(
2139 cause: &ObligationCause<'tcx>,
2140 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2141 diag: &mut Diagnostic,
2144 "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
2147 if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
2148 if expected_def.is_enum() {
2152 if let Some((name, ty)) = expected_def
2156 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
2157 .map(|field| (field.name, field.ty(self.tcx, expected_substs)))
2158 .find(|(_, ty)| self.same_type_modulo_infer(*ty, exp_found.found))
2160 if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() {
2161 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2162 let suggestion = if expected_def.is_struct() {
2163 format!("{}.{}", snippet, name)
2164 } else if expected_def.is_union() {
2165 format!("unsafe {{ {}.{} }}", snippet, name)
2169 diag.span_suggestion(
2172 "you might have meant to use field `{}` whose type is `{}`",
2176 Applicability::MaybeIncorrect,
2184 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
2186 fn suggest_as_ref_where_appropriate(
2189 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2190 diag: &mut Diagnostic,
2192 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2193 && let Some(msg) = self.should_suggest_as_ref(exp_found.expected, exp_found.found)
2195 diag.span_suggestion(
2198 // HACK: fix issue# 100605, suggesting convert from &Option<T> to Option<&T>, remove the extra `&`
2199 format!("{}.as_ref()", snippet.trim_start_matches('&')),
2200 Applicability::MachineApplicable,
2205 pub fn should_suggest_as_ref(&self, expected: Ty<'tcx>, found: Ty<'tcx>) -> Option<&str> {
2206 if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
2207 (expected.kind(), found.kind())
2209 if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
2210 if exp_def == &found_def {
2211 let have_as_ref = &[
2214 "you can convert from `&Option<T>` to `Option<&T>` using \
2219 "you can convert from `&Result<T, E>` to \
2220 `Result<&T, &E>` using `.as_ref()`",
2223 if let Some(msg) = have_as_ref.iter().find_map(|(name, msg)| {
2224 self.tcx.is_diagnostic_item(*name, exp_def.did()).then_some(msg)
2226 let mut show_suggestion = true;
2227 for (exp_ty, found_ty) in
2228 iter::zip(exp_substs.types(), found_substs.types())
2230 match *exp_ty.kind() {
2231 ty::Ref(_, exp_ty, _) => {
2232 match (exp_ty.kind(), found_ty.kind()) {
2236 | (ty::Infer(_), _) => {}
2237 _ if self.same_type_modulo_infer(exp_ty, found_ty) => {}
2238 _ => show_suggestion = false,
2241 ty::Param(_) | ty::Infer(_) => {}
2242 _ => show_suggestion = false,
2245 if show_suggestion {
2255 pub fn report_and_explain_type_error(
2257 trace: TypeTrace<'tcx>,
2258 terr: TypeError<'tcx>,
2259 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2260 use crate::traits::ObligationCauseCode::MatchExpressionArm;
2262 debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2264 let span = trace.cause.span();
2265 let failure_code = trace.cause.as_failure_code(terr);
2266 let mut diag = match failure_code {
2267 FailureCode::Error0038(did) => {
2268 let violations = self.tcx.object_safety_violations(did);
2269 report_object_safety_error(self.tcx, span, did, violations)
2271 FailureCode::Error0317(failure_str) => {
2272 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
2274 FailureCode::Error0580(failure_str) => {
2275 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
2277 FailureCode::Error0308(failure_str) => {
2278 fn escape_literal(s: &str) -> String {
2279 let mut escaped = String::with_capacity(s.len());
2280 let mut chrs = s.chars().peekable();
2281 while let Some(first) = chrs.next() {
2282 match (first, chrs.peek()) {
2283 ('\\', Some(&delim @ '"') | Some(&delim @ '\'')) => {
2285 escaped.push(delim);
2288 ('"' | '\'', _) => {
2292 (c, _) => escaped.push(c),
2297 let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
2298 if let Some((expected, found)) = trace.values.ty() {
2299 match (expected.kind(), found.kind()) {
2300 (ty::Tuple(_), ty::Tuple(_)) => {}
2301 // If a tuple of length one was expected and the found expression has
2302 // parentheses around it, perhaps the user meant to write `(expr,)` to
2303 // build a tuple (issue #86100)
2304 (ty::Tuple(fields), _) => {
2305 self.emit_tuple_wrap_err(&mut err, span, found, fields)
2307 // If a character was expected and the found expression is a string literal
2308 // containing a single character, perhaps the user meant to write `'c'` to
2309 // specify a character literal (issue #92479)
2310 (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2311 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2312 && let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
2313 && code.chars().count() == 1
2315 err.span_suggestion(
2317 "if you meant to write a `char` literal, use single quotes",
2318 format!("'{}'", escape_literal(code)),
2319 Applicability::MachineApplicable,
2323 // If a string was expected and the found expression is a character literal,
2324 // perhaps the user meant to write `"s"` to specify a string literal.
2325 (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2326 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2328 code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2330 err.span_suggestion(
2332 "if you meant to write a `str` literal, use double quotes",
2333 format!("\"{}\"", escape_literal(code)),
2334 Applicability::MachineApplicable,
2342 let code = trace.cause.code();
2343 if let &MatchExpressionArm(box MatchExpressionArmCause { source, .. }) = code
2344 && let hir::MatchSource::TryDesugar = source
2345 && let Some((expected_ty, found_ty)) = self.values_str(trace.values)
2348 "`?` operator cannot convert from `{}` to `{}`",
2350 expected_ty.content(),
2355 FailureCode::Error0644(failure_str) => {
2356 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
2359 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false, false);
2363 fn emit_tuple_wrap_err(
2365 err: &mut Diagnostic,
2368 expected_fields: &List<Ty<'tcx>>,
2370 let [expected_tup_elem] = expected_fields[..] else { return };
2372 if !self.same_type_modulo_infer(expected_tup_elem, found) {
2376 let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2379 let msg = "use a trailing comma to create a tuple with one element";
2380 if code.starts_with('(') && code.ends_with(')') {
2381 let before_close = span.hi() - BytePos::from_u32(1);
2382 err.span_suggestion(
2383 span.with_hi(before_close).shrink_to_hi(),
2386 Applicability::MachineApplicable,
2389 err.multipart_suggestion(
2391 vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
2392 Applicability::MachineApplicable,
2399 values: ValuePairs<'tcx>,
2400 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2402 infer::Regions(exp_found) => self.expected_found_str(exp_found),
2403 infer::Terms(exp_found) => self.expected_found_str_term(exp_found),
2404 infer::TraitRefs(exp_found) => {
2405 let pretty_exp_found = ty::error::ExpectedFound {
2406 expected: exp_found.expected.print_only_trait_path(),
2407 found: exp_found.found.print_only_trait_path(),
2409 match self.expected_found_str(pretty_exp_found) {
2410 Some((expected, found)) if expected == found => {
2411 self.expected_found_str(exp_found)
2416 infer::PolyTraitRefs(exp_found) => {
2417 let pretty_exp_found = ty::error::ExpectedFound {
2418 expected: exp_found.expected.print_only_trait_path(),
2419 found: exp_found.found.print_only_trait_path(),
2421 match self.expected_found_str(pretty_exp_found) {
2422 Some((expected, found)) if expected == found => {
2423 self.expected_found_str(exp_found)
2431 fn expected_found_str_term(
2433 exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2434 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2435 let exp_found = self.resolve_vars_if_possible(exp_found);
2436 if exp_found.references_error() {
2440 Some(match (exp_found.expected.unpack(), exp_found.found.unpack()) {
2441 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => self.cmp(expected, found),
2443 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2444 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2449 /// Returns a string of the form "expected `{}`, found `{}`".
2450 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
2452 exp_found: ty::error::ExpectedFound<T>,
2453 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2454 let exp_found = self.resolve_vars_if_possible(exp_found);
2455 if exp_found.references_error() {
2460 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2461 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2465 pub fn report_generic_bound_failure(
2467 generic_param_scope: LocalDefId,
2469 origin: Option<SubregionOrigin<'tcx>>,
2470 bound_kind: GenericKind<'tcx>,
2473 self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
2477 pub fn construct_generic_bound_failure(
2479 generic_param_scope: LocalDefId,
2481 origin: Option<SubregionOrigin<'tcx>>,
2482 bound_kind: GenericKind<'tcx>,
2484 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2485 // Attempt to obtain the span of the parameter so we can
2486 // suggest adding an explicit lifetime bound to it.
2487 let generics = self.tcx.generics_of(generic_param_scope);
2488 // type_param_span is (span, has_bounds)
2489 let type_param_span = match bound_kind {
2490 GenericKind::Param(ref param) => {
2491 // Account for the case where `param` corresponds to `Self`,
2492 // which doesn't have the expected type argument.
2493 if !(generics.has_self && param.index == 0) {
2494 let type_param = generics.type_param(param, self.tcx);
2495 type_param.def_id.as_local().map(|def_id| {
2496 // Get the `hir::Param` to verify whether it already has any bounds.
2497 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2498 // instead we suggest `T: 'a + 'b` in that case.
2499 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2500 let ast_generics = self.tcx.hir().get_generics(hir_id.owner.def_id);
2502 ast_generics.and_then(|g| g.bounds_span_for_suggestions(def_id));
2503 // `sp` only covers `T`, change it so that it covers
2504 // `T:` when appropriate
2505 if let Some(span) = bounds {
2508 let sp = self.tcx.def_span(def_id);
2509 (sp.shrink_to_hi(), false)
2520 let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
2522 iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
2523 .flat_map(|g| &g.params)
2524 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2525 .map(|p| p.name.as_str())
2526 .collect::<Vec<_>>();
2528 .find(|candidate| !lts_names.contains(&&candidate[..]))
2529 .unwrap_or("'lt".to_string())
2532 let add_lt_sugg = generics
2535 .and_then(|param| param.def_id.as_local())
2536 .map(|def_id| (self.tcx.def_span(def_id).shrink_to_lo(), format!("{}, ", new_lt)));
2538 let labeled_user_string = match bound_kind {
2539 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2540 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
2541 GenericKind::Opaque(def_id, substs) => {
2542 format!("the opaque type `{}`", self.tcx.def_path_str_with_substs(def_id, substs))
2546 if let Some(SubregionOrigin::CompareImplItemObligation {
2552 return self.report_extra_impl_obligation(
2556 &format!("`{}: {}`", bound_kind, sub),
2560 fn binding_suggestion<'tcx, S: fmt::Display>(
2561 err: &mut Diagnostic,
2562 type_param_span: Option<(Span, bool)>,
2563 bound_kind: GenericKind<'tcx>,
2565 add_lt_sugg: Option<(Span, String)>,
2567 let msg = "consider adding an explicit lifetime bound";
2568 if let Some((sp, has_lifetimes)) = type_param_span {
2570 if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) };
2571 let mut suggestions = vec![(sp, suggestion)];
2572 if let Some(add_lt_sugg) = add_lt_sugg {
2573 suggestions.push(add_lt_sugg);
2575 err.multipart_suggestion_verbose(
2576 format!("{msg}..."),
2578 Applicability::MaybeIncorrect, // Issue #41966
2581 let consider = format!("{} `{}: {}`...", msg, bound_kind, sub);
2582 err.help(&consider);
2586 let new_binding_suggestion =
2587 |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| {
2588 let msg = "consider introducing an explicit lifetime bound";
2589 if let Some((sp, has_lifetimes)) = type_param_span {
2590 let suggestion = if has_lifetimes {
2591 format!(" + {}", new_lt)
2593 format!(": {}", new_lt)
2596 vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {}", new_lt))];
2597 if let Some(lt) = add_lt_sugg.clone() {
2599 sugg.rotate_right(1);
2601 // `MaybeIncorrect` due to issue #41966.
2602 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2607 enum SubOrigin<'hir> {
2608 GAT(&'hir hir::Generics<'hir>),
2614 let sub_origin = 'origin: {
2616 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
2617 let node = self.tcx.hir().get_if_local(def_id).unwrap();
2619 Node::GenericParam(param) => {
2620 for h in self.tcx.hir().parent_iter(param.hir_id) {
2621 break 'origin match h.1 {
2622 Node::ImplItem(hir::ImplItem {
2623 kind: hir::ImplItemKind::Type(..),
2627 | Node::TraitItem(hir::TraitItem {
2628 kind: hir::TraitItemKind::Type(..),
2631 }) => SubOrigin::GAT(generics),
2632 Node::ImplItem(hir::ImplItem {
2633 kind: hir::ImplItemKind::Fn(..),
2636 | Node::TraitItem(hir::TraitItem {
2637 kind: hir::TraitItemKind::Fn(..),
2640 | Node::Item(hir::Item {
2641 kind: hir::ItemKind::Fn(..), ..
2642 }) => SubOrigin::Fn,
2643 Node::Item(hir::Item {
2644 kind: hir::ItemKind::Trait(..),
2646 }) => SubOrigin::Trait,
2647 Node::Item(hir::Item {
2648 kind: hir::ItemKind::Impl(..), ..
2649 }) => SubOrigin::Impl,
2661 debug!(?sub_origin);
2663 let mut err = match (*sub, sub_origin) {
2664 // In the case of GATs, we have to be careful. If we a type parameter `T` on an impl,
2665 // but a lifetime `'a` on an associated type, then we might need to suggest adding
2666 // `where T: 'a`. Importantly, this is on the GAT span, not on the `T` declaration.
2667 (ty::ReEarlyBound(ty::EarlyBoundRegion { name: _, .. }), SubOrigin::GAT(generics)) => {
2668 // Does the required lifetime have a nice name we can print?
2669 let mut err = struct_span_err!(
2673 "{} may not live long enough",
2676 let pred = format!("{}: {}", bound_kind, sub);
2677 let suggestion = format!("{} {}", generics.add_where_or_trailing_comma(), pred,);
2678 err.span_suggestion(
2679 generics.tail_span_for_predicate_suggestion(),
2680 "consider adding a where clause",
2682 Applicability::MaybeIncorrect,
2687 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2688 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }),
2690 ) if name != kw::UnderscoreLifetime => {
2691 // Does the required lifetime have a nice name we can print?
2692 let mut err = struct_span_err!(
2696 "{} may not live long enough",
2699 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2700 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2701 // uses `Debug` output, so we handle it specially here so that suggestions are
2703 binding_suggestion(&mut err, type_param_span, bound_kind, name, None);
2707 (ty::ReStatic, _) => {
2708 // Does the required lifetime have a nice name we can print?
2709 let mut err = struct_span_err!(
2713 "{} may not live long enough",
2716 binding_suggestion(&mut err, type_param_span, bound_kind, "'static", None);
2721 // If not, be less specific.
2722 let mut err = struct_span_err!(
2726 "{} may not live long enough",
2729 note_and_explain_region(
2732 &format!("{} must be valid for ", labeled_user_string),
2737 if let Some(infer::RelateParamBound(_, t, _)) = origin {
2738 let return_impl_trait =
2739 self.tcx.return_type_impl_trait(generic_param_scope).is_some();
2740 let t = self.resolve_vars_if_possible(t);
2743 // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2745 // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2746 ty::Closure(_, _substs) | ty::Opaque(_, _substs) if return_impl_trait => {
2747 new_binding_suggestion(&mut err, type_param_span);
2764 if let Some(origin) = origin {
2765 self.note_region_origin(&mut err, &origin);
2770 fn report_sub_sup_conflict(
2772 var_origin: RegionVariableOrigin,
2773 sub_origin: SubregionOrigin<'tcx>,
2774 sub_region: Region<'tcx>,
2775 sup_origin: SubregionOrigin<'tcx>,
2776 sup_region: Region<'tcx>,
2778 let mut err = self.report_inference_failure(var_origin);
2780 note_and_explain_region(
2783 "first, the lifetime cannot outlive ",
2789 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2790 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2791 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2792 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2793 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2795 if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2796 (&sup_origin, &sub_origin)
2798 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
2799 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
2800 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
2801 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
2803 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2804 (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
2806 if sub_expected == sup_expected && sub_found == sup_found {
2807 note_and_explain_region(
2810 "...but the lifetime must also be valid for ",
2816 sup_trace.cause.span,
2817 &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2820 err.note_expected_found(&"", sup_expected, &"", sup_found);
2827 self.note_region_origin(&mut err, &sup_origin);
2829 note_and_explain_region(
2832 "but, the lifetime must be valid for ",
2838 self.note_region_origin(&mut err, &sub_origin);
2842 /// Determine whether an error associated with the given span and definition
2843 /// should be treated as being caused by the implicit `From` conversion
2844 /// within `?` desugaring.
2845 pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2846 span.is_desugaring(DesugaringKind::QuestionMark)
2847 && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2850 /// Structurally compares two types, modulo any inference variables.
2852 /// Returns `true` if two types are equal, or if one type is an inference variable compatible
2853 /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
2854 /// FloatVar inference type are compatible with themselves or their concrete types (Int and
2855 /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
2856 pub fn same_type_modulo_infer(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
2857 let (a, b) = self.resolve_vars_if_possible((a, b));
2858 SameTypeModuloInfer(self).relate(a, b).is_ok()
2862 struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>);
2864 impl<'tcx> TypeRelation<'tcx> for SameTypeModuloInfer<'_, 'tcx> {
2865 fn tcx(&self) -> TyCtxt<'tcx> {
2869 fn param_env(&self) -> ty::ParamEnv<'tcx> {
2870 // Unused, only for consts which we treat as always equal
2871 ty::ParamEnv::empty()
2874 fn tag(&self) -> &'static str {
2875 "SameTypeModuloInfer"
2878 fn a_is_expected(&self) -> bool {
2882 fn relate_with_variance<T: relate::Relate<'tcx>>(
2884 _variance: ty::Variance,
2885 _info: ty::VarianceDiagInfo<'tcx>,
2888 ) -> relate::RelateResult<'tcx, T> {
2892 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
2893 match (a.kind(), b.kind()) {
2894 (ty::Int(_) | ty::Uint(_), ty::Infer(ty::InferTy::IntVar(_)))
2896 ty::Infer(ty::InferTy::IntVar(_)),
2897 ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2899 | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2901 ty::Infer(ty::InferTy::FloatVar(_)),
2902 ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2904 | (ty::Infer(ty::InferTy::TyVar(_)), _)
2905 | (_, ty::Infer(ty::InferTy::TyVar(_))) => Ok(a),
2906 (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Mismatch),
2907 _ => relate::super_relate_tys(self, a, b),
2913 a: ty::Region<'tcx>,
2914 b: ty::Region<'tcx>,
2915 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
2916 if (a.is_var() && b.is_free_or_static())
2917 || (b.is_var() && a.is_free_or_static())
2918 || (a.is_var() && b.is_var())
2923 Err(TypeError::Mismatch)
2929 a: ty::Binder<'tcx, T>,
2930 b: ty::Binder<'tcx, T>,
2931 ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2933 T: relate::Relate<'tcx>,
2935 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2941 _b: ty::Const<'tcx>,
2942 ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2943 // FIXME(compiler-errors): This could at least do some first-order
2949 impl<'tcx> InferCtxt<'tcx> {
2950 fn report_inference_failure(
2952 var_origin: RegionVariableOrigin,
2953 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2954 let br_string = |br: ty::BoundRegionKind| {
2955 let mut s = match br {
2956 ty::BrNamed(_, name) => name.to_string(),
2964 let var_description = match var_origin {
2965 infer::MiscVariable(_) => String::new(),
2966 infer::PatternRegion(_) => " for pattern".to_string(),
2967 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2968 infer::Autoref(_) => " for autoref".to_string(),
2969 infer::Coercion(_) => " for automatic coercion".to_string(),
2970 infer::LateBoundRegion(_, br, infer::FnCall) => {
2971 format!(" for lifetime parameter {}in function call", br_string(br))
2973 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2974 format!(" for lifetime parameter {}in generic type", br_string(br))
2976 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2977 " for lifetime parameter {}in trait containing associated type `{}`",
2979 self.tcx.associated_item(def_id).name
2981 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2982 infer::UpvarRegion(ref upvar_id, _) => {
2983 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2984 format!(" for capture of `{}` by closure", var_name)
2986 infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2993 "cannot infer an appropriate lifetime{} due to conflicting requirements",
2999 pub enum FailureCode {
3001 Error0317(&'static str),
3002 Error0580(&'static str),
3003 Error0308(&'static str),
3004 Error0644(&'static str),
3007 pub trait ObligationCauseExt<'tcx> {
3008 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode;
3009 fn as_requirement_str(&self) -> &'static str;
3012 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
3013 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
3014 use self::FailureCode::*;
3015 use crate::traits::ObligationCauseCode::*;
3017 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
3018 Error0308("method not compatible with trait")
3020 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
3021 Error0308("type not compatible with trait")
3023 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
3024 Error0308("const not compatible with trait")
3026 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
3027 Error0308(match source {
3028 hir::MatchSource::TryDesugar => "`?` operator has incompatible types",
3029 _ => "`match` arms have incompatible types",
3032 IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
3033 IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
3034 LetElse => Error0308("`else` clause of `let...else` does not diverge"),
3035 MainFunctionType => Error0580("`main` function has wrong type"),
3036 StartFunctionType => Error0308("`#[start]` function has wrong type"),
3037 IntrinsicType => Error0308("intrinsic has wrong type"),
3038 MethodReceiver => Error0308("mismatched `self` parameter type"),
3040 // In the case where we have no more specific thing to
3041 // say, also take a look at the error code, maybe we can
3044 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
3045 Error0644("closure/generator type that references itself")
3047 TypeError::IntrinsicCast => {
3048 Error0308("cannot coerce intrinsics to function pointers")
3050 TypeError::ObjectUnsafeCoercion(did) => Error0038(did),
3051 _ => Error0308("mismatched types"),
3056 fn as_requirement_str(&self) -> &'static str {
3057 use crate::traits::ObligationCauseCode::*;
3059 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
3060 "method type is compatible with trait"
3062 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
3063 "associated type is compatible with trait"
3065 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
3066 "const is compatible with trait"
3068 ExprAssignable => "expression is assignable",
3069 IfExpression { .. } => "`if` and `else` have incompatible types",
3070 IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
3071 MainFunctionType => "`main` function has the correct type",
3072 StartFunctionType => "`#[start]` function has the correct type",
3073 IntrinsicType => "intrinsic has the correct type",
3074 MethodReceiver => "method receiver has the correct type",
3075 _ => "types are compatible",
3080 /// Newtype to allow implementing IntoDiagnosticArg
3081 pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
3083 impl IntoDiagnosticArg for ObligationCauseAsDiagArg<'_> {
3084 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
3085 use crate::traits::ObligationCauseCode::*;
3086 let kind = match self.0.code() {
3087 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => "method_compat",
3088 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => "type_compat",
3089 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => "const_compat",
3090 ExprAssignable => "expr_assignable",
3091 IfExpression { .. } => "if_else_different",
3092 IfExpressionWithNoElse => "no_else",
3093 MainFunctionType => "fn_main_correct_type",
3094 StartFunctionType => "fn_start_correct_type",
3095 IntrinsicType => "intristic_correct_type",
3096 MethodReceiver => "method_correct_type",
3100 rustc_errors::DiagnosticArgValue::Str(kind)
3104 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
3105 /// extra information about each type, but we only care about the category.
3106 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
3107 pub enum TyCategory {
3110 Generator(hir::GeneratorKind),
3115 fn descr(&self) -> &'static str {
3117 Self::Closure => "closure",
3118 Self::Opaque => "opaque type",
3119 Self::Generator(gk) => gk.descr(),
3120 Self::Foreign => "foreign type",
3124 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
3126 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
3127 ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
3128 ty::Generator(def_id, ..) => {
3129 Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
3131 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
3137 impl<'tcx> InferCtxt<'tcx> {
3138 /// Given a [`hir::Block`], get the span of its last expression or
3139 /// statement, peeling off any inner blocks.
3140 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
3141 let block = block.innermost_block();
3142 if let Some(expr) = &block.expr {
3144 } else if let Some(stmt) = block.stmts.last() {
3145 // possibly incorrect trailing `;` in the else arm
3148 // empty block; point at its entirety
3153 /// Given a [`hir::HirId`] for a block, get the span of its last expression
3154 /// or statement, peeling off any inner blocks.
3155 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
3156 match self.tcx.hir().get(hir_id) {
3157 hir::Node::Block(blk) => self.find_block_span(blk),
3158 // The parser was in a weird state if either of these happen, but
3159 // it's better not to panic.
3160 hir::Node::Expr(e) => e.span,
3161 _ => rustc_span::DUMMY_SP,
3166 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
3167 /// Be helpful when the user wrote `{... expr; }` and taking the `;` off
3168 /// is enough to fix the error.
3169 pub fn could_remove_semicolon(
3171 blk: &'tcx hir::Block<'tcx>,
3172 expected_ty: Ty<'tcx>,
3173 ) -> Option<(Span, StatementAsExpression)> {
3174 let blk = blk.innermost_block();
3175 // Do not suggest if we have a tail expr.
3176 if blk.expr.is_some() {
3179 let last_stmt = blk.stmts.last()?;
3180 let hir::StmtKind::Semi(ref last_expr) = last_stmt.kind else {
3183 let last_expr_ty = self.typeck_results.as_ref()?.expr_ty_opt(*last_expr)?;
3184 let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) {
3185 _ if last_expr_ty.references_error() => return None,
3186 _ if self.same_type_modulo_infer(last_expr_ty, expected_ty) => {
3187 StatementAsExpression::CorrectType
3189 (ty::Opaque(last_def_id, _), ty::Opaque(exp_def_id, _))
3190 if last_def_id == exp_def_id =>
3192 StatementAsExpression::CorrectType
3194 (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => {
3196 "both opaque, likely future {:?} {:?} {:?} {:?}",
3197 last_def_id, last_bounds, exp_def_id, exp_bounds
3200 let last_local_id = last_def_id.as_local()?;
3201 let exp_local_id = exp_def_id.as_local()?;
3204 &self.tcx.hir().expect_item(last_local_id).kind,
3205 &self.tcx.hir().expect_item(exp_local_id).kind,
3208 hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: last_bounds, .. }),
3209 hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: exp_bounds, .. }),
3210 ) if iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| {
3211 match (left, right) {
3213 hir::GenericBound::Trait(tl, ml),
3214 hir::GenericBound::Trait(tr, mr),
3215 ) if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
3221 hir::GenericBound::LangItemTrait(langl, _, _, argsl),
3222 hir::GenericBound::LangItemTrait(langr, _, _, argsr),
3223 ) if langl == langr => {
3224 // FIXME: consider the bounds!
3225 debug!("{:?} {:?}", argsl, argsr);
3232 StatementAsExpression::NeedsBoxing
3234 _ => StatementAsExpression::CorrectType,
3239 let span = if last_stmt.span.from_expansion() {
3240 let mac_call = rustc_span::source_map::original_sp(last_stmt.span, blk.span);
3241 self.tcx.sess.source_map().mac_call_stmt_semi_span(mac_call)?
3243 last_stmt.span.with_lo(last_stmt.span.hi() - BytePos(1))
3245 Some((span, needs_box))
3248 /// Suggest returning a local binding with a compatible type if the block
3249 /// has no return expression.
3250 pub fn consider_returning_binding(
3252 blk: &'tcx hir::Block<'tcx>,
3253 expected_ty: Ty<'tcx>,
3254 err: &mut Diagnostic,
3256 let blk = blk.innermost_block();
3257 // Do not suggest if we have a tail expr.
3258 if blk.expr.is_some() {
3261 let mut shadowed = FxIndexSet::default();
3262 let mut candidate_idents = vec![];
3263 let mut find_compatible_candidates = |pat: &hir::Pat<'_>| {
3264 if let hir::PatKind::Binding(_, hir_id, ident, _) = &pat.kind
3265 && let Some(pat_ty) = self
3268 .and_then(|typeck_results| typeck_results.node_type_opt(*hir_id))
3270 let pat_ty = self.resolve_vars_if_possible(pat_ty);
3271 if self.same_type_modulo_infer(pat_ty, expected_ty)
3272 && !(pat_ty, expected_ty).references_error()
3273 && shadowed.insert(ident.name)
3275 candidate_idents.push((*ident, pat_ty));
3281 let hir = self.tcx.hir();
3282 for stmt in blk.stmts.iter().rev() {
3283 let hir::StmtKind::Local(local) = &stmt.kind else { continue; };
3284 local.pat.walk(&mut find_compatible_candidates);
3286 match hir.find(hir.get_parent_node(blk.hir_id)) {
3287 Some(hir::Node::Expr(hir::Expr { hir_id, .. })) => {
3288 match hir.find(hir.get_parent_node(*hir_id)) {
3289 Some(hir::Node::Arm(hir::Arm { pat, .. })) => {
3290 pat.walk(&mut find_compatible_candidates);
3293 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body), .. })
3294 | hir::Node::ImplItem(hir::ImplItem {
3295 kind: hir::ImplItemKind::Fn(_, body),
3298 | hir::Node::TraitItem(hir::TraitItem {
3299 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body)),
3302 | hir::Node::Expr(hir::Expr {
3303 kind: hir::ExprKind::Closure(hir::Closure { body, .. }),
3307 for param in hir.body(*body).params {
3308 param.pat.walk(&mut find_compatible_candidates);
3311 Some(hir::Node::Expr(hir::Expr {
3314 hir::Expr { kind: hir::ExprKind::Let(let_), .. },
3319 })) if then_block.hir_id == *hir_id => {
3320 let_.pat.walk(&mut find_compatible_candidates);
3328 match &candidate_idents[..] {
3330 let sm = self.tcx.sess.source_map();
3331 if let Some(stmt) = blk.stmts.last() {
3332 let stmt_span = sm.stmt_span(stmt.span, blk.span);
3333 let sugg = if sm.is_multiline(blk.span)
3334 && let Some(spacing) = sm.indentation_before(stmt_span)
3336 format!("\n{spacing}{ident}")
3340 err.span_suggestion_verbose(
3341 stmt_span.shrink_to_hi(),
3342 format!("consider returning the local binding `{ident}`"),
3344 Applicability::MaybeIncorrect,
3347 let sugg = if sm.is_multiline(blk.span)
3348 && let Some(spacing) = sm.indentation_before(blk.span.shrink_to_lo())
3350 format!("\n{spacing} {ident}\n{spacing}")
3352 format!(" {ident} ")
3354 let left_span = sm.span_through_char(blk.span, '{').shrink_to_hi();
3355 err.span_suggestion_verbose(
3356 sm.span_extend_while(left_span, |c| c.is_whitespace()).unwrap_or(left_span),
3357 format!("consider returning the local binding `{ident}`"),
3359 Applicability::MaybeIncorrect,
3364 values if (1..3).contains(&values.len()) => {
3365 let spans = values.iter().map(|(ident, _)| ident.span).collect::<Vec<_>>();
3366 err.span_note(spans, "consider returning one of these bindings");