1use std::io;
85use std::io::prelude::*;
86use std::rc::Rc;
87
88use rustc_attr_data_structures::{AttributeKind, find_attr};
89use rustc_data_structures::fx::FxIndexMap;
90use rustc_hir as hir;
91use rustc_hir::def::*;
92use rustc_hir::def_id::LocalDefId;
93use rustc_hir::intravisit::{self, Visitor};
94use rustc_hir::{Expr, HirId, HirIdMap, HirIdSet};
95use rustc_index::IndexVec;
96use rustc_middle::query::Providers;
97use rustc_middle::span_bug;
98use rustc_middle::ty::{self, RootVariableMinCaptureList, Ty, TyCtxt};
99use rustc_session::lint;
100use rustc_span::{BytePos, Span, Symbol, sym};
101use tracing::{debug, instrument};
102
103use self::LiveNodeKind::*;
104use self::VarKind::*;
105use crate::errors;
106
107mod rwu_table;
108
109rustc_index::newtype_index! {
110 #[debug_format = "v({})"]
111 pub struct Variable {}
112}
113
114rustc_index::newtype_index! {
115 #[debug_format = "ln({})"]
116 pub struct LiveNode {}
117}
118
119#[derive(Copy, Clone, PartialEq, Debug)]
120enum LiveNodeKind {
121 UpvarNode(Span),
122 ExprNode(Span, HirId),
123 VarDefNode(Span, HirId),
124 ClosureNode,
125 ExitNode,
126}
127
128fn live_node_kind_to_string(lnk: LiveNodeKind, tcx: TyCtxt<'_>) -> String {
129 let sm = tcx.sess.source_map();
130 match lnk {
131 UpvarNode(s) => format!("Upvar node [{}]", sm.span_to_diagnostic_string(s)),
132 ExprNode(s, _) => format!("Expr node [{}]", sm.span_to_diagnostic_string(s)),
133 VarDefNode(s, _) => format!("Var def node [{}]", sm.span_to_diagnostic_string(s)),
134 ClosureNode => "Closure node".to_owned(),
135 ExitNode => "Exit node".to_owned(),
136 }
137}
138
139fn check_liveness(tcx: TyCtxt<'_>, def_id: LocalDefId) {
140 let parent = tcx.local_parent(def_id);
142 if let DefKind::Impl { .. } = tcx.def_kind(parent)
143 && tcx.has_attr(parent, sym::automatically_derived)
144 {
145 return;
146 }
147
148 if find_attr!(tcx.get_all_attrs(def_id.to_def_id()), AttributeKind::Naked(..)) {
150 return;
151 }
152
153 let mut maps = IrMaps::new(tcx);
154 let body = tcx.hir_body_owned_by(def_id);
155 let hir_id = tcx.hir_body_owner(body.id());
156
157 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
158 for &var_hir_id in upvars.keys() {
159 let var_name = tcx.hir_name(var_hir_id);
160 maps.add_variable(Upvar(var_hir_id, var_name));
161 }
162 }
163
164 maps.visit_body(&body);
167
168 let mut lsets = Liveness::new(&mut maps, def_id);
170 let entry_ln = lsets.compute(&body, hir_id);
171 lsets.log_liveness(entry_ln, body.id().hir_id);
172
173 lsets.visit_body(&body);
175 lsets.warn_about_unused_upvars(entry_ln);
176 lsets.warn_about_unused_args(&body, entry_ln);
177}
178
179pub(crate) fn provide(providers: &mut Providers) {
180 *providers = Providers { check_liveness, ..*providers };
181}
182
183struct CaptureInfo {
206 ln: LiveNode,
207 var_hid: HirId,
208}
209
210#[derive(Copy, Clone, Debug)]
211struct LocalInfo {
212 id: HirId,
213 name: Symbol,
214 is_shorthand: bool,
215}
216
217#[derive(Copy, Clone, Debug)]
218enum VarKind {
219 Param(HirId, Symbol),
220 Local(LocalInfo),
221 Upvar(HirId, Symbol),
222}
223
224struct CollectLitsVisitor<'tcx> {
225 lit_exprs: Vec<&'tcx hir::Expr<'tcx>>,
226}
227
228impl<'tcx> Visitor<'tcx> for CollectLitsVisitor<'tcx> {
229 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
230 if let hir::ExprKind::Lit(_) = expr.kind {
231 self.lit_exprs.push(expr);
232 }
233 intravisit::walk_expr(self, expr);
234 }
235}
236
237struct IrMaps<'tcx> {
238 tcx: TyCtxt<'tcx>,
239 live_node_map: HirIdMap<LiveNode>,
240 variable_map: HirIdMap<Variable>,
241 capture_info_map: HirIdMap<Rc<Vec<CaptureInfo>>>,
242 var_kinds: IndexVec<Variable, VarKind>,
243 lnks: IndexVec<LiveNode, LiveNodeKind>,
244}
245
246impl<'tcx> IrMaps<'tcx> {
247 fn new(tcx: TyCtxt<'tcx>) -> IrMaps<'tcx> {
248 IrMaps {
249 tcx,
250 live_node_map: HirIdMap::default(),
251 variable_map: HirIdMap::default(),
252 capture_info_map: Default::default(),
253 var_kinds: IndexVec::new(),
254 lnks: IndexVec::new(),
255 }
256 }
257
258 fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode {
259 let ln = self.lnks.push(lnk);
260
261 debug!("{:?} is of kind {}", ln, live_node_kind_to_string(lnk, self.tcx));
262
263 ln
264 }
265
266 fn add_live_node_for_node(&mut self, hir_id: HirId, lnk: LiveNodeKind) {
267 let ln = self.add_live_node(lnk);
268 self.live_node_map.insert(hir_id, ln);
269
270 debug!("{:?} is node {:?}", ln, hir_id);
271 }
272
273 fn add_variable(&mut self, vk: VarKind) -> Variable {
274 let v = self.var_kinds.push(vk);
275
276 match vk {
277 Local(LocalInfo { id: node_id, .. }) | Param(node_id, _) | Upvar(node_id, _) => {
278 self.variable_map.insert(node_id, v);
279 }
280 }
281
282 debug!("{:?} is {:?}", v, vk);
283
284 v
285 }
286
287 fn variable(&self, hir_id: HirId, span: Span) -> Variable {
288 match self.variable_map.get(&hir_id) {
289 Some(&var) => var,
290 None => {
291 span_bug!(span, "no variable registered for id {:?}", hir_id);
292 }
293 }
294 }
295
296 fn variable_name(&self, var: Variable) -> Symbol {
297 match self.var_kinds[var] {
298 Local(LocalInfo { name, .. }) | Param(_, name) | Upvar(_, name) => name,
299 }
300 }
301
302 fn variable_is_shorthand(&self, var: Variable) -> bool {
303 match self.var_kinds[var] {
304 Local(LocalInfo { is_shorthand, .. }) => is_shorthand,
305 Param(..) | Upvar(..) => false,
306 }
307 }
308
309 fn set_captures(&mut self, hir_id: HirId, cs: Vec<CaptureInfo>) {
310 self.capture_info_map.insert(hir_id, Rc::new(cs));
311 }
312
313 fn collect_shorthand_field_ids(&self, pat: &hir::Pat<'tcx>) -> HirIdSet {
314 let mut shorthand_field_ids = HirIdSet::default();
317
318 pat.walk_always(|pat| {
319 if let hir::PatKind::Struct(_, fields, _) = pat.kind {
320 let short = fields.iter().filter(|f| f.is_shorthand);
321 shorthand_field_ids.extend(short.map(|f| f.pat.hir_id));
322 }
323 });
324
325 shorthand_field_ids
326 }
327
328 fn add_from_pat(&mut self, pat: &hir::Pat<'tcx>) {
329 let shorthand_field_ids = self.collect_shorthand_field_ids(pat);
330
331 pat.each_binding(|_, hir_id, _, ident| {
332 self.add_live_node_for_node(hir_id, VarDefNode(ident.span, hir_id));
333 self.add_variable(Local(LocalInfo {
334 id: hir_id,
335 name: ident.name,
336 is_shorthand: shorthand_field_ids.contains(&hir_id),
337 }));
338 });
339 }
340}
341
342impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> {
343 fn visit_local(&mut self, local: &'tcx hir::LetStmt<'tcx>) {
344 self.add_from_pat(local.pat);
345 if local.els.is_some() {
346 self.add_live_node_for_node(local.hir_id, ExprNode(local.span, local.hir_id));
347 }
348 intravisit::walk_local(self, local);
349 }
350
351 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
352 self.add_from_pat(&arm.pat);
353 intravisit::walk_arm(self, arm);
354 }
355
356 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
357 let shorthand_field_ids = self.collect_shorthand_field_ids(param.pat);
358 param.pat.each_binding(|_bm, hir_id, _x, ident| {
359 let var = match param.pat.kind {
360 rustc_hir::PatKind::Struct(..) => Local(LocalInfo {
361 id: hir_id,
362 name: ident.name,
363 is_shorthand: shorthand_field_ids.contains(&hir_id),
364 }),
365 _ => Param(hir_id, ident.name),
366 };
367 self.add_variable(var);
368 });
369 intravisit::walk_param(self, param);
370 }
371
372 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
373 match expr.kind {
374 hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => {
376 debug!("expr {}: path that leads to {:?}", expr.hir_id, path.res);
377 if let Res::Local(_var_hir_id) = path.res {
378 self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id));
379 }
380 }
381 hir::ExprKind::Closure(closure) => {
382 self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id));
385
386 let mut call_caps = Vec::new();
391 if let Some(upvars) = self.tcx.upvars_mentioned(closure.def_id) {
392 call_caps.extend(upvars.keys().map(|var_id| {
393 let upvar = upvars[var_id];
394 let upvar_ln = self.add_live_node(UpvarNode(upvar.span));
395 CaptureInfo { ln: upvar_ln, var_hid: *var_id }
396 }));
397 }
398 self.set_captures(expr.hir_id, call_caps);
399 }
400
401 hir::ExprKind::Let(let_expr) => {
402 self.add_from_pat(let_expr.pat);
403 }
404
405 hir::ExprKind::If(..)
407 | hir::ExprKind::Match(..)
408 | hir::ExprKind::Loop(..)
409 | hir::ExprKind::Yield(..) => {
410 self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id));
411 }
412 hir::ExprKind::Binary(op, ..) if op.node.is_lazy() => {
413 self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id));
414 }
415
416 hir::ExprKind::InlineAsm(asm) if asm.contains_label() => {
418 self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id));
419 intravisit::walk_expr(self, expr);
420 }
421
422 hir::ExprKind::Index(..)
424 | hir::ExprKind::Field(..)
425 | hir::ExprKind::Array(..)
426 | hir::ExprKind::Call(..)
427 | hir::ExprKind::MethodCall(..)
428 | hir::ExprKind::Use(..)
429 | hir::ExprKind::Tup(..)
430 | hir::ExprKind::Binary(..)
431 | hir::ExprKind::AddrOf(..)
432 | hir::ExprKind::Cast(..)
433 | hir::ExprKind::DropTemps(..)
434 | hir::ExprKind::Unary(..)
435 | hir::ExprKind::Break(..)
436 | hir::ExprKind::Continue(_)
437 | hir::ExprKind::Lit(_)
438 | hir::ExprKind::ConstBlock(..)
439 | hir::ExprKind::Ret(..)
440 | hir::ExprKind::Become(..)
441 | hir::ExprKind::Block(..)
442 | hir::ExprKind::Assign(..)
443 | hir::ExprKind::AssignOp(..)
444 | hir::ExprKind::Struct(..)
445 | hir::ExprKind::Repeat(..)
446 | hir::ExprKind::InlineAsm(..)
447 | hir::ExprKind::OffsetOf(..)
448 | hir::ExprKind::Type(..)
449 | hir::ExprKind::UnsafeBinderCast(..)
450 | hir::ExprKind::Err(_)
451 | hir::ExprKind::Path(hir::QPath::TypeRelative(..))
452 | hir::ExprKind::Path(hir::QPath::LangItem(..)) => {}
453 }
454 intravisit::walk_expr(self, expr);
455 }
456}
457
458const ACC_READ: u32 = 1;
465const ACC_WRITE: u32 = 2;
466const ACC_USE: u32 = 4;
467
468struct Liveness<'a, 'tcx> {
469 ir: &'a mut IrMaps<'tcx>,
470 typeck_results: &'a ty::TypeckResults<'tcx>,
471 typing_env: ty::TypingEnv<'tcx>,
472 closure_min_captures: Option<&'tcx RootVariableMinCaptureList<'tcx>>,
473 successors: IndexVec<LiveNode, Option<LiveNode>>,
474 rwu_table: rwu_table::RWUTable,
475
476 closure_ln: LiveNode,
480 exit_ln: LiveNode,
483
484 break_ln: HirIdMap<LiveNode>,
488 cont_ln: HirIdMap<LiveNode>,
489}
490
491impl<'a, 'tcx> Liveness<'a, 'tcx> {
492 fn new(ir: &'a mut IrMaps<'tcx>, body_owner: LocalDefId) -> Liveness<'a, 'tcx> {
493 let typeck_results = ir.tcx.typeck(body_owner);
494 assert!(typeck_results.tainted_by_errors.is_none());
497 let typing_env = ty::TypingEnv::non_body_analysis(ir.tcx, body_owner);
499 let closure_min_captures = typeck_results.closure_min_captures.get(&body_owner);
500 let closure_ln = ir.add_live_node(ClosureNode);
501 let exit_ln = ir.add_live_node(ExitNode);
502
503 let num_live_nodes = ir.lnks.len();
504 let num_vars = ir.var_kinds.len();
505
506 Liveness {
507 ir,
508 typeck_results,
509 typing_env,
510 closure_min_captures,
511 successors: IndexVec::from_elem_n(None, num_live_nodes),
512 rwu_table: rwu_table::RWUTable::new(num_live_nodes, num_vars),
513 closure_ln,
514 exit_ln,
515 break_ln: Default::default(),
516 cont_ln: Default::default(),
517 }
518 }
519
520 fn live_node(&self, hir_id: HirId, span: Span) -> LiveNode {
521 match self.ir.live_node_map.get(&hir_id) {
522 Some(&ln) => ln,
523 None => {
524 span_bug!(span, "no live node registered for node {:?}", hir_id);
529 }
530 }
531 }
532
533 fn variable(&self, hir_id: HirId, span: Span) -> Variable {
534 self.ir.variable(hir_id, span)
535 }
536
537 fn define_bindings_in_pat(&mut self, pat: &hir::Pat<'_>, mut succ: LiveNode) -> LiveNode {
538 pat.each_binding_or_first(&mut |_, hir_id, pat_sp, ident| {
542 let ln = self.live_node(hir_id, pat_sp);
543 let var = self.variable(hir_id, ident.span);
544 self.init_from_succ(ln, succ);
545 self.define(ln, var);
546 succ = ln;
547 });
548 succ
549 }
550
551 fn live_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
552 self.rwu_table.get_reader(ln, var)
553 }
554
555 fn live_on_exit(&self, ln: LiveNode, var: Variable) -> bool {
557 let successor = self.successors[ln].unwrap();
558 self.live_on_entry(successor, var)
559 }
560
561 fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
562 self.rwu_table.get_used(ln, var)
563 }
564
565 fn assigned_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
566 self.rwu_table.get_writer(ln, var)
567 }
568
569 fn assigned_on_exit(&self, ln: LiveNode, var: Variable) -> bool {
570 match self.successors[ln] {
571 Some(successor) => self.assigned_on_entry(successor, var),
572 None => {
573 self.ir.tcx.dcx().delayed_bug("no successor");
574 true
575 }
576 }
577 }
578
579 fn write_vars<F>(&self, wr: &mut dyn Write, mut test: F) -> io::Result<()>
580 where
581 F: FnMut(Variable) -> bool,
582 {
583 for var in self.ir.var_kinds.indices() {
584 if test(var) {
585 write!(wr, " {var:?}")?;
586 }
587 }
588 Ok(())
589 }
590
591 #[allow(unused_must_use)]
592 fn ln_str(&self, ln: LiveNode) -> String {
593 let mut wr = Vec::new();
594 {
595 let wr = &mut wr as &mut dyn Write;
596 write!(wr, "[{:?} of kind {:?} reads", ln, self.ir.lnks[ln]);
597 self.write_vars(wr, |var| self.rwu_table.get_reader(ln, var));
598 write!(wr, " writes");
599 self.write_vars(wr, |var| self.rwu_table.get_writer(ln, var));
600 write!(wr, " uses");
601 self.write_vars(wr, |var| self.rwu_table.get_used(ln, var));
602
603 write!(wr, " precedes {:?}]", self.successors[ln]);
604 }
605 String::from_utf8(wr).unwrap()
606 }
607
608 fn log_liveness(&self, entry_ln: LiveNode, hir_id: HirId) {
609 debug!(
611 "^^ liveness computation results for body {} (entry={:?})",
612 {
613 for ln_idx in self.ir.lnks.indices() {
614 debug!("{:?}", self.ln_str(ln_idx));
615 }
616 hir_id
617 },
618 entry_ln
619 );
620 }
621
622 fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) {
623 self.successors[ln] = Some(succ_ln);
624
625 }
628
629 fn init_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) {
630 self.successors[ln] = Some(succ_ln);
632 self.rwu_table.copy(ln, succ_ln);
633 debug!("init_from_succ(ln={}, succ={})", self.ln_str(ln), self.ln_str(succ_ln));
634 }
635
636 fn merge_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) -> bool {
637 if ln == succ_ln {
638 return false;
639 }
640
641 let changed = self.rwu_table.union(ln, succ_ln);
642 debug!("merge_from_succ(ln={:?}, succ={}, changed={})", ln, self.ln_str(succ_ln), changed);
643 changed
644 }
645
646 fn define(&mut self, writer: LiveNode, var: Variable) {
650 let used = self.rwu_table.get_used(writer, var);
651 self.rwu_table.set(writer, var, rwu_table::RWU { reader: false, writer: false, used });
652 debug!("{:?} defines {:?}: {}", writer, var, self.ln_str(writer));
653 }
654
655 fn acc(&mut self, ln: LiveNode, var: Variable, acc: u32) {
657 debug!("{:?} accesses[{:x}] {:?}: {}", ln, acc, var, self.ln_str(ln));
658
659 let mut rwu = self.rwu_table.get(ln, var);
660
661 if (acc & ACC_WRITE) != 0 {
662 rwu.reader = false;
663 rwu.writer = true;
664 }
665
666 if (acc & ACC_READ) != 0 {
669 rwu.reader = true;
670 }
671
672 if (acc & ACC_USE) != 0 {
673 rwu.used = true;
674 }
675
676 self.rwu_table.set(ln, var, rwu);
677 }
678
679 fn compute(&mut self, body: &hir::Body<'_>, hir_id: HirId) -> LiveNode {
680 debug!("compute: for body {:?}", body.id().hir_id);
681
682 if let Some(closure_min_captures) = self.closure_min_captures {
699 for (&var_hir_id, min_capture_list) in closure_min_captures {
701 for captured_place in min_capture_list {
702 match captured_place.info.capture_kind {
703 ty::UpvarCapture::ByRef(_) => {
704 let var = self.variable(
705 var_hir_id,
706 captured_place.get_capture_kind_span(self.ir.tcx),
707 );
708 self.acc(self.exit_ln, var, ACC_READ | ACC_USE);
709 }
710 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
711 }
712 }
713 }
714 }
715
716 let succ = self.propagate_through_expr(body.value, self.exit_ln);
717
718 if self.closure_min_captures.is_none() {
719 return succ;
723 }
724
725 let ty = self.typeck_results.node_type(hir_id);
726 match ty.kind() {
727 ty::Closure(_def_id, args) => match args.as_closure().kind() {
728 ty::ClosureKind::Fn => {}
729 ty::ClosureKind::FnMut => {}
730 ty::ClosureKind::FnOnce => return succ,
731 },
732 ty::CoroutineClosure(_def_id, args) => match args.as_coroutine_closure().kind() {
733 ty::ClosureKind::Fn => {}
734 ty::ClosureKind::FnMut => {}
735 ty::ClosureKind::FnOnce => return succ,
736 },
737 ty::Coroutine(..) => return succ,
738 _ => {
739 span_bug!(
740 body.value.span,
741 "{} has upvars so it should have a closure type: {:?}",
742 hir_id,
743 ty
744 );
745 }
746 };
747
748 loop {
750 self.init_from_succ(self.closure_ln, succ);
751 for param in body.params {
752 param.pat.each_binding(|_bm, hir_id, _x, ident| {
753 let var = self.variable(hir_id, ident.span);
754 self.define(self.closure_ln, var);
755 })
756 }
757
758 if !self.merge_from_succ(self.exit_ln, self.closure_ln) {
759 break;
760 }
761 assert_eq!(succ, self.propagate_through_expr(body.value, self.exit_ln));
762 }
763
764 succ
765 }
766
767 fn propagate_through_block(&mut self, blk: &hir::Block<'_>, succ: LiveNode) -> LiveNode {
768 if blk.targeted_by_break {
769 self.break_ln.insert(blk.hir_id, succ);
770 }
771 let succ = self.propagate_through_opt_expr(blk.expr, succ);
772 blk.stmts.iter().rev().fold(succ, |succ, stmt| self.propagate_through_stmt(stmt, succ))
773 }
774
775 fn propagate_through_stmt(&mut self, stmt: &hir::Stmt<'_>, succ: LiveNode) -> LiveNode {
776 match stmt.kind {
777 hir::StmtKind::Let(local) => {
778 if let Some(els) = local.els {
793 if let Some(init) = local.init {
810 let else_ln = self.propagate_through_block(els, succ);
811 let ln = self.live_node(local.hir_id, local.span);
812 self.init_from_succ(ln, succ);
813 self.merge_from_succ(ln, else_ln);
814 let succ = self.propagate_through_expr(init, ln);
815 self.define_bindings_in_pat(local.pat, succ)
816 } else {
817 span_bug!(
818 stmt.span,
819 "variable is uninitialized but an unexpected else branch is found"
820 )
821 }
822 } else {
823 let succ = self.propagate_through_opt_expr(local.init, succ);
824 self.define_bindings_in_pat(local.pat, succ)
825 }
826 }
827 hir::StmtKind::Item(..) => succ,
828 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
829 self.propagate_through_expr(expr, succ)
830 }
831 }
832 }
833
834 fn propagate_through_exprs(&mut self, exprs: &[Expr<'_>], succ: LiveNode) -> LiveNode {
835 exprs.iter().rev().fold(succ, |succ, expr| self.propagate_through_expr(expr, succ))
836 }
837
838 fn propagate_through_opt_expr(
839 &mut self,
840 opt_expr: Option<&Expr<'_>>,
841 succ: LiveNode,
842 ) -> LiveNode {
843 opt_expr.map_or(succ, |expr| self.propagate_through_expr(expr, succ))
844 }
845
846 fn propagate_through_expr(&mut self, expr: &Expr<'_>, succ: LiveNode) -> LiveNode {
847 debug!("propagate_through_expr: {:?}", expr);
848
849 match expr.kind {
850 hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => {
852 self.access_path(expr.hir_id, path, succ, ACC_READ | ACC_USE)
853 }
854
855 hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(e, succ),
856
857 hir::ExprKind::Closure { .. } => {
858 debug!("{:?} is an ExprKind::Closure", expr);
859
860 let caps = self
863 .ir
864 .capture_info_map
865 .get(&expr.hir_id)
866 .cloned()
867 .unwrap_or_else(|| span_bug!(expr.span, "no registered caps"));
868
869 caps.iter().rev().fold(succ, |succ, cap| {
870 self.init_from_succ(cap.ln, succ);
871 let var = self.variable(cap.var_hid, expr.span);
872 self.acc(cap.ln, var, ACC_READ | ACC_USE);
873 cap.ln
874 })
875 }
876
877 hir::ExprKind::Let(let_expr) => {
878 let succ = self.propagate_through_expr(let_expr.init, succ);
879 self.define_bindings_in_pat(let_expr.pat, succ)
880 }
881
882 hir::ExprKind::Loop(ref blk, ..) => self.propagate_through_loop(expr, blk, succ),
885
886 hir::ExprKind::Yield(e, ..) => {
887 let yield_ln = self.live_node(expr.hir_id, expr.span);
888 self.init_from_succ(yield_ln, succ);
889 self.merge_from_succ(yield_ln, self.exit_ln);
890 self.propagate_through_expr(e, yield_ln)
891 }
892
893 hir::ExprKind::If(ref cond, ref then, ref else_opt) => {
894 let else_ln = self.propagate_through_opt_expr(else_opt.as_deref(), succ);
908 let then_ln = self.propagate_through_expr(then, succ);
909 let ln = self.live_node(expr.hir_id, expr.span);
910 self.init_from_succ(ln, else_ln);
911 self.merge_from_succ(ln, then_ln);
912 self.propagate_through_expr(cond, ln)
913 }
914
915 hir::ExprKind::Match(ref e, arms, _) => {
916 let ln = self.live_node(expr.hir_id, expr.span);
931 self.init_empty(ln, succ);
932 for arm in arms {
933 let body_succ = self.propagate_through_expr(arm.body, succ);
934
935 let guard_succ = arm
936 .guard
937 .as_ref()
938 .map_or(body_succ, |g| self.propagate_through_expr(g, body_succ));
939 let arm_succ = self.define_bindings_in_pat(&arm.pat, guard_succ);
940 self.merge_from_succ(ln, arm_succ);
941 }
942 self.propagate_through_expr(e, ln)
943 }
944
945 hir::ExprKind::Ret(ref o_e) => {
946 self.propagate_through_opt_expr(o_e.as_deref(), self.exit_ln)
948 }
949
950 hir::ExprKind::Become(e) => {
951 self.propagate_through_expr(e, self.exit_ln)
953 }
954
955 hir::ExprKind::Break(label, ref opt_expr) => {
956 let target = match label.target_id {
958 Ok(hir_id) => self.break_ln.get(&hir_id),
959 Err(err) => span_bug!(expr.span, "loop scope error: {}", err),
960 }
961 .cloned();
962
963 match target {
967 Some(b) => self.propagate_through_opt_expr(opt_expr.as_deref(), b),
968 None => span_bug!(expr.span, "`break` to unknown label"),
969 }
970 }
971
972 hir::ExprKind::Continue(label) => {
973 let sc = label
975 .target_id
976 .unwrap_or_else(|err| span_bug!(expr.span, "loop scope error: {}", err));
977
978 self.cont_ln.get(&sc).cloned().unwrap_or_else(|| {
981 span_bug!(expr.span, "continue to unknown label");
984 })
985 }
986
987 hir::ExprKind::Assign(ref l, ref r, _) => {
988 let succ = self.write_place(l, succ, ACC_WRITE);
991 let succ = self.propagate_through_place_components(l, succ);
992 self.propagate_through_expr(r, succ)
993 }
994
995 hir::ExprKind::AssignOp(_, ref l, ref r) => {
996 if self.typeck_results.is_method_call(expr) {
998 let succ = self.propagate_through_expr(l, succ);
999 self.propagate_through_expr(r, succ)
1000 } else {
1001 let succ = self.write_place(l, succ, ACC_WRITE | ACC_READ);
1004 let succ = self.propagate_through_expr(r, succ);
1005 self.propagate_through_place_components(l, succ)
1006 }
1007 }
1008
1009 hir::ExprKind::Array(exprs) => self.propagate_through_exprs(exprs, succ),
1011
1012 hir::ExprKind::Struct(_, fields, ref with_expr) => {
1013 let succ = match with_expr {
1014 hir::StructTailExpr::Base(base) => {
1015 self.propagate_through_opt_expr(Some(base), succ)
1016 }
1017 hir::StructTailExpr::None | hir::StructTailExpr::DefaultFields(_) => succ,
1018 };
1019 fields
1020 .iter()
1021 .rev()
1022 .fold(succ, |succ, field| self.propagate_through_expr(field.expr, succ))
1023 }
1024
1025 hir::ExprKind::Call(ref f, args) => {
1026 let is_ctor = |f: &Expr<'_>| matches!(f.kind, hir::ExprKind::Path(hir::QPath::Resolved(_, path)) if matches!(path.res, rustc_hir::def::Res::Def(rustc_hir::def::DefKind::Ctor(_, _), _)));
1027 let succ =
1028 if !is_ctor(f) { self.check_is_ty_uninhabited(expr, succ) } else { succ };
1029
1030 let succ = self.propagate_through_exprs(args, succ);
1031 self.propagate_through_expr(f, succ)
1032 }
1033
1034 hir::ExprKind::MethodCall(.., receiver, args, _) => {
1035 let succ = self.check_is_ty_uninhabited(expr, succ);
1036 let succ = self.propagate_through_exprs(args, succ);
1037 self.propagate_through_expr(receiver, succ)
1038 }
1039
1040 hir::ExprKind::Use(expr, _) => {
1041 let succ = self.check_is_ty_uninhabited(expr, succ);
1042 self.propagate_through_expr(expr, succ)
1043 }
1044
1045 hir::ExprKind::Tup(exprs) => self.propagate_through_exprs(exprs, succ),
1046
1047 hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => {
1048 let r_succ = self.propagate_through_expr(r, succ);
1049
1050 let ln = self.live_node(expr.hir_id, expr.span);
1051 self.init_from_succ(ln, succ);
1052 self.merge_from_succ(ln, r_succ);
1053
1054 self.propagate_through_expr(l, ln)
1055 }
1056
1057 hir::ExprKind::Index(ref l, ref r, _) | hir::ExprKind::Binary(_, ref l, ref r) => {
1058 let r_succ = self.propagate_through_expr(r, succ);
1059 self.propagate_through_expr(l, r_succ)
1060 }
1061
1062 hir::ExprKind::AddrOf(_, _, ref e)
1063 | hir::ExprKind::Cast(ref e, _)
1064 | hir::ExprKind::Type(ref e, _)
1065 | hir::ExprKind::UnsafeBinderCast(_, ref e, _)
1066 | hir::ExprKind::DropTemps(ref e)
1067 | hir::ExprKind::Unary(_, ref e)
1068 | hir::ExprKind::Repeat(ref e, _) => self.propagate_through_expr(e, succ),
1069
1070 hir::ExprKind::InlineAsm(asm) => {
1071 let mut succ =
1086 if self.typeck_results.expr_ty(expr).is_never() { self.exit_ln } else { succ };
1087
1088 if asm.contains_label() {
1090 let ln = self.live_node(expr.hir_id, expr.span);
1091 self.init_from_succ(ln, succ);
1092 for (op, _op_sp) in asm.operands.iter().rev() {
1093 match op {
1094 hir::InlineAsmOperand::Label { block } => {
1095 let label_ln = self.propagate_through_block(block, succ);
1096 self.merge_from_succ(ln, label_ln);
1097 }
1098 hir::InlineAsmOperand::In { .. }
1099 | hir::InlineAsmOperand::Out { .. }
1100 | hir::InlineAsmOperand::InOut { .. }
1101 | hir::InlineAsmOperand::SplitInOut { .. }
1102 | hir::InlineAsmOperand::Const { .. }
1103 | hir::InlineAsmOperand::SymFn { .. }
1104 | hir::InlineAsmOperand::SymStatic { .. } => {}
1105 }
1106 }
1107 succ = ln;
1108 }
1109
1110 for (op, _op_sp) in asm.operands.iter().rev() {
1112 match op {
1113 hir::InlineAsmOperand::In { .. }
1114 | hir::InlineAsmOperand::Const { .. }
1115 | hir::InlineAsmOperand::SymFn { .. }
1116 | hir::InlineAsmOperand::SymStatic { .. }
1117 | hir::InlineAsmOperand::Label { .. } => {}
1118 hir::InlineAsmOperand::Out { expr, .. } => {
1119 if let Some(expr) = expr {
1120 succ = self.write_place(expr, succ, ACC_WRITE);
1121 }
1122 }
1123 hir::InlineAsmOperand::InOut { expr, .. } => {
1124 succ = self.write_place(expr, succ, ACC_READ | ACC_WRITE | ACC_USE);
1125 }
1126 hir::InlineAsmOperand::SplitInOut { out_expr, .. } => {
1127 if let Some(expr) = out_expr {
1128 succ = self.write_place(expr, succ, ACC_WRITE);
1129 }
1130 }
1131 }
1132 }
1133
1134 for (op, _op_sp) in asm.operands.iter().rev() {
1136 match op {
1137 hir::InlineAsmOperand::In { expr, .. } => {
1138 succ = self.propagate_through_expr(expr, succ)
1139 }
1140 hir::InlineAsmOperand::Out { expr, .. } => {
1141 if let Some(expr) = expr {
1142 succ = self.propagate_through_place_components(expr, succ);
1143 }
1144 }
1145 hir::InlineAsmOperand::InOut { expr, .. } => {
1146 succ = self.propagate_through_place_components(expr, succ);
1147 }
1148 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1149 if let Some(expr) = out_expr {
1150 succ = self.propagate_through_place_components(expr, succ);
1151 }
1152 succ = self.propagate_through_expr(in_expr, succ);
1153 }
1154 hir::InlineAsmOperand::Const { .. }
1155 | hir::InlineAsmOperand::SymFn { .. }
1156 | hir::InlineAsmOperand::SymStatic { .. }
1157 | hir::InlineAsmOperand::Label { .. } => {}
1158 }
1159 }
1160 succ
1161 }
1162
1163 hir::ExprKind::Lit(..)
1164 | hir::ExprKind::ConstBlock(..)
1165 | hir::ExprKind::Err(_)
1166 | hir::ExprKind::Path(hir::QPath::TypeRelative(..))
1167 | hir::ExprKind::Path(hir::QPath::LangItem(..))
1168 | hir::ExprKind::OffsetOf(..) => succ,
1169
1170 hir::ExprKind::Block(ref blk, _) => self.propagate_through_block(blk, succ),
1173 }
1174 }
1175
1176 fn propagate_through_place_components(&mut self, expr: &Expr<'_>, succ: LiveNode) -> LiveNode {
1177 match expr.kind {
1227 hir::ExprKind::Path(_) => succ,
1228 hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(e, succ),
1229 _ => self.propagate_through_expr(expr, succ),
1230 }
1231 }
1232
1233 fn write_place(&mut self, expr: &Expr<'_>, succ: LiveNode, acc: u32) -> LiveNode {
1235 match expr.kind {
1236 hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => {
1237 self.access_path(expr.hir_id, path, succ, acc)
1238 }
1239
1240 _ => succ,
1245 }
1246 }
1247
1248 fn access_var(
1249 &mut self,
1250 hir_id: HirId,
1251 var_hid: HirId,
1252 succ: LiveNode,
1253 acc: u32,
1254 span: Span,
1255 ) -> LiveNode {
1256 let ln = self.live_node(hir_id, span);
1257 if acc != 0 {
1258 self.init_from_succ(ln, succ);
1259 let var = self.variable(var_hid, span);
1260 self.acc(ln, var, acc);
1261 }
1262 ln
1263 }
1264
1265 fn access_path(
1266 &mut self,
1267 hir_id: HirId,
1268 path: &hir::Path<'_>,
1269 succ: LiveNode,
1270 acc: u32,
1271 ) -> LiveNode {
1272 match path.res {
1273 Res::Local(hid) => self.access_var(hir_id, hid, succ, acc, path.span),
1274 _ => succ,
1275 }
1276 }
1277
1278 fn propagate_through_loop(
1279 &mut self,
1280 expr: &Expr<'_>,
1281 body: &hir::Block<'_>,
1282 succ: LiveNode,
1283 ) -> LiveNode {
1284 let ln = self.live_node(expr.hir_id, expr.span);
1298 self.init_empty(ln, succ);
1299 debug!("propagate_through_loop: using id for loop body {} {:?}", expr.hir_id, body);
1300
1301 self.break_ln.insert(expr.hir_id, succ);
1302
1303 self.cont_ln.insert(expr.hir_id, ln);
1304
1305 let body_ln = self.propagate_through_block(body, ln);
1306
1307 while self.merge_from_succ(ln, body_ln) {
1309 assert_eq!(body_ln, self.propagate_through_block(body, ln));
1310 }
1311
1312 ln
1313 }
1314
1315 fn check_is_ty_uninhabited(&mut self, expr: &Expr<'_>, succ: LiveNode) -> LiveNode {
1316 let ty = self.typeck_results.expr_ty(expr);
1317 let m = self.ir.tcx.parent_module(expr.hir_id).to_def_id();
1318 if ty.is_inhabited_from(self.ir.tcx, m, self.typing_env) {
1319 return succ;
1320 }
1321 match self.ir.lnks[succ] {
1322 LiveNodeKind::ExprNode(succ_span, succ_id) => {
1323 self.warn_about_unreachable(expr.span, ty, succ_span, succ_id, "expression");
1324 }
1325 LiveNodeKind::VarDefNode(succ_span, succ_id) => {
1326 self.warn_about_unreachable(expr.span, ty, succ_span, succ_id, "definition");
1327 }
1328 _ => {}
1329 };
1330 self.exit_ln
1331 }
1332
1333 fn warn_about_unreachable<'desc>(
1334 &mut self,
1335 orig_span: Span,
1336 orig_ty: Ty<'tcx>,
1337 expr_span: Span,
1338 expr_id: HirId,
1339 descr: &'desc str,
1340 ) {
1341 if !orig_ty.is_never() {
1342 self.ir.tcx.emit_node_span_lint(
1353 lint::builtin::UNREACHABLE_CODE,
1354 expr_id,
1355 expr_span,
1356 errors::UnreachableDueToUninhabited {
1357 expr: expr_span,
1358 orig: orig_span,
1359 descr,
1360 ty: orig_ty,
1361 },
1362 );
1363 }
1364 }
1365}
1366
1367impl<'a, 'tcx> Visitor<'tcx> for Liveness<'a, 'tcx> {
1371 fn visit_local(&mut self, local: &'tcx hir::LetStmt<'tcx>) {
1372 self.check_unused_vars_in_pat(local.pat, None, None, |spans, hir_id, ln, var| {
1373 if local.init.is_some() {
1374 self.warn_about_dead_assign(spans, hir_id, ln, var, None);
1375 }
1376 });
1377
1378 intravisit::walk_local(self, local);
1379 }
1380
1381 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
1382 check_expr(self, ex);
1383 intravisit::walk_expr(self, ex);
1384 }
1385
1386 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1387 self.check_unused_vars_in_pat(arm.pat, None, None, |_, _, _, _| {});
1388 intravisit::walk_arm(self, arm);
1389 }
1390}
1391
1392fn check_expr<'tcx>(this: &mut Liveness<'_, 'tcx>, expr: &'tcx Expr<'tcx>) {
1393 match expr.kind {
1394 hir::ExprKind::Assign(ref l, ..) => {
1395 this.check_place(l);
1396 }
1397
1398 hir::ExprKind::AssignOp(_, ref l, _) => {
1399 if !this.typeck_results.is_method_call(expr) {
1400 this.check_place(l);
1401 }
1402 }
1403
1404 hir::ExprKind::InlineAsm(asm) => {
1405 for (op, _op_sp) in asm.operands {
1406 match op {
1407 hir::InlineAsmOperand::Out { expr, .. } => {
1408 if let Some(expr) = expr {
1409 this.check_place(expr);
1410 }
1411 }
1412 hir::InlineAsmOperand::InOut { expr, .. } => {
1413 this.check_place(expr);
1414 }
1415 hir::InlineAsmOperand::SplitInOut { out_expr, .. } => {
1416 if let Some(out_expr) = out_expr {
1417 this.check_place(out_expr);
1418 }
1419 }
1420 _ => {}
1421 }
1422 }
1423 }
1424
1425 hir::ExprKind::Let(let_expr) => {
1426 this.check_unused_vars_in_pat(let_expr.pat, None, None, |_, _, _, _| {});
1427 }
1428
1429 hir::ExprKind::Call(..)
1431 | hir::ExprKind::MethodCall(..)
1432 | hir::ExprKind::Use(..)
1433 | hir::ExprKind::Match(..)
1434 | hir::ExprKind::Loop(..)
1435 | hir::ExprKind::Index(..)
1436 | hir::ExprKind::Field(..)
1437 | hir::ExprKind::Array(..)
1438 | hir::ExprKind::Tup(..)
1439 | hir::ExprKind::Binary(..)
1440 | hir::ExprKind::Cast(..)
1441 | hir::ExprKind::If(..)
1442 | hir::ExprKind::DropTemps(..)
1443 | hir::ExprKind::Unary(..)
1444 | hir::ExprKind::Ret(..)
1445 | hir::ExprKind::Become(..)
1446 | hir::ExprKind::Break(..)
1447 | hir::ExprKind::Continue(..)
1448 | hir::ExprKind::Lit(_)
1449 | hir::ExprKind::ConstBlock(..)
1450 | hir::ExprKind::Block(..)
1451 | hir::ExprKind::AddrOf(..)
1452 | hir::ExprKind::OffsetOf(..)
1453 | hir::ExprKind::Struct(..)
1454 | hir::ExprKind::Repeat(..)
1455 | hir::ExprKind::Closure { .. }
1456 | hir::ExprKind::Path(_)
1457 | hir::ExprKind::Yield(..)
1458 | hir::ExprKind::Type(..)
1459 | hir::ExprKind::UnsafeBinderCast(..)
1460 | hir::ExprKind::Err(_) => {}
1461 }
1462}
1463
1464impl<'tcx> Liveness<'_, 'tcx> {
1465 fn check_place(&mut self, expr: &'tcx Expr<'tcx>) {
1466 match expr.kind {
1467 hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => {
1468 if let Res::Local(var_hid) = path.res {
1469 let ln = self.live_node(expr.hir_id, expr.span);
1474 let var = self.variable(var_hid, expr.span);
1475 let sugg = self.annotate_mut_binding_to_immutable_binding(var_hid, expr);
1476 self.warn_about_dead_assign(vec![expr.span], expr.hir_id, ln, var, sugg);
1477 }
1478 }
1479 _ => {
1480 intravisit::walk_expr(self, expr);
1483 }
1484 }
1485 }
1486
1487 fn should_warn(&self, var: Variable) -> Option<String> {
1488 let name = self.ir.variable_name(var);
1489 let name = name.as_str();
1490 if name.as_bytes()[0] == b'_' {
1491 return None;
1492 }
1493 Some(name.to_owned())
1494 }
1495
1496 fn warn_about_unused_upvars(&self, entry_ln: LiveNode) {
1497 let Some(closure_min_captures) = self.closure_min_captures else {
1498 return;
1499 };
1500
1501 for (&var_hir_id, min_capture_list) in closure_min_captures {
1503 for captured_place in min_capture_list {
1504 match captured_place.info.capture_kind {
1505 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
1506 ty::UpvarCapture::ByRef(..) => continue,
1507 };
1508 let span = captured_place.get_capture_kind_span(self.ir.tcx);
1509 let var = self.variable(var_hir_id, span);
1510 if self.used_on_entry(entry_ln, var) {
1511 if !self.live_on_entry(entry_ln, var) {
1512 if let Some(name) = self.should_warn(var) {
1513 self.ir.tcx.emit_node_span_lint(
1514 lint::builtin::UNUSED_ASSIGNMENTS,
1515 var_hir_id,
1516 vec![span],
1517 errors::UnusedCaptureMaybeCaptureRef { name },
1518 );
1519 }
1520 }
1521 } else if let Some(name) = self.should_warn(var) {
1522 self.ir.tcx.emit_node_span_lint(
1523 lint::builtin::UNUSED_VARIABLES,
1524 var_hir_id,
1525 vec![span],
1526 errors::UnusedVarMaybeCaptureRef { name },
1527 );
1528 }
1529 }
1530 }
1531 }
1532
1533 fn warn_about_unused_args(&self, body: &hir::Body<'_>, entry_ln: LiveNode) {
1534 if let Some(intrinsic) = self.ir.tcx.intrinsic(self.ir.tcx.hir_body_owner_def_id(body.id()))
1535 {
1536 if intrinsic.must_be_overridden {
1537 return;
1538 }
1539 }
1540
1541 for p in body.params {
1542 self.check_unused_vars_in_pat(
1543 p.pat,
1544 Some(entry_ln),
1545 Some(body),
1546 |spans, hir_id, ln, var| {
1547 if !self.live_on_entry(ln, var)
1548 && let Some(name) = self.should_warn(var)
1549 {
1550 self.ir.tcx.emit_node_span_lint(
1551 lint::builtin::UNUSED_ASSIGNMENTS,
1552 hir_id,
1553 spans,
1554 errors::UnusedAssignPassed { name },
1555 );
1556 }
1557 },
1558 );
1559 }
1560 }
1561
1562 fn check_unused_vars_in_pat(
1563 &self,
1564 pat: &hir::Pat<'_>,
1565 entry_ln: Option<LiveNode>,
1566 opt_body: Option<&hir::Body<'_>>,
1567 on_used_on_entry: impl Fn(Vec<Span>, HirId, LiveNode, Variable),
1568 ) {
1569 let mut vars: FxIndexMap<Symbol, (LiveNode, Variable, Vec<(HirId, Span, Span)>)> =
1574 <_>::default();
1575
1576 pat.each_binding(|_, hir_id, pat_sp, ident| {
1577 let ln = entry_ln.unwrap_or_else(|| self.live_node(hir_id, pat_sp));
1578 let var = self.variable(hir_id, ident.span);
1579 let id_and_sp = (hir_id, pat_sp, ident.span);
1580 vars.entry(self.ir.variable_name(var))
1581 .and_modify(|(.., hir_ids_and_spans)| hir_ids_and_spans.push(id_and_sp))
1582 .or_insert_with(|| (ln, var, vec![id_and_sp]));
1583 });
1584
1585 let can_remove = match pat.kind {
1586 hir::PatKind::Struct(_, fields, true) => {
1587 fields.iter().all(|f| f.is_shorthand)
1589 }
1590 _ => false,
1591 };
1592
1593 for (_, (ln, var, hir_ids_and_spans)) in vars {
1594 if self.used_on_entry(ln, var) {
1595 let id = hir_ids_and_spans[0].0;
1596 let spans =
1597 hir_ids_and_spans.into_iter().map(|(_, _, ident_span)| ident_span).collect();
1598 on_used_on_entry(spans, id, ln, var);
1599 } else {
1600 self.report_unused(hir_ids_and_spans, ln, var, can_remove, pat, opt_body);
1601 }
1602 }
1603 }
1604
1605 fn annotate_mut_binding_to_immutable_binding(
1624 &self,
1625 var_hid: HirId,
1626 expr: &'tcx Expr<'tcx>,
1627 ) -> Option<errors::UnusedAssignSuggestion> {
1628 if let hir::Node::Expr(parent) = self.ir.tcx.parent_hir_node(expr.hir_id)
1629 && let hir::ExprKind::Assign(_, rhs, _) = parent.kind
1630 && let hir::ExprKind::AddrOf(borrow_kind, _mut, inner) = rhs.kind
1631 && let hir::BorrowKind::Ref = borrow_kind
1632 && let hir::Node::Pat(pat) = self.ir.tcx.hir_node(var_hid)
1633 && let hir::Node::Param(hir::Param { ty_span, .. }) =
1634 self.ir.tcx.parent_hir_node(pat.hir_id)
1635 && let item_id = self.ir.tcx.hir_get_parent_item(pat.hir_id)
1636 && let item = self.ir.tcx.hir_owner_node(item_id)
1637 && let Some(fn_decl) = item.fn_decl()
1638 && let hir::PatKind::Binding(hir::BindingMode::MUT, _hir_id, ident, _) = pat.kind
1639 && let Some((lt, mut_ty)) = fn_decl
1640 .inputs
1641 .iter()
1642 .filter_map(|ty| {
1643 if ty.span == *ty_span
1644 && let hir::TyKind::Ref(lt, mut_ty) = ty.kind
1645 {
1646 Some((lt, mut_ty))
1647 } else {
1648 None
1649 }
1650 })
1651 .next()
1652 {
1653 let ty_span = if mut_ty.mutbl.is_mut() {
1654 None
1656 } else {
1657 Some(mut_ty.ty.span.shrink_to_lo())
1659 };
1660 let pre = if lt.ident.span.is_empty() { "" } else { " " };
1661 Some(errors::UnusedAssignSuggestion {
1662 ty_span,
1663 pre,
1664 ty_ref_span: pat.span.until(ident.span),
1665 ident_span: expr.span.shrink_to_lo(),
1666 expr_ref_span: rhs.span.until(inner.span),
1667 })
1668 } else {
1669 None
1670 }
1671 }
1672
1673 #[instrument(skip(self), level = "INFO")]
1674 fn report_unused(
1675 &self,
1676 hir_ids_and_spans: Vec<(HirId, Span, Span)>,
1677 ln: LiveNode,
1678 var: Variable,
1679 can_remove: bool,
1680 pat: &hir::Pat<'_>,
1681 opt_body: Option<&hir::Body<'_>>,
1682 ) {
1683 let first_hir_id = hir_ids_and_spans[0].0;
1684 if let Some(name) = self.should_warn(var).filter(|name| name != "self") {
1685 let is_assigned =
1689 if ln == self.exit_ln { false } else { self.assigned_on_exit(ln, var) };
1690
1691 if is_assigned {
1692 self.ir.tcx.emit_node_span_lint(
1693 lint::builtin::UNUSED_VARIABLES,
1694 first_hir_id,
1695 hir_ids_and_spans
1696 .into_iter()
1697 .map(|(_, _, ident_span)| ident_span)
1698 .collect::<Vec<_>>(),
1699 errors::UnusedVarAssignedOnly { name },
1700 )
1701 } else if can_remove {
1702 let spans = hir_ids_and_spans
1703 .iter()
1704 .map(|(_, pat_span, _)| {
1705 let span = self
1706 .ir
1707 .tcx
1708 .sess
1709 .source_map()
1710 .span_extend_to_next_char(*pat_span, ',', true);
1711 span.with_hi(BytePos(span.hi().0 + 1))
1712 })
1713 .collect();
1714 self.ir.tcx.emit_node_span_lint(
1715 lint::builtin::UNUSED_VARIABLES,
1716 first_hir_id,
1717 hir_ids_and_spans.iter().map(|(_, pat_span, _)| *pat_span).collect::<Vec<_>>(),
1718 errors::UnusedVarRemoveField {
1719 name,
1720 sugg: errors::UnusedVarRemoveFieldSugg { spans },
1721 },
1722 );
1723 } else {
1724 let (shorthands, non_shorthands): (Vec<_>, Vec<_>) =
1725 hir_ids_and_spans.iter().copied().partition(|(hir_id, _, ident_span)| {
1726 let var = self.variable(*hir_id, *ident_span);
1727 self.ir.variable_is_shorthand(var)
1728 });
1729
1730 if !shorthands.is_empty() {
1734 let shorthands =
1735 shorthands.into_iter().map(|(_, pat_span, _)| pat_span).collect();
1736 let non_shorthands =
1737 non_shorthands.into_iter().map(|(_, pat_span, _)| pat_span).collect();
1738
1739 self.ir.tcx.emit_node_span_lint(
1740 lint::builtin::UNUSED_VARIABLES,
1741 first_hir_id,
1742 hir_ids_and_spans
1743 .iter()
1744 .map(|(_, pat_span, _)| *pat_span)
1745 .collect::<Vec<_>>(),
1746 errors::UnusedVarTryIgnore {
1747 name: name.clone(),
1748 sugg: errors::UnusedVarTryIgnoreSugg {
1749 shorthands,
1750 non_shorthands,
1751 name,
1752 },
1753 },
1754 );
1755 } else {
1756 let from_macro = non_shorthands
1759 .iter()
1760 .find(|(_, pat_span, ident_span)| {
1761 !pat_span.eq_ctxt(*ident_span) && pat_span.from_expansion()
1762 })
1763 .map(|(_, pat_span, _)| *pat_span);
1764 let non_shorthands = non_shorthands
1765 .into_iter()
1766 .map(|(_, _, ident_span)| ident_span)
1767 .collect::<Vec<_>>();
1768
1769 let suggestions = self.string_interp_suggestions(&name, opt_body);
1770 let sugg = if let Some(span) = from_macro {
1771 errors::UnusedVariableSugg::NoSugg { span, name: name.clone() }
1772 } else {
1773 errors::UnusedVariableSugg::TryPrefixSugg {
1774 spans: non_shorthands,
1775 name: name.clone(),
1776 }
1777 };
1778
1779 self.ir.tcx.emit_node_span_lint(
1780 lint::builtin::UNUSED_VARIABLES,
1781 first_hir_id,
1782 hir_ids_and_spans
1783 .iter()
1784 .map(|(_, _, ident_span)| *ident_span)
1785 .collect::<Vec<_>>(),
1786 errors::UnusedVariableTryPrefix {
1787 label: if !suggestions.is_empty() { Some(pat.span) } else { None },
1788 name,
1789 sugg,
1790 string_interp: suggestions,
1791 },
1792 );
1793 }
1794 }
1795 }
1796 }
1797
1798 fn string_interp_suggestions(
1799 &self,
1800 name: &str,
1801 opt_body: Option<&hir::Body<'_>>,
1802 ) -> Vec<errors::UnusedVariableStringInterp> {
1803 let mut suggs = Vec::new();
1804 let Some(opt_body) = opt_body else {
1805 return suggs;
1806 };
1807 let mut visitor = CollectLitsVisitor { lit_exprs: vec![] };
1808 intravisit::walk_body(&mut visitor, opt_body);
1809 for lit_expr in visitor.lit_exprs {
1810 let hir::ExprKind::Lit(litx) = &lit_expr.kind else { continue };
1811 let rustc_ast::LitKind::Str(syb, _) = litx.node else {
1812 continue;
1813 };
1814 let name_str: &str = syb.as_str();
1815 let name_pa = format!("{{{name}}}");
1816 if name_str.contains(&name_pa) {
1817 suggs.push(errors::UnusedVariableStringInterp {
1818 lit: lit_expr.span,
1819 lo: lit_expr.span.shrink_to_lo(),
1820 hi: lit_expr.span.shrink_to_hi(),
1821 });
1822 }
1823 }
1824 suggs
1825 }
1826
1827 fn warn_about_dead_assign(
1828 &self,
1829 spans: Vec<Span>,
1830 hir_id: HirId,
1831 ln: LiveNode,
1832 var: Variable,
1833 suggestion: Option<errors::UnusedAssignSuggestion>,
1834 ) {
1835 if !self.live_on_exit(ln, var)
1836 && let Some(name) = self.should_warn(var)
1837 {
1838 let help = suggestion.is_none();
1839 self.ir.tcx.emit_node_span_lint(
1840 lint::builtin::UNUSED_ASSIGNMENTS,
1841 hir_id,
1842 spans,
1843 errors::UnusedAssign { name, suggestion, help },
1844 );
1845 }
1846 }
1847}