Skip to main content

rustc_mir_transform/
liveness.rs

1use rustc_abi::FieldIdx;
2use rustc_data_structures::fx::{FxHashSet, FxIndexMap, IndexEntry};
3use rustc_hir::def::{CtorKind, DefKind};
4use rustc_hir::def_id::{DefId, LocalDefId};
5use rustc_hir::find_attr;
6use rustc_index::IndexVec;
7use rustc_index::bit_set::DenseBitSet;
8use rustc_middle::bug;
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_session::lint;
18use rustc_span::Span;
19use rustc_span::edit_distance::find_best_match_for_name;
20use rustc_span::symbol::{Symbol, kw, sym};
21
22use crate::errors;
23
24#[derive(#[automatically_derived]
impl ::core::marker::Copy for AccessKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AccessKind {
    #[inline]
    fn clone(&self) -> AccessKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AccessKind {
    #[inline]
    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::cmp::PartialEq for AccessKind {
    #[inline]
    fn eq(&self, other: &AccessKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AccessKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
25enum AccessKind {
26    Param,
27    Assign,
28    Capture,
29}
30
31#[derive(#[automatically_derived]
impl ::core::marker::Copy for CaptureKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CaptureKind {
    #[inline]
    fn clone(&self) -> CaptureKind {
        let _: ::core::clone::AssertParamIsClone<ty::ClosureKind>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CaptureKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            CaptureKind::Closure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Closure", &__self_0),
            CaptureKind::Coroutine =>
                ::core::fmt::Formatter::write_str(f, "Coroutine"),
            CaptureKind::CoroutineClosure =>
                ::core::fmt::Formatter::write_str(f, "CoroutineClosure"),
            CaptureKind::None => ::core::fmt::Formatter::write_str(f, "None"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CaptureKind {
    #[inline]
    fn eq(&self, other: &CaptureKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (CaptureKind::Closure(__self_0),
                    CaptureKind::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)]
32enum CaptureKind {
33    Closure(ty::ClosureKind),
34    Coroutine,
35    CoroutineClosure,
36    None,
37}
38
39#[derive(#[automatically_derived]
impl ::core::marker::Copy for Access { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Access {
    #[inline]
    fn clone(&self) -> Access {
        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]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "Access",
            "kind", &self.kind, "location", &self.location, "live",
            &self.live, "is_direct", &&self.is_direct)
    }
}Debug)]
40struct Access {
41    /// Describe the current access.
42    kind: AccessKind,
43    /// MIR location where this access happens.
44    location: Location,
45    /// Is the accessed place is live at the current statement?
46    /// When we encounter multiple statements at the same location, we only increase the liveness,
47    /// in order to avoid false positives.
48    live: bool,
49    /// Is this a direct access to the place itself, no projections, or to a field?
50    /// This helps distinguish `x = ...` from `x.field = ...`
51    is_direct: bool,
52}
53
54x;#[tracing::instrument(level = "debug", skip(tcx), ret)]
55pub(crate) fn check_liveness<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> DenseBitSet<FieldIdx> {
56    // Don't run on synthetic MIR, as that will ICE trying to access HIR.
57    if tcx.is_synthetic_mir(def_id) {
58        return DenseBitSet::new_empty(0);
59    }
60
61    // Don't run unused pass for intrinsics
62    if tcx.intrinsic(def_id.to_def_id()).is_some() {
63        return DenseBitSet::new_empty(0);
64    }
65
66    // Don't run unused pass for #[naked]
67    if find_attr!(tcx, def_id.to_def_id(), Naked(..)) {
68        return DenseBitSet::new_empty(0);
69    }
70
71    // Don't run unused pass for #[derive]
72    let parent = tcx.local_parent(tcx.typeck_root_def_id_local(def_id));
73    if let DefKind::Impl { of_trait: true } = tcx.def_kind(parent)
74        && find_attr!(tcx, parent, AutomaticallyDerived(..))
75    {
76        return DenseBitSet::new_empty(0);
77    }
78
79    let mut body = &*tcx.mir_promoted(def_id).0.borrow();
80    let mut body_mem;
81
82    // Don't run if there are errors.
83    if body.tainted_by_errors.is_some() {
84        return DenseBitSet::new_empty(0);
85    }
86
87    let mut checked_places = PlaceSet::default();
88    checked_places.insert_locals(&body.local_decls);
89
90    // The body is the one of a closure or generator, so we also want to analyse captures.
91    let (capture_kind, num_captures) = if tcx.is_closure_like(def_id.to_def_id()) {
92        let mut self_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
93        let mut self_is_ref = false;
94        if let ty::Ref(_, ty, _) = self_ty.kind() {
95            self_ty = *ty;
96            self_is_ref = true;
97        }
98
99        let (capture_kind, args) = match self_ty.kind() {
100            ty::Closure(_, args) => {
101                (CaptureKind::Closure(args.as_closure().kind()), ty::UpvarArgs::Closure(args))
102            }
103            &ty::Coroutine(_, args) => (CaptureKind::Coroutine, ty::UpvarArgs::Coroutine(args)),
104            &ty::CoroutineClosure(_, args) => {
105                (CaptureKind::CoroutineClosure, ty::UpvarArgs::CoroutineClosure(args))
106            }
107            _ => bug!("expected closure or generator, found {:?}", self_ty),
108        };
109
110        let captures = tcx.closure_captures(def_id);
111        checked_places.insert_captures(tcx, self_is_ref, captures, args.upvar_tys());
112
113        // `FnMut` closures can modify captured values and carry those
114        // modified values with them in subsequent calls. To model this behaviour,
115        // we consider the `FnMut` closure as jumping to `bb0` upon return.
116        if let CaptureKind::Closure(ty::ClosureKind::FnMut) = capture_kind {
117            // FIXME: stop cloning the body.
118            body_mem = body.clone();
119            for bbdata in body_mem.basic_blocks_mut() {
120                // We can call a closure again, either after a normal return or an unwind.
121                if let TerminatorKind::Return | TerminatorKind::UnwindResume =
122                    bbdata.terminator().kind
123                {
124                    bbdata.terminator_mut().kind = TerminatorKind::Goto { target: START_BLOCK };
125                }
126            }
127            body = &body_mem;
128        }
129
130        (capture_kind, args.upvar_tys().len())
131    } else {
132        (CaptureKind::None, 0)
133    };
134
135    // Get the remaining variables' names from debuginfo.
136    checked_places.record_debuginfo(&body.var_debug_info);
137
138    let self_assignment = find_self_assignments(&checked_places, body);
139
140    let mut live =
141        MaybeLivePlaces { tcx, capture_kind, checked_places: &checked_places, self_assignment }
142            .iterate_to_fixpoint(tcx, body, None)
143            .into_results_cursor(body);
144
145    let typing_env = ty::TypingEnv::post_analysis(tcx, body.source.def_id());
146
147    let mut assignments =
148        AssignmentResult::find_dead_assignments(tcx, typing_env, &checked_places, &mut live, body);
149
150    assignments.merge_guards();
151
152    let dead_captures = assignments.compute_dead_captures(num_captures);
153
154    assignments.report_fully_unused();
155    assignments.report_unused_assignments();
156
157    dead_captures
158}
159
160/// Small helper to make semantics easier to read.
161#[inline]
162fn is_capture(place: PlaceRef<'_>) -> bool {
163    if !place.projection.is_empty() {
164        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);
165        true
166    } else {
167        false
168    }
169}
170
171/// Give a diagnostic when an unused variable may be a typo of a unit variant or a struct.
172fn maybe_suggest_unit_pattern_typo<'tcx>(
173    tcx: TyCtxt<'tcx>,
174    body_def_id: DefId,
175    name: Symbol,
176    span: Span,
177    ty: Ty<'tcx>,
178) -> Option<errors::PatternTypo> {
179    if let ty::Adt(adt_def, _) = ty.peel_refs().kind() {
180        let variant_names: Vec<_> = adt_def
181            .variants()
182            .iter()
183            .filter(|v| #[allow(non_exhaustive_omitted_patterns)] match v.ctor {
    Some((CtorKind::Const, _)) => true,
    _ => false,
}matches!(v.ctor, Some((CtorKind::Const, _))))
184            .map(|v| v.name)
185            .collect();
186        if let Some(name) = find_best_match_for_name(&variant_names, name, None)
187            && let Some(variant) = adt_def
188                .variants()
189                .iter()
190                .find(|v| v.name == name && #[allow(non_exhaustive_omitted_patterns)] match v.ctor {
    Some((CtorKind::Const, _)) => true,
    _ => false,
}matches!(v.ctor, Some((CtorKind::Const, _))))
191        {
192            return Some(errors::PatternTypo {
193                span,
194                code: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(variant.def_id) }with_no_trimmed_paths!(tcx.def_path_str(variant.def_id)),
195                kind: tcx.def_descr(variant.def_id),
196                item_name: variant.name,
197            });
198        }
199    }
200
201    // Look for consts of the same type with similar names as well,
202    // not just unit structs and variants.
203    let constants = tcx
204        .hir_body_owners()
205        .filter(|&def_id| {
206            #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
    DefKind::Const { .. } => true,
    _ => false,
}matches!(tcx.def_kind(def_id), DefKind::Const { .. })
207                && tcx.type_of(def_id).instantiate_identity() == ty
208                && tcx.visibility(def_id).is_accessible_from(body_def_id, tcx)
209        })
210        .collect::<Vec<_>>();
211    let names = constants.iter().map(|&def_id| tcx.item_name(def_id)).collect::<Vec<_>>();
212    if let Some(item_name) = find_best_match_for_name(&names, name, None)
213        && let Some(position) = names.iter().position(|&n| n == item_name)
214        && let Some(&def_id) = constants.get(position)
215    {
216        return Some(errors::PatternTypo {
217            span,
218            code: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(def_id) }with_no_trimmed_paths!(tcx.def_path_str(def_id)),
219            kind: "constant",
220            item_name,
221        });
222    }
223
224    None
225}
226
227/// Return whether we should consider the current place as a drop guard and skip reporting.
228fn maybe_drop_guard<'tcx>(
229    tcx: TyCtxt<'tcx>,
230    typing_env: ty::TypingEnv<'tcx>,
231    index: PlaceIndex,
232    ever_dropped: &DenseBitSet<PlaceIndex>,
233    checked_places: &PlaceSet<'tcx>,
234    body: &Body<'tcx>,
235) -> bool {
236    if ever_dropped.contains(index) {
237        let ty = checked_places.places[index].ty(&body.local_decls, tcx).ty;
238        #[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!(
239            ty.kind(),
240            ty::Closure(..)
241                | ty::Coroutine(..)
242                | ty::Tuple(..)
243                | ty::Adt(..)
244                | ty::Dynamic(..)
245                | ty::Array(..)
246                | ty::Slice(..)
247                | ty::Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. })
248        ) && ty.needs_drop(tcx, typing_env)
249    } else {
250        false
251    }
252}
253
254/// Detect the following case
255///
256/// ```text
257/// fn change_object(mut a: &Ty) {
258///     let a = Ty::new();
259///     b = &a;
260/// }
261/// ```
262///
263/// where the user likely meant to modify the value behind there reference, use `a` as an out
264/// parameter, instead of mutating the local binding. When encountering this we suggest:
265///
266/// ```text
267/// fn change_object(a: &'_ mut Ty) {
268///     let a = Ty::new();
269///     *b = a;
270/// }
271/// ```
272fn annotate_mut_binding_to_immutable_binding<'tcx>(
273    tcx: TyCtxt<'tcx>,
274    place: PlaceRef<'tcx>,
275    body_def_id: LocalDefId,
276    assignment_span: Span,
277    body: &Body<'tcx>,
278) -> Option<errors::UnusedAssignSuggestion> {
279    use rustc_hir as hir;
280    use rustc_hir::intravisit::{self, Visitor};
281
282    // Verify we have a mutable argument...
283    let local = place.as_local()?;
284    let LocalKind::Arg = body.local_kind(local) else { return None };
285    let Mutability::Mut = body.local_decls[local].mutability else { return None };
286
287    // ... with reference type...
288    let hir_param_index =
289        local.as_usize() - if tcx.is_closure_like(body_def_id.to_def_id()) { 2 } else { 1 };
290    let fn_decl = tcx.hir_node_by_def_id(body_def_id).fn_decl()?;
291    let ty = fn_decl.inputs[hir_param_index];
292    let hir::TyKind::Ref(lt, mut_ty) = ty.kind else { return None };
293
294    // ... as a binding pattern.
295    let hir_body = tcx.hir_maybe_body_owned_by(body_def_id)?;
296    let param = hir_body.params[hir_param_index];
297    let hir::PatKind::Binding(hir::BindingMode::MUT, _hir_id, ident, _) = param.pat.kind else {
298        return None;
299    };
300
301    // Find the assignment to modify.
302    let mut finder = ExprFinder { assignment_span, lhs: None, rhs: None };
303    finder.visit_body(hir_body);
304    let lhs = finder.lhs?;
305    let rhs = finder.rhs?;
306
307    let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _mut, inner) = rhs.kind else { return None };
308
309    // Changes to the parameter's type.
310    let pre = if lt.ident.span.is_empty() { "" } else { " " };
311    let ty_span = if mut_ty.mutbl.is_mut() {
312        // Leave `&'name mut Ty` and `&mut Ty` as they are (#136028).
313        None
314    } else {
315        // `&'name Ty` -> `&'name mut Ty` or `&Ty` -> `&mut Ty`
316        Some(mut_ty.ty.span.shrink_to_lo())
317    };
318
319    return Some(errors::UnusedAssignSuggestion {
320        ty_span,
321        pre,
322        // Span of the `mut` before the binding.
323        ty_ref_span: param.pat.span.until(ident.span),
324        // Where to add a `*`.
325        pre_lhs_span: lhs.span.shrink_to_lo(),
326        // Where to remove the borrow.
327        rhs_borrow_span: rhs.span.until(inner.span),
328    });
329
330    #[derive(#[automatically_derived]
impl<'hir> ::core::fmt::Debug for ExprFinder<'hir> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "ExprFinder",
            "assignment_span", &self.assignment_span, "lhs", &self.lhs, "rhs",
            &&self.rhs)
    }
}Debug)]
331    struct ExprFinder<'hir> {
332        assignment_span: Span,
333        lhs: Option<&'hir hir::Expr<'hir>>,
334        rhs: Option<&'hir hir::Expr<'hir>>,
335    }
336    impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
337        fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
338            if expr.span == self.assignment_span
339                && let hir::ExprKind::Assign(lhs, rhs, _) = expr.kind
340            {
341                self.lhs = Some(lhs);
342                self.rhs = Some(rhs);
343            } else {
344                intravisit::walk_expr(self, expr)
345            }
346        }
347    }
348}
349
350/// Compute self-assignments of the form `a += b`.
351///
352/// MIR building generates 2 statements and 1 terminator for such assignments:
353/// - _temp = CheckedBinaryOp(a, b)
354/// - assert(!_temp.1)
355/// - a = _temp.0
356///
357/// This function tries to detect this pattern in order to avoid marking statement as a definition
358/// and use. This will let the analysis be dictated by the next use of `a`.
359///
360/// Note that we will still need to account for the use of `b`.
361fn find_self_assignments<'tcx>(
362    checked_places: &PlaceSet<'tcx>,
363    body: &Body<'tcx>,
364) -> FxHashSet<Location> {
365    let mut self_assign = FxHashSet::default();
366
367    const FIELD_0: FieldIdx = FieldIdx::from_u32(0);
368    const FIELD_1: FieldIdx = FieldIdx::from_u32(1);
369
370    for (bb, bb_data) in body.basic_blocks.iter_enumerated() {
371        for (statement_index, stmt) in bb_data.statements.iter().enumerate() {
372            let StatementKind::Assign(box (first_place, rvalue)) = &stmt.kind else { continue };
373            match rvalue {
374                // For checked binary ops, the MIR builder inserts an assertion in between.
375                Rvalue::BinaryOp(
376                    BinOp::AddWithOverflow | BinOp::SubWithOverflow | BinOp::MulWithOverflow,
377                    box (Operand::Copy(lhs), _),
378                ) => {
379                    // Checked binary ops only appear at the end of the block, before the assertion.
380                    if statement_index + 1 != bb_data.statements.len() {
381                        continue;
382                    }
383
384                    let TerminatorKind::Assert {
385                        cond,
386                        target,
387                        msg: box AssertKind::Overflow(..),
388                        ..
389                    } = &bb_data.terminator().kind
390                    else {
391                        continue;
392                    };
393                    let Some(assign) = body.basic_blocks[*target].statements.first() else {
394                        continue;
395                    };
396                    let StatementKind::Assign(box (dest, Rvalue::Use(Operand::Move(temp)))) =
397                        assign.kind
398                    else {
399                        continue;
400                    };
401
402                    if dest != *lhs {
403                        continue;
404                    }
405
406                    let Operand::Move(cond) = cond else { continue };
407                    let [PlaceElem::Field(FIELD_0, _)] = &temp.projection.as_slice() else {
408                        continue;
409                    };
410                    let [PlaceElem::Field(FIELD_1, _)] = &cond.projection.as_slice() else {
411                        continue;
412                    };
413
414                    // We ignore indirect self-assignment, because both occurrences of `dest` are uses.
415                    let is_indirect = checked_places
416                        .get(dest.as_ref())
417                        .map_or(false, |(_, projections)| is_indirect(projections));
418                    if is_indirect {
419                        continue;
420                    }
421
422                    if first_place.local == temp.local
423                        && first_place.local == cond.local
424                        && first_place.projection.is_empty()
425                    {
426                        // Original block
427                        self_assign.insert(Location {
428                            block: bb,
429                            statement_index: bb_data.statements.len() - 1,
430                        });
431                        self_assign.insert(Location {
432                            block: bb,
433                            statement_index: bb_data.statements.len(),
434                        });
435                        // Target block
436                        self_assign.insert(Location { block: *target, statement_index: 0 });
437                    }
438                }
439                // Straight self-assignment.
440                Rvalue::BinaryOp(op, box (Operand::Copy(lhs), _)) => {
441                    if lhs != first_place {
442                        continue;
443                    }
444
445                    // We ignore indirect self-assignment, because both occurrences of `dest` are uses.
446                    let is_indirect = checked_places
447                        .get(first_place.as_ref())
448                        .map_or(false, |(_, projections)| is_indirect(projections));
449                    if is_indirect {
450                        continue;
451                    }
452
453                    self_assign.insert(Location { block: bb, statement_index });
454
455                    // Checked division verifies overflow before performing the division, so we
456                    // need to go and ignore this check in the predecessor block.
457                    if let BinOp::Div | BinOp::Rem = op
458                        && statement_index == 0
459                        && let &[pred] = body.basic_blocks.predecessors()[bb].as_slice()
460                        && let TerminatorKind::Assert { msg, .. } =
461                            &body.basic_blocks[pred].terminator().kind
462                        && let AssertKind::Overflow(..) = **msg
463                        && let len = body.basic_blocks[pred].statements.len()
464                        && len >= 2
465                    {
466                        // BitAnd of two checks.
467                        self_assign.insert(Location { block: pred, statement_index: len - 1 });
468                        // `lhs == MIN`.
469                        self_assign.insert(Location { block: pred, statement_index: len - 2 });
470                    }
471                }
472                _ => {}
473            }
474        }
475    }
476
477    self_assign
478}
479
480#[derive(#[automatically_derived]
impl<'tcx> ::core::default::Default for PlaceSet<'tcx> {
    #[inline]
    fn default() -> PlaceSet<'tcx> {
        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]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f, "PlaceSet",
            "places", &self.places, "names", &self.names, "locals",
            &self.locals, "capture_field_pos", &self.capture_field_pos,
            "captures", &&self.captures)
    }
}Debug)]
481struct PlaceSet<'tcx> {
482    places: IndexVec<PlaceIndex, PlaceRef<'tcx>>,
483    names: IndexVec<PlaceIndex, Option<(Symbol, Span)>>,
484
485    /// Places corresponding to locals, common case.
486    locals: IndexVec<Local, Option<PlaceIndex>>,
487
488    // Handling of captures.
489    /// If `_1` is a reference, we need to add a `Deref` to the matched place.
490    capture_field_pos: usize,
491    /// Captured fields.
492    captures: IndexVec<FieldIdx, (PlaceIndex, bool)>,
493}
494
495impl<'tcx> PlaceSet<'tcx> {
496    fn insert_locals(&mut self, decls: &IndexVec<Local, LocalDecl<'tcx>>) {
497        self.locals = IndexVec::from_elem(None, &decls);
498        for (local, decl) in decls.iter_enumerated() {
499            // Record all user-written locals for the analysis.
500            // We also keep the `RefForGuard` locals (more on that below).
501            if let LocalInfo::User(BindingForm::Var(_) | BindingForm::RefForGuard(_)) =
502                decl.local_info()
503            {
504                let index = self.places.push(local.into());
505                self.locals[local] = Some(index);
506                let _index = self.names.push(None);
507                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);
508            }
509        }
510    }
511
512    fn insert_captures(
513        &mut self,
514        tcx: TyCtxt<'tcx>,
515        self_is_ref: bool,
516        captures: &[&'tcx ty::CapturedPlace<'tcx>],
517        upvars: &ty::List<Ty<'tcx>>,
518    ) {
519        // We should not track the environment local separately.
520        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);
521
522        let self_place = Place {
523            local: ty::CAPTURE_STRUCT_LOCAL,
524            projection: tcx.mk_place_elems(if self_is_ref { &[PlaceElem::Deref] } else { &[] }),
525        };
526        if self_is_ref {
527            self.capture_field_pos = 1;
528        }
529
530        for (f, (capture, ty)) in std::iter::zip(captures, upvars).enumerate() {
531            let f = FieldIdx::from_usize(f);
532            let elem = PlaceElem::Field(f, ty);
533            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(..));
534            let place = if by_ref {
535                self_place.project_deeper(&[elem, PlaceElem::Deref], tcx)
536            } else {
537                self_place.project_deeper(&[elem], tcx)
538            };
539            let index = self.places.push(place.as_ref());
540            let _f = self.captures.push((index, by_ref));
541            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);
542
543            // Record a variable name from the capture, because it is much friendlier than the
544            // debuginfo name.
545            self.names.insert(
546                index,
547                (Symbol::intern(&capture.to_string(tcx)), capture.get_path_span(tcx)),
548            );
549        }
550    }
551
552    fn record_debuginfo(&mut self, var_debug_info: &Vec<VarDebugInfo<'tcx>>) {
553        let ignore_name = |name: Symbol| {
554            name == sym::empty || name == kw::SelfLower || name.as_str().starts_with('_')
555        };
556        for var_debug_info in var_debug_info {
557            if let VarDebugInfoContents::Place(place) = var_debug_info.value
558                && let Some(index) = self.locals[place.local]
559                && !ignore_name(var_debug_info.name)
560            {
561                self.names.get_or_insert_with(index, || {
562                    (var_debug_info.name, var_debug_info.source_info.span)
563                });
564            }
565        }
566
567        // Discard places that will not result in a diagnostic.
568        for index_opt in self.locals.iter_mut() {
569            if let Some(index) = *index_opt {
570                let remove = match self.names[index] {
571                    None => true,
572                    Some((name, _)) => ignore_name(name),
573                };
574                if remove {
575                    *index_opt = None;
576                }
577            }
578        }
579    }
580
581    #[inline]
582    fn get(&self, place: PlaceRef<'tcx>) -> Option<(PlaceIndex, &'tcx [PlaceElem<'tcx>])> {
583        if let Some(index) = self.locals[place.local] {
584            return Some((index, place.projection));
585        }
586        if place.local == ty::CAPTURE_STRUCT_LOCAL
587            && !self.captures.is_empty()
588            && self.capture_field_pos < place.projection.len()
589            && let PlaceElem::Field(f, _) = place.projection[self.capture_field_pos]
590            && let Some((index, by_ref)) = self.captures.get(f)
591        {
592            let mut start = self.capture_field_pos + 1;
593            if *by_ref {
594                // Account for an extra Deref.
595                start += 1;
596            }
597            // We may have an attempt to access `_1.f` as a shallow reborrow. Just ignore it.
598            if start <= place.projection.len() {
599                let projection = &place.projection[start..];
600                return Some((*index, projection));
601            }
602        }
603        None
604    }
605
606    fn iter(&self) -> impl Iterator<Item = (PlaceIndex, &PlaceRef<'tcx>)> {
607        self.places.iter_enumerated()
608    }
609
610    fn len(&self) -> usize {
611        self.places.len()
612    }
613}
614
615struct AssignmentResult<'a, 'tcx> {
616    tcx: TyCtxt<'tcx>,
617    typing_env: ty::TypingEnv<'tcx>,
618    checked_places: &'a PlaceSet<'tcx>,
619    body: &'a Body<'tcx>,
620    /// Set of locals that are live at least once. This is used to report fully unused locals.
621    ever_live: DenseBitSet<PlaceIndex>,
622    /// Set of locals that have a non-trivial drop. This is used to skip reporting unused
623    /// assignment if it would be used by the `Drop` impl.
624    ever_dropped: DenseBitSet<PlaceIndex>,
625    /// Set of assignments for each local. Here, assignment is understood in the AST sense. Any
626    /// MIR that may look like an assignment (Assign, DropAndReplace, Yield, Call) are considered.
627    ///
628    /// For each local, we return a map: for each source position, whether the statement is live
629    /// and which kind of access it performs. When we encounter multiple statements at the same
630    /// location, we only increase the liveness, in order to avoid false positives.
631    assignments: IndexVec<PlaceIndex, FxIndexMap<SourceInfo, Access>>,
632}
633
634impl<'a, 'tcx> AssignmentResult<'a, 'tcx> {
635    /// Collect all assignments to checked locals.
636    ///
637    /// Assignments are collected, even if they are live. Dead assignments are reported, and live
638    /// assignments are used to make diagnostics correct for match guards.
639    fn find_dead_assignments(
640        tcx: TyCtxt<'tcx>,
641        typing_env: ty::TypingEnv<'tcx>,
642        checked_places: &'a PlaceSet<'tcx>,
643        cursor: &mut ResultsCursor<'_, 'tcx, MaybeLivePlaces<'_, 'tcx>>,
644        body: &'a Body<'tcx>,
645    ) -> AssignmentResult<'a, 'tcx> {
646        let mut ever_live = DenseBitSet::new_empty(checked_places.len());
647        let mut ever_dropped = DenseBitSet::new_empty(checked_places.len());
648        let mut assignments = IndexVec::<PlaceIndex, FxIndexMap<_, _>>::from_elem(
649            Default::default(),
650            &checked_places.places,
651        );
652
653        let mut check_place = |place: Place<'tcx>,
654                               kind,
655                               source_info: SourceInfo,
656                               location: Location,
657                               live: &DenseBitSet<PlaceIndex>| {
658            if let Some((index, extra_projections)) = checked_places.get(place.as_ref()) {
659                if !is_indirect(extra_projections) {
660                    let is_direct = extra_projections.is_empty();
661                    match assignments[index].entry(source_info) {
662                        IndexEntry::Vacant(v) => {
663                            let access =
664                                Access { kind, location, live: live.contains(index), is_direct };
665                            v.insert(access);
666                        }
667                        IndexEntry::Occupied(mut o) => {
668                            // There were already a sighting. Mark this statement as live if it
669                            // was, to avoid false positives.
670                            o.get_mut().live |= live.contains(index);
671                            o.get_mut().is_direct &= is_direct;
672                        }
673                    }
674                }
675            }
676        };
677
678        let mut record_drop = |place: Place<'tcx>| {
679            if let Some((index, &[])) = checked_places.get(place.as_ref()) {
680                ever_dropped.insert(index);
681            }
682        };
683
684        for (bb, bb_data) in traversal::postorder(body) {
685            cursor.seek_to_block_end(bb);
686            let live = cursor.get();
687            ever_live.union(live);
688
689            let terminator = bb_data.terminator();
690            match &terminator.kind {
691                TerminatorKind::Call { destination: place, .. }
692                | TerminatorKind::Yield { resume_arg: place, .. } => {
693                    check_place(
694                        *place,
695                        AccessKind::Assign,
696                        terminator.source_info,
697                        body.terminator_loc(bb),
698                        live,
699                    );
700                    record_drop(*place)
701                }
702                TerminatorKind::Drop { place, .. } => record_drop(*place),
703                TerminatorKind::InlineAsm { operands, .. } => {
704                    for operand in operands {
705                        if let InlineAsmOperand::Out { place: Some(place), .. }
706                        | InlineAsmOperand::InOut { out_place: Some(place), .. } = operand
707                        {
708                            check_place(
709                                *place,
710                                AccessKind::Assign,
711                                terminator.source_info,
712                                body.terminator_loc(bb),
713                                live,
714                            );
715                        }
716                    }
717                }
718                _ => {}
719            }
720
721            for (statement_index, statement) in bb_data.statements.iter().enumerate().rev() {
722                let location = Location { block: bb, statement_index };
723                cursor.seek_before_primary_effect(location);
724                let live = cursor.get();
725                ever_live.union(live);
726                match &statement.kind {
727                    StatementKind::Assign(box (place, _))
728                    | StatementKind::SetDiscriminant { box place, .. } => {
729                        check_place(
730                            *place,
731                            AccessKind::Assign,
732                            statement.source_info,
733                            location,
734                            live,
735                        );
736                    }
737                    StatementKind::Retag(_, _)
738                    | StatementKind::StorageLive(_)
739                    | StatementKind::StorageDead(_)
740                    | StatementKind::Coverage(_)
741                    | StatementKind::Intrinsic(_)
742                    | StatementKind::Nop
743                    | StatementKind::FakeRead(_)
744                    | StatementKind::PlaceMention(_)
745                    | StatementKind::ConstEvalCounter
746                    | StatementKind::BackwardIncompatibleDropHint { .. }
747                    | StatementKind::AscribeUserType(_, _) => (),
748                }
749            }
750        }
751
752        // Check liveness of function arguments on entry.
753        {
754            cursor.seek_to_block_start(START_BLOCK);
755            let live = cursor.get();
756            ever_live.union(live);
757
758            // Verify that arguments and captured values are useful.
759            for (index, place) in checked_places.iter() {
760                let kind = if is_capture(*place) {
761                    // This is a by-ref capture, an assignment to it will modify surrounding
762                    // environment, so we do not report it.
763                    if place.projection.last() == Some(&PlaceElem::Deref) {
764                        continue;
765                    }
766
767                    AccessKind::Capture
768                } else if body.local_kind(place.local) == LocalKind::Arg {
769                    AccessKind::Param
770                } else {
771                    continue;
772                };
773                let source_info = body.local_decls[place.local].source_info;
774                let access = Access {
775                    kind,
776                    location: Location::START,
777                    live: live.contains(index),
778                    is_direct: true,
779                };
780                assignments[index].insert(source_info, access);
781            }
782        }
783
784        AssignmentResult {
785            tcx,
786            typing_env,
787            checked_places,
788            ever_live,
789            ever_dropped,
790            assignments,
791            body,
792        }
793    }
794
795    /// Match guards introduce a different local to freeze the guarded value as immutable.
796    /// Having two locals, we need to make sure that we do not report an unused_variable
797    /// when the guard local is used but not the arm local, or vice versa, like in this example.
798    ///
799    ///    match 5 {
800    ///      x if x > 2 => {}
801    ///      ^    ^- This is `local`
802    ///      +------ This is `arm_local`
803    ///      _ => {}
804    ///    }
805    ///
806    fn merge_guards(&mut self) {
807        for (index, place) in self.checked_places.iter() {
808            let local = place.local;
809            if let &LocalInfo::User(BindingForm::RefForGuard(arm_local)) =
810                self.body.local_decls[local].local_info()
811            {
812                if true {
    if !place.projection.is_empty() {
        ::core::panicking::panic("assertion failed: place.projection.is_empty()")
    };
};debug_assert!(place.projection.is_empty());
813
814                // Local to use in the arm.
815                let Some((arm_index, _proj)) = self.checked_places.get(arm_local.into()) else {
816                    continue;
817                };
818                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);
819                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, &[]);
820
821                // Mark the arm local as used if the guard local is used.
822                if self.ever_live.contains(index) {
823                    self.ever_live.insert(arm_index);
824                }
825
826                // Some assignments are common to both locals in the source code.
827                // Sadly, we can only detect this using the `source_info`.
828                // Therefore, we loop over all the assignments we have for the guard local:
829                // - if they already appeared for the arm local, the assignment is live if one of the
830                //   two versions is live;
831                // - if it does not appear for the arm local, it happened inside the guard, so we add
832                //   it as-is.
833                let guard_assignments = std::mem::take(&mut self.assignments[index]);
834                let arm_assignments = &mut self.assignments[arm_index];
835                for (source_info, access) in guard_assignments {
836                    match arm_assignments.entry(source_info) {
837                        IndexEntry::Vacant(v) => {
838                            v.insert(access);
839                        }
840                        IndexEntry::Occupied(mut o) => {
841                            o.get_mut().live |= access.live;
842                        }
843                    }
844                }
845            }
846        }
847    }
848
849    /// Compute captures that are fully dead.
850    fn compute_dead_captures(&self, num_captures: usize) -> DenseBitSet<FieldIdx> {
851        // Report to caller the set of dead captures.
852        let mut dead_captures = DenseBitSet::new_empty(num_captures);
853        for (index, place) in self.checked_places.iter() {
854            if self.ever_live.contains(index) {
855                continue;
856            }
857
858            // This is a capture: pass information to the enclosing function.
859            if is_capture(*place) {
860                for p in place.projection {
861                    if let PlaceElem::Field(f, _) = p {
862                        dead_captures.insert(*f);
863                        break;
864                    }
865                }
866                continue;
867            }
868        }
869
870        dead_captures
871    }
872
873    /// Check if a local is referenced in any reachable basic block.
874    /// Variables in unreachable code (e.g., after `todo!()`) should not trigger unused warnings.
875    fn is_local_in_reachable_code(&self, local: Local) -> bool {
876        struct LocalVisitor {
877            target_local: Local,
878            found: bool,
879        }
880
881        impl<'tcx> Visitor<'tcx> for LocalVisitor {
882            fn visit_local(&mut self, local: Local, _context: PlaceContext, _location: Location) {
883                if local == self.target_local {
884                    self.found = true;
885                }
886            }
887        }
888
889        let mut visitor = LocalVisitor { target_local: local, found: false };
890        for (bb, bb_data) in traversal::postorder(self.body) {
891            visitor.visit_basic_block_data(bb, bb_data);
892            if visitor.found {
893                return true;
894            }
895        }
896
897        false
898    }
899
900    /// Report fully unused locals, and forget the corresponding assignments.
901    fn report_fully_unused(&mut self) {
902        let tcx = self.tcx;
903
904        // Give a diagnostic when any of the string constants look like a naked format string that
905        // would interpolate our dead local.
906        let mut string_constants_in_body = None;
907        let mut maybe_suggest_literal_matching_name = |name: Symbol| {
908            // Visiting MIR to enumerate string constants can be expensive, so cache the result.
909            let string_constants_in_body = string_constants_in_body.get_or_insert_with(|| {
910                struct LiteralFinder {
911                    found: Vec<(Span, String)>,
912                }
913
914                impl<'tcx> Visitor<'tcx> for LiteralFinder {
915                    fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _: Location) {
916                        if let ty::Ref(_, ref_ty, _) = constant.ty().kind()
917                            && ref_ty.kind() == &ty::Str
918                        {
919                            let rendered_constant = constant.const_.to_string();
920                            self.found.push((constant.span, rendered_constant));
921                        }
922                    }
923                }
924
925                let mut finder = LiteralFinder { found: ::alloc::vec::Vec::new()vec![] };
926                finder.visit_body(self.body);
927                finder.found
928            });
929
930            let brace_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}", name))
    })format!("{{{name}");
