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 mc::{Place, PlaceBase, Projection};
10 use rustc::infer::InferCtxt;
11 use rustc::ty::{self, adjustment, TyCtxt};
13 use rustc_hir::def::Res;
14 use rustc_hir::def_id::DefId;
15 use rustc_hir::PatKind;
17 use crate::mem_categorization as mc;
20 ///////////////////////////////////////////////////////////////////////////
23 /// This trait defines the callbacks you can expect to receive when
24 /// employing the ExprUseVisitor.
25 pub trait Delegate<'tcx> {
26 // The value found at `place` is either copied or moved, depending
28 fn consume(&mut self, place: &mc::Place<'tcx>, mode: ConsumeMode);
30 // The value found at `place` is being borrowed with kind `bk`.
31 fn borrow(&mut self, place: &mc::Place<'tcx>, bk: ty::BorrowKind);
33 // The path at `place` is being assigned to.
34 fn mutate(&mut self, assignee_place: &mc::Place<'tcx>);
37 #[derive(Copy, Clone, PartialEq, Debug)]
38 pub enum ConsumeMode {
39 Copy, // reference to x where x has a type that copies
40 Move, // reference to x where x has a type that moves
43 #[derive(Copy, Clone, PartialEq, Debug)]
47 WriteAndRead, // x += y
50 ///////////////////////////////////////////////////////////////////////////
51 // The ExprUseVisitor type
53 // This is the code that actually walks the tree.
54 pub struct ExprUseVisitor<'a, 'tcx> {
55 mc: mc::MemCategorizationContext<'a, 'tcx>,
56 delegate: &'a mut dyn Delegate<'tcx>,
59 // If the MC results in an error, it's because the type check
60 // failed (or will fail, when the error is uncovered and reported
61 // during writeback). In this case, we just ignore this part of the
64 // Note that this macro appears similar to try!(), but, unlike try!(),
65 // it does not propagate the error.
66 macro_rules! return_if_err {
71 debug!("mc reported err");
78 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
79 /// Creates the ExprUseVisitor, configuring it with the various options provided:
81 /// - `delegate` -- who receives the callbacks
82 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
83 /// - `tables` --- typeck results for the code being analyzed
85 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
86 infcx: &'a InferCtxt<'a, 'tcx>,
88 param_env: ty::ParamEnv<'tcx>,
89 tables: &'a ty::TypeckTables<'tcx>,
92 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, tables),
97 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
98 debug!("consume_body(body={:?})", body);
100 for param in body.params {
101 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
102 debug!("consume_body: param_ty = {:?}", param_ty);
104 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
106 self.walk_irrefutable_pat(¶m_place, ¶m.pat);
109 self.consume_expr(&body.value);
112 fn tcx(&self) -> TyCtxt<'tcx> {
116 fn delegate_consume(&mut self, place: &Place<'tcx>) {
117 debug!("delegate_consume(place={:?})", place);
119 let mode = copy_or_move(&self.mc, place);
120 self.delegate.consume(place, mode);
123 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
125 self.consume_expr(&expr);
129 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
130 debug!("consume_expr(expr={:?})", expr);
132 let place = return_if_err!(self.mc.cat_expr(expr));
133 self.delegate_consume(&place);
134 self.walk_expr(expr);
137 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
138 let place = return_if_err!(self.mc.cat_expr(expr));
139 self.delegate.mutate(&place);
140 self.walk_expr(expr);
143 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
144 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
146 let place = return_if_err!(self.mc.cat_expr(expr));
147 self.delegate.borrow(&place, bk);
152 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
156 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
157 debug!("walk_expr(expr={:?})", expr);
159 self.walk_adjustment(expr);
162 hir::ExprKind::Path(_) => {}
164 hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
166 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
168 self.select_from_expr(base);
171 hir::ExprKind::Field(ref base, _) => {
173 self.select_from_expr(base);
176 hir::ExprKind::Index(ref lhs, ref rhs) => {
178 self.select_from_expr(lhs);
179 self.consume_expr(rhs);
182 hir::ExprKind::Call(ref callee, ref args) => {
184 self.consume_expr(callee);
185 self.consume_exprs(args);
188 hir::ExprKind::MethodCall(.., ref args) => {
190 self.consume_exprs(args);
193 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
194 self.walk_struct_expr(fields, opt_with);
197 hir::ExprKind::Tup(ref exprs) => {
198 self.consume_exprs(exprs);
201 hir::ExprKind::Match(ref discr, arms, _) => {
202 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
203 self.borrow_expr(&discr, ty::ImmBorrow);
205 // treatment of the discriminant is handled while walking the arms.
207 self.walk_arm(&discr_place, arm);
211 hir::ExprKind::Array(ref exprs) => {
212 self.consume_exprs(exprs);
215 hir::ExprKind::AddrOf(_, m, ref base) => {
217 // make sure that the thing we are pointing out stays valid
218 // for the lifetime `scope_r` of the resulting ptr:
219 let bk = ty::BorrowKind::from_mutbl(m);
220 self.borrow_expr(&base, bk);
223 hir::ExprKind::InlineAsm(ref ia) => {
224 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
226 self.consume_expr(output);
228 self.mutate_expr(output);
231 self.consume_exprs(&ia.inputs_exprs);
234 hir::ExprKind::Continue(..) | hir::ExprKind::Lit(..) | hir::ExprKind::Err => {}
236 hir::ExprKind::Loop(ref blk, _, _) => {
237 self.walk_block(blk);
240 hir::ExprKind::Unary(_, ref lhs) => {
241 self.consume_expr(lhs);
244 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
245 self.consume_expr(lhs);
246 self.consume_expr(rhs);
249 hir::ExprKind::Block(ref blk, _) => {
250 self.walk_block(blk);
253 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
254 if let Some(ref expr) = *opt_expr {
255 self.consume_expr(expr);
259 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
260 self.mutate_expr(lhs);
261 self.consume_expr(rhs);
264 hir::ExprKind::Cast(ref base, _) => {
265 self.consume_expr(base);
268 hir::ExprKind::DropTemps(ref expr) => {
269 self.consume_expr(expr);
272 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
273 if self.mc.tables.is_method_call(expr) {
274 self.consume_expr(lhs);
276 self.mutate_expr(lhs);
278 self.consume_expr(rhs);
281 hir::ExprKind::Repeat(ref base, _) => {
282 self.consume_expr(base);
285 hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
286 self.walk_captures(expr, fn_decl_span);
289 hir::ExprKind::Box(ref base) => {
290 self.consume_expr(base);
293 hir::ExprKind::Yield(ref value, _) => {
294 self.consume_expr(value);
299 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
301 hir::StmtKind::Local(ref local) => {
302 self.walk_local(&local);
305 hir::StmtKind::Item(_) => {
306 // We don't visit nested items in this visitor,
307 // only the fn body we were given.
310 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
311 self.consume_expr(&expr);
316 fn walk_local(&mut self, local: &hir::Local<'_>) {
317 if let Some(ref expr) = local.init {
318 // Variable declarations with
319 // initializers are considered
320 // "assigns", which is handled by
322 self.walk_expr(&expr);
323 let init_place = return_if_err!(self.mc.cat_expr(&expr));
324 self.walk_irrefutable_pat(&init_place, &local.pat);
328 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
329 /// depending on its type.
330 fn walk_block(&mut self, blk: &hir::Block<'_>) {
331 debug!("walk_block(blk.hir_id={})", blk.hir_id);
333 for stmt in blk.stmts {
334 self.walk_stmt(stmt);
337 if let Some(ref tail_expr) = blk.expr {
338 self.consume_expr(&tail_expr);
344 fields: &[hir::Field<'_>],
345 opt_with: &Option<&'hir hir::Expr<'_>>,
347 // Consume the expressions supplying values for each field.
348 for field in fields {
349 self.consume_expr(&field.expr);
352 let with_expr = match *opt_with {
359 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
361 // Select just those fields of the `with`
362 // expression that will actually be used
363 match with_place.ty.kind {
364 ty::Adt(adt, substs) if adt.is_struct() => {
365 // Consume those fields of the with expression that are needed.
366 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
367 let is_mentioned = fields
369 .any(|f| self.tcx().field_index(f.hir_id, self.mc.tables) == f_index);
371 let field_place = self.mc.cat_projection(
374 with_field.ty(self.tcx(), substs),
376 self.delegate_consume(&field_place);
381 // the base expression should always evaluate to a
382 // struct; however, when EUV is run during typeck, it
383 // may not. This will generate an error earlier in typeck,
384 // so we can just ignore it.
385 if !self.tcx().sess.has_errors() {
386 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
391 // walk the with expression so that complex expressions
392 // are properly handled.
393 self.walk_expr(with_expr);
396 // Invoke the appropriate delegate calls for anything that gets
397 // consumed or borrowed as part of the automatic adjustment
399 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
400 let adjustments = self.mc.tables.expr_adjustments(expr);
401 let mut place = return_if_err!(self.mc.cat_expr_unadjusted(expr));
402 for adjustment in adjustments {
403 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
404 match adjustment.kind {
405 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
406 // Creating a closure/fn-pointer or unsizing consumes
407 // the input and stores it into the resulting rvalue.
408 self.delegate_consume(&place);
411 adjustment::Adjust::Deref(None) => {}
413 // Autoderefs for overloaded Deref calls in fact reference
414 // their receiver. That is, if we have `(*x)` where `x`
415 // is of type `Rc<T>`, then this in fact is equivalent to
416 // `x.deref()`. Since `deref()` is declared with `&self`,
417 // this is an autoref of `x`.
418 adjustment::Adjust::Deref(Some(ref deref)) => {
419 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
420 self.delegate.borrow(&place, bk);
423 adjustment::Adjust::Borrow(ref autoref) => {
424 self.walk_autoref(expr, &place, autoref);
427 place = return_if_err!(self.mc.cat_expr_adjusted(expr, place, &adjustment));
431 /// Walks the autoref `autoref` applied to the autoderef'd
432 /// `expr`. `base_place` is the mem-categorized form of `expr`
433 /// after all relevant autoderefs have occurred.
436 expr: &hir::Expr<'_>,
437 base_place: &mc::Place<'tcx>,
438 autoref: &adjustment::AutoBorrow<'tcx>,
441 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
442 expr.hir_id, base_place, autoref
446 adjustment::AutoBorrow::Ref(_, m) => {
447 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
450 adjustment::AutoBorrow::RawPtr(m) => {
451 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
453 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
458 fn walk_arm(&mut self, discr_place: &Place<'tcx>, arm: &hir::Arm<'_>) {
459 self.walk_pat(discr_place, &arm.pat);
461 if let Some(hir::Guard::If(ref e)) = arm.guard {
465 self.consume_expr(&arm.body);
468 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
469 /// let binding, and *not* a match arm or nested pat.)
470 fn walk_irrefutable_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat<'_>) {
471 self.walk_pat(discr_place, pat);
474 /// The core driver for walking a pattern
475 fn walk_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat<'_>) {
476 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
478 let tcx = self.tcx();
479 let ExprUseVisitor { ref mc, ref mut delegate } = *self;
480 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
481 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
482 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
483 if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) {
484 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
486 // pat_ty: the type of the binding being produced.
487 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
488 debug!("walk_pat: pat_ty={:?}", pat_ty);
490 // Each match binding is effectively an assignment to the
491 // binding being produced.
492 let def = Res::Local(canonical_id);
493 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
494 delegate.mutate(binding_place);
497 // It is also a borrow or copy/move of the value being matched.
499 ty::BindByReference(m) => {
500 let bk = ty::BorrowKind::from_mutbl(m);
501 delegate.borrow(place, bk);
503 ty::BindByValue(..) => {
504 let mode = copy_or_move(mc, place);
505 debug!("walk_pat binding consuming pat");
506 delegate.consume(place, mode);
514 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) {
515 debug!("walk_captures({:?})", closure_expr);
517 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
518 if let Some(upvars) = self.tcx().upvars(closure_def_id) {
519 for &var_id in upvars.keys() {
520 let upvar_id = ty::UpvarId {
521 var_path: ty::UpvarPath { hir_id: var_id },
522 closure_expr_id: closure_def_id.to_local(),
524 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
525 let captured_place = return_if_err!(self.cat_captured_var(
530 match upvar_capture {
531 ty::UpvarCapture::ByValue => {
532 let mode = copy_or_move(&self.mc, &captured_place);
533 self.delegate.consume(&captured_place, mode);
535 ty::UpvarCapture::ByRef(upvar_borrow) => {
536 self.delegate.borrow(&captured_place, upvar_borrow.kind);
545 closure_hir_id: hir::HirId,
548 ) -> mc::McResult<mc::Place<'tcx>> {
549 // Create the place for the variable being borrowed, from the
550 // perspective of the creator (parent) of the closure.
551 let var_ty = self.mc.node_ty(var_id)?;
552 self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
556 fn copy_or_move<'a, 'tcx>(
557 mc: &mc::MemCategorizationContext<'a, 'tcx>,
560 if !mc.type_is_copy_modulo_regions(place.ty, place.span) { Move } else { Copy }