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;
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
31 fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, mode: ConsumeMode);
33 // The value found at `place` is being borrowed with kind `bk`.
34 fn borrow(&mut self, place_with_id: &PlaceWithHirId<'tcx>, bk: ty::BorrowKind);
36 // The path at `place_with_id` is being assigned to.
37 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>);
40 #[derive(Copy, Clone, PartialEq, Debug)]
41 pub enum ConsumeMode {
42 Copy, // reference to x where x has a type that copies
43 Move, // reference to x where x has a type that moves
46 #[derive(Copy, Clone, PartialEq, Debug)]
50 WriteAndRead, // x += y
53 ///////////////////////////////////////////////////////////////////////////
54 // The ExprUseVisitor type
56 // This is the code that actually walks the tree.
57 pub struct ExprUseVisitor<'a, 'tcx> {
58 mc: mc::MemCategorizationContext<'a, 'tcx>,
59 delegate: &'a mut dyn Delegate<'tcx>,
62 // If the MC results in an error, it's because the type check
63 // failed (or will fail, when the error is uncovered and reported
64 // during writeback). In this case, we just ignore this part of the
67 // Note that this macro appears similar to try!(), but, unlike try!(),
68 // it does not propagate the error.
69 macro_rules! return_if_err {
74 debug!("mc reported err");
81 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
82 /// Creates the ExprUseVisitor, configuring it with the various options provided:
84 /// - `delegate` -- who receives the callbacks
85 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
86 /// - `typeck_results` --- typeck results for the code being analyzed
88 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
89 infcx: &'a InferCtxt<'a, 'tcx>,
90 body_owner: LocalDefId,
91 param_env: ty::ParamEnv<'tcx>,
92 typeck_results: &'a ty::TypeckResults<'tcx>,
95 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
100 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
101 debug!("consume_body(body={:?})", body);
103 for param in body.params {
104 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
105 debug!("consume_body: param_ty = {:?}", param_ty);
107 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
109 self.walk_irrefutable_pat(¶m_place, ¶m.pat);
112 self.consume_expr(&body.value);
115 fn tcx(&self) -> TyCtxt<'tcx> {
119 fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>) {
120 debug!("delegate_consume(place_with_id={:?})", place_with_id);
122 let mode = copy_or_move(&self.mc, place_with_id);
123 self.delegate.consume(place_with_id, mode);
126 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
128 self.consume_expr(&expr);
132 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
133 debug!("consume_expr(expr={:?})", expr);
135 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
136 self.delegate_consume(&place_with_id);
137 self.walk_expr(expr);
140 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
141 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
142 self.delegate.mutate(&place_with_id);
143 self.walk_expr(expr);
146 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
147 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
149 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
150 self.delegate.borrow(&place_with_id, bk);
155 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
159 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
160 debug!("walk_expr(expr={:?})", expr);
162 self.walk_adjustment(expr);
165 hir::ExprKind::Path(_) => {}
167 hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
169 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
171 self.select_from_expr(base);
174 hir::ExprKind::Field(ref base, _) => {
176 self.select_from_expr(base);
179 hir::ExprKind::Index(ref lhs, ref rhs) => {
181 self.select_from_expr(lhs);
182 self.consume_expr(rhs);
185 hir::ExprKind::Call(ref callee, ref args) => {
187 self.consume_expr(callee);
188 self.consume_exprs(args);
191 hir::ExprKind::MethodCall(.., ref args, _) => {
193 self.consume_exprs(args);
196 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
197 self.walk_struct_expr(fields, opt_with);
200 hir::ExprKind::Tup(ref exprs) => {
201 self.consume_exprs(exprs);
204 hir::ExprKind::Match(ref discr, arms, _) => {
205 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
206 self.borrow_expr(&discr, ty::ImmBorrow);
208 // treatment of the discriminant is handled while walking the arms.
210 self.walk_arm(&discr_place, arm);
214 hir::ExprKind::Array(ref exprs) => {
215 self.consume_exprs(exprs);
218 hir::ExprKind::AddrOf(_, m, ref base) => {
220 // make sure that the thing we are pointing out stays valid
221 // for the lifetime `scope_r` of the resulting ptr:
222 let bk = ty::BorrowKind::from_mutbl(m);
223 self.borrow_expr(&base, bk);
226 hir::ExprKind::InlineAsm(ref asm) => {
227 for op in asm.operands {
229 hir::InlineAsmOperand::In { expr, .. }
230 | hir::InlineAsmOperand::Const { expr, .. }
231 | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
232 hir::InlineAsmOperand::Out { expr, .. } => {
233 if let Some(expr) = expr {
234 self.mutate_expr(expr);
237 hir::InlineAsmOperand::InOut { expr, .. } => {
238 self.mutate_expr(expr);
240 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
241 self.consume_expr(in_expr);
242 if let Some(out_expr) = out_expr {
243 self.mutate_expr(out_expr);
250 hir::ExprKind::LlvmInlineAsm(ref ia) => {
251 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
253 self.consume_expr(output);
255 self.mutate_expr(output);
258 self.consume_exprs(&ia.inputs_exprs);
261 hir::ExprKind::Continue(..) | hir::ExprKind::Lit(..) | hir::ExprKind::Err => {}
263 hir::ExprKind::Loop(ref blk, _, _) => {
264 self.walk_block(blk);
267 hir::ExprKind::Unary(_, ref lhs) => {
268 self.consume_expr(lhs);
271 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
272 self.consume_expr(lhs);
273 self.consume_expr(rhs);
276 hir::ExprKind::Block(ref blk, _) => {
277 self.walk_block(blk);
280 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
281 if let Some(ref expr) = *opt_expr {
282 self.consume_expr(expr);
286 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
287 self.mutate_expr(lhs);
288 self.consume_expr(rhs);
291 hir::ExprKind::Cast(ref base, _) => {
292 self.consume_expr(base);
295 hir::ExprKind::DropTemps(ref expr) => {
296 self.consume_expr(expr);
299 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
300 if self.mc.typeck_results.is_method_call(expr) {
301 self.consume_expr(lhs);
303 self.mutate_expr(lhs);
305 self.consume_expr(rhs);
308 hir::ExprKind::Repeat(ref base, _) => {
309 self.consume_expr(base);
312 hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
313 self.walk_captures(expr, fn_decl_span);
316 hir::ExprKind::Box(ref base) => {
317 self.consume_expr(base);
320 hir::ExprKind::Yield(ref value, _) => {
321 self.consume_expr(value);
326 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
328 hir::StmtKind::Local(ref local) => {
329 self.walk_local(&local);
332 hir::StmtKind::Item(_) => {
333 // We don't visit nested items in this visitor,
334 // only the fn body we were given.
337 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
338 self.consume_expr(&expr);
343 fn walk_local(&mut self, local: &hir::Local<'_>) {
344 if let Some(ref expr) = local.init {
345 // Variable declarations with
346 // initializers are considered
347 // "assigns", which is handled by
349 self.walk_expr(&expr);
350 let init_place = return_if_err!(self.mc.cat_expr(&expr));
351 self.walk_irrefutable_pat(&init_place, &local.pat);
355 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
356 /// depending on its type.
357 fn walk_block(&mut self, blk: &hir::Block<'_>) {
358 debug!("walk_block(blk.hir_id={})", blk.hir_id);
360 for stmt in blk.stmts {
361 self.walk_stmt(stmt);
364 if let Some(ref tail_expr) = blk.expr {
365 self.consume_expr(&tail_expr);
371 fields: &[hir::Field<'_>],
372 opt_with: &Option<&'hir hir::Expr<'_>>,
374 // Consume the expressions supplying values for each field.
375 for field in fields {
376 self.consume_expr(&field.expr);
379 let with_expr = match *opt_with {
386 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
388 // Select just those fields of the `with`
389 // expression that will actually be used
390 match with_place.place.ty().kind {
391 ty::Adt(adt, substs) if adt.is_struct() => {
392 // Consume those fields of the with expression that are needed.
393 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
394 let is_mentioned = fields.iter().any(|f| {
395 self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
398 let field_place = self.mc.cat_projection(
401 with_field.ty(self.tcx(), substs),
402 ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
404 self.delegate_consume(&field_place);
409 // the base expression should always evaluate to a
410 // struct; however, when EUV is run during typeck, it
411 // may not. This will generate an error earlier in typeck,
412 // so we can just ignore it.
413 if !self.tcx().sess.has_errors() {
414 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
419 // walk the with expression so that complex expressions
420 // are properly handled.
421 self.walk_expr(with_expr);
424 // Invoke the appropriate delegate calls for anything that gets
425 // consumed or borrowed as part of the automatic adjustment
427 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
428 let adjustments = self.mc.typeck_results.expr_adjustments(expr);
429 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
430 for adjustment in adjustments {
431 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
432 match adjustment.kind {
433 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
434 // Creating a closure/fn-pointer or unsizing consumes
435 // the input and stores it into the resulting rvalue.
436 self.delegate_consume(&place_with_id);
439 adjustment::Adjust::Deref(None) => {}
441 // Autoderefs for overloaded Deref calls in fact reference
442 // their receiver. That is, if we have `(*x)` where `x`
443 // is of type `Rc<T>`, then this in fact is equivalent to
444 // `x.deref()`. Since `deref()` is declared with `&self`,
445 // this is an autoref of `x`.
446 adjustment::Adjust::Deref(Some(ref deref)) => {
447 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
448 self.delegate.borrow(&place_with_id, bk);
451 adjustment::Adjust::Borrow(ref autoref) => {
452 self.walk_autoref(expr, &place_with_id, autoref);
456 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
460 /// Walks the autoref `autoref` applied to the autoderef'd
461 /// `expr`. `base_place` is the mem-categorized form of `expr`
462 /// after all relevant autoderefs have occurred.
465 expr: &hir::Expr<'_>,
466 base_place: &PlaceWithHirId<'tcx>,
467 autoref: &adjustment::AutoBorrow<'tcx>,
470 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
471 expr.hir_id, base_place, autoref
475 adjustment::AutoBorrow::Ref(_, m) => {
476 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
479 adjustment::AutoBorrow::RawPtr(m) => {
480 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
482 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
487 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
488 self.walk_pat(discr_place, &arm.pat);
490 if let Some(hir::Guard::If(ref e)) = arm.guard {
494 self.consume_expr(&arm.body);
497 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
498 /// let binding, and *not* a match arm or nested pat.)
499 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
500 self.walk_pat(discr_place, pat);
503 /// The core driver for walking a pattern
504 fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
505 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
507 let tcx = self.tcx();
508 let ExprUseVisitor { ref mc, ref mut delegate } = *self;
509 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
510 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
511 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
513 mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
515 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
517 // pat_ty: the type of the binding being produced.
518 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
519 debug!("walk_pat: pat_ty={:?}", pat_ty);
521 // Each match binding is effectively an assignment to the
522 // binding being produced.
523 let def = Res::Local(canonical_id);
524 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
525 delegate.mutate(binding_place);
528 // It is also a borrow or copy/move of the value being matched.
530 ty::BindByReference(m) => {
531 let bk = ty::BorrowKind::from_mutbl(m);
532 delegate.borrow(place, bk);
534 ty::BindByValue(..) => {
535 let mode = copy_or_move(mc, place);
536 debug!("walk_pat binding consuming pat");
537 delegate.consume(place, mode);
545 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) {
546 debug!("walk_captures({:?})", closure_expr);
548 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
549 if let Some(upvars) = self.tcx().upvars_mentioned(closure_def_id) {
550 for &var_id in upvars.keys() {
551 let upvar_id = ty::UpvarId {
552 var_path: ty::UpvarPath { hir_id: var_id },
553 closure_expr_id: closure_def_id,
555 let upvar_capture = self.mc.typeck_results.upvar_capture(upvar_id);
556 let captured_place = return_if_err!(self.cat_captured_var(
561 match upvar_capture {
562 ty::UpvarCapture::ByValue => {
563 let mode = copy_or_move(&self.mc, &captured_place);
564 self.delegate.consume(&captured_place, mode);
566 ty::UpvarCapture::ByRef(upvar_borrow) => {
567 self.delegate.borrow(&captured_place, upvar_borrow.kind);
576 closure_hir_id: hir::HirId,
579 ) -> mc::McResult<PlaceWithHirId<'tcx>> {
580 // Create the place for the variable being borrowed, from the
581 // perspective of the creator (parent) of the closure.
582 let var_ty = self.mc.node_ty(var_id)?;
583 self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
587 fn copy_or_move<'a, 'tcx>(
588 mc: &mc::MemCategorizationContext<'a, 'tcx>,
589 place_with_id: &PlaceWithHirId<'tcx>,
591 if !mc.type_is_copy_modulo_regions(
592 place_with_id.place.ty(),
593 mc.tcx().hir().span(place_with_id.hir_id),