931            string_constants_in_body
932                .iter()
933                .filter(|(_, rendered_constant)| {
934                    rendered_constant
935                        .split(&brace_name)
936                        .any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.chars().next() {
    Some('}' | ':') => true,
    _ => false,
}matches!(c.chars().next(), Some('}' | ':')))
937                })
938                .map(|&(lit, _)| errors::UnusedVariableStringInterp { lit })
939                .collect::<Vec<_>>()
940        };
941
942        // First, report fully unused locals.
943        for (index, place) in self.checked_places.iter() {
944            if self.ever_live.contains(index) {
945                continue;
946            }
947
948            // this is a capture: let the enclosing function report the unused variable.
949            if is_capture(*place) {
950                continue;
951            }
952
953            let local = place.local;
954            let decl = &self.body.local_decls[local];
955
956            if decl.from_compiler_desugaring() {
957                continue;
958            }
959
960            // Only report actual user-defined binding from now on.
961            let LocalInfo::User(BindingForm::Var(binding)) = decl.local_info() else { continue };
962            let Some(hir_id) = decl.source_info.scope.lint_root(&self.body.source_scopes) else {
963                continue;
964            };
965
966            let introductions = &binding.introductions;
967
968            let Some((name, def_span)) = self.checked_places.names[index] else { continue };
969
970            // #117284, when `ident_span` and `def_span` have different contexts
971            // we can't provide a good suggestion, instead we pointed out the spans from macro
972            let from_macro = def_span.from_expansion()
973                && introductions.iter().any(|intro| intro.span.eq_ctxt(def_span));
974
975            let maybe_suggest_typo = || {
976                if let LocalKind::Arg = self.body.local_kind(local) {
977                    None
978                } else {
979                    maybe_suggest_unit_pattern_typo(
980                        tcx,
981                        self.body.source.def_id(),
982                        name,
983                        def_span,
984                        decl.ty,
985                    )
986                }
987            };
988
989            let statements = &mut self.assignments[index];
990            if statements.is_empty() {
991                if !self.is_local_in_reachable_code(local) {
992                    continue;
993                }
994
995                let sugg = if from_macro {
996                    errors::UnusedVariableSugg::NoSugg { span: def_span, name }
997                } else {
998                    let typo = maybe_suggest_typo();
999                    errors::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 }
1000                };
1001                tcx.emit_node_span_lint(
1002                    lint::builtin::UNUSED_VARIABLES,
1003                    hir_id,
1004                    def_span,
1005                    errors::UnusedVariable {
1006                        name,
1007                        string_interp: maybe_suggest_literal_matching_name(name),
1008                        sugg,
1009                    },
1010                );
1011                continue;
1012            }
1013
1014            // Idiomatic rust assigns a value to a local upon definition. However, we do not want to
1015            // warn twice, for the unused local and for the unused assignment. Therefore, we remove
1016            // from the list of assignments the ones that happen at the definition site.
1017            statements.retain(|source_info, _| {
1018                !binding.introductions.iter().any(|intro| intro.span == source_info.span)
1019            });
1020
1021            // Extra assignments that we recognize thanks to the initialization span. We need to
1022            // take care of macro contexts here to be accurate.
1023            if let Some((_, initializer_span)) = binding.opt_match_place {
1024                statements.retain(|source_info, _| {
1025                    let within = source_info.span.find_ancestor_inside(initializer_span);
1026                    let outer_initializer_span =
1027                        initializer_span.find_ancestor_in_same_ctxt(source_info.span);
1028                    within.is_none()
1029                        && outer_initializer_span.map_or(true, |s| !s.contains(source_info.span))
1030                });
1031            }
1032
1033            if !statements.is_empty() {
1034                // We have a dead local with outstanding assignments and with non-trivial drop.
1035                // This is probably a drop-guard, so we do not issue a warning there.
1036                if maybe_drop_guard(
1037                    tcx,
1038                    self.typing_env,
1039                    index,
1040                    &self.ever_dropped,
1041                    self.checked_places,
1042                    self.body,
1043                ) {
1044                    statements.retain(|_, access| access.is_direct);
1045                    if statements.is_empty() {
1046                        continue;
1047                    }
1048                }
1049
1050                let typo = maybe_suggest_typo();
1051                tcx.emit_node_span_lint(
1052                    lint::builtin::UNUSED_VARIABLES,
1053                    hir_id,
1054                    def_span,
1055                    errors::UnusedVarAssignedOnly { name, typo },
1056                );
1057                continue;
1058            }
1059
1060            // We do not have outstanding assignments, suggest renaming the binding.
1061            let spans = introductions.iter().map(|intro| intro.span).collect::<Vec<_>>();
1062
1063            let any_shorthand = introductions.iter().any(|intro| intro.is_shorthand);
1064
1065            let sugg = if any_shorthand {
1066                errors::UnusedVariableSugg::TryIgnore {
1067                    name,
1068                    shorthands: introductions
1069                        .iter()
1070                        .filter_map(
1071                            |intro| if intro.is_shorthand { Some(intro.span) } else { None },
1072                        )
1073                        .collect(),
1074                    non_shorthands: introductions
1075                        .iter()
1076                        .filter_map(
1077                            |intro| {
1078                                if !intro.is_shorthand { Some(intro.span) } else { None }
1079                            },
1080                        )
1081                        .collect(),
1082                }
1083            } else if from_macro {
1084                errors::UnusedVariableSugg::NoSugg { span: def_span, name }
1085            } else if !introductions.is_empty() {
1086                let typo = maybe_suggest_typo();
1087                errors::UnusedVariableSugg::TryPrefix { name, typo, spans: spans.clone() }
1088            } else {
1089                let typo = maybe_suggest_typo();
1090                errors::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] }
1091            };
1092
1093            tcx.emit_node_span_lint(
1094                lint::builtin::UNUSED_VARIABLES,
1095                hir_id,
1096                spans,
1097                errors::UnusedVariable {
1098                    name,
1099                    string_interp: maybe_suggest_literal_matching_name(name),
1100                    sugg,
1101                },
1102            );
1103        }
1104    }
1105
1106    /// Second, report unused assignments that do not correspond to initialization.
1107    /// Initializations have been removed in the previous loop reporting unused variables.
1108    fn report_unused_assignments(self) {
1109        let tcx = self.tcx;
1110
1111        for (index, statements) in self.assignments.into_iter_enumerated() {
1112            if statements.is_empty() {
1113                continue;
1114            }
1115
1116            let Some((name, decl_span)) = self.checked_places.names[index] else { continue };
1117
1118            let is_maybe_drop_guard = maybe_drop_guard(
1119                tcx,
1120                self.typing_env,
1121                index,
1122                &self.ever_dropped,
1123                self.checked_places,
1124                self.body,
1125            );
1126
1127            // By convention, underscore-prefixed bindings are allowed to be unused explicitly.
1128            if name.as_str().starts_with('_') {
1129                continue;
1130            }
1131
1132            let mut next_direct_assignments: Vec<(Span, Location)> = Vec::new();
1133            let mut dead_statements = Vec::with_capacity(statements.len());
1134
1135            for (source_info, Access { live, kind, is_direct, location }) in statements.into_iter()
1136            {
1137                let direct_assignment = kind == AccessKind::Assign && is_direct;
1138                let should_report = !live && (is_direct || !is_maybe_drop_guard);
1139
1140                let overwrite = if should_report && direct_assignment {
1141                    next_direct_assignments
1142                        .iter()
1143                        .rfind(|(_, overwrite_location)| {
1144                            location.is_predecessor_of(*overwrite_location, self.body)
1145                        })
1146                        .map(|&(overwrite_span, _)| errors::UnusedAssignOverwrite {
1147                            assigned_span: source_info.span,
1148                            overwrite_span,
1149                            name,
1150                        })
1151                } else {
1152                    None
1153                };
1154
1155                if direct_assignment {
1156                    next_direct_assignments.push((source_info.span, location));
1157                }
1158
1159                if !should_report {
1160                    continue;
1161                }
1162                dead_statements.push((source_info, kind, is_direct, overwrite));
1163            }
1164
1165            // We probed MIR in reverse order for dataflow.
1166            // Emit diagnostics in source order instead.
1167            for (source_info, kind, is_direct, overwrite) in dead_statements.into_iter().rev() {
1168                // Report the dead assignment.
1169                let Some(hir_id) = source_info.scope.lint_root(&self.body.source_scopes) else {
1170                    continue;
1171                };
1172
1173                match kind {
1174                    AccessKind::Assign => {
1175                        let suggestion = annotate_mut_binding_to_immutable_binding(
1176                            tcx,
1177                            self.checked_places.places[index],
1178                            self.body.source.def_id().expect_local(),
1179                            source_info.span,
1180                            self.body,
1181                        );
1182                        let overwrite =
1183                            if suggestion.is_none() && is_direct { overwrite } else { None };
1184                        let help = suggestion.is_none() && overwrite.is_none();
1185                        tcx.emit_node_span_lint(
1186                            lint::builtin::UNUSED_ASSIGNMENTS,
1187                            hir_id,
1188                            source_info.span,
1189                            errors::UnusedAssign { name, overwrite, help, suggestion },
1190                        )
1191                    }
1192                    AccessKind::Param => tcx.emit_node_span_lint(
1193                        lint::builtin::UNUSED_ASSIGNMENTS,
1194                        hir_id,
1195                        source_info.span,
1196                        errors::UnusedAssignPassed { name },
1197                    ),
1198                    AccessKind::Capture => tcx.emit_node_span_lint(
1199                        lint::builtin::UNUSED_ASSIGNMENTS,
1200                        hir_id,
1201                        decl_span,
1202                        errors::UnusedCaptureMaybeCaptureRef { name },
1203                    ),
1204                }
1205            }
1206        }
1207    }
1208}
1209
1210impl ::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! {
1211    pub struct PlaceIndex {}
1212}
1213
1214impl DebugWithContext<MaybeLivePlaces<'_, '_>> for PlaceIndex {
1215    fn fmt_with(
1216        &self,
1217        ctxt: &MaybeLivePlaces<'_, '_>,
1218        f: &mut std::fmt::Formatter<'_>,
1219    ) -> std::fmt::Result {
1220        std::fmt::Debug::fmt(&ctxt.checked_places.places[*self], f)
1221    }
1222}
1223
1224pub struct MaybeLivePlaces<'a, 'tcx> {
1225    tcx: TyCtxt<'tcx>,
1226    checked_places: &'a PlaceSet<'tcx>,
1227    capture_kind: CaptureKind,
1228    self_assignment: FxHashSet<Location>,
1229}
1230
1231impl<'tcx> MaybeLivePlaces<'_, 'tcx> {
1232    fn transfer_function<'a>(
1233        &'a self,
1234        trans: &'a mut DenseBitSet<PlaceIndex>,
1235    ) -> TransferFunction<'a, 'tcx> {
1236        TransferFunction {
1237            tcx: self.tcx,
1238            checked_places: &self.checked_places,
1239            capture_kind: self.capture_kind,
1240            trans,
1241            self_assignment: &self.self_assignment,
1242        }
1243    }
1244}
1245
1246impl<'tcx> Analysis<'tcx> for MaybeLivePlaces<'_, 'tcx> {
1247    type Domain = DenseBitSet<PlaceIndex>;
1248    type Direction = Backward;
1249
1250    const NAME: &'static str = "liveness-lint";
1251
1252    fn bottom_value(&self, _: &Body<'tcx>) -> Self::Domain {
1253        // bottom = not live
1254        DenseBitSet::new_empty(self.checked_places.len())
1255    }
1256
1257    fn initialize_start_block(&self, _: &Body<'tcx>, _: &mut Self::Domain) {
1258        // No variables are live until we observe a use
1259    }
1260
1261    fn apply_primary_statement_effect(
1262        &self,
1263        trans: &mut Self::Domain,
1264        statement: &Statement<'tcx>,
1265        location: Location,
1266    ) {
1267        self.transfer_function(trans).visit_statement(statement, location);
1268    }
1269
1270    fn apply_primary_terminator_effect<'mir>(
1271        &self,
1272        trans: &mut Self::Domain,
1273        terminator: &'mir Terminator<'tcx>,
1274        location: Location,
1275    ) -> TerminatorEdges<'mir, 'tcx> {
1276        self.transfer_function(trans).visit_terminator(terminator, location);
1277        terminator.edges()
1278    }
1279
1280    fn apply_call_return_effect(
1281        &self,
1282        _trans: &mut Self::Domain,
1283        _block: BasicBlock,
1284        _return_places: CallReturnPlaces<'_, 'tcx>,
1285    ) {
1286        // FIXME: what should happen here?
1287    }
1288}
1289
1290struct TransferFunction<'a, 'tcx> {
1291    tcx: TyCtxt<'tcx>,
1292    checked_places: &'a PlaceSet<'tcx>,
1293    trans: &'a mut DenseBitSet<PlaceIndex>,
1294    capture_kind: CaptureKind,
1295    self_assignment: &'a FxHashSet<Location>,
1296}
1297
1298impl<'tcx> Visitor<'tcx> for TransferFunction<'_, 'tcx> {
1299    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1300        match statement.kind {
1301            // `ForLet(None)` and `ForGuardBinding` fake reads erroneously mark the just-assigned
1302            // locals as live. This defeats the purpose of the analysis for such bindings.
1303            StatementKind::FakeRead(box (
1304                FakeReadCause::ForLet(None) | FakeReadCause::ForGuardBinding,
1305                _,
1306            )) => return,
1307            // Handle self-assignment by restricting the read/write they do.
1308            StatementKind::Assign(box (ref dest, ref rvalue))
1309                if self.self_assignment.contains(&location) =>
1310            {
1311                if let Rvalue::BinaryOp(
1312                    BinOp::AddWithOverflow | BinOp::SubWithOverflow | BinOp::MulWithOverflow,
1313                    box (_, rhs),
1314                ) = rvalue
1315                {
1316                    // We are computing the binary operation:
1317                    // - the LHS will be assigned, so we don't read it;
1318                    // - the RHS still needs to be read.
1319                    self.visit_operand(rhs, location);
1320                    self.visit_place(
1321                        dest,
1322                        PlaceContext::MutatingUse(MutatingUseContext::Store),
1323                        location,
1324                    );
1325                } else if let Rvalue::BinaryOp(_, box (_, rhs)) = rvalue {
1326                    // We are computing the binary operation:
1327                    // - the LHS is being updated, so we don't read it;
1328                    // - the RHS still needs to be read.
1329                    self.visit_operand(rhs, location);
1330                } else {
1331                    // This is the second part of a checked self-assignment,
1332                    // we are assigning the result.
1333                    // We do not consider the write to the destination as a `def`.
1334                    // `self_assignment` must be false if the assignment is indirect.
1335                    self.visit_rvalue(rvalue, location);
1336                }
1337            }
1338            _ => self.super_statement(statement, location),
1339        }
1340    }
1341
1342    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1343        // By-ref captures could be read by the surrounding environment, so we mark
1344        // them as live upon yield and return.
1345        match terminator.kind {
1346            TerminatorKind::Return
1347            | TerminatorKind::Yield { .. }
1348            | TerminatorKind::Goto { target: START_BLOCK } // Inserted for the `FnMut` case.
1349            | TerminatorKind::Call { target: None, .. } // unwinding could be caught
1350                if self.capture_kind != CaptureKind::None =>
1351            {
1352                // All indirect captures have an effect on the environment, so we mark them as live.
1353                for (index, place) in self.checked_places.iter() {
1354                    if place.local == ty::CAPTURE_STRUCT_LOCAL
1355                        && place.projection.last() == Some(&PlaceElem::Deref)
1356                    {
1357                        self.trans.insert(index);
1358                    }
1359                }
1360            }
1361            // Do not consider a drop to be a use. We whitelist interesting drops elsewhere.
1362            TerminatorKind::Drop { .. } => {}
1363            // Ignore assertions since they must be triggered by actual code.
1364            TerminatorKind::Assert { .. } => {}
1365            _ => self.super_terminator(terminator, location),
1366        }
1367    }
1368
1369    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1370        match rvalue {
1371            // When a closure/generator does not use some of its captures, do not consider these
1372            // captures as live in the surrounding function. This allows to report unused variables,
1373            // even if they have been (uselessly) captured.
1374            Rvalue::Aggregate(
1375                box AggregateKind::Closure(def_id, _) | box AggregateKind::Coroutine(def_id, _),
1376                operands,
1377            ) => {
1378                if let Some(def_id) = def_id.as_local() {
1379                    let dead_captures = self.tcx.check_liveness(def_id);
1380                    for (field, operand) in
1381                        operands.iter_enumerated().take(dead_captures.domain_size())
1382                    {
1383                        if !dead_captures.contains(field) {
1384                            self.visit_operand(operand, location);
1385                        }
1386                    }
1387                }
1388            }
1389            _ => self.super_rvalue(rvalue, location),
1390        }
1391    }
1392
1393    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1394        if let Some((index, extra_projections)) = self.checked_places.get(place.as_ref()) {
1395            for i in (extra_projections.len()..=place.projection.len()).rev() {
1396                let place_part =
1397                    PlaceRef { local: place.local, projection: &place.projection[..i] };
1398                let extra_projections = &place.projection[i..];
1399
1400                if let Some(&elem) = extra_projections.get(0) {
1401                    self.visit_projection_elem(place_part, elem, context, location);
1402                }
1403            }
1404
1405            match DefUse::for_place(extra_projections, context) {
1406                Some(DefUse::Def) => {
1407                    self.trans.remove(index);
1408                }
1409                Some(DefUse::Use) => {
1410                    self.trans.insert(index);
1411                }
1412                None => {}
1413            }
1414        } else {
1415            self.super_place(place, context, location)
1416        }
1417    }
1418
1419    fn visit_local(&mut self, local: Local, context: PlaceContext, _: Location) {
1420        if let Some((index, _proj)) = self.checked_places.get(local.into()) {
1421            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, &[]);
1422            match DefUse::for_place(&[], context) {
1423                Some(DefUse::Def) => {
1424                    self.trans.remove(index);
1425                }
1426                Some(DefUse::Use) => {
1427                    self.trans.insert(index);
1428                }
1429                _ => {}
1430            }
1431        }
1432    }
1433}
1434
1435#[derive(#[automatically_derived]
impl ::core::cmp::Eq for DefUse {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for DefUse {
    #[inline]
    fn eq(&self, other: &DefUse) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for DefUse {
    #[inline]
    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]
    fn clone(&self) -> DefUse {
        match self { DefUse::Def => DefUse::Def, DefUse::Use => DefUse::Use, }
    }
}Clone)]
1436enum DefUse {
1437    Def,
1438    Use,
1439}
1440
1441fn is_indirect(proj: &[PlaceElem<'_>]) -> bool {
1442    proj.iter().any(|p| p.is_indirect())
1443}
1444
1445impl DefUse {
1446    fn for_place<'tcx>(projection: &[PlaceElem<'tcx>], context: PlaceContext) -> Option<DefUse> {
1447        let is_indirect = is_indirect(projection);
1448        match context {
1449            PlaceContext::MutatingUse(
1450                MutatingUseContext::Store | MutatingUseContext::SetDiscriminant,
1451            ) => {
1452                if is_indirect {
1453                    // Treat derefs as a use of the base local. `*p = 4` is not a def of `p` but a
1454                    // use.
1455                    Some(DefUse::Use)
1456                } else if projection.is_empty() {
1457                    Some(DefUse::Def)
1458                } else {
1459                    None
1460                }
1461            }
1462
1463            // For the associated terminators, this is only a `Def` when the terminator returns
1464            // "successfully." As such, we handle this case separately in `call_return_effect`
1465            // above. However, if the place looks like `*_5`, this is still unconditionally a use of
1466            // `_5`.
1467            PlaceContext::MutatingUse(
1468                MutatingUseContext::Call
1469                | MutatingUseContext::Yield
1470                | MutatingUseContext::AsmOutput,
1471            ) => is_indirect.then_some(DefUse::Use),
1472
1473            // All other contexts are uses...
1474            PlaceContext::MutatingUse(
1475                MutatingUseContext::RawBorrow
1476                | MutatingUseContext::Borrow
1477                | MutatingUseContext::Drop
1478                | MutatingUseContext::Retag,
1479            )
1480            | PlaceContext::NonMutatingUse(
1481                NonMutatingUseContext::RawBorrow
1482                | NonMutatingUseContext::Copy
1483                | NonMutatingUseContext::Inspect
1484                | NonMutatingUseContext::Move
1485                | NonMutatingUseContext::FakeBorrow
1486                | NonMutatingUseContext::SharedBorrow
1487                | NonMutatingUseContext::PlaceMention,
1488            ) => Some(DefUse::Use),
1489
1490            PlaceContext::NonUse(
1491                NonUseContext::StorageLive
1492                | NonUseContext::StorageDead
1493                | NonUseContext::AscribeUserTy(_)
1494                | NonUseContext::BackwardIncompatibleDropHint
1495                | NonUseContext::VarDebugInfo,
1496            ) => None,
1497
1498            PlaceContext::MutatingUse(MutatingUseContext::Projection)
1499            | PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection) => {
1500                {
    ::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")
1501            }
1502        }
1503    }
1504}