1use rustc_abi::FieldIdx;
2use rustc_attr_ir::find_attr;
3use rustc_data_structures::fx::{FxHashSet, FxIndexMap, IndexEntry};
4use rustc_hir::def::{CtorKind, DefKind};
5use rustc_hir::def_id::{DefId, LocalDefId};
6use rustc_index::IndexVec;
7use rustc_index::bit_set::DenseBitSet;
8use rustc_lint_defs::builtin::{UNUSED_ASSIGNMENTS, UNUSED_VARIABLES};
9use rustc_middle::mir::visit::{
10 MutatingUseContext, NonMutatingUseContext, NonUseContext, PlaceContext, Visitor,
11};
12use rustc_middle::mir::*;
13use rustc_middle::ty::print::with_no_trimmed_paths;
14use rustc_middle::ty::{self, Ty, TyCtxt};
15use rustc_mir_dataflow::fmt::DebugWithContext;
16use rustc_mir_dataflow::{Analysis, Backward, ResultsCursor};
17use rustc_span::edit_distance::find_best_match_for_name;
18use rustc_span::symbol::{Symbol, kw, sym};
19use rustc_span::{Span, bug};
20
21use crate::diagnostics;
22
23#[derive(#[automatically_derived]impl ::core::marker::Copy for AccessKind { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for AccessKind {
}
#[automatically_derived]impl ::core::clone::Clone for AccessKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AccessKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AccessKind::Param => "Param",
AccessKind::Assign => "Assign",
AccessKind::Capture => "Capture",
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
AccessKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AccessKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for AccessKind { }Eq)]
24enum AccessKind {
25 Param,
26 Assign,
27 Capture,
28}
29
30#[derive(#[automatically_derived]impl ::core::marker::Copy for CaptureKind { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for CaptureKind {
}
#[automatically_derived]impl ::core::clone::Clone for CaptureKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<ty::ClosureKind>;
*self
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for CaptureKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Closure(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Closure", &__self_0),
Self::Coroutine =>
::core::fmt::Formatter::write_str(f, "Coroutine"),
Self::CoroutineClosure =>
::core::fmt::Formatter::write_str(f, "CoroutineClosure"),
Self::None => ::core::fmt::Formatter::write_str(f, "None"),
}
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
CaptureKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CaptureKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Closure(__self_0), Self::Closure(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for CaptureKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ty::ClosureKind>;
}
}Eq)]
31enum CaptureKind {
32 Closure(ty::ClosureKind),
33 Coroutine,
34 CoroutineClosure,
35 None,
36}
37
38#[derive(#[automatically_derived]impl ::core::marker::Copy for Access { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Access {
}
#[automatically_derived]impl ::core::clone::Clone for Access {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<AccessKind>;
let _: ::core::clone::AssertParamIsClone<Location>;
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Access {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"Access kind location live is_direct", &self.kind, &self.location,
&self.live, &&self.is_direct)
}
}Debug)]
39struct Access {
40 kind: AccessKind,
42 location: Location,
44 live: bool,
48 is_direct: bool,
51}
52
53{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::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("check_liveness",
"rustc_mir_transform::liveness", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/liveness.rs"),
::tracing_core::__macro_support::Option::Some(53u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_transform::liveness"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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: DenseBitSet<FieldIdx> =
loop {};
return __tracing_attr_fake_return;
}
{
if tcx.is_synthetic_mir(def_id) {
return DenseBitSet::new_empty(0);
}
if tcx.intrinsic(def_id.to_def_id()).is_some() {
return DenseBitSet::new_empty(0);
}
if {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(def_id.to_def_id(),
&tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Naked(..)) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some() {
return DenseBitSet::new_empty(0);
}
let parent =
tcx.local_parent(tcx.typeck_root_def_id_local(def_id));
if let DefKind::Impl { of_trait: true } =
tcx.def_kind(parent) &&
{
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(parent, &tcx)
{
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(AutomaticallyDerived) =>
{
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some() {
return DenseBitSet::new_empty(0);
}
let mut body = &*tcx.mir_promoted(def_id).0.borrow();
let mut body_mem;
if body.tainted_by_errors.is_some() {
return DenseBitSet::new_empty(0);
}
let mut checked_places = PlaceSet::default();
checked_places.insert_locals(&body.local_decls);
let (capture_kind, num_captures) =
if tcx.is_closure_like(def_id.to_def_id()) {
let mut self_ty =
body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
let mut self_is_ref = false;
if let ty::Ref(_, ty, _) = self_ty.kind() {
self_ty = *ty;
self_is_ref = true;
}
let (capture_kind, args) =
match self_ty.kind() {
ty::Closure(_, args) => {
(CaptureKind::Closure(args.as_closure().kind()),
ty::UpvarArgs::Closure(*args))
}
&ty::Coroutine(_, args) =>
(CaptureKind::Coroutine, ty::UpvarArgs::Coroutine(args)),
&ty::CoroutineClosure(_, args) => {
(CaptureKind::CoroutineClosure,
ty::UpvarArgs::CoroutineClosure(args))
}
_ =>
::rustc_span::macros::bug_impl(None,
format_args!("expected closure or generator, found {0:?}",
self_ty), Location::caller()),
};
let captures = tcx.closure_captures(def_id);
checked_places.insert_captures(tcx, self_is_ref, captures,
args.upvar_tys());
if let CaptureKind::Closure(ty::ClosureKind::FnMut) =
capture_kind {
body_mem = body.clone();
for bbdata in body_mem.basic_blocks_mut() {
if let TerminatorKind::Return | TerminatorKind::UnwindResume
= bbdata.terminator.kind {
bbdata.terminator.kind = TerminatorKind::goto(START_BLOCK);
}
}
body = &body_mem;
}
(capture_kind, args.upvar_tys().len())
} else { (CaptureKind::None, 0) };
checked_places.record_debuginfo(&body.var_debug_info);
let self_assignment =
find_self_assignments(&checked_places, body);
let mut live =
MaybeLivePlaces {
tcx,
capture_kind,
checked_places: &checked_places,
self_assignment,
}.iterate_to_fixpoint(tcx, body,
None).into_results_cursor(body);
let typing_env =
ty::TypingEnv::post_analysis_no_rigid_aliases(tcx,
body.source.def_id());
let mut assignments =
AssignmentResult::find_dead_assignments(tcx, typing_env,
&checked_places, &mut live, body);
assignments.merge_guards();
let dead_captures =
assignments.compute_dead_captures(num_captures);
assignments.report_fully_unused();
assignments.report_unused_assignments();
dead_captures
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/liveness.rs:53",
"rustc_mir_transform::liveness", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/liveness.rs"),
::tracing_core::__macro_support::Option::Some(53u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_transform::liveness"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[tracing::instrument(level = "debug", skip(tcx), ret)]
54pub(crate) fn check_liveness<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> DenseBitSet<FieldIdx> {
55 if tcx.is_synthetic_mir(def_id) {
57 return DenseBitSet::new_empty(0);
58 }
59
60 if tcx.intrinsic(def_id.to_def_id()).is_some() {
62 return DenseBitSet::new_empty(0);
63 }
64
65 if find_attr!(tcx, def_id.to_def_id(), Naked(..)) {
67 return DenseBitSet::new_empty(0);
68 }
69
70 let parent = tcx.local_parent(tcx.typeck_root_def_id_local(def_id));
72 if let DefKind::Impl { of_trait: true } = tcx.def_kind(parent)
73 && find_attr!(tcx, parent, AutomaticallyDerived)
74 {
75 return DenseBitSet::new_empty(0);
76 }
77
78 let mut body = &*tcx.mir_promoted(def_id).0.borrow();
79 let mut body_mem;
80
81 if body.tainted_by_errors.is_some() {
83 return DenseBitSet::new_empty(0);
84 }
85
86 let mut checked_places = PlaceSet::default();
87 checked_places.insert_locals(&body.local_decls);
88
89 let (capture_kind, num_captures) = if tcx.is_closure_like(def_id.to_def_id()) {
91 let mut self_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
92 let mut self_is_ref = false;
93 if let ty::Ref(_, ty, _) = self_ty.kind() {
94 self_ty = *ty;
95 self_is_ref = true;
96 }
97
98 let (capture_kind, args) = match self_ty.kind() {
99 ty::Closure(_, args) => {
100 (CaptureKind::Closure(args.as_closure().kind()), ty::UpvarArgs::Closure(*args))
101 }
102 &ty::Coroutine(_, args) => (CaptureKind::Coroutine, ty::UpvarArgs::Coroutine(args)),
103 &ty::CoroutineClosure(_, args) => {
104 (CaptureKind::CoroutineClosure, ty::UpvarArgs::CoroutineClosure(args))
105 }
106 _ => bug!("expected closure or generator, found {:?}", self_ty),
107 };
108
109 let captures = tcx.closure_captures(def_id);
110 checked_places.insert_captures(tcx, self_is_ref, captures, args.upvar_tys());
111
112 if let CaptureKind::Closure(ty::ClosureKind::FnMut) = capture_kind {
116 body_mem = body.clone();
118 for bbdata in body_mem.basic_blocks_mut() {
119 if let TerminatorKind::Return | TerminatorKind::UnwindResume =
121 bbdata.terminator.kind
122 {
123 bbdata.terminator.kind = TerminatorKind::goto(START_BLOCK);
124 }
125 }
126 body = &body_mem;
127 }
128
129 (capture_kind, args.upvar_tys().len())
130 } else {
131 (CaptureKind::None, 0)
132 };
133
134 checked_places.record_debuginfo(&body.var_debug_info);
136
137 let self_assignment = find_self_assignments(&checked_places, body);
138
139 let mut live =
140 MaybeLivePlaces { tcx, capture_kind, checked_places: &checked_places, self_assignment }
141 .iterate_to_fixpoint(tcx, body, None)
142 .into_results_cursor(body);
143
144 let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, body.source.def_id());
147
148 let mut assignments =
149 AssignmentResult::find_dead_assignments(tcx, typing_env, &checked_places, &mut live, body);
150
151 assignments.merge_guards();
152
153 let dead_captures = assignments.compute_dead_captures(num_captures);
154
155 assignments.report_fully_unused();
156 assignments.report_unused_assignments();
157
158 dead_captures
159}
160
161#[inline]
163fn is_capture(place: PlaceRef<'_>) -> bool {
164 if !place.projection.is_empty() {
165 if true {
{
match (&place.local, &ty::CAPTURE_STRUCT_LOCAL) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(place.local, ty::CAPTURE_STRUCT_LOCAL);
166 true
167 } else {
168 false
169 }
170}
171
172fn maybe_suggest_unit_pattern_typo<'tcx>(
174 tcx: TyCtxt<'tcx>,
175 body_def_id: DefId,
176 name: Symbol,
177 span: Span,
178 ty: Ty<'tcx>,
179) -> Option<diagnostics::PatternTypo> {
180 if let ty::Adt(adt_def, _) = ty.peel_refs().kind() {
181 let variant_names: Vec<_> = adt_def
182 .variants()
183 .iter()
184 .filter(|v| #[allow(non_exhaustive_omitted_patterns)] match v.ctor {
Some((CtorKind::Const, _)) => true,
_ => false,
}matches!(v.ctor, Some((CtorKind::Const, _))))
185 .map(|v| v.name)
186 .collect();
187 if let Some(name) = find_best_match_for_name(&variant_names, name, None)
188 && let Some(variant) = adt_def
189 .variants()
190 .iter()
191 .find(|v| v.name == name && #[allow(non_exhaustive_omitted_patterns)] match v.ctor {
Some((CtorKind::Const, _)) => true,
_ => false,
}matches!(v.ctor, Some((CtorKind::Const, _))))
192 {
193 return Some(diagnostics::PatternTypo {
194 span,
195 code: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(variant.def_id) }with_no_trimmed_paths!(tcx.def_path_str(variant.def_id)),
196 kind: tcx.def_descr(variant.def_id),
197 item_name: variant.name,
198 });
199 }
200 }
201
202 let constants = tcx
205 .hir_body_owners()
206 .filter(|&def_id| {
207 tcx.def_kind(def_id) == DefKind::Const
208 && tcx.type_of(def_id).instantiate_identity().skip_norm_wip() == ty
209 && tcx.visibility(def_id).is_accessible_from(body_def_id, tcx)
210 })
211 .collect::<Vec<_>>();
212 let names = constants.iter().map(|&def_id| tcx.item_name(def_id)).collect::<Vec<_>>();
213 if let Some(item_name) = find_best_match_for_name(&names, name, None)
214 && let Some(position) = names.iter().position(|&n| n == item_name)
215 && let Some(&def_id) = constants.get(position)
216 {
217 return Some(diagnostics::PatternTypo {
218 span,
219 code: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(def_id) }with_no_trimmed_paths!(tcx.def_path_str(def_id)),
220 kind: "constant",
221 item_name,
222 });
223 }
224
225 None
226}
227
228fn maybe_drop_guard<'tcx>(
230 tcx: TyCtxt<'tcx>,
231 typing_env: ty::TypingEnv<'tcx>,
232 index: PlaceIndex,
233 ever_dropped: &DenseBitSet<PlaceIndex>,
234 checked_places: &PlaceSet<'tcx>,
235 body: &Body<'tcx>,
236) -> bool {
237 if ever_dropped.contains(index) {
238 let ty = checked_places.places[index].ty(&body.local_decls, tcx).ty;
239 let ty = ty::set_aliases_to_non_rigid(tcx, ty).skip_norm_wip();
244 #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Closure(..) | ty::Coroutine(..) | ty::Tuple(..) | ty::Adt(..) |
ty::Dynamic(..) | ty::Array(..) | ty::Slice(..) |
ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => true,
_ => false,
}matches!(
245 ty.kind(),
246 ty::Closure(..)
247 | ty::Coroutine(..)
248 | ty::Tuple(..)
249 | ty::Adt(..)
250 | ty::Dynamic(..)
251 | ty::Array(..)
252 | ty::Slice(..)
253 | ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. })
254 ) && ty.needs_drop(tcx, typing_env)
255 } else {
256 false
257 }
258}
259
260fn annotate_mut_binding_to_immutable_binding<'tcx>(
279 tcx: TyCtxt<'tcx>,
280 place: PlaceRef<'tcx>,
281 body_def_id: LocalDefId,
282 assignment_span: Span,
283 body: &Body<'tcx>,
284) -> Option<diagnostics::UnusedAssignSuggestion> {
285 use rustc_hir as hir;
286 use rustc_hir::intravisit::{self, Visitor};
287
288 let local = place.as_local()?;
290 let LocalKind::Arg = body.local_kind(local) else { return None };
291 let Mutability::Mut = body.local_decls[local].mutability else { return None };
292
293 let hir_param_index =
295 local.as_usize() - if tcx.is_closure_like(body_def_id.to_def_id()) { 2 } else { 1 };
296 let fn_decl = tcx.hir_node_by_def_id(body_def_id).fn_decl()?;
297 let ty = fn_decl.inputs[hir_param_index];
298 let hir::TyKind::Ref(lt, inner_ty, mutbl) = ty.kind else { return None };
299
300 let hir_body = tcx.hir_maybe_body_owned_by(body_def_id)?;
302 let param = hir_body.params[hir_param_index];
303 let hir::PatKind::Binding(hir::BindingMode::MUT, _hir_id, ident, _) = param.pat.kind else {
304 return None;
305 };
306
307 let mut finder = ExprFinder { assignment_span, lhs: None, rhs: None };
309 finder.visit_body(hir_body);
310 let lhs = finder.lhs?;
311 let rhs = finder.rhs?;
312
313 let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _mut, inner) = rhs.kind else { return None };
314
315 let pre = if lt.ident.span.is_empty() { "" } else { " " };
317 let ty_span = if mutbl.is_mut() {
318 None
320 } else {
321 Some(inner_ty.span.shrink_to_lo())
323 };
324
325 return Some(diagnostics::UnusedAssignSuggestion {
326 ty_span,
327 pre,
328 ty_ref_span: param.pat.span.until(ident.span),
330 pre_lhs_span: lhs.span.shrink_to_lo(),
332 rhs_borrow_span: rhs.span.until(inner.span),
334 });
335
336 #[derive(#[automatically_derived]impl<'hir> ::core::fmt::Debug for ExprFinder<'hir> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"ExprFinder assignment_span lhs rhs", &self.assignment_span,
&self.lhs, &&self.rhs)
}
}Debug)]
337 struct ExprFinder<'hir> {
338 assignment_span: Span,
339 lhs: Option<&'hir hir::Expr<'hir>>,
340 rhs: Option<&'hir hir::Expr<'hir>>,
341 }
342 impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
343 fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
344 if expr.span == self.assignment_span
345 && let hir::ExprKind::Assign(lhs, rhs, _) = expr.kind
346 {
347 self.lhs = Some(lhs);
348 self.rhs = Some(rhs);
349 } else {
350 intravisit::walk_expr(self, expr)
351 }
352 }
353 }
354}
355
356fn find_self_assignments<'tcx>(
368 checked_places: &PlaceSet<'tcx>,
369 body: &Body<'tcx>,
370) -> FxHashSet<Location> {
371 let mut self_assign = FxHashSet::default();
372
373 const FIELD_0: FieldIdx = FieldIdx::from_u32(0);
374 const FIELD_1: FieldIdx = FieldIdx::from_u32(1);
375
376 for (bb, bb_data) in body.basic_blocks.iter_enumerated() {
377 for (statement_index, stmt) in bb_data.statements.iter().enumerate() {
378 let StatementKind::Assign((first_place, rvalue)) = &stmt.kind else { continue };
379 match rvalue {
380 Rvalue::BinaryOp(
382 BinOp::AddWithOverflow | BinOp::SubWithOverflow | BinOp::MulWithOverflow,
383 (Operand::Copy(lhs), _),
384 ) => {
385 if statement_index + 1 != bb_data.statements.len() {
387 continue;
388 }
389
390 let TerminatorKind::Assert {
391 cond, target, msg: AssertKind::Overflow(..), ..
392 } = &bb_data.terminator.kind
393 else {
394 continue;
395 };
396 let Some(assign) = body.basic_blocks[*target].statements.first() else {
397 continue;
398 };
399 let StatementKind::Assign((dest, Rvalue::Use(Operand::Move(temp), _))) =
400 assign.kind
401 else {
402 continue;
403 };
404
405 if dest != *lhs {
406 continue;
407 }
408
409 let Operand::Move(cond) = cond else { continue };
410 let [PlaceElem::Field(FIELD_0, _)] = &temp.projection.as_slice() else {
411 continue;
412 };
413 let [PlaceElem::Field(FIELD_1, _)] = &cond.projection.as_slice() else {
414 continue;
415 };
416
417 let is_indirect = checked_places
419 .get(dest.as_ref())
420 .is_some_and(|(_, projections)| is_indirect(projections));
421 if is_indirect {
422 continue;
423 }
424
425 if first_place.local == temp.local
426 && first_place.local == cond.local
427 && first_place.projection.is_empty()
428 {
429 self_assign.insert(Location {
431 block: bb,
432 statement_index: bb_data.statements.len() - 1,
433 });
434 self_assign.insert(Location {
435 block: bb,
436 statement_index: bb_data.statements.len(),
437 });
438 self_assign.insert(target.start_location());
440 }
441 }
442 Rvalue::BinaryOp(op, (Operand::Copy(lhs), _)) => {
444 if lhs != first_place {
445 continue;
446 }
447
448 let is_indirect = checked_places
450 .get(first_place.as_ref())
451 .map_or(false, |(_, projections)| is_indirect(projections));
452 if is_indirect {
453 continue;
454 }
455
456 self_assign.insert(Location { block: bb, statement_index });
457
458 if let BinOp::Div | BinOp::Rem = op
461 && statement_index == 0
462 && let &[pred] = body.basic_blocks.predecessors()[bb].as_slice()
463 && let TerminatorKind::Assert { msg, .. } =
464 &body.basic_blocks[pred].terminator.kind
465 && let AssertKind::Overflow(..) = **msg
466 && let len = body.basic_blocks[pred].statements.len()
467 && len >= 2
468 {
469 self_assign.insert(Location { block: pred, statement_index: len - 1 });
471 self_assign.insert(Location { block: pred, statement_index: len - 2 });
473 }
474 }
475 _ => {}
476 }
477 }
478 }
479
480 self_assign
481}
482
483#[derive(#[automatically_derived]impl<'tcx> ::core::default::Default for PlaceSet<'tcx>
{
#[inline]
fn default() -> Self {
PlaceSet {
places: ::core::default::Default::default(),
names: ::core::default::Default::default(),
locals: ::core::default::Default::default(),
capture_field_pos: ::core::default::Default::default(),
captures: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for PlaceSet<'tcx> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f,
"PlaceSet places names locals capture_field_pos captures",
&self.places, &self.names, &self.locals, &self.capture_field_pos,
&&self.captures)
}
}Debug)]
484struct PlaceSet<'tcx> {
485 places: IndexVec<PlaceIndex, PlaceRef<'tcx>>,
486 names: IndexVec<PlaceIndex, Option<(Symbol, Span)>>,
487
488 locals: IndexVec<Local, Option<PlaceIndex>>,
490
491 capture_field_pos: usize,
494 captures: IndexVec<FieldIdx, (PlaceIndex, bool)>,
496}
497
498impl<'tcx> PlaceSet<'tcx> {
499 fn insert_locals(&mut self, decls: &IndexVec<Local, LocalDecl<'tcx>>) {
500 self.locals = IndexVec::from_elem(None, &decls);
501 for (local, decl) in decls.iter_enumerated() {
502 if let LocalInfo::User(BindingForm::Var(_) | BindingForm::RefForGuard(_)) =
505 decl.local_info()
506 {
507 let index = self.places.push(local.into());
508 self.locals[local] = Some(index);
509 let _index = self.names.push(None);
510 if true {
{
match (&index, &_index) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(index, _index);
511 }
512 }
513 }
514
515 fn insert_captures(
516 &mut self,
517 tcx: TyCtxt<'tcx>,
518 self_is_ref: bool,
519 captures: &[&'tcx ty::CapturedPlace<'tcx>],
520 upvars: &ty::List<Ty<'tcx>>,
521 ) {
522 if true {
{
match (&self.locals[ty::CAPTURE_STRUCT_LOCAL], &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.locals[ty::CAPTURE_STRUCT_LOCAL], None);
524
525 let self_place = Place {
526 local: ty::CAPTURE_STRUCT_LOCAL,
527 projection: tcx.mk_place_elems(if self_is_ref { &[PlaceElem::Deref] } else { &[] }),
528 };
529 if self_is_ref {
530 self.capture_field_pos = 1;
531 }
532
533 for (f, (capture, ty)) in std::iter::zip(captures, upvars).enumerate() {
534 let f = FieldIdx::from_usize(f);
535 let elem = PlaceElem::Field(f, ty);
536 let by_ref = #[allow(non_exhaustive_omitted_patterns)] match capture.info.capture_kind {
ty::UpvarCapture::ByRef(..) => true,
_ => false,
}matches!(capture.info.capture_kind, ty::UpvarCapture::ByRef(..));
537 let place = if by_ref {
538 self_place.project_deeper(&[elem, PlaceElem::Deref], tcx)
539 } else {
540 self_place.project_deeper(&[elem], tcx)
541 };
542 let index = self.places.push(place.as_ref());
543 let _f = self.captures.push((index, by_ref));
544 if true {
{
match (&_f, &f) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(_f, f);
545
546 self.names.insert(
549 index,
550 (Symbol::intern(&capture.to_string(tcx)), capture.get_path_span(tcx)),
551 );
552 }
553 }
554
555 fn record_debuginfo(&mut self, var_debug_info: &Vec<VarDebugInfo<'tcx>>) {
556 let ignore_name = |name: Symbol| {
557 name == sym::empty || name == kw::SelfLower || name.as_str().starts_with('_')
558 };
559 for var_debug_info in var_debug_info {
560 if let VarDebugInfoContents::Place(place) = var_debug_info.value
561 && let Some(index) = self.locals[place.local]
562 && !ignore_name(var_debug_info.name)
563 {
564 self.names.get_or_insert_with(index, || {
565 (var_debug_info.name, var_debug_info.source_info.span)
566 });
567 }
568 }
569
570 for index_opt in self.locals.iter_mut() {
572 if let Some(index) = *index_opt {
573 let remove = match self.names[index] {
574 None => true,
575 Some((name, _)) => ignore_name(name),
576 };
577 if remove {
578 *index_opt = None;
579 }
580 }
581 }
582 }
583
584 #[inline]
585 fn get(&self, place: PlaceRef<'tcx>) -> Option<(PlaceIndex, &'tcx [PlaceElem<'tcx>])> {
586 if let Some(index) = self.locals[place.local] {
587 return Some((index, place.projection));
588 }
589 if place.local == ty::CAPTURE_STRUCT_LOCAL
590 && !self.captures.is_empty()
591 && self.capture_field_pos < place.projection.len()
592 && let PlaceElem::Field(f, _) = place.projection[self.capture_field_pos]
593 && let Some((index, by_ref)) = self.captures.get(f)
594 {
595 let mut start = self.capture_field_pos + 1;
596 if *by_ref {
597 start += 1;
599 }
600 if start <= place.projection.len() {
602 let projection = &place.projection[start..];
603 return Some((*index, projection));
604 }
605 }
606 None
607 }
608
609 fn iter(&self) -> impl Iterator<Item = (PlaceIndex, &PlaceRef<'tcx>)> {
610 self.places.iter_enumerated()
611 }
612
613 fn len(&self) -> usize {
614 self.places.len()
615 }
616}
617
618struct AssignmentResult<'a, 'tcx> {
619 tcx: TyCtxt<'tcx>,
620 typing_env: ty::TypingEnv<'tcx>,
621 checked_places: &'a PlaceSet<'tcx>,
622 body: &'a Body<'tcx>,
623 ever_live: DenseBitSet<PlaceIndex>,
625 ever_dropped: DenseBitSet<PlaceIndex>,
628 assignments: IndexVec<PlaceIndex, FxIndexMap<SourceInfo, Access>>,
635}
636
637impl<'a, 'tcx> AssignmentResult<'a, 'tcx> {
638 fn find_dead_assignments(
643 tcx: TyCtxt<'tcx>,
644 typing_env: ty::TypingEnv<'tcx>,
645 checked_places: &'a PlaceSet<'tcx>,
646 cursor: &mut ResultsCursor<'_, 'tcx, MaybeLivePlaces<'_, 'tcx>>,
647 body: &'a Body<'tcx>,
648 ) -> AssignmentResult<'a, 'tcx> {
649 let mut ever_live = DenseBitSet::new_empty(checked_places.len());
650 let mut ever_dropped = DenseBitSet::new_empty(checked_places.len());
651 let mut assignments = IndexVec::<PlaceIndex, FxIndexMap<_, _>>::from_elem(
652 Default::default(),
653 &checked_places.places,
654 );
655
656 let mut check_place = |place: Place<'tcx>,
657 kind,
658 source_info: SourceInfo,
659 location: Location,
660 live: &DenseBitSet<PlaceIndex>| {
661 if let Some((index, extra_projections)) = checked_places.get(place.as_ref()) {
662 if !is_indirect(extra_projections) {
663 let is_direct = extra_projections.is_empty();
664 match assignments[index].entry(source_info) {
665 IndexEntry::Vacant(v) => {
666 let access =
667 Access { kind, location, live: live.contains(index), is_direct };
668 v.insert(access);
669 }
670 IndexEntry::Occupied(mut o) => {
671 o.get_mut().live |= live.contains(index);
674 o.get_mut().is_direct &= is_direct;
675 }
676 }
677 }
678 }
679 };
680
681 let mut record_drop = |place: Place<'tcx>| {
682 if let Some((index, &[])) = checked_places.get(place.as_ref()) {
683 ever_dropped.insert(index);
684 }
685 };
686
687 for (bb, bb_data) in traversal::postorder(body) {
688 cursor.seek_to_block_end(bb);
689 let live = cursor.get();
690 ever_live.union(live);
691
692 let terminator = &bb_data.terminator;
693 match &terminator.kind {
694 TerminatorKind::Call { destination: place, .. }
695 | TerminatorKind::Yield { resume_arg: place, .. } => {
696 check_place(
697 *place,
698 AccessKind::Assign,
699 terminator.source_info,
700 body.terminator_loc(bb),
701 live,
702 );
703 record_drop(*place)
704 }
705 TerminatorKind::Drop { place, .. } => record_drop(*place),
706 TerminatorKind::InlineAsm { operands, .. } => {
707 for operand in operands {
708 if let InlineAsmOperand::Out { place: Some(place), .. }
709 | InlineAsmOperand::InOut { out_place: Some(place), .. } = operand
710 {
711 check_place(
712 *place,
713 AccessKind::Assign,
714 terminator.source_info,
715 body.terminator_loc(bb),
716 live,
717 );
718 }
719 }
720 }
721 _ => {}
722 }
723
724 for (statement_index, statement) in bb_data.statements.iter().enumerate().rev() {
725 let location = Location { block: bb, statement_index };
726 cursor.seek_before_primary_effect(location);
727 let live = cursor.get();
728 ever_live.union(live);
729 match &statement.kind {
730 StatementKind::Assign((place, _)) => {
731 check_place(
732 *place,
733 AccessKind::Assign,
734 statement.source_info,
735 location,
736 live,
737 );
738 }
739 StatementKind::SetDiscriminant { place, .. } => {
740 check_place(
741 **place,
742 AccessKind::Assign,
743 statement.source_info,
744 location,
745 live,
746 );
747 }
748 StatementKind::StorageLive(_)
749 | StatementKind::StorageDead(_)
750 | StatementKind::Coverage(_)
751 | StatementKind::Intrinsic(_)
752 | StatementKind::Nop
753 | StatementKind::FakeRead(_)
754 | StatementKind::PlaceMention(_)
755 | StatementKind::ConstEvalCounter
756 | StatementKind::BackwardIncompatibleDropHint { .. }
757 | StatementKind::AscribeUserType(_, _) => (),
758 }
759 }
760 }
761
762 {
764 cursor.seek_to_block_start(START_BLOCK);
765 let live = cursor.get();
766 ever_live.union(live);
767
768 for (index, place) in checked_places.iter() {
770 let kind = if is_capture(*place) {
771 if place.projection.last() == Some(&PlaceElem::Deref) {
774 continue;
775 }
776
777 AccessKind::Capture
778 } else if body.local_kind(place.local) == LocalKind::Arg {
779 AccessKind::Param
780 } else {
781 continue;
782 };
783 let source_info = body.local_decls[place.local].source_info;
784 let access = Access {
785 kind,
786 location: Location::START,
787 live: live.contains(index),
788 is_direct: true,
789 };
790 assignments[index].insert(source_info, access);
791 }
792 }
793
794 AssignmentResult {
795 tcx,
796 typing_env,
797 checked_places,
798 ever_live,
799 ever_dropped,
800 assignments,
801 body,
802 }
803 }
804
805 fn merge_guards(&mut self) {
817 for (index, place) in self.checked_places.iter() {
818 let local = place.local;
819 if let &LocalInfo::User(BindingForm::RefForGuard(arm_local)) =
820 self.body.local_decls[local].local_info()
821 {
822 if true {
if !place.projection.is_empty() {
::core::panicking::panic("assertion failed: place.projection.is_empty()")
};
};debug_assert!(place.projection.is_empty());
823
824 let Some((arm_index, _proj)) = self.checked_places.get(arm_local.into()) else {
826 continue;
827 };
828 if true {
{
match (&index, &arm_index) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_ne!(index, arm_index);
829 if true {
{
match (&_proj, &&[]) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(_proj, &[]);
830
831 if self.ever_live.contains(index) {
833 self.ever_live.insert(arm_index);
834 }
835
836 let guard_assignments = std::mem::take(&mut self.assignments[index]);
844 let arm_assignments = &mut self.assignments[arm_index];
845 for (source_info, access) in guard_assignments {
846 match arm_assignments.entry(source_info) {
847 IndexEntry::Vacant(v) => {
848 v.insert(access);
849 }
850 IndexEntry::Occupied(mut o) => {
851 o.get_mut().live |= access.live;
852 }
853 }
854 }
855 }
856 }
857 }
858
859 fn compute_dead_captures(&self, num_captures: usize) -> DenseBitSet<FieldIdx> {
861 let mut dead_captures = DenseBitSet::new_empty(num_captures);
863 for (index, place) in self.checked_places.iter() {
864 if self.ever_live.contains(index) {
865 continue;
866 }
867
868 if is_capture(*place) {
870 for p in place.projection {
871 if let PlaceElem::Field(f, _) = p {
872 dead_captures.insert(*f);
873 break;
874 }
875 }
876 continue;
877 }
878 }
879
880 dead_captures
881 }
882
883 fn is_local_in_reachable_code(&self, local: Local) -> bool {
886 struct LocalVisitor {
887 target_local: Local,
888 found: bool,
889 }
890
891 impl<'tcx> Visitor<'tcx> for LocalVisitor {
892 fn visit_local(&mut self, local: Local, _context: PlaceContext, _location: Location) {
893 if local == self.target_local {
894 self.found = true;
895 }
896 }
897 }
898
899 let mut visitor = LocalVisitor { target_local: local, found: false };
900 for (bb, bb_data) in traversal::postorder(self.body) {
901 visitor.visit_basic_block_data(bb, bb_data);
902 if visitor.found {
903 return true;
904 }
905 }
906
907 false
908 }
909
910 fn is_local_used_in_source(&self, name: Symbol, def_span: Span) -> bool {
921 use rustc_hir as hir;
922 use rustc_hir::def::Res;
923 use rustc_hir::intravisit::{self, Visitor};
924
925 let Some(body_def_id) = self.body.source.def_id().as_local() else { return false };
926 let Some(hir_body) = self.tcx.hir_maybe_body_owned_by(body_def_id) else { return false };
927 let typeck_results = self.tcx.typeck(body_def_id);
928
929 struct LocalUseVisitor<'a, 'tcx> {
930 tcx: TyCtxt<'tcx>,
931 typeck_results: &'a ty::TypeckResults<'tcx>,
932 name: Symbol,
933 def_span: Span,
934 found: bool,
935 }
936
937 impl<'a, 'tcx> Visitor<'tcx> for LocalUseVisitor<'a, 'tcx> {
938 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
939 if self.found {
940 return;
941 }
942
943 if let hir::ExprKind::Path(qpath) = &expr.kind
944 && let Res::Local(hir_id) = self.typeck_results.qpath_res(qpath, expr.hir_id)
945 && self.tcx.hir_name(hir_id) == self.name
946 && self.tcx.hir_span(hir_id) == self.def_span
947 {
948 self.found = true;
949 return;
950 }
951
952 intravisit::walk_expr(self, expr);
953 }
954 }
955
956 let mut visitor =
957 LocalUseVisitor { tcx: self.tcx, typeck_results, name, def_span, found: false };
958 visitor.visit_body(hir_body);
959 visitor.found
960 }
961
962 fn report_fully_unused(&mut self) {
964 let tcx = self.tcx;
965
966 let mut string_constants_in_body = None;
969 let mut maybe_suggest_literal_matching_name = |name: Symbol| {
970 let string_constants_in_body = string_constants_in_body.get_or_insert_with(|| {
972 struct LiteralFinder {
973 found: Vec<(Span, String)>,
974 }
975
976 impl<'tcx> Visitor<'tcx> for LiteralFinder {
977 fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _: Location) {
978 if let ty::Ref(_, ref_ty, _) = constant.ty().kind()
979 && ref_ty.kind() == &ty::Str
980 {
981 let rendered_constant = constant.const_.to_string();
982 self.found.push((constant.span, rendered_constant));
983 }
984 }
985 }
986
987 let mut finder = LiteralFinder { found: ::alloc::vec::Vec::new()vec![] };
988 finder.visit_body(self.body);
989 finder.found
990 });
991
992 let brace_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{{0}", name))
})format!("{{{name}");
993 string_constants_in_body
994 .iter()
995 .filter(|(_, rendered_constant)| {
996 rendered_constant
997 .split(&brace_name)
998 .any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.chars().next() {
Some('}' | ':') => true,
_ => false,
}matches!(c.chars().next(), Some('}' | ':')))
999 })
1000 .map(|&(lit, _)| diagnostics::UnusedVariableStringInterp { lit })
1001 .collect::<Vec<_>>()
1002 };
1003
1004 for (index, place) in self.checked_places.iter() {
1006 if self.ever_live.contains(index) {
1007 continue;
1008 }
1009
1010 if is_capture(*place) {
1012 continue;
1013 }
1014
1015 let local = place.local;
1016 let decl = &self.body.local_decls[local];
1017
1018 if decl.from_compiler_desugaring() {
1019 continue;
1020 }
1021
1022 let LocalInfo::User(BindingForm::Var(binding)) = decl.local_info() else { continue };
1024 let Some(hir_id) = decl.source_info.scope.lint_root(&self.body.source_scopes) else {
1025 continue;
1026 };
1027
1028 let introductions = &binding.introductions;
1029
1030 let Some((name, def_span)) = self.checked_places.names[index] else { continue };
1031
1032 let from_macro = def_span.from_expansion()
1035 && introductions.iter().any(|intro| intro.span.ctxt() == def_span.ctxt());
1036
1037 let maybe_suggest_typo = || {
1038 if let LocalKind::Arg = self.body.local_kind(local) {
1039 None
1040 } else {
1041 maybe_suggest_unit_pattern_typo(
1042 tcx,
1043 self.body.source.def_id(),
1044 name,
1045 def_span,
1046 decl.ty,
1047 )
1048 }
1049 };
1050
1051 let is_used_after_uninitialized = self.body.local_kind(local) == LocalKind::Temp
1054 && #[allow(non_exhaustive_omitted_patterns)] match binding.opt_match_place {
Some((None, _)) => true,
_ => false,
}matches!(binding.opt_match_place, Some((None, _)))
1055 && self.is_local_used_in_source(name, def_span);
1056
1057 let statements = &mut self.assignments[index];
1058 if statements.is_empty() {
1059 if is_used_after_uninitialized {
1060 continue;
1065 }
1066
1067 if !self.is_local_in_reachable_code(local) {
1068 continue;
1069 }
1070
1071 let sugg = if from_macro {
1072 diagnostics::UnusedVariableSugg::NoSugg { span: def_span, name }
1073 } else {
1074 let typo = maybe_suggest_typo();
1075 diagnostics::UnusedVariableSugg::TryPrefix { spans: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[def_span]))vec![def_span], name, typo }
1076 };
1077 tcx.emit_node_span_lint(
1078 UNUSED_VARIABLES,
1079 hir_id,
1080 def_span,
1081 diagnostics::UnusedVariable {
1082 name,
1083 string_interp: maybe_suggest_literal_matching_name(name),
1084 sugg,
1085 },
1086 );
1087 continue;
1088 }
1089
1090 statements.retain(|source_info, _| {
1094 !binding.introductions.iter().any(|intro| intro.span == source_info.span)
1095 });
1096
1097 if let Some((_, initializer_span)) = binding.opt_match_place {
1100 statements.retain(|source_info, _| {
1101 let within = source_info.span.find_ancestor_inside(initializer_span);
1102 let outer_initializer_span =
1103 initializer_span.find_ancestor_in_same_ctxt(source_info.span);
1104 within.is_none()
1105 && outer_initializer_span.is_none_or(|s| !s.contains(source_info.span))
1106 });
1107 }
1108
1109 if !statements.is_empty() {
1110 if maybe_drop_guard(
1113 tcx,
1114 self.typing_env,
1115 index,
1116 &self.ever_dropped,
1117 self.checked_places,
1118 self.body,
1119 ) {
1120 statements.retain(|_, access| access.is_direct);
1121 if statements.is_empty() {
1122 continue;
1123 }
1124 }
1125
1126 let typo = maybe_suggest_typo();
1127 tcx.emit_node_span_lint(
1128 UNUSED_VARIABLES,
1129 hir_id,
1130 def_span,
1131 diagnostics::UnusedVarAssignedOnly { name, typo },
1132 );
1133 continue;
1134 }
1135
1136 let spans = introductions.iter().map(|intro| intro.span).collect::<Vec<_>>();
1138
1139 let any_shorthand = introductions.iter().any(|intro| intro.is_shorthand);
1140
1141 let sugg = if any_shorthand {
1142 diagnostics::UnusedVariableSugg::TryIgnore {
1143 name: name.to_ident_string(),
1144 shorthands: introductions
1145 .iter()
1146 .filter_map(
1147 |intro| if intro.is_shorthand { Some(intro.span) } else { None },
1148 )
1149 .collect(),
1150 non_shorthands: introductions
1151 .iter()
1152 .filter_map(
1153 |intro| {
1154 if !intro.is_shorthand { Some(intro.span) } else { None }
1155 },
1156 )
1157 .collect(),
1158 }
1159 } else if from_macro {
1160 diagnostics::UnusedVariableSugg::NoSugg { span: def_span, name }
1161 } else if !introductions.is_empty() {
1162 let typo = maybe_suggest_typo();
1163 diagnostics::UnusedVariableSugg::TryPrefix { name, typo, spans: spans.clone() }
1164 } else {
1165 let typo = maybe_suggest_typo();
1166 diagnostics::UnusedVariableSugg::TryPrefix { name, typo, spans: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[def_span]))vec![def_span] }
1167 };
1168
1169 tcx.emit_node_span_lint(
1170 UNUSED_VARIABLES,
1171 hir_id,
1172 spans,
1173 diagnostics::UnusedVariable {
1174 name,
1175 string_interp: maybe_suggest_literal_matching_name(name),
1176 sugg,
1177 },
1178 );
1179 }
1180 }
1181
1182 fn report_unused_assignments(self) {
1185 let tcx = self.tcx;
1186
1187 for (index, statements) in self.assignments.into_iter_enumerated() {
1188 if statements.is_empty() {
1189 continue;
1190 }
1191
1192 let Some((name, decl_span)) = self.checked_places.names[index] else { continue };
1193
1194 let is_maybe_drop_guard = maybe_drop_guard(
1195 tcx,
1196 self.typing_env,
1197 index,
1198 &self.ever_dropped,
1199 self.checked_places,
1200 self.body,
1201 );
1202
1203 if name.as_str().starts_with('_') {
1205 continue;
1206 }
1207
1208 let mut next_direct_assignments: Vec<(Span, Location)> = Vec::new();
1209 let mut dead_statements = Vec::with_capacity(statements.len());
1210
1211 for (source_info, Access { live, kind, is_direct, location }) in statements.into_iter()
1212 {
1213 let direct_assignment = kind == AccessKind::Assign && is_direct;
1214 let should_report = !live && (is_direct || !is_maybe_drop_guard);
1215
1216 let overwrite = if should_report && direct_assignment {
1217 next_direct_assignments
1218 .iter()
1219 .rfind(|(_, overwrite_location)| {
1220 location.is_predecessor_of(*overwrite_location, self.body)
1221 })
1222 .map(|&(overwrite_span, _)| diagnostics::UnusedAssignOverwrite {
1223 assigned_span: source_info.span,
1224 overwrite_span,
1225 name,
1226 })
1227 } else {
1228 None
1229 };
1230
1231 if direct_assignment {
1232 next_direct_assignments.push((source_info.span, location));
1233 }
1234
1235 if !should_report {
1236 continue;
1237 }
1238 dead_statements.push((source_info, kind, is_direct, overwrite));
1239 }
1240
1241 for (source_info, kind, is_direct, overwrite) in dead_statements.into_iter().rev() {
1244 let Some(hir_id) = source_info.scope.lint_root(&self.body.source_scopes) else {
1246 continue;
1247 };
1248
1249 match kind {
1250 AccessKind::Assign => {
1251 let suggestion = annotate_mut_binding_to_immutable_binding(
1252 tcx,
1253 self.checked_places.places[index],
1254 self.body.source.def_id().expect_local(),
1255 source_info.span,
1256 self.body,
1257 );
1258 let overwrite =
1259 if suggestion.is_none() && is_direct { overwrite } else { None };
1260 let help = suggestion.is_none() && overwrite.is_none();
1261 tcx.emit_node_span_lint(
1262 UNUSED_ASSIGNMENTS,
1263 hir_id,
1264 source_info.span,
1265 diagnostics::UnusedAssign { name, overwrite, help, suggestion },
1266 )
1267 }
1268 AccessKind::Param => tcx.emit_node_span_lint(
1269 UNUSED_ASSIGNMENTS,
1270 hir_id,
1271 source_info.span,
1272 diagnostics::UnusedAssignPassed { name },
1273 ),
1274 AccessKind::Capture => tcx.emit_node_span_lint(
1275 UNUSED_ASSIGNMENTS,
1276 hir_id,
1277 decl_span,
1278 diagnostics::UnusedCaptureMaybeCaptureRef { name },
1279 ),
1280 }
1281 }
1282 }
1283 }
1284}
1285
1286#[automatically_derived]impl ::core::marker::Copy for PlaceIndex { }
impl PlaceIndex {
#[doc = r" Maximum value the index can take, as a `u32`."]
pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
#[doc = r" Maximum value the index can take."]
pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
#[doc = r" Zero value of the index."]
pub const ZERO: Self = Self::from_u32(0);
#[doc = r" Creates a new index from a given `usize`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_usize(value: usize) -> Self {
if !(value <= (0xFFFF_FF00 as usize)) {
::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
};
unsafe { Self::from_u32_unchecked(value as u32) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u32(value: u32) -> Self {
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u16`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u16(value: u16) -> Self {
let value = value as u32;
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc =
r" The provided value must be less than or equal to the maximum value for the newtype."]
#[doc =
r" Providing a value outside this range is undefined due to layout restrictions."]
#[doc = r""]
#[doc = r" Prefer using `from_u32`."]
#[inline]
pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
Self {
private_use_as_methods_instead: unsafe {
std::mem::transmute(value)
},
}
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn index(self) -> usize { self.as_usize() }
#[doc = r" Extracts the value of this index as a `u32`."]
#[inline]
pub const fn as_u32(self) -> u32 {
unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for PlaceIndex {
type Output = Self;
#[inline]
fn add(self, other: usize) -> Self {
Self::from_usize(self.index() + other)
}
}
impl std::ops::AddAssign<usize> for PlaceIndex {
#[inline]
fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for PlaceIndex {
#[inline]
fn new(value: usize) -> Self { Self::from_usize(value) }
#[inline]
fn index(self) -> usize { self.as_usize() }
}
impl From<PlaceIndex> for u32 {
#[inline]
fn from(v: PlaceIndex) -> u32 { v.as_u32() }
}
impl From<PlaceIndex> for usize {
#[inline]
fn from(v: PlaceIndex) -> usize { v.as_usize() }
}
impl From<usize> for PlaceIndex {
#[inline]
fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for PlaceIndex {
#[inline]
fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for PlaceIndex {}
impl ::std::cmp::PartialEq for PlaceIndex {
fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for PlaceIndex {}
impl ::std::hash::Hash for PlaceIndex {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self.as_u32().hash(state)
}
}
impl ::std::fmt::Debug for PlaceIndex {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
1287 pub struct PlaceIndex {}
1288}
1289
1290impl DebugWithContext<MaybeLivePlaces<'_, '_>> for PlaceIndex {
1291 fn fmt_with(
1292 &self,
1293 ctxt: &MaybeLivePlaces<'_, '_>,
1294 f: &mut std::fmt::Formatter<'_>,
1295 ) -> std::fmt::Result {
1296 std::fmt::Debug::fmt(&ctxt.checked_places.places[*self], f)
1297 }
1298}
1299
1300pub struct MaybeLivePlaces<'a, 'tcx> {
1301 tcx: TyCtxt<'tcx>,
1302 checked_places: &'a PlaceSet<'tcx>,
1303 capture_kind: CaptureKind,
1304 self_assignment: FxHashSet<Location>,
1305}
1306
1307impl<'tcx> MaybeLivePlaces<'_, 'tcx> {
1308 fn transfer_function<'a>(
1309 &'a self,
1310 trans: &'a mut DenseBitSet<PlaceIndex>,
1311 ) -> TransferFunction<'a, 'tcx> {
1312 TransferFunction {
1313 tcx: self.tcx,
1314 checked_places: &self.checked_places,
1315 capture_kind: self.capture_kind,
1316 trans,
1317 self_assignment: &self.self_assignment,
1318 }
1319 }
1320}
1321
1322impl<'tcx> Analysis<'tcx> for MaybeLivePlaces<'_, 'tcx> {
1323 type Domain = DenseBitSet<PlaceIndex>;
1324 type Direction = Backward;
1325
1326 const NAME: &'static str = "liveness-lint";
1327
1328 fn bottom_value(&self, _: &Body<'tcx>) -> Self::Domain {
1329 DenseBitSet::new_empty(self.checked_places.len())
1331 }
1332
1333 fn initialize_start_block(&self, _: &Body<'tcx>, _: &mut Self::Domain) {
1334 }
1336
1337 fn apply_primary_statement_effect(
1338 &self,
1339 trans: &mut Self::Domain,
1340 statement: &Statement<'tcx>,
1341 location: Location,
1342 ) {
1343 self.transfer_function(trans).visit_statement(statement, location);
1344 }
1345
1346 fn apply_primary_terminator_effect(
1347 &self,
1348 trans: &mut Self::Domain,
1349 terminator: &Terminator<'tcx>,
1350 location: Location,
1351 ) {
1352 self.transfer_function(trans).visit_terminator(terminator, location);
1353 }
1354
1355 fn apply_call_return_effect(
1356 &self,
1357 _trans: &mut Self::Domain,
1358 _block: BasicBlock,
1359 _return_places: CallReturnPlaces<'_, 'tcx>,
1360 ) {
1361 }
1363}
1364
1365struct TransferFunction<'a, 'tcx> {
1366 tcx: TyCtxt<'tcx>,
1367 checked_places: &'a PlaceSet<'tcx>,
1368 trans: &'a mut DenseBitSet<PlaceIndex>,
1369 capture_kind: CaptureKind,
1370 self_assignment: &'a FxHashSet<Location>,
1371}
1372
1373impl<'tcx> Visitor<'tcx> for TransferFunction<'_, 'tcx> {
1374 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1375 match statement.kind {
1376 StatementKind::FakeRead((
1379 FakeReadCause::ForLet(None) | FakeReadCause::ForGuardBinding,
1380 _,
1381 )) => return,
1382 StatementKind::Assign((ref dest, ref rvalue))
1384 if self.self_assignment.contains(&location) =>
1385 {
1386 if let Rvalue::BinaryOp(
1387 BinOp::AddWithOverflow | BinOp::SubWithOverflow | BinOp::MulWithOverflow,
1388 (_, rhs),
1389 ) = rvalue
1390 {
1391 self.visit_operand(rhs, location);
1395 self.visit_place(
1396 dest,
1397 PlaceContext::MutatingUse(MutatingUseContext::Store),
1398 location,
1399 );
1400 } else if let Rvalue::BinaryOp(_, (_, rhs)) = rvalue {
1401 self.visit_operand(rhs, location);
1405 } else {
1406 self.visit_rvalue(rvalue, location);
1411 }
1412 }
1413 _ => self.super_statement(statement, location),
1414 }
1415 }
1416
1417 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1418 match terminator.kind {
1421 TerminatorKind::Return
1422 | TerminatorKind::Yield { .. }
1423 | TerminatorKind::Goto { target: START_BLOCK, .. } | TerminatorKind::Call { target: None, .. } if self.capture_kind != CaptureKind::None =>
1426 {
1427 for (index, place) in self.checked_places.iter() {
1429 if place.local == ty::CAPTURE_STRUCT_LOCAL
1430 && place.projection.last() == Some(&PlaceElem::Deref)
1431 {
1432 self.trans.insert(index);
1433 }
1434 }
1435 }
1436 TerminatorKind::Drop { .. } => {}
1438 TerminatorKind::Assert { .. } => {}
1440 _ => self.super_terminator(terminator, location),
1441 }
1442 }
1443
1444 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1445 match rvalue {
1446 Rvalue::Aggregate(
1450 AggregateKind::Closure(def_id, _) | AggregateKind::Coroutine(def_id, _),
1451 operands,
1452 ) => {
1453 if let Some(def_id) = def_id.as_local() {
1454 let dead_captures = self.tcx.check_liveness(def_id);
1455 for (field, operand) in
1456 operands.iter_enumerated().take(dead_captures.domain_size())
1457 {
1458 if !dead_captures.contains(field) {
1459 self.visit_operand(operand, location);
1460 }
1461 }
1462 }
1463 }
1464 _ => self.super_rvalue(rvalue, location),
1465 }
1466 }
1467
1468 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1469 if let Some((index, extra_projections)) = self.checked_places.get(place.as_ref()) {
1470 for i in (extra_projections.len()..=place.projection.len()).rev() {
1471 let place_part =
1472 PlaceRef { local: place.local, projection: &place.projection[..i] };
1473 let extra_projections = &place.projection[i..];
1474
1475 if let Some(&elem) = extra_projections.get(0) {
1476 self.visit_projection_elem(place_part, elem, context, location);
1477 }
1478 }
1479
1480 match DefUse::for_place(extra_projections, context) {
1481 Some(DefUse::Def) => {
1482 self.trans.remove(index);
1483 }
1484 Some(DefUse::Use) => {
1485 self.trans.insert(index);
1486 }
1487 None => {}
1488 }
1489 } else {
1490 self.super_place(place, context, location)
1491 }
1492 }
1493
1494 fn visit_local(&mut self, local: Local, context: PlaceContext, _: Location) {
1495 if let Some((index, _proj)) = self.checked_places.get(local.into()) {
1496 if true {
{
match (&_proj, &&[]) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(_proj, &[]);
1497 match DefUse::for_place(&[], context) {
1498 Some(DefUse::Def) => {
1499 self.trans.remove(index);
1500 }
1501 Some(DefUse::Use) => {
1502 self.trans.insert(index);
1503 }
1504 _ => {}
1505 }
1506 }
1507 }
1508}
1509
1510#[derive(#[automatically_derived]impl ::core::cmp::Eq for DefUse { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for DefUse {
}
#[automatically_derived]impl ::core::cmp::PartialEq for DefUse {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::fmt::Debug for DefUse {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { DefUse::Def => "Def", DefUse::Use => "Use", })
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for DefUse {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self { Self::Def => DefUse::Def, Self::Use => DefUse::Use, }
}
}Clone)]
1511enum DefUse {
1512 Def,
1513 Use,
1514}
1515
1516fn is_indirect(proj: &[PlaceElem<'_>]) -> bool {
1517 proj.iter().any(|p| p.is_indirect())
1518}
1519
1520impl DefUse {
1521 fn for_place<'tcx>(projection: &[PlaceElem<'tcx>], context: PlaceContext) -> Option<DefUse> {
1522 let is_indirect = is_indirect(projection);
1523 match context {
1524 PlaceContext::MutatingUse(
1525 MutatingUseContext::Store | MutatingUseContext::SetDiscriminant,
1526 ) => {
1527 if is_indirect {
1528 Some(DefUse::Use)
1531 } else if projection.is_empty() {
1532 Some(DefUse::Def)
1533 } else {
1534 None
1535 }
1536 }
1537
1538 PlaceContext::MutatingUse(
1543 MutatingUseContext::Call
1544 | MutatingUseContext::Yield
1545 | MutatingUseContext::AsmOutput,
1546 ) => is_indirect.then_some(DefUse::Use),
1547
1548 PlaceContext::MutatingUse(
1550 MutatingUseContext::RawBorrow
1551 | MutatingUseContext::Borrow
1552 | MutatingUseContext::Drop,
1553 )
1554 | PlaceContext::NonMutatingUse(
1555 NonMutatingUseContext::RawBorrow
1556 | NonMutatingUseContext::Copy
1557 | NonMutatingUseContext::Inspect
1558 | NonMutatingUseContext::Move
1559 | NonMutatingUseContext::FakeBorrow
1560 | NonMutatingUseContext::SharedBorrow
1561 | NonMutatingUseContext::PlaceMention,
1562 ) => Some(DefUse::Use),
1563
1564 PlaceContext::NonUse(
1565 NonUseContext::StorageLive
1566 | NonUseContext::StorageDead
1567 | NonUseContext::AscribeUserTy(_)
1568 | NonUseContext::BackwardIncompatibleDropHint
1569 | NonUseContext::VarDebugInfo,
1570 ) => None,
1571
1572 PlaceContext::MutatingUse(MutatingUseContext::Projection)
1573 | PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection) => {
1574 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("A projection could be a def or a use and must be handled separately")));
}unreachable!("A projection could be a def or a use and must be handled separately")
1575 }
1576 }
1577 }
1578}