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_index::vec::Idx;
15 use rustc_infer::infer::InferCtxt;
16 use rustc_middle::ty::{self, adjustment, TyCtxt};
17 use rustc_target::abi::VariantIdx;
19 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
30 fn consume(&mut self, place_with_id: &mc::PlaceWithHirId<'tcx>, mode: ConsumeMode);
32 // The value found at `place` is being borrowed with kind `bk`.
33 fn borrow(&mut self, place_with_id: &mc::PlaceWithHirId<'tcx>, bk: ty::BorrowKind);
35 // The path at `place_with_id` is being assigned to.
36 fn mutate(&mut self, assignee_place: &mc::PlaceWithHirId<'tcx>);
39 #[derive(Copy, Clone, PartialEq, Debug)]
40 pub enum ConsumeMode {
41 Copy, // reference to x where x has a type that copies
42 Move, // reference to x where x has a type that moves
45 #[derive(Copy, Clone, PartialEq, Debug)]
49 WriteAndRead, // x += y
52 ///////////////////////////////////////////////////////////////////////////
53 // The ExprUseVisitor type
55 // This is the code that actually walks the tree.
56 pub struct ExprUseVisitor<'a, 'tcx> {
57 mc: mc::MemCategorizationContext<'a, 'tcx>,
58 delegate: &'a mut dyn Delegate<'tcx>,
61 // If the MC results in an error, it's because the type check
62 // failed (or will fail, when the error is uncovered and reported
63 // during writeback). In this case, we just ignore this part of the
66 // Note that this macro appears similar to try!(), but, unlike try!(),
67 // it does not propagate the error.
68 macro_rules! return_if_err {
73 debug!("mc reported err");
80 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
81 /// Creates the ExprUseVisitor, configuring it with the various options provided:
83 /// - `delegate` -- who receives the callbacks
84 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
85 /// - `tables` --- typeck results for the code being analyzed
87 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
88 infcx: &'a InferCtxt<'a, 'tcx>,
89 body_owner: LocalDefId,
90 param_env: ty::ParamEnv<'tcx>,
91 tables: &'a ty::TypeckTables<'tcx>,
94 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, tables),
99 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
100 debug!("consume_body(body={:?})", body);
102 for param in body.params {
103 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
104 debug!("consume_body: param_ty = {:?}", param_ty);
106 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
108 self.walk_irrefutable_pat(¶m_place, ¶m.pat);
111 self.consume_expr(&body.value);
114 fn tcx(&self) -> TyCtxt<'tcx> {
118 fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>) {
119 debug!("delegate_consume(place_with_id={:?})", place_with_id);
121 let mode = copy_or_move(&self.mc, place_with_id);
122 self.delegate.consume(place_with_id, mode);
125 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
127 self.consume_expr(&expr);
131 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
132 debug!("consume_expr(expr={:?})", expr);
134 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
135 self.delegate_consume(&place_with_id);
136 self.walk_expr(expr);
139 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
140 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
141 self.delegate.mutate(&place_with_id);
142 self.walk_expr(expr);
145 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
146 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
148 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
149 self.delegate.borrow(&place_with_id, bk);
154 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
158 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
159 debug!("walk_expr(expr={:?})", expr);
161 self.walk_adjustment(expr);
164 hir::ExprKind::Path(_) => {}
166 hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
168 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
170 self.select_from_expr(base);
173 hir::ExprKind::Field(ref base, _) => {
175 self.select_from_expr(base);
178 hir::ExprKind::Index(ref lhs, ref rhs) => {
180 self.select_from_expr(lhs);
181 self.consume_expr(rhs);
184 hir::ExprKind::Call(ref callee, ref args) => {
186 self.consume_expr(callee);
187 self.consume_exprs(args);
190 hir::ExprKind::MethodCall(.., ref args, _) => {
192 self.consume_exprs(args);
195 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
196 self.walk_struct_expr(fields, opt_with);
199 hir::ExprKind::Tup(ref exprs) => {
200 self.consume_exprs(exprs);
203 hir::ExprKind::Match(ref discr, arms, _) => {
204 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
205 self.borrow_expr(&discr, ty::ImmBorrow);
207 // treatment of the discriminant is handled while walking the arms.
209 self.walk_arm(&discr_place, arm);
213 hir::ExprKind::Array(ref exprs) => {
214 self.consume_exprs(exprs);
217 hir::ExprKind::AddrOf(_, m, ref base) => {
219 // make sure that the thing we are pointing out stays valid
220 // for the lifetime `scope_r` of the resulting ptr:
221 let bk = ty::BorrowKind::from_mutbl(m);
222 self.borrow_expr(&base, bk);
225 hir::ExprKind::InlineAsm(ref asm) => {
226 for op in asm.operands {
228 hir::InlineAsmOperand::In { expr, .. }
229 | hir::InlineAsmOperand::Const { expr, .. }
230 | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
231 hir::InlineAsmOperand::Out { expr, .. } => {
232 if let Some(expr) = expr {
233 self.mutate_expr(expr);
236 hir::InlineAsmOperand::InOut { expr, .. } => {
237 self.mutate_expr(expr);
239 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
240 self.consume_expr(in_expr);
241 if let Some(out_expr) = out_expr {
242 self.mutate_expr(out_expr);
249 hir::ExprKind::LlvmInlineAsm(ref ia) => {
250 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
252 self.consume_expr(output);
254 self.mutate_expr(output);
257 self.consume_exprs(&ia.inputs_exprs);
260 hir::ExprKind::Continue(..) | hir::ExprKind::Lit(..) | hir::ExprKind::Err => {}
262 hir::ExprKind::Loop(ref blk, _, _) => {
263 self.walk_block(blk);
266 hir::ExprKind::Unary(_, ref lhs) => {
267 self.consume_expr(lhs);
270 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
271 self.consume_expr(lhs);
272 self.consume_expr(rhs);
275 hir::ExprKind::Block(ref blk, _) => {
276 self.walk_block(blk);
279 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
280 if let Some(ref expr) = *opt_expr {
281 self.consume_expr(expr);
285 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
286 self.mutate_expr(lhs);
287 self.consume_expr(rhs);
290 hir::ExprKind::Cast(ref base, _) => {
291 self.consume_expr(base);
294 hir::ExprKind::DropTemps(ref expr) => {
295 self.consume_expr(expr);
298 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
299 if self.mc.tables.is_method_call(expr) {
300 self.consume_expr(lhs);
302 self.mutate_expr(lhs);
304 self.consume_expr(rhs);
307 hir::ExprKind::Repeat(ref base, _) => {
308 self.consume_expr(base);
311 hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
312 self.walk_captures(expr, fn_decl_span);
315 hir::ExprKind::Box(ref base) => {
316 self.consume_expr(base);
319 hir::ExprKind::Yield(ref value, _) => {
320 self.consume_expr(value);
325 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
327 hir::StmtKind::Local(ref local) => {
328 self.walk_local(&local);
331 hir::StmtKind::Item(_) => {
332 // We don't visit nested items in this visitor,
333 // only the fn body we were given.
336 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
337 self.consume_expr(&expr);
342 fn walk_local(&mut self, local: &hir::Local<'_>) {
343 if let Some(ref expr) = local.init {
344 // Variable declarations with
345 // initializers are considered
346 // "assigns", which is handled by
348 self.walk_expr(&expr);
349 let init_place = return_if_err!(self.mc.cat_expr(&expr));
350 self.walk_irrefutable_pat(&init_place, &local.pat);
354 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
355 /// depending on its type.
356 fn walk_block(&mut self, blk: &hir::Block<'_>) {
357 debug!("walk_block(blk.hir_id={})", blk.hir_id);
359 for stmt in blk.stmts {
360 self.walk_stmt(stmt);
363 if let Some(ref tail_expr) = blk.expr {
364 self.consume_expr(&tail_expr);
370 fields: &[hir::Field<'_>],
371 opt_with: &Option<&'hir hir::Expr<'_>>,
373 // Consume the expressions supplying values for each field.
374 for field in fields {
375 self.consume_expr(&field.expr);
378 let with_expr = match *opt_with {
385 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
387 // Select just those fields of the `with`
388 // expression that will actually be used
389 match with_place.place.ty().kind {
390 ty::Adt(adt, substs) if adt.is_struct() => {
391 // Consume those fields of the with expression that are needed.
392 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
393 let is_mentioned = fields
395 .any(|f| self.tcx().field_index(f.hir_id, self.mc.tables) == f_index);
397 let field_place = self.mc.cat_projection(
400 with_field.ty(self.tcx(), substs),
401 mc::ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
403 self.delegate_consume(&field_place);
408 // the base expression should always evaluate to a
409 // struct; however, when EUV is run during typeck, it
410 // may not. This will generate an error earlier in typeck,
411 // so we can just ignore it.
412 if !self.tcx().sess.has_errors() {
413 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
418 // walk the with expression so that complex expressions
419 // are properly handled.
420 self.walk_expr(with_expr);
423 // Invoke the appropriate delegate calls for anything that gets
424 // consumed or borrowed as part of the automatic adjustment
426 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
427 let adjustments = self.mc.tables.expr_adjustments(expr);
428 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
429 for adjustment in adjustments {
430 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
431 match adjustment.kind {
432 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
433 // Creating a closure/fn-pointer or unsizing consumes
434 // the input and stores it into the resulting rvalue.
435 self.delegate_consume(&place_with_id);
438 adjustment::Adjust::Deref(None) => {}
440 // Autoderefs for overloaded Deref calls in fact reference
441 // their receiver. That is, if we have `(*x)` where `x`
442 // is of type `Rc<T>`, then this in fact is equivalent to
443 // `x.deref()`. Since `deref()` is declared with `&self`,
444 // this is an autoref of `x`.
445 adjustment::Adjust::Deref(Some(ref deref)) => {
446 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
447 self.delegate.borrow(&place_with_id, bk);
450 adjustment::Adjust::Borrow(ref autoref) => {
451 self.walk_autoref(expr, &place_with_id, autoref);
455 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
459 /// Walks the autoref `autoref` applied to the autoderef'd
460 /// `expr`. `base_place` is the mem-categorized form of `expr`
461 /// after all relevant autoderefs have occurred.
464 expr: &hir::Expr<'_>,
465 base_place: &mc::PlaceWithHirId<'tcx>,
466 autoref: &adjustment::AutoBorrow<'tcx>,
469 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
470 expr.hir_id, base_place, autoref
474 adjustment::AutoBorrow::Ref(_, m) => {
475 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
478 adjustment::AutoBorrow::RawPtr(m) => {
479 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
481 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
486 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
487 self.walk_pat(discr_place, &arm.pat);
489 if let Some(hir::Guard::If(ref e)) = arm.guard {
493 self.consume_expr(&arm.body);
496 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
497 /// let binding, and *not* a match arm or nested pat.)
498 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
499 self.walk_pat(discr_place, pat);
502 /// The core driver for walking a pattern
503 fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
504 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
506 let tcx = self.tcx();
507 let ExprUseVisitor { ref mc, ref mut delegate } = *self;
508 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
509 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
510 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
511 if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) {
512 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
514 // pat_ty: the type of the binding being produced.
515 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
516 debug!("walk_pat: pat_ty={:?}", pat_ty);
518 // Each match binding is effectively an assignment to the
519 // binding being produced.
520 let def = Res::Local(canonical_id);
521 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
522 delegate.mutate(binding_place);
525 // It is also a borrow or copy/move of the value being matched.
527 ty::BindByReference(m) => {
528 let bk = ty::BorrowKind::from_mutbl(m);
529 delegate.borrow(place, bk);
531 ty::BindByValue(..) => {
532 let mode = copy_or_move(mc, place);
533 debug!("walk_pat binding consuming pat");
534 delegate.consume(place, mode);
542 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) {
543 debug!("walk_captures({:?})", closure_expr);
545 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
546 if let Some(upvars) = self.tcx().upvars_mentioned(closure_def_id) {
547 for &var_id in upvars.keys() {
548 let upvar_id = ty::UpvarId {
549 var_path: ty::UpvarPath { hir_id: var_id },
550 closure_expr_id: closure_def_id,
552 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
553 let captured_place = return_if_err!(self.cat_captured_var(
558 match upvar_capture {
559 ty::UpvarCapture::ByValue => {
560 let mode = copy_or_move(&self.mc, &captured_place);
561 self.delegate.consume(&captured_place, mode);
563 ty::UpvarCapture::ByRef(upvar_borrow) => {
564 self.delegate.borrow(&captured_place, upvar_borrow.kind);
573 closure_hir_id: hir::HirId,
576 ) -> mc::McResult<mc::PlaceWithHirId<'tcx>> {
577 // Create the place for the variable being borrowed, from the
578 // perspective of the creator (parent) of the closure.
579 let var_ty = self.mc.node_ty(var_id)?;
580 self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
584 fn copy_or_move<'a, 'tcx>(
585 mc: &mc::MemCategorizationContext<'a, 'tcx>,
586 place_with_id: &PlaceWithHirId<'tcx>,
588 if !mc.type_is_copy_modulo_regions(
589 place_with_id.place.ty(),
590 mc.tcx().hir().span(place_with_id.hir_id),