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::{PlaceBase, Place, Projection};
11 use rustc::hir::{self, PatKind};
12 use rustc::hir::def::Res;
13 use rustc::hir::def_id::DefId;
14 use rustc::hir::ptr::P;
15 use rustc::infer::InferCtxt;
16 use rustc::ty::{self, TyCtxt, adjustment};
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 => {
67 return overloaded_call_type
73 bug!("overloaded call didn't map to known function trait")
76 fn from_method_id(tcx: TyCtxt<'_>, method_id: DefId) -> OverloadedCallType {
77 let method = tcx.associated_item(method_id);
78 OverloadedCallType::from_trait_id(tcx, method.container.id())
82 ///////////////////////////////////////////////////////////////////////////
83 // The ExprUseVisitor type
85 // This is the code that actually walks the tree.
86 pub struct ExprUseVisitor<'a, 'tcx> {
87 mc: mc::MemCategorizationContext<'a, 'tcx>,
88 delegate: &'a mut dyn Delegate<'tcx>,
91 // If the MC results in an error, it's because the type check
92 // failed (or will fail, when the error is uncovered and reported
93 // during writeback). In this case, we just ignore this part of the
96 // Note that this macro appears similar to try!(), but, unlike try!(),
97 // it does not propagate the error.
98 macro_rules! return_if_err {
103 debug!("mc reported err");
110 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
111 /// Creates the ExprUseVisitor, configuring it with the various options provided:
113 /// - `delegate` -- who receives the callbacks
114 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
115 /// - `tables` --- typeck results for the code being analyzed
117 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
118 infcx: &'a InferCtxt<'a, 'tcx>,
120 param_env: ty::ParamEnv<'tcx>,
121 tables: &'a ty::TypeckTables<'tcx>,
124 mc: mc::MemCategorizationContext::new(
134 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
135 debug!("consume_body(body={:?})", body);
137 for param in body.params {
138 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
139 debug!("consume_body: param_ty = {:?}", param_ty);
141 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
143 self.walk_irrefutable_pat(¶m_place, ¶m.pat);
146 self.consume_expr(&body.value);
149 fn tcx(&self) -> TyCtxt<'tcx> {
153 fn delegate_consume(&mut self, place: &Place<'tcx>) {
154 debug!("delegate_consume(place={:?})", place);
156 let mode = copy_or_move(&self.mc, place);
157 self.delegate.consume(place, mode);
160 fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
162 self.consume_expr(&expr);
166 pub fn consume_expr(&mut self, expr: &hir::Expr) {
167 debug!("consume_expr(expr={:?})", expr);
169 let place = return_if_err!(self.mc.cat_expr(expr));
170 self.delegate_consume(&place);
171 self.walk_expr(expr);
174 fn mutate_expr(&mut self, expr: &hir::Expr) {
175 let place = return_if_err!(self.mc.cat_expr(expr));
176 self.delegate.mutate(&place);
177 self.walk_expr(expr);
180 fn borrow_expr(&mut self, expr: &hir::Expr, bk: ty::BorrowKind) {
181 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
183 let place = return_if_err!(self.mc.cat_expr(expr));
184 self.delegate.borrow(&place, bk);
189 fn select_from_expr(&mut self, expr: &hir::Expr) {
193 pub fn walk_expr(&mut self, expr: &hir::Expr) {
194 debug!("walk_expr(expr={:?})", expr);
196 self.walk_adjustment(expr);
199 hir::ExprKind::Path(_) => { }
201 hir::ExprKind::Type(ref subexpr, _) => {
202 self.walk_expr(subexpr)
205 hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base
206 self.select_from_expr(base);
209 hir::ExprKind::Field(ref base, _) => { // base.f
210 self.select_from_expr(base);
213 hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs]
214 self.select_from_expr(lhs);
215 self.consume_expr(rhs);
218 hir::ExprKind::Call(ref callee, ref args) => { // callee(args)
219 self.walk_callee(expr, callee);
220 self.consume_exprs(args);
223 hir::ExprKind::MethodCall(.., ref args) => { // callee.m(args)
224 self.consume_exprs(args);
227 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
228 self.walk_struct_expr(fields, opt_with);
231 hir::ExprKind::Tup(ref exprs) => {
232 self.consume_exprs(exprs);
235 hir::ExprKind::Match(ref discr, ref arms, _) => {
236 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
237 self.borrow_expr(&discr, ty::ImmBorrow);
239 // treatment of the discriminant is handled while walking the arms.
241 self.walk_arm(&discr_place, arm);
245 hir::ExprKind::Array(ref exprs) => {
246 self.consume_exprs(exprs);
249 hir::ExprKind::AddrOf(_, m, ref base) => { // &base
250 // make sure that the thing we are pointing out stays valid
251 // for the lifetime `scope_r` of the resulting ptr:
252 let bk = ty::BorrowKind::from_mutbl(m);
253 self.borrow_expr(&base, bk);
256 hir::ExprKind::InlineAsm(ref ia) => {
257 for (o, output) in ia.inner.outputs.iter().zip(&ia.outputs_exprs) {
259 self.consume_expr(output);
261 self.mutate_expr(output);
264 self.consume_exprs(&ia.inputs_exprs);
267 hir::ExprKind::Continue(..) |
268 hir::ExprKind::Lit(..) |
269 hir::ExprKind::Err => {}
271 hir::ExprKind::Loop(ref blk, _, _) => {
272 self.walk_block(blk);
275 hir::ExprKind::Unary(_, ref lhs) => {
276 self.consume_expr(lhs);
279 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
280 self.consume_expr(lhs);
281 self.consume_expr(rhs);
284 hir::ExprKind::Block(ref blk, _) => {
285 self.walk_block(blk);
288 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
289 if let Some(ref expr) = *opt_expr {
290 self.consume_expr(expr);
294 hir::ExprKind::Assign(ref lhs, ref rhs) => {
295 self.mutate_expr(lhs);
296 self.consume_expr(rhs);
299 hir::ExprKind::Cast(ref base, _) => {
300 self.consume_expr(base);
303 hir::ExprKind::DropTemps(ref expr) => {
304 self.consume_expr(expr);
307 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
308 if self.mc.tables.is_method_call(expr) {
309 self.consume_expr(lhs);
311 self.mutate_expr(lhs);
313 self.consume_expr(rhs);
316 hir::ExprKind::Repeat(ref base, _) => {
317 self.consume_expr(base);
320 hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
321 self.walk_captures(expr, fn_decl_span);
324 hir::ExprKind::Box(ref base) => {
325 self.consume_expr(base);
328 hir::ExprKind::Yield(ref value, _) => {
329 self.consume_expr(value);
334 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
335 let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
336 debug!("walk_callee: callee={:?} callee_ty={:?}",
338 match callee_ty.kind {
339 ty::FnDef(..) | ty::FnPtr(_) => {
340 self.consume_expr(callee);
344 if let Some(def_id) = self.mc.tables.type_dependent_def_id(call.hir_id) {
345 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
346 FnMutOverloadedCall => {
347 self.borrow_expr(callee, ty::MutBorrow);
349 FnOverloadedCall => {
350 self.borrow_expr(callee, ty::ImmBorrow);
352 FnOnceOverloadedCall => self.consume_expr(callee),
355 self.tcx().sess.delay_span_bug(call.span,
356 "no type-dependent def for overloaded call");
362 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
364 hir::StmtKind::Local(ref local) => {
365 self.walk_local(&local);
368 hir::StmtKind::Item(_) => {
369 // We don't visit nested items in this visitor,
370 // only the fn body we were given.
373 hir::StmtKind::Expr(ref expr) |
374 hir::StmtKind::Semi(ref expr) => {
375 self.consume_expr(&expr);
380 fn walk_local(&mut self, local: &hir::Local) {
381 if let Some(ref expr) = local.init {
382 // Variable declarations with
383 // initializers are considered
384 // "assigns", which is handled by
386 self.walk_expr(&expr);
387 let init_place = return_if_err!(self.mc.cat_expr(&expr));
388 self.walk_irrefutable_pat(&init_place, &local.pat);
392 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
393 /// depending on its type.
394 fn walk_block(&mut self, blk: &hir::Block) {
395 debug!("walk_block(blk.hir_id={})", blk.hir_id);
397 for stmt in &blk.stmts {
398 self.walk_stmt(stmt);
401 if let Some(ref tail_expr) = blk.expr {
402 self.consume_expr(&tail_expr);
406 fn walk_struct_expr(&mut self,
407 fields: &[hir::Field],
408 opt_with: &Option<P<hir::Expr>>) {
409 // Consume the expressions supplying values for each field.
410 for field in fields {
411 self.consume_expr(&field.expr);
414 let with_expr = match *opt_with {
419 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
421 // Select just those fields of the `with`
422 // expression that will actually be used
423 match with_place.ty.kind {
424 ty::Adt(adt, substs) if adt.is_struct() => {
425 // Consume those fields of the with expression that are needed.
426 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
427 let is_mentioned = fields.iter().any(|f| {
428 self.tcx().field_index(f.hir_id, self.mc.tables) == f_index
431 let field_place = self.mc.cat_projection(
434 with_field.ty(self.tcx(), substs),
436 self.delegate_consume(&field_place);
441 // the base expression should always evaluate to a
442 // struct; however, when EUV is run during typeck, it
443 // may not. This will generate an error earlier in typeck,
444 // so we can just ignore it.
445 if !self.tcx().sess.has_errors() {
448 "with expression doesn't evaluate to a struct");
453 // walk the with expression so that complex expressions
454 // are properly handled.
455 self.walk_expr(with_expr);
458 // Invoke the appropriate delegate calls for anything that gets
459 // consumed or borrowed as part of the automatic adjustment
461 fn walk_adjustment(&mut self, expr: &hir::Expr) {
462 let adjustments = self.mc.tables.expr_adjustments(expr);
463 let mut place = return_if_err!(self.mc.cat_expr_unadjusted(expr));
464 for adjustment in adjustments {
465 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
466 match adjustment.kind {
467 adjustment::Adjust::NeverToAny |
468 adjustment::Adjust::Pointer(_) => {
469 // Creating a closure/fn-pointer or unsizing consumes
470 // the input and stores it into the resulting rvalue.
471 self.delegate_consume(&place);
474 adjustment::Adjust::Deref(None) => {}
476 // Autoderefs for overloaded Deref calls in fact reference
477 // their receiver. That is, if we have `(*x)` where `x`
478 // is of type `Rc<T>`, then this in fact is equivalent to
479 // `x.deref()`. Since `deref()` is declared with `&self`,
480 // this is an autoref of `x`.
481 adjustment::Adjust::Deref(Some(ref deref)) => {
482 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
483 self.delegate.borrow(&place, bk);
486 adjustment::Adjust::Borrow(ref autoref) => {
487 self.walk_autoref(expr, &place, autoref);
490 place = return_if_err!(self.mc.cat_expr_adjusted(expr, place, &adjustment));
494 /// Walks the autoref `autoref` applied to the autoderef'd
495 /// `expr`. `base_place` is the mem-categorized form of `expr`
496 /// after all relevant autoderefs have occurred.
497 fn walk_autoref(&mut self,
499 base_place: &mc::Place<'tcx>,
500 autoref: &adjustment::AutoBorrow<'tcx>) {
501 debug!("walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
507 adjustment::AutoBorrow::Ref(_, m) => {
508 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
511 adjustment::AutoBorrow::RawPtr(m) => {
512 debug!("walk_autoref: expr.hir_id={} base_place={:?}",
517 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
522 fn walk_arm(&mut self, discr_place: &Place<'tcx>, arm: &hir::Arm) {
523 self.walk_pat(discr_place, &arm.pat);
525 if let Some(hir::Guard::If(ref e)) = arm.guard {
529 self.consume_expr(&arm.body);
532 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
533 /// let binding, and *not* a match arm or nested pat.)
534 fn walk_irrefutable_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat) {
535 self.walk_pat(discr_place, pat);
539 /// The core driver for walking a pattern
540 fn walk_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat) {
541 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
543 let tcx = self.tcx();
544 let ExprUseVisitor { ref mc, ref mut delegate } = *self;
545 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
546 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
548 "walk_pat: binding place={:?} pat={:?}",
552 if let Some(&bm) = mc.tables.pat_binding_modes().get(pat.hir_id) {
553 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
555 // pat_ty: the type of the binding being produced.
556 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
557 debug!("walk_pat: pat_ty={:?}", pat_ty);
559 // Each match binding is effectively an assignment to the
560 // binding being produced.
561 let def = Res::Local(canonical_id);
562 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
563 delegate.mutate(binding_place);
566 // It is also a borrow or copy/move of the value being matched.
568 ty::BindByReference(m) => {
569 let bk = ty::BorrowKind::from_mutbl(m);
570 delegate.borrow(place, bk);
572 ty::BindByValue(..) => {
573 let mode = copy_or_move(mc, place);
574 debug!("walk_pat binding consuming pat");
575 delegate.consume(place, mode);
579 tcx.sess.delay_span_bug(pat.span, "missing binding mode");
585 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
586 debug!("walk_captures({:?})", closure_expr);
588 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
589 if let Some(upvars) = self.tcx().upvars(closure_def_id) {
590 for &var_id in upvars.keys() {
591 let upvar_id = ty::UpvarId {
592 var_path: ty::UpvarPath { hir_id: var_id },
593 closure_expr_id: closure_def_id.to_local(),
595 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
596 let captured_place = return_if_err!(self.cat_captured_var(
601 match upvar_capture {
602 ty::UpvarCapture::ByValue => {
603 let mode = copy_or_move(&self.mc, &captured_place);
604 self.delegate.consume(&captured_place, mode);
606 ty::UpvarCapture::ByRef(upvar_borrow) => {
607 self.delegate.borrow(&captured_place, upvar_borrow.kind);
614 fn cat_captured_var(&mut self,
615 closure_hir_id: hir::HirId,
618 -> mc::McResult<mc::Place<'tcx>> {
619 // Create the place for the variable being borrowed, from the
620 // perspective of the creator (parent) of the closure.
621 let var_ty = self.mc.node_ty(var_id)?;
622 self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
626 fn copy_or_move<'a, 'tcx>(
627 mc: &mc::MemCategorizationContext<'a, 'tcx>,
630 if !mc.type_is_copy_modulo_regions(place.ty, place.span) {