1use std::assert_matches::debug_assert_matches;
2use std::cell::LazyCell;
3
4use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
5use rustc_data_structures::unord::UnordSet;
6use rustc_errors::{LintDiagnostic, Subdiagnostic};
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_macros::LintDiagnostic;
13use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
14use rustc_middle::ty::relate::{
15 Relate, RelateResult, TypeRelation, structurally_relate_consts, structurally_relate_tys,
16};
17use rustc_middle::ty::{
18 self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
19};
20use rustc_middle::{bug, span_bug};
21use rustc_session::lint::FutureIncompatibilityReason;
22use rustc_session::{declare_lint, declare_lint_pass};
23use rustc_span::edition::Edition;
24use rustc_span::{Span, Symbol};
25use rustc_trait_selection::errors::{
26 AddPreciseCapturingForOvercapture, impl_trait_overcapture_suggestion,
27};
28use rustc_trait_selection::regions::OutlivesEnvironmentBuildExt;
29use rustc_trait_selection::traits::ObligationCtxt;
30
31use crate::{LateContext, LateLintPass, fluent_generated as fluent};
32
33declare_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: FutureIncompatibilityReason::EditionSemanticsChange(Edition::Edition2024),
74 reference: "<https://doc.rust-lang.org/nightly/edition-guide/rust-2024/rpit-lifetime-capture.html>",
75 };
76}
77
78declare_lint! {
79 pub IMPL_TRAIT_REDUNDANT_CAPTURES,
101 Allow,
102 "redundant precise-capturing `use<...>` syntax on an `impl Trait`",
103}
104
105declare_lint_pass!(
106 ImplTraitOvercaptures => [IMPL_TRAIT_OVERCAPTURES, IMPL_TRAIT_REDUNDANT_CAPTURES]
109);
110
111impl<'tcx> LateLintPass<'tcx> for ImplTraitOvercaptures {
112 fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx hir::Item<'tcx>) {
113 match &it.kind {
114 hir::ItemKind::Fn { .. } => check_fn(cx.tcx, it.owner_id.def_id),
115 _ => {}
116 }
117 }
118
119 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx hir::ImplItem<'tcx>) {
120 match &it.kind {
121 hir::ImplItemKind::Fn(_, _) => check_fn(cx.tcx, it.owner_id.def_id),
122 _ => {}
123 }
124 }
125
126 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx hir::TraitItem<'tcx>) {
127 match &it.kind {
128 hir::TraitItemKind::Fn(_, _) => check_fn(cx.tcx, it.owner_id.def_id),
129 _ => {}
130 }
131 }
132}
133
134#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
135enum ParamKind {
136 Early(Symbol, u32),
138 Free(DefId),
140 Late,
142}
143
144fn check_fn(tcx: TyCtxt<'_>, parent_def_id: LocalDefId) {
145 let sig = tcx.fn_sig(parent_def_id).instantiate_identity();
146
147 let mut in_scope_parameters = FxIndexMap::default();
148 let mut current_def_id = Some(parent_def_id.to_def_id());
150 while let Some(def_id) = current_def_id {
151 let generics = tcx.generics_of(def_id);
152 for param in &generics.own_params {
153 in_scope_parameters.insert(param.def_id, ParamKind::Early(param.name, param.index));
154 }
155 current_def_id = generics.parent;
156 }
157
158 for bound_var in sig.bound_vars() {
159 let ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) = bound_var else {
160 span_bug!(tcx.def_span(parent_def_id), "unexpected non-lifetime binder on fn sig");
161 };
162
163 in_scope_parameters.insert(def_id, ParamKind::Free(def_id));
164 }
165
166 let sig = tcx.liberate_late_bound_regions(parent_def_id.to_def_id(), sig);
167
168 sig.visit_with(&mut VisitOpaqueTypes {
171 tcx,
172 parent_def_id,
173 in_scope_parameters,
174 seen: Default::default(),
175 variances: LazyCell::new(|| {
177 let mut functional_variances = FunctionalVariances {
178 tcx,
179 variances: FxHashMap::default(),
180 ambient_variance: ty::Covariant,
181 generics: tcx.generics_of(parent_def_id),
182 };
183 functional_variances.relate(sig, sig).unwrap();
184 functional_variances.variances
185 }),
186 outlives_env: LazyCell::new(|| {
187 let typing_env = ty::TypingEnv::non_body_analysis(tcx, parent_def_id);
188 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
189 let ocx = ObligationCtxt::new(&infcx);
190 let assumed_wf_tys = ocx.assumed_wf_types(param_env, parent_def_id).unwrap_or_default();
191 OutlivesEnvironment::new(&infcx, parent_def_id, param_env, assumed_wf_tys)
192 }),
193 });
194}
195
196struct VisitOpaqueTypes<'tcx, VarFn, OutlivesFn> {
197 tcx: TyCtxt<'tcx>,
198 parent_def_id: LocalDefId,
199 in_scope_parameters: FxIndexMap<DefId, ParamKind>,
200 variances: LazyCell<FxHashMap<DefId, ty::Variance>, VarFn>,
201 outlives_env: LazyCell<OutlivesEnvironment<'tcx>, OutlivesFn>,
202 seen: FxIndexSet<LocalDefId>,
203}
204
205impl<'tcx, VarFn, OutlivesFn> TypeVisitor<TyCtxt<'tcx>>
206 for VisitOpaqueTypes<'tcx, VarFn, OutlivesFn>
207where
208 VarFn: FnOnce() -> FxHashMap<DefId, ty::Variance>,
209 OutlivesFn: FnOnce() -> OutlivesEnvironment<'tcx>,
210{
211 fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(&mut self, t: &ty::Binder<'tcx, T>) {
212 let mut added = vec![];
214 for arg in t.bound_vars() {
215 let arg: ty::BoundVariableKind = arg;
216 match arg {
217 ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id))
218 | ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)) => {
219 added.push(def_id);
220 let unique = self.in_scope_parameters.insert(def_id, ParamKind::Late);
221 assert_eq!(unique, None);
222 }
223 _ => {
224 self.tcx.dcx().span_delayed_bug(
225 self.tcx.def_span(self.parent_def_id),
226 format!("unsupported bound variable kind: {arg:?}"),
227 );
228 }
229 }
230 }
231
232 t.super_visit_with(self);
233
234 for arg in added.into_iter().rev() {
237 self.in_scope_parameters.shift_remove(&arg);
238 }
239 }
240
241 fn visit_ty(&mut self, t: Ty<'tcx>) {
242 if !t.has_aliases() {
243 return;
244 }
245
246 if let ty::Alias(ty::Projection, opaque_ty) = *t.kind()
247 && self.tcx.is_impl_trait_in_trait(opaque_ty.def_id)
248 {
249 self.tcx
251 .type_of(opaque_ty.def_id)
252 .instantiate(self.tcx, opaque_ty.args)
253 .visit_with(self)
254 } else if let ty::Alias(ty::Opaque, opaque_ty) = *t.kind()
255 && let Some(opaque_def_id) = opaque_ty.def_id.as_local()
256 && self.seen.insert(opaque_def_id)
258 && let opaque =
260 self.tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty()
261 && let hir::OpaqueTyOrigin::FnReturn { parent, .. }
265 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = opaque.origin
266 && parent == self.parent_def_id
267 {
268 let opaque_span = self.tcx.def_span(opaque_def_id);
269 let new_capture_rules = opaque_span.at_least_rust_2024();
270 if !new_capture_rules
271 && !opaque.bounds.iter().any(|bound| matches!(bound, hir::GenericBound::Use(..)))
272 {
273 let mut captured = FxIndexSet::default();
275 let mut captured_regions = FxIndexSet::default();
276 let variances = self.tcx.variances_of(opaque_def_id);
277 let mut current_def_id = Some(opaque_def_id.to_def_id());
278 while let Some(def_id) = current_def_id {
279 let generics = self.tcx.generics_of(def_id);
280 for param in &generics.own_params {
281 if variances[param.index as usize] != ty::Invariant {
283 continue;
284 }
285
286 let arg = opaque_ty.args[param.index as usize];
287 captured.insert(extract_def_id_from_arg(self.tcx, generics, arg));
290
291 captured_regions.extend(arg.as_region());
292 }
293 current_def_id = generics.parent;
294 }
295
296 let mut uncaptured_args: FxIndexSet<_> = self
298 .in_scope_parameters
299 .iter()
300 .filter(|&(def_id, _)| !captured.contains(def_id))
301 .collect();
302 uncaptured_args.retain(|&(def_id, kind)| {
305 let Some(ty::Bivariant | ty::Contravariant) = self.variances.get(def_id) else {
306 return true;
310 };
311 debug_assert_matches!(self.tcx.def_kind(def_id), DefKind::LifetimeParam);
313 let uncaptured = match *kind {
314 ParamKind::Early(name, index) => ty::Region::new_early_param(
315 self.tcx,
316 ty::EarlyParamRegion { name, index },
317 ),
318 ParamKind::Free(def_id) => ty::Region::new_late_param(
319 self.tcx,
320 self.parent_def_id.to_def_id(),
321 ty::LateParamRegionKind::Named(def_id),
322 ),
323 ParamKind::Late => return true,
325 };
326 !captured_regions.iter().any(|r| {
328 self.outlives_env
329 .free_region_map()
330 .sub_free_regions(self.tcx, *r, uncaptured)
331 })
332 });
333
334 if !uncaptured_args.is_empty() {
337 let suggestion = impl_trait_overcapture_suggestion(
338 self.tcx,
339 opaque_def_id,
340 self.parent_def_id,
341 captured,
342 );
343
344 let uncaptured_spans: Vec<_> = uncaptured_args
345 .into_iter()
346 .map(|(def_id, _)| self.tcx.def_span(def_id))
347 .collect();
348
349 self.tcx.emit_node_span_lint(
350 IMPL_TRAIT_OVERCAPTURES,
351 self.tcx.local_def_id_to_hir_id(opaque_def_id),
352 opaque_span,
353 ImplTraitOvercapturesLint {
354 self_ty: t,
355 num_captured: uncaptured_spans.len(),
356 uncaptured_spans,
357 suggestion,
358 },
359 );
360 }
361 }
362
363 if new_capture_rules
367 && let Some((captured_args, capturing_span)) =
368 opaque.bounds.iter().find_map(|bound| match *bound {
369 hir::GenericBound::Use(a, s) => Some((a, s)),
370 _ => None,
371 })
372 {
373 let mut explicitly_captured = UnordSet::default();
374 for arg in captured_args {
375 match self.tcx.named_bound_var(arg.hir_id()) {
376 Some(
377 ResolvedArg::EarlyBound(def_id) | ResolvedArg::LateBound(_, _, def_id),
378 ) => {
379 if self.tcx.def_kind(self.tcx.local_parent(def_id)) == DefKind::OpaqueTy
380 {
381 let def_id = self
382 .tcx
383 .map_opaque_lifetime_to_parent_lifetime(def_id)
384 .opt_param_def_id(self.tcx, self.parent_def_id.to_def_id())
385 .expect("variable should have been duplicated from parent");
386
387 explicitly_captured.insert(def_id);
388 } else {
389 explicitly_captured.insert(def_id.to_def_id());
390 }
391 }
392 _ => {
393 self.tcx.dcx().span_delayed_bug(
394 self.tcx.hir_span(arg.hir_id()),
395 "no valid for captured arg",
396 );
397 }
398 }
399 }
400
401 if self
402 .in_scope_parameters
403 .iter()
404 .all(|(def_id, _)| explicitly_captured.contains(def_id))
405 {
406 self.tcx.emit_node_span_lint(
407 IMPL_TRAIT_REDUNDANT_CAPTURES,
408 self.tcx.local_def_id_to_hir_id(opaque_def_id),
409 opaque_span,
410 ImplTraitRedundantCapturesLint { capturing_span },
411 );
412 }
413 }
414
415 for clause in
420 self.tcx.item_bounds(opaque_ty.def_id).iter_instantiated(self.tcx, opaque_ty.args)
421 {
422 clause.visit_with(self)
423 }
424 }
425
426 t.super_visit_with(self);
427 }
428}
429
430struct ImplTraitOvercapturesLint<'tcx> {
431 uncaptured_spans: Vec<Span>,
432 self_ty: Ty<'tcx>,
433 num_captured: usize,
434 suggestion: Option<AddPreciseCapturingForOvercapture>,
435}
436
437impl<'a> LintDiagnostic<'a, ()> for ImplTraitOvercapturesLint<'_> {
438 fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::Diag<'a, ()>) {
439 diag.primary_message(fluent::lint_impl_trait_overcaptures);
440 diag.arg("self_ty", self.self_ty.to_string())
441 .arg("num_captured", self.num_captured)
442 .span_note(self.uncaptured_spans, fluent::lint_note)
443 .note(fluent::lint_note2);
444 if let Some(suggestion) = self.suggestion {
445 suggestion.add_to_diag(diag);
446 }
447 }
448}
449
450#[derive(LintDiagnostic)]
451#[diag(lint_impl_trait_redundant_captures)]
452struct ImplTraitRedundantCapturesLint {
453 #[suggestion(lint_suggestion, code = "", applicability = "machine-applicable")]
454 capturing_span: Span,
455}
456
457fn extract_def_id_from_arg<'tcx>(
458 tcx: TyCtxt<'tcx>,
459 generics: &'tcx ty::Generics,
460 arg: ty::GenericArg<'tcx>,
461) -> DefId {
462 match arg.kind() {
463 ty::GenericArgKind::Lifetime(re) => match re.kind() {
464 ty::ReEarlyParam(ebr) => generics.region_param(ebr, tcx).def_id,
465 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. })
466 | ty::ReLateParam(ty::LateParamRegion {
467 scope: _,
468 kind: ty::LateParamRegionKind::Named(def_id),
469 }) => def_id,
470 _ => unreachable!(),
471 },
472 ty::GenericArgKind::Type(ty) => {
473 let ty::Param(param_ty) = *ty.kind() else {
474 bug!();
475 };
476 generics.type_param(param_ty, tcx).def_id
477 }
478 ty::GenericArgKind::Const(ct) => {
479 let ty::ConstKind::Param(param_ct) = ct.kind() else {
480 bug!();
481 };
482 generics.const_param(param_ct, tcx).def_id
483 }
484 }
485}
486
487struct FunctionalVariances<'tcx> {
494 tcx: TyCtxt<'tcx>,
495 variances: FxHashMap<DefId, ty::Variance>,
496 ambient_variance: ty::Variance,
497 generics: &'tcx ty::Generics,
498}
499
500impl<'tcx> TypeRelation<TyCtxt<'tcx>> for FunctionalVariances<'tcx> {
501 fn cx(&self) -> TyCtxt<'tcx> {
502 self.tcx
503 }
504
505 fn relate_with_variance<T: Relate<TyCtxt<'tcx>>>(
506 &mut self,
507 variance: ty::Variance,
508 _: ty::VarianceDiagInfo<TyCtxt<'tcx>>,
509 a: T,
510 b: T,
511 ) -> RelateResult<'tcx, T> {
512 let old_variance = self.ambient_variance;
513 self.ambient_variance = self.ambient_variance.xform(variance);
514 self.relate(a, b).unwrap();
515 self.ambient_variance = old_variance;
516 Ok(a)
517 }
518
519 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
520 structurally_relate_tys(self, a, b).unwrap();
521 Ok(a)
522 }
523
524 fn regions(
525 &mut self,
526 a: ty::Region<'tcx>,
527 _: ty::Region<'tcx>,
528 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
529 let def_id = match a.kind() {
530 ty::ReEarlyParam(ebr) => self.generics.region_param(ebr, self.tcx).def_id,
531 ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. })
532 | ty::ReLateParam(ty::LateParamRegion {
533 scope: _,
534 kind: ty::LateParamRegionKind::Named(def_id),
535 }) => def_id,
536 _ => {
537 return Ok(a);
538 }
539 };
540
541 if let Some(variance) = self.variances.get_mut(&def_id) {
542 *variance = unify(*variance, self.ambient_variance);
543 } else {
544 self.variances.insert(def_id, self.ambient_variance);
545 }
546
547 Ok(a)
548 }
549
550 fn consts(
551 &mut self,
552 a: ty::Const<'tcx>,
553 b: ty::Const<'tcx>,
554 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
555 structurally_relate_consts(self, a, b).unwrap();
556 Ok(a)
557 }
558
559 fn binders<T>(
560 &mut self,
561 a: ty::Binder<'tcx, T>,
562 b: ty::Binder<'tcx, T>,
563 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
564 where
565 T: Relate<TyCtxt<'tcx>>,
566 {
567 self.relate(a.skip_binder(), b.skip_binder()).unwrap();
568 Ok(a)
569 }
570}
571
572fn unify(a: ty::Variance, b: ty::Variance) -> ty::Variance {
574 match (a, b) {
575 (ty::Bivariant, other) | (other, ty::Bivariant) => other,
577 (ty::Invariant, _) | (_, ty::Invariant) => ty::Invariant,
579 (ty::Contravariant, ty::Covariant) | (ty::Covariant, ty::Contravariant) => ty::Invariant,
581 (ty::Contravariant, ty::Contravariant) => ty::Contravariant,
583 (ty::Covariant, ty::Covariant) => ty::Covariant,
584 }
585}