summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_infer/src/infer/error_reporting
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
commit698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch)
tree173a775858bd501c378080a10dca74132f05bc50 /compiler/rustc_infer/src/infer/error_reporting
parentInitial commit. (diff)
downloadrustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz
rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'compiler/rustc_infer/src/infer/error_reporting')
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/mod.rs3121
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs1134
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs234
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs234
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs102
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mod.rs77
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs116
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs501
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs577
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs176
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs167
-rw-r--r--compiler/rustc_infer/src/infer/error_reporting/note.rs414
12 files changed, 6853 insertions, 0 deletions
diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs
new file mode 100644
index 000000000..20864c657
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs
@@ -0,0 +1,3121 @@
+//! Error Reporting Code for the inference engine
+//!
+//! Because of the way inference, and in particular region inference,
+//! works, it often happens that errors are not detected until far after
+//! the relevant line of code has been type-checked. Therefore, there is
+//! an elaborate system to track why a particular constraint in the
+//! inference graph arose so that we can explain to the user what gave
+//! rise to a particular error.
+//!
+//! The system is based around a set of "origin" types. An "origin" is the
+//! reason that a constraint or inference variable arose. There are
+//! different "origin" enums for different kinds of constraints/variables
+//! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
+//! a span, but also more information so that we can generate a meaningful
+//! error message.
+//!
+//! Having a catalog of all the different reasons an error can arise is
+//! also useful for other reasons, like cross-referencing FAQs etc, though
+//! we are not really taking advantage of this yet.
+//!
+//! # Region Inference
+//!
+//! Region inference is particularly tricky because it always succeeds "in
+//! the moment" and simply registers a constraint. Then, at the end, we
+//! can compute the full graph and report errors, so we need to be able to
+//! store and later report what gave rise to the conflicting constraints.
+//!
+//! # Subtype Trace
+//!
+//! Determining whether `T1 <: T2` often involves a number of subtypes and
+//! subconstraints along the way. A "TypeTrace" is an extended version
+//! of an origin that traces the types and other values that were being
+//! compared. It is not necessarily comprehensive (in fact, at the time of
+//! this writing it only tracks the root values being compared) but I'd
+//! like to extend it to include significant "waypoints". For example, if
+//! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
+//! <: T4` fails, I'd like the trace to include enough information to say
+//! "in the 2nd element of the tuple". Similarly, failures when comparing
+//! arguments or return types in fn types should be able to cite the
+//! specific position, etc.
+//!
+//! # Reality vs plan
+//!
+//! Of course, there is still a LOT of code in typeck that has yet to be
+//! ported to this system, and which relies on string concatenation at the
+//! time of error detection.
+
+use super::lexical_region_resolve::RegionResolutionError;
+use super::region_constraints::GenericKind;
+use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
+
+use crate::infer;
+use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
+use crate::traits::error_reporting::report_object_safety_error;
+use crate::traits::{
+ IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
+ StatementAsExpression,
+};
+
+use rustc_data_structures::fx::{FxHashMap, FxHashSet};
+use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed};
+use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString, MultiSpan};
+use rustc_hir as hir;
+use rustc_hir::def_id::{DefId, LocalDefId};
+use rustc_hir::lang_items::LangItem;
+use rustc_hir::Node;
+use rustc_middle::dep_graph::DepContext;
+use rustc_middle::ty::print::with_no_trimmed_paths;
+use rustc_middle::ty::{
+ self, error::TypeError, Binder, List, Region, Subst, Ty, TyCtxt, TypeFoldable,
+ TypeSuperVisitable, TypeVisitable,
+};
+use rustc_span::{sym, symbol::kw, BytePos, DesugaringKind, Pos, Span};
+use rustc_target::spec::abi;
+use std::ops::ControlFlow;
+use std::{cmp, fmt, iter};
+
+mod note;
+
+mod need_type_info;
+pub use need_type_info::TypeAnnotationNeeded;
+
+pub mod nice_region_error;
+
+pub(super) fn note_and_explain_region<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ err: &mut Diagnostic,
+ prefix: &str,
+ region: ty::Region<'tcx>,
+ suffix: &str,
+ alt_span: Option<Span>,
+) {
+ let (description, span) = match *region {
+ ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
+ msg_span_from_free_region(tcx, region, alt_span)
+ }
+
+ ty::ReEmpty(ty::UniverseIndex::ROOT) => ("the empty lifetime".to_owned(), alt_span),
+
+ // uh oh, hope no user ever sees THIS
+ ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), alt_span),
+
+ ty::RePlaceholder(_) => return,
+
+ // FIXME(#13998) RePlaceholder should probably print like
+ // ReFree rather than dumping Debug output on the user.
+ //
+ // We shouldn't really be having unification failures with ReVar
+ // and ReLateBound though.
+ ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
+ (format!("lifetime {:?}", region), alt_span)
+ }
+ };
+
+ emit_msg_span(err, prefix, description, span, suffix);
+}
+
+fn explain_free_region<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ err: &mut Diagnostic,
+ prefix: &str,
+ region: ty::Region<'tcx>,
+ suffix: &str,
+) {
+ let (description, span) = msg_span_from_free_region(tcx, region, None);
+
+ label_msg_span(err, prefix, description, span, suffix);
+}
+
+fn msg_span_from_free_region<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ region: ty::Region<'tcx>,
+ alt_span: Option<Span>,
+) -> (String, Option<Span>) {
+ match *region {
+ ty::ReEarlyBound(_) | ty::ReFree(_) => {
+ let (msg, span) = msg_span_from_early_bound_and_free_regions(tcx, region);
+ (msg, Some(span))
+ }
+ ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
+ ty::ReEmpty(ty::UniverseIndex::ROOT) => ("an empty lifetime".to_owned(), alt_span),
+ ty::ReEmpty(ui) => (format!("an empty lifetime in universe {:?}", ui), alt_span),
+ _ => bug!("{:?}", region),
+ }
+}
+
+fn msg_span_from_early_bound_and_free_regions<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ region: ty::Region<'tcx>,
+) -> (String, Span) {
+ let scope = region.free_region_binding_scope(tcx).expect_local();
+ match *region {
+ ty::ReEarlyBound(ref br) => {
+ let mut sp = tcx.def_span(scope);
+ if let Some(param) =
+ tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
+ {
+ sp = param.span;
+ }
+ let text = if br.has_name() {
+ format!("the lifetime `{}` as defined here", br.name)
+ } else {
+ format!("the anonymous lifetime as defined here")
+ };
+ (text, sp)
+ }
+ ty::ReFree(ref fr) => {
+ if !fr.bound_region.is_named()
+ && let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region)
+ {
+ ("the anonymous lifetime defined here".to_string(), ty.span)
+ } else {
+ match fr.bound_region {
+ ty::BoundRegionKind::BrNamed(_, name) => {
+ let mut sp = tcx.def_span(scope);
+ if let Some(param) =
+ tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
+ {
+ sp = param.span;
+ }
+ let text = if name == kw::UnderscoreLifetime {
+ format!("the anonymous lifetime as defined here")
+ } else {
+ format!("the lifetime `{}` as defined here", name)
+ };
+ (text, sp)
+ }
+ ty::BrAnon(idx) => (
+ format!("the anonymous lifetime #{} defined here", idx + 1),
+ tcx.def_span(scope)
+ ),
+ _ => (
+ format!("the lifetime `{}` as defined here", region),
+ tcx.def_span(scope),
+ ),
+ }
+ }
+ }
+ _ => bug!(),
+ }
+}
+
+fn emit_msg_span(
+ err: &mut Diagnostic,
+ prefix: &str,
+ description: String,
+ span: Option<Span>,
+ suffix: &str,
+) {
+ let message = format!("{}{}{}", prefix, description, suffix);
+
+ if let Some(span) = span {
+ err.span_note(span, &message);
+ } else {
+ err.note(&message);
+ }
+}
+
+fn label_msg_span(
+ err: &mut Diagnostic,
+ prefix: &str,
+ description: String,
+ span: Option<Span>,
+ suffix: &str,
+) {
+ let message = format!("{}{}{}", prefix, description, suffix);
+
+ if let Some(span) = span {
+ err.span_label(span, &message);
+ } else {
+ err.note(&message);
+ }
+}
+
+pub fn unexpected_hidden_region_diagnostic<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ span: Span,
+ hidden_ty: Ty<'tcx>,
+ hidden_region: ty::Region<'tcx>,
+ opaque_ty: ty::OpaqueTypeKey<'tcx>,
+) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ let opaque_ty = tcx.mk_opaque(opaque_ty.def_id.to_def_id(), opaque_ty.substs);
+ let mut err = struct_span_err!(
+ tcx.sess,
+ span,
+ E0700,
+ "hidden type for `{opaque_ty}` captures lifetime that does not appear in bounds",
+ );
+
+ // Explain the region we are capturing.
+ match *hidden_region {
+ ty::ReEmpty(ty::UniverseIndex::ROOT) => {
+ // All lifetimes shorter than the function body are `empty` in
+ // lexical region resolution. The default explanation of "an empty
+ // lifetime" isn't really accurate here.
+ let message = format!(
+ "hidden type `{}` captures lifetime smaller than the function body",
+ hidden_ty
+ );
+ err.span_note(span, &message);
+ }
+ ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty(_) => {
+ // Assuming regionck succeeded (*), we ought to always be
+ // capturing *some* region from the fn header, and hence it
+ // ought to be free. So under normal circumstances, we will go
+ // down this path which gives a decent human readable
+ // explanation.
+ //
+ // (*) if not, the `tainted_by_errors` field would be set to
+ // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
+ explain_free_region(
+ tcx,
+ &mut err,
+ &format!("hidden type `{}` captures ", hidden_ty),
+ hidden_region,
+ "",
+ );
+ if let Some(reg_info) = tcx.is_suitable_region(hidden_region) {
+ let fn_returns = tcx.return_type_impl_or_dyn_traits(reg_info.def_id);
+ nice_region_error::suggest_new_region_bound(
+ tcx,
+ &mut err,
+ fn_returns,
+ hidden_region.to_string(),
+ None,
+ format!("captures `{}`", hidden_region),
+ None,
+ )
+ }
+ }
+ _ => {
+ // Ugh. This is a painful case: the hidden region is not one
+ // that we can easily summarize or explain. This can happen
+ // in a case like
+ // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
+ //
+ // ```
+ // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
+ // if condition() { a } else { b }
+ // }
+ // ```
+ //
+ // Here the captured lifetime is the intersection of `'a` and
+ // `'b`, which we can't quite express.
+
+ // We can at least report a really cryptic error for now.
+ note_and_explain_region(
+ tcx,
+ &mut err,
+ &format!("hidden type `{}` captures ", hidden_ty),
+ hidden_region,
+ "",
+ None,
+ );
+ }
+ }
+
+ err
+}
+
+impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
+ pub fn report_region_errors(
+ &self,
+ generic_param_scope: LocalDefId,
+ errors: &[RegionResolutionError<'tcx>],
+ ) {
+ debug!("report_region_errors(): {} errors to start", errors.len());
+
+ // try to pre-process the errors, which will group some of them
+ // together into a `ProcessedErrors` group:
+ let errors = self.process_errors(errors);
+
+ debug!("report_region_errors: {} errors after preprocessing", errors.len());
+
+ for error in errors {
+ debug!("report_region_errors: error = {:?}", error);
+
+ if !self.try_report_nice_region_error(&error) {
+ match error.clone() {
+ // These errors could indicate all manner of different
+ // problems with many different solutions. Rather
+ // than generate a "one size fits all" error, what we
+ // attempt to do is go through a number of specific
+ // scenarios and try to find the best way to present
+ // the error. If all of these fails, we fall back to a rather
+ // general bit of code that displays the error information
+ RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
+ if sub.is_placeholder() || sup.is_placeholder() {
+ self.report_placeholder_failure(origin, sub, sup).emit();
+ } else {
+ self.report_concrete_failure(origin, sub, sup).emit();
+ }
+ }
+
+ RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
+ self.report_generic_bound_failure(
+ generic_param_scope,
+ origin.span(),
+ Some(origin),
+ param_ty,
+ sub,
+ );
+ }
+
+ RegionResolutionError::SubSupConflict(
+ _,
+ var_origin,
+ sub_origin,
+ sub_r,
+ sup_origin,
+ sup_r,
+ _,
+ ) => {
+ if sub_r.is_placeholder() {
+ self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
+ } else if sup_r.is_placeholder() {
+ self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
+ } else {
+ self.report_sub_sup_conflict(
+ var_origin, sub_origin, sub_r, sup_origin, sup_r,
+ );
+ }
+ }
+
+ RegionResolutionError::UpperBoundUniverseConflict(
+ _,
+ _,
+ var_universe,
+ sup_origin,
+ sup_r,
+ ) => {
+ assert!(sup_r.is_placeholder());
+
+ // Make a dummy value for the "sub region" --
+ // this is the initial value of the
+ // placeholder. In practice, we expect more
+ // tailored errors that don't really use this
+ // value.
+ let sub_r = self.tcx.mk_region(ty::ReEmpty(var_universe));
+
+ self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
+ }
+ }
+ }
+ }
+ }
+
+ // This method goes through all the errors and try to group certain types
+ // of error together, for the purpose of suggesting explicit lifetime
+ // parameters to the user. This is done so that we can have a more
+ // complete view of what lifetimes should be the same.
+ // If the return value is an empty vector, it means that processing
+ // failed (so the return value of this method should not be used).
+ //
+ // The method also attempts to weed out messages that seem like
+ // duplicates that will be unhelpful to the end-user. But
+ // obviously it never weeds out ALL errors.
+ fn process_errors(
+ &self,
+ errors: &[RegionResolutionError<'tcx>],
+ ) -> Vec<RegionResolutionError<'tcx>> {
+ debug!("process_errors()");
+
+ // We want to avoid reporting generic-bound failures if we can
+ // avoid it: these have a very high rate of being unhelpful in
+ // practice. This is because they are basically secondary
+ // checks that test the state of the region graph after the
+ // rest of inference is done, and the other kinds of errors
+ // indicate that the region constraint graph is internally
+ // inconsistent, so these test results are likely to be
+ // meaningless.
+ //
+ // Therefore, we filter them out of the list unless they are
+ // the only thing in the list.
+
+ let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
+ RegionResolutionError::GenericBoundFailure(..) => true,
+ RegionResolutionError::ConcreteFailure(..)
+ | RegionResolutionError::SubSupConflict(..)
+ | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
+ };
+
+ let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
+ errors.to_owned()
+ } else {
+ errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
+ };
+
+ // sort the errors by span, for better error message stability.
+ errors.sort_by_key(|u| match *u {
+ RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
+ RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
+ RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
+ RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
+ });
+ errors
+ }
+
+ /// Adds a note if the types come from similarly named crates
+ fn check_and_note_conflicting_crates(&self, err: &mut Diagnostic, terr: &TypeError<'tcx>) {
+ use hir::def_id::CrateNum;
+ use rustc_hir::definitions::DisambiguatedDefPathData;
+ use ty::print::Printer;
+ use ty::subst::GenericArg;
+
+ struct AbsolutePathPrinter<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ }
+
+ struct NonTrivialPath;
+
+ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
+ type Error = NonTrivialPath;
+
+ type Path = Vec<String>;
+ type Region = !;
+ type Type = !;
+ type DynExistential = !;
+ type Const = !;
+
+ fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
+ self.tcx
+ }
+
+ fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
+ Err(NonTrivialPath)
+ }
+
+ fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
+ Err(NonTrivialPath)
+ }
+
+ fn print_dyn_existential(
+ self,
+ _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
+ ) -> Result<Self::DynExistential, Self::Error> {
+ Err(NonTrivialPath)
+ }
+
+ fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
+ Err(NonTrivialPath)
+ }
+
+ fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
+ Ok(vec![self.tcx.crate_name(cnum).to_string()])
+ }
+ fn path_qualified(
+ self,
+ _self_ty: Ty<'tcx>,
+ _trait_ref: Option<ty::TraitRef<'tcx>>,
+ ) -> Result<Self::Path, Self::Error> {
+ Err(NonTrivialPath)
+ }
+
+ fn path_append_impl(
+ self,
+ _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
+ _disambiguated_data: &DisambiguatedDefPathData,
+ _self_ty: Ty<'tcx>,
+ _trait_ref: Option<ty::TraitRef<'tcx>>,
+ ) -> Result<Self::Path, Self::Error> {
+ Err(NonTrivialPath)
+ }
+ fn path_append(
+ self,
+ print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
+ disambiguated_data: &DisambiguatedDefPathData,
+ ) -> Result<Self::Path, Self::Error> {
+ let mut path = print_prefix(self)?;
+ path.push(disambiguated_data.to_string());
+ Ok(path)
+ }
+ fn path_generic_args(
+ self,
+ print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
+ _args: &[GenericArg<'tcx>],
+ ) -> Result<Self::Path, Self::Error> {
+ print_prefix(self)
+ }
+ }
+
+ let report_path_match = |err: &mut Diagnostic, did1: DefId, did2: DefId| {
+ // Only external crates, if either is from a local
+ // module we could have false positives
+ if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
+ let abs_path =
+ |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
+
+ // We compare strings because DefPath can be different
+ // for imported and non-imported crates
+ let same_path = || -> Result<_, NonTrivialPath> {
+ Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
+ || abs_path(did1)? == abs_path(did2)?)
+ };
+ if same_path().unwrap_or(false) {
+ let crate_name = self.tcx.crate_name(did1.krate);
+ err.note(&format!(
+ "perhaps two different versions of crate `{}` are being used?",
+ crate_name
+ ));
+ }
+ }
+ };
+ match *terr {
+ TypeError::Sorts(ref exp_found) => {
+ // if they are both "path types", there's a chance of ambiguity
+ // due to different versions of the same crate
+ if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
+ (exp_found.expected.kind(), exp_found.found.kind())
+ {
+ report_path_match(err, exp_adt.did(), found_adt.did());
+ }
+ }
+ TypeError::Traits(ref exp_found) => {
+ report_path_match(err, exp_found.expected, exp_found.found);
+ }
+ _ => (), // FIXME(#22750) handle traits and stuff
+ }
+ }
+
+ fn note_error_origin(
+ &self,
+ err: &mut Diagnostic,
+ cause: &ObligationCause<'tcx>,
+ exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
+ terr: &TypeError<'tcx>,
+ ) {
+ match *cause.code() {
+ ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
+ let ty = self.resolve_vars_if_possible(root_ty);
+ if !matches!(ty.kind(), ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)))
+ {
+ // don't show type `_`
+ if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
+ && let ty::Adt(def, substs) = ty.kind()
+ && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
+ {
+ err.span_label(span, format!("this is an iterator with items of type `{}`", substs.type_at(0)));
+ } else {
+ err.span_label(span, format!("this expression has type `{}`", ty));
+ }
+ }
+ if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
+ && ty.is_box() && ty.boxed_ty() == found
+ && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
+ {
+ err.span_suggestion(
+ span,
+ "consider dereferencing the boxed value",
+ format!("*{}", snippet),
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+ ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
+ err.span_label(span, "expected due to this");
+ }
+ ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
+ arm_block_id,
+ arm_span,
+ arm_ty,
+ prior_arm_block_id,
+ prior_arm_span,
+ prior_arm_ty,
+ source,
+ ref prior_arms,
+ scrut_hir_id,
+ opt_suggest_box_span,
+ scrut_span,
+ ..
+ }) => match source {
+ hir::MatchSource::TryDesugar => {
+ if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
+ let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
+ let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
+ let arg_expr = args.first().expect("try desugaring call w/out arg");
+ self.in_progress_typeck_results.and_then(|typeck_results| {
+ typeck_results.borrow().expr_ty_opt(arg_expr)
+ })
+ } else {
+ bug!("try desugaring w/out call expr as scrutinee");
+ };
+
+ match scrut_ty {
+ Some(ty) if expected == ty => {
+ let source_map = self.tcx.sess.source_map();
+ err.span_suggestion(
+ source_map.end_point(cause.span),
+ "try removing this `?`",
+ "",
+ Applicability::MachineApplicable,
+ );
+ }
+ _ => {}
+ }
+ }
+ }
+ _ => {
+ // `prior_arm_ty` can be `!`, `expected` will have better info when present.
+ let t = self.resolve_vars_if_possible(match exp_found {
+ Some(ty::error::ExpectedFound { expected, .. }) => expected,
+ _ => prior_arm_ty,
+ });
+ let source_map = self.tcx.sess.source_map();
+ let mut any_multiline_arm = source_map.is_multiline(arm_span);
+ if prior_arms.len() <= 4 {
+ for sp in prior_arms {
+ any_multiline_arm |= source_map.is_multiline(*sp);
+ err.span_label(*sp, format!("this is found to be of type `{}`", t));
+ }
+ } else if let Some(sp) = prior_arms.last() {
+ any_multiline_arm |= source_map.is_multiline(*sp);
+ err.span_label(
+ *sp,
+ format!("this and all prior arms are found to be of type `{}`", t),
+ );
+ }
+ let outer_error_span = if any_multiline_arm {
+ // Cover just `match` and the scrutinee expression, not
+ // the entire match body, to reduce diagram noise.
+ cause.span.shrink_to_lo().to(scrut_span)
+ } else {
+ cause.span
+ };
+ let msg = "`match` arms have incompatible types";
+ err.span_label(outer_error_span, msg);
+ self.suggest_remove_semi_or_return_binding(
+ err,
+ prior_arm_block_id,
+ prior_arm_ty,
+ prior_arm_span,
+ arm_block_id,
+ arm_ty,
+ arm_span,
+ );
+ if let Some(ret_sp) = opt_suggest_box_span {
+ // Get return type span and point to it.
+ self.suggest_boxing_for_return_impl_trait(
+ err,
+ ret_sp,
+ prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
+ );
+ }
+ }
+ },
+ ObligationCauseCode::IfExpression(box IfExpressionCause {
+ then_id,
+ else_id,
+ then_ty,
+ else_ty,
+ outer_span,
+ opt_suggest_box_span,
+ }) => {
+ let then_span = self.find_block_span_from_hir_id(then_id);
+ let else_span = self.find_block_span_from_hir_id(else_id);
+ err.span_label(then_span, "expected because of this");
+ if let Some(sp) = outer_span {
+ err.span_label(sp, "`if` and `else` have incompatible types");
+ }
+ self.suggest_remove_semi_or_return_binding(
+ err,
+ Some(then_id),
+ then_ty,
+ then_span,
+ Some(else_id),
+ else_ty,
+ else_span,
+ );
+ if let Some(ret_sp) = opt_suggest_box_span {
+ self.suggest_boxing_for_return_impl_trait(
+ err,
+ ret_sp,
+ [then_span, else_span].into_iter(),
+ );
+ }
+ }
+ ObligationCauseCode::LetElse => {
+ err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
+ err.help("...or use `match` instead of `let...else`");
+ }
+ _ => {
+ if let ObligationCauseCode::BindingObligation(_, binding_span) =
+ cause.code().peel_derives()
+ {
+ if matches!(terr, TypeError::RegionsPlaceholderMismatch) {
+ err.span_note(*binding_span, "the lifetime requirement is introduced here");
+ }
+ }
+ }
+ }
+ }
+
+ fn suggest_remove_semi_or_return_binding(
+ &self,
+ err: &mut Diagnostic,
+ first_id: Option<hir::HirId>,
+ first_ty: Ty<'tcx>,
+ first_span: Span,
+ second_id: Option<hir::HirId>,
+ second_ty: Ty<'tcx>,
+ second_span: Span,
+ ) {
+ let remove_semicolon = [
+ (first_id, self.resolve_vars_if_possible(second_ty)),
+ (second_id, self.resolve_vars_if_possible(first_ty)),
+ ]
+ .into_iter()
+ .find_map(|(id, ty)| {
+ let hir::Node::Block(blk) = self.tcx.hir().get(id?) else { return None };
+ self.could_remove_semicolon(blk, ty)
+ });
+ match remove_semicolon {
+ Some((sp, StatementAsExpression::NeedsBoxing)) => {
+ err.multipart_suggestion(
+ "consider removing this semicolon and boxing the expressions",
+ vec![
+ (first_span.shrink_to_lo(), "Box::new(".to_string()),
+ (first_span.shrink_to_hi(), ")".to_string()),
+ (second_span.shrink_to_lo(), "Box::new(".to_string()),
+ (second_span.shrink_to_hi(), ")".to_string()),
+ (sp, String::new()),
+ ],
+ Applicability::MachineApplicable,
+ );
+ }
+ Some((sp, StatementAsExpression::CorrectType)) => {
+ err.span_suggestion_short(
+ sp,
+ "consider removing this semicolon",
+ "",
+ Applicability::MachineApplicable,
+ );
+ }
+ None => {
+ for (id, ty) in [(first_id, second_ty), (second_id, first_ty)] {
+ if let Some(id) = id
+ && let hir::Node::Block(blk) = self.tcx.hir().get(id)
+ && self.consider_returning_binding(blk, ty, err)
+ {
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ fn suggest_boxing_for_return_impl_trait(
+ &self,
+ err: &mut Diagnostic,
+ return_sp: Span,
+ arm_spans: impl Iterator<Item = Span>,
+ ) {
+ err.multipart_suggestion(
+ "you could change the return type to be a boxed trait object",
+ vec![
+ (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
+ (return_sp.shrink_to_hi(), ">".to_string()),
+ ],
+ Applicability::MaybeIncorrect,
+ );
+ let sugg = arm_spans
+ .flat_map(|sp| {
+ [(sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string())]
+ .into_iter()
+ })
+ .collect::<Vec<_>>();
+ err.multipart_suggestion(
+ "if you change the return type to expect trait objects, box the returned expressions",
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ }
+
+ /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
+ /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
+ /// populate `other_value` with `other_ty`.
+ ///
+ /// ```text
+ /// Foo<Bar<Qux>>
+ /// ^^^^--------^ this is highlighted
+ /// | |
+ /// | this type argument is exactly the same as the other type, not highlighted
+ /// this is highlighted
+ /// Bar<Qux>
+ /// -------- this type is the same as a type argument in the other type, not highlighted
+ /// ```
+ fn highlight_outer(
+ &self,
+ value: &mut DiagnosticStyledString,
+ other_value: &mut DiagnosticStyledString,
+ name: String,
+ sub: ty::subst::SubstsRef<'tcx>,
+ pos: usize,
+ other_ty: Ty<'tcx>,
+ ) {
+ // `value` and `other_value` hold two incomplete type representation for display.
+ // `name` is the path of both types being compared. `sub`
+ value.push_highlighted(name);
+ let len = sub.len();
+ if len > 0 {
+ value.push_highlighted("<");
+ }
+
+ // Output the lifetimes for the first type
+ let lifetimes = sub
+ .regions()
+ .map(|lifetime| {
+ let s = lifetime.to_string();
+ if s.is_empty() { "'_".to_string() } else { s }
+ })
+ .collect::<Vec<_>>()
+ .join(", ");
+ if !lifetimes.is_empty() {
+ if sub.regions().count() < len {
+ value.push_normal(lifetimes + ", ");
+ } else {
+ value.push_normal(lifetimes);
+ }
+ }
+
+ // Highlight all the type arguments that aren't at `pos` and compare the type argument at
+ // `pos` and `other_ty`.
+ for (i, type_arg) in sub.types().enumerate() {
+ if i == pos {
+ let values = self.cmp(type_arg, other_ty);
+ value.0.extend((values.0).0);
+ other_value.0.extend((values.1).0);
+ } else {
+ value.push_highlighted(type_arg.to_string());
+ }
+
+ if len > 0 && i != len - 1 {
+ value.push_normal(", ");
+ }
+ }
+ if len > 0 {
+ value.push_highlighted(">");
+ }
+ }
+
+ /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
+ /// as that is the difference to the other type.
+ ///
+ /// For the following code:
+ ///
+ /// ```ignore (illustrative)
+ /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
+ /// ```
+ ///
+ /// The type error output will behave in the following way:
+ ///
+ /// ```text
+ /// Foo<Bar<Qux>>
+ /// ^^^^--------^ this is highlighted
+ /// | |
+ /// | this type argument is exactly the same as the other type, not highlighted
+ /// this is highlighted
+ /// Bar<Qux>
+ /// -------- this type is the same as a type argument in the other type, not highlighted
+ /// ```
+ fn cmp_type_arg(
+ &self,
+ mut t1_out: &mut DiagnosticStyledString,
+ mut t2_out: &mut DiagnosticStyledString,
+ path: String,
+ sub: &'tcx [ty::GenericArg<'tcx>],
+ other_path: String,
+ other_ty: Ty<'tcx>,
+ ) -> Option<()> {
+ // FIXME/HACK: Go back to `SubstsRef` to use its inherent methods,
+ // ideally that shouldn't be necessary.
+ let sub = self.tcx.intern_substs(sub);
+ for (i, ta) in sub.types().enumerate() {
+ if ta == other_ty {
+ self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
+ return Some(());
+ }
+ if let ty::Adt(def, _) = ta.kind() {
+ let path_ = self.tcx.def_path_str(def.did());
+ if path_ == other_path {
+ self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
+ return Some(());
+ }
+ }
+ }
+ None
+ }
+
+ /// Adds a `,` to the type representation only if it is appropriate.
+ fn push_comma(
+ &self,
+ value: &mut DiagnosticStyledString,
+ other_value: &mut DiagnosticStyledString,
+ len: usize,
+ pos: usize,
+ ) {
+ if len > 0 && pos != len - 1 {
+ value.push_normal(", ");
+ other_value.push_normal(", ");
+ }
+ }
+
+ /// Given two `fn` signatures highlight only sub-parts that are different.
+ fn cmp_fn_sig(
+ &self,
+ sig1: &ty::PolyFnSig<'tcx>,
+ sig2: &ty::PolyFnSig<'tcx>,
+ ) -> (DiagnosticStyledString, DiagnosticStyledString) {
+ let get_lifetimes = |sig| {
+ use rustc_hir::def::Namespace;
+ let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
+ .name_all_regions(sig)
+ .unwrap();
+ let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
+ (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
+ };
+
+ let (lt1, sig1) = get_lifetimes(sig1);
+ let (lt2, sig2) = get_lifetimes(sig2);
+
+ // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
+ let mut values = (
+ DiagnosticStyledString::normal("".to_string()),
+ DiagnosticStyledString::normal("".to_string()),
+ );
+
+ // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
+ // ^^^^^^
+ values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
+ values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
+
+ // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
+ // ^^^^^^^^^^
+ if sig1.abi != abi::Abi::Rust {
+ values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
+ }
+ if sig2.abi != abi::Abi::Rust {
+ values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
+ }
+
+ // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
+ // ^^^^^^^^
+ let lifetime_diff = lt1 != lt2;
+ values.0.push(lt1, lifetime_diff);
+ values.1.push(lt2, lifetime_diff);
+
+ // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
+ // ^^^
+ values.0.push_normal("fn(");
+ values.1.push_normal("fn(");
+
+ // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
+ // ^^^^^
+ let len1 = sig1.inputs().len();
+ let len2 = sig2.inputs().len();
+ if len1 == len2 {
+ for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
+ let (x1, x2) = self.cmp(*l, *r);
+ (values.0).0.extend(x1.0);
+ (values.1).0.extend(x2.0);
+ self.push_comma(&mut values.0, &mut values.1, len1, i);
+ }
+ } else {
+ for (i, l) in sig1.inputs().iter().enumerate() {
+ values.0.push_highlighted(l.to_string());
+ if i != len1 - 1 {
+ values.0.push_highlighted(", ");
+ }
+ }
+ for (i, r) in sig2.inputs().iter().enumerate() {
+ values.1.push_highlighted(r.to_string());
+ if i != len2 - 1 {
+ values.1.push_highlighted(", ");
+ }
+ }
+ }
+
+ if sig1.c_variadic {
+ if len1 > 0 {
+ values.0.push_normal(", ");
+ }
+ values.0.push("...", !sig2.c_variadic);
+ }
+ if sig2.c_variadic {
+ if len2 > 0 {
+ values.1.push_normal(", ");
+ }
+ values.1.push("...", !sig1.c_variadic);
+ }
+
+ // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
+ // ^
+ values.0.push_normal(")");
+ values.1.push_normal(")");
+
+ // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
+ // ^^^^^^^^
+ let output1 = sig1.output();
+ let output2 = sig2.output();
+ let (x1, x2) = self.cmp(output1, output2);
+ if !output1.is_unit() {
+ values.0.push_normal(" -> ");
+ (values.0).0.extend(x1.0);
+ }
+ if !output2.is_unit() {
+ values.1.push_normal(" -> ");
+ (values.1).0.extend(x2.0);
+ }
+ values
+ }
+
+ /// Compares two given types, eliding parts that are the same between them and highlighting
+ /// relevant differences, and return two representation of those types for highlighted printing.
+ pub fn cmp(
+ &self,
+ t1: Ty<'tcx>,
+ t2: Ty<'tcx>,
+ ) -> (DiagnosticStyledString, DiagnosticStyledString) {
+ debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
+
+ // helper functions
+ fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
+ match (a.kind(), b.kind()) {
+ (a, b) if *a == *b => true,
+ (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
+ | (
+ &ty::Infer(ty::InferTy::IntVar(_)),
+ &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
+ )
+ | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
+ | (
+ &ty::Infer(ty::InferTy::FloatVar(_)),
+ &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
+ ) => true,
+ _ => false,
+ }
+ }
+
+ fn push_ty_ref<'tcx>(
+ region: ty::Region<'tcx>,
+ ty: Ty<'tcx>,
+ mutbl: hir::Mutability,
+ s: &mut DiagnosticStyledString,
+ ) {
+ let mut r = region.to_string();
+ if r == "'_" {
+ r.clear();
+ } else {
+ r.push(' ');
+ }
+ s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
+ s.push_normal(ty.to_string());
+ }
+
+ // process starts here
+ match (t1.kind(), t2.kind()) {
+ (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
+ let did1 = def1.did();
+ let did2 = def2.did();
+ let sub_no_defaults_1 =
+ self.tcx.generics_of(did1).own_substs_no_defaults(self.tcx, sub1);
+ let sub_no_defaults_2 =
+ self.tcx.generics_of(did2).own_substs_no_defaults(self.tcx, sub2);
+ let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
+ let path1 = self.tcx.def_path_str(did1);
+ let path2 = self.tcx.def_path_str(did2);
+ if did1 == did2 {
+ // Easy case. Replace same types with `_` to shorten the output and highlight
+ // the differing ones.
+ // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
+ // Foo<Bar, _>
+ // Foo<Quz, _>
+ // --- ^ type argument elided
+ // |
+ // highlighted in output
+ values.0.push_normal(path1);
+ values.1.push_normal(path2);
+
+ // Avoid printing out default generic parameters that are common to both
+ // types.
+ let len1 = sub_no_defaults_1.len();
+ let len2 = sub_no_defaults_2.len();
+ let common_len = cmp::min(len1, len2);
+ let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
+ let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
+ let common_default_params =
+ iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
+ .filter(|(a, b)| a == b)
+ .count();
+ let len = sub1.len() - common_default_params;
+ let consts_offset = len - sub1.consts().count();
+
+ // Only draw `<...>` if there are lifetime/type arguments.
+ if len > 0 {
+ values.0.push_normal("<");
+ values.1.push_normal("<");
+ }
+
+ fn lifetime_display(lifetime: Region<'_>) -> String {
+ let s = lifetime.to_string();
+ if s.is_empty() { "'_".to_string() } else { s }
+ }
+ // At one point we'd like to elide all lifetimes here, they are irrelevant for
+ // all diagnostics that use this output
+ //
+ // Foo<'x, '_, Bar>
+ // Foo<'y, '_, Qux>
+ // ^^ ^^ --- type arguments are not elided
+ // | |
+ // | elided as they were the same
+ // not elided, they were different, but irrelevant
+ //
+ // For bound lifetimes, keep the names of the lifetimes,
+ // even if they are the same so that it's clear what's happening
+ // if we have something like
+ //
+ // for<'r, 's> fn(Inv<'r>, Inv<'s>)
+ // for<'r> fn(Inv<'r>, Inv<'r>)
+ let lifetimes = sub1.regions().zip(sub2.regions());
+ for (i, lifetimes) in lifetimes.enumerate() {
+ let l1 = lifetime_display(lifetimes.0);
+ let l2 = lifetime_display(lifetimes.1);
+ if lifetimes.0 != lifetimes.1 {
+ values.0.push_highlighted(l1);
+ values.1.push_highlighted(l2);
+ } else if lifetimes.0.is_late_bound() {
+ values.0.push_normal(l1);
+ values.1.push_normal(l2);
+ } else {
+ values.0.push_normal("'_");
+ values.1.push_normal("'_");
+ }
+ self.push_comma(&mut values.0, &mut values.1, len, i);
+ }
+
+ // We're comparing two types with the same path, so we compare the type
+ // arguments for both. If they are the same, do not highlight and elide from the
+ // output.
+ // Foo<_, Bar>
+ // Foo<_, Qux>
+ // ^ elided type as this type argument was the same in both sides
+ let type_arguments = sub1.types().zip(sub2.types());
+ let regions_len = sub1.regions().count();
+ let num_display_types = consts_offset - regions_len;
+ for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
+ let i = i + regions_len;
+ if ta1 == ta2 {
+ values.0.push_normal("_");
+ values.1.push_normal("_");
+ } else {
+ let (x1, x2) = self.cmp(ta1, ta2);
+ (values.0).0.extend(x1.0);
+ (values.1).0.extend(x2.0);
+ }
+ self.push_comma(&mut values.0, &mut values.1, len, i);
+ }
+
+ // Do the same for const arguments, if they are equal, do not highlight and
+ // elide them from the output.
+ let const_arguments = sub1.consts().zip(sub2.consts());
+ for (i, (ca1, ca2)) in const_arguments.enumerate() {
+ let i = i + consts_offset;
+ if ca1 == ca2 {
+ values.0.push_normal("_");
+ values.1.push_normal("_");
+ } else {
+ values.0.push_highlighted(ca1.to_string());
+ values.1.push_highlighted(ca2.to_string());
+ }
+ self.push_comma(&mut values.0, &mut values.1, len, i);
+ }
+
+ // Close the type argument bracket.
+ // Only draw `<...>` if there are lifetime/type arguments.
+ if len > 0 {
+ values.0.push_normal(">");
+ values.1.push_normal(">");
+ }
+ values
+ } else {
+ // Check for case:
+ // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
+ // Foo<Bar<Qux>
+ // ------- this type argument is exactly the same as the other type
+ // Bar<Qux>
+ if self
+ .cmp_type_arg(
+ &mut values.0,
+ &mut values.1,
+ path1.clone(),
+ sub_no_defaults_1,
+ path2.clone(),
+ t2,
+ )
+ .is_some()
+ {
+ return values;
+ }
+ // Check for case:
+ // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
+ // Bar<Qux>
+ // Foo<Bar<Qux>>
+ // ------- this type argument is exactly the same as the other type
+ if self
+ .cmp_type_arg(
+ &mut values.1,
+ &mut values.0,
+ path2,
+ sub_no_defaults_2,
+ path1,
+ t1,
+ )
+ .is_some()
+ {
+ return values;
+ }
+
+ // We can't find anything in common, highlight relevant part of type path.
+ // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
+ // foo::bar::Baz<Qux>
+ // foo::bar::Bar<Zar>
+ // -------- this part of the path is different
+
+ let t1_str = t1.to_string();
+ let t2_str = t2.to_string();
+ let min_len = t1_str.len().min(t2_str.len());
+
+ const SEPARATOR: &str = "::";
+ let separator_len = SEPARATOR.len();
+ let split_idx: usize =
+ iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
+ .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
+ .map(|(mod_str, _)| mod_str.len() + separator_len)
+ .sum();
+
+ debug!(
+ "cmp: separator_len={}, split_idx={}, min_len={}",
+ separator_len, split_idx, min_len
+ );
+
+ if split_idx >= min_len {
+ // paths are identical, highlight everything
+ (
+ DiagnosticStyledString::highlighted(t1_str),
+ DiagnosticStyledString::highlighted(t2_str),
+ )
+ } else {
+ let (common, uniq1) = t1_str.split_at(split_idx);
+ let (_, uniq2) = t2_str.split_at(split_idx);
+ debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
+
+ values.0.push_normal(common);
+ values.0.push_highlighted(uniq1);
+ values.1.push_normal(common);
+ values.1.push_highlighted(uniq2);
+
+ values
+ }
+ }
+ }
+
+ // When finding T != &T, highlight only the borrow
+ (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(ref_ty1, t2) => {
+ let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
+ push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
+ values.1.push_normal(t2.to_string());
+ values
+ }
+ (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(t1, ref_ty2) => {
+ let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
+ values.0.push_normal(t1.to_string());
+ push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
+ values
+ }
+
+ // When encountering &T != &mut T, highlight only the borrow
+ (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
+ if equals(ref_ty1, ref_ty2) =>
+ {
+ let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
+ push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
+ push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
+ values
+ }
+
+ // When encountering tuples of the same size, highlight only the differing types
+ (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
+ let mut values =
+ (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
+ let len = substs1.len();
+ for (i, (left, right)) in substs1.iter().zip(substs2).enumerate() {
+ let (x1, x2) = self.cmp(left, right);
+ (values.0).0.extend(x1.0);
+ (values.1).0.extend(x2.0);
+ self.push_comma(&mut values.0, &mut values.1, len, i);
+ }
+ if len == 1 {
+ // Keep the output for single element tuples as `(ty,)`.
+ values.0.push_normal(",");
+ values.1.push_normal(",");
+ }
+ values.0.push_normal(")");
+ values.1.push_normal(")");
+ values
+ }
+
+ (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
+ let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
+ let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
+ let mut values = self.cmp_fn_sig(&sig1, &sig2);
+ let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
+ let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
+ let same_path = path1 == path2;
+ values.0.push(path1, !same_path);
+ values.1.push(path2, !same_path);
+ values
+ }
+
+ (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
+ let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
+ let mut values = self.cmp_fn_sig(&sig1, sig2);
+ values.0.push_highlighted(format!(
+ " {{{}}}",
+ self.tcx.def_path_str_with_substs(*did1, substs1)
+ ));
+ values
+ }
+
+ (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
+ let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
+ let mut values = self.cmp_fn_sig(sig1, &sig2);
+ values.1.push_normal(format!(
+ " {{{}}}",
+ self.tcx.def_path_str_with_substs(*did2, substs2)
+ ));
+ values
+ }
+
+ (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
+
+ _ => {
+ if t1 == t2 {
+ // The two types are the same, elide and don't highlight.
+ (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
+ } else {
+ // We couldn't find anything in common, highlight everything.
+ (
+ DiagnosticStyledString::highlighted(t1.to_string()),
+ DiagnosticStyledString::highlighted(t2.to_string()),
+ )
+ }
+ }
+ }
+ }
+
+ /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
+ /// the return type of `async fn`s.
+ ///
+ /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
+ ///
+ /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
+ /// the message in `secondary_span` as the primary label, and apply the message that would
+ /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
+ /// E0271, like `src/test/ui/issues/issue-39970.stderr`.
+ #[tracing::instrument(
+ level = "debug",
+ skip(self, diag, secondary_span, swap_secondary_and_primary, force_label)
+ )]
+ pub fn note_type_err(
+ &self,
+ diag: &mut Diagnostic,
+ cause: &ObligationCause<'tcx>,
+ secondary_span: Option<(Span, String)>,
+ mut values: Option<ValuePairs<'tcx>>,
+ terr: &TypeError<'tcx>,
+ swap_secondary_and_primary: bool,
+ force_label: bool,
+ ) {
+ let span = cause.span();
+
+ // For some types of errors, expected-found does not make
+ // sense, so just ignore the values we were given.
+ if let TypeError::CyclicTy(_) = terr {
+ values = None;
+ }
+ struct OpaqueTypesVisitor<'tcx> {
+ types: FxHashMap<TyCategory, FxHashSet<Span>>,
+ expected: FxHashMap<TyCategory, FxHashSet<Span>>,
+ found: FxHashMap<TyCategory, FxHashSet<Span>>,
+ ignore_span: Span,
+ tcx: TyCtxt<'tcx>,
+ }
+
+ impl<'tcx> OpaqueTypesVisitor<'tcx> {
+ fn visit_expected_found(
+ tcx: TyCtxt<'tcx>,
+ expected: Ty<'tcx>,
+ found: Ty<'tcx>,
+ ignore_span: Span,
+ ) -> Self {
+ let mut types_visitor = OpaqueTypesVisitor {
+ types: Default::default(),
+ expected: Default::default(),
+ found: Default::default(),
+ ignore_span,
+ tcx,
+ };
+ // The visitor puts all the relevant encountered types in `self.types`, but in
+ // here we want to visit two separate types with no relation to each other, so we
+ // move the results from `types` to `expected` or `found` as appropriate.
+ expected.visit_with(&mut types_visitor);
+ std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
+ found.visit_with(&mut types_visitor);
+ std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
+ types_visitor
+ }
+
+ fn report(&self, err: &mut Diagnostic) {
+ self.add_labels_for_types(err, "expected", &self.expected);
+ self.add_labels_for_types(err, "found", &self.found);
+ }
+
+ fn add_labels_for_types(
+ &self,
+ err: &mut Diagnostic,
+ target: &str,
+ types: &FxHashMap<TyCategory, FxHashSet<Span>>,
+ ) {
+ for (key, values) in types.iter() {
+ let count = values.len();
+ let kind = key.descr();
+ let mut returned_async_output_error = false;
+ for &sp in values {
+ if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
+ if [sp] != err.span.primary_spans() {
+ let mut span: MultiSpan = sp.into();
+ span.push_span_label(
+ sp,
+ format!(
+ "checked the `Output` of this `async fn`, {}{} {}{}",
+ if count > 1 { "one of the " } else { "" },
+ target,
+ kind,
+ pluralize!(count),
+ ),
+ );
+ err.span_note(
+ span,
+ "while checking the return type of the `async fn`",
+ );
+ } else {
+ err.span_label(
+ sp,
+ format!(
+ "checked the `Output` of this `async fn`, {}{} {}{}",
+ if count > 1 { "one of the " } else { "" },
+ target,
+ kind,
+ pluralize!(count),
+ ),
+ );
+ err.note("while checking the return type of the `async fn`");
+ }
+ returned_async_output_error = true;
+ } else {
+ err.span_label(
+ sp,
+ format!(
+ "{}{} {}{}",
+ if count == 1 { "the " } else { "one of the " },
+ target,
+ kind,
+ pluralize!(count),
+ ),
+ );
+ }
+ }
+ }
+ }
+ }
+
+ impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
+ fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
+ if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
+ let span = self.tcx.def_span(def_id);
+ // Avoid cluttering the output when the "found" and error span overlap:
+ //
+ // error[E0308]: mismatched types
+ // --> $DIR/issue-20862.rs:2:5
+ // |
+ // LL | |y| x + y
+ // | ^^^^^^^^^
+ // | |
+ // | the found closure
+ // | expected `()`, found closure
+ // |
+ // = note: expected unit type `()`
+ // found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
+ if !self.ignore_span.overlaps(span) {
+ self.types.entry(kind).or_default().insert(span);
+ }
+ }
+ t.super_visit_with(self)
+ }
+ }
+
+ debug!("note_type_err(diag={:?})", diag);
+ enum Mismatch<'a> {
+ Variable(ty::error::ExpectedFound<Ty<'a>>),
+ Fixed(&'static str),
+ }
+ let (expected_found, exp_found, is_simple_error, values) = match values {
+ None => (None, Mismatch::Fixed("type"), false, None),
+ Some(values) => {
+ let values = self.resolve_vars_if_possible(values);
+ let (is_simple_error, exp_found) = match values {
+ ValuePairs::Terms(infer::ExpectedFound {
+ expected: ty::Term::Ty(expected),
+ found: ty::Term::Ty(found),
+ }) => {
+ let is_simple_err = expected.is_simple_text() && found.is_simple_text();
+ OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
+ .report(diag);
+
+ (
+ is_simple_err,
+ Mismatch::Variable(infer::ExpectedFound { expected, found }),
+ )
+ }
+ ValuePairs::TraitRefs(_) | ValuePairs::PolyTraitRefs(_) => {
+ (false, Mismatch::Fixed("trait"))
+ }
+ _ => (false, Mismatch::Fixed("type")),
+ };
+ let vals = match self.values_str(values) {
+ Some((expected, found)) => Some((expected, found)),
+ None => {
+ // Derived error. Cancel the emitter.
+ // NOTE(eddyb) this was `.cancel()`, but `diag`
+ // is borrowed, so we can't fully defuse it.
+ diag.downgrade_to_delayed_bug();
+ return;
+ }
+ };
+ (vals, exp_found, is_simple_error, Some(values))
+ }
+ };
+
+ match terr {
+ // Ignore msg for object safe coercion
+ // since E0038 message will be printed
+ TypeError::ObjectUnsafeCoercion(_) => {}
+ _ => {
+ let mut label_or_note = |span: Span, msg: &str| {
+ if force_label || &[span] == diag.span.primary_spans() {
+ diag.span_label(span, msg);
+ } else {
+ diag.span_note(span, msg);
+ }
+ };
+ if let Some((sp, msg)) = secondary_span {
+ if swap_secondary_and_primary {
+ let terr = if let Some(infer::ValuePairs::Terms(infer::ExpectedFound {
+ expected,
+ ..
+ })) = values
+ {
+ format!("expected this to be `{}`", expected)
+ } else {
+ terr.to_string()
+ };
+ label_or_note(sp, &terr);
+ label_or_note(span, &msg);
+ } else {
+ label_or_note(span, &terr.to_string());
+ label_or_note(sp, &msg);
+ }
+ } else {
+ label_or_note(span, &terr.to_string());
+ }
+ }
+ };
+ if let Some((expected, found)) = expected_found {
+ let (expected_label, found_label, exp_found) = match exp_found {
+ Mismatch::Variable(ef) => (
+ ef.expected.prefix_string(self.tcx),
+ ef.found.prefix_string(self.tcx),
+ Some(ef),
+ ),
+ Mismatch::Fixed(s) => (s.into(), s.into(), None),
+ };
+ match (&terr, expected == found) {
+ (TypeError::Sorts(values), extra) => {
+ let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
+ (true, ty::Opaque(def_id, _)) => {
+ let sm = self.tcx.sess.source_map();
+ let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
+ format!(
+ " (opaque type at <{}:{}:{}>)",
+ sm.filename_for_diagnostics(&pos.file.name),
+ pos.line,
+ pos.col.to_usize() + 1,
+ )
+ }
+ (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
+ (false, _) => "".to_string(),
+ };
+ if !(values.expected.is_simple_text() && values.found.is_simple_text())
+ || (exp_found.map_or(false, |ef| {
+ // This happens when the type error is a subset of the expectation,
+ // like when you have two references but one is `usize` and the other
+ // is `f32`. In those cases we still want to show the `note`. If the
+ // value from `ef` is `Infer(_)`, then we ignore it.
+ if !ef.expected.is_ty_infer() {
+ ef.expected != values.expected
+ } else if !ef.found.is_ty_infer() {
+ ef.found != values.found
+ } else {
+ false
+ }
+ }))
+ {
+ diag.note_expected_found_extra(
+ &expected_label,
+ expected,
+ &found_label,
+ found,
+ &sort_string(values.expected),
+ &sort_string(values.found),
+ );
+ }
+ }
+ (TypeError::ObjectUnsafeCoercion(_), _) => {
+ diag.note_unsuccessful_coercion(found, expected);
+ }
+ (_, _) => {
+ debug!(
+ "note_type_err: exp_found={:?}, expected={:?} found={:?}",
+ exp_found, expected, found
+ );
+ if !is_simple_error || terr.must_include_note() {
+ diag.note_expected_found(&expected_label, expected, &found_label, found);
+ }
+ }
+ }
+ }
+ let exp_found = match exp_found {
+ Mismatch::Variable(exp_found) => Some(exp_found),
+ Mismatch::Fixed(_) => None,
+ };
+ let exp_found = match terr {
+ // `terr` has more accurate type information than `exp_found` in match expressions.
+ ty::error::TypeError::Sorts(terr)
+ if exp_found.map_or(false, |ef| terr.found == ef.found) =>
+ {
+ Some(*terr)
+ }
+ _ => exp_found,
+ };
+ debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
+ if let Some(exp_found) = exp_found {
+ let should_suggest_fixes =
+ if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
+ // Skip if the root_ty of the pattern is not the same as the expected_ty.
+ // If these types aren't equal then we've probably peeled off a layer of arrays.
+ self.same_type_modulo_infer(*root_ty, exp_found.expected)
+ } else {
+ true
+ };
+
+ if should_suggest_fixes {
+ self.suggest_tuple_pattern(cause, &exp_found, diag);
+ self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
+ self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
+ self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
+ }
+ }
+
+ // In some (most?) cases cause.body_id points to actual body, but in some cases
+ // it's an actual definition. According to the comments (e.g. in
+ // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
+ // is relied upon by some other code. This might (or might not) need cleanup.
+ let body_owner_def_id =
+ self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
+ self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
+ });
+ self.check_and_note_conflicting_crates(diag, terr);
+ self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
+
+ if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
+ && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
+ && let Some(def_id) = def_id.as_local()
+ {
+ let span = self.tcx.def_span(def_id);
+ diag.span_note(span, "this closure does not fulfill the lifetime requirements");
+ }
+
+ // It reads better to have the error origin as the final
+ // thing.
+ self.note_error_origin(diag, cause, exp_found, terr);
+
+ debug!(?diag);
+ }
+
+ fn suggest_tuple_pattern(
+ &self,
+ cause: &ObligationCause<'tcx>,
+ exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
+ diag: &mut Diagnostic,
+ ) {
+ // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with
+ // some modifications due to that being in typeck and this being in infer.
+ if let ObligationCauseCode::Pattern { .. } = cause.code() {
+ if let ty::Adt(expected_adt, substs) = exp_found.expected.kind() {
+ let compatible_variants: Vec<_> = expected_adt
+ .variants()
+ .iter()
+ .filter(|variant| {
+ variant.fields.len() == 1 && variant.ctor_kind == hir::def::CtorKind::Fn
+ })
+ .filter_map(|variant| {
+ let sole_field = &variant.fields[0];
+ let sole_field_ty = sole_field.ty(self.tcx, substs);
+ if self.same_type_modulo_infer(sole_field_ty, exp_found.found) {
+ let variant_path =
+ with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
+ // FIXME #56861: DRYer prelude filtering
+ if let Some(path) = variant_path.strip_prefix("std::prelude::") {
+ if let Some((_, path)) = path.split_once("::") {
+ return Some(path.to_string());
+ }
+ }
+ Some(variant_path)
+ } else {
+ None
+ }
+ })
+ .collect();
+ match &compatible_variants[..] {
+ [] => {}
+ [variant] => {
+ diag.multipart_suggestion_verbose(
+ &format!("try wrapping the pattern in `{}`", variant),
+ vec![
+ (cause.span.shrink_to_lo(), format!("{}(", variant)),
+ (cause.span.shrink_to_hi(), ")".to_string()),
+ ],
+ Applicability::MaybeIncorrect,
+ );
+ }
+ _ => {
+ // More than one matching variant.
+ diag.multipart_suggestions(
+ &format!(
+ "try wrapping the pattern in a variant of `{}`",
+ self.tcx.def_path_str(expected_adt.did())
+ ),
+ compatible_variants.into_iter().map(|variant| {
+ vec![
+ (cause.span.shrink_to_lo(), format!("{}(", variant)),
+ (cause.span.shrink_to_hi(), ")".to_string()),
+ ]
+ }),
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ }
+ }
+ }
+
+ pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Binder<'tcx, Ty<'tcx>>> {
+ if let ty::Opaque(def_id, substs) = ty.kind() {
+ let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
+ // Future::Output
+ let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
+
+ let bounds = self.tcx.bound_explicit_item_bounds(*def_id);
+
+ for predicate in bounds.transpose_iter().map(|e| e.map_bound(|(p, _)| *p)) {
+ let predicate = predicate.subst(self.tcx, substs);
+ let output = predicate
+ .kind()
+ .map_bound(|kind| match kind {
+ ty::PredicateKind::Projection(projection_predicate)
+ if projection_predicate.projection_ty.item_def_id == item_def_id =>
+ {
+ projection_predicate.term.ty()
+ }
+ _ => None,
+ })
+ .transpose();
+ if output.is_some() {
+ // We don't account for multiple `Future::Output = Ty` constraints.
+ return output;
+ }
+ }
+ }
+ None
+ }
+
+ /// A possible error is to forget to add `.await` when using futures:
+ ///
+ /// ```compile_fail,E0308
+ /// async fn make_u32() -> u32 {
+ /// 22
+ /// }
+ ///
+ /// fn take_u32(x: u32) {}
+ ///
+ /// async fn foo() {
+ /// let x = make_u32();
+ /// take_u32(x);
+ /// }
+ /// ```
+ ///
+ /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
+ /// expected type. If this is the case, and we are inside of an async body, it suggests adding
+ /// `.await` to the tail of the expression.
+ fn suggest_await_on_expect_found(
+ &self,
+ cause: &ObligationCause<'tcx>,
+ exp_span: Span,
+ exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
+ diag: &mut Diagnostic,
+ ) {
+ debug!(
+ "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
+ exp_span, exp_found.expected, exp_found.found,
+ );
+
+ if let ObligationCauseCode::CompareImplItemObligation { .. } = cause.code() {
+ return;
+ }
+
+ match (
+ self.get_impl_future_output_ty(exp_found.expected).map(Binder::skip_binder),
+ self.get_impl_future_output_ty(exp_found.found).map(Binder::skip_binder),
+ ) {
+ (Some(exp), Some(found)) if self.same_type_modulo_infer(exp, found) => match cause
+ .code()
+ {
+ ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => {
+ let then_span = self.find_block_span_from_hir_id(*then_id);
+ diag.multipart_suggestion(
+ "consider `await`ing on both `Future`s",
+ vec![
+ (then_span.shrink_to_hi(), ".await".to_string()),
+ (exp_span.shrink_to_hi(), ".await".to_string()),
+ ],
+ Applicability::MaybeIncorrect,
+ );
+ }
+ ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
+ prior_arms,
+ ..
+ }) => {
+ if let [.., arm_span] = &prior_arms[..] {
+ diag.multipart_suggestion(
+ "consider `await`ing on both `Future`s",
+ vec![
+ (arm_span.shrink_to_hi(), ".await".to_string()),
+ (exp_span.shrink_to_hi(), ".await".to_string()),
+ ],
+ Applicability::MaybeIncorrect,
+ );
+ } else {
+ diag.help("consider `await`ing on both `Future`s");
+ }
+ }
+ _ => {
+ diag.help("consider `await`ing on both `Future`s");
+ }
+ },
+ (_, Some(ty)) if self.same_type_modulo_infer(exp_found.expected, ty) => {
+ diag.span_suggestion_verbose(
+ exp_span.shrink_to_hi(),
+ "consider `await`ing on the `Future`",
+ ".await",
+ Applicability::MaybeIncorrect,
+ );
+ }
+ (Some(ty), _) if self.same_type_modulo_infer(ty, exp_found.found) => match cause.code()
+ {
+ ObligationCauseCode::Pattern { span: Some(then_span), .. } => {
+ diag.span_suggestion_verbose(
+ then_span.shrink_to_hi(),
+ "consider `await`ing on the `Future`",
+ ".await",
+ Applicability::MaybeIncorrect,
+ );
+ }
+ ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => {
+ let then_span = self.find_block_span_from_hir_id(*then_id);
+ diag.span_suggestion_verbose(
+ then_span.shrink_to_hi(),
+ "consider `await`ing on the `Future`",
+ ".await",
+ Applicability::MaybeIncorrect,
+ );
+ }
+ ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
+ ref prior_arms,
+ ..
+ }) => {
+ diag.multipart_suggestion_verbose(
+ "consider `await`ing on the `Future`",
+ prior_arms
+ .iter()
+ .map(|arm| (arm.shrink_to_hi(), ".await".to_string()))
+ .collect(),
+ Applicability::MaybeIncorrect,
+ );
+ }
+ _ => {}
+ },
+ _ => {}
+ }
+ }
+
+ fn suggest_accessing_field_where_appropriate(
+ &self,
+ cause: &ObligationCause<'tcx>,
+ exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
+ diag: &mut Diagnostic,
+ ) {
+ debug!(
+ "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
+ cause, exp_found
+ );
+ if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
+ if expected_def.is_enum() {
+ return;
+ }
+
+ if let Some((name, ty)) = expected_def
+ .non_enum_variant()
+ .fields
+ .iter()
+ .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
+ .map(|field| (field.name, field.ty(self.tcx, expected_substs)))
+ .find(|(_, ty)| self.same_type_modulo_infer(*ty, exp_found.found))
+ {
+ if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() {
+ if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
+ let suggestion = if expected_def.is_struct() {
+ format!("{}.{}", snippet, name)
+ } else if expected_def.is_union() {
+ format!("unsafe {{ {}.{} }}", snippet, name)
+ } else {
+ return;
+ };
+ diag.span_suggestion(
+ span,
+ &format!(
+ "you might have meant to use field `{}` whose type is `{}`",
+ name, ty
+ ),
+ suggestion,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ }
+ }
+ }
+
+ /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
+ /// suggests it.
+ fn suggest_as_ref_where_appropriate(
+ &self,
+ span: Span,
+ exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
+ diag: &mut Diagnostic,
+ ) {
+ if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
+ (exp_found.expected.kind(), exp_found.found.kind())
+ {
+ if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
+ let path_str = format!("{:?}", exp_def);
+ if exp_def == &found_def {
+ let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
+ `.as_ref()`";
+ let result_msg = "you can convert from `&Result<T, E>` to \
+ `Result<&T, &E>` using `.as_ref()`";
+ let have_as_ref = &[
+ ("std::option::Option", opt_msg),
+ ("core::option::Option", opt_msg),
+ ("std::result::Result", result_msg),
+ ("core::result::Result", result_msg),
+ ];
+ if let Some(msg) = have_as_ref
+ .iter()
+ .find_map(|(path, msg)| (&path_str == path).then_some(msg))
+ {
+ let mut show_suggestion = true;
+ for (exp_ty, found_ty) in
+ iter::zip(exp_substs.types(), found_substs.types())
+ {
+ match *exp_ty.kind() {
+ ty::Ref(_, exp_ty, _) => {
+ match (exp_ty.kind(), found_ty.kind()) {
+ (_, ty::Param(_))
+ | (_, ty::Infer(_))
+ | (ty::Param(_), _)
+ | (ty::Infer(_), _) => {}
+ _ if self.same_type_modulo_infer(exp_ty, found_ty) => {}
+ _ => show_suggestion = false,
+ };
+ }
+ ty::Param(_) | ty::Infer(_) => {}
+ _ => show_suggestion = false,
+ }
+ }
+ if let (Ok(snippet), true) =
+ (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
+ {
+ diag.span_suggestion(
+ span,
+ *msg,
+ format!("{}.as_ref()", snippet),
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ pub fn report_and_explain_type_error(
+ &self,
+ trace: TypeTrace<'tcx>,
+ terr: &TypeError<'tcx>,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ use crate::traits::ObligationCauseCode::MatchExpressionArm;
+
+ debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
+
+ let span = trace.cause.span();
+ let failure_code = trace.cause.as_failure_code(terr);
+ let mut diag = match failure_code {
+ FailureCode::Error0038(did) => {
+ let violations = self.tcx.object_safety_violations(did);
+ report_object_safety_error(self.tcx, span, did, violations)
+ }
+ FailureCode::Error0317(failure_str) => {
+ struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
+ }
+ FailureCode::Error0580(failure_str) => {
+ struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
+ }
+ FailureCode::Error0308(failure_str) => {
+ let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
+ if let Some((expected, found)) = trace.values.ty() {
+ match (expected.kind(), found.kind()) {
+ (ty::Tuple(_), ty::Tuple(_)) => {}
+ // If a tuple of length one was expected and the found expression has
+ // parentheses around it, perhaps the user meant to write `(expr,)` to
+ // build a tuple (issue #86100)
+ (ty::Tuple(fields), _) => {
+ self.emit_tuple_wrap_err(&mut err, span, found, fields)
+ }
+ // If a character was expected and the found expression is a string literal
+ // containing a single character, perhaps the user meant to write `'c'` to
+ // specify a character literal (issue #92479)
+ (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
+ if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
+ && let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
+ && code.chars().count() == 1
+ {
+ err.span_suggestion(
+ span,
+ "if you meant to write a `char` literal, use single quotes",
+ format!("'{}'", code),
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+ // If a string was expected and the found expression is a character literal,
+ // perhaps the user meant to write `"s"` to specify a string literal.
+ (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
+ if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
+ if let Some(code) =
+ code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
+ {
+ err.span_suggestion(
+ span,
+ "if you meant to write a `str` literal, use double quotes",
+ format!("\"{}\"", code),
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ let code = trace.cause.code();
+ if let &MatchExpressionArm(box MatchExpressionArmCause { source, .. }) = code
+ && let hir::MatchSource::TryDesugar = source
+ && let Some((expected_ty, found_ty)) = self.values_str(trace.values)
+ {
+ err.note(&format!(
+ "`?` operator cannot convert from `{}` to `{}`",
+ found_ty.content(),
+ expected_ty.content(),
+ ));
+ }
+ err
+ }
+ FailureCode::Error0644(failure_str) => {
+ struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
+ }
+ };
+ self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false, false);
+ diag
+ }
+
+ fn emit_tuple_wrap_err(
+ &self,
+ err: &mut Diagnostic,
+ span: Span,
+ found: Ty<'tcx>,
+ expected_fields: &List<Ty<'tcx>>,
+ ) {
+ let [expected_tup_elem] = expected_fields[..] else { return };
+
+ if !self.same_type_modulo_infer(expected_tup_elem, found) {
+ return;
+ }
+
+ let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
+ else { return };
+
+ let msg = "use a trailing comma to create a tuple with one element";
+ if code.starts_with('(') && code.ends_with(')') {
+ let before_close = span.hi() - BytePos::from_u32(1);
+ err.span_suggestion(
+ span.with_hi(before_close).shrink_to_hi(),
+ msg,
+ ",",
+ Applicability::MachineApplicable,
+ );
+ } else {
+ err.multipart_suggestion(
+ msg,
+ vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+
+ fn values_str(
+ &self,
+ values: ValuePairs<'tcx>,
+ ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
+ match values {
+ infer::Regions(exp_found) => self.expected_found_str(exp_found),
+ infer::Terms(exp_found) => self.expected_found_str_term(exp_found),
+ infer::TraitRefs(exp_found) => {
+ let pretty_exp_found = ty::error::ExpectedFound {
+ expected: exp_found.expected.print_only_trait_path(),
+ found: exp_found.found.print_only_trait_path(),
+ };
+ match self.expected_found_str(pretty_exp_found) {
+ Some((expected, found)) if expected == found => {
+ self.expected_found_str(exp_found)
+ }
+ ret => ret,
+ }
+ }
+ infer::PolyTraitRefs(exp_found) => {
+ let pretty_exp_found = ty::error::ExpectedFound {
+ expected: exp_found.expected.print_only_trait_path(),
+ found: exp_found.found.print_only_trait_path(),
+ };
+ match self.expected_found_str(pretty_exp_found) {
+ Some((expected, found)) if expected == found => {
+ self.expected_found_str(exp_found)
+ }
+ ret => ret,
+ }
+ }
+ }
+ }
+
+ fn expected_found_str_term(
+ &self,
+ exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
+ ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
+ let exp_found = self.resolve_vars_if_possible(exp_found);
+ if exp_found.references_error() {
+ return None;
+ }
+
+ Some(match (exp_found.expected, exp_found.found) {
+ (ty::Term::Ty(expected), ty::Term::Ty(found)) => self.cmp(expected, found),
+ (expected, found) => (
+ DiagnosticStyledString::highlighted(expected.to_string()),
+ DiagnosticStyledString::highlighted(found.to_string()),
+ ),
+ })
+ }
+
+ /// Returns a string of the form "expected `{}`, found `{}`".
+ fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
+ &self,
+ exp_found: ty::error::ExpectedFound<T>,
+ ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
+ let exp_found = self.resolve_vars_if_possible(exp_found);
+ if exp_found.references_error() {
+ return None;
+ }
+
+ Some((
+ DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
+ DiagnosticStyledString::highlighted(exp_found.found.to_string()),
+ ))
+ }
+
+ pub fn report_generic_bound_failure(
+ &self,
+ generic_param_scope: LocalDefId,
+ span: Span,
+ origin: Option<SubregionOrigin<'tcx>>,
+ bound_kind: GenericKind<'tcx>,
+ sub: Region<'tcx>,
+ ) {
+ self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
+ .emit();
+ }
+
+ pub fn construct_generic_bound_failure(
+ &self,
+ generic_param_scope: LocalDefId,
+ span: Span,
+ origin: Option<SubregionOrigin<'tcx>>,
+ bound_kind: GenericKind<'tcx>,
+ sub: Region<'tcx>,
+ ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
+ // Attempt to obtain the span of the parameter so we can
+ // suggest adding an explicit lifetime bound to it.
+ let generics = self.tcx.generics_of(generic_param_scope);
+ // type_param_span is (span, has_bounds)
+ let type_param_span = match bound_kind {
+ GenericKind::Param(ref param) => {
+ // Account for the case where `param` corresponds to `Self`,
+ // which doesn't have the expected type argument.
+ if !(generics.has_self && param.index == 0) {
+ let type_param = generics.type_param(param, self.tcx);
+ type_param.def_id.as_local().map(|def_id| {
+ // Get the `hir::Param` to verify whether it already has any bounds.
+ // We do this to avoid suggesting code that ends up as `T: 'a'b`,
+ // instead we suggest `T: 'a + 'b` in that case.
+ let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
+ let ast_generics = self.tcx.hir().get_generics(hir_id.owner);
+ let bounds =
+ ast_generics.and_then(|g| g.bounds_span_for_suggestions(def_id));
+ // `sp` only covers `T`, change it so that it covers
+ // `T:` when appropriate
+ if let Some(span) = bounds {
+ (span, true)
+ } else {
+ let sp = self.tcx.def_span(def_id);
+ (sp.shrink_to_hi(), false)
+ }
+ })
+ } else {
+ None
+ }
+ }
+ _ => None,
+ };
+
+ let new_lt = {
+ let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
+ let lts_names =
+ iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
+ .flat_map(|g| &g.params)
+ .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
+ .map(|p| p.name.as_str())
+ .collect::<Vec<_>>();
+ possible
+ .find(|candidate| !lts_names.contains(&&candidate[..]))
+ .unwrap_or("'lt".to_string())
+ };
+
+ let add_lt_sugg = generics
+ .params
+ .first()
+ .and_then(|param| param.def_id.as_local())
+ .map(|def_id| (self.tcx.def_span(def_id).shrink_to_lo(), format!("{}, ", new_lt)));
+
+ let labeled_user_string = match bound_kind {
+ GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
+ GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
+ };
+
+ if let Some(SubregionOrigin::CompareImplItemObligation {
+ span,
+ impl_item_def_id,
+ trait_item_def_id,
+ }) = origin
+ {
+ return self.report_extra_impl_obligation(
+ span,
+ impl_item_def_id,
+ trait_item_def_id,
+ &format!("`{}: {}`", bound_kind, sub),
+ );
+ }
+
+ fn binding_suggestion<'tcx, S: fmt::Display>(
+ err: &mut Diagnostic,
+ type_param_span: Option<(Span, bool)>,
+ bound_kind: GenericKind<'tcx>,
+ sub: S,
+ ) {
+ let msg = "consider adding an explicit lifetime bound";
+ if let Some((sp, has_lifetimes)) = type_param_span {
+ let suggestion =
+ if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) };
+ err.span_suggestion_verbose(
+ sp,
+ &format!("{}...", msg),
+ suggestion,
+ Applicability::MaybeIncorrect, // Issue #41966
+ );
+ } else {
+ let consider = format!("{} `{}: {}`...", msg, bound_kind, sub,);
+ err.help(&consider);
+ }
+ }
+
+ let new_binding_suggestion =
+ |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| {
+ let msg = "consider introducing an explicit lifetime bound";
+ if let Some((sp, has_lifetimes)) = type_param_span {
+ let suggestion = if has_lifetimes {
+ format!(" + {}", new_lt)
+ } else {
+ format!(": {}", new_lt)
+ };
+ let mut sugg =
+ vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {}", new_lt))];
+ if let Some(lt) = add_lt_sugg {
+ sugg.push(lt);
+ sugg.rotate_right(1);
+ }
+ // `MaybeIncorrect` due to issue #41966.
+ err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
+ }
+ };
+
+ #[derive(Debug)]
+ enum SubOrigin<'hir> {
+ GAT(&'hir hir::Generics<'hir>),
+ Impl,
+ Trait,
+ Fn,
+ Unknown,
+ }
+ let sub_origin = 'origin: {
+ match *sub {
+ ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
+ let node = self.tcx.hir().get_if_local(def_id).unwrap();
+ match node {
+ Node::GenericParam(param) => {
+ for h in self.tcx.hir().parent_iter(param.hir_id) {
+ break 'origin match h.1 {
+ Node::ImplItem(hir::ImplItem {
+ kind: hir::ImplItemKind::TyAlias(..),
+ generics,
+ ..
+ })
+ | Node::TraitItem(hir::TraitItem {
+ kind: hir::TraitItemKind::Type(..),
+ generics,
+ ..
+ }) => SubOrigin::GAT(generics),
+ Node::ImplItem(hir::ImplItem {
+ kind: hir::ImplItemKind::Fn(..),
+ ..
+ })
+ | Node::TraitItem(hir::TraitItem {
+ kind: hir::TraitItemKind::Fn(..),
+ ..
+ })
+ | Node::Item(hir::Item {
+ kind: hir::ItemKind::Fn(..), ..
+ }) => SubOrigin::Fn,
+ Node::Item(hir::Item {
+ kind: hir::ItemKind::Trait(..),
+ ..
+ }) => SubOrigin::Trait,
+ Node::Item(hir::Item {
+ kind: hir::ItemKind::Impl(..), ..
+ }) => SubOrigin::Impl,
+ _ => continue,
+ };
+ }
+ }
+ _ => {}
+ }
+ }
+ _ => {}
+ }
+ SubOrigin::Unknown
+ };
+ debug!(?sub_origin);
+
+ let mut err = match (*sub, sub_origin) {
+ // In the case of GATs, we have to be careful. If we a type parameter `T` on an impl,
+ // but a lifetime `'a` on an associated type, then we might need to suggest adding
+ // `where T: 'a`. Importantly, this is on the GAT span, not on the `T` declaration.
+ (ty::ReEarlyBound(ty::EarlyBoundRegion { name: _, .. }), SubOrigin::GAT(generics)) => {
+ // Does the required lifetime have a nice name we can print?
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0309,
+ "{} may not live long enough",
+ labeled_user_string
+ );
+ let pred = format!("{}: {}", bound_kind, sub);
+ let suggestion = format!("{} {}", generics.add_where_or_trailing_comma(), pred,);
+ err.span_suggestion(
+ generics.tail_span_for_predicate_suggestion(),
+ "consider adding a where clause",
+ suggestion,
+ Applicability::MaybeIncorrect,
+ );
+ err
+ }
+ (
+ ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
+ | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }),
+ _,
+ ) if name != kw::UnderscoreLifetime => {
+ // Does the required lifetime have a nice name we can print?
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0309,
+ "{} may not live long enough",
+ labeled_user_string
+ );
+ // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
+ // for the bound is not suitable for suggestions when `-Zverbose` is set because it
+ // uses `Debug` output, so we handle it specially here so that suggestions are
+ // always correct.
+ binding_suggestion(&mut err, type_param_span, bound_kind, name);
+ err
+ }
+
+ (ty::ReStatic, _) => {
+ // Does the required lifetime have a nice name we can print?
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0310,
+ "{} may not live long enough",
+ labeled_user_string
+ );
+ binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
+ err
+ }
+
+ _ => {
+ // If not, be less specific.
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0311,
+ "{} may not live long enough",
+ labeled_user_string
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ &format!("{} must be valid for ", labeled_user_string),
+ sub,
+ "...",
+ None,
+ );
+ if let Some(infer::RelateParamBound(_, t, _)) = origin {
+ let return_impl_trait =
+ self.tcx.return_type_impl_trait(generic_param_scope).is_some();
+ let t = self.resolve_vars_if_possible(t);
+ match t.kind() {
+ // We've got:
+ // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
+ // suggest:
+ // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
+ ty::Closure(_, _substs) | ty::Opaque(_, _substs) if return_impl_trait => {
+ new_binding_suggestion(&mut err, type_param_span);
+ }
+ _ => {
+ binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
+ }
+ }
+ }
+ err
+ }
+ };
+
+ if let Some(origin) = origin {
+ self.note_region_origin(&mut err, &origin);
+ }
+ err
+ }
+
+ fn report_sub_sup_conflict(
+ &self,
+ var_origin: RegionVariableOrigin,
+ sub_origin: SubregionOrigin<'tcx>,
+ sub_region: Region<'tcx>,
+ sup_origin: SubregionOrigin<'tcx>,
+ sup_region: Region<'tcx>,
+ ) {
+ let mut err = self.report_inference_failure(var_origin);
+
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "first, the lifetime cannot outlive ",
+ sup_region,
+ "...",
+ None,
+ );
+
+ debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
+ debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
+ debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
+ debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
+ debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
+
+ if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
+ (&sup_origin, &sub_origin)
+ {
+ debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
+ debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
+ debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
+ debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
+
+ if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
+ (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
+ {
+ if sub_expected == sup_expected && sub_found == sup_found {
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "...but the lifetime must also be valid for ",
+ sub_region,
+ "...",
+ None,
+ );
+ err.span_note(
+ sup_trace.cause.span,
+ &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
+ );
+
+ err.note_expected_found(&"", sup_expected, &"", sup_found);
+ err.emit();
+ return;
+ }
+ }
+ }
+
+ self.note_region_origin(&mut err, &sup_origin);
+
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "but, the lifetime must be valid for ",
+ sub_region,
+ "...",
+ None,
+ );
+
+ self.note_region_origin(&mut err, &sub_origin);
+ err.emit();
+ }
+
+ /// Determine whether an error associated with the given span and definition
+ /// should be treated as being caused by the implicit `From` conversion
+ /// within `?` desugaring.
+ pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
+ span.is_desugaring(DesugaringKind::QuestionMark)
+ && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
+ }
+
+ /// Structurally compares two types, modulo any inference variables.
+ ///
+ /// Returns `true` if two types are equal, or if one type is an inference variable compatible
+ /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
+ /// FloatVar inference type are compatible with themselves or their concrete types (Int and
+ /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
+ pub fn same_type_modulo_infer(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
+ let (a, b) = self.resolve_vars_if_possible((a, b));
+ match (a.kind(), b.kind()) {
+ (&ty::Adt(def_a, substs_a), &ty::Adt(def_b, substs_b)) => {
+ if def_a != def_b {
+ return false;
+ }
+
+ substs_a
+ .types()
+ .zip(substs_b.types())
+ .all(|(a, b)| self.same_type_modulo_infer(a, b))
+ }
+ (&ty::FnDef(did_a, substs_a), &ty::FnDef(did_b, substs_b)) => {
+ if did_a != did_b {
+ return false;
+ }
+
+ substs_a
+ .types()
+ .zip(substs_b.types())
+ .all(|(a, b)| self.same_type_modulo_infer(a, b))
+ }
+ (&ty::Int(_) | &ty::Uint(_), &ty::Infer(ty::InferTy::IntVar(_)))
+ | (
+ &ty::Infer(ty::InferTy::IntVar(_)),
+ &ty::Int(_) | &ty::Uint(_) | &ty::Infer(ty::InferTy::IntVar(_)),
+ )
+ | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
+ | (
+ &ty::Infer(ty::InferTy::FloatVar(_)),
+ &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
+ )
+ | (&ty::Infer(ty::InferTy::TyVar(_)), _)
+ | (_, &ty::Infer(ty::InferTy::TyVar(_))) => true,
+ (&ty::Ref(_, ty_a, mut_a), &ty::Ref(_, ty_b, mut_b)) => {
+ mut_a == mut_b && self.same_type_modulo_infer(ty_a, ty_b)
+ }
+ (&ty::RawPtr(a), &ty::RawPtr(b)) => {
+ a.mutbl == b.mutbl && self.same_type_modulo_infer(a.ty, b.ty)
+ }
+ (&ty::Slice(a), &ty::Slice(b)) => self.same_type_modulo_infer(a, b),
+ (&ty::Array(a_ty, a_ct), &ty::Array(b_ty, b_ct)) => {
+ self.same_type_modulo_infer(a_ty, b_ty) && a_ct == b_ct
+ }
+ (&ty::Tuple(a), &ty::Tuple(b)) => {
+ if a.len() != b.len() {
+ return false;
+ }
+ std::iter::zip(a.iter(), b.iter()).all(|(a, b)| self.same_type_modulo_infer(a, b))
+ }
+ (&ty::FnPtr(a), &ty::FnPtr(b)) => {
+ let a = a.skip_binder().inputs_and_output;
+ let b = b.skip_binder().inputs_and_output;
+ if a.len() != b.len() {
+ return false;
+ }
+ std::iter::zip(a.iter(), b.iter()).all(|(a, b)| self.same_type_modulo_infer(a, b))
+ }
+ // FIXME(compiler-errors): This needs to be generalized more
+ _ => a == b,
+ }
+ }
+}
+
+impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
+ fn report_inference_failure(
+ &self,
+ var_origin: RegionVariableOrigin,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ let br_string = |br: ty::BoundRegionKind| {
+ let mut s = match br {
+ ty::BrNamed(_, name) => name.to_string(),
+ _ => String::new(),
+ };
+ if !s.is_empty() {
+ s.push(' ');
+ }
+ s
+ };
+ let var_description = match var_origin {
+ infer::MiscVariable(_) => String::new(),
+ infer::PatternRegion(_) => " for pattern".to_string(),
+ infer::AddrOfRegion(_) => " for borrow expression".to_string(),
+ infer::Autoref(_) => " for autoref".to_string(),
+ infer::Coercion(_) => " for automatic coercion".to_string(),
+ infer::LateBoundRegion(_, br, infer::FnCall) => {
+ format!(" for lifetime parameter {}in function call", br_string(br))
+ }
+ infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
+ format!(" for lifetime parameter {}in generic type", br_string(br))
+ }
+ infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
+ " for lifetime parameter {}in trait containing associated type `{}`",
+ br_string(br),
+ self.tcx.associated_item(def_id).name
+ ),
+ infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
+ infer::UpvarRegion(ref upvar_id, _) => {
+ let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
+ format!(" for capture of `{}` by closure", var_name)
+ }
+ infer::Nll(..) => bug!("NLL variable found in lexical phase"),
+ };
+
+ struct_span_err!(
+ self.tcx.sess,
+ var_origin.span(),
+ E0495,
+ "cannot infer an appropriate lifetime{} due to conflicting requirements",
+ var_description
+ )
+ }
+}
+
+pub enum FailureCode {
+ Error0038(DefId),
+ Error0317(&'static str),
+ Error0580(&'static str),
+ Error0308(&'static str),
+ Error0644(&'static str),
+}
+
+pub trait ObligationCauseExt<'tcx> {
+ fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
+ fn as_requirement_str(&self) -> &'static str;
+}
+
+impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
+ fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
+ use self::FailureCode::*;
+ use crate::traits::ObligationCauseCode::*;
+ match self.code() {
+ CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
+ Error0308("method not compatible with trait")
+ }
+ CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
+ Error0308("type not compatible with trait")
+ }
+ CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
+ Error0308("const not compatible with trait")
+ }
+ MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
+ Error0308(match source {
+ hir::MatchSource::TryDesugar => "`?` operator has incompatible types",
+ _ => "`match` arms have incompatible types",
+ })
+ }
+ IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
+ IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
+ LetElse => Error0308("`else` clause of `let...else` does not diverge"),
+ MainFunctionType => Error0580("`main` function has wrong type"),
+ StartFunctionType => Error0308("`#[start]` function has wrong type"),
+ IntrinsicType => Error0308("intrinsic has wrong type"),
+ MethodReceiver => Error0308("mismatched `self` parameter type"),
+
+ // In the case where we have no more specific thing to
+ // say, also take a look at the error code, maybe we can
+ // tailor to that.
+ _ => match terr {
+ TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
+ Error0644("closure/generator type that references itself")
+ }
+ TypeError::IntrinsicCast => {
+ Error0308("cannot coerce intrinsics to function pointers")
+ }
+ TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
+ _ => Error0308("mismatched types"),
+ },
+ }
+ }
+
+ fn as_requirement_str(&self) -> &'static str {
+ use crate::traits::ObligationCauseCode::*;
+ match self.code() {
+ CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
+ "method type is compatible with trait"
+ }
+ CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
+ "associated type is compatible with trait"
+ }
+ CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
+ "const is compatible with trait"
+ }
+ ExprAssignable => "expression is assignable",
+ IfExpression { .. } => "`if` and `else` have incompatible types",
+ IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
+ MainFunctionType => "`main` function has the correct type",
+ StartFunctionType => "`#[start]` function has the correct type",
+ IntrinsicType => "intrinsic has the correct type",
+ MethodReceiver => "method receiver has the correct type",
+ _ => "types are compatible",
+ }
+ }
+}
+
+/// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
+/// extra information about each type, but we only care about the category.
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+pub enum TyCategory {
+ Closure,
+ Opaque,
+ Generator(hir::GeneratorKind),
+ Foreign,
+}
+
+impl TyCategory {
+ fn descr(&self) -> &'static str {
+ match self {
+ Self::Closure => "closure",
+ Self::Opaque => "opaque type",
+ Self::Generator(gk) => gk.descr(),
+ Self::Foreign => "foreign type",
+ }
+ }
+
+ pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
+ match *ty.kind() {
+ ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
+ ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
+ ty::Generator(def_id, ..) => {
+ Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
+ }
+ ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
+ _ => None,
+ }
+ }
+}
+
+impl<'tcx> InferCtxt<'_, 'tcx> {
+ /// Given a [`hir::Block`], get the span of its last expression or
+ /// statement, peeling off any inner blocks.
+ pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
+ let block = block.innermost_block();
+ if let Some(expr) = &block.expr {
+ expr.span
+ } else if let Some(stmt) = block.stmts.last() {
+ // possibly incorrect trailing `;` in the else arm
+ stmt.span
+ } else {
+ // empty block; point at its entirety
+ block.span
+ }
+ }
+
+ /// Given a [`hir::HirId`] for a block, get the span of its last expression
+ /// or statement, peeling off any inner blocks.
+ pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
+ match self.tcx.hir().get(hir_id) {
+ hir::Node::Block(blk) => self.find_block_span(blk),
+ // The parser was in a weird state if either of these happen, but
+ // it's better not to panic.
+ hir::Node::Expr(e) => e.span,
+ _ => rustc_span::DUMMY_SP,
+ }
+ }
+
+ /// Be helpful when the user wrote `{... expr; }` and taking the `;` off
+ /// is enough to fix the error.
+ pub fn could_remove_semicolon(
+ &self,
+ blk: &'tcx hir::Block<'tcx>,
+ expected_ty: Ty<'tcx>,
+ ) -> Option<(Span, StatementAsExpression)> {
+ let blk = blk.innermost_block();
+ // Do not suggest if we have a tail expr.
+ if blk.expr.is_some() {
+ return None;
+ }
+ let last_stmt = blk.stmts.last()?;
+ let hir::StmtKind::Semi(ref last_expr) = last_stmt.kind else {
+ return None;
+ };
+ let last_expr_ty = self.in_progress_typeck_results?.borrow().expr_ty_opt(*last_expr)?;
+ let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) {
+ _ if last_expr_ty.references_error() => return None,
+ _ if self.same_type_modulo_infer(last_expr_ty, expected_ty) => {
+ StatementAsExpression::CorrectType
+ }
+ (ty::Opaque(last_def_id, _), ty::Opaque(exp_def_id, _))
+ if last_def_id == exp_def_id =>
+ {
+ StatementAsExpression::CorrectType
+ }
+ (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => {
+ debug!(
+ "both opaque, likely future {:?} {:?} {:?} {:?}",
+ last_def_id, last_bounds, exp_def_id, exp_bounds
+ );
+
+ let last_local_id = last_def_id.as_local()?;
+ let exp_local_id = exp_def_id.as_local()?;
+
+ match (
+ &self.tcx.hir().expect_item(last_local_id).kind,
+ &self.tcx.hir().expect_item(exp_local_id).kind,
+ ) {
+ (
+ hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: last_bounds, .. }),
+ hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: exp_bounds, .. }),
+ ) if iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| {
+ match (left, right) {
+ (
+ hir::GenericBound::Trait(tl, ml),
+ hir::GenericBound::Trait(tr, mr),
+ ) if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
+ && ml == mr =>
+ {
+ true
+ }
+ (
+ hir::GenericBound::LangItemTrait(langl, _, _, argsl),
+ hir::GenericBound::LangItemTrait(langr, _, _, argsr),
+ ) if langl == langr => {
+ // FIXME: consider the bounds!
+ debug!("{:?} {:?}", argsl, argsr);
+ true
+ }
+ _ => false,
+ }
+ }) =>
+ {
+ StatementAsExpression::NeedsBoxing
+ }
+ _ => StatementAsExpression::CorrectType,
+ }
+ }
+ _ => return None,
+ };
+ let span = if last_stmt.span.from_expansion() {
+ let mac_call = rustc_span::source_map::original_sp(last_stmt.span, blk.span);
+ self.tcx.sess.source_map().mac_call_stmt_semi_span(mac_call)?
+ } else {
+ last_stmt.span.with_lo(last_stmt.span.hi() - BytePos(1))
+ };
+ Some((span, needs_box))
+ }
+
+ /// Suggest returning a local binding with a compatible type if the block
+ /// has no return expression.
+ pub fn consider_returning_binding(
+ &self,
+ blk: &'tcx hir::Block<'tcx>,
+ expected_ty: Ty<'tcx>,
+ err: &mut Diagnostic,
+ ) -> bool {
+ let blk = blk.innermost_block();
+ // Do not suggest if we have a tail expr.
+ if blk.expr.is_some() {
+ return false;
+ }
+ let mut shadowed = FxHashSet::default();
+ let mut candidate_idents = vec![];
+ let mut find_compatible_candidates = |pat: &hir::Pat<'_>| {
+ if let hir::PatKind::Binding(_, hir_id, ident, _) = &pat.kind
+ && let Some(pat_ty) = self
+ .in_progress_typeck_results
+ .and_then(|typeck_results| typeck_results.borrow().node_type_opt(*hir_id))
+ {
+ let pat_ty = self.resolve_vars_if_possible(pat_ty);
+ if self.same_type_modulo_infer(pat_ty, expected_ty)
+ && !(pat_ty, expected_ty).references_error()
+ && shadowed.insert(ident.name)
+ {
+ candidate_idents.push((*ident, pat_ty));
+ }
+ }
+ true
+ };
+
+ let hir = self.tcx.hir();
+ for stmt in blk.stmts.iter().rev() {
+ let hir::StmtKind::Local(local) = &stmt.kind else { continue; };
+ local.pat.walk(&mut find_compatible_candidates);
+ }
+ match hir.find(hir.get_parent_node(blk.hir_id)) {
+ Some(hir::Node::Expr(hir::Expr { hir_id, .. })) => {
+ match hir.find(hir.get_parent_node(*hir_id)) {
+ Some(hir::Node::Arm(hir::Arm { pat, .. })) => {
+ pat.walk(&mut find_compatible_candidates);
+ }
+ Some(
+ hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body), .. })
+ | hir::Node::ImplItem(hir::ImplItem {
+ kind: hir::ImplItemKind::Fn(_, body),
+ ..
+ })
+ | hir::Node::TraitItem(hir::TraitItem {
+ kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body)),
+ ..
+ })
+ | hir::Node::Expr(hir::Expr {
+ kind: hir::ExprKind::Closure(hir::Closure { body, .. }),
+ ..
+ }),
+ ) => {
+ for param in hir.body(*body).params {
+ param.pat.walk(&mut find_compatible_candidates);
+ }
+ }
+ Some(hir::Node::Expr(hir::Expr {
+ kind:
+ hir::ExprKind::If(
+ hir::Expr { kind: hir::ExprKind::Let(let_), .. },
+ then_block,
+ _,
+ ),
+ ..
+ })) if then_block.hir_id == *hir_id => {
+ let_.pat.walk(&mut find_compatible_candidates);
+ }
+ _ => {}
+ }
+ }
+ _ => {}
+ }
+
+ match &candidate_idents[..] {
+ [(ident, _ty)] => {
+ let sm = self.tcx.sess.source_map();
+ if let Some(stmt) = blk.stmts.last() {
+ let stmt_span = sm.stmt_span(stmt.span, blk.span);
+ let sugg = if sm.is_multiline(blk.span)
+ && let Some(spacing) = sm.indentation_before(stmt_span)
+ {
+ format!("\n{spacing}{ident}")
+ } else {
+ format!(" {ident}")
+ };
+ err.span_suggestion_verbose(
+ stmt_span.shrink_to_hi(),
+ format!("consider returning the local binding `{ident}`"),
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ } else {
+ let sugg = if sm.is_multiline(blk.span)
+ && let Some(spacing) = sm.indentation_before(blk.span.shrink_to_lo())
+ {
+ format!("\n{spacing} {ident}\n{spacing}")
+ } else {
+ format!(" {ident} ")
+ };
+ let left_span = sm.span_through_char(blk.span, '{').shrink_to_hi();
+ err.span_suggestion_verbose(
+ sm.span_extend_while(left_span, |c| c.is_whitespace()).unwrap_or(left_span),
+ format!("consider returning the local binding `{ident}`"),
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ true
+ }
+ values if (1..3).contains(&values.len()) => {
+ let spans = values.iter().map(|(ident, _)| ident.span).collect::<Vec<_>>();
+ err.span_note(spans, "consider returning one of these bindings");
+ true
+ }
+ _ => false,
+ }
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs
new file mode 100644
index 000000000..561d1354e
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs
@@ -0,0 +1,1134 @@
+use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
+use crate::infer::InferCtxt;
+use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
+use rustc_hir as hir;
+use rustc_hir::def::Res;
+use rustc_hir::def::{CtorOf, DefKind, Namespace};
+use rustc_hir::def_id::DefId;
+use rustc_hir::intravisit::{self, Visitor};
+use rustc_hir::{Body, Closure, Expr, ExprKind, FnRetTy, HirId, Local, LocalSource};
+use rustc_middle::hir::nested_filter;
+use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
+use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
+use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Print, Printer};
+use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst, SubstsRef};
+use rustc_middle::ty::{self, DefIdTree, InferConst};
+use rustc_middle::ty::{IsSuggestable, Ty, TyCtxt, TypeckResults};
+use rustc_span::symbol::{kw, Ident};
+use rustc_span::{BytePos, Span};
+use std::borrow::Cow;
+use std::iter;
+
+pub enum TypeAnnotationNeeded {
+ /// ```compile_fail,E0282
+ /// let x = "hello".chars().rev().collect();
+ /// ```
+ E0282,
+ /// An implementation cannot be chosen unambiguously because of lack of information.
+ /// ```compile_fail,E0283
+ /// let _ = Default::default();
+ /// ```
+ E0283,
+ /// ```compile_fail,E0284
+ /// let mut d: u64 = 2;
+ /// d = d % 1u32.into();
+ /// ```
+ E0284,
+}
+
+impl Into<rustc_errors::DiagnosticId> for TypeAnnotationNeeded {
+ fn into(self) -> rustc_errors::DiagnosticId {
+ match self {
+ Self::E0282 => rustc_errors::error_code!(E0282),
+ Self::E0283 => rustc_errors::error_code!(E0283),
+ Self::E0284 => rustc_errors::error_code!(E0284),
+ }
+ }
+}
+
+/// Information about a constant or a type containing inference variables.
+pub struct InferenceDiagnosticsData {
+ pub name: String,
+ pub span: Option<Span>,
+ pub kind: UnderspecifiedArgKind,
+ pub parent: Option<InferenceDiagnosticsParentData>,
+}
+
+/// Data on the parent definition where a generic argument was declared.
+pub struct InferenceDiagnosticsParentData {
+ prefix: &'static str,
+ name: String,
+}
+
+pub enum UnderspecifiedArgKind {
+ Type { prefix: Cow<'static, str> },
+ Const { is_parameter: bool },
+}
+
+impl InferenceDiagnosticsData {
+ /// Generate a label for a generic argument which can't be inferred. When not
+ /// much is known about the argument, `use_diag` may be used to describe the
+ /// labeled value.
+ fn cannot_infer_msg(&self) -> String {
+ if self.name == "_" && matches!(self.kind, UnderspecifiedArgKind::Type { .. }) {
+ return "cannot infer type".to_string();
+ }
+
+ let suffix = match &self.parent {
+ Some(parent) => parent.suffix_string(),
+ None => String::new(),
+ };
+
+ // For example: "cannot infer type for type parameter `T`"
+ format!("cannot infer {} `{}`{}", self.kind.prefix_string(), self.name, suffix)
+ }
+
+ fn where_x_is_specified(&self, in_type: Ty<'_>) -> String {
+ if in_type.is_ty_infer() {
+ String::new()
+ } else if self.name == "_" {
+ // FIXME: Consider specializing this message if there is a single `_`
+ // in the type.
+ ", where the placeholders `_` are specified".to_string()
+ } else {
+ format!(", where the {} `{}` is specified", self.kind.prefix_string(), self.name)
+ }
+ }
+}
+
+impl InferenceDiagnosticsParentData {
+ fn for_parent_def_id(
+ tcx: TyCtxt<'_>,
+ parent_def_id: DefId,
+ ) -> Option<InferenceDiagnosticsParentData> {
+ let parent_name =
+ tcx.def_key(parent_def_id).disambiguated_data.data.get_opt_name()?.to_string();
+
+ Some(InferenceDiagnosticsParentData {
+ prefix: tcx.def_kind(parent_def_id).descr(parent_def_id),
+ name: parent_name,
+ })
+ }
+
+ fn for_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<InferenceDiagnosticsParentData> {
+ Self::for_parent_def_id(tcx, tcx.parent(def_id))
+ }
+
+ fn suffix_string(&self) -> String {
+ format!(" declared on the {} `{}`", self.prefix, self.name)
+ }
+}
+
+impl UnderspecifiedArgKind {
+ fn prefix_string(&self) -> Cow<'static, str> {
+ match self {
+ Self::Type { prefix } => format!("type for {}", prefix).into(),
+ Self::Const { is_parameter: true } => "the value of const parameter".into(),
+ Self::Const { is_parameter: false } => "the value of the constant".into(),
+ }
+ }
+}
+
+fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'_, 'tcx>, ns: Namespace) -> FmtPrinter<'a, 'tcx> {
+ let mut printer = FmtPrinter::new(infcx.tcx, ns);
+ let ty_getter = move |ty_vid| {
+ if infcx.probe_ty_var(ty_vid).is_ok() {
+ warn!("resolved ty var in error message");
+ }
+ if let TypeVariableOriginKind::TypeParameterDefinition(name, _) =
+ infcx.inner.borrow_mut().type_variables().var_origin(ty_vid).kind
+ {
+ Some(name)
+ } else {
+ None
+ }
+ };
+ printer.ty_infer_name_resolver = Some(Box::new(ty_getter));
+ let const_getter = move |ct_vid| {
+ if infcx.probe_const_var(ct_vid).is_ok() {
+ warn!("resolved const var in error message");
+ }
+ if let ConstVariableOriginKind::ConstParameterDefinition(name, _) =
+ infcx.inner.borrow_mut().const_unification_table().probe_value(ct_vid).origin.kind
+ {
+ return Some(name);
+ } else {
+ None
+ }
+ };
+ printer.const_infer_name_resolver = Some(Box::new(const_getter));
+ printer
+}
+
+fn ty_to_string<'tcx>(infcx: &InferCtxt<'_, 'tcx>, ty: Ty<'tcx>) -> String {
+ let printer = fmt_printer(infcx, Namespace::TypeNS);
+ let ty = infcx.resolve_vars_if_possible(ty);
+ match ty.kind() {
+ // We don't want the regular output for `fn`s because it includes its path in
+ // invalid pseudo-syntax, we want the `fn`-pointer output instead.
+ ty::FnDef(..) => ty.fn_sig(infcx.tcx).print(printer).unwrap().into_buffer(),
+ // FIXME: The same thing for closures, but this only works when the closure
+ // does not capture anything.
+ //
+ // We do have to hide the `extern "rust-call"` ABI in that case though,
+ // which is too much of a bother for now.
+ _ => ty.print(printer).unwrap().into_buffer(),
+ }
+}
+
+/// We don't want to directly use `ty_to_string` for closures as their type isn't really
+/// something users are familar with. Directly printing the `fn_sig` of closures also
+/// doesn't work as they actually use the "rust-call" API.
+fn closure_as_fn_str<'tcx>(infcx: &InferCtxt<'_, 'tcx>, ty: Ty<'tcx>) -> String {
+ let ty::Closure(_, substs) = ty.kind() else { unreachable!() };
+ let fn_sig = substs.as_closure().sig();
+ let args = fn_sig
+ .inputs()
+ .skip_binder()
+ .iter()
+ .next()
+ .map(|args| {
+ args.tuple_fields()
+ .iter()
+ .map(|arg| ty_to_string(infcx, arg))
+ .collect::<Vec<_>>()
+ .join(", ")
+ })
+ .unwrap_or_default();
+ let ret = if fn_sig.output().skip_binder().is_unit() {
+ String::new()
+ } else {
+ format!(" -> {}", ty_to_string(infcx, fn_sig.output().skip_binder()))
+ };
+ format!("fn({}){}", args, ret)
+}
+
+impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
+ /// Extracts data used by diagnostic for either types or constants
+ /// which were stuck during inference.
+ pub fn extract_inference_diagnostics_data(
+ &self,
+ arg: GenericArg<'tcx>,
+ highlight: Option<ty::print::RegionHighlightMode<'tcx>>,
+ ) -> InferenceDiagnosticsData {
+ match arg.unpack() {
+ GenericArgKind::Type(ty) => {
+ if let ty::Infer(ty::TyVar(ty_vid)) = *ty.kind() {
+ let mut inner = self.inner.borrow_mut();
+ let ty_vars = &inner.type_variables();
+ let var_origin = ty_vars.var_origin(ty_vid);
+ if let TypeVariableOriginKind::TypeParameterDefinition(name, def_id) =
+ var_origin.kind
+ {
+ if name != kw::SelfUpper {
+ return InferenceDiagnosticsData {
+ name: name.to_string(),
+ span: Some(var_origin.span),
+ kind: UnderspecifiedArgKind::Type {
+ prefix: "type parameter".into(),
+ },
+ parent: def_id.and_then(|def_id| {
+ InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id)
+ }),
+ };
+ }
+ }
+ }
+
+ let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS);
+ if let Some(highlight) = highlight {
+ printer.region_highlight_mode = highlight;
+ }
+ InferenceDiagnosticsData {
+ name: ty.print(printer).unwrap().into_buffer(),
+ span: None,
+ kind: UnderspecifiedArgKind::Type { prefix: ty.prefix_string(self.tcx) },
+ parent: None,
+ }
+ }
+ GenericArgKind::Const(ct) => {
+ if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
+ let origin =
+ self.inner.borrow_mut().const_unification_table().probe_value(vid).origin;
+ if let ConstVariableOriginKind::ConstParameterDefinition(name, def_id) =
+ origin.kind
+ {
+ return InferenceDiagnosticsData {
+ name: name.to_string(),
+ span: Some(origin.span),
+ kind: UnderspecifiedArgKind::Const { is_parameter: true },
+ parent: InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id),
+ };
+ }
+
+ debug_assert!(!origin.span.is_dummy());
+ let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::ValueNS);
+ if let Some(highlight) = highlight {
+ printer.region_highlight_mode = highlight;
+ }
+ InferenceDiagnosticsData {
+ name: ct.print(printer).unwrap().into_buffer(),
+ span: Some(origin.span),
+ kind: UnderspecifiedArgKind::Const { is_parameter: false },
+ parent: None,
+ }
+ } else {
+ // If we end up here the `FindInferSourceVisitor`
+ // won't work, as its expected argument isn't an inference variable.
+ //
+ // FIXME: Ideally we should look into the generic constant
+ // to figure out which inference var is actually unresolved so that
+ // this path is unreachable.
+ let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::ValueNS);
+ if let Some(highlight) = highlight {
+ printer.region_highlight_mode = highlight;
+ }
+ InferenceDiagnosticsData {
+ name: ct.print(printer).unwrap().into_buffer(),
+ span: None,
+ kind: UnderspecifiedArgKind::Const { is_parameter: false },
+ parent: None,
+ }
+ }
+ }
+ GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"),
+ }
+ }
+
+ /// Used as a fallback in [InferCtxt::emit_inference_failure_err]
+ /// in case we weren't able to get a better error.
+ fn bad_inference_failure_err(
+ &self,
+ span: Span,
+ arg_data: InferenceDiagnosticsData,
+ error_code: TypeAnnotationNeeded,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ let error_code = error_code.into();
+ let mut err =
+ self.tcx.sess.struct_span_err_with_code(span, "type annotations needed", error_code);
+ err.span_label(span, arg_data.cannot_infer_msg());
+ err
+ }
+
+ pub fn emit_inference_failure_err(
+ &self,
+ body_id: Option<hir::BodyId>,
+ failure_span: Span,
+ arg: GenericArg<'tcx>,
+ error_code: TypeAnnotationNeeded,
+ should_label_span: bool,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ let arg = self.resolve_vars_if_possible(arg);
+ let arg_data = self.extract_inference_diagnostics_data(arg, None);
+
+ let Some(typeck_results) = self.in_progress_typeck_results else {
+ // If we don't have any typeck results we're outside
+ // of a body, so we won't be able to get better info
+ // here.
+ return self.bad_inference_failure_err(failure_span, arg_data, error_code);
+ };
+ let typeck_results = typeck_results.borrow();
+ let typeck_results = &typeck_results;
+
+ let mut local_visitor = FindInferSourceVisitor::new(&self, typeck_results, arg);
+ if let Some(body_id) = body_id {
+ let expr = self.tcx.hir().expect_expr(body_id.hir_id);
+ local_visitor.visit_expr(expr);
+ }
+
+ let Some(InferSource { span, kind }) = local_visitor.infer_source else {
+ return self.bad_inference_failure_err(failure_span, arg_data, error_code)
+ };
+
+ let error_code = error_code.into();
+ let mut err = self.tcx.sess.struct_span_err_with_code(
+ span,
+ &format!("type annotations needed{}", kind.ty_msg(self)),
+ error_code,
+ );
+
+ if should_label_span && !failure_span.overlaps(span) {
+ err.span_label(failure_span, "type must be known at this point");
+ }
+
+ match kind {
+ InferSourceKind::LetBinding { insert_span, pattern_name, ty } => {
+ let suggestion_msg = if let Some(name) = pattern_name {
+ format!(
+ "consider giving `{}` an explicit type{}",
+ name,
+ arg_data.where_x_is_specified(ty)
+ )
+ } else {
+ format!(
+ "consider giving this pattern a type{}",
+ arg_data.where_x_is_specified(ty)
+ )
+ };
+ err.span_suggestion_verbose(
+ insert_span,
+ &suggestion_msg,
+ format!(": {}", ty_to_string(self, ty)),
+ Applicability::HasPlaceholders,
+ );
+ }
+ InferSourceKind::ClosureArg { insert_span, ty } => {
+ err.span_suggestion_verbose(
+ insert_span,
+ &format!(
+ "consider giving this closure parameter an explicit type{}",
+ arg_data.where_x_is_specified(ty)
+ ),
+ format!(": {}", ty_to_string(self, ty)),
+ Applicability::HasPlaceholders,
+ );
+ }
+ InferSourceKind::GenericArg {
+ insert_span,
+ argument_index,
+ generics_def_id,
+ def_id: _,
+ generic_args,
+ } => {
+ let generics = self.tcx.generics_of(generics_def_id);
+ let is_type = matches!(arg.unpack(), GenericArgKind::Type(_));
+
+ let cannot_infer_msg = format!(
+ "cannot infer {} of the {} parameter `{}`{}",
+ if is_type { "type" } else { "the value" },
+ if is_type { "type" } else { "const" },
+ generics.params[argument_index].name,
+ // We use the `generics_def_id` here, as even when suggesting `None::<T>`,
+ // the type parameter `T` was still declared on the enum, not on the
+ // variant.
+ InferenceDiagnosticsParentData::for_parent_def_id(self.tcx, generics_def_id)
+ .map_or(String::new(), |parent| parent.suffix_string()),
+ );
+
+ err.span_label(span, cannot_infer_msg);
+
+ let args = fmt_printer(self, Namespace::TypeNS)
+ .comma_sep(generic_args.iter().copied().map(|arg| {
+ if arg.is_suggestable(self.tcx, true) {
+ return arg;
+ }
+
+ match arg.unpack() {
+ GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"),
+ GenericArgKind::Type(_) => self
+ .next_ty_var(TypeVariableOrigin {
+ span: rustc_span::DUMMY_SP,
+ kind: TypeVariableOriginKind::MiscVariable,
+ })
+ .into(),
+ GenericArgKind::Const(arg) => self
+ .next_const_var(
+ arg.ty(),
+ ConstVariableOrigin {
+ span: rustc_span::DUMMY_SP,
+ kind: ConstVariableOriginKind::MiscVariable,
+ },
+ )
+ .into(),
+ }
+ }))
+ .unwrap()
+ .into_buffer();
+
+ err.span_suggestion_verbose(
+ insert_span,
+ &format!(
+ "consider specifying the generic argument{}",
+ pluralize!(generic_args.len()),
+ ),
+ format!("::<{}>", args),
+ Applicability::HasPlaceholders,
+ );
+ }
+ InferSourceKind::FullyQualifiedMethodCall { receiver, successor, substs, def_id } => {
+ let printer = fmt_printer(self, Namespace::ValueNS);
+ let def_path = printer.print_def_path(def_id, substs).unwrap().into_buffer();
+
+ // We only care about whether we have to add `&` or `&mut ` for now.
+ // This is the case if the last adjustment is a borrow and the
+ // first adjustment was not a builtin deref.
+ let adjustment = match typeck_results.expr_adjustments(receiver) {
+ [
+ Adjustment { kind: Adjust::Deref(None), target: _ },
+ ..,
+ Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), target: _ },
+ ] => "",
+ [
+ ..,
+ Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mut_)), target: _ },
+ ] => match mut_ {
+ AutoBorrowMutability::Mut { .. } => "&mut ",
+ AutoBorrowMutability::Not => "&",
+ },
+ _ => "",
+ };
+
+ let suggestion = vec![
+ (receiver.span.shrink_to_lo(), format!("{def_path}({adjustment}")),
+ (receiver.span.shrink_to_hi().with_hi(successor.1), successor.0.to_string()),
+ ];
+ err.multipart_suggestion_verbose(
+ "try using a fully qualified path to specify the expected types",
+ suggestion,
+ Applicability::HasPlaceholders,
+ );
+ }
+ InferSourceKind::ClosureReturn { ty, data, should_wrap_expr } => {
+ let ret = ty_to_string(self, ty);
+ let (arrow, post) = match data {
+ FnRetTy::DefaultReturn(_) => ("-> ", " "),
+ _ => ("", ""),
+ };
+ let suggestion = match should_wrap_expr {
+ Some(end_span) => vec![
+ (data.span(), format!("{}{}{}{{ ", arrow, ret, post)),
+ (end_span, " }".to_string()),
+ ],
+ None => vec![(data.span(), format!("{}{}{}", arrow, ret, post))],
+ };
+ err.multipart_suggestion_verbose(
+ "try giving this closure an explicit return type",
+ suggestion,
+ Applicability::HasPlaceholders,
+ );
+ }
+ }
+ err
+ }
+
+ pub fn need_type_info_err_in_generator(
+ &self,
+ kind: hir::GeneratorKind,
+ span: Span,
+ ty: Ty<'tcx>,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ let ty = self.resolve_vars_if_possible(ty);
+ let data = self.extract_inference_diagnostics_data(ty.into(), None);
+
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0698,
+ "type inside {} must be known in this context",
+ kind,
+ );
+ err.span_label(span, data.cannot_infer_msg());
+ err
+ }
+}
+
+#[derive(Debug)]
+struct InferSource<'tcx> {
+ span: Span,
+ kind: InferSourceKind<'tcx>,
+}
+
+#[derive(Debug)]
+enum InferSourceKind<'tcx> {
+ LetBinding {
+ insert_span: Span,
+ pattern_name: Option<Ident>,
+ ty: Ty<'tcx>,
+ },
+ ClosureArg {
+ insert_span: Span,
+ ty: Ty<'tcx>,
+ },
+ GenericArg {
+ insert_span: Span,
+ argument_index: usize,
+ generics_def_id: DefId,
+ def_id: DefId,
+ generic_args: &'tcx [GenericArg<'tcx>],
+ },
+ FullyQualifiedMethodCall {
+ receiver: &'tcx Expr<'tcx>,
+ /// If the method has other arguments, this is ", " and the start of the first argument,
+ /// while for methods without arguments this is ")" and the end of the method call.
+ successor: (&'static str, BytePos),
+ substs: SubstsRef<'tcx>,
+ def_id: DefId,
+ },
+ ClosureReturn {
+ ty: Ty<'tcx>,
+ data: &'tcx FnRetTy<'tcx>,
+ should_wrap_expr: Option<Span>,
+ },
+}
+
+impl<'tcx> InferSource<'tcx> {
+ fn from_expansion(&self) -> bool {
+ let source_from_expansion = match self.kind {
+ InferSourceKind::LetBinding { insert_span, .. }
+ | InferSourceKind::ClosureArg { insert_span, .. }
+ | InferSourceKind::GenericArg { insert_span, .. } => insert_span.from_expansion(),
+ InferSourceKind::FullyQualifiedMethodCall { receiver, .. } => {
+ receiver.span.from_expansion()
+ }
+ InferSourceKind::ClosureReturn { data, should_wrap_expr, .. } => {
+ data.span().from_expansion() || should_wrap_expr.map_or(false, Span::from_expansion)
+ }
+ };
+ source_from_expansion || self.span.from_expansion()
+ }
+}
+
+impl<'tcx> InferSourceKind<'tcx> {
+ fn ty_msg(&self, infcx: &InferCtxt<'_, 'tcx>) -> String {
+ match *self {
+ InferSourceKind::LetBinding { ty, .. }
+ | InferSourceKind::ClosureArg { ty, .. }
+ | InferSourceKind::ClosureReturn { ty, .. } => {
+ if ty.is_closure() {
+ format!(" for the closure `{}`", closure_as_fn_str(infcx, ty))
+ } else if !ty.is_ty_infer() {
+ format!(" for `{}`", ty_to_string(infcx, ty))
+ } else {
+ String::new()
+ }
+ }
+ // FIXME: We should be able to add some additional info here.
+ InferSourceKind::GenericArg { .. }
+ | InferSourceKind::FullyQualifiedMethodCall { .. } => String::new(),
+ }
+ }
+}
+
+#[derive(Debug)]
+struct InsertableGenericArgs<'tcx> {
+ insert_span: Span,
+ substs: SubstsRef<'tcx>,
+ generics_def_id: DefId,
+ def_id: DefId,
+}
+
+/// A visitor which searches for the "best" spot to use in the inference error.
+///
+/// For this it walks over the hir body and tries to check all places where
+/// inference variables could be bound.
+///
+/// While doing so, the currently best spot is stored in `infer_source`.
+/// For details on how we rank spots, see [Self::source_cost]
+struct FindInferSourceVisitor<'a, 'tcx> {
+ infcx: &'a InferCtxt<'a, 'tcx>,
+ typeck_results: &'a TypeckResults<'tcx>,
+
+ target: GenericArg<'tcx>,
+
+ attempt: usize,
+ infer_source_cost: usize,
+ infer_source: Option<InferSource<'tcx>>,
+}
+
+impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
+ fn new(
+ infcx: &'a InferCtxt<'a, 'tcx>,
+ typeck_results: &'a TypeckResults<'tcx>,
+ target: GenericArg<'tcx>,
+ ) -> Self {
+ FindInferSourceVisitor {
+ infcx,
+ typeck_results,
+
+ target,
+
+ attempt: 0,
+ infer_source_cost: usize::MAX,
+ infer_source: None,
+ }
+ }
+
+ /// Computes cost for the given source.
+ ///
+ /// Sources with a small cost are prefer and should result
+ /// in a clearer and idiomatic suggestion.
+ fn source_cost(&self, source: &InferSource<'tcx>) -> usize {
+ #[derive(Clone, Copy)]
+ struct CostCtxt<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ }
+ impl<'tcx> CostCtxt<'tcx> {
+ fn arg_cost(self, arg: GenericArg<'tcx>) -> usize {
+ match arg.unpack() {
+ GenericArgKind::Lifetime(_) => 0, // erased
+ GenericArgKind::Type(ty) => self.ty_cost(ty),
+ GenericArgKind::Const(_) => 3, // some non-zero value
+ }
+ }
+ fn ty_cost(self, ty: Ty<'tcx>) -> usize {
+ match *ty.kind() {
+ ty::Closure(..) => 1000,
+ ty::FnDef(..) => 150,
+ ty::FnPtr(..) => 30,
+ ty::Adt(def, substs) => {
+ 5 + self
+ .tcx
+ .generics_of(def.did())
+ .own_substs_no_defaults(self.tcx, substs)
+ .iter()
+ .map(|&arg| self.arg_cost(arg))
+ .sum::<usize>()
+ }
+ ty::Tuple(args) => 5 + args.iter().map(|arg| self.ty_cost(arg)).sum::<usize>(),
+ ty::Ref(_, ty, _) => 2 + self.ty_cost(ty),
+ ty::Infer(..) => 0,
+ _ => 1,
+ }
+ }
+ }
+
+ // The sources are listed in order of preference here.
+ let tcx = self.infcx.tcx;
+ let ctx = CostCtxt { tcx };
+ let base_cost = match source.kind {
+ InferSourceKind::LetBinding { ty, .. } => ctx.ty_cost(ty),
+ InferSourceKind::ClosureArg { ty, .. } => ctx.ty_cost(ty),
+ InferSourceKind::GenericArg { def_id, generic_args, .. } => {
+ let variant_cost = match tcx.def_kind(def_id) {
+ // `None::<u32>` and friends are ugly.
+ DefKind::Variant | DefKind::Ctor(CtorOf::Variant, _) => 15,
+ _ => 10,
+ };
+ variant_cost + generic_args.iter().map(|&arg| ctx.arg_cost(arg)).sum::<usize>()
+ }
+ InferSourceKind::FullyQualifiedMethodCall { substs, .. } => {
+ 20 + substs.iter().map(|arg| ctx.arg_cost(arg)).sum::<usize>()
+ }
+ InferSourceKind::ClosureReturn { ty, should_wrap_expr, .. } => {
+ 30 + ctx.ty_cost(ty) + if should_wrap_expr.is_some() { 10 } else { 0 }
+ }
+ };
+
+ let suggestion_may_apply = if source.from_expansion() { 10000 } else { 0 };
+
+ base_cost + suggestion_may_apply
+ }
+
+ /// Uses `fn source_cost` to determine whether this inference source is preferable to
+ /// previous sources. We generally prefer earlier sources.
+ #[instrument(level = "debug", skip(self))]
+ fn update_infer_source(&mut self, new_source: InferSource<'tcx>) {
+ let cost = self.source_cost(&new_source) + self.attempt;
+ debug!(?cost);
+ self.attempt += 1;
+ if cost < self.infer_source_cost {
+ self.infer_source_cost = cost;
+ self.infer_source = Some(new_source);
+ }
+ }
+
+ fn node_substs_opt(&self, hir_id: HirId) -> Option<SubstsRef<'tcx>> {
+ let substs = self.typeck_results.node_substs_opt(hir_id);
+ self.infcx.resolve_vars_if_possible(substs)
+ }
+
+ fn opt_node_type(&self, hir_id: HirId) -> Option<Ty<'tcx>> {
+ let ty = self.typeck_results.node_type_opt(hir_id);
+ self.infcx.resolve_vars_if_possible(ty)
+ }
+
+ // Check whether this generic argument is the inference variable we
+ // are looking for.
+ fn generic_arg_is_target(&self, arg: GenericArg<'tcx>) -> bool {
+ if arg == self.target {
+ return true;
+ }
+
+ match (arg.unpack(), self.target.unpack()) {
+ (GenericArgKind::Type(inner_ty), GenericArgKind::Type(target_ty)) => {
+ use ty::{Infer, TyVar};
+ match (inner_ty.kind(), target_ty.kind()) {
+ (&Infer(TyVar(a_vid)), &Infer(TyVar(b_vid))) => {
+ self.infcx.inner.borrow_mut().type_variables().sub_unified(a_vid, b_vid)
+ }
+ _ => false,
+ }
+ }
+ (GenericArgKind::Const(inner_ct), GenericArgKind::Const(target_ct)) => {
+ use ty::InferConst::*;
+ match (inner_ct.kind(), target_ct.kind()) {
+ (ty::ConstKind::Infer(Var(a_vid)), ty::ConstKind::Infer(Var(b_vid))) => self
+ .infcx
+ .inner
+ .borrow_mut()
+ .const_unification_table()
+ .unioned(a_vid, b_vid),
+ _ => false,
+ }
+ }
+ _ => false,
+ }
+ }
+
+ /// Does this generic argument contain our target inference variable
+ /// in a way which can be written by the user.
+ fn generic_arg_contains_target(&self, arg: GenericArg<'tcx>) -> bool {
+ let mut walker = arg.walk();
+ while let Some(inner) = walker.next() {
+ if self.generic_arg_is_target(inner) {
+ return true;
+ }
+ match inner.unpack() {
+ GenericArgKind::Lifetime(_) => {}
+ GenericArgKind::Type(ty) => {
+ if matches!(ty.kind(), ty::Opaque(..) | ty::Closure(..) | ty::Generator(..)) {
+ // Opaque types can't be named by the user right now.
+ //
+ // Both the generic arguments of closures and generators can
+ // also not be named. We may want to only look into the closure
+ // signature in case it has no captures, as that can be represented
+ // using `fn(T) -> R`.
+
+ // FIXME(type_alias_impl_trait): These opaque types
+ // can actually be named, so it would make sense to
+ // adjust this case and add a test for it.
+ walker.skip_current_subtree();
+ }
+ }
+ GenericArgKind::Const(ct) => {
+ if matches!(ct.kind(), ty::ConstKind::Unevaluated(..)) {
+ // You can't write the generic arguments for
+ // unevaluated constants.
+ walker.skip_current_subtree();
+ }
+ }
+ }
+ }
+ false
+ }
+
+ fn expr_inferred_subst_iter(
+ &self,
+ expr: &'tcx hir::Expr<'tcx>,
+ ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
+ let tcx = self.infcx.tcx;
+ match expr.kind {
+ hir::ExprKind::Path(ref path) => {
+ if let Some(substs) = self.node_substs_opt(expr.hir_id) {
+ return self.path_inferred_subst_iter(expr.hir_id, substs, path);
+ }
+ }
+ // FIXME(#98711): Ideally we would also deal with type relative
+ // paths here, even if that is quite rare.
+ //
+ // See the `need_type_info/expr-struct-type-relative-gat.rs` test
+ // for an example where that would be needed.
+ //
+ // However, the `type_dependent_def_id` for `Self::Output` in an
+ // impl is currently the `DefId` of `Output` in the trait definition
+ // which makes this somewhat difficult and prevents us from just
+ // using `self.path_inferred_subst_iter` here.
+ hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _) => {
+ if let Some(ty) = self.opt_node_type(expr.hir_id) {
+ if let ty::Adt(_, substs) = ty.kind() {
+ return Box::new(self.resolved_path_inferred_subst_iter(path, substs));
+ }
+ }
+ }
+ hir::ExprKind::MethodCall(segment, _, _) => {
+ if let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) {
+ let generics = tcx.generics_of(def_id);
+ let insertable: Option<_> = try {
+ if generics.has_impl_trait() {
+ None?
+ }
+ let substs = self.node_substs_opt(expr.hir_id)?;
+ let span = tcx.hir().span(segment.hir_id?);
+ let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
+ InsertableGenericArgs {
+ insert_span,
+ substs,
+ generics_def_id: def_id,
+ def_id,
+ }
+ };
+ return Box::new(insertable.into_iter());
+ }
+ }
+ _ => {}
+ }
+
+ Box::new(iter::empty())
+ }
+
+ fn resolved_path_inferred_subst_iter(
+ &self,
+ path: &'tcx hir::Path<'tcx>,
+ substs: SubstsRef<'tcx>,
+ ) -> impl Iterator<Item = InsertableGenericArgs<'tcx>> + 'a {
+ let tcx = self.infcx.tcx;
+ // The last segment of a path often has `Res::Err` and the
+ // correct `Res` is the one of the whole path.
+ //
+ // FIXME: We deal with that one separately for now,
+ // would be good to remove this special case.
+ let last_segment_using_path_data: Option<_> = try {
+ let generics_def_id = tcx.res_generics_def_id(path.res)?;
+ let generics = tcx.generics_of(generics_def_id);
+ if generics.has_impl_trait() {
+ None?
+ }
+ let insert_span =
+ path.segments.last().unwrap().ident.span.shrink_to_hi().with_hi(path.span.hi());
+ InsertableGenericArgs {
+ insert_span,
+ substs,
+ generics_def_id,
+ def_id: path.res.def_id(),
+ }
+ };
+
+ path.segments
+ .iter()
+ .filter_map(move |segment| {
+ let res = segment.res?;
+ let generics_def_id = tcx.res_generics_def_id(res)?;
+ let generics = tcx.generics_of(generics_def_id);
+ if generics.has_impl_trait() {
+ return None;
+ }
+ let span = tcx.hir().span(segment.hir_id?);
+ let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
+ Some(InsertableGenericArgs {
+ insert_span,
+ substs,
+ generics_def_id,
+ def_id: res.def_id(),
+ })
+ })
+ .chain(last_segment_using_path_data)
+ }
+
+ fn path_inferred_subst_iter(
+ &self,
+ hir_id: HirId,
+ substs: SubstsRef<'tcx>,
+ qpath: &'tcx hir::QPath<'tcx>,
+ ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
+ let tcx = self.infcx.tcx;
+ match qpath {
+ hir::QPath::Resolved(_self_ty, path) => {
+ Box::new(self.resolved_path_inferred_subst_iter(path, substs))
+ }
+ hir::QPath::TypeRelative(ty, segment) => {
+ let Some(def_id) = self.typeck_results.type_dependent_def_id(hir_id) else {
+ return Box::new(iter::empty());
+ };
+
+ let generics = tcx.generics_of(def_id);
+ let segment: Option<_> = try {
+ if !segment.infer_args || generics.has_impl_trait() {
+ None?;
+ }
+ let span = tcx.hir().span(segment.hir_id?);
+ let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
+ InsertableGenericArgs { insert_span, substs, generics_def_id: def_id, def_id }
+ };
+
+ let parent_def_id = generics.parent.unwrap();
+ if tcx.def_kind(parent_def_id) == DefKind::Impl {
+ let parent_ty = tcx.bound_type_of(parent_def_id).subst(tcx, substs);
+ match (parent_ty.kind(), &ty.kind) {
+ (
+ ty::Adt(def, substs),
+ hir::TyKind::Path(hir::QPath::Resolved(_self_ty, path)),
+ ) => {
+ if tcx.res_generics_def_id(path.res) != Some(def.did()) {
+ match path.res {
+ Res::Def(DefKind::TyAlias, _) => {
+ // FIXME: Ideally we should support this. For that
+ // we have to map back from the self type to the
+ // type alias though. That's difficult.
+ //
+ // See the `need_type_info/type-alias.rs` test for
+ // some examples.
+ }
+ // There cannot be inference variables in the self type,
+ // so there's nothing for us to do here.
+ Res::SelfTy { .. } => {}
+ _ => warn!(
+ "unexpected path: def={:?} substs={:?} path={:?}",
+ def, substs, path,
+ ),
+ }
+ } else {
+ return Box::new(
+ self.resolved_path_inferred_subst_iter(path, substs)
+ .chain(segment),
+ );
+ }
+ }
+ _ => (),
+ }
+ }
+
+ Box::new(segment.into_iter())
+ }
+ hir::QPath::LangItem(_, _, _) => Box::new(iter::empty()),
+ }
+ }
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> {
+ type NestedFilter = nested_filter::OnlyBodies;
+
+ fn nested_visit_map(&mut self) -> Self::Map {
+ self.infcx.tcx.hir()
+ }
+
+ fn visit_local(&mut self, local: &'tcx Local<'tcx>) {
+ intravisit::walk_local(self, local);
+
+ if let Some(ty) = self.opt_node_type(local.hir_id) {
+ if self.generic_arg_contains_target(ty.into()) {
+ match local.source {
+ LocalSource::Normal if local.ty.is_none() => {
+ self.update_infer_source(InferSource {
+ span: local.pat.span,
+ kind: InferSourceKind::LetBinding {
+ insert_span: local.pat.span.shrink_to_hi(),
+ pattern_name: local.pat.simple_ident(),
+ ty,
+ },
+ })
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+
+ /// For closures, we first visit the parameters and then the content,
+ /// as we prefer those.
+ fn visit_body(&mut self, body: &'tcx Body<'tcx>) {
+ for param in body.params {
+ debug!(
+ "param: span {:?}, ty_span {:?}, pat.span {:?}",
+ param.span, param.ty_span, param.pat.span
+ );
+ if param.ty_span != param.pat.span {
+ debug!("skipping param: has explicit type");
+ continue;
+ }
+
+ let Some(param_ty) = self.opt_node_type(param.hir_id) else {
+ continue
+ };
+
+ if self.generic_arg_contains_target(param_ty.into()) {
+ self.update_infer_source(InferSource {
+ span: param.pat.span,
+ kind: InferSourceKind::ClosureArg {
+ insert_span: param.pat.span.shrink_to_hi(),
+ ty: param_ty,
+ },
+ })
+ }
+ }
+ intravisit::walk_body(self, body);
+ }
+
+ #[instrument(level = "debug", skip(self))]
+ fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
+ let tcx = self.infcx.tcx;
+ match expr.kind {
+ // When encountering `func(arg)` first look into `arg` and then `func`,
+ // as `arg` is "more specific".
+ ExprKind::Call(func, args) => {
+ for arg in args {
+ self.visit_expr(arg);
+ }
+ self.visit_expr(func);
+ }
+ _ => intravisit::walk_expr(self, expr),
+ }
+
+ for args in self.expr_inferred_subst_iter(expr) {
+ debug!(?args);
+ let InsertableGenericArgs { insert_span, substs, generics_def_id, def_id } = args;
+ let generics = tcx.generics_of(generics_def_id);
+ if let Some(argument_index) = generics
+ .own_substs(substs)
+ .iter()
+ .position(|&arg| self.generic_arg_contains_target(arg))
+ {
+ let substs = self.infcx.resolve_vars_if_possible(substs);
+ let generic_args = &generics.own_substs_no_defaults(tcx, substs)
+ [generics.own_counts().lifetimes..];
+ let span = match expr.kind {
+ ExprKind::MethodCall(path, _, _) => path.ident.span,
+ _ => expr.span,
+ };
+
+ self.update_infer_source(InferSource {
+ span,
+ kind: InferSourceKind::GenericArg {
+ insert_span,
+ argument_index,
+ generics_def_id,
+ def_id,
+ generic_args,
+ },
+ });
+ }
+ }
+
+ if let Some(node_ty) = self.opt_node_type(expr.hir_id) {
+ if let (
+ &ExprKind::Closure(&Closure { fn_decl, body, fn_decl_span, .. }),
+ ty::Closure(_, substs),
+ ) = (&expr.kind, node_ty.kind())
+ {
+ let output = substs.as_closure().sig().output().skip_binder();
+ if self.generic_arg_contains_target(output.into()) {
+ let body = self.infcx.tcx.hir().body(body);
+ let should_wrap_expr = if matches!(body.value.kind, ExprKind::Block(..)) {
+ None
+ } else {
+ Some(body.value.span.shrink_to_hi())
+ };
+ self.update_infer_source(InferSource {
+ span: fn_decl_span,
+ kind: InferSourceKind::ClosureReturn {
+ ty: output,
+ data: &fn_decl.output,
+ should_wrap_expr,
+ },
+ })
+ }
+ }
+ }
+
+ let has_impl_trait = |def_id| {
+ iter::successors(Some(tcx.generics_of(def_id)), |generics| {
+ generics.parent.map(|def_id| tcx.generics_of(def_id))
+ })
+ .any(|generics| generics.has_impl_trait())
+ };
+ if let ExprKind::MethodCall(path, args, span) = expr.kind
+ && let Some(substs) = self.node_substs_opt(expr.hir_id)
+ && substs.iter().any(|arg| self.generic_arg_contains_target(arg))
+ && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id)
+ && self.infcx.tcx.trait_of_item(def_id).is_some()
+ && !has_impl_trait(def_id)
+ {
+ let successor =
+ args.get(1).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo()));
+ let substs = self.infcx.resolve_vars_if_possible(substs);
+ self.update_infer_source(InferSource {
+ span: path.ident.span,
+ kind: InferSourceKind::FullyQualifiedMethodCall {
+ receiver: args.first().unwrap(),
+ successor,
+ substs,
+ def_id,
+ }
+ })
+ }
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs
new file mode 100644
index 000000000..9a2ab3e32
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs
@@ -0,0 +1,234 @@
+//! Error Reporting for Anonymous Region Lifetime Errors
+//! where both the regions are anonymous.
+
+use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
+use crate::infer::error_reporting::nice_region_error::util::AnonymousParamInfo;
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::SubregionOrigin;
+use crate::infer::TyCtxt;
+
+use rustc_errors::{struct_span_err, Applicability, Diagnostic, ErrorGuaranteed};
+use rustc_hir as hir;
+use rustc_hir::{GenericParamKind, Ty};
+use rustc_middle::ty::Region;
+use rustc_span::symbol::kw;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ /// Print the error message for lifetime errors when both the concerned regions are anonymous.
+ ///
+ /// Consider a case where we have
+ ///
+ /// ```compile_fail,E0623
+ /// fn foo(x: &mut Vec<&u8>, y: &u8) {
+ /// x.push(y);
+ /// }
+ /// ```
+ ///
+ /// The example gives
+ ///
+ /// ```text
+ /// fn foo(x: &mut Vec<&u8>, y: &u8) {
+ /// --- --- these references are declared with different lifetimes...
+ /// x.push(y);
+ /// ^ ...but data from `y` flows into `x` here
+ /// ```
+ ///
+ /// It has been extended for the case of structs too.
+ ///
+ /// Consider the example
+ ///
+ /// ```no_run
+ /// struct Ref<'a> { x: &'a u32 }
+ /// ```
+ ///
+ /// ```text
+ /// fn foo(mut x: Vec<Ref>, y: Ref) {
+ /// --- --- these structs are declared with different lifetimes...
+ /// x.push(y);
+ /// ^ ...but data from `y` flows into `x` here
+ /// }
+ /// ```
+ ///
+ /// It will later be extended to trait objects.
+ pub(super) fn try_report_anon_anon_conflict(&self) -> Option<ErrorGuaranteed> {
+ let (span, sub, sup) = self.regions()?;
+
+ if let Some(RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::ReferenceOutlivesReferent(..),
+ ..,
+ )) = self.error
+ {
+ // This error doesn't make much sense in this case.
+ return None;
+ }
+
+ // Determine whether the sub and sup consist of both anonymous (elided) regions.
+ let anon_reg_sup = self.tcx().is_suitable_region(sup)?;
+
+ let anon_reg_sub = self.tcx().is_suitable_region(sub)?;
+ let scope_def_id_sup = anon_reg_sup.def_id;
+ let bregion_sup = anon_reg_sup.boundregion;
+ let scope_def_id_sub = anon_reg_sub.def_id;
+ let bregion_sub = anon_reg_sub.boundregion;
+
+ let ty_sup = find_anon_type(self.tcx(), sup, &bregion_sup)?;
+
+ let ty_sub = find_anon_type(self.tcx(), sub, &bregion_sub)?;
+
+ debug!(
+ "try_report_anon_anon_conflict: found_param1={:?} sup={:?} br1={:?}",
+ ty_sub, sup, bregion_sup
+ );
+ debug!(
+ "try_report_anon_anon_conflict: found_param2={:?} sub={:?} br2={:?}",
+ ty_sup, sub, bregion_sub
+ );
+
+ let (ty_sup, ty_fndecl_sup) = ty_sup;
+ let (ty_sub, ty_fndecl_sub) = ty_sub;
+
+ let AnonymousParamInfo { param: anon_param_sup, .. } =
+ self.find_param_with_region(sup, sup)?;
+ let AnonymousParamInfo { param: anon_param_sub, .. } =
+ self.find_param_with_region(sub, sub)?;
+
+ let sup_is_ret_type =
+ self.is_return_type_anon(scope_def_id_sup, bregion_sup, ty_fndecl_sup);
+ let sub_is_ret_type =
+ self.is_return_type_anon(scope_def_id_sub, bregion_sub, ty_fndecl_sub);
+
+ let span_label_var1 = match anon_param_sup.pat.simple_ident() {
+ Some(simple_ident) => format!(" from `{}`", simple_ident),
+ None => String::new(),
+ };
+
+ let span_label_var2 = match anon_param_sub.pat.simple_ident() {
+ Some(simple_ident) => format!(" into `{}`", simple_ident),
+ None => String::new(),
+ };
+
+ debug!(
+ "try_report_anon_anon_conflict: sub_is_ret_type={:?} sup_is_ret_type={:?}",
+ sub_is_ret_type, sup_is_ret_type
+ );
+
+ let mut err = struct_span_err!(self.tcx().sess, span, E0623, "lifetime mismatch");
+
+ match (sup_is_ret_type, sub_is_ret_type) {
+ (ret_capture @ Some(ret_span), _) | (_, ret_capture @ Some(ret_span)) => {
+ let param_span =
+ if sup_is_ret_type == ret_capture { ty_sub.span } else { ty_sup.span };
+
+ err.span_label(
+ param_span,
+ "this parameter and the return type are declared with different lifetimes...",
+ );
+ err.span_label(ret_span, "");
+ err.span_label(span, format!("...but data{} is returned here", span_label_var1));
+ }
+
+ (None, None) => {
+ if ty_sup.hir_id == ty_sub.hir_id {
+ err.span_label(ty_sup.span, "this type is declared with multiple lifetimes...");
+ err.span_label(ty_sub.span, "");
+ err.span_label(span, "...but data with one lifetime flows into the other here");
+ } else {
+ err.span_label(
+ ty_sup.span,
+ "these two types are declared with different lifetimes...",
+ );
+ err.span_label(ty_sub.span, "");
+ err.span_label(
+ span,
+ format!("...but data{} flows{} here", span_label_var1, span_label_var2),
+ );
+ }
+ }
+ }
+
+ if suggest_adding_lifetime_params(self.tcx(), sub, ty_sup, ty_sub, &mut err) {
+ err.note("each elided lifetime in input position becomes a distinct lifetime");
+ }
+
+ let reported = err.emit();
+ Some(reported)
+ }
+}
+
+pub fn suggest_adding_lifetime_params<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ sub: Region<'tcx>,
+ ty_sup: &Ty<'_>,
+ ty_sub: &Ty<'_>,
+ err: &mut Diagnostic,
+) -> bool {
+ let (
+ hir::Ty { kind: hir::TyKind::Rptr(lifetime_sub, _), .. },
+ hir::Ty { kind: hir::TyKind::Rptr(lifetime_sup, _), .. },
+ ) = (ty_sub, ty_sup) else {
+ return false;
+ };
+
+ if !lifetime_sub.name.is_anonymous() || !lifetime_sup.name.is_anonymous() {
+ return false;
+ };
+
+ let Some(anon_reg) = tcx.is_suitable_region(sub) else {
+ return false;
+ };
+
+ let hir_id = tcx.hir().local_def_id_to_hir_id(anon_reg.def_id);
+
+ let node = tcx.hir().get(hir_id);
+ let is_impl = matches!(&node, hir::Node::ImplItem(_));
+ let generics = match node {
+ hir::Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, ref generics, ..), .. })
+ | hir::Node::TraitItem(&hir::TraitItem { ref generics, .. })
+ | hir::Node::ImplItem(&hir::ImplItem { ref generics, .. }) => generics,
+ _ => return false,
+ };
+
+ let suggestion_param_name = generics
+ .params
+ .iter()
+ .filter(|p| matches!(p.kind, GenericParamKind::Lifetime { .. }))
+ .map(|p| p.name.ident().name)
+ .find(|i| *i != kw::UnderscoreLifetime);
+ let introduce_new = suggestion_param_name.is_none();
+ let suggestion_param_name =
+ suggestion_param_name.map(|n| n.to_string()).unwrap_or_else(|| "'a".to_owned());
+
+ debug!(?lifetime_sup.span);
+ debug!(?lifetime_sub.span);
+ let make_suggestion = |span: rustc_span::Span| {
+ if span.is_empty() {
+ (span, format!("{}, ", suggestion_param_name))
+ } else if let Ok("&") = tcx.sess.source_map().span_to_snippet(span).as_deref() {
+ (span.shrink_to_hi(), format!("{} ", suggestion_param_name))
+ } else {
+ (span, suggestion_param_name.clone())
+ }
+ };
+ let mut suggestions =
+ vec![make_suggestion(lifetime_sub.span), make_suggestion(lifetime_sup.span)];
+
+ if introduce_new {
+ let new_param_suggestion =
+ if let Some(first) = generics.params.iter().find(|p| !p.name.ident().span.is_empty()) {
+ (first.span.shrink_to_lo(), format!("{}, ", suggestion_param_name))
+ } else {
+ (generics.span, format!("<{}>", suggestion_param_name))
+ };
+
+ suggestions.push(new_param_suggestion);
+ }
+
+ let mut sugg = String::from("consider introducing a named lifetime parameter");
+ if is_impl {
+ sugg.push_str(" and update trait if needed");
+ }
+ err.multipart_suggestion(sugg, suggestions, Applicability::MaybeIncorrect);
+
+ true
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs
new file mode 100644
index 000000000..c1b201da6
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs
@@ -0,0 +1,234 @@
+use rustc_hir as hir;
+use rustc_hir::intravisit::{self, Visitor};
+use rustc_middle::hir::map::Map;
+use rustc_middle::hir::nested_filter;
+use rustc_middle::middle::resolve_lifetime as rl;
+use rustc_middle::ty::{self, Region, TyCtxt};
+
+/// This function calls the `visit_ty` method for the parameters
+/// corresponding to the anonymous regions. The `nested_visitor.found_type`
+/// contains the anonymous type.
+///
+/// # Arguments
+/// region - the anonymous region corresponding to the anon_anon conflict
+/// br - the bound region corresponding to the above region which is of type `BrAnon(_)`
+///
+/// # Example
+/// ```compile_fail,E0623
+/// fn foo(x: &mut Vec<&u8>, y: &u8)
+/// { x.push(y); }
+/// ```
+/// The function returns the nested type corresponding to the anonymous region
+/// for e.g., `&u8` and `Vec<&u8>`.
+pub fn find_anon_type<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ region: Region<'tcx>,
+ br: &ty::BoundRegionKind,
+) -> Option<(&'tcx hir::Ty<'tcx>, &'tcx hir::FnSig<'tcx>)> {
+ let anon_reg = tcx.is_suitable_region(region)?;
+ let hir_id = tcx.hir().local_def_id_to_hir_id(anon_reg.def_id);
+ let fn_sig = tcx.hir().get(hir_id).fn_sig()?;
+
+ fn_sig
+ .decl
+ .inputs
+ .iter()
+ .find_map(|arg| find_component_for_bound_region(tcx, arg, br))
+ .map(|ty| (ty, fn_sig))
+}
+
+// This method creates a FindNestedTypeVisitor which returns the type corresponding
+// to the anonymous region.
+fn find_component_for_bound_region<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ arg: &'tcx hir::Ty<'tcx>,
+ br: &ty::BoundRegionKind,
+) -> Option<&'tcx hir::Ty<'tcx>> {
+ let mut nested_visitor = FindNestedTypeVisitor {
+ tcx,
+ bound_region: *br,
+ found_type: None,
+ current_index: ty::INNERMOST,
+ };
+ nested_visitor.visit_ty(arg);
+ nested_visitor.found_type
+}
+
+// The FindNestedTypeVisitor captures the corresponding `hir::Ty` of the
+// anonymous region. The example above would lead to a conflict between
+// the two anonymous lifetimes for &u8 in x and y respectively. This visitor
+// would be invoked twice, once for each lifetime, and would
+// walk the types like &mut Vec<&u8> and &u8 looking for the HIR
+// where that lifetime appears. This allows us to highlight the
+// specific part of the type in the error message.
+struct FindNestedTypeVisitor<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ // The bound_region corresponding to the Refree(freeregion)
+ // associated with the anonymous region we are looking for.
+ bound_region: ty::BoundRegionKind,
+ // The type where the anonymous lifetime appears
+ // for e.g., Vec<`&u8`> and <`&u8`>
+ found_type: Option<&'tcx hir::Ty<'tcx>>,
+ current_index: ty::DebruijnIndex,
+}
+
+impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> {
+ type NestedFilter = nested_filter::OnlyBodies;
+
+ fn nested_visit_map(&mut self) -> Self::Map {
+ self.tcx.hir()
+ }
+
+ fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
+ match arg.kind {
+ hir::TyKind::BareFn(_) => {
+ self.current_index.shift_in(1);
+ intravisit::walk_ty(self, arg);
+ self.current_index.shift_out(1);
+ return;
+ }
+
+ hir::TyKind::TraitObject(bounds, ..) => {
+ for bound in bounds {
+ self.current_index.shift_in(1);
+ self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
+ self.current_index.shift_out(1);
+ }
+ }
+
+ hir::TyKind::Rptr(ref lifetime, _) => {
+ // the lifetime of the TyRptr
+ let hir_id = lifetime.hir_id;
+ match (self.tcx.named_region(hir_id), self.bound_region) {
+ // Find the index of the named region that was part of the
+ // error. We will then search the function parameters for a bound
+ // region at the right depth with the same index
+ (Some(rl::Region::EarlyBound(_, id)), ty::BrNamed(def_id, _)) => {
+ debug!("EarlyBound id={:?} def_id={:?}", id, def_id);
+ if id == def_id {
+ self.found_type = Some(arg);
+ return; // we can stop visiting now
+ }
+ }
+
+ // Find the index of the named region that was part of the
+ // error. We will then search the function parameters for a bound
+ // region at the right depth with the same index
+ (
+ Some(rl::Region::LateBound(debruijn_index, _, id)),
+ ty::BrNamed(def_id, _),
+ ) => {
+ debug!(
+ "FindNestedTypeVisitor::visit_ty: LateBound depth = {:?}",
+ debruijn_index
+ );
+ debug!("LateBound id={:?} def_id={:?}", id, def_id);
+ if debruijn_index == self.current_index && id == def_id {
+ self.found_type = Some(arg);
+ return; // we can stop visiting now
+ }
+ }
+
+ (
+ Some(
+ rl::Region::Static
+ | rl::Region::Free(_, _)
+ | rl::Region::EarlyBound(_, _)
+ | rl::Region::LateBound(_, _, _),
+ )
+ | None,
+ _,
+ ) => {
+ debug!("no arg found");
+ }
+ }
+ }
+ // Checks if it is of type `hir::TyKind::Path` which corresponds to a struct.
+ hir::TyKind::Path(_) => {
+ let subvisitor = &mut TyPathVisitor {
+ tcx: self.tcx,
+ found_it: false,
+ bound_region: self.bound_region,
+ current_index: self.current_index,
+ };
+ intravisit::walk_ty(subvisitor, arg); // call walk_ty; as visit_ty is empty,
+ // this will visit only outermost type
+ if subvisitor.found_it {
+ self.found_type = Some(arg);
+ }
+ }
+ _ => {}
+ }
+ // walk the embedded contents: e.g., if we are visiting `Vec<&Foo>`,
+ // go on to visit `&Foo`
+ intravisit::walk_ty(self, arg);
+ }
+}
+
+// The visitor captures the corresponding `hir::Ty` of the anonymous region
+// in the case of structs ie. `hir::TyKind::Path`.
+// This visitor would be invoked for each lifetime corresponding to a struct,
+// and would walk the types like Vec<Ref> in the above example and Ref looking for the HIR
+// where that lifetime appears. This allows us to highlight the
+// specific part of the type in the error message.
+struct TyPathVisitor<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ found_it: bool,
+ bound_region: ty::BoundRegionKind,
+ current_index: ty::DebruijnIndex,
+}
+
+impl<'tcx> Visitor<'tcx> for TyPathVisitor<'tcx> {
+ type NestedFilter = nested_filter::OnlyBodies;
+
+ fn nested_visit_map(&mut self) -> Map<'tcx> {
+ self.tcx.hir()
+ }
+
+ fn visit_lifetime(&mut self, lifetime: &hir::Lifetime) {
+ match (self.tcx.named_region(lifetime.hir_id), self.bound_region) {
+ // the lifetime of the TyPath!
+ (Some(rl::Region::EarlyBound(_, id)), ty::BrNamed(def_id, _)) => {
+ debug!("EarlyBound id={:?} def_id={:?}", id, def_id);
+ if id == def_id {
+ self.found_it = true;
+ return; // we can stop visiting now
+ }
+ }
+
+ (Some(rl::Region::LateBound(debruijn_index, _, id)), ty::BrNamed(def_id, _)) => {
+ debug!("FindNestedTypeVisitor::visit_ty: LateBound depth = {:?}", debruijn_index,);
+ debug!("id={:?}", id);
+ debug!("def_id={:?}", def_id);
+ if debruijn_index == self.current_index && id == def_id {
+ self.found_it = true;
+ return; // we can stop visiting now
+ }
+ }
+
+ (
+ Some(
+ rl::Region::Static
+ | rl::Region::EarlyBound(_, _)
+ | rl::Region::LateBound(_, _, _)
+ | rl::Region::Free(_, _),
+ )
+ | None,
+ _,
+ ) => {
+ debug!("no arg found");
+ }
+ }
+ }
+
+ fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
+ // ignore nested types
+ //
+ // If you have a type like `Foo<'a, &Ty>` we
+ // are only interested in the immediate lifetimes ('a).
+ //
+ // Making `visit_ty` empty will ignore the `&Ty` embedded
+ // inside, it will get reached by the outer visitor.
+ debug!("`Ty` corresponding to a struct is {:?}", arg);
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs
new file mode 100644
index 000000000..893ca3cf7
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs
@@ -0,0 +1,102 @@
+//! Error Reporting for when the lifetime for a type doesn't match the `impl` selected for a predicate
+//! to hold.
+
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::error_reporting::note_and_explain_region;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::{SubregionOrigin, TypeTrace};
+use crate::traits::ObligationCauseCode;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
+use rustc_hir as hir;
+use rustc_hir::intravisit::Visitor;
+use rustc_middle::ty::TypeVisitor;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ pub(super) fn try_report_mismatched_static_lifetime(&self) -> Option<ErrorGuaranteed> {
+ let error = self.error.as_ref()?;
+ debug!("try_report_mismatched_static_lifetime {:?}", error);
+
+ let RegionResolutionError::ConcreteFailure(origin, sub, sup) = error.clone() else {
+ return None;
+ };
+ if !sub.is_static() {
+ return None;
+ }
+ let SubregionOrigin::Subtype(box TypeTrace { ref cause, .. }) = origin else {
+ return None;
+ };
+ // If we added a "points at argument expression" obligation, we remove it here, we care
+ // about the original obligation only.
+ let code = match cause.code() {
+ ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => &*parent_code,
+ code => code,
+ };
+ let ObligationCauseCode::MatchImpl(parent, impl_def_id) = code else {
+ return None;
+ };
+ let ObligationCauseCode::BindingObligation(_def_id, binding_span) = *parent.code() else {
+ return None;
+ };
+ let mut err = self.tcx().sess.struct_span_err(cause.span, "incompatible lifetime on type");
+ // FIXME: we should point at the lifetime
+ let mut multi_span: MultiSpan = vec![binding_span].into();
+ multi_span.push_span_label(binding_span, "introduces a `'static` lifetime requirement");
+ err.span_note(multi_span, "because this has an unmet lifetime requirement");
+ note_and_explain_region(self.tcx(), &mut err, "", sup, "...", Some(binding_span));
+ if let Some(impl_node) = self.tcx().hir().get_if_local(*impl_def_id) {
+ // If an impl is local, then maybe this isn't what they want. Try to
+ // be as helpful as possible with implicit lifetimes.
+
+ // First, let's get the hir self type of the impl
+ let hir::Node::Item(hir::Item {
+ kind: hir::ItemKind::Impl(hir::Impl { self_ty: impl_self_ty, .. }),
+ ..
+ }) = impl_node else {
+ bug!("Node not an impl.");
+ };
+
+ // Next, let's figure out the set of trait objects with implicit static bounds
+ let ty = self.tcx().type_of(*impl_def_id);
+ let mut v = super::static_impl_trait::TraitObjectVisitor(FxHashSet::default());
+ v.visit_ty(ty);
+ let mut traits = vec![];
+ for matching_def_id in v.0 {
+ let mut hir_v =
+ super::static_impl_trait::HirTraitObjectVisitor(&mut traits, matching_def_id);
+ hir_v.visit_ty(&impl_self_ty);
+ }
+
+ if traits.is_empty() {
+ // If there are no trait object traits to point at, either because
+ // there aren't trait objects or because none are implicit, then just
+ // write a single note on the impl itself.
+
+ let impl_span = self.tcx().def_span(*impl_def_id);
+ err.span_note(impl_span, "...does not necessarily outlive the static lifetime introduced by the compatible `impl`");
+ } else {
+ // Otherwise, point at all implicit static lifetimes
+
+ err.note("...does not necessarily outlive the static lifetime introduced by the compatible `impl`");
+ for span in &traits {
+ err.span_note(*span, "this has an implicit `'static` lifetime requirement");
+ // It would be nice to put this immediately under the above note, but they get
+ // pushed to the end.
+ err.span_suggestion_verbose(
+ span.shrink_to_hi(),
+ "consider relaxing the implicit `'static` requirement",
+ " + '_",
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ } else {
+ // Otherwise just point out the impl.
+
+ let impl_span = self.tcx().def_span(*impl_def_id);
+ err.span_note(impl_span, "...does not necessarily outlive the static lifetime introduced by the compatible `impl`");
+ }
+ let reported = err.emit();
+ Some(reported)
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mod.rs
new file mode 100644
index 000000000..53d9acf7d
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mod.rs
@@ -0,0 +1,77 @@
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError::*;
+use crate::infer::InferCtxt;
+use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed};
+use rustc_middle::ty::{self, TyCtxt};
+use rustc_span::source_map::Span;
+
+mod different_lifetimes;
+pub mod find_anon_type;
+mod mismatched_static_lifetime;
+mod named_anon_conflict;
+mod placeholder_error;
+mod static_impl_trait;
+mod trait_impl_difference;
+mod util;
+
+pub use different_lifetimes::suggest_adding_lifetime_params;
+pub use find_anon_type::find_anon_type;
+pub use static_impl_trait::{suggest_new_region_bound, HirTraitObjectVisitor, TraitObjectVisitor};
+pub use util::find_param_with_region;
+
+impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
+ pub fn try_report_nice_region_error(&self, error: &RegionResolutionError<'tcx>) -> bool {
+ NiceRegionError::new(self, error.clone()).try_report().is_some()
+ }
+}
+
+pub struct NiceRegionError<'cx, 'tcx> {
+ infcx: &'cx InferCtxt<'cx, 'tcx>,
+ error: Option<RegionResolutionError<'tcx>>,
+ regions: Option<(Span, ty::Region<'tcx>, ty::Region<'tcx>)>,
+}
+
+impl<'cx, 'tcx> NiceRegionError<'cx, 'tcx> {
+ pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>, error: RegionResolutionError<'tcx>) -> Self {
+ Self { infcx, error: Some(error), regions: None }
+ }
+
+ pub fn new_from_span(
+ infcx: &'cx InferCtxt<'cx, 'tcx>,
+ span: Span,
+ sub: ty::Region<'tcx>,
+ sup: ty::Region<'tcx>,
+ ) -> Self {
+ Self { infcx, error: None, regions: Some((span, sub, sup)) }
+ }
+
+ fn tcx(&self) -> TyCtxt<'tcx> {
+ self.infcx.tcx
+ }
+
+ pub fn try_report_from_nll(&self) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
+ // Due to the improved diagnostics returned by the MIR borrow checker, only a subset of
+ // the nice region errors are required when running under the MIR borrow checker.
+ self.try_report_named_anon_conflict().or_else(|| self.try_report_placeholder_conflict())
+ }
+
+ pub fn try_report(&self) -> Option<ErrorGuaranteed> {
+ self.try_report_from_nll()
+ .map(|mut diag| diag.emit())
+ .or_else(|| self.try_report_impl_not_conforming_to_trait())
+ .or_else(|| self.try_report_anon_anon_conflict())
+ .or_else(|| self.try_report_static_impl_trait())
+ .or_else(|| self.try_report_mismatched_static_lifetime())
+ }
+
+ pub(super) fn regions(&self) -> Option<(Span, ty::Region<'tcx>, ty::Region<'tcx>)> {
+ match (&self.error, self.regions) {
+ (Some(ConcreteFailure(origin, sub, sup)), None) => Some((origin.span(), *sub, *sup)),
+ (Some(SubSupConflict(_, _, origin, sub, _, sup, _)), None) => {
+ Some((origin.span(), *sub, *sup))
+ }
+ (None, Some((span, sub, sup))) => Some((span, sub, sup)),
+ _ => None,
+ }
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs
new file mode 100644
index 000000000..76cb76d9f
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/named_anon_conflict.rs
@@ -0,0 +1,116 @@
+//! Error Reporting for Anonymous Region Lifetime Errors
+//! where one region is named and the other is anonymous.
+use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
+use rustc_middle::ty;
+use rustc_span::symbol::kw;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ /// When given a `ConcreteFailure` for a function with parameters containing a named region and
+ /// an anonymous region, emit an descriptive diagnostic error.
+ pub(super) fn try_report_named_anon_conflict(
+ &self,
+ ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
+ let (span, sub, sup) = self.regions()?;
+
+ debug!(
+ "try_report_named_anon_conflict(sub={:?}, sup={:?}, error={:?})",
+ sub, sup, self.error,
+ );
+
+ // Determine whether the sub and sup consist of one named region ('a)
+ // and one anonymous (elided) region. If so, find the parameter arg
+ // where the anonymous region appears (there must always be one; we
+ // only introduced anonymous regions in parameters) as well as a
+ // version new_ty of its type where the anonymous region is replaced
+ // with the named one.
+ let (named, anon, anon_param_info, region_info) = if sub.has_name()
+ && self.tcx().is_suitable_region(sup).is_some()
+ && self.find_param_with_region(sup, sub).is_some()
+ {
+ (
+ sub,
+ sup,
+ self.find_param_with_region(sup, sub).unwrap(),
+ self.tcx().is_suitable_region(sup).unwrap(),
+ )
+ } else if sup.has_name()
+ && self.tcx().is_suitable_region(sub).is_some()
+ && self.find_param_with_region(sub, sup).is_some()
+ {
+ (
+ sup,
+ sub,
+ self.find_param_with_region(sub, sup).unwrap(),
+ self.tcx().is_suitable_region(sub).unwrap(),
+ )
+ } else {
+ return None; // inapplicable
+ };
+
+ // Suggesting to add a `'static` lifetime to a parameter is nearly always incorrect,
+ // and can steer users down the wrong path.
+ if named.is_static() {
+ return None;
+ }
+
+ debug!("try_report_named_anon_conflict: named = {:?}", named);
+ debug!("try_report_named_anon_conflict: anon_param_info = {:?}", anon_param_info);
+ debug!("try_report_named_anon_conflict: region_info = {:?}", region_info);
+
+ let param = anon_param_info.param;
+ let new_ty = anon_param_info.param_ty;
+ let new_ty_span = anon_param_info.param_ty_span;
+ let br = anon_param_info.bound_region;
+ let is_first = anon_param_info.is_first;
+ let scope_def_id = region_info.def_id;
+ let is_impl_item = region_info.is_impl_item;
+
+ match br {
+ ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) => {}
+ _ => {
+ /* not an anonymous region */
+ debug!("try_report_named_anon_conflict: not an anonymous region");
+ return None;
+ }
+ }
+
+ if is_impl_item {
+ debug!("try_report_named_anon_conflict: impl item, bail out");
+ return None;
+ }
+
+ if find_anon_type(self.tcx(), anon, &br).is_some()
+ && self.is_self_anon(is_first, scope_def_id)
+ {
+ return None;
+ }
+
+ let (error_var, span_label_var) = match param.pat.simple_ident() {
+ Some(simple_ident) => (
+ format!("the type of `{}`", simple_ident),
+ format!("the type of `{}`", simple_ident),
+ ),
+ None => ("parameter type".to_owned(), "type".to_owned()),
+ };
+
+ let mut diag = struct_span_err!(
+ self.tcx().sess,
+ span,
+ E0621,
+ "explicit lifetime required in {}",
+ error_var
+ );
+
+ diag.span_label(span, format!("lifetime `{}` required", named));
+ diag.span_suggestion(
+ new_ty_span,
+ &format!("add explicit lifetime `{}` to {}", named, span_label_var),
+ new_ty,
+ Applicability::Unspecified,
+ );
+
+ Some(diag)
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs
new file mode 100644
index 000000000..998699158
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs
@@ -0,0 +1,501 @@
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::ValuePairs;
+use crate::infer::{SubregionOrigin, TypeTrace};
+use crate::traits::{ObligationCause, ObligationCauseCode};
+use rustc_data_structures::intern::Interned;
+use rustc_errors::{Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
+use rustc_hir::def::Namespace;
+use rustc_hir::def_id::DefId;
+use rustc_middle::ty::error::ExpectedFound;
+use rustc_middle::ty::print::{FmtPrinter, Print, RegionHighlightMode};
+use rustc_middle::ty::subst::SubstsRef;
+use rustc_middle::ty::{self, RePlaceholder, ReVar, Region, TyCtxt};
+
+use std::fmt::{self, Write};
+
+impl<'tcx> NiceRegionError<'_, 'tcx> {
+ /// When given a `ConcreteFailure` for a function with arguments containing a named region and
+ /// an anonymous region, emit a descriptive diagnostic error.
+ pub(super) fn try_report_placeholder_conflict(
+ &self,
+ ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
+ match &self.error {
+ ///////////////////////////////////////////////////////////////////////////
+ // NB. The ordering of cases in this match is very
+ // sensitive, because we are often matching against
+ // specific cases and then using an `_` to match all
+ // others.
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Check for errors from comparing trait failures -- first
+ // with two placeholders, then with one.
+ Some(RegionResolutionError::SubSupConflict(
+ vid,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ Some(*sub_placeholder),
+ Some(*sup_placeholder),
+ values,
+ ),
+
+ Some(RegionResolutionError::SubSupConflict(
+ vid,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ _,
+ _,
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ Some(*sub_placeholder),
+ None,
+ values,
+ ),
+
+ Some(RegionResolutionError::SubSupConflict(
+ vid,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ _,
+ _,
+ sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ None,
+ Some(*sup_placeholder),
+ values,
+ ),
+
+ Some(RegionResolutionError::SubSupConflict(
+ vid,
+ _,
+ _,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ _,
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ None,
+ Some(*sup_placeholder),
+ values,
+ ),
+
+ Some(RegionResolutionError::UpperBoundUniverseConflict(
+ vid,
+ _,
+ _,
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sup_placeholder @ Region(Interned(RePlaceholder(_), _)),
+ )) => self.try_report_trait_placeholder_mismatch(
+ Some(self.tcx().mk_region(ReVar(*vid))),
+ cause,
+ None,
+ Some(*sup_placeholder),
+ values,
+ ),
+
+ Some(RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_region @ Region(Interned(RePlaceholder(_), _)),
+ sup_region @ Region(Interned(RePlaceholder(_), _)),
+ )) => self.try_report_trait_placeholder_mismatch(
+ None,
+ cause,
+ Some(*sub_region),
+ Some(*sup_region),
+ values,
+ ),
+
+ Some(RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_region @ Region(Interned(RePlaceholder(_), _)),
+ sup_region,
+ )) => self.try_report_trait_placeholder_mismatch(
+ (!sup_region.has_name()).then_some(*sup_region),
+ cause,
+ Some(*sub_region),
+ None,
+ values,
+ ),
+
+ Some(RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::Subtype(box TypeTrace { cause, values }),
+ sub_region,
+ sup_region @ Region(Interned(RePlaceholder(_), _)),
+ )) => self.try_report_trait_placeholder_mismatch(
+ (!sub_region.has_name()).then_some(*sub_region),
+ cause,
+ None,
+ Some(*sup_region),
+ values,
+ ),
+
+ _ => None,
+ }
+ }
+
+ fn try_report_trait_placeholder_mismatch(
+ &self,
+ vid: Option<Region<'tcx>>,
+ cause: &ObligationCause<'tcx>,
+ sub_placeholder: Option<Region<'tcx>>,
+ sup_placeholder: Option<Region<'tcx>>,
+ value_pairs: &ValuePairs<'tcx>,
+ ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
+ let (expected_substs, found_substs, trait_def_id) = match value_pairs {
+ ValuePairs::TraitRefs(ExpectedFound { expected, found })
+ if expected.def_id == found.def_id =>
+ {
+ (expected.substs, found.substs, expected.def_id)
+ }
+ ValuePairs::PolyTraitRefs(ExpectedFound { expected, found })
+ if expected.def_id() == found.def_id() =>
+ {
+ // It's possible that the placeholders come from a binder
+ // outside of this value pair. Use `no_bound_vars` as a
+ // simple heuristic for that.
+ (expected.no_bound_vars()?.substs, found.no_bound_vars()?.substs, expected.def_id())
+ }
+ _ => return None,
+ };
+
+ Some(self.report_trait_placeholder_mismatch(
+ vid,
+ cause,
+ sub_placeholder,
+ sup_placeholder,
+ trait_def_id,
+ expected_substs,
+ found_substs,
+ ))
+ }
+
+ // error[E0308]: implementation of `Foo` does not apply to enough lifetimes
+ // --> /home/nmatsakis/tmp/foo.rs:12:5
+ // |
+ // 12 | all::<&'static u32>();
+ // | ^^^^^^^^^^^^^^^^^^^ lifetime mismatch
+ // |
+ // = note: Due to a where-clause on the function `all`,
+ // = note: `T` must implement `...` for any two lifetimes `'1` and `'2`.
+ // = note: However, the type `T` only implements `...` for some specific lifetime `'2`.
+ #[instrument(level = "debug", skip(self))]
+ fn report_trait_placeholder_mismatch(
+ &self,
+ vid: Option<Region<'tcx>>,
+ cause: &ObligationCause<'tcx>,
+ sub_placeholder: Option<Region<'tcx>>,
+ sup_placeholder: Option<Region<'tcx>>,
+ trait_def_id: DefId,
+ expected_substs: SubstsRef<'tcx>,
+ actual_substs: SubstsRef<'tcx>,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ let span = cause.span();
+ let msg = format!(
+ "implementation of `{}` is not general enough",
+ self.tcx().def_path_str(trait_def_id),
+ );
+ let mut err = self.tcx().sess.struct_span_err(span, &msg);
+
+ let leading_ellipsis = if let ObligationCauseCode::ItemObligation(def_id) = *cause.code() {
+ err.span_label(span, "doesn't satisfy where-clause");
+ err.span_label(
+ self.tcx().def_span(def_id),
+ &format!("due to a where-clause on `{}`...", self.tcx().def_path_str(def_id)),
+ );
+ true
+ } else {
+ err.span_label(span, &msg);
+ false
+ };
+
+ let expected_trait_ref = self.infcx.resolve_vars_if_possible(ty::TraitRef {
+ def_id: trait_def_id,
+ substs: expected_substs,
+ });
+ let actual_trait_ref = self
+ .infcx
+ .resolve_vars_if_possible(ty::TraitRef { def_id: trait_def_id, substs: actual_substs });
+
+ // Search the expected and actual trait references to see (a)
+ // whether the sub/sup placeholders appear in them (sometimes
+ // you have a trait ref like `T: Foo<fn(&u8)>`, where the
+ // placeholder was created as part of an inner type) and (b)
+ // whether the inference variable appears. In each case,
+ // assign a counter value in each case if so.
+ let mut counter = 0;
+ let mut has_sub = None;
+ let mut has_sup = None;
+
+ let mut actual_has_vid = None;
+ let mut expected_has_vid = None;
+
+ self.tcx().for_each_free_region(&expected_trait_ref, |r| {
+ if Some(r) == sub_placeholder && has_sub.is_none() {
+ has_sub = Some(counter);
+ counter += 1;
+ } else if Some(r) == sup_placeholder && has_sup.is_none() {
+ has_sup = Some(counter);
+ counter += 1;
+ }
+
+ if Some(r) == vid && expected_has_vid.is_none() {
+ expected_has_vid = Some(counter);
+ counter += 1;
+ }
+ });
+
+ self.tcx().for_each_free_region(&actual_trait_ref, |r| {
+ if Some(r) == vid && actual_has_vid.is_none() {
+ actual_has_vid = Some(counter);
+ counter += 1;
+ }
+ });
+
+ let actual_self_ty_has_vid =
+ self.tcx().any_free_region_meets(&actual_trait_ref.self_ty(), |r| Some(r) == vid);
+
+ let expected_self_ty_has_vid =
+ self.tcx().any_free_region_meets(&expected_trait_ref.self_ty(), |r| Some(r) == vid);
+
+ let any_self_ty_has_vid = actual_self_ty_has_vid || expected_self_ty_has_vid;
+
+ debug!(
+ ?actual_has_vid,
+ ?expected_has_vid,
+ ?has_sub,
+ ?has_sup,
+ ?actual_self_ty_has_vid,
+ ?expected_self_ty_has_vid,
+ );
+
+ self.explain_actual_impl_that_was_found(
+ &mut err,
+ sub_placeholder,
+ sup_placeholder,
+ has_sub,
+ has_sup,
+ expected_trait_ref,
+ actual_trait_ref,
+ vid,
+ expected_has_vid,
+ actual_has_vid,
+ any_self_ty_has_vid,
+ leading_ellipsis,
+ );
+
+ err
+ }
+
+ /// Add notes with details about the expected and actual trait refs, with attention to cases
+ /// when placeholder regions are involved: either the trait or the self type containing
+ /// them needs to be mentioned the closest to the placeholders.
+ /// This makes the error messages read better, however at the cost of some complexity
+ /// due to the number of combinations we have to deal with.
+ fn explain_actual_impl_that_was_found(
+ &self,
+ err: &mut Diagnostic,
+ sub_placeholder: Option<Region<'tcx>>,
+ sup_placeholder: Option<Region<'tcx>>,
+ has_sub: Option<usize>,
+ has_sup: Option<usize>,
+ expected_trait_ref: ty::TraitRef<'tcx>,
+ actual_trait_ref: ty::TraitRef<'tcx>,
+ vid: Option<Region<'tcx>>,
+ expected_has_vid: Option<usize>,
+ actual_has_vid: Option<usize>,
+ any_self_ty_has_vid: bool,
+ leading_ellipsis: bool,
+ ) {
+ // HACK(eddyb) maybe move this in a more central location.
+ #[derive(Copy, Clone)]
+ struct Highlighted<'tcx, T> {
+ tcx: TyCtxt<'tcx>,
+ highlight: RegionHighlightMode<'tcx>,
+ value: T,
+ }
+
+ impl<'tcx, T> Highlighted<'tcx, T> {
+ fn map<U>(self, f: impl FnOnce(T) -> U) -> Highlighted<'tcx, U> {
+ Highlighted { tcx: self.tcx, highlight: self.highlight, value: f(self.value) }
+ }
+ }
+
+ impl<'tcx, T> fmt::Display for Highlighted<'tcx, T>
+ where
+ T: for<'a> Print<
+ 'tcx,
+ FmtPrinter<'a, 'tcx>,
+ Error = fmt::Error,
+ Output = FmtPrinter<'a, 'tcx>,
+ >,
+ {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS);
+ printer.region_highlight_mode = self.highlight;
+
+ let s = self.value.print(printer)?.into_buffer();
+ f.write_str(&s)
+ }
+ }
+
+ // The weird thing here with the `maybe_highlighting_region` calls and the
+ // the match inside is meant to be like this:
+ //
+ // - The match checks whether the given things (placeholders, etc) appear
+ // in the types are about to print
+ // - Meanwhile, the `maybe_highlighting_region` calls set up
+ // highlights so that, if they do appear, we will replace
+ // them `'0` and whatever. (This replacement takes place
+ // inside the closure given to `maybe_highlighting_region`.)
+ //
+ // There is some duplication between the calls -- i.e., the
+ // `maybe_highlighting_region` checks if (e.g.) `has_sub` is
+ // None, an then we check again inside the closure, but this
+ // setup sort of minimized the number of calls and so form.
+
+ let highlight_trait_ref = |trait_ref| Highlighted {
+ tcx: self.tcx(),
+ highlight: RegionHighlightMode::new(self.tcx()),
+ value: trait_ref,
+ };
+
+ let same_self_type = actual_trait_ref.self_ty() == expected_trait_ref.self_ty();
+
+ let mut expected_trait_ref = highlight_trait_ref(expected_trait_ref);
+ expected_trait_ref.highlight.maybe_highlighting_region(sub_placeholder, has_sub);
+ expected_trait_ref.highlight.maybe_highlighting_region(sup_placeholder, has_sup);
+ err.note(&{
+ let passive_voice = match (has_sub, has_sup) {
+ (Some(_), _) | (_, Some(_)) => any_self_ty_has_vid,
+ (None, None) => {
+ expected_trait_ref.highlight.maybe_highlighting_region(vid, expected_has_vid);
+ match expected_has_vid {
+ Some(_) => true,
+ None => any_self_ty_has_vid,
+ }
+ }
+ };
+
+ let mut note = if same_self_type {
+ let mut self_ty = expected_trait_ref.map(|tr| tr.self_ty());
+ self_ty.highlight.maybe_highlighting_region(vid, actual_has_vid);
+
+ if self_ty.value.is_closure()
+ && self
+ .tcx()
+ .fn_trait_kind_from_lang_item(expected_trait_ref.value.def_id)
+ .is_some()
+ {
+ let closure_sig = self_ty.map(|closure| {
+ if let ty::Closure(_, substs) = closure.kind() {
+ self.tcx().signature_unclosure(
+ substs.as_closure().sig(),
+ rustc_hir::Unsafety::Normal,
+ )
+ } else {
+ bug!("type is not longer closure");
+ }
+ });
+
+ format!(
+ "{}closure with signature `{}` must implement `{}`",
+ if leading_ellipsis { "..." } else { "" },
+ closure_sig,
+ expected_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ } else {
+ format!(
+ "{}`{}` must implement `{}`",
+ if leading_ellipsis { "..." } else { "" },
+ self_ty,
+ expected_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ }
+ } else if passive_voice {
+ format!(
+ "{}`{}` would have to be implemented for the type `{}`",
+ if leading_ellipsis { "..." } else { "" },
+ expected_trait_ref.map(|tr| tr.print_only_trait_path()),
+ expected_trait_ref.map(|tr| tr.self_ty()),
+ )
+ } else {
+ format!(
+ "{}`{}` must implement `{}`",
+ if leading_ellipsis { "..." } else { "" },
+ expected_trait_ref.map(|tr| tr.self_ty()),
+ expected_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ };
+
+ match (has_sub, has_sup) {
+ (Some(n1), Some(n2)) => {
+ let _ = write!(
+ note,
+ ", for any two lifetimes `'{}` and `'{}`...",
+ std::cmp::min(n1, n2),
+ std::cmp::max(n1, n2),
+ );
+ }
+ (Some(n), _) | (_, Some(n)) => {
+ let _ = write!(note, ", for any lifetime `'{}`...", n,);
+ }
+ (None, None) => {
+ if let Some(n) = expected_has_vid {
+ let _ = write!(note, ", for some specific lifetime `'{}`...", n,);
+ }
+ }
+ }
+
+ note
+ });
+
+ let mut actual_trait_ref = highlight_trait_ref(actual_trait_ref);
+ actual_trait_ref.highlight.maybe_highlighting_region(vid, actual_has_vid);
+ err.note(&{
+ let passive_voice = match actual_has_vid {
+ Some(_) => any_self_ty_has_vid,
+ None => true,
+ };
+
+ let mut note = if same_self_type {
+ format!(
+ "...but it actually implements `{}`",
+ actual_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ } else if passive_voice {
+ format!(
+ "...but `{}` is actually implemented for the type `{}`",
+ actual_trait_ref.map(|tr| tr.print_only_trait_path()),
+ actual_trait_ref.map(|tr| tr.self_ty()),
+ )
+ } else {
+ format!(
+ "...but `{}` actually implements `{}`",
+ actual_trait_ref.map(|tr| tr.self_ty()),
+ actual_trait_ref.map(|tr| tr.print_only_trait_path()),
+ )
+ };
+
+ if let Some(n) = actual_has_vid {
+ let _ = write!(note, ", for some specific lifetime `'{}`", n);
+ }
+
+ note
+ });
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs
new file mode 100644
index 000000000..9886c572a
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs
@@ -0,0 +1,577 @@
+//! Error Reporting for static impl Traits.
+
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::{SubregionOrigin, TypeTrace};
+use crate::traits::{ObligationCauseCode, UnifyReceiverContext};
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::{struct_span_err, Applicability, Diagnostic, ErrorGuaranteed, MultiSpan};
+use rustc_hir::def_id::DefId;
+use rustc_hir::intravisit::{walk_ty, Visitor};
+use rustc_hir::{self as hir, GenericBound, Item, ItemKind, Lifetime, LifetimeName, Node, TyKind};
+use rustc_middle::ty::{
+ self, AssocItemContainer, StaticLifetimeVisitor, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor,
+};
+use rustc_span::symbol::Ident;
+use rustc_span::Span;
+
+use std::ops::ControlFlow;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ /// Print the error message for lifetime errors when the return type is a static `impl Trait`,
+ /// `dyn Trait` or if a method call on a trait object introduces a static requirement.
+ pub(super) fn try_report_static_impl_trait(&self) -> Option<ErrorGuaranteed> {
+ debug!("try_report_static_impl_trait(error={:?})", self.error);
+ let tcx = self.tcx();
+ let (var_origin, sub_origin, sub_r, sup_origin, sup_r, spans) = match self.error.as_ref()? {
+ RegionResolutionError::SubSupConflict(
+ _,
+ var_origin,
+ sub_origin,
+ sub_r,
+ sup_origin,
+ sup_r,
+ spans,
+ ) if sub_r.is_static() => (var_origin, sub_origin, sub_r, sup_origin, sup_r, spans),
+ RegionResolutionError::ConcreteFailure(
+ SubregionOrigin::Subtype(box TypeTrace { cause, .. }),
+ sub_r,
+ sup_r,
+ ) if sub_r.is_static() => {
+ // This is for an implicit `'static` requirement coming from `impl dyn Trait {}`.
+ if let ObligationCauseCode::UnifyReceiver(ctxt) = cause.code() {
+ // This may have a closure and it would cause ICE
+ // through `find_param_with_region` (#78262).
+ let anon_reg_sup = tcx.is_suitable_region(*sup_r)?;
+ let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.def_id);
+ if fn_returns.is_empty() {
+ return None;
+ }
+
+ let param = self.find_param_with_region(*sup_r, *sub_r)?;
+ let lifetime = if sup_r.has_name() {
+ format!("lifetime `{}`", sup_r)
+ } else {
+ "an anonymous lifetime `'_`".to_string()
+ };
+ let mut err = struct_span_err!(
+ tcx.sess,
+ cause.span,
+ E0772,
+ "{} has {} but calling `{}` introduces an implicit `'static` lifetime \
+ requirement",
+ param
+ .param
+ .pat
+ .simple_ident()
+ .map(|s| format!("`{}`", s))
+ .unwrap_or_else(|| "`fn` parameter".to_string()),
+ lifetime,
+ ctxt.assoc_item.name,
+ );
+ err.span_label(param.param_ty_span, &format!("this data with {}...", lifetime));
+ err.span_label(
+ cause.span,
+ &format!(
+ "...is used and required to live as long as `'static` here \
+ because of an implicit lifetime bound on the {}",
+ match ctxt.assoc_item.container {
+ AssocItemContainer::TraitContainer => {
+ let id = ctxt.assoc_item.container_id(tcx);
+ format!("`impl` of `{}`", tcx.def_path_str(id))
+ }
+ AssocItemContainer::ImplContainer => "inherent `impl`".to_string(),
+ },
+ ),
+ );
+ if self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt) {
+ let reported = err.emit();
+ return Some(reported);
+ } else {
+ err.cancel();
+ }
+ }
+ return None;
+ }
+ _ => return None,
+ };
+ debug!(
+ "try_report_static_impl_trait(var={:?}, sub={:?} {:?} sup={:?} {:?})",
+ var_origin, sub_origin, sub_r, sup_origin, sup_r
+ );
+ let anon_reg_sup = tcx.is_suitable_region(*sup_r)?;
+ debug!("try_report_static_impl_trait: anon_reg_sup={:?}", anon_reg_sup);
+ let sp = var_origin.span();
+ let return_sp = sub_origin.span();
+ let param = self.find_param_with_region(*sup_r, *sub_r)?;
+ let (lifetime_name, lifetime) = if sup_r.has_name() {
+ (sup_r.to_string(), format!("lifetime `{}`", sup_r))
+ } else {
+ ("'_".to_owned(), "an anonymous lifetime `'_`".to_string())
+ };
+ let param_name = param
+ .param
+ .pat
+ .simple_ident()
+ .map(|s| format!("`{}`", s))
+ .unwrap_or_else(|| "`fn` parameter".to_string());
+ let mut err = struct_span_err!(
+ tcx.sess,
+ sp,
+ E0759,
+ "{} has {} but it needs to satisfy a `'static` lifetime requirement",
+ param_name,
+ lifetime,
+ );
+
+ let (mention_influencer, influencer_point) =
+ if sup_origin.span().overlaps(param.param_ty_span) {
+ // Account for `async fn` like in `async-await/issues/issue-62097.rs`.
+ // The desugaring of `async `fn`s causes `sup_origin` and `param` to point at the same
+ // place (but with different `ctxt`, hence `overlaps` instead of `==` above).
+ //
+ // This avoids the following:
+ //
+ // LL | pub async fn run_dummy_fn(&self) {
+ // | ^^^^^
+ // | |
+ // | this data with an anonymous lifetime `'_`...
+ // | ...is captured here...
+ (false, sup_origin.span())
+ } else {
+ (!sup_origin.span().overlaps(return_sp), param.param_ty_span)
+ };
+ err.span_label(influencer_point, &format!("this data with {}...", lifetime));
+
+ debug!("try_report_static_impl_trait: param_info={:?}", param);
+
+ let mut spans = spans.clone();
+
+ if mention_influencer {
+ spans.push(sup_origin.span());
+ }
+ // We dedup the spans *ignoring* expansion context.
+ spans.sort();
+ spans.dedup_by_key(|span| (span.lo(), span.hi()));
+
+ // We try to make the output have fewer overlapping spans if possible.
+ let require_msg = if spans.is_empty() {
+ "...is used and required to live as long as `'static` here"
+ } else {
+ "...and is required to live as long as `'static` here"
+ };
+ let require_span =
+ if sup_origin.span().overlaps(return_sp) { sup_origin.span() } else { return_sp };
+
+ for span in &spans {
+ err.span_label(*span, "...is used here...");
+ }
+
+ if spans.iter().any(|sp| sp.overlaps(return_sp) || *sp > return_sp) {
+ // If any of the "captured here" labels appears on the same line or after
+ // `require_span`, we put it on a note to ensure the text flows by appearing
+ // always at the end.
+ err.span_note(require_span, require_msg);
+ } else {
+ // We don't need a note, it's already at the end, it can be shown as a `span_label`.
+ err.span_label(require_span, require_msg);
+ }
+
+ if let SubregionOrigin::RelateParamBound(_, _, Some(bound)) = sub_origin {
+ err.span_note(*bound, "`'static` lifetime requirement introduced by this bound");
+ }
+ if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = sub_origin {
+ if let ObligationCauseCode::ReturnValue(hir_id)
+ | ObligationCauseCode::BlockTailExpression(hir_id) = cause.code()
+ {
+ let parent_id = tcx.hir().get_parent_item(*hir_id);
+ let parent_id = tcx.hir().local_def_id_to_hir_id(parent_id);
+ if let Some(fn_decl) = tcx.hir().fn_decl_by_hir_id(parent_id) {
+ let mut span: MultiSpan = fn_decl.output.span().into();
+ let mut add_label = true;
+ if let hir::FnRetTy::Return(ty) = fn_decl.output {
+ let mut v = StaticLifetimeVisitor(vec![], tcx.hir());
+ v.visit_ty(ty);
+ if !v.0.is_empty() {
+ span = v.0.clone().into();
+ for sp in v.0 {
+ span.push_span_label(sp, "`'static` requirement introduced here");
+ }
+ add_label = false;
+ }
+ }
+ if add_label {
+ span.push_span_label(
+ fn_decl.output.span(),
+ "requirement introduced by this return type",
+ );
+ }
+ span.push_span_label(cause.span, "because of this returned expression");
+ err.span_note(
+ span,
+ "`'static` lifetime requirement introduced by the return type",
+ );
+ }
+ }
+ }
+
+ let fn_returns = tcx.return_type_impl_or_dyn_traits(anon_reg_sup.def_id);
+
+ let mut override_error_code = None;
+ if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sup_origin
+ && let ObligationCauseCode::UnifyReceiver(ctxt) = cause.code()
+ // Handle case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a
+ // `'static` lifetime when called as a method on a binding: `bar.qux()`.
+ && self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt)
+ {
+ override_error_code = Some(ctxt.assoc_item.name);
+ }
+
+ if let SubregionOrigin::Subtype(box TypeTrace { cause, .. }) = &sub_origin
+ && let code = match cause.code() {
+ ObligationCauseCode::MatchImpl(parent, ..) => parent.code(),
+ _ => cause.code(),
+ }
+ && let (&ObligationCauseCode::ItemObligation(item_def_id), None) = (code, override_error_code)
+ {
+ // Same case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a `'static`
+ // lifetime as above, but called using a fully-qualified path to the method:
+ // `Foo::qux(bar)`.
+ let mut v = TraitObjectVisitor(FxHashSet::default());
+ v.visit_ty(param.param_ty);
+ if let Some((ident, self_ty)) =
+ self.get_impl_ident_and_self_ty_from_trait(item_def_id, &v.0)
+ && self.suggest_constrain_dyn_trait_in_impl(&mut err, &v.0, ident, self_ty)
+ {
+ override_error_code = Some(ident.name);
+ }
+ }
+ if let (Some(ident), true) = (override_error_code, fn_returns.is_empty()) {
+ // Provide a more targeted error code and description.
+ err.code(rustc_errors::error_code!(E0772));
+ err.set_primary_message(&format!(
+ "{} has {} but calling `{}` introduces an implicit `'static` lifetime \
+ requirement",
+ param_name, lifetime, ident,
+ ));
+ }
+
+ let arg = match param.param.pat.simple_ident() {
+ Some(simple_ident) => format!("argument `{}`", simple_ident),
+ None => "the argument".to_string(),
+ };
+ let captures = format!("captures data from {}", arg);
+ suggest_new_region_bound(
+ tcx,
+ &mut err,
+ fn_returns,
+ lifetime_name,
+ Some(arg),
+ captures,
+ Some((param.param_ty_span, param.param_ty.to_string())),
+ );
+
+ let reported = err.emit();
+ Some(reported)
+ }
+}
+
+pub fn suggest_new_region_bound(
+ tcx: TyCtxt<'_>,
+ err: &mut Diagnostic,
+ fn_returns: Vec<&rustc_hir::Ty<'_>>,
+ lifetime_name: String,
+ arg: Option<String>,
+ captures: String,
+ param: Option<(Span, String)>,
+) {
+ debug!("try_report_static_impl_trait: fn_return={:?}", fn_returns);
+ // FIXME: account for the need of parens in `&(dyn Trait + '_)`
+ let consider = "consider changing the";
+ let declare = "to declare that the";
+ let explicit = format!("you can add an explicit `{}` lifetime bound", lifetime_name);
+ let explicit_static =
+ arg.map(|arg| format!("explicit `'static` bound to the lifetime of {}", arg));
+ let add_static_bound = "alternatively, add an explicit `'static` bound to this reference";
+ let plus_lt = format!(" + {}", lifetime_name);
+ for fn_return in fn_returns {
+ if fn_return.span.desugaring_kind().is_some() {
+ // Skip `async` desugaring `impl Future`.
+ continue;
+ }
+ match fn_return.kind {
+ TyKind::OpaqueDef(item_id, _) => {
+ let item = tcx.hir().item(item_id);
+ let ItemKind::OpaqueTy(opaque) = &item.kind else {
+ return;
+ };
+
+ if let Some(span) = opaque
+ .bounds
+ .iter()
+ .filter_map(|arg| match arg {
+ GenericBound::Outlives(Lifetime {
+ name: LifetimeName::Static,
+ span,
+ ..
+ }) => Some(*span),
+ _ => None,
+ })
+ .next()
+ {
+ if let Some(explicit_static) = &explicit_static {
+ err.span_suggestion_verbose(
+ span,
+ &format!("{} `impl Trait`'s {}", consider, explicit_static),
+ &lifetime_name,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ if let Some((param_span, param_ty)) = param.clone() {
+ err.span_suggestion_verbose(
+ param_span,
+ add_static_bound,
+ param_ty,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ } else if opaque
+ .bounds
+ .iter()
+ .filter_map(|arg| match arg {
+ GenericBound::Outlives(Lifetime { name, span, .. })
+ if name.ident().to_string() == lifetime_name =>
+ {
+ Some(*span)
+ }
+ _ => None,
+ })
+ .next()
+ .is_some()
+ {
+ } else {
+ err.span_suggestion_verbose(
+ fn_return.span.shrink_to_hi(),
+ &format!(
+ "{declare} `impl Trait` {captures}, {explicit}",
+ declare = declare,
+ captures = captures,
+ explicit = explicit,
+ ),
+ &plus_lt,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ TyKind::TraitObject(_, lt, _) => match lt.name {
+ LifetimeName::ImplicitObjectLifetimeDefault => {
+ err.span_suggestion_verbose(
+ fn_return.span.shrink_to_hi(),
+ &format!(
+ "{declare} trait object {captures}, {explicit}",
+ declare = declare,
+ captures = captures,
+ explicit = explicit,
+ ),
+ &plus_lt,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ name if name.ident().to_string() != lifetime_name => {
+ // With this check we avoid suggesting redundant bounds. This
+ // would happen if there are nested impl/dyn traits and only
+ // one of them has the bound we'd suggest already there, like
+ // in `impl Foo<X = dyn Bar> + '_`.
+ if let Some(explicit_static) = &explicit_static {
+ err.span_suggestion_verbose(
+ lt.span,
+ &format!("{} trait object's {}", consider, explicit_static),
+ &lifetime_name,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ if let Some((param_span, param_ty)) = param.clone() {
+ err.span_suggestion_verbose(
+ param_span,
+ add_static_bound,
+ param_ty,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ _ => {}
+ },
+ _ => {}
+ }
+ }
+}
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ fn get_impl_ident_and_self_ty_from_trait(
+ &self,
+ def_id: DefId,
+ trait_objects: &FxHashSet<DefId>,
+ ) -> Option<(Ident, &'tcx hir::Ty<'tcx>)> {
+ let tcx = self.tcx();
+ match tcx.hir().get_if_local(def_id) {
+ Some(Node::ImplItem(impl_item)) => {
+ match tcx.hir().find_by_def_id(tcx.hir().get_parent_item(impl_item.hir_id())) {
+ Some(Node::Item(Item {
+ kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
+ ..
+ })) => Some((impl_item.ident, self_ty)),
+ _ => None,
+ }
+ }
+ Some(Node::TraitItem(trait_item)) => {
+ let trait_did = tcx.hir().get_parent_item(trait_item.hir_id());
+ match tcx.hir().find_by_def_id(trait_did) {
+ Some(Node::Item(Item { kind: ItemKind::Trait(..), .. })) => {
+ // The method being called is defined in the `trait`, but the `'static`
+ // obligation comes from the `impl`. Find that `impl` so that we can point
+ // at it in the suggestion.
+ let trait_did = trait_did.to_def_id();
+ match tcx
+ .hir()
+ .trait_impls(trait_did)
+ .iter()
+ .filter_map(|&impl_did| {
+ match tcx.hir().get_if_local(impl_did.to_def_id()) {
+ Some(Node::Item(Item {
+ kind: ItemKind::Impl(hir::Impl { self_ty, .. }),
+ ..
+ })) if trait_objects.iter().all(|did| {
+ // FIXME: we should check `self_ty` against the receiver
+ // type in the `UnifyReceiver` context, but for now, use
+ // this imperfect proxy. This will fail if there are
+ // multiple `impl`s for the same trait like
+ // `impl Foo for Box<dyn Bar>` and `impl Foo for dyn Bar`.
+ // In that case, only the first one will get suggestions.
+ let mut traits = vec![];
+ let mut hir_v = HirTraitObjectVisitor(&mut traits, *did);
+ hir_v.visit_ty(self_ty);
+ !traits.is_empty()
+ }) =>
+ {
+ Some(self_ty)
+ }
+ _ => None,
+ }
+ })
+ .next()
+ {
+ Some(self_ty) => Some((trait_item.ident, self_ty)),
+ _ => None,
+ }
+ }
+ _ => None,
+ }
+ }
+ _ => None,
+ }
+ }
+
+ /// When we call a method coming from an `impl Foo for dyn Bar`, `dyn Bar` introduces a default
+ /// `'static` obligation. Suggest relaxing that implicit bound.
+ fn find_impl_on_dyn_trait(
+ &self,
+ err: &mut Diagnostic,
+ ty: Ty<'_>,
+ ctxt: &UnifyReceiverContext<'tcx>,
+ ) -> bool {
+ let tcx = self.tcx();
+
+ // Find the method being called.
+ let Ok(Some(instance)) = ty::Instance::resolve(
+ tcx,
+ ctxt.param_env,
+ ctxt.assoc_item.def_id,
+ self.infcx.resolve_vars_if_possible(ctxt.substs),
+ ) else {
+ return false;
+ };
+
+ let mut v = TraitObjectVisitor(FxHashSet::default());
+ v.visit_ty(ty);
+
+ // Get the `Ident` of the method being called and the corresponding `impl` (to point at
+ // `Bar` in `impl Foo for dyn Bar {}` and the definition of the method being called).
+ let Some((ident, self_ty)) = self.get_impl_ident_and_self_ty_from_trait(instance.def_id(), &v.0) else {
+ return false;
+ };
+
+ // Find the trait object types in the argument, so we point at *only* the trait object.
+ self.suggest_constrain_dyn_trait_in_impl(err, &v.0, ident, self_ty)
+ }
+
+ fn suggest_constrain_dyn_trait_in_impl(
+ &self,
+ err: &mut Diagnostic,
+ found_dids: &FxHashSet<DefId>,
+ ident: Ident,
+ self_ty: &hir::Ty<'_>,
+ ) -> bool {
+ let mut suggested = false;
+ for found_did in found_dids {
+ let mut traits = vec![];
+ let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
+ hir_v.visit_ty(&self_ty);
+ for span in &traits {
+ let mut multi_span: MultiSpan = vec![*span].into();
+ multi_span
+ .push_span_label(*span, "this has an implicit `'static` lifetime requirement");
+ multi_span.push_span_label(
+ ident.span,
+ "calling this method introduces the `impl`'s 'static` requirement",
+ );
+ err.span_note(multi_span, "the used `impl` has a `'static` requirement");
+ err.span_suggestion_verbose(
+ span.shrink_to_hi(),
+ "consider relaxing the implicit `'static` requirement",
+ " + '_",
+ Applicability::MaybeIncorrect,
+ );
+ suggested = true;
+ }
+ }
+ suggested
+ }
+}
+
+/// Collect all the trait objects in a type that could have received an implicit `'static` lifetime.
+pub struct TraitObjectVisitor(pub FxHashSet<DefId>);
+
+impl<'tcx> TypeVisitor<'tcx> for TraitObjectVisitor {
+ fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
+ match t.kind() {
+ ty::Dynamic(preds, re) if re.is_static() => {
+ if let Some(def_id) = preds.principal_def_id() {
+ self.0.insert(def_id);
+ }
+ ControlFlow::CONTINUE
+ }
+ _ => t.super_visit_with(self),
+ }
+ }
+}
+
+/// Collect all `hir::Ty<'_>` `Span`s for trait objects with an implicit lifetime.
+pub struct HirTraitObjectVisitor<'a>(pub &'a mut Vec<Span>, pub DefId);
+
+impl<'a, 'tcx> Visitor<'tcx> for HirTraitObjectVisitor<'a> {
+ fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
+ if let TyKind::TraitObject(
+ poly_trait_refs,
+ Lifetime { name: LifetimeName::ImplicitObjectLifetimeDefault, .. },
+ _,
+ ) = t.kind
+ {
+ for ptr in poly_trait_refs {
+ if Some(self.1) == ptr.trait_ref.trait_def_id() {
+ self.0.push(ptr.span);
+ }
+ }
+ }
+ walk_ty(self, t);
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs
new file mode 100644
index 000000000..da465a764
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs
@@ -0,0 +1,176 @@
+//! Error Reporting for `impl` items that do not match the obligations from their `trait`.
+
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::lexical_region_resolve::RegionResolutionError;
+use crate::infer::Subtype;
+use crate::traits::ObligationCauseCode::CompareImplItemObligation;
+use rustc_errors::{ErrorGuaranteed, MultiSpan};
+use rustc_hir as hir;
+use rustc_hir::def::Res;
+use rustc_hir::def_id::DefId;
+use rustc_hir::intravisit::Visitor;
+use rustc_middle::hir::nested_filter;
+use rustc_middle::ty::print::RegionHighlightMode;
+use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor};
+use rustc_span::Span;
+
+use std::ops::ControlFlow;
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ /// Print the error message for lifetime errors when the `impl` doesn't conform to the `trait`.
+ pub(super) fn try_report_impl_not_conforming_to_trait(&self) -> Option<ErrorGuaranteed> {
+ let error = self.error.as_ref()?;
+ debug!("try_report_impl_not_conforming_to_trait {:?}", error);
+ if let RegionResolutionError::SubSupConflict(
+ _,
+ var_origin,
+ sub_origin,
+ _sub,
+ sup_origin,
+ _sup,
+ _,
+ ) = error.clone()
+ && let (Subtype(sup_trace), Subtype(sub_trace)) = (&sup_origin, &sub_origin)
+ && let sub_expected_found @ Some((sub_expected, sub_found)) = sub_trace.values.ty()
+ && let sup_expected_found @ Some(_) = sup_trace.values.ty()
+ && let CompareImplItemObligation { trait_item_def_id, .. } = sub_trace.cause.code()
+ && sup_expected_found == sub_expected_found
+ {
+ let guar =
+ self.emit_err(var_origin.span(), sub_expected, sub_found, *trait_item_def_id);
+ return Some(guar);
+ }
+ None
+ }
+
+ fn emit_err(
+ &self,
+ sp: Span,
+ expected: Ty<'tcx>,
+ found: Ty<'tcx>,
+ trait_def_id: DefId,
+ ) -> ErrorGuaranteed {
+ let trait_sp = self.tcx().def_span(trait_def_id);
+ let mut err = self
+ .tcx()
+ .sess
+ .struct_span_err(sp, "`impl` item signature doesn't match `trait` item signature");
+
+ // Mark all unnamed regions in the type with a number.
+ // This diagnostic is called in response to lifetime errors, so be informative.
+ struct HighlightBuilder<'tcx> {
+ highlight: RegionHighlightMode<'tcx>,
+ counter: usize,
+ }
+
+ impl<'tcx> HighlightBuilder<'tcx> {
+ fn build(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> RegionHighlightMode<'tcx> {
+ let mut builder =
+ HighlightBuilder { highlight: RegionHighlightMode::new(tcx), counter: 1 };
+ builder.visit_ty(ty);
+ builder.highlight
+ }
+ }
+
+ impl<'tcx> ty::visit::TypeVisitor<'tcx> for HighlightBuilder<'tcx> {
+ fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
+ if !r.has_name() && self.counter <= 3 {
+ self.highlight.highlighting_region(r, self.counter);
+ self.counter += 1;
+ }
+ r.super_visit_with(self)
+ }
+ }
+
+ let expected_highlight = HighlightBuilder::build(self.tcx(), expected);
+ let expected = self
+ .infcx
+ .extract_inference_diagnostics_data(expected.into(), Some(expected_highlight))
+ .name;
+ let found_highlight = HighlightBuilder::build(self.tcx(), found);
+ let found =
+ self.infcx.extract_inference_diagnostics_data(found.into(), Some(found_highlight)).name;
+
+ err.span_label(sp, &format!("found `{}`", found));
+ err.span_label(trait_sp, &format!("expected `{}`", expected));
+
+ // Get the span of all the used type parameters in the method.
+ let assoc_item = self.tcx().associated_item(trait_def_id);
+ let mut visitor = TypeParamSpanVisitor { tcx: self.tcx(), types: vec![] };
+ match assoc_item.kind {
+ ty::AssocKind::Fn => {
+ let hir = self.tcx().hir();
+ if let Some(hir_id) =
+ assoc_item.def_id.as_local().map(|id| hir.local_def_id_to_hir_id(id))
+ {
+ if let Some(decl) = hir.fn_decl_by_hir_id(hir_id) {
+ visitor.visit_fn_decl(decl);
+ }
+ }
+ }
+ _ => {}
+ }
+ let mut type_param_span: MultiSpan = visitor.types.to_vec().into();
+ for &span in &visitor.types {
+ type_param_span
+ .push_span_label(span, "consider borrowing this type parameter in the trait");
+ }
+
+ err.note(&format!("expected `{}`\n found `{}`", expected, found));
+
+ err.span_help(
+ type_param_span,
+ "the lifetime requirements from the `impl` do not correspond to the requirements in \
+ the `trait`",
+ );
+ if visitor.types.is_empty() {
+ err.help(
+ "verify the lifetime relationships in the `trait` and `impl` between the `self` \
+ argument, the other inputs and its output",
+ );
+ }
+ err.emit()
+ }
+}
+
+struct TypeParamSpanVisitor<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ types: Vec<Span>,
+}
+
+impl<'tcx> Visitor<'tcx> for TypeParamSpanVisitor<'tcx> {
+ type NestedFilter = nested_filter::OnlyBodies;
+
+ fn nested_visit_map(&mut self) -> Self::Map {
+ self.tcx.hir()
+ }
+
+ fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
+ match arg.kind {
+ hir::TyKind::Rptr(_, ref mut_ty) => {
+ // We don't want to suggest looking into borrowing `&T` or `&Self`.
+ hir::intravisit::walk_ty(self, mut_ty.ty);
+ return;
+ }
+ hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
+ [segment]
+ if segment
+ .res
+ .map(|res| {
+ matches!(
+ res,
+ Res::SelfTy { trait_: _, alias_to: _ }
+ | Res::Def(hir::def::DefKind::TyParam, _)
+ )
+ })
+ .unwrap_or(false) =>
+ {
+ self.types.push(path.span);
+ }
+ _ => {}
+ },
+ _ => {}
+ }
+ hir::intravisit::walk_ty(self, arg);
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs
new file mode 100644
index 000000000..3e9d491af
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs
@@ -0,0 +1,167 @@
+//! Helper functions corresponding to lifetime errors due to
+//! anonymous regions.
+
+use crate::infer::error_reporting::nice_region_error::NiceRegionError;
+use crate::infer::TyCtxt;
+use rustc_hir as hir;
+use rustc_hir::def_id::LocalDefId;
+use rustc_middle::ty::{self, Binder, DefIdTree, Region, Ty, TypeVisitable};
+use rustc_span::Span;
+
+/// Information about the anonymous region we are searching for.
+#[derive(Debug)]
+pub struct AnonymousParamInfo<'tcx> {
+ /// The parameter corresponding to the anonymous region.
+ pub param: &'tcx hir::Param<'tcx>,
+ /// The type corresponding to the anonymous region parameter.
+ pub param_ty: Ty<'tcx>,
+ /// The ty::BoundRegionKind corresponding to the anonymous region.
+ pub bound_region: ty::BoundRegionKind,
+ /// The `Span` of the parameter type.
+ pub param_ty_span: Span,
+ /// Signals that the argument is the first parameter in the declaration.
+ pub is_first: bool,
+}
+
+// This method walks the Type of the function body parameters using
+// `fold_regions()` function and returns the
+// &hir::Param of the function parameter corresponding to the anonymous
+// region and the Ty corresponding to the named region.
+// Currently only the case where the function declaration consists of
+// one named region and one anonymous region is handled.
+// Consider the example `fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32`
+// Here, we would return the hir::Param for y, we return the type &'a
+// i32, which is the type of y but with the anonymous region replaced
+// with 'a, the corresponding bound region and is_first which is true if
+// the hir::Param is the first parameter in the function declaration.
+#[instrument(skip(tcx), level = "debug")]
+pub fn find_param_with_region<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ anon_region: Region<'tcx>,
+ replace_region: Region<'tcx>,
+) -> Option<AnonymousParamInfo<'tcx>> {
+ let (id, bound_region) = match *anon_region {
+ ty::ReFree(ref free_region) => (free_region.scope, free_region.bound_region),
+ ty::ReEarlyBound(ebr) => {
+ (tcx.parent(ebr.def_id), ty::BoundRegionKind::BrNamed(ebr.def_id, ebr.name))
+ }
+ _ => return None, // not a free region
+ };
+
+ let hir = &tcx.hir();
+ let def_id = id.as_local()?;
+ let hir_id = hir.local_def_id_to_hir_id(def_id);
+
+ // FIXME: use def_kind
+ // Don't perform this on closures
+ match hir.get(hir_id) {
+ hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
+ return None;
+ }
+ _ => {}
+ }
+
+ let body_id = hir.maybe_body_owned_by(def_id)?;
+
+ let owner_id = hir.body_owner(body_id);
+ let fn_decl = hir.fn_decl_by_hir_id(owner_id).unwrap();
+ let poly_fn_sig = tcx.fn_sig(id);
+
+ let fn_sig = tcx.liberate_late_bound_regions(id, poly_fn_sig);
+ let body = hir.body(body_id);
+ body.params
+ .iter()
+ .take(if fn_sig.c_variadic {
+ fn_sig.inputs().len()
+ } else {
+ assert_eq!(fn_sig.inputs().len(), body.params.len());
+ body.params.len()
+ })
+ .enumerate()
+ .find_map(|(index, param)| {
+ // May return None; sometimes the tables are not yet populated.
+ let ty = fn_sig.inputs()[index];
+ let mut found_anon_region = false;
+ let new_param_ty = tcx.fold_regions(ty, |r, _| {
+ if r == anon_region {
+ found_anon_region = true;
+ replace_region
+ } else {
+ r
+ }
+ });
+ if found_anon_region {
+ let ty_hir_id = fn_decl.inputs[index].hir_id;
+ let param_ty_span = hir.span(ty_hir_id);
+ let is_first = index == 0;
+ Some(AnonymousParamInfo {
+ param,
+ param_ty: new_param_ty,
+ param_ty_span,
+ bound_region,
+ is_first,
+ })
+ } else {
+ None
+ }
+ })
+}
+
+impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
+ pub(super) fn find_param_with_region(
+ &self,
+ anon_region: Region<'tcx>,
+ replace_region: Region<'tcx>,
+ ) -> Option<AnonymousParamInfo<'tcx>> {
+ find_param_with_region(self.tcx(), anon_region, replace_region)
+ }
+
+ // Here, we check for the case where the anonymous region
+ // is in the return type as written by the user.
+ // FIXME(#42703) - Need to handle certain cases here.
+ pub(super) fn is_return_type_anon(
+ &self,
+ scope_def_id: LocalDefId,
+ br: ty::BoundRegionKind,
+ hir_sig: &hir::FnSig<'_>,
+ ) -> Option<Span> {
+ let fn_ty = self.tcx().type_of(scope_def_id);
+ if let ty::FnDef(_, _) = fn_ty.kind() {
+ let ret_ty = fn_ty.fn_sig(self.tcx()).output();
+ let span = hir_sig.decl.output.span();
+ let future_output = if hir_sig.header.is_async() {
+ ret_ty.map_bound(|ty| self.infcx.get_impl_future_output_ty(ty)).transpose()
+ } else {
+ None
+ };
+ return match future_output {
+ Some(output) if self.includes_region(output, br) => Some(span),
+ None if self.includes_region(ret_ty, br) => Some(span),
+ _ => None,
+ };
+ }
+ None
+ }
+
+ fn includes_region(
+ &self,
+ ty: Binder<'tcx, impl TypeVisitable<'tcx>>,
+ region: ty::BoundRegionKind,
+ ) -> bool {
+ let late_bound_regions = self.tcx().collect_referenced_late_bound_regions(&ty);
+ late_bound_regions.iter().any(|r| *r == region)
+ }
+
+ // Here we check for the case where anonymous region
+ // corresponds to self and if yes, we display E0312.
+ // FIXME(#42700) - Need to format self properly to
+ // enable E0621 for it.
+ pub(super) fn is_self_anon(&self, is_first: bool, scope_def_id: LocalDefId) -> bool {
+ is_first
+ && self
+ .tcx()
+ .opt_associated_item(scope_def_id.to_def_id())
+ .map(|i| i.fn_has_self_parameter)
+ == Some(true)
+ }
+}
diff --git a/compiler/rustc_infer/src/infer/error_reporting/note.rs b/compiler/rustc_infer/src/infer/error_reporting/note.rs
new file mode 100644
index 000000000..c1940c5c0
--- /dev/null
+++ b/compiler/rustc_infer/src/infer/error_reporting/note.rs
@@ -0,0 +1,414 @@
+use crate::infer::error_reporting::{note_and_explain_region, ObligationCauseExt};
+use crate::infer::{self, InferCtxt, SubregionOrigin};
+use rustc_errors::{struct_span_err, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
+use rustc_middle::traits::ObligationCauseCode;
+use rustc_middle::ty::error::TypeError;
+use rustc_middle::ty::{self, Region};
+
+impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
+ pub(super) fn note_region_origin(&self, err: &mut Diagnostic, origin: &SubregionOrigin<'tcx>) {
+ let mut label_or_note = |span, msg: &str| {
+ let sub_count = err.children.iter().filter(|d| d.span.is_dummy()).count();
+ let expanded_sub_count = err.children.iter().filter(|d| !d.span.is_dummy()).count();
+ let span_is_primary = err.span.primary_spans().iter().all(|&sp| sp == span);
+ if span_is_primary && sub_count == 0 && expanded_sub_count == 0 {
+ err.span_label(span, msg);
+ } else if span_is_primary && expanded_sub_count == 0 {
+ err.note(msg);
+ } else {
+ err.span_note(span, msg);
+ }
+ };
+ match *origin {
+ infer::Subtype(ref trace) => {
+ if let Some((expected, found)) = self.values_str(trace.values) {
+ label_or_note(
+ trace.cause.span,
+ &format!("...so that the {}", trace.cause.as_requirement_str()),
+ );
+
+ err.note_expected_found(&"", expected, &"", found);
+ } else {
+ // FIXME: this really should be handled at some earlier stage. Our
+ // handling of region checking when type errors are present is
+ // *terrible*.
+
+ label_or_note(
+ trace.cause.span,
+ &format!("...so that {}", trace.cause.as_requirement_str()),
+ );
+ }
+ }
+ infer::Reborrow(span) => {
+ label_or_note(span, "...so that reference does not outlive borrowed content");
+ }
+ infer::ReborrowUpvar(span, ref upvar_id) => {
+ let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
+ label_or_note(span, &format!("...so that closure can access `{}`", var_name));
+ }
+ infer::RelateObjectBound(span) => {
+ label_or_note(span, "...so that it can be closed over into an object");
+ }
+ infer::DataBorrowed(ty, span) => {
+ label_or_note(
+ span,
+ &format!(
+ "...so that the type `{}` is not borrowed for too long",
+ self.ty_to_string(ty)
+ ),
+ );
+ }
+ infer::ReferenceOutlivesReferent(ty, span) => {
+ label_or_note(
+ span,
+ &format!(
+ "...so that the reference type `{}` does not outlive the data it points at",
+ self.ty_to_string(ty)
+ ),
+ );
+ }
+ infer::RelateParamBound(span, t, opt_span) => {
+ label_or_note(
+ span,
+ &format!(
+ "...so that the type `{}` will meet its required lifetime bounds{}",
+ self.ty_to_string(t),
+ if opt_span.is_some() { "..." } else { "" },
+ ),
+ );
+ if let Some(span) = opt_span {
+ err.span_note(span, "...that is required by this bound");
+ }
+ }
+ infer::RelateRegionParamBound(span) => {
+ label_or_note(
+ span,
+ "...so that the declared lifetime parameter bounds are satisfied",
+ );
+ }
+ infer::CompareImplItemObligation { span, .. } => {
+ label_or_note(
+ span,
+ "...so that the definition in impl matches the definition from the trait",
+ );
+ }
+ infer::CheckAssociatedTypeBounds { ref parent, .. } => {
+ self.note_region_origin(err, &parent);
+ }
+ }
+ }
+
+ pub(super) fn report_concrete_failure(
+ &self,
+ origin: SubregionOrigin<'tcx>,
+ sub: Region<'tcx>,
+ sup: Region<'tcx>,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ match origin {
+ infer::Subtype(box trace) => {
+ let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
+ let mut err = self.report_and_explain_type_error(trace, &terr);
+ match (*sub, *sup) {
+ (ty::RePlaceholder(_), ty::RePlaceholder(_)) => {}
+ (ty::RePlaceholder(_), _) => {
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "",
+ sup,
+ " doesn't meet the lifetime requirements",
+ None,
+ );
+ }
+ (_, ty::RePlaceholder(_)) => {
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "the required lifetime does not necessarily outlive ",
+ sub,
+ "",
+ None,
+ );
+ }
+ _ => {
+ note_and_explain_region(self.tcx, &mut err, "", sup, "...", None);
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "...does not necessarily outlive ",
+ sub,
+ "",
+ None,
+ );
+ }
+ }
+ err
+ }
+ infer::Reborrow(span) => {
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0312,
+ "lifetime of reference outlives lifetime of borrowed content..."
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "...the reference is valid for ",
+ sub,
+ "...",
+ None,
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "...but the borrowed content is only valid for ",
+ sup,
+ "",
+ None,
+ );
+ err
+ }
+ infer::ReborrowUpvar(span, ref upvar_id) => {
+ let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0313,
+ "lifetime of borrowed pointer outlives lifetime of captured variable `{}`...",
+ var_name
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "...the borrowed pointer is valid for ",
+ sub,
+ "...",
+ None,
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ &format!("...but `{}` is only valid for ", var_name),
+ sup,
+ "",
+ None,
+ );
+ err
+ }
+ infer::RelateObjectBound(span) => {
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0476,
+ "lifetime of the source pointer does not outlive lifetime bound of the \
+ object type"
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "object type is valid for ",
+ sub,
+ "",
+ None,
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "source pointer is only valid for ",
+ sup,
+ "",
+ None,
+ );
+ err
+ }
+ infer::RelateParamBound(span, ty, opt_span) => {
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0477,
+ "the type `{}` does not fulfill the required lifetime",
+ self.ty_to_string(ty)
+ );
+ match *sub {
+ ty::ReStatic => note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "type must satisfy ",
+ sub,
+ if opt_span.is_some() { " as required by this binding" } else { "" },
+ opt_span,
+ ),
+ _ => note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "type must outlive ",
+ sub,
+ if opt_span.is_some() { " as required by this binding" } else { "" },
+ opt_span,
+ ),
+ }
+ err
+ }
+ infer::RelateRegionParamBound(span) => {
+ let mut err =
+ struct_span_err!(self.tcx.sess, span, E0478, "lifetime bound not satisfied");
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "lifetime parameter instantiated with ",
+ sup,
+ "",
+ None,
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "but lifetime parameter must outlive ",
+ sub,
+ "",
+ None,
+ );
+ err
+ }
+ infer::DataBorrowed(ty, span) => {
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0490,
+ "a value of type `{}` is borrowed for too long",
+ self.ty_to_string(ty)
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "the type is valid for ",
+ sub,
+ "",
+ None,
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "but the borrow lasts for ",
+ sup,
+ "",
+ None,
+ );
+ err
+ }
+ infer::ReferenceOutlivesReferent(ty, span) => {
+ let mut err = struct_span_err!(
+ self.tcx.sess,
+ span,
+ E0491,
+ "in type `{}`, reference has a longer lifetime than the data it references",
+ self.ty_to_string(ty)
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "the pointer is valid for ",
+ sub,
+ "",
+ None,
+ );
+ note_and_explain_region(
+ self.tcx,
+ &mut err,
+ "but the referenced data is only valid for ",
+ sup,
+ "",
+ None,
+ );
+ err
+ }
+ infer::CompareImplItemObligation { span, impl_item_def_id, trait_item_def_id } => self
+ .report_extra_impl_obligation(
+ span,
+ impl_item_def_id,
+ trait_item_def_id,
+ &format!("`{}: {}`", sup, sub),
+ ),
+ infer::CheckAssociatedTypeBounds { impl_item_def_id, trait_item_def_id, parent } => {
+ let mut err = self.report_concrete_failure(*parent, sub, sup);
+
+ let trait_item_span = self.tcx.def_span(trait_item_def_id);
+ let item_name = self.tcx.item_name(impl_item_def_id.to_def_id());
+ err.span_label(
+ trait_item_span,
+ format!("definition of `{}` from trait", item_name),
+ );
+
+ let trait_predicates = self.tcx.explicit_predicates_of(trait_item_def_id);
+ let impl_predicates = self.tcx.explicit_predicates_of(impl_item_def_id);
+
+ let impl_predicates: rustc_data_structures::fx::FxHashSet<_> =
+ impl_predicates.predicates.into_iter().map(|(pred, _)| pred).collect();
+ let clauses: Vec<_> = trait_predicates
+ .predicates
+ .into_iter()
+ .filter(|&(pred, _)| !impl_predicates.contains(pred))
+ .map(|(pred, _)| format!("{}", pred))
+ .collect();
+
+ if !clauses.is_empty() {
+ let generics = self.tcx.hir().get_generics(impl_item_def_id).unwrap();
+ let where_clause_span = generics.tail_span_for_predicate_suggestion();
+
+ let suggestion = format!(
+ "{} {}",
+ generics.add_where_or_trailing_comma(),
+ clauses.join(", "),
+ );
+ err.span_suggestion(
+ where_clause_span,
+ &format!(
+ "try copying {} from the trait",
+ if clauses.len() > 1 { "these clauses" } else { "this clause" }
+ ),
+ suggestion,
+ rustc_errors::Applicability::MaybeIncorrect,
+ );
+ }
+
+ err
+ }
+ }
+ }
+
+ pub(super) fn report_placeholder_failure(
+ &self,
+ placeholder_origin: SubregionOrigin<'tcx>,
+ sub: Region<'tcx>,
+ sup: Region<'tcx>,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ // I can't think how to do better than this right now. -nikomatsakis
+ debug!(?placeholder_origin, ?sub, ?sup, "report_placeholder_failure");
+ match placeholder_origin {
+ infer::Subtype(box ref trace)
+ if matches!(
+ &trace.cause.code().peel_derives(),
+ ObligationCauseCode::BindingObligation(..)
+ ) =>
+ {
+ // Hack to get around the borrow checker because trace.cause has an `Rc`.
+ if let ObligationCauseCode::BindingObligation(_, span) =
+ &trace.cause.code().peel_derives()
+ {
+ let span = *span;
+ let mut err = self.report_concrete_failure(placeholder_origin, sub, sup);
+ err.span_note(span, "the lifetime requirement is introduced here");
+ err
+ } else {
+ unreachable!()
+ }
+ }
+ infer::Subtype(box trace) => {
+ let terr = TypeError::RegionsPlaceholderMismatch;
+ return self.report_and_explain_type_error(trace, &terr);
+ }
+ _ => return self.report_concrete_failure(placeholder_origin, sub, sup),
+ }
+ }
+}