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::*;
6 use self::OverloadedCallType::*;
8 // Export these here so that Clippy can use them.
9 pub use mc::{Place, PlaceBase, Projection};
11 use rustc::infer::InferCtxt;
12 use rustc::ty::{self, adjustment, TyCtxt};
14 use rustc_hir::def::Res;
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::PatKind;
18 use crate::mem_categorization as mc;
21 ///////////////////////////////////////////////////////////////////////////
24 /// This trait defines the callbacks you can expect to receive when
25 /// employing the ExprUseVisitor.
26 pub trait Delegate<'tcx> {
27 // The value found at `place` is either copied or moved, depending
29 fn consume(&mut self, place: &mc::Place<'tcx>, mode: ConsumeMode);
31 // The value found at `place` is being borrowed with kind `bk`.
32 fn borrow(&mut self, place: &mc::Place<'tcx>, bk: ty::BorrowKind);
34 // The path at `place` is being assigned to.
35 fn mutate(&mut self, assignee_place: &mc::Place<'tcx>);
38 #[derive(Copy, Clone, PartialEq, Debug)]
39 pub enum ConsumeMode {
40 Copy, // reference to x where x has a type that copies
41 Move, // reference to x where x has a type that moves
44 #[derive(Copy, Clone, PartialEq, Debug)]
48 WriteAndRead, // x += y
51 #[derive(Copy, Clone)]
52 enum OverloadedCallType {
58 impl OverloadedCallType {
59 fn from_trait_id(tcx: TyCtxt<'_>, trait_id: DefId) -> OverloadedCallType {
60 for &(maybe_function_trait, overloaded_call_type) in &[
61 (tcx.lang_items().fn_once_trait(), FnOnceOverloadedCall),
62 (tcx.lang_items().fn_mut_trait(), FnMutOverloadedCall),
63 (tcx.lang_items().fn_trait(), FnOverloadedCall),
65 match maybe_function_trait {
66 Some(function_trait) if function_trait == trait_id => return overloaded_call_type,
71 bug!("overloaded call didn't map to known function trait")
74 fn from_method_id(tcx: TyCtxt<'_>, method_id: DefId) -> OverloadedCallType {
75 let method = tcx.associated_item(method_id);
76 OverloadedCallType::from_trait_id(tcx, method.container.id())
80 ///////////////////////////////////////////////////////////////////////////
81 // The ExprUseVisitor type
83 // This is the code that actually walks the tree.
84 pub struct ExprUseVisitor<'a, 'tcx> {
85 mc: mc::MemCategorizationContext<'a, 'tcx>,
86 delegate: &'a mut dyn Delegate<'tcx>,
89 // If the MC results in an error, it's because the type check
90 // failed (or will fail, when the error is uncovered and reported
91 // during writeback). In this case, we just ignore this part of the
94 // Note that this macro appears similar to try!(), but, unlike try!(),
95 // it does not propagate the error.
96 macro_rules! return_if_err {
101 debug!("mc reported err");
108 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
109 /// Creates the ExprUseVisitor, configuring it with the various options provided:
111 /// - `delegate` -- who receives the callbacks
112 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
113 /// - `tables` --- typeck results for the code being analyzed
115 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
116 infcx: &'a InferCtxt<'a, 'tcx>,
118 param_env: ty::ParamEnv<'tcx>,
119 tables: &'a ty::TypeckTables<'tcx>,
122 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, tables),
127 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
128 debug!("consume_body(body={:?})", body);
130 for param in body.params {
131 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
132 debug!("consume_body: param_ty = {:?}", param_ty);
134 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
136 self.walk_irrefutable_pat(¶m_place, ¶m.pat);
139 self.consume_expr(&body.value);
142 fn tcx(&self) -> TyCtxt<'tcx> {
146 fn delegate_consume(&mut self, place: &Place<'tcx>) {
147 debug!("delegate_consume(place={:?})", place);
149 let mode = copy_or_move(&self.mc, place);
150 self.delegate.consume(place, mode);
153 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
155 self.consume_expr(&expr);
159 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
160 debug!("consume_expr(expr={:?})", expr);
162 let place = return_if_err!(self.mc.cat_expr(expr));
163 self.delegate_consume(&place);
164 self.walk_expr(expr);
167 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
168 let place = return_if_err!(self.mc.cat_expr(expr));
169 self.delegate.mutate(&place);
170 self.walk_expr(expr);
173 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
174 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
176 let place = return_if_err!(self.mc.cat_expr(expr));
177 self.delegate.borrow(&place, bk);
182 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
186 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
187 debug!("walk_expr(expr={:?})", expr);
189 self.walk_adjustment(expr);
192 hir::ExprKind::Path(_) => {}
194 hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
196 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
198 self.select_from_expr(base);
201 hir::ExprKind::Field(ref base, _) => {
203 self.select_from_expr(base);
206 hir::ExprKind::Index(ref lhs, ref rhs) => {
208 self.select_from_expr(lhs);
209 self.consume_expr(rhs);
212 hir::ExprKind::Call(ref callee, ref args) => {
214 self.walk_callee(expr, callee);
215 self.consume_exprs(args);
218 hir::ExprKind::MethodCall(.., ref args) => {
220 self.consume_exprs(args);
223 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
224 self.walk_struct_expr(fields, opt_with);
227 hir::ExprKind::Tup(ref exprs) => {
228 self.consume_exprs(exprs);
231 hir::ExprKind::Match(ref discr, arms, _) => {
232 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
233 self.borrow_expr(&discr, ty::ImmBorrow);
235 // treatment of the discriminant is handled while walking the arms.
237 self.walk_arm(&discr_place, arm);
241 hir::ExprKind::Array(ref exprs) => {
242 self.consume_exprs(exprs);
245 hir::ExprKind::AddrOf(_, m, ref base) => {
247 // make sure that the thing we are pointing out stays valid
248 // for the lifetime `scope_r` of the resulting ptr:
249 let bk = ty::BorrowKind::from_mutbl(m);
250 self.borrow_expr(&base, bk);
253 hir::ExprKind::InlineAsm(ref ia) => {
254 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
256 self.consume_expr(output);
258 self.mutate_expr(output);
261 self.consume_exprs(&ia.inputs_exprs);
264 hir::ExprKind::Continue(..) | hir::ExprKind::Lit(..) | hir::ExprKind::Err => {}
266 hir::ExprKind::Loop(ref blk, _, _) => {
267 self.walk_block(blk);
270 hir::ExprKind::Unary(_, ref lhs) => {
271 self.consume_expr(lhs);
274 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
275 self.consume_expr(lhs);
276 self.consume_expr(rhs);
279 hir::ExprKind::Block(ref blk, _) => {
280 self.walk_block(blk);
283 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
284 if let Some(ref expr) = *opt_expr {
285 self.consume_expr(expr);
289 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
290 self.mutate_expr(lhs);
291 self.consume_expr(rhs);
294 hir::ExprKind::Cast(ref base, _) => {
295 self.consume_expr(base);
298 hir::ExprKind::DropTemps(ref expr) => {
299 self.consume_expr(expr);
302 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
303 if self.mc.tables.is_method_call(expr) {
304 self.consume_expr(lhs);
306 self.mutate_expr(lhs);
308 self.consume_expr(rhs);
311 hir::ExprKind::Repeat(ref base, _) => {
312 self.consume_expr(base);
315 hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
316 self.walk_captures(expr, fn_decl_span);
319 hir::ExprKind::Box(ref base) => {
320 self.consume_expr(base);
323 hir::ExprKind::Yield(ref value, _) => {
324 self.consume_expr(value);
329 fn walk_callee(&mut self, call: &hir::Expr<'_>, callee: &hir::Expr<'_>) {
330 let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
331 debug!("walk_callee: callee={:?} callee_ty={:?}", callee, callee_ty);
332 match callee_ty.kind {
333 ty::FnDef(..) | ty::FnPtr(_) => {
334 self.consume_expr(callee);
338 if let Some(def_id) = self.mc.tables.type_dependent_def_id(call.hir_id) {
339 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
340 FnMutOverloadedCall => {
341 self.borrow_expr(callee, ty::MutBorrow);
343 FnOverloadedCall => {
344 self.borrow_expr(callee, ty::ImmBorrow);
346 FnOnceOverloadedCall => self.consume_expr(callee),
351 .delay_span_bug(call.span, "no type-dependent def for overloaded call");
357 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
359 hir::StmtKind::Local(ref local) => {
360 self.walk_local(&local);
363 hir::StmtKind::Item(_) => {
364 // We don't visit nested items in this visitor,
365 // only the fn body we were given.
368 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
369 self.consume_expr(&expr);
374 fn walk_local(&mut self, local: &hir::Local<'_>) {
375 if let Some(ref expr) = local.init {
376 // Variable declarations with
377 // initializers are considered
378 // "assigns", which is handled by
380 self.walk_expr(&expr);
381 let init_place = return_if_err!(self.mc.cat_expr(&expr));
382 self.walk_irrefutable_pat(&init_place, &local.pat);
386 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
387 /// depending on its type.
388 fn walk_block(&mut self, blk: &hir::Block<'_>) {
389 debug!("walk_block(blk.hir_id={})", blk.hir_id);
391 for stmt in blk.stmts {
392 self.walk_stmt(stmt);
395 if let Some(ref tail_expr) = blk.expr {
396 self.consume_expr(&tail_expr);
402 fields: &[hir::Field<'_>],
403 opt_with: &Option<&'hir hir::Expr<'_>>,
405 // Consume the expressions supplying values for each field.
406 for field in fields {
407 self.consume_expr(&field.expr);
410 let with_expr = match *opt_with {
417 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
419 // Select just those fields of the `with`
420 // expression that will actually be used
421 match with_place.ty.kind {
422 ty::Adt(adt, substs) if adt.is_struct() => {
423 // Consume those fields of the with expression that are needed.
424 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
425 let is_mentioned = fields
427 .any(|f| self.tcx().field_index(f.hir_id, self.mc.tables) == f_index);
429 let field_place = self.mc.cat_projection(
432 with_field.ty(self.tcx(), substs),
434 self.delegate_consume(&field_place);
439 // the base expression should always evaluate to a
440 // struct; however, when EUV is run during typeck, it
441 // may not. This will generate an error earlier in typeck,
442 // so we can just ignore it.
443 if !self.tcx().sess.has_errors() {
444 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
449 // walk the with expression so that complex expressions
450 // are properly handled.
451 self.walk_expr(with_expr);
454 // Invoke the appropriate delegate calls for anything that gets
455 // consumed or borrowed as part of the automatic adjustment
457 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
458 let adjustments = self.mc.tables.expr_adjustments(expr);
459 let mut place = return_if_err!(self.mc.cat_expr_unadjusted(expr));
460 for adjustment in adjustments {
461 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
462 match adjustment.kind {
463 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
464 // Creating a closure/fn-pointer or unsizing consumes
465 // the input and stores it into the resulting rvalue.
466 self.delegate_consume(&place);
469 adjustment::Adjust::Deref(None) => {}
471 // Autoderefs for overloaded Deref calls in fact reference
472 // their receiver. That is, if we have `(*x)` where `x`
473 // is of type `Rc<T>`, then this in fact is equivalent to
474 // `x.deref()`. Since `deref()` is declared with `&self`,
475 // this is an autoref of `x`.
476 adjustment::Adjust::Deref(Some(ref deref)) => {
477 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
478 self.delegate.borrow(&place, bk);
481 adjustment::Adjust::Borrow(ref autoref) => {
482 self.walk_autoref(expr, &place, autoref);
485 place = return_if_err!(self.mc.cat_expr_adjusted(expr, place, &adjustment));
489 /// Walks the autoref `autoref` applied to the autoderef'd
490 /// `expr`. `base_place` is the mem-categorized form of `expr`
491 /// after all relevant autoderefs have occurred.
494 expr: &hir::Expr<'_>,
495 base_place: &mc::Place<'tcx>,
496 autoref: &adjustment::AutoBorrow<'tcx>,
499 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
500 expr.hir_id, base_place, autoref
504 adjustment::AutoBorrow::Ref(_, m) => {
505 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
508 adjustment::AutoBorrow::RawPtr(m) => {
509 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
511 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
516 fn walk_arm(&mut self, discr_place: &Place<'tcx>, arm: &hir::Arm<'_>) {
517 self.walk_pat(discr_place, &arm.pat);
519 if let Some(hir::Guard::If(ref e)) = arm.guard {
523 self.consume_expr(&arm.body);
526 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
527 /// let binding, and *not* a match arm or nested pat.)
528 fn walk_irrefutable_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat<'_>) {
529 self.walk_pat(discr_place, pat);
532 /// The core driver for walking a pattern
533 fn walk_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat<'_>) {
534 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
536 let tcx = self.tcx();
537 let ExprUseVisitor { ref mc, ref mut delegate } = *self;
538 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
539 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
540 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
541 if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) {
542 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
544 // pat_ty: the type of the binding being produced.
545 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
546 debug!("walk_pat: pat_ty={:?}", pat_ty);
548 // Each match binding is effectively an assignment to the
549 // binding being produced.
550 let def = Res::Local(canonical_id);
551 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
552 delegate.mutate(binding_place);
555 // It is also a borrow or copy/move of the value being matched.
557 ty::BindByReference(m) => {
558 let bk = ty::BorrowKind::from_mutbl(m);
559 delegate.borrow(place, bk);
561 ty::BindByValue(..) => {
562 let mode = copy_or_move(mc, place);
563 debug!("walk_pat binding consuming pat");
564 delegate.consume(place, mode);
572 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) {
573 debug!("walk_captures({:?})", closure_expr);
575 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
576 if let Some(upvars) = self.tcx().upvars(closure_def_id) {
577 for &var_id in upvars.keys() {
578 let upvar_id = ty::UpvarId {
579 var_path: ty::UpvarPath { hir_id: var_id },
580 closure_expr_id: closure_def_id.to_local(),
582 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
583 let captured_place = return_if_err!(self.cat_captured_var(
588 match upvar_capture {
589 ty::UpvarCapture::ByValue => {
590 let mode = copy_or_move(&self.mc, &captured_place);
591 self.delegate.consume(&captured_place, mode);
593 ty::UpvarCapture::ByRef(upvar_borrow) => {
594 self.delegate.borrow(&captured_place, upvar_borrow.kind);
603 closure_hir_id: hir::HirId,
606 ) -> mc::McResult<mc::Place<'tcx>> {
607 // Create the place for the variable being borrowed, from the
608 // perspective of the creator (parent) of the closure.
609 let var_ty = self.mc.node_ty(var_id)?;
610 self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
614 fn copy_or_move<'a, 'tcx>(
615 mc: &mc::MemCategorizationContext<'a, 'tcx>,
618 if !mc.type_is_copy_modulo_regions(place.ty, place.span) { Move } else { Copy }