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