1use std::cell::LazyCell;
2use std::debug_assert_matches;
3
4use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
5use rustc_data_structures::unord::UnordSet;
6use rustc_errors::{Diagnostic, Subdiagnostic, msg};
7use rustc_hir as hir;
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::{DefId, LocalDefId};
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_infer::infer::outlives::env::OutlivesEnvironment;
12use rustc_lint_defs::{declare_lint, declare_lint_pass, fcw};
13use rustc_macros::Diagnostic;
14use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
15use rustc_middle::ty::relate::{
16 Relate, RelateResult, TypeRelation, relate_args_with_variances, structurally_relate_consts,
17 structurally_relate_tys,
18};
19use rustc_middle::ty::{
20 self, RegionExt, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
21 Unnormalized,
22};
23use rustc_middle::{bug, span_bug};
24use rustc_span::{Span, Symbol};
25use rustc_trait_selection::diagnostics::{
26 AddPreciseCapturingForOvercapture, impl_trait_overcapture_suggestion,
27};
28use rustc_trait_selection::regions::OutlivesEnvironmentBuildExt;
29use rustc_trait_selection::traits::ObligationCtxt;
30
31use crate::{LateContext, LateLintPass};
32
33#[doc =
r" The `impl_trait_overcaptures` lint warns against cases where lifetime"]
#[doc = r" capture behavior will differ in edition 2024."]
#[doc = r""]
#[doc =
r" In the 2024 edition, `impl Trait`s will capture all lifetimes in scope,"]
#[doc =
r" rather than just the lifetimes that are mentioned in the bounds of the type."]
#[doc =
r" Often these sets are equal, but if not, it means that the `impl Trait` may"]
#[doc = r" cause erroneous borrow-checker errors."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail,edition2021"]
#[doc = r" # #![deny(impl_trait_overcaptures)]"]
#[doc = r" # use std::fmt::Display;"]
#[doc = r" let mut x = vec![];"]
#[doc = r" x.push(1);"]
#[doc = r""]
#[doc = r" fn test(x: &Vec<i32>) -> impl Display {"]
#[doc = r" x[0]"]
#[doc = r" }"]
#[doc = r""]
#[doc = r" let element = test(&x);"]
#[doc = r" x.push(2);"]
#[doc = r#" println!("{element}");"#]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" In edition < 2024, the returned `impl Display` doesn't capture the"]
#[doc =
r" lifetime from the `&Vec<i32>`, so the vector can be mutably borrowed"]
#[doc = r" while the `impl Display` is live."]
#[doc = r""]
#[doc =
r" To fix this, we can explicitly state that the `impl Display` doesn't"]
#[doc = r" capture any lifetimes, using `impl Display + use<>`."]
pub static IMPL_TRAIT_OVERCAPTURES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "IMPL_TRAIT_OVERCAPTURES",
default_level: ::rustc_lint_defs::Allow,
desc: "`impl Trait` will capture more lifetimes than possibly intended in edition 2024",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionSemanticsChange(::rustc_lint_defs::EditionFcw {
edition: rustc_span::edition::Edition::Edition2024,
page_slug: "rpit-lifetime-capture",
}),
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
34 pub IMPL_TRAIT_OVERCAPTURES,
70 Allow,
71 "`impl Trait` will capture more lifetimes than possibly intended in edition 2024",
72 @future_incompatible = FutureIncompatibleInfo {
73 reason: fcw!(EditionSemanticsChange 2024 "rpit-lifetime-capture"),
74 };
75}
76
77#[doc =
r" The `impl_trait_redundant_captures` lint warns against cases where use of the"]
#[doc = r" precise capturing `use<...>` syntax is not needed."]
#[doc = r""]
#[doc =
r" In the 2024 edition, `impl Trait`s will capture all lifetimes in scope."]
#[doc =
r" If precise-capturing `use<...>` syntax is used, and the set of parameters"]
#[doc =
r" that are captures are *equal* to the set of parameters in scope, then"]
#[doc = r" the syntax is redundant, and can be removed."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2024,compile_fail"]
#[doc = r" # #![deny(impl_trait_redundant_captures)]"]
#[doc = r" fn test<'a>(x: &'a i32) -> impl Sized + use<'a> { x }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" To fix this, remove the `use<'a>`, since the lifetime is already captured"]
#[doc = r" since it is in scope."]
pub static IMPL_TRAIT_REDUNDANT_CAPTURES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "IMPL_TRAIT_REDUNDANT_CAPTURES",
default_level: ::rustc_lint_defs::Allow,
desc: "redundant precise-capturing `use<...>` syntax on an `impl Trait`",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
78 pub IMPL_TRAIT_REDUNDANT_CAPTURES,
100 Allow,
101 "redundant precise-capturing `use<...>` syntax on an `impl Trait`",
102}
103
104#[doc =
r" Lint for opaque types that will begin capturing in-scope but unmentioned lifetimes"]
#[doc = r" in edition 2024."]
pub struct ImplTraitOvercaptures;
#[automatically_derived]
impl ::core::marker::Copy for ImplTraitOvercaptures { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ImplTraitOvercaptures { }
#[automatically_derived]
impl ::core::clone::Clone for ImplTraitOvercaptures {
#[inline]
fn clone(&self) -> ImplTraitOvercaptures { *self }
}
impl ::rustc_lint_defs::LintPass for ImplTraitOvercaptures {
fn name(&self) -> &'static str { "ImplTraitOvercaptures" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[IMPL_TRAIT_OVERCAPTURES, IMPL_TRAIT_REDUNDANT_CAPTURES]))
}
}
impl ImplTraitOvercaptures {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[IMPL_TRAIT_OVERCAPTURES, IMPL_TRAIT_REDUNDANT_CAPTURES]))
}
}declare_lint_pass!(
105 ImplTraitOvercaptures => [IMPL_TRAIT_OVERCAPTURES, IMPL_TRAIT_REDUNDANT_CAPTURES]
108);
109
110impl<'tcx> LateLintPass<'tcx> for ImplTraitOvercaptures {
111 fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx hir::Item<'tcx>) {
112 match &it.kind {
113 hir::ItemKind::Fn { .. } => check_fn(cx.tcx, it.owner_id.def_id),
114 _ => {}
115 }
116 }
117
118 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx hir::ImplItem<'tcx>) {
119 match &it.kind {
120 hir::ImplItemKind::Fn(_, _) => check_fn(cx.tcx, it.owner_id.def_id),
121 _ => {}
122 }
123 }
124
125 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx hir::TraitItem<'tcx>) {
126 match &it.kind {
127 hir::TraitItemKind::Fn(_, _) => check_fn(cx.tcx, it.owner_id.def_id),
128 _ => {}
129 }
130 }
131}
132
133#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for ParamKind {
#[inline]
fn eq(&self, other: &ParamKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ParamKind::Early(__self_0, __self_1),
ParamKind::Early(__arg1_0, __arg1_1)) =>
__self_1 == __arg1_1 && __self_0 == __arg1_0,
(ParamKind::Free(__self_0), ParamKind::Free(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ParamKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Symbol>;
let _: ::core::cmp::AssertParamIsEq<u32>;
let _: ::core::cmp::AssertParamIsEq<DefId>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ParamKind {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
ParamKind::Early(__self_0, __self_1) => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
ParamKind::Free(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for ParamKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ParamKind::Early(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Early",
__self_0, &__self_1),
ParamKind::Free(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Free",
&__self_0),
ParamKind::Late => ::core::fmt::Formatter::write_str(f, "Late"),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ParamKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ParamKind {
#[inline]
fn clone(&self) -> ParamKind {
let _: ::core::clone::AssertParamIsClone<Symbol>;
let _: ::core::clone::AssertParamIsClone<u32>;
let _: ::core::clone::AssertParamIsClone<DefId>;
*self
}
}Clone)]
134enum ParamKind {
135 Early(Symbol, u32),
137 Free(DefId),
139 Late,
141}
142
143fn check_fn(tcx: TyCtxt<'_>, parent_def_id: LocalDefId) {
144 let sig = tcx.fn_sig(parent_def_id).instantiate_identity().skip_norm_wip();
145
146 let mut in_scope_parameters = FxIndexMap::default();
147 let mut current_def_id = Some(parent_def_id.to_def_id());
149 while let Some(def_id) = current_def_id {
150 let generics = tcx.generics_of(def_id);
151 for param in &generics.own_params {
152 in_scope_parameters.insert(param.def_id, ParamKind::Early(param.name, param.index));
153 }
154 current_def_id = generics.parent;
155 }
156
157 for bound_var in sig.bound_vars() {
158 let ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) = bound_var else {
159 ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(parent_def_id),
format_args!("unexpected non-lifetime binder on fn sig"));span_bug!(tcx.def_span(parent_def_id), "unexpected non-lifetime binder on fn sig");
160 };
161
162 in_scope_parameters.insert(def_id, ParamKind::Free(def_id));
163 }
164
165 let sig = tcx.liberate_late_bound_regions(parent_def_id.to_def_id(), sig);
166
167 sig.visit_with(&mut VisitOpaqueTypes {
170 tcx,
171 parent_def_id,
172 in_scope_parameters,
173 seen: Default::default(),
174 variances: LazyCell::new(|| {
176 let mut functional_variances = FunctionalVariances {
177 tcx,
178 variances: FxHashMap::default(),
179 ambient_variance: ty::Covariant,
180 generics: tcx.generics_of(parent_def_id),
181 };
182 functional_variances.relate(sig, sig).unwrap();
183 functional_variances.variances
184 }),
185 outlives_env: LazyCell::new(|| {
186 let typing_env = ty::TypingEnv::non_body_analysis(tcx, parent_def_id);
187 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
188 let ocx = ObligationCtxt::new(&infcx);
189 let assumed_wf_tys = ocx.assumed_wf_types(param_env, parent_def_id).unwrap_or_default();
190 OutlivesEnvironment::new(&infcx, parent_def_id, param_env, assumed_wf_tys)
191 }),
192 });
193}
194
195struct VisitOpaqueTypes<'tcx, VarFn, OutlivesFn> {
196 tcx: TyCtxt<'tcx>,
197 parent_def_id: LocalDefId,
198 in_scope_parameters: FxIndexMap<DefId, ParamKind>,
199 variances: LazyCell<FxHashMap<DefId, ty::Variance>, VarFn>,
200 outlives_env: LazyCell<OutlivesEnvironment<'tcx>, OutlivesFn>,
201 seen: FxIndexSet<LocalDefId>,
202}
203
204impl<'tcx, VarFn, OutlivesFn> TypeVisitor<TyCtxt<'tcx>>
205 for VisitOpaqueTypes<'tcx, VarFn, OutlivesFn>
206where
207 VarFn: FnOnce() -> FxHashMap<DefId, ty::Variance>,
208 OutlivesFn: FnOnce() -> OutlivesEnvironment<'tcx>,
209{
210 fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(&mut self, t: &ty::Binder<'tcx, T>) {
211 let mut added = ::alloc::vec::Vec::new()vec![];
213 for arg in t.bound_vars() {
214 let arg: ty::BoundVariableKind<'tcx> = arg;
215 match arg {
216 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id))
217 | ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)) => {
218 let previous = self.in_scope_parameters.insert(def_id, ParamKind::Late);
223 added.push((def_id, previous));
224 }
225 _ => {
226 self.tcx.dcx().span_delayed_bug(
227 self.tcx.def_span(self.parent_def_id),
228 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsupported bound variable kind: {0:?}",
arg))
})format!("unsupported bound variable kind: {arg:?}"),
229 );
230 }
231 }
232 }
233
234 t.super_visit_with(self);
235
236 for (arg, previous) in added.into_iter().rev() {
238 if let Some(previous) = previous {
239 self.in_scope_parameters.insert(arg, previous);
240 } else {
241 self.in_scope_parameters.shift_remove(&arg);
242 }
243 }
244 }
245
246 fn visit_ty(&mut self, t: Ty<'tcx>) {
247 if !t.has_aliases() {
248 return;
249 }
250
251 if let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. }) = *t.kind()
252 && self.tcx.is_impl_trait_in_trait(def_id)
253 {
254 self.tcx.type_of(def_id).instantiate(self.tcx, args).skip_norm_wip().visit_with(self)
256 } else if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args: opaque_ty_args, .. }) = *t.kind()
257 && let Some(opaque_def_id) = def_id.as_local()
258 && self.seen.insert(opaque_def_id)
260 && let opaque =
262 self.tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty()
263 && let hir::OpaqueTyOrigin::FnReturn { parent, .. }
267 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = opaque.origin
268 && parent == self.parent_def_id
269 {
270 let opaque_span = self.tcx.def_span(opaque_def_id);
271 let new_capture_rules = opaque_span.at_least_rust_2024();
272 if !new_capture_rules
273 && !opaque.bounds.iter().any(|bound| #[allow(non_exhaustive_omitted_patterns)] match bound {
hir::GenericBound::Use(..) => true,
_ => false,
}matches!(bound, hir::GenericBound::Use(..)))
274 {
275 let mut captured = FxIndexSet::default();
277 let mut captured_regions = FxIndexSet::default();
278 let variances = self.tcx.variances_of(opaque_def_id);
279 let mut current_def_id = Some(opaque_def_id.to_def_id());
280 while let Some(def_id) = current_def_id {
281 let generics = self.tcx.generics_of(def_id);
282 for param in &generics.own_params {
283 if variances[param.index as usize] != ty::Invariant {
285 continue;
286 }
287
288 let arg = opaque_ty_args[param.index as usize];
289 captured.insert(extract_def_id_from_arg(self.tcx, generics, arg));
292
293 captured_regions.extend(arg.as_region());
294 }
295 current_def_id = generics.parent;
296 }
297
298 let mut uncaptured_args: FxIndexSet<_> = self
300 .in_scope_parameters
301 .iter()
302 .filter(|&(def_id, _)| !captured.contains(def_id))
303 .collect();
304 uncaptured_args.retain(|&(def_id, kind)| {
307 let Some(ty::Bivariant | ty::Contravariant) = self.variances.get(def_id) else {
308 return true;
312 };
313 if true {
{
match self.tcx.def_kind(*def_id) {
DefKind::LifetimeParam => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::LifetimeParam", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.tcx.def_kind(*def_id), DefKind::LifetimeParam);
315 let uncaptured = match *kind {
316 ParamKind::Early(name, index) => ty::Region::new_early_param(
317 self.tcx,
318 ty::EarlyParamRegion { name, index },
319 ),
320 ParamKind::Free(def_id) => ty::Region::new_late_param(
321 self.tcx,
322 self.parent_def_id.to_def_id(),
323 ty::LateParamRegionKind::Named(def_id),
324 ),
325 ParamKind::Late => return true,
327 };
328 !captured_regions.iter().any(|r| {
330 self.outlives_env
331 .free_region_map()
332 .sub_free_regions(self.tcx, *r, uncaptured)
333 })
334 });
335
336 if !uncaptured_args.is_empty() {
339 let suggestion = impl_trait_overcapture_suggestion(
340 self.tcx,
341 opaque_def_id,
342 self.parent_def_id,
343 captured,
344 );
345
346 let uncaptured_spans: Vec<_> = uncaptured_args
347 .into_iter()
348 .map(|(&def_id, _)| self.tcx.def_span(def_id))
349 .collect();
350
351 self.tcx.emit_node_span_lint(
352 IMPL_TRAIT_OVERCAPTURES,
353 self.tcx.local_def_id_to_hir_id(opaque_def_id),
354 opaque_span,
355 ImplTraitOvercapturesLint {
356 self_ty: t,
357 num_captured: uncaptured_spans.len(),
358 uncaptured_spans,
359 suggestion,
360 },
361 );
362 }
363 }
364
365 if new_capture_rules
369 && let Some((use_idx, captured_args, capturing_span)) =
370 opaque.bounds.iter().enumerate().find_map(|(i, bound)| match *bound {
371 hir::GenericBound::Use(a, s) => Some((i, a, s)),
372 _ => None,
373 })
374 {
375 let mut explicitly_captured = UnordSet::default();
376 for arg in captured_args {
377 match self.tcx.named_bound_var(arg.hir_id()) {
378 Some(
379 ResolvedArg::EarlyBound(def_id) | ResolvedArg::LateBound(_, _, def_id),
380 ) => {
381 if self.tcx.def_kind(self.tcx.local_parent(def_id)) == DefKind::OpaqueTy
382 {
383 let def_id = self
384 .tcx
385 .map_opaque_lifetime_to_parent_lifetime(def_id)
386 .opt_param_def_id(self.tcx, self.parent_def_id.to_def_id())
387 .expect("variable should have been duplicated from parent");
388
389 explicitly_captured.insert(def_id);
390 } else {
391 explicitly_captured.insert(def_id.to_def_id());
392 }
393 }
394 _ => {
395 self.tcx.dcx().span_delayed_bug(
396 self.tcx.hir_span(arg.hir_id()),
397 "no valid for captured arg",
398 );
399 }
400 }
401 }
402
403 if self
404 .in_scope_parameters
405 .iter()
406 .all(|(def_id, _)| explicitly_captured.contains(def_id))
407 {
408 let suggestion_span = if let Some(next) = opaque.bounds.get(use_idx + 1) {
412 capturing_span.with_hi(next.span().lo())
413 } else if let Some(prev_idx) = use_idx.checked_sub(1) {
414 let prev = opaque.bounds[prev_idx];
415 capturing_span.with_lo(prev.span().hi())
416 } else {
417 capturing_span
420 };
421
422 self.tcx.emit_node_span_lint(
423 IMPL_TRAIT_REDUNDANT_CAPTURES,
424 self.tcx.local_def_id_to_hir_id(opaque_def_id),
425 opaque_span,
426 ImplTraitRedundantCapturesLint { capturing_span: suggestion_span },
427 );
428 }
429 }
430
431 for clause in self
436 .tcx
437 .item_bounds(def_id)
438 .iter_instantiated(self.tcx, opaque_ty_args)
439 .map(Unnormalized::skip_norm_wip)
440 {
441 clause.visit_with(self)
442 }
443 }
444
445 t.super_visit_with(self);
446 }
447}
448
449struct ImplTraitOvercapturesLint<'tcx> {
450 uncaptured_spans: Vec<Span>,
451 self_ty: Ty<'tcx>,
452 num_captured: usize,
453 suggestion: Option<AddPreciseCapturingForOvercapture>,
454}
455
456impl<'a> Diagnostic<'a, ()> for ImplTraitOvercapturesLint<'_> {
457 fn into_diag(
458 self,
459 dcx: rustc_errors::DiagCtxtHandle<'a>,
460 level: rustc_errors::Level,
461 ) -> rustc_errors::Diag<'a, ()> {
462 let mut diag = rustc_errors::Diag::new(
463 dcx,
464 level,
465 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$self_ty}` will capture more lifetimes than possibly intended in edition 2024"))msg!("`{$self_ty}` will capture more lifetimes than possibly intended in edition 2024"),
466 );
467 diag.arg("self_ty", self.self_ty.to_string())
468 .arg("num_captured", self.num_captured)
469 .span_note(
470 self.uncaptured_spans,
471 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("specifically, {$num_captured ->\n [one] this lifetime is\n *[other] these lifetimes are\n } in scope but not mentioned in the type's bounds"))msg!(
472 "specifically, {$num_captured ->
473 [one] this lifetime is
474 *[other] these lifetimes are
475 } in scope but not mentioned in the type's bounds"
476 ),
477 )
478 .note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("all lifetimes in scope will be captured by `impl Trait`s in edition 2024"))msg!("all lifetimes in scope will be captured by `impl Trait`s in edition 2024"));
479 if let Some(suggestion) = self.suggestion {
480 suggestion.add_to_diag(&mut diag);
481 }
482 diag
483 }
484}
485
486#[derive(const _: () =
{
impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
ImplTraitRedundantCapturesLint where
G: rustc_errors::EmissionGuarantee {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
match self {
ImplTraitRedundantCapturesLint { capturing_span: __binding_0
} => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("all possible in-scope parameters are already captured, so `use<...>` syntax is redundant")));
let __code_107 =
[::alloc::__export::must_use({
::alloc::fmt::format(format_args!(""))
})].into_iter();
;
diag.span_suggestions_with_style(__binding_0,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("remove the `use<...>` syntax")),
__code_107, rustc_errors::Applicability::MachineApplicable,
rustc_errors::SuggestionStyle::ShowCode);
diag
}
}
}
}
};Diagnostic)]
487#[diag("all possible in-scope parameters are already captured, so `use<...>` syntax is redundant")]
488struct ImplTraitRedundantCapturesLint {
489 #[suggestion("remove the `use<...>` syntax", code = "", applicability = "machine-applicable")]
490 capturing_span: Span,
491}
492
493fn extract_def_id_from_arg<'tcx>(
494 tcx: TyCtxt<'tcx>,
495 generics: &'tcx ty::Generics,
496 arg: ty::GenericArg<'tcx>,
497) -> DefId {
498 match arg.kind() {
499 ty::GenericArgKind::Lifetime(re) => match re.kind() {
500 ty::ReEarlyParam(ebr) => generics.region_param(ebr, tcx).def_id,
501 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. })
502 | ty::ReLateParam(ty::LateParamRegion {
503 scope: _,
504 kind: ty::LateParamRegionKind::Named(def_id),
505 }) => def_id,
506 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
507 },
508 ty::GenericArgKind::Type(ty) => {
509 let ty::Param(param_ty) = *ty.kind() else {
510 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
511 };
512 generics.type_param(param_ty, tcx).def_id
513 }
514 ty::GenericArgKind::Const(ct) => {
515 let ty::ConstKind::Param(param_ct) = ct.kind() else {
516 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
517 };
518 generics.const_param(param_ct, tcx).def_id
519 }
520 }
521}
522
523struct FunctionalVariances<'tcx> {
530 tcx: TyCtxt<'tcx>,
531 variances: FxHashMap<DefId, ty::Variance>,
532 ambient_variance: ty::Variance,
533 generics: &'tcx ty::Generics,
534}
535
536impl<'tcx> TypeRelation<TyCtxt<'tcx>> for FunctionalVariances<'tcx> {
537 fn cx(&self) -> TyCtxt<'tcx> {
538 self.tcx
539 }
540
541 fn relate_ty_args(
542 &mut self,
543 a_ty: Ty<'tcx>,
544 _: Ty<'tcx>,
545 def_id: DefId,
546 a_args: ty::GenericArgsRef<'tcx>,
547 b_args: ty::GenericArgsRef<'tcx>,
548 _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>,
549 ) -> RelateResult<'tcx, Ty<'tcx>> {
550 let variances = self.cx().variances_of(def_id);
551 relate_args_with_variances(self, variances, a_args, b_args)?;
552 Ok(a_ty)
553 }
554
555 fn relate_with_variance<T: Relate<TyCtxt<'tcx>>>(
556 &mut self,
557 variance: ty::Variance,
558 _: ty::VarianceDiagInfo<TyCtxt<'tcx>>,
559 a: T,
560 b: T,
561 ) -> RelateResult<'tcx, T> {
562 let old_variance = self.ambient_variance;
563 self.ambient_variance = self.ambient_variance.xform(variance);
564 self.relate(a, b).unwrap();
565 self.ambient_variance = old_variance;
566 Ok(a)
567 }
568
569 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
570 structurally_relate_tys(self, a, b).unwrap();
571 Ok(a)
572 }
573
574 fn regions(
575 &mut self,
576 a: ty::Region<'tcx>,
577 _: ty::Region<'tcx>,
578 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
579 let def_id = match a.kind() {
580 ty::ReEarlyParam(ebr) => self.generics.region_param(ebr, self.tcx).def_id,
581 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. })
582 | ty::ReLateParam(ty::LateParamRegion {
583 scope: _,
584 kind: ty::LateParamRegionKind::Named(def_id),
585 }) => def_id,
586 _ => {
587 return Ok(a);
588 }
589 };
590
591 if let Some(variance) = self.variances.get_mut(&def_id) {
592 *variance = unify(*variance, self.ambient_variance);
593 } else {
594 self.variances.insert(def_id, self.ambient_variance);
595 }
596
597 Ok(a)
598 }
599
600 fn consts(
601 &mut self,
602 a: ty::Const<'tcx>,
603 b: ty::Const<'tcx>,
604 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
605 structurally_relate_consts(self, a, b).unwrap();
606 Ok(a)
607 }
608
609 fn binders<T>(
610 &mut self,
611 a: ty::Binder<'tcx, T>,
612 b: ty::Binder<'tcx, T>,
613 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
614 where
615 T: Relate<TyCtxt<'tcx>>,
616 {
617 self.relate(a.skip_binder(), b.skip_binder()).unwrap();
618 Ok(a)
619 }
620}
621
622fn unify(a: ty::Variance, b: ty::Variance) -> ty::Variance {
624 match (a, b) {
625 (ty::Bivariant, other) | (other, ty::Bivariant) => other,
627 (ty::Invariant, _) | (_, ty::Invariant) => ty::Invariant,
629 (ty::Contravariant, ty::Covariant) | (ty::Covariant, ty::Contravariant) => ty::Invariant,
631 (ty::Contravariant, ty::Contravariant) => ty::Contravariant,
633 (ty::Covariant, ty::Covariant) => ty::Covariant,
634 }
635}