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};
18 use rustc_target::abi::VariantIdx;
20 use crate::mem_categorization as mc;
22 ///////////////////////////////////////////////////////////////////////////
25 /// This trait defines the callbacks you can expect to receive when
26 /// employing the ExprUseVisitor.
27 pub trait Delegate<'tcx> {
28 // The value found at `place` is either copied or moved, depending
29 // on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
31 // The parameter `diag_expr_id` indicates the HIR id that ought to be used for
32 // diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
33 // id will be the id of the expression `expr` but the place itself will have
34 // the id of the binding in the pattern `pat`.
37 place_with_id: &PlaceWithHirId<'tcx>,
38 diag_expr_id: hir::HirId,
42 // The value found at `place` is being borrowed with kind `bk`.
43 // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
46 place_with_id: &PlaceWithHirId<'tcx>,
47 diag_expr_id: hir::HirId,
51 // The path at `assignee_place` is being assigned to.
52 // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
53 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
56 #[derive(Copy, Clone, PartialEq, Debug)]
57 pub enum ConsumeMode {
58 Copy, // reference to x where x has a type that copies
59 Move, // reference to x where x has a type that moves
62 #[derive(Copy, Clone, PartialEq, Debug)]
66 WriteAndRead, // x += y
69 ///////////////////////////////////////////////////////////////////////////
70 // The ExprUseVisitor type
72 // This is the code that actually walks the tree.
73 pub struct ExprUseVisitor<'a, 'tcx> {
74 mc: mc::MemCategorizationContext<'a, 'tcx>,
75 body_owner: LocalDefId,
76 delegate: &'a mut dyn Delegate<'tcx>,
79 // If the MC results in an error, it's because the type check
80 // failed (or will fail, when the error is uncovered and reported
81 // during writeback). In this case, we just ignore this part of the
84 // Note that this macro appears similar to try!(), but, unlike try!(),
85 // it does not propagate the error.
86 macro_rules! return_if_err {
91 debug!("mc reported err");
98 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
99 /// Creates the ExprUseVisitor, configuring it with the various options provided:
101 /// - `delegate` -- who receives the callbacks
102 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
103 /// - `typeck_results` --- typeck results for the code being analyzed
105 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
106 infcx: &'a InferCtxt<'a, 'tcx>,
107 body_owner: LocalDefId,
108 param_env: ty::ParamEnv<'tcx>,
109 typeck_results: &'a ty::TypeckResults<'tcx>,
112 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
118 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
119 debug!("consume_body(body={:?})", body);
121 for param in body.params {
122 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
123 debug!("consume_body: param_ty = {:?}", param_ty);
125 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
127 self.walk_irrefutable_pat(¶m_place, ¶m.pat);
130 self.consume_expr(&body.value);
133 fn tcx(&self) -> TyCtxt<'tcx> {
137 fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
138 debug!("delegate_consume(place_with_id={:?})", place_with_id);
140 let mode = copy_or_move(&self.mc, place_with_id);
141 self.delegate.consume(place_with_id, diag_expr_id, mode);
144 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
146 self.consume_expr(&expr);
150 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
151 debug!("consume_expr(expr={:?})", expr);
153 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
154 self.delegate_consume(&place_with_id, place_with_id.hir_id);
155 self.walk_expr(expr);
158 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
159 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
160 self.delegate.mutate(&place_with_id, place_with_id.hir_id);
161 self.walk_expr(expr);
164 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
165 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
167 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
168 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
173 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
177 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
178 debug!("walk_expr(expr={:?})", expr);
180 self.walk_adjustment(expr);
183 hir::ExprKind::Path(_) => {}
185 hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
187 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
189 self.select_from_expr(base);
192 hir::ExprKind::Field(ref base, _) => {
194 self.select_from_expr(base);
197 hir::ExprKind::Index(ref lhs, ref rhs) => {
199 self.select_from_expr(lhs);
200 self.consume_expr(rhs);
203 hir::ExprKind::Call(ref callee, ref args) => {
205 self.consume_expr(callee);
206 self.consume_exprs(args);
209 hir::ExprKind::MethodCall(.., ref args, _) => {
211 self.consume_exprs(args);
214 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
215 self.walk_struct_expr(fields, opt_with);
218 hir::ExprKind::Tup(ref exprs) => {
219 self.consume_exprs(exprs);
222 hir::ExprKind::Match(ref discr, arms, _) => {
223 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
224 self.borrow_expr(&discr, ty::ImmBorrow);
226 // treatment of the discriminant is handled while walking the arms.
228 self.walk_arm(&discr_place, arm);
232 hir::ExprKind::Array(ref exprs) => {
233 self.consume_exprs(exprs);
236 hir::ExprKind::AddrOf(_, m, ref base) => {
238 // make sure that the thing we are pointing out stays valid
239 // for the lifetime `scope_r` of the resulting ptr:
240 let bk = ty::BorrowKind::from_mutbl(m);
241 self.borrow_expr(&base, bk);
244 hir::ExprKind::InlineAsm(ref asm) => {
245 for op in asm.operands {
247 hir::InlineAsmOperand::In { expr, .. }
248 | hir::InlineAsmOperand::Const { expr, .. }
249 | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
250 hir::InlineAsmOperand::Out { expr, .. } => {
251 if let Some(expr) = expr {
252 self.mutate_expr(expr);
255 hir::InlineAsmOperand::InOut { expr, .. } => {
256 self.mutate_expr(expr);
258 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
259 self.consume_expr(in_expr);
260 if let Some(out_expr) = out_expr {
261 self.mutate_expr(out_expr);
268 hir::ExprKind::LlvmInlineAsm(ref ia) => {
269 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
271 self.consume_expr(output);
273 self.mutate_expr(output);
276 self.consume_exprs(&ia.inputs_exprs);
279 hir::ExprKind::Continue(..)
280 | hir::ExprKind::Lit(..)
281 | hir::ExprKind::ConstBlock(..)
282 | hir::ExprKind::Err => {}
284 hir::ExprKind::Loop(ref blk, _, _) => {
285 self.walk_block(blk);
288 hir::ExprKind::Unary(_, ref lhs) => {
289 self.consume_expr(lhs);
292 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
293 self.consume_expr(lhs);
294 self.consume_expr(rhs);
297 hir::ExprKind::Block(ref blk, _) => {
298 self.walk_block(blk);
301 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
302 if let Some(ref expr) = *opt_expr {
303 self.consume_expr(expr);
307 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
308 self.mutate_expr(lhs);
309 self.consume_expr(rhs);
312 hir::ExprKind::Cast(ref base, _) => {
313 self.consume_expr(base);
316 hir::ExprKind::DropTemps(ref expr) => {
317 self.consume_expr(expr);
320 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
321 if self.mc.typeck_results.is_method_call(expr) {
322 self.consume_expr(lhs);
324 self.mutate_expr(lhs);
326 self.consume_expr(rhs);
329 hir::ExprKind::Repeat(ref base, _) => {
330 self.consume_expr(base);
333 hir::ExprKind::Closure(..) => {
334 self.walk_captures(expr);
337 hir::ExprKind::Box(ref base) => {
338 self.consume_expr(base);
341 hir::ExprKind::Yield(ref value, _) => {
342 self.consume_expr(value);
347 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
349 hir::StmtKind::Local(ref local) => {
350 self.walk_local(&local);
353 hir::StmtKind::Item(_) => {
354 // We don't visit nested items in this visitor,
355 // only the fn body we were given.
358 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
359 self.consume_expr(&expr);
364 fn walk_local(&mut self, local: &hir::Local<'_>) {
365 if let Some(ref expr) = local.init {
366 // Variable declarations with
367 // initializers are considered
368 // "assigns", which is handled by
370 self.walk_expr(&expr);
371 let init_place = return_if_err!(self.mc.cat_expr(&expr));
372 self.walk_irrefutable_pat(&init_place, &local.pat);
376 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
377 /// depending on its type.
378 fn walk_block(&mut self, blk: &hir::Block<'_>) {
379 debug!("walk_block(blk.hir_id={})", blk.hir_id);
381 for stmt in blk.stmts {
382 self.walk_stmt(stmt);
385 if let Some(ref tail_expr) = blk.expr {
386 self.consume_expr(&tail_expr);
392 fields: &[hir::Field<'_>],
393 opt_with: &Option<&'hir hir::Expr<'_>>,
395 // Consume the expressions supplying values for each field.
396 for field in fields {
397 self.consume_expr(&field.expr);
400 let with_expr = match *opt_with {
407 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
409 // Select just those fields of the `with`
410 // expression that will actually be used
411 match with_place.place.ty().kind() {
412 ty::Adt(adt, substs) if adt.is_struct() => {
413 // Consume those fields of the with expression that are needed.
414 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
415 let is_mentioned = fields.iter().any(|f| {
416 self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
419 let field_place = self.mc.cat_projection(
422 with_field.ty(self.tcx(), substs),
423 ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
425 self.delegate_consume(&field_place, field_place.hir_id);
430 // the base expression should always evaluate to a
431 // struct; however, when EUV is run during typeck, it
432 // may not. This will generate an error earlier in typeck,
433 // so we can just ignore it.
434 if !self.tcx().sess.has_errors() {
435 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
440 // walk the with expression so that complex expressions
441 // are properly handled.
442 self.walk_expr(with_expr);
445 // Invoke the appropriate delegate calls for anything that gets
446 // consumed or borrowed as part of the automatic adjustment
448 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
449 let adjustments = self.mc.typeck_results.expr_adjustments(expr);
450 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
451 for adjustment in adjustments {
452 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
453 match adjustment.kind {
454 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
455 // Creating a closure/fn-pointer or unsizing consumes
456 // the input and stores it into the resulting rvalue.
457 self.delegate_consume(&place_with_id, place_with_id.hir_id);
460 adjustment::Adjust::Deref(None) => {}
462 // Autoderefs for overloaded Deref calls in fact reference
463 // their receiver. That is, if we have `(*x)` where `x`
464 // is of type `Rc<T>`, then this in fact is equivalent to
465 // `x.deref()`. Since `deref()` is declared with `&self`,
466 // this is an autoref of `x`.
467 adjustment::Adjust::Deref(Some(ref deref)) => {
468 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
469 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
472 adjustment::Adjust::Borrow(ref autoref) => {
473 self.walk_autoref(expr, &place_with_id, autoref);
477 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
481 /// Walks the autoref `autoref` applied to the autoderef'd
482 /// `expr`. `base_place` is the mem-categorized form of `expr`
483 /// after all relevant autoderefs have occurred.
486 expr: &hir::Expr<'_>,
487 base_place: &PlaceWithHirId<'tcx>,
488 autoref: &adjustment::AutoBorrow<'tcx>,
491 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
492 expr.hir_id, base_place, autoref
496 adjustment::AutoBorrow::Ref(_, m) => {
497 self.delegate.borrow(
500 ty::BorrowKind::from_mutbl(m.into()),
504 adjustment::AutoBorrow::RawPtr(m) => {
505 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
507 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
512 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
513 self.walk_pat(discr_place, &arm.pat);
515 if let Some(hir::Guard::If(ref e)) = arm.guard {
519 self.consume_expr(&arm.body);
522 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
523 /// let binding, and *not* a match arm or nested pat.)
524 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
525 self.walk_pat(discr_place, pat);
528 /// The core driver for walking a pattern
529 fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
530 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
532 let tcx = self.tcx();
533 let ExprUseVisitor { ref mc, body_owner: _, ref mut delegate } = *self;
534 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
535 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
536 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
538 mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
540 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
542 // pat_ty: the type of the binding being produced.
543 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
544 debug!("walk_pat: pat_ty={:?}", pat_ty);
546 // Each match binding is effectively an assignment to the
547 // binding being produced.
548 let def = Res::Local(canonical_id);
549 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
550 delegate.mutate(binding_place, binding_place.hir_id);
553 // It is also a borrow or copy/move of the value being matched.
554 // In a cases of pattern like `let pat = upvar`, don't use the span
555 // of the pattern, as this just looks confusing, instead use the span
556 // of the discriminant.
558 ty::BindByReference(m) => {
559 let bk = ty::BorrowKind::from_mutbl(m);
560 delegate.borrow(place, discr_place.hir_id, bk);
562 ty::BindByValue(..) => {
563 let mode = copy_or_move(mc, &place);
564 debug!("walk_pat binding consuming pat");
565 delegate.consume(place, discr_place.hir_id, mode);
573 /// Handle the case where the current body contains a closure.
575 /// When the current body being handled is a closure, then we must make sure that
576 /// - The parent closure only captures Places from the nested closure that are not local to it.
578 /// In the following example the closures `c` only captures `p.x`` even though `incr`
579 /// is a capture of the nested closure
585 /// let nested = || p.x += incr;
589 /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
590 /// closure as the DefId.
591 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>) {
592 debug!("walk_captures({:?})", closure_expr);
594 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id).to_def_id();
595 let upvars = self.tcx().upvars_mentioned(self.body_owner);
597 // For purposes of this function, generator and closures are equivalent.
598 let body_owner_is_closure = match self.tcx().type_of(self.body_owner.to_def_id()).kind() {
599 ty::Closure(..) | ty::Generator(..) => true,
603 if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
605 for (var_hir_id, min_list) in min_captures.iter() {
606 if upvars.map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id)) {
607 // The nested closure might be capturing the current (enclosing) closure's local variables.
608 // We check if the root variable is ever mentioned within the enclosing closure, if not
609 // then for the current body (if it's a closure) these aren't captures, we will ignore them.
612 for captured_place in min_list {
613 let place = &captured_place.place;
614 let capture_info = captured_place.info;
616 let upvar_id = if body_owner_is_closure {
617 // Mark the place to be captured by the enclosing closure
618 ty::UpvarId::new(*var_hir_id, self.body_owner)
620 ty::UpvarId::new(*var_hir_id, closure_def_id.expect_local())
622 let place_with_id = PlaceWithHirId::new(
623 capture_info.expr_id.unwrap_or(closure_expr.hir_id),
625 PlaceBase::Upvar(upvar_id),
626 place.projections.clone(),
628 match capture_info.capture_kind {
629 ty::UpvarCapture::ByValue(_) => {
630 let mode = copy_or_move(&self.mc, &place_with_id);
631 self.delegate.consume(&place_with_id, place_with_id.hir_id, mode);
633 ty::UpvarCapture::ByRef(upvar_borrow) => {
634 self.delegate.borrow(
636 place_with_id.hir_id,
647 fn copy_or_move<'a, 'tcx>(
648 mc: &mc::MemCategorizationContext<'a, 'tcx>,
649 place_with_id: &PlaceWithHirId<'tcx>,
651 if !mc.type_is_copy_modulo_regions(
652 place_with_id.place.ty(),
653 mc.tcx().hir().span(place_with_id.hir_id),