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::{PlaceBase, PlaceWithHirId, Projection};
11 use rustc_hir::def::Res;
12 use rustc_hir::def_id::LocalDefId;
13 use rustc_hir::PatKind;
14 use rustc_infer::infer::InferCtxt;
15 use rustc_middle::ty::{self, adjustment, TyCtxt};
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_with_id: &mc::PlaceWithHirId<'tcx>, mode: ConsumeMode);
30 // The value found at `place` is being borrowed with kind `bk`.
31 fn borrow(&mut self, place_with_id: &mc::PlaceWithHirId<'tcx>, bk: ty::BorrowKind);
33 // The path at `place_with_id` is being assigned to.
34 fn mutate(&mut self, assignee_place: &mc::PlaceWithHirId<'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>,
87 body_owner: LocalDefId,
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_with_id: &PlaceWithHirId<'tcx>) {
117 debug!("delegate_consume(place_with_id={:?})", place_with_id);
119 let mode = copy_or_move(&self.mc, place_with_id);
120 self.delegate.consume(place_with_id, 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_with_id = return_if_err!(self.mc.cat_expr(expr));
133 self.delegate_consume(&place_with_id);
134 self.walk_expr(expr);
137 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
138 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
139 self.delegate.mutate(&place_with_id);
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_with_id = return_if_err!(self.mc.cat_expr(expr));
147 self.delegate.borrow(&place_with_id, 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 asm) => {
224 for op in asm.operands {
226 hir::InlineAsmOperand::In { expr, .. }
227 | hir::InlineAsmOperand::Const { expr, .. }
228 | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
229 hir::InlineAsmOperand::Out { expr, .. } => {
230 if let Some(expr) = expr {
231 self.mutate_expr(expr);
234 hir::InlineAsmOperand::InOut { expr, .. } => {
235 self.mutate_expr(expr);
237 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
238 self.consume_expr(in_expr);
239 if let Some(out_expr) = out_expr {
240 self.mutate_expr(out_expr);
247 hir::ExprKind::LlvmInlineAsm(ref ia) => {
248 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
250 self.consume_expr(output);
252 self.mutate_expr(output);
255 self.consume_exprs(&ia.inputs_exprs);
258 hir::ExprKind::Continue(..) | hir::ExprKind::Lit(..) | hir::ExprKind::Err => {}
260 hir::ExprKind::Loop(ref blk, _, _) => {
261 self.walk_block(blk);
264 hir::ExprKind::Unary(_, ref lhs) => {
265 self.consume_expr(lhs);
268 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
269 self.consume_expr(lhs);
270 self.consume_expr(rhs);
273 hir::ExprKind::Block(ref blk, _) => {
274 self.walk_block(blk);
277 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
278 if let Some(ref expr) = *opt_expr {
279 self.consume_expr(expr);
283 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
284 self.mutate_expr(lhs);
285 self.consume_expr(rhs);
288 hir::ExprKind::Cast(ref base, _) => {
289 self.consume_expr(base);
292 hir::ExprKind::DropTemps(ref expr) => {
293 self.consume_expr(expr);
296 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
297 if self.mc.tables.is_method_call(expr) {
298 self.consume_expr(lhs);
300 self.mutate_expr(lhs);
302 self.consume_expr(rhs);
305 hir::ExprKind::Repeat(ref base, _) => {
306 self.consume_expr(base);
309 hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
310 self.walk_captures(expr, fn_decl_span);
313 hir::ExprKind::Box(ref base) => {
314 self.consume_expr(base);
317 hir::ExprKind::Yield(ref value, _) => {
318 self.consume_expr(value);
323 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
325 hir::StmtKind::Local(ref local) => {
326 self.walk_local(&local);
329 hir::StmtKind::Item(_) => {
330 // We don't visit nested items in this visitor,
331 // only the fn body we were given.
334 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
335 self.consume_expr(&expr);
340 fn walk_local(&mut self, local: &hir::Local<'_>) {
341 if let Some(ref expr) = local.init {
342 // Variable declarations with
343 // initializers are considered
344 // "assigns", which is handled by
346 self.walk_expr(&expr);
347 let init_place = return_if_err!(self.mc.cat_expr(&expr));
348 self.walk_irrefutable_pat(&init_place, &local.pat);
352 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
353 /// depending on its type.
354 fn walk_block(&mut self, blk: &hir::Block<'_>) {
355 debug!("walk_block(blk.hir_id={})", blk.hir_id);
357 for stmt in blk.stmts {
358 self.walk_stmt(stmt);
361 if let Some(ref tail_expr) = blk.expr {
362 self.consume_expr(&tail_expr);
368 fields: &[hir::Field<'_>],
369 opt_with: &Option<&'hir hir::Expr<'_>>,
371 // Consume the expressions supplying values for each field.
372 for field in fields {
373 self.consume_expr(&field.expr);
376 let with_expr = match *opt_with {
383 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
385 // Select just those fields of the `with`
386 // expression that will actually be used
387 match with_place.place.ty().kind {
388 ty::Adt(adt, substs) if adt.is_struct() => {
389 // Consume those fields of the with expression that are needed.
390 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
391 let is_mentioned = fields
393 .any(|f| self.tcx().field_index(f.hir_id, self.mc.tables) == f_index);
395 let field_place = self.mc.cat_projection(
398 with_field.ty(self.tcx(), substs),
400 self.delegate_consume(&field_place);
405 // the base expression should always evaluate to a
406 // struct; however, when EUV is run during typeck, it
407 // may not. This will generate an error earlier in typeck,
408 // so we can just ignore it.
409 if !self.tcx().sess.has_errors() {
410 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
415 // walk the with expression so that complex expressions
416 // are properly handled.
417 self.walk_expr(with_expr);
420 // Invoke the appropriate delegate calls for anything that gets
421 // consumed or borrowed as part of the automatic adjustment
423 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
424 let adjustments = self.mc.tables.expr_adjustments(expr);
425 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
426 for adjustment in adjustments {
427 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
428 match adjustment.kind {
429 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
430 // Creating a closure/fn-pointer or unsizing consumes
431 // the input and stores it into the resulting rvalue.
432 self.delegate_consume(&place_with_id);
435 adjustment::Adjust::Deref(None) => {}
437 // Autoderefs for overloaded Deref calls in fact reference
438 // their receiver. That is, if we have `(*x)` where `x`
439 // is of type `Rc<T>`, then this in fact is equivalent to
440 // `x.deref()`. Since `deref()` is declared with `&self`,
441 // this is an autoref of `x`.
442 adjustment::Adjust::Deref(Some(ref deref)) => {
443 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
444 self.delegate.borrow(&place_with_id, bk);
447 adjustment::Adjust::Borrow(ref autoref) => {
448 self.walk_autoref(expr, &place_with_id, autoref);
452 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
456 /// Walks the autoref `autoref` applied to the autoderef'd
457 /// `expr`. `base_place` is the mem-categorized form of `expr`
458 /// after all relevant autoderefs have occurred.
461 expr: &hir::Expr<'_>,
462 base_place: &mc::PlaceWithHirId<'tcx>,
463 autoref: &adjustment::AutoBorrow<'tcx>,
466 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
467 expr.hir_id, base_place, autoref
471 adjustment::AutoBorrow::Ref(_, m) => {
472 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
475 adjustment::AutoBorrow::RawPtr(m) => {
476 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
478 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
483 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
484 self.walk_pat(discr_place, &arm.pat);
486 if let Some(hir::Guard::If(ref e)) = arm.guard {
490 self.consume_expr(&arm.body);
493 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
494 /// let binding, and *not* a match arm or nested pat.)
495 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
496 self.walk_pat(discr_place, pat);
499 /// The core driver for walking a pattern
500 fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
501 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
503 let tcx = self.tcx();
504 let ExprUseVisitor { ref mc, ref mut delegate } = *self;
505 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
506 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
507 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
508 if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) {
509 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
511 // pat_ty: the type of the binding being produced.
512 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
513 debug!("walk_pat: pat_ty={:?}", pat_ty);
515 // Each match binding is effectively an assignment to the
516 // binding being produced.
517 let def = Res::Local(canonical_id);
518 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
519 delegate.mutate(binding_place);
522 // It is also a borrow or copy/move of the value being matched.
524 ty::BindByReference(m) => {
525 let bk = ty::BorrowKind::from_mutbl(m);
526 delegate.borrow(place, bk);
528 ty::BindByValue(..) => {
529 let mode = copy_or_move(mc, place);
530 debug!("walk_pat binding consuming pat");
531 delegate.consume(place, mode);
539 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) {
540 debug!("walk_captures({:?})", closure_expr);
542 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
543 if let Some(upvars) = self.tcx().upvars_mentioned(closure_def_id) {
544 for &var_id in upvars.keys() {
545 let upvar_id = ty::UpvarId {
546 var_path: ty::UpvarPath { hir_id: var_id },
547 closure_expr_id: closure_def_id,
549 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
550 let captured_place = return_if_err!(self.cat_captured_var(
555 match upvar_capture {
556 ty::UpvarCapture::ByValue => {
557 let mode = copy_or_move(&self.mc, &captured_place);
558 self.delegate.consume(&captured_place, mode);
560 ty::UpvarCapture::ByRef(upvar_borrow) => {
561 self.delegate.borrow(&captured_place, upvar_borrow.kind);
570 closure_hir_id: hir::HirId,
573 ) -> mc::McResult<mc::PlaceWithHirId<'tcx>> {
574 // Create the place for the variable being borrowed, from the
575 // perspective of the creator (parent) of the closure.
576 let var_ty = self.mc.node_ty(var_id)?;
577 self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
581 fn copy_or_move<'a, 'tcx>(
582 mc: &mc::MemCategorizationContext<'a, 'tcx>,
583 place_with_id: &PlaceWithHirId<'tcx>,
585 if !mc.type_is_copy_modulo_regions(
586 place_with_id.place.ty(),
587 mc.tcx().hir().span(place_with_id.hir_id),