1 //! A different sort of visitor for walking fn bodies. Unlike the
2 //! normal visitor, which just walks the entire body in one shot, the
3 //! `ExprUseVisitor` determines how expressions are being used.
5 pub use self::ConsumeMode::*;
7 // Export these here so that Clippy can use them.
8 pub use rustc_middle::hir::place::{PlaceBase, PlaceWithHirId, Projection};
11 use rustc_hir::def::Res;
12 use rustc_hir::def_id::LocalDefId;
13 use rustc_hir::PatKind;
14 use rustc_index::vec::Idx;
15 use rustc_infer::infer::InferCtxt;
16 use rustc_middle::hir::place::ProjectionKind;
17 use rustc_middle::ty::{self, adjustment, TyCtxt};
19 use rustc_target::abi::VariantIdx;
21 use crate::mem_categorization as mc;
23 ///////////////////////////////////////////////////////////////////////////
26 /// This trait defines the callbacks you can expect to receive when
27 /// employing the ExprUseVisitor.
28 pub trait Delegate<'tcx> {
29 // The value found at `place` is either copied or moved, depending
30 // on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
32 // The parameter `diag_expr_id` indicates the HIR id that ought to be used for
33 // diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
34 // id will be the id of the expression `expr` but the place itself will have
35 // the id of the binding in the pattern `pat`.
38 place_with_id: &PlaceWithHirId<'tcx>,
39 diag_expr_id: hir::HirId,
43 // The value found at `place` is being borrowed with kind `bk`.
44 // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
47 place_with_id: &PlaceWithHirId<'tcx>,
48 diag_expr_id: hir::HirId,
52 // The path at `assignee_place` is being assigned to.
53 // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
54 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
57 #[derive(Copy, Clone, PartialEq, Debug)]
58 pub enum ConsumeMode {
59 Copy, // reference to x where x has a type that copies
60 Move, // reference to x where x has a type that moves
63 #[derive(Copy, Clone, PartialEq, Debug)]
67 WriteAndRead, // x += y
70 ///////////////////////////////////////////////////////////////////////////
71 // The ExprUseVisitor type
73 // This is the code that actually walks the tree.
74 pub struct ExprUseVisitor<'a, 'tcx> {
75 mc: mc::MemCategorizationContext<'a, 'tcx>,
76 body_owner: LocalDefId,
77 delegate: &'a mut dyn Delegate<'tcx>,
80 // If the MC results in an error, it's because the type check
81 // failed (or will fail, when the error is uncovered and reported
82 // during writeback). In this case, we just ignore this part of the
85 // Note that this macro appears similar to try!(), but, unlike try!(),
86 // it does not propagate the error.
87 macro_rules! return_if_err {
92 debug!("mc reported err");
99 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
100 /// Creates the ExprUseVisitor, configuring it with the various options provided:
102 /// - `delegate` -- who receives the callbacks
103 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
104 /// - `typeck_results` --- typeck results for the code being analyzed
106 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
107 infcx: &'a InferCtxt<'a, 'tcx>,
108 body_owner: LocalDefId,
109 param_env: ty::ParamEnv<'tcx>,
110 typeck_results: &'a ty::TypeckResults<'tcx>,
113 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
119 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
120 debug!("consume_body(body={:?})", body);
122 for param in body.params {
123 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
124 debug!("consume_body: param_ty = {:?}", param_ty);
126 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
128 self.walk_irrefutable_pat(¶m_place, ¶m.pat);
131 self.consume_expr(&body.value);
134 fn tcx(&self) -> TyCtxt<'tcx> {
138 fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
139 debug!("delegate_consume(place_with_id={:?})", place_with_id);
141 let mode = copy_or_move(&self.mc, place_with_id);
142 self.delegate.consume(place_with_id, diag_expr_id, mode);
145 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
147 self.consume_expr(&expr);
151 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
152 debug!("consume_expr(expr={:?})", expr);
154 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
155 self.delegate_consume(&place_with_id, place_with_id.hir_id);
156 self.walk_expr(expr);
159 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
160 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
161 self.delegate.mutate(&place_with_id, place_with_id.hir_id);
162 self.walk_expr(expr);
165 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
166 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
168 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
169 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
174 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
178 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
179 debug!("walk_expr(expr={:?})", expr);
181 self.walk_adjustment(expr);
184 hir::ExprKind::Path(_) => {}
186 hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
188 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
190 self.select_from_expr(base);
193 hir::ExprKind::Field(ref base, _) => {
195 self.select_from_expr(base);
198 hir::ExprKind::Index(ref lhs, ref rhs) => {
200 self.select_from_expr(lhs);
201 self.consume_expr(rhs);
204 hir::ExprKind::Call(ref callee, ref args) => {
206 self.consume_expr(callee);
207 self.consume_exprs(args);
210 hir::ExprKind::MethodCall(.., ref args, _) => {
212 self.consume_exprs(args);
215 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
216 self.walk_struct_expr(fields, opt_with);
219 hir::ExprKind::Tup(ref exprs) => {
220 self.consume_exprs(exprs);
223 hir::ExprKind::Match(ref discr, arms, _) => {
224 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
225 self.borrow_expr(&discr, ty::ImmBorrow);
227 // treatment of the discriminant is handled while walking the arms.
229 self.walk_arm(&discr_place, arm);
233 hir::ExprKind::Array(ref exprs) => {
234 self.consume_exprs(exprs);
237 hir::ExprKind::AddrOf(_, m, ref base) => {
239 // make sure that the thing we are pointing out stays valid
240 // for the lifetime `scope_r` of the resulting ptr:
241 let bk = ty::BorrowKind::from_mutbl(m);
242 self.borrow_expr(&base, bk);
245 hir::ExprKind::InlineAsm(ref asm) => {
246 for op in asm.operands {
248 hir::InlineAsmOperand::In { expr, .. }
249 | hir::InlineAsmOperand::Const { expr, .. }
250 | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
251 hir::InlineAsmOperand::Out { expr, .. } => {
252 if let Some(expr) = expr {
253 self.mutate_expr(expr);
256 hir::InlineAsmOperand::InOut { expr, .. } => {
257 self.mutate_expr(expr);
259 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
260 self.consume_expr(in_expr);
261 if let Some(out_expr) = out_expr {
262 self.mutate_expr(out_expr);
269 hir::ExprKind::LlvmInlineAsm(ref ia) => {
270 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
272 self.consume_expr(output);
274 self.mutate_expr(output);
277 self.consume_exprs(&ia.inputs_exprs);
280 hir::ExprKind::Continue(..)
281 | hir::ExprKind::Lit(..)
282 | hir::ExprKind::ConstBlock(..)
283 | hir::ExprKind::Err => {}
285 hir::ExprKind::Loop(ref blk, _, _) => {
286 self.walk_block(blk);
289 hir::ExprKind::Unary(_, ref lhs) => {
290 self.consume_expr(lhs);
293 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
294 self.consume_expr(lhs);
295 self.consume_expr(rhs);
298 hir::ExprKind::Block(ref blk, _) => {
299 self.walk_block(blk);
302 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
303 if let Some(ref expr) = *opt_expr {
304 self.consume_expr(expr);
308 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
309 self.mutate_expr(lhs);
310 self.consume_expr(rhs);
313 hir::ExprKind::Cast(ref base, _) => {
314 self.consume_expr(base);
317 hir::ExprKind::DropTemps(ref expr) => {
318 self.consume_expr(expr);
321 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
322 if self.mc.typeck_results.is_method_call(expr) {
323 self.consume_expr(lhs);
325 self.mutate_expr(lhs);
327 self.consume_expr(rhs);
330 hir::ExprKind::Repeat(ref base, _) => {
331 self.consume_expr(base);
334 hir::ExprKind::Closure(..) => {
335 self.walk_captures(expr);
338 hir::ExprKind::Box(ref base) => {
339 self.consume_expr(base);
342 hir::ExprKind::Yield(ref value, _) => {
343 self.consume_expr(value);
348 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
350 hir::StmtKind::Local(ref local) => {
351 self.walk_local(&local);
354 hir::StmtKind::Item(_) => {
355 // We don't visit nested items in this visitor,
356 // only the fn body we were given.
359 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
360 self.consume_expr(&expr);
365 fn walk_local(&mut self, local: &hir::Local<'_>) {
366 if let Some(ref expr) = local.init {
367 // Variable declarations with
368 // initializers are considered
369 // "assigns", which is handled by
371 self.walk_expr(&expr);
372 let init_place = return_if_err!(self.mc.cat_expr(&expr));
373 self.walk_irrefutable_pat(&init_place, &local.pat);
377 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
378 /// depending on its type.
379 fn walk_block(&mut self, blk: &hir::Block<'_>) {
380 debug!("walk_block(blk.hir_id={})", blk.hir_id);
382 for stmt in blk.stmts {
383 self.walk_stmt(stmt);
386 if let Some(ref tail_expr) = blk.expr {
387 self.consume_expr(&tail_expr);
393 fields: &[hir::Field<'_>],
394 opt_with: &Option<&'hir hir::Expr<'_>>,
396 // Consume the expressions supplying values for each field.
397 for field in fields {
398 self.consume_expr(&field.expr);
401 let with_expr = match *opt_with {
408 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
410 // Select just those fields of the `with`
411 // expression that will actually be used
412 match with_place.place.ty().kind() {
413 ty::Adt(adt, substs) if adt.is_struct() => {
414 // Consume those fields of the with expression that are needed.
415 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
416 let is_mentioned = fields.iter().any(|f| {
417 self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
420 let field_place = self.mc.cat_projection(
423 with_field.ty(self.tcx(), substs),
424 ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
426 self.delegate_consume(&field_place, field_place.hir_id);
431 // the base expression should always evaluate to a
432 // struct; however, when EUV is run during typeck, it
433 // may not. This will generate an error earlier in typeck,
434 // so we can just ignore it.
435 if !self.tcx().sess.has_errors() {
436 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
441 // walk the with expression so that complex expressions
442 // are properly handled.
443 self.walk_expr(with_expr);
446 // Invoke the appropriate delegate calls for anything that gets
447 // consumed or borrowed as part of the automatic adjustment
449 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
450 let adjustments = self.mc.typeck_results.expr_adjustments(expr);
451 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
452 for adjustment in adjustments {
453 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
454 match adjustment.kind {
455 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
456 // Creating a closure/fn-pointer or unsizing consumes
457 // the input and stores it into the resulting rvalue.
458 self.delegate_consume(&place_with_id, place_with_id.hir_id);
461 adjustment::Adjust::Deref(None) => {}
463 // Autoderefs for overloaded Deref calls in fact reference
464 // their receiver. That is, if we have `(*x)` where `x`
465 // is of type `Rc<T>`, then this in fact is equivalent to
466 // `x.deref()`. Since `deref()` is declared with `&self`,
467 // this is an autoref of `x`.
468 adjustment::Adjust::Deref(Some(ref deref)) => {
469 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
470 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
473 adjustment::Adjust::Borrow(ref autoref) => {
474 self.walk_autoref(expr, &place_with_id, autoref);
478 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
482 /// Walks the autoref `autoref` applied to the autoderef'd
483 /// `expr`. `base_place` is the mem-categorized form of `expr`
484 /// after all relevant autoderefs have occurred.
487 expr: &hir::Expr<'_>,
488 base_place: &PlaceWithHirId<'tcx>,
489 autoref: &adjustment::AutoBorrow<'tcx>,
492 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
493 expr.hir_id, base_place, autoref
497 adjustment::AutoBorrow::Ref(_, m) => {
498 self.delegate.borrow(
501 ty::BorrowKind::from_mutbl(m.into()),
505 adjustment::AutoBorrow::RawPtr(m) => {
506 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
508 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
513 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
514 self.walk_pat(discr_place, &arm.pat);
516 if let Some(hir::Guard::If(ref e)) = arm.guard {
520 self.consume_expr(&arm.body);
523 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
524 /// let binding, and *not* a match arm or nested pat.)
525 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
526 self.walk_pat(discr_place, pat);
529 /// The core driver for walking a pattern
530 fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
531 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
533 let tcx = self.tcx();
534 let ExprUseVisitor { ref mc, body_owner: _, ref mut delegate } = *self;
535 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
536 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
537 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
539 mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
541 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
543 // pat_ty: the type of the binding being produced.
544 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
545 debug!("walk_pat: pat_ty={:?}", pat_ty);
547 // Each match binding is effectively an assignment to the
548 // binding being produced.
549 let def = Res::Local(canonical_id);
550 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
551 delegate.mutate(binding_place, binding_place.hir_id);
554 // It is also a borrow or copy/move of the value being matched.
555 // In a cases of pattern like `let pat = upvar`, don't use the span
556 // of the pattern, as this just looks confusing, instead use the span
557 // of the discriminant.
559 ty::BindByReference(m) => {
560 let bk = ty::BorrowKind::from_mutbl(m);
561 delegate.borrow(place, discr_place.hir_id, bk);
563 ty::BindByValue(..) => {
564 let mode = copy_or_move(mc, &place);
565 debug!("walk_pat binding consuming pat");
566 delegate.consume(place, discr_place.hir_id, mode);
574 /// Walk closure captures but using `closure_caputes` instead
575 /// of `closure_min_captures`.
577 /// This is needed because clippy uses `ExprUseVisitor` after TypeckResults
578 /// are written back. We don't currently writeback min_captures to
580 fn walk_captures_closure_captures(&mut self, closure_expr: &hir::Expr<'_>) {
581 // FIXME(arora-aman): Remove this function once rust-lang/project-rfc-2229#18
583 debug!("walk_captures_closure_captures({:?}), ", closure_expr);
585 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id).to_def_id();
586 let cl_span = self.tcx().hir().span(closure_expr.hir_id);
588 let captures = &self.mc.typeck_results.closure_captures[&closure_def_id];
590 for (&var_id, &upvar_id) in captures {
591 let upvar_capture = self.mc.typeck_results.upvar_capture(upvar_id);
593 return_if_err!(self.cat_captured_var(closure_expr.hir_id, cl_span, var_id));
594 match upvar_capture {
595 ty::UpvarCapture::ByValue(_) => {
596 let mode = copy_or_move(&self.mc, &captured_place);
597 self.delegate.consume(&captured_place, captured_place.hir_id, mode);
599 ty::UpvarCapture::ByRef(upvar_borrow) => {
600 self.delegate.borrow(&captured_place, captured_place.hir_id, upvar_borrow.kind);
606 /// Handle the case where the current body contains a closure.
608 /// When the current body being handled is a closure, then we must make sure that
609 /// - The parent closure only captures Places from the nested closure that are not local to it.
611 /// In the following example the closures `c` only captures `p.x`` even though `incr`
612 /// is a capture of the nested closure
618 /// let nested = || p.x += incr;
622 /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
623 /// closure as the DefId.
624 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>) {
625 debug!("walk_captures({:?})", closure_expr);
627 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id).to_def_id();
628 let upvars = self.tcx().upvars_mentioned(self.body_owner);
630 // For purposes of this function, generator and closures are equivalent.
631 let body_owner_is_closure = match self.tcx().type_of(self.body_owner.to_def_id()).kind() {
632 ty::Closure(..) | ty::Generator(..) => true,
636 if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
638 for (var_hir_id, min_list) in min_captures.iter() {
639 if upvars.map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id)) {
640 // The nested closure might be capturing the current (enclosing) closure's local variables.
641 // We check if the root variable is ever mentioned within the enclosing closure, if not
642 // then for the current body (if it's a closure) these aren't captures, we will ignore them.
645 for captured_place in min_list {
646 let place = &captured_place.place;
647 let capture_info = captured_place.info;
649 let upvar_id = if body_owner_is_closure {
650 // Mark the place to be captured by the enclosing closure
651 ty::UpvarId::new(*var_hir_id, self.body_owner)
653 ty::UpvarId::new(*var_hir_id, closure_def_id.expect_local())
655 let place_with_id = PlaceWithHirId::new(
656 capture_info.expr_id.unwrap_or(closure_expr.hir_id),
658 PlaceBase::Upvar(upvar_id),
659 place.projections.clone(),
662 match capture_info.capture_kind {
663 ty::UpvarCapture::ByValue(_) => {
664 let mode = copy_or_move(&self.mc, &place_with_id);
665 self.delegate.consume(&place_with_id, place_with_id.hir_id, mode);
667 ty::UpvarCapture::ByRef(upvar_borrow) => {
668 self.delegate.borrow(
670 place_with_id.hir_id,
677 } else if self.mc.typeck_results.closure_captures.contains_key(&closure_def_id) {
678 // Handle the case where clippy calls ExprUseVisitor after
679 self.walk_captures_closure_captures(closure_expr)
685 closure_hir_id: hir::HirId,
688 ) -> mc::McResult<PlaceWithHirId<'tcx>> {
689 // Create the place for the variable being borrowed, from the
690 // perspective of the creator (parent) of the closure.
691 let var_ty = self.mc.node_ty(var_id)?;
692 self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
696 fn copy_or_move<'a, 'tcx>(
697 mc: &mc::MemCategorizationContext<'a, 'tcx>,
698 place_with_id: &PlaceWithHirId<'tcx>,
700 if !mc.type_is_copy_modulo_regions(
701 place_with_id.place.ty(),
702 mc.tcx().hir().span(place_with_id.hir_id),