1use std::iter;
2
3use rustc_data_structures::fx::FxIndexSet;
4use rustc_errors::{
5 Applicability, Diag, E0309, E0310, E0311, E0803, Subdiagnostic, msg, struct_span_code_err,
6};
7use rustc_hir::def::{DefKind, Namespace};
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_hir::intravisit::Visitor;
10use rustc_hir::{self as hir, ParamName};
11use rustc_middle::bug;
12use rustc_middle::traits::ObligationCauseCode;
13use rustc_middle::ty::error::TypeError;
14use rustc_middle::ty::print::RegionHighlightMode;
15use rustc_middle::ty::{
16 self, IsSuggestable, Region, Ty, TyCtxt, TypeVisitableExt as _, Upcast as _,
17};
18use rustc_span::{BytePos, ErrorGuaranteed, Span, Symbol, kw, sym};
19use tracing::{debug, instrument};
20
21use super::ObligationCauseAsDiagArg;
22use super::nice_region_error::find_anon_type;
23use crate::diagnostics::{
24 self, FulfillReqLifetime, LfBoundNotSatisfied, OutlivesBound, OutlivesContent,
25 RefLongerThanData, RegionOriginNote, WhereClauseSuggestions, note_and_explain,
26};
27use crate::error_reporting::TypeErrCtxt;
28use crate::error_reporting::infer::ObligationCauseExt;
29use crate::error_reporting::infer::nice_region_error::placeholder_error::Highlighted;
30use crate::infer::region_constraints::GenericKind;
31use crate::infer::{
32 BoundRegionConversionTime, InferCtxt, RegionResolutionError, RegionVariableOrigin,
33 SubregionOrigin,
34};
35
36impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
37 pub fn report_region_errors(
38 &self,
39 generic_param_scope: LocalDefId,
40 errors: &[RegionResolutionError<'tcx>],
41 ) -> ErrorGuaranteed {
42 if !!errors.is_empty() {
::core::panicking::panic("assertion failed: !errors.is_empty()")
};assert!(!errors.is_empty());
43
44 if let Some(guaranteed) = self.infcx.tainted_by_errors() {
45 return guaranteed;
46 }
47
48 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:48",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(48u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_region_errors(): {0} errors to start",
errors.len()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("report_region_errors(): {} errors to start", errors.len());
49
50 let errors = self.process_errors(errors);
53
54 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:54",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(54u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_region_errors: {0} errors after preprocessing",
errors.len()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("report_region_errors: {} errors after preprocessing", errors.len());
55
56 let mut guar = None;
57 for error in errors {
58 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:58",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(58u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_region_errors: error = {0:?}",
error) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("report_region_errors: error = {:?}", error);
59
60 let e = if let Some(guar) =
61 self.try_report_nice_region_error(generic_param_scope, &error)
62 {
63 guar
64 } else {
65 match error.clone() {
66 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
74 if sub.is_placeholder() || sup.is_placeholder() {
75 self.report_placeholder_failure(generic_param_scope, origin, sub, sup)
76 .emit()
77 } else {
78 self.report_concrete_failure(generic_param_scope, origin, sub, sup)
79 .emit()
80 }
81 }
82
83 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => self
84 .report_generic_bound_failure(
85 generic_param_scope,
86 origin.span(),
87 Some(origin),
88 param_ty,
89 sub,
90 ),
91
92 RegionResolutionError::SubSupConflict(
93 _,
94 var_origin,
95 sub_origin,
96 sub_r,
97 sup_origin,
98 sup_r,
99 _,
100 ) => {
101 if sub_r.is_placeholder() {
102 self.report_placeholder_failure(
103 generic_param_scope,
104 sub_origin,
105 sub_r,
106 sup_r,
107 )
108 .emit()
109 } else if sup_r.is_placeholder() {
110 self.report_placeholder_failure(
111 generic_param_scope,
112 sup_origin,
113 sub_r,
114 sup_r,
115 )
116 .emit()
117 } else {
118 self.report_sub_sup_conflict(
119 generic_param_scope,
120 var_origin,
121 sub_origin,
122 sub_r,
123 sup_origin,
124 sup_r,
125 )
126 }
127 }
128
129 RegionResolutionError::UpperBoundUniverseConflict(
130 _,
131 _,
132 _,
133 sup_origin,
134 sup_r,
135 ) => {
136 if !sup_r.is_placeholder() {
::core::panicking::panic("assertion failed: sup_r.is_placeholder()")
};assert!(sup_r.is_placeholder());
137
138 let sub_r = self.tcx.lifetimes.re_erased;
144
145 self.report_placeholder_failure(
146 generic_param_scope,
147 sup_origin,
148 sub_r,
149 sup_r,
150 )
151 .emit()
152 }
153
154 RegionResolutionError::CannotNormalize(clause, origin) => {
155 let clause: ty::Clause<'tcx> =
156 clause.map_bound(ty::ClauseKind::TypeOutlives).upcast(self.tcx);
157 self.tcx
158 .dcx()
159 .struct_span_err(origin.span(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot normalize `{0}`", clause))
})format!("cannot normalize `{clause}`"))
160 .emit()
161 }
162 }
163 };
164
165 guar = Some(e)
166 }
167
168 guar.unwrap()
169 }
170
171 fn process_errors(
182 &self,
183 errors: &[RegionResolutionError<'tcx>],
184 ) -> Vec<RegionResolutionError<'tcx>> {
185 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:185",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(185u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("process_errors()")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("process_errors()");
186
187 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
200 RegionResolutionError::GenericBoundFailure(..) => true,
201 RegionResolutionError::ConcreteFailure(..)
202 | RegionResolutionError::SubSupConflict(..)
203 | RegionResolutionError::UpperBoundUniverseConflict(..)
204 | RegionResolutionError::CannotNormalize(..) => false,
205 };
206
207 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
208 errors.to_owned()
209 } else {
210 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
211 };
212
213 errors.sort_by_key(|u| match *u {
215 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
216 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
217 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
218 RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
219 RegionResolutionError::CannotNormalize(_, ref sro) => sro.span(),
220 });
221 errors
222 }
223
224 pub(super) fn note_region_origin(&self, err: &mut Diag<'_>, origin: &SubregionOrigin<'tcx>) {
225 match *origin {
226 SubregionOrigin::Subtype(ref trace) => RegionOriginNote::WithRequirement {
227 span: trace.cause.span,
228 requirement: ObligationCauseAsDiagArg(trace.cause.clone()),
229 expected_found: self.values_str(trace.values, &trace.cause, err.long_ty_path()),
230 }
231 .add_to_diag(err),
232 SubregionOrigin::Reborrow(span) => RegionOriginNote::Plain {
233 span,
234 msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that reference does not outlive borrowed content"))msg!("...so that reference does not outlive borrowed content"),
235 }
236 .add_to_diag(err),
237 SubregionOrigin::RelateObjectBound(span) => {
238 RegionOriginNote::Plain {
239 span,
240 msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that it can be closed over into an object"))msg!("...so that it can be closed over into an object"),
241 }
242 .add_to_diag(err);
243 }
244 SubregionOrigin::ReferenceOutlivesReferent(ty, span) => {
245 RegionOriginNote::WithName {
246 span,
247 msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the reference type `{$name}` does not outlive the data it points at"))msg!("...so that the reference type `{$name}` does not outlive the data it points at"),
248 name: &self.ty_to_string(ty),
249 continues: false,
250 }
251 .add_to_diag(err);
252 }
253 SubregionOrigin::RelateParamBound(span, ty, opt_span) => {
254 RegionOriginNote::WithName {
255 span,
256 msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the type `{$name}` will meet its required lifetime bounds{$continues ->\n [true] ...\n *[false] {\"\"}\n }"))msg!(
257 "...so that the type `{$name}` will meet its required lifetime bounds{$continues ->
258 [true] ...
259 *[false] {\"\"}
260 }"
261 ),
262 name: &self.ty_to_string(ty),
263 continues: opt_span.is_some(),
264 }
265 .add_to_diag(err);
266 if let Some(span) = opt_span {
267 RegionOriginNote::Plain {
268 span,
269 msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...that is required by this bound"))msg!("...that is required by this bound"),
270 }
271 .add_to_diag(err);
272 }
273 }
274 SubregionOrigin::RelateRegionParamBound(span, _) => {
275 RegionOriginNote::Plain {
276 span,
277 msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the declared lifetime parameter bounds are satisfied"))msg!("...so that the declared lifetime parameter bounds are satisfied"),
278 }
279 .add_to_diag(err);
280 }
281 SubregionOrigin::CompareImplItemObligation { span, .. } => {
282 RegionOriginNote::Plain {
283 span,
284 msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the definition in impl matches the definition from the trait"))msg!(
285 "...so that the definition in impl matches the definition from the trait"
286 ),
287 }
288 .add_to_diag(err);
289 }
290 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => {
291 self.note_region_origin(err, parent);
292 }
293 SubregionOrigin::AscribeUserTypeProvePredicate(span) => {
294 RegionOriginNote::Plain { span, msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the where clause holds"))msg!("...so that the where clause holds") }
295 .add_to_diag(err);
296 }
297 SubregionOrigin::SolverRegionConstraint(span) => {
298 RegionOriginNote::Plain {
299 span,
300 msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this diagnostic is currently WIP while -Zassumptions-on-binders is incomplete"))msg!("this diagnostic is currently WIP while -Zassumptions-on-binders is incomplete"),
301 }
302 .add_to_diag(err);
303 }
304 }
305 }
306
307 pub(super) fn report_concrete_failure(
308 &self,
309 generic_param_scope: LocalDefId,
310 origin: SubregionOrigin<'tcx>,
311 sub: Region<'tcx>,
312 sup: Region<'tcx>,
313 ) -> Diag<'a> {
314 let mut err = match origin {
315 SubregionOrigin::Subtype(trace) => {
316 let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
317 let mut err = self.report_and_explain_type_error(
318 *trace,
319 self.tcx.param_env(generic_param_scope),
320 terr,
321 );
322 match (sub.kind(), sup.kind()) {
323 (ty::RePlaceholder(_), ty::RePlaceholder(_)) => {}
324 (ty::RePlaceholder(_), _) => {
325 note_and_explain_region(
326 self.tcx,
327 &mut err,
328 generic_param_scope,
329 "",
330 sup,
331 " doesn't meet the lifetime requirements",
332 None,
333 );
334 }
335 (_, ty::RePlaceholder(_)) => {
336 note_and_explain_region(
337 self.tcx,
338 &mut err,
339 generic_param_scope,
340 "the required lifetime does not necessarily outlive ",
341 sub,
342 "",
343 None,
344 );
345 }
346 _ => {
347 note_and_explain_region(
348 self.tcx,
349 &mut err,
350 generic_param_scope,
351 "",
352 sup,
353 "...",
354 None,
355 );
356 note_and_explain_region(
357 self.tcx,
358 &mut err,
359 generic_param_scope,
360 "...does not necessarily outlive ",
361 sub,
362 "",
363 None,
364 );
365 }
366 }
367 err
368 }
369 SubregionOrigin::Reborrow(span) => {
370 let reference_valid = note_and_explain::RegionExplanation::new(
371 self.tcx,
372 generic_param_scope,
373 sub,
374 None,
375 note_and_explain::PrefixKind::RefValidFor,
376 note_and_explain::SuffixKind::Continues,
377 );
378 let content_valid = note_and_explain::RegionExplanation::new(
379 self.tcx,
380 generic_param_scope,
381 sup,
382 None,
383 note_and_explain::PrefixKind::ContentValidFor,
384 note_and_explain::SuffixKind::Empty,
385 );
386 self.dcx().create_err(OutlivesContent {
387 span,
388 notes: reference_valid.into_iter().chain(content_valid).collect(),
389 })
390 }
391 SubregionOrigin::RelateObjectBound(span) => {
392 let object_valid = note_and_explain::RegionExplanation::new(
393 self.tcx,
394 generic_param_scope,
395 sub,
396 None,
397 note_and_explain::PrefixKind::TypeObjValidFor,
398 note_and_explain::SuffixKind::Empty,
399 );
400 let pointer_valid = note_and_explain::RegionExplanation::new(
401 self.tcx,
402 generic_param_scope,
403 sup,
404 None,
405 note_and_explain::PrefixKind::SourcePointerValidFor,
406 note_and_explain::SuffixKind::Empty,
407 );
408 self.dcx().create_err(OutlivesBound {
409 span,
410 notes: object_valid.into_iter().chain(pointer_valid).collect(),
411 })
412 }
413 SubregionOrigin::RelateParamBound(span, ty, opt_span) => {
414 let prefix = match sub.kind() {
415 ty::ReStatic => note_and_explain::PrefixKind::TypeSatisfy,
416 _ => note_and_explain::PrefixKind::TypeOutlive,
417 };
418 let suffix = if opt_span.is_some() {
419 note_and_explain::SuffixKind::ReqByBinding
420 } else {
421 note_and_explain::SuffixKind::Empty
422 };
423 let note = note_and_explain::RegionExplanation::new(
424 self.tcx,
425 generic_param_scope,
426 sub,
427 opt_span,
428 prefix,
429 suffix,
430 );
431 self.dcx().create_err(FulfillReqLifetime {
432 span,
433 ty: self.resolve_vars_if_possible(ty),
434 note,
435 })
436 }
437 SubregionOrigin::RelateRegionParamBound(span, ty) => {
438 let param_instantiated = note_and_explain::RegionExplanation::new(
439 self.tcx,
440 generic_param_scope,
441 sup,
442 None,
443 note_and_explain::PrefixKind::LfParamInstantiatedWith,
444 note_and_explain::SuffixKind::Empty,
445 );
446 let mut alt_span = None;
447 if let Some(ty) = ty
448 && sub.is_static()
449 && let ty::Dynamic(preds, _) = ty.kind()
450 && let Some(def_id) = preds.principal_def_id()
451 {
452 for (clause, span) in
453 self.tcx.predicates_of(def_id).instantiate_identity(self.tcx).into_iter()
454 {
455 if let ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) =
456 clause.kind().skip_binder()
457 && let ty::Param(param) = a.kind()
458 && param.name == kw::SelfUpper
459 && b.is_static()
460 {
461 alt_span = Some(span);
463 }
464 }
465 }
466 let param_must_outlive = note_and_explain::RegionExplanation::new(
467 self.tcx,
468 generic_param_scope,
469 sub,
470 alt_span,
471 note_and_explain::PrefixKind::LfParamMustOutlive,
472 note_and_explain::SuffixKind::Empty,
473 );
474 self.dcx().create_err(LfBoundNotSatisfied {
475 span,
476 notes: param_instantiated.into_iter().chain(param_must_outlive).collect(),
477 })
478 }
479 SubregionOrigin::ReferenceOutlivesReferent(ty, span) => {
480 let pointer_valid = note_and_explain::RegionExplanation::new(
481 self.tcx,
482 generic_param_scope,
483 sub,
484 None,
485 note_and_explain::PrefixKind::PointerValidFor,
486 note_and_explain::SuffixKind::Empty,
487 );
488 let data_valid = note_and_explain::RegionExplanation::new(
489 self.tcx,
490 generic_param_scope,
491 sup,
492 None,
493 note_and_explain::PrefixKind::DataValidFor,
494 note_and_explain::SuffixKind::Empty,
495 );
496 self.dcx().create_err(RefLongerThanData {
497 span,
498 ty: self.resolve_vars_if_possible(ty),
499 notes: pointer_valid.into_iter().chain(data_valid).collect(),
500 })
501 }
502 SubregionOrigin::CompareImplItemObligation {
503 span,
504 impl_item_def_id,
505 trait_item_def_id,
506 } => {
507 let mut err = self.report_extra_impl_obligation(
508 span,
509 impl_item_def_id,
510 trait_item_def_id,
511 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}: {1}`", sup, sub))
})format!("`{sup}: {sub}`"),
512 );
513 if let Some(generics) = self.tcx.hir_get_generics(impl_item_def_id)
515 && generics.where_clause_span.contains(span)
516 {
517 self.suggest_copy_trait_method_bounds(
518 trait_item_def_id,
519 impl_item_def_id,
520 &mut err,
521 );
522 }
523 err
524 }
525 SubregionOrigin::CheckAssociatedTypeBounds {
526 impl_item_def_id,
527 trait_item_def_id,
528 parent,
529 } => {
530 let mut err = self.report_concrete_failure(generic_param_scope, *parent, sub, sup);
531
532 if !self.tcx.is_impl_trait_in_trait(impl_item_def_id.to_def_id()) {
535 let trait_item_span = self.tcx.def_span(trait_item_def_id);
536 let item_name = self.tcx.item_name(impl_item_def_id.to_def_id());
537 err.span_label(
538 trait_item_span,
539 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("definition of `{0}` from trait",
item_name))
})format!("definition of `{item_name}` from trait"),
540 );
541 }
542
543 self.suggest_copy_trait_method_bounds(
544 trait_item_def_id,
545 impl_item_def_id,
546 &mut err,
547 );
548 err
549 }
550 SubregionOrigin::AscribeUserTypeProvePredicate(span) => {
551 let instantiated = note_and_explain::RegionExplanation::new(
552 self.tcx,
553 generic_param_scope,
554 sup,
555 None,
556 note_and_explain::PrefixKind::LfInstantiatedWith,
557 note_and_explain::SuffixKind::Empty,
558 );
559 let must_outlive = note_and_explain::RegionExplanation::new(
560 self.tcx,
561 generic_param_scope,
562 sub,
563 None,
564 note_and_explain::PrefixKind::LfMustOutlive,
565 note_and_explain::SuffixKind::Empty,
566 );
567 self.dcx().create_err(LfBoundNotSatisfied {
568 span,
569 notes: instantiated.into_iter().chain(must_outlive).collect(),
570 })
571 }
572 SubregionOrigin::SolverRegionConstraint(span) => {
573 let mut d = self.dcx().struct_span_err(
574 span,
575 "unsatisfied lifetime constraint from -Zassumptions-on-binders :3",
576 );
577 d.note("meoow :c");
578 d
579 }
580 };
581 if sub.is_error() || sup.is_error() {
582 err.downgrade_to_delayed_bug();
583 }
584 err
585 }
586
587 pub fn suggest_copy_trait_method_bounds(
588 &self,
589 trait_item_def_id: DefId,
590 impl_item_def_id: LocalDefId,
591 err: &mut Diag<'_>,
592 ) {
593 let Some(impl_def_id) = self.tcx.trait_impl_of_assoc(impl_item_def_id.to_def_id()) else {
599 return;
600 };
601 let trait_ref = self.tcx.impl_trait_ref(impl_def_id);
602 let trait_args = trait_ref
603 .instantiate_identity()
604 .skip_norm_wip()
605 .with_replaced_self_ty(self.tcx, Ty::new_param(self.tcx, 0, kw::SelfUpper))
607 .args;
608 let trait_item_args = ty::GenericArgs::identity_for_item(self.tcx, impl_item_def_id)
609 .rebase_onto(self.tcx, impl_def_id, trait_args);
610
611 let Ok(trait_predicates) = self
612 .tcx
613 .explicit_predicates_of(trait_item_def_id)
614 .instantiate_own(self.tcx, trait_item_args)
615 .map(|(pred, _)| {
616 let pred = pred.skip_norm_wip();
617 if pred.is_suggestable(self.tcx, false) { Ok(pred.to_string()) } else { Err(()) }
618 })
619 .collect::<Result<Vec<_>, ()>>()
620 else {
621 return;
622 };
623
624 let Some(generics) = self.tcx.hir_get_generics(impl_item_def_id) else {
625 return;
626 };
627
628 let suggestion = if trait_predicates.is_empty() {
629 WhereClauseSuggestions::Remove { span: generics.where_clause_span }
630 } else {
631 let space = if generics.where_clause_span.is_empty() { " " } else { "" };
632 WhereClauseSuggestions::CopyPredicates {
633 span: generics.where_clause_span,
634 space,
635 trait_predicates: trait_predicates.join(", "),
636 }
637 };
638 err.subdiagnostic(suggestion);
639 }
640
641 pub(super) fn report_placeholder_failure(
642 &self,
643 generic_param_scope: LocalDefId,
644 placeholder_origin: SubregionOrigin<'tcx>,
645 sub: Region<'tcx>,
646 sup: Region<'tcx>,
647 ) -> Diag<'a> {
648 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:649",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(649u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("placeholder_origin")
}> =
::tracing::__macro_support::FieldName::new("placeholder_origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sub")
}> =
::tracing::__macro_support::FieldName::new("sub");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sup")
}> =
::tracing::__macro_support::FieldName::new("sup");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_placeholder_failure")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&placeholder_origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sub)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sup)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?placeholder_origin, ?sub, ?sup, "report_placeholder_failure");
650 match placeholder_origin {
651 SubregionOrigin::Subtype(ref trace)
652 if #[allow(non_exhaustive_omitted_patterns)] match &trace.cause.code().peel_derives()
{
ObligationCauseCode::WhereClause(..) |
ObligationCauseCode::WhereClauseInExpr(..) => true,
_ => false,
}matches!(
653 &trace.cause.code().peel_derives(),
654 ObligationCauseCode::WhereClause(..)
655 | ObligationCauseCode::WhereClauseInExpr(..)
656 ) =>
657 {
658 if let ObligationCauseCode::WhereClause(_, span)
660 | ObligationCauseCode::WhereClauseInExpr(_, span, ..) =
661 &trace.cause.code().peel_derives()
662 {
663 let span = *span;
664 let mut err = self.report_concrete_failure(
665 generic_param_scope,
666 placeholder_origin,
667 sub,
668 sup,
669 );
670 if !span.is_dummy() {
671 err =
672 err.with_span_note(span, "the lifetime requirement is introduced here");
673 }
674 err
675 } else {
676 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("control flow ensures we have a `BindingObligation` or `WhereClauseInExpr` here...")));
}unreachable!(
677 "control flow ensures we have a `BindingObligation` or `WhereClauseInExpr` here..."
678 )
679 }
680 }
681 SubregionOrigin::Subtype(trace) => {
682 let terr = TypeError::RegionsPlaceholderMismatch;
683 return self.report_and_explain_type_error(
684 *trace,
685 self.tcx.param_env(generic_param_scope),
686 terr,
687 );
688 }
689 _ => {
690 return self.report_concrete_failure(
691 generic_param_scope,
692 placeholder_origin,
693 sub,
694 sup,
695 );
696 }
697 }
698 }
699
700 pub fn report_generic_bound_failure(
701 &self,
702 generic_param_scope: LocalDefId,
703 span: Span,
704 origin: Option<SubregionOrigin<'tcx>>,
705 bound_kind: GenericKind<'tcx>,
706 sub: Region<'tcx>,
707 ) -> ErrorGuaranteed {
708 self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
709 .emit()
710 }
711
712 pub fn construct_generic_bound_failure(
713 &self,
714 generic_param_scope: LocalDefId,
715 span: Span,
716 origin: Option<SubregionOrigin<'tcx>>,
717 bound_kind: GenericKind<'tcx>,
718 sub: Region<'tcx>,
719 ) -> Diag<'a> {
720 if let Some(SubregionOrigin::CompareImplItemObligation {
721 span,
722 impl_item_def_id,
723 trait_item_def_id,
724 }) = origin
725 {
726 return self.report_extra_impl_obligation(
727 span,
728 impl_item_def_id,
729 trait_item_def_id,
730 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}: {1}`", bound_kind, sub))
})format!("`{bound_kind}: {sub}`"),
731 );
732 }
733
734 let labeled_user_string = match bound_kind {
735 GenericKind::Param(_) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the parameter type `{0}`",
bound_kind))
})format!("the parameter type `{bound_kind}`"),
736 GenericKind::Placeholder(_) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the placeholder type `{0}`",
bound_kind))
})format!("the placeholder type `{bound_kind}`"),
737 GenericKind::Alias(p) => match p.kind {
738 ty::Projection { .. } | ty::Inherent { .. } => {
739 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the associated type `{0}`",
bound_kind))
})format!("the associated type `{bound_kind}`")
740 }
741 ty::Free { .. } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the type alias `{0}`", bound_kind))
})format!("the type alias `{bound_kind}`"),
742 ty::Opaque { .. } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the opaque type `{0}`",
bound_kind))
})format!("the opaque type `{bound_kind}`"),
743 },
744 };
745
746 let mut err = self
747 .tcx
748 .dcx()
749 .struct_span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} may not live long enough",
labeled_user_string))
})format!("{labeled_user_string} may not live long enough"));
750 err.code(match sub.kind() {
751 ty::ReEarlyParam(_) | ty::ReLateParam(_) if sub.is_named(self.tcx) => E0309,
752 ty::ReStatic => E0310,
753 _ => E0311,
754 });
755
756 '_explain: {
757 let (description, span) = match sub.kind() {
758 ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::ReStatic => {
759 msg_span_from_named_region(self.tcx, generic_param_scope, sub, Some(span))
760 }
761 _ => (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}`", sub))
})format!("lifetime `{sub}`"), Some(span)),
762 };
763 let prefix = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} must be valid for ",
labeled_user_string))
})format!("{labeled_user_string} must be valid for ");
764 label_msg_span(&mut err, &prefix, description, span, "...");
765 if let Some(origin) = origin {
766 self.note_region_origin(&mut err, &origin);
767 }
768 }
769
770 'suggestion: {
771 let msg = "consider adding an explicit lifetime bound";
772
773 if (bound_kind, sub).has_infer_regions()
774 || (bound_kind, sub).has_placeholders()
775 || !bound_kind.is_suggestable(self.tcx, false)
776 {
777 let lt_name = sub.get_name_or_anon(self.tcx).to_string();
778 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}: {2}`...", msg,
bound_kind, lt_name))
})format!("{msg} `{bound_kind}: {lt_name}`..."));
779 break 'suggestion;
780 }
781
782 let mut generic_param_scope = generic_param_scope;
783 while self.tcx.def_kind(generic_param_scope) == DefKind::OpaqueTy {
784 generic_param_scope = self.tcx.local_parent(generic_param_scope);
785 }
786
787 let (type_scope, type_param_sugg_span) = match bound_kind {
789 GenericKind::Param(param) => {
790 let generics = self.tcx.generics_of(generic_param_scope);
791 let type_param = generics.type_param(param, self.tcx);
792 let def_id = type_param.def_id.expect_local();
793 let scope = self.tcx.local_def_id_to_hir_id(def_id).owner.def_id;
794 let hir_generics = self.tcx.hir_get_generics(scope).unwrap();
798 let sugg_span = match hir_generics.bounds_span_for_suggestions(def_id) {
799 Some((span, open_paren_sp)) => {
800 Some((span, LifetimeSuggestion::NeedsPlus(open_paren_sp)))
801 }
802 None if generics.has_self && param.index == 0 => None,
804 None => {
805 let mut colon_flag = false;
806 let span = if let Some(param) =
807 hir_generics.params.iter().find(|param| param.def_id == def_id)
808 && let ParamName::Plain(ident) = param.name
809 {
810 if let Some(sp) = param.colon_span {
811 colon_flag = true;
812 sp.shrink_to_hi()
813 } else {
814 ident.span.shrink_to_hi()
815 }
816 } else {
817 let span = self.tcx.def_span(def_id);
818 span.shrink_to_hi()
819 };
820 match colon_flag {
821 true => Some((span, LifetimeSuggestion::HasColon)),
822 false => Some((span, LifetimeSuggestion::NeedsColon)),
823 }
824 }
825 };
826 (scope, sugg_span)
827 }
828 _ => (generic_param_scope, None),
829 };
830 let suggestion_scope = {
831 let lifetime_scope = match sub.kind() {
832 ty::ReStatic => hir::def_id::CRATE_DEF_ID,
833 _ => match self.tcx.is_suitable_region(generic_param_scope, sub) {
834 Some(info) => info.scope,
835 None => generic_param_scope,
836 },
837 };
838 match self.tcx.is_descendant_of(type_scope, lifetime_scope) {
839 true => type_scope,
840 false => lifetime_scope,
841 }
842 };
843
844 let mut suggs = ::alloc::vec::Vec::new()vec![];
845 let lt_name = self.suggest_name_region(generic_param_scope, sub, &mut suggs);
846
847 if let Some((sp, suggestion_type)) = type_param_sugg_span
848 && suggestion_scope == type_scope
849 {
850 match suggestion_type {
851 LifetimeSuggestion::NeedsPlus(open_paren_sp) => {
852 let suggestion = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + {0}", lt_name))
})format!(" + {lt_name}");
853 if let Some(open_paren_sp) = open_paren_sp {
854 suggs.push((open_paren_sp, "(".to_string()));
855 suggs.push((sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("){0}", suggestion))
})format!("){suggestion}")));
856 } else {
857 suggs.push((sp, suggestion));
858 }
859 }
860 LifetimeSuggestion::NeedsColon => suggs.push((sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}", lt_name))
})format!(": {lt_name}"))),
861 LifetimeSuggestion::HasColon => suggs.push((sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", lt_name))
})format!(" {lt_name}"))),
862 }
863 } else if let GenericKind::Alias(ref p) = bound_kind
864 && let ty::Projection { def_id } = p.kind
865 && let DefKind::AssocTy = self.tcx.def_kind(def_id)
866 && let Some(ty::ImplTraitInTraitData::Trait { .. }) =
867 self.tcx.opt_rpitit_info(def_id)
868 {
869 } else if let Some(generics) = self.tcx.hir_get_generics(suggestion_scope) {
872 let pred = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", bound_kind, lt_name))
})format!("{bound_kind}: {lt_name}");
873 let suggestion = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}",
generics.add_where_or_trailing_comma(), pred))
})format!("{} {}", generics.add_where_or_trailing_comma(), pred);
874 suggs.push((generics.tail_span_for_predicate_suggestion(), suggestion))
875 } else {
876 let consider = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}: {2}`...", msg,
bound_kind, sub))
})format!("{msg} `{bound_kind}: {sub}`...");
877 err.help(consider);
878 }
879
880 if !suggs.is_empty() {
881 err.multipart_suggestion(
882 msg,
883 suggs,
884 Applicability::MaybeIncorrect, );
886 }
887 }
888
889 if sub.kind() == ty::ReStatic
890 && let Some(node) = self.tcx.hir_get_if_local(generic_param_scope.into())
891 && let hir::Node::Item(hir::Item {
892 kind: hir::ItemKind::Fn { sig, body, has_body: true, .. },
893 ..
894 })
895 | hir::Node::TraitItem(hir::TraitItem {
896 kind: hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body)),
897 ..
898 })
899 | hir::Node::ImplItem(hir::ImplItem {
900 kind: hir::ImplItemKind::Fn(sig, body), ..
901 }) = node
902 && let hir::Node::Expr(expr) = self.tcx.hir_node(body.hir_id)
903 && let hir::ExprKind::Block(block, _) = expr.kind
904 && let Some(tail) = block.expr
905 && tail.span == span
906 && let hir::FnRetTy::Return(ty) = sig.decl.output
907 && let hir::TyKind::Path(path) = ty.kind
908 && let hir::QPath::Resolved(None, path) = path
909 && let hir::def::Res::Def(_, def_id) = path.res
910 && Some(def_id) == self.tcx.lang_items().owned_box()
911 && let [segment] = path.segments
912 && let Some(args) = segment.args
913 && let [hir::GenericArg::Type(ty)] = args.args
914 && let hir::TyKind::TraitObject(_, tagged_ref) = ty.kind
915 && let hir::LifetimeKind::ImplicitObjectLifetimeDefault = tagged_ref.pointer().kind
916 {
917 err.span_label(
920 ty.span,
921 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this `dyn Trait` has an implicit `\'static` lifetime bound"))
})format!("this `dyn Trait` has an implicit `'static` lifetime bound"),
922 );
923 }
924
925 err
926 }
927
928 pub fn suggest_name_region(
929 &self,
930 generic_param_scope: LocalDefId,
931 lifetime: Region<'tcx>,
932 add_lt_suggs: &mut Vec<(Span, String)>,
933 ) -> String {
934 struct LifetimeReplaceVisitor<'a> {
935 needle: hir::LifetimeKind,
936 new_lt: &'a str,
937 add_lt_suggs: &'a mut Vec<(Span, String)>,
938 }
939
940 impl<'hir> hir::intravisit::Visitor<'hir> for LifetimeReplaceVisitor<'_> {
941 fn visit_lifetime(&mut self, lt: &'hir hir::Lifetime) {
942 if lt.kind == self.needle {
943 self.add_lt_suggs.push(lt.suggestion(self.new_lt));
944 }
945 }
946 }
947
948 let (lifetime_def_id, lifetime_scope) =
949 match self.tcx.is_suitable_region(generic_param_scope, lifetime) {
950 Some(info) if !lifetime.is_named(self.tcx) => {
951 (info.region_def_id.expect_local(), info.scope)
952 }
953 _ => return lifetime.get_name_or_anon(self.tcx).to_string(),
954 };
955
956 let new_lt = {
957 let generics = self.tcx.generics_of(lifetime_scope);
958 let mut used_names =
959 iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
960 .flat_map(|g| &g.own_params)
961 .filter(|p| #[allow(non_exhaustive_omitted_patterns)] match p.kind {
ty::GenericParamDefKind::Lifetime => true,
_ => false,
}matches!(p.kind, ty::GenericParamDefKind::Lifetime))
962 .map(|p| p.name)
963 .collect::<Vec<_>>();
964 let hir_id = self.tcx.local_def_id_to_hir_id(lifetime_scope);
965 used_names.extend(self.tcx.late_bound_vars(hir_id).into_iter().filter_map(
967 |p| match p {
968 ty::BoundVariableKind::Region(lt) => lt.get_name(self.tcx),
969 _ => None,
970 },
971 ));
972 (b'a'..=b'z')
973 .map(|c| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}", c as char))
})format!("'{}", c as char))
974 .find(|candidate| !used_names.iter().any(|e| e.as_str() == candidate))
975 .unwrap_or_else(|| "'lt".to_string())
976 };
977
978 let mut visitor = LifetimeReplaceVisitor {
979 needle: hir::LifetimeKind::Param(lifetime_def_id),
980 add_lt_suggs,
981 new_lt: &new_lt,
982 };
983 match self.tcx.expect_hir_owner_node(lifetime_scope) {
984 hir::OwnerNode::Item(i) => visitor.visit_item(i),
985 hir::OwnerNode::ForeignItem(i) => visitor.visit_foreign_item(i),
986 hir::OwnerNode::ImplItem(i) => visitor.visit_impl_item(i),
987 hir::OwnerNode::TraitItem(i) => visitor.visit_trait_item(i),
988 hir::OwnerNode::Crate(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("OwnerNode::Crate doesn\'t not have generics"))bug!("OwnerNode::Crate doesn't not have generics"),
989 hir::OwnerNode::Synthetic => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
990 }
991
992 let ast_generics = self.tcx.hir_get_generics(lifetime_scope).unwrap();
993 let sugg = ast_generics
994 .span_for_lifetime_suggestion()
995 .map(|span| (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", new_lt))
})format!("{new_lt}, ")))
996 .unwrap_or_else(|| (ast_generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", new_lt))
})format!("<{new_lt}>")));
997 add_lt_suggs.push(sugg);
998
999 new_lt
1000 }
1001
1002 fn report_sub_sup_conflict(
1003 &self,
1004 generic_param_scope: LocalDefId,
1005 var_origin: RegionVariableOrigin<'tcx>,
1006 sub_origin: SubregionOrigin<'tcx>,
1007 sub_region: Region<'tcx>,
1008 sup_origin: SubregionOrigin<'tcx>,
1009 sup_region: Region<'tcx>,
1010 ) -> ErrorGuaranteed {
1011 let mut err = self.report_inference_failure(var_origin);
1012
1013 note_and_explain_region(
1014 self.tcx,
1015 &mut err,
1016 generic_param_scope,
1017 "first, the lifetime cannot outlive ",
1018 sup_region,
1019 "...",
1020 None,
1021 );
1022
1023 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1023",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(1023u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: var_origin={0:?}",
var_origin) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1024 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1024",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(1024u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: sub_region={0:?}",
sub_region) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1025 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1025",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(1025u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: sub_origin={0:?}",
sub_origin) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1026 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1026",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(1026u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: sup_region={0:?}",
sup_region) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1027 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1027",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(1027u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: sup_origin={0:?}",
sup_origin) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1028
1029 if let SubregionOrigin::Subtype(ref sup_trace) = sup_origin
1030 && let SubregionOrigin::Subtype(ref sub_trace) = sub_origin
1031 && let Some((sup_expected, sup_found)) =
1032 self.values_str(sup_trace.values, &sup_trace.cause, err.long_ty_path())
1033 && let Some((sub_expected, sub_found)) =
1034 self.values_str(sub_trace.values, &sub_trace.cause, err.long_ty_path())
1035 && sub_expected == sup_expected
1036 && sub_found == sup_found
1037 {
1038 note_and_explain_region(
1039 self.tcx,
1040 &mut err,
1041 generic_param_scope,
1042 "...but the lifetime must also be valid for ",
1043 sub_region,
1044 "...",
1045 None,
1046 );
1047 err.span_note(
1048 sup_trace.cause.span,
1049 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...so that the {0}",
sup_trace.cause.as_requirement_str()))
})format!("...so that the {}", sup_trace.cause.as_requirement_str()),
1050 );
1051
1052 err.note_expected_found("", sup_expected, "", sup_found);
1053 return if sub_region.is_error() | sup_region.is_error() {
1054 err.delay_as_bug()
1055 } else {
1056 err.emit()
1057 };
1058 }
1059
1060 self.note_region_origin(&mut err, &sup_origin);
1061
1062 note_and_explain_region(
1063 self.tcx,
1064 &mut err,
1065 generic_param_scope,
1066 "but, the lifetime must be valid for ",
1067 sub_region,
1068 "...",
1069 None,
1070 );
1071
1072 self.note_region_origin(&mut err, &sub_origin);
1073 if sub_region.is_error() | sup_region.is_error() { err.delay_as_bug() } else { err.emit() }
1074 }
1075
1076 fn report_inference_failure(&self, var_origin: RegionVariableOrigin<'tcx>) -> Diag<'_> {
1077 let br_string = |br: ty::BoundRegionKind<'tcx>| {
1078 let mut s = match br {
1079 ty::BoundRegionKind::Named(def_id) => self.tcx.item_name(def_id).to_string(),
1080 _ => String::new(),
1081 };
1082 if !s.is_empty() {
1083 s.push(' ');
1084 }
1085 s
1086 };
1087 let var_description = match var_origin {
1088 RegionVariableOrigin::Misc(_) => String::new(),
1089 RegionVariableOrigin::PatternRegion(_) => " for pattern".to_string(),
1090 RegionVariableOrigin::BorrowRegion(_) => " for borrow expression".to_string(),
1091 RegionVariableOrigin::Autoref(_) => " for autoref".to_string(),
1092 RegionVariableOrigin::Coercion(_) => " for automatic coercion".to_string(),
1093 RegionVariableOrigin::BoundRegion(_, br, BoundRegionConversionTime::FnCall) => {
1094 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" for lifetime parameter {0}in function call",
br_string(br)))
})format!(" for lifetime parameter {}in function call", br_string(br))
1095 }
1096 RegionVariableOrigin::BoundRegion(
1097 _,
1098 br,
1099 BoundRegionConversionTime::HigherRankedType,
1100 ) => {
1101 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" for lifetime parameter {0}in generic type",
br_string(br)))
})format!(" for lifetime parameter {}in generic type", br_string(br))
1102 }
1103 RegionVariableOrigin::BoundRegion(
1104 _,
1105 br,
1106 BoundRegionConversionTime::AssocTypeProjection(def_id),
1107 ) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" for lifetime parameter {0}in trait containing associated type `{1}`",
br_string(br), self.tcx.associated_item(def_id).name()))
})format!(
1108 " for lifetime parameter {}in trait containing associated type `{}`",
1109 br_string(br),
1110 self.tcx.associated_item(def_id).name()
1111 ),
1112 RegionVariableOrigin::RegionParameterDefinition(_, name) => {
1113 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" for lifetime parameter `{0}`",
name))
})format!(" for lifetime parameter `{name}`")
1114 }
1115 RegionVariableOrigin::UpvarRegion(ref upvar_id, _) => {
1116 let var_name = self.tcx.hir_name(upvar_id.var_path.hir_id);
1117 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" for capture of `{0}` by closure",
var_name))
})format!(" for capture of `{var_name}` by closure")
1118 }
1119 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable found in lexical phase"))bug!("NLL variable found in lexical phase"),
1120 };
1121
1122 {
self.dcx().struct_span_err(var_origin.span(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot infer an appropriate lifetime{0} due to conflicting requirements",
var_description))
})).with_code(E0803)
}struct_span_code_err!(
1123 self.dcx(),
1124 var_origin.span(),
1125 E0803,
1126 "cannot infer an appropriate lifetime{} due to conflicting requirements",
1127 var_description
1128 )
1129 }
1130}
1131
1132enum LifetimeSuggestion {
1133 NeedsPlus(Option<Span>),
1134 NeedsColon,
1135 HasColon,
1136}
1137
1138pub(super) fn note_and_explain_region<'tcx>(
1139 tcx: TyCtxt<'tcx>,
1140 err: &mut Diag<'_>,
1141 generic_param_scope: LocalDefId,
1142 prefix: &str,
1143 region: ty::Region<'tcx>,
1144 suffix: &str,
1145 alt_span: Option<Span>,
1146) {
1147 let (description, span) = match region.kind() {
1148 ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::RePlaceholder(_) | ty::ReStatic => {
1149 msg_span_from_named_region(tcx, generic_param_scope, region, alt_span)
1150 }
1151
1152 ty::ReError(_) => return,
1153
1154 ty::ReVar(_) => (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}`", region))
})format!("lifetime `{region}`"), alt_span),
1156
1157 ty::ReBound(..) | ty::ReErased => {
1158 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected region for note_and_explain_region: {0:?}",
region));bug!("unexpected region for note_and_explain_region: {:?}", region);
1159 }
1160 };
1161
1162 emit_msg_span(err, prefix, description, span, suffix);
1163}
1164
1165fn explain_free_region<'tcx>(
1166 tcx: TyCtxt<'tcx>,
1167 err: &mut Diag<'_>,
1168 generic_param_scope: LocalDefId,
1169 prefix: &str,
1170 region: ty::Region<'tcx>,
1171 suffix: &str,
1172) {
1173 let (description, span) = msg_span_from_named_region(tcx, generic_param_scope, region, None);
1174
1175 label_msg_span(err, prefix, description, span, suffix);
1176}
1177
1178fn msg_span_from_named_region<'tcx>(
1179 tcx: TyCtxt<'tcx>,
1180 generic_param_scope: LocalDefId,
1181 region: ty::Region<'tcx>,
1182 alt_span: Option<Span>,
1183) -> (String, Option<Span>) {
1184 match region.kind() {
1185 ty::ReEarlyParam(br) => {
1186 let param_def_id = tcx.generics_of(generic_param_scope).region_param(br, tcx).def_id;
1187 let span = tcx.def_span(param_def_id);
1188 let text = if br.is_named() {
1189 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the lifetime `{0}` as defined here",
br.name))
})format!("the lifetime `{}` as defined here", br.name)
1190 } else {
1191 "the anonymous lifetime as defined here".to_string()
1192 };
1193 (text, Some(span))
1194 }
1195 ty::ReLateParam(ref fr) => {
1196 if !fr.kind.is_named(tcx)
1197 && let Some((ty, _)) = find_anon_type(tcx, generic_param_scope, region)
1198 {
1199 ("the anonymous lifetime defined here".to_string(), Some(ty.span))
1200 } else {
1201 match fr.kind {
1202 ty::LateParamRegionKind::Named(param_def_id) => {
1203 let name = tcx.item_name(param_def_id);
1204 let span = tcx.def_span(param_def_id);
1205 let text = if name == kw::UnderscoreLifetime {
1206 "the anonymous lifetime as defined here".to_string()
1207 } else {
1208 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the lifetime `{0}` as defined here",
name))
})format!("the lifetime `{name}` as defined here")
1209 };
1210 (text, Some(span))
1211 }
1212 ty::LateParamRegionKind::Anon(_) => (
1213 "the anonymous lifetime as defined here".to_string(),
1214 Some(tcx.def_span(generic_param_scope)),
1215 ),
1216 _ => (
1217 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the lifetime `{0}` as defined here",
region))
})format!("the lifetime `{region}` as defined here"),
1218 Some(tcx.def_span(generic_param_scope)),
1219 ),
1220 }
1221 }
1222 }
1223 ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
1224 ty::RePlaceholder(ty::PlaceholderRegion {
1225 bound: ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. },
1226 ..
1227 }) => (
1228 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the lifetime `{0}` as defined here",
tcx.item_name(def_id)))
})format!("the lifetime `{}` as defined here", tcx.item_name(def_id)),
1229 Some(tcx.def_span(def_id)),
1230 ),
1231 ty::RePlaceholder(ty::PlaceholderRegion {
1232 bound: ty::BoundRegion { kind: ty::BoundRegionKind::Anon, .. },
1233 ..
1234 }) => ("an anonymous lifetime".to_owned(), None),
1235 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?}", region))bug!("{:?}", region),
1236 }
1237}
1238
1239fn emit_msg_span(
1240 err: &mut Diag<'_>,
1241 prefix: &str,
1242 description: String,
1243 span: Option<Span>,
1244 suffix: &str,
1245) {
1246 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, description,
suffix))
})format!("{prefix}{description}{suffix}");
1247
1248 if let Some(span) = span {
1249 err.span_note(span, message);
1250 } else {
1251 err.note(message);
1252 }
1253}
1254
1255fn label_msg_span(
1256 err: &mut Diag<'_>,
1257 prefix: &str,
1258 description: String,
1259 span: Option<Span>,
1260 suffix: &str,
1261) {
1262 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, description,
suffix))
})format!("{prefix}{description}{suffix}");
1263
1264 if let Some(span) = span {
1265 err.span_label(span, message);
1266 } else {
1267 err.note(message);
1268 }
1269}
1270
1271#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("unexpected_hidden_region_diagnostic",
"rustc_trait_selection::error_reporting::infer::region",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
::tracing_core::__macro_support::Option::Some(1271u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("generic_param_scope")
}> =
::tracing::__macro_support::FieldName::new("generic_param_scope");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("hidden_ty")
}> =
::tracing::__macro_support::FieldName::new("hidden_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("hidden_region")
}> =
::tracing::__macro_support::FieldName::new("hidden_region");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("opaque_ty_key")
}> =
::tracing::__macro_support::FieldName::new("opaque_ty_key");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_param_scope)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hidden_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hidden_region)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opaque_ty_key)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Diag<'a> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = infcx.tcx;
let mut err =
infcx.dcx().create_err(diagnostics::OpaqueCapturesLifetime {
span,
opaque_ty: Ty::new_opaque(tcx, ty::IsRigid::No,
opaque_ty_key.def_id.to_def_id(), opaque_ty_key.args),
opaque_ty_span: tcx.def_span(opaque_ty_key.def_id),
});
let mut highlight = RegionHighlightMode::default();
highlight.keep_regions = true;
let hidden_ty =
Highlighted {
highlight,
ns: Namespace::TypeNS,
tcx,
value: hidden_ty,
};
match hidden_region.kind() {
ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::ReStatic => {
explain_free_region(tcx, &mut err, generic_param_scope,
&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("hidden type `{0}` captures ",
hidden_ty))
}), hidden_region, "");
if let Some(_) =
tcx.is_suitable_region(generic_param_scope, hidden_region) {
suggest_precise_capturing(tcx, opaque_ty_key.def_id,
hidden_region, &mut err);
}
}
ty::RePlaceholder(_) => {
explain_free_region(tcx, &mut err, generic_param_scope,
&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("hidden type `{0}` captures ",
hidden_ty))
}), hidden_region, "");
}
ty::ReError(_) => { err.downgrade_to_delayed_bug(); }
_ => {
note_and_explain_region(tcx, &mut err, generic_param_scope,
&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("hidden type `{0}` captures ",
hidden_ty))
}), hidden_region, "", None);
}
}
err
}
}
}#[instrument(level = "trace", skip(infcx))]
1272pub fn unexpected_hidden_region_diagnostic<'a, 'tcx>(
1273 infcx: &'a InferCtxt<'tcx>,
1274 generic_param_scope: LocalDefId,
1275 span: Span,
1276 hidden_ty: Ty<'tcx>,
1277 hidden_region: ty::Region<'tcx>,
1278 opaque_ty_key: ty::OpaqueTypeKey<'tcx>,
1279) -> Diag<'a> {
1280 let tcx = infcx.tcx;
1281 let mut err = infcx.dcx().create_err(diagnostics::OpaqueCapturesLifetime {
1282 span,
1283 opaque_ty: Ty::new_opaque(
1284 tcx,
1285 ty::IsRigid::No,
1286 opaque_ty_key.def_id.to_def_id(),
1287 opaque_ty_key.args,
1288 ),
1289 opaque_ty_span: tcx.def_span(opaque_ty_key.def_id),
1290 });
1291 let mut highlight = RegionHighlightMode::default();
1292 highlight.keep_regions = true;
1293 let hidden_ty = Highlighted { highlight, ns: Namespace::TypeNS, tcx, value: hidden_ty };
1294
1295 match hidden_region.kind() {
1297 ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::ReStatic => {
1298 explain_free_region(
1307 tcx,
1308 &mut err,
1309 generic_param_scope,
1310 &format!("hidden type `{hidden_ty}` captures "),
1311 hidden_region,
1312 "",
1313 );
1314 if let Some(_) = tcx.is_suitable_region(generic_param_scope, hidden_region) {
1315 suggest_precise_capturing(tcx, opaque_ty_key.def_id, hidden_region, &mut err);
1316 }
1317 }
1318 ty::RePlaceholder(_) => {
1319 explain_free_region(
1320 tcx,
1321 &mut err,
1322 generic_param_scope,
1323 &format!("hidden type `{}` captures ", hidden_ty),
1324 hidden_region,
1325 "",
1326 );
1327 }
1328 ty::ReError(_) => {
1329 err.downgrade_to_delayed_bug();
1330 }
1331 _ => {
1332 note_and_explain_region(
1348 tcx,
1349 &mut err,
1350 generic_param_scope,
1351 &format!("hidden type `{hidden_ty}` captures "),
1352 hidden_region,
1353 "",
1354 None,
1355 );
1356 }
1357 }
1358
1359 err
1360}
1361
1362fn suggest_precise_capturing<'tcx>(
1363 tcx: TyCtxt<'tcx>,
1364 opaque_def_id: LocalDefId,
1365 captured_lifetime: ty::Region<'tcx>,
1366 diag: &mut Diag<'_>,
1367) {
1368 let hir::OpaqueTy { bounds, origin, .. } =
1369 tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
1370
1371 let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. } = *origin else {
1372 return;
1373 };
1374
1375 let new_lifetime = Symbol::intern(&captured_lifetime.to_string());
1376
1377 if let Some((args, span)) = bounds.iter().find_map(|bound| match bound {
1378 hir::GenericBound::Use(args, span) => Some((args, span)),
1379 _ => None,
1380 }) {
1381 let last_lifetime_span = args.iter().rev().find_map(|arg| match arg {
1382 hir::PreciseCapturingArg::Lifetime(lt) => Some(lt.ident.span),
1383 _ => None,
1384 });
1385
1386 let first_param_span = args.iter().find_map(|arg| match arg {
1387 hir::PreciseCapturingArg::Param(p) => Some(p.ident.span),
1388 _ => None,
1389 });
1390
1391 let (span, pre, post) = if let Some(last_lifetime_span) = last_lifetime_span {
1392 (last_lifetime_span.shrink_to_hi(), ", ", "")
1393 } else if let Some(first_param_span) = first_param_span {
1394 (first_param_span.shrink_to_lo(), "", ", ")
1395 } else {
1396 (span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(), "", "")
1400 };
1401
1402 diag.subdiagnostic(diagnostics::AddPreciseCapturing::Existing {
1403 span,
1404 new_lifetime,
1405 pre,
1406 post,
1407 });
1408 } else {
1409 let mut captured_lifetimes = FxIndexSet::default();
1410 let mut captured_non_lifetimes = FxIndexSet::default();
1411
1412 let variances = tcx.variances_of(opaque_def_id);
1413 let mut generics = tcx.generics_of(opaque_def_id);
1414 let mut synthetics = ::alloc::vec::Vec::new()vec![];
1415 loop {
1416 for param in &generics.own_params {
1417 if variances[param.index as usize] == ty::Bivariant {
1418 continue;
1419 }
1420
1421 match param.kind {
1422 ty::GenericParamDefKind::Lifetime => {
1423 captured_lifetimes.insert(param.name);
1424 }
1425 ty::GenericParamDefKind::Type { synthetic: true, .. } => {
1426 synthetics.push((tcx.def_span(param.def_id), param.name));
1427 }
1428 ty::GenericParamDefKind::Type { .. }
1429 | ty::GenericParamDefKind::Const { .. } => {
1430 captured_non_lifetimes.insert(param.name);
1431 }
1432 }
1433 }
1434
1435 if let Some(parent) = generics.parent {
1436 generics = tcx.generics_of(parent);
1437 } else {
1438 break;
1439 }
1440 }
1441
1442 if !captured_lifetimes.insert(new_lifetime) {
1443 return;
1445 }
1446
1447 if synthetics.is_empty() {
1448 let concatenated_bounds = captured_lifetimes
1449 .into_iter()
1450 .chain(captured_non_lifetimes)
1451 .map(|sym| sym.to_string())
1452 .collect::<Vec<_>>()
1453 .join(", ");
1454
1455 diag.subdiagnostic(diagnostics::AddPreciseCapturing::New {
1456 span: tcx.def_span(opaque_def_id).shrink_to_hi(),
1457 new_lifetime,
1458 concatenated_bounds,
1459 });
1460 } else {
1461 let mut next_fresh_param = || {
1462 ['T', 'U', 'V', 'W', 'X', 'Y', 'A', 'B', 'C']
1463 .into_iter()
1464 .map(sym::character)
1465 .chain((0..).map(|i| Symbol::intern(&::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("T{0}", i)) })format!("T{i}"))))
1466 .find(|s| captured_non_lifetimes.insert(*s))
1467 .unwrap()
1468 };
1469
1470 let mut new_params = String::new();
1471 let mut suggs = ::alloc::vec::Vec::new()vec![];
1472 let mut apit_spans = ::alloc::vec::Vec::new()vec![];
1473
1474 for (i, (span, name)) in synthetics.into_iter().enumerate() {
1475 apit_spans.push(span);
1476
1477 let fresh_param = next_fresh_param();
1478
1479 suggs.push((span, fresh_param.to_string()));
1481
1482 if i > 0 {
1490 new_params += ", ";
1491 }
1492 let name_as_bounds = name.as_str().trim_start_matches("impl").trim_start();
1493 new_params += fresh_param.as_str();
1494 new_params += ": ";
1495 new_params += name_as_bounds;
1496 }
1497
1498 let Some(generics) = tcx.hir_get_generics(fn_def_id) else {
1499 return;
1501 };
1502
1503 suggs.push(if let Some(params_span) = generics.span_for_param_suggestion() {
1505 (params_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", new_params))
})format!(", {new_params}"))
1506 } else {
1507 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", new_params))
})format!("<{new_params}>"))
1508 });
1509
1510 let concatenated_bounds = captured_lifetimes
1511 .into_iter()
1512 .chain(captured_non_lifetimes)
1513 .map(|sym| sym.to_string())
1514 .collect::<Vec<_>>()
1515 .join(", ");
1516
1517 suggs.push((
1518 tcx.def_span(opaque_def_id).shrink_to_hi(),
1519 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + use<{0}>", concatenated_bounds))
})format!(" + use<{concatenated_bounds}>"),
1520 ));
1521
1522 diag.subdiagnostic(diagnostics::AddPreciseCapturingAndParams {
1523 suggs,
1524 new_lifetime,
1525 apit_spans,
1526 });
1527 }
1528 }
1529}