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 use crate::hir::def::Res;
9 use crate::hir::def_id::DefId;
10 use crate::hir::ptr::P;
11 use crate::infer::InferCtxt;
12 use crate::middle::mem_categorization as mc;
13 use crate::middle::region;
14 use crate::ty::{self, TyCtxt, adjustment};
16 use crate::hir::{self, PatKind};
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 `cmt` is either copied or moved, depending
28 fn consume(&mut self, cmt: &mc::cmt_<'tcx>, mode: ConsumeMode);
30 // The value found at `cmt` is being borrowed with kind `bk`.
31 fn borrow(&mut self, cmt: &mc::cmt_<'tcx>, bk: ty::BorrowKind);
33 // The path at `cmt` is being assigned to.
34 fn mutate(&mut self, assignee_cmt: &mc::cmt_<'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 #[derive(Copy, Clone)]
51 enum OverloadedCallType {
57 impl OverloadedCallType {
58 fn from_trait_id(tcx: TyCtxt<'_>, trait_id: DefId) -> OverloadedCallType {
59 for &(maybe_function_trait, overloaded_call_type) in &[
60 (tcx.lang_items().fn_once_trait(), FnOnceOverloadedCall),
61 (tcx.lang_items().fn_mut_trait(), FnMutOverloadedCall),
62 (tcx.lang_items().fn_trait(), FnOverloadedCall)
64 match maybe_function_trait {
65 Some(function_trait) if function_trait == trait_id => {
66 return overloaded_call_type
72 bug!("overloaded call didn't map to known function trait")
75 fn from_method_id(tcx: TyCtxt<'_>, method_id: DefId) -> OverloadedCallType {
76 let method = tcx.associated_item(method_id);
77 OverloadedCallType::from_trait_id(tcx, method.container.id())
81 ///////////////////////////////////////////////////////////////////////////
82 // The ExprUseVisitor type
84 // This is the code that actually walks the tree.
85 pub struct ExprUseVisitor<'a, 'tcx> {
86 mc: mc::MemCategorizationContext<'a, 'tcx>,
87 delegate: &'a mut dyn Delegate<'tcx>,
88 param_env: ty::ParamEnv<'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 /// - `region_scope_tree` --- region scope tree for the code being analyzed
116 /// - `tables` --- typeck results for the code being analyzed
118 /// See also `with_infer`, which is used *during* typeck.
120 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
123 param_env: ty::ParamEnv<'tcx>,
124 region_scope_tree: &'a region::ScopeTree,
125 tables: &'a ty::TypeckTables<'tcx>,
128 mc: mc::MemCategorizationContext::new(tcx,
139 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
141 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
142 infcx: &'a InferCtxt<'a, 'tcx>,
144 param_env: ty::ParamEnv<'tcx>,
145 region_scope_tree: &'a region::ScopeTree,
146 tables: &'a ty::TypeckTables<'tcx>,
149 mc: mc::MemCategorizationContext::with_infer(
161 pub fn consume_body(&mut self, body: &hir::Body) {
162 debug!("consume_body(body={:?})", body);
164 for param in &body.params {
165 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
166 debug!("consume_body: param_ty = {:?}", param_ty);
168 let param_cmt = Rc::new(self.mc.cat_rvalue(
173 self.walk_irrefutable_pat(param_cmt, ¶m.pat);
176 self.consume_expr(&body.value);
179 fn tcx(&self) -> TyCtxt<'tcx> {
183 fn delegate_consume(&mut self, cmt: &mc::cmt_<'tcx>) {
184 debug!("delegate_consume(cmt={:?})", cmt);
186 let mode = copy_or_move(&self.mc, self.param_env, cmt);
187 self.delegate.consume(cmt, mode);
190 fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
192 self.consume_expr(&expr);
196 pub fn consume_expr(&mut self, expr: &hir::Expr) {
197 debug!("consume_expr(expr={:?})", expr);
199 let cmt = return_if_err!(self.mc.cat_expr(expr));
200 self.delegate_consume(&cmt);
201 self.walk_expr(expr);
204 fn mutate_expr(&mut self, expr: &hir::Expr) {
205 let cmt = return_if_err!(self.mc.cat_expr(expr));
206 self.delegate.mutate(&cmt);
207 self.walk_expr(expr);
210 fn borrow_expr(&mut self, expr: &hir::Expr, bk: ty::BorrowKind) {
211 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
213 let cmt = return_if_err!(self.mc.cat_expr(expr));
214 self.delegate.borrow(&cmt, bk);
219 fn select_from_expr(&mut self, expr: &hir::Expr) {
223 pub fn walk_expr(&mut self, expr: &hir::Expr) {
224 debug!("walk_expr(expr={:?})", expr);
226 self.walk_adjustment(expr);
229 hir::ExprKind::Path(_) => { }
231 hir::ExprKind::Type(ref subexpr, _) => {
232 self.walk_expr(subexpr)
235 hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base
236 self.select_from_expr(base);
239 hir::ExprKind::Field(ref base, _) => { // base.f
240 self.select_from_expr(base);
243 hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs]
244 self.select_from_expr(lhs);
245 self.consume_expr(rhs);
248 hir::ExprKind::Call(ref callee, ref args) => { // callee(args)
249 self.walk_callee(expr, callee);
250 self.consume_exprs(args);
253 hir::ExprKind::MethodCall(.., ref args) => { // callee.m(args)
254 self.consume_exprs(args);
257 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
258 self.walk_struct_expr(fields, opt_with);
261 hir::ExprKind::Tup(ref exprs) => {
262 self.consume_exprs(exprs);
265 hir::ExprKind::Match(ref discr, ref arms, _) => {
266 let discr_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&discr)));
267 self.borrow_expr(&discr, ty::ImmBorrow);
269 // treatment of the discriminant is handled while walking the arms.
271 self.walk_arm(discr_cmt.clone(), arm);
275 hir::ExprKind::Array(ref exprs) => {
276 self.consume_exprs(exprs);
279 hir::ExprKind::AddrOf(m, ref base) => { // &base
280 // make sure that the thing we are pointing out stays valid
281 // for the lifetime `scope_r` of the resulting ptr:
282 let bk = ty::BorrowKind::from_mutbl(m);
283 self.borrow_expr(&base, bk);
286 hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => {
287 for (o, output) in ia.outputs.iter().zip(outputs) {
289 self.consume_expr(output);
291 self.mutate_expr(output);
294 self.consume_exprs(inputs);
297 hir::ExprKind::Continue(..) |
298 hir::ExprKind::Lit(..) |
299 hir::ExprKind::Err => {}
301 hir::ExprKind::Loop(ref blk, _, _) => {
302 self.walk_block(blk);
305 hir::ExprKind::Unary(_, ref lhs) => {
306 self.consume_expr(lhs);
309 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
310 self.consume_expr(lhs);
311 self.consume_expr(rhs);
314 hir::ExprKind::Block(ref blk, _) => {
315 self.walk_block(blk);
318 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
319 if let Some(ref expr) = *opt_expr {
320 self.consume_expr(expr);
324 hir::ExprKind::Assign(ref lhs, ref rhs) => {
325 self.mutate_expr(lhs);
326 self.consume_expr(rhs);
329 hir::ExprKind::Cast(ref base, _) => {
330 self.consume_expr(base);
333 hir::ExprKind::DropTemps(ref expr) => {
334 self.consume_expr(expr);
337 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
338 if self.mc.tables.is_method_call(expr) {
339 self.consume_expr(lhs);
341 self.mutate_expr(lhs);
343 self.consume_expr(rhs);
346 hir::ExprKind::Repeat(ref base, _) => {
347 self.consume_expr(base);
350 hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
351 self.walk_captures(expr, fn_decl_span);
354 hir::ExprKind::Box(ref base) => {
355 self.consume_expr(base);
358 hir::ExprKind::Yield(ref value, _) => {
359 self.consume_expr(value);
364 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
365 let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
366 debug!("walk_callee: callee={:?} callee_ty={:?}",
368 match callee_ty.kind {
369 ty::FnDef(..) | ty::FnPtr(_) => {
370 self.consume_expr(callee);
374 if let Some(def_id) = self.mc.tables.type_dependent_def_id(call.hir_id) {
375 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
376 FnMutOverloadedCall => {
377 self.borrow_expr(callee, ty::MutBorrow);
379 FnOverloadedCall => {
380 self.borrow_expr(callee, ty::ImmBorrow);
382 FnOnceOverloadedCall => self.consume_expr(callee),
385 self.tcx().sess.delay_span_bug(call.span,
386 "no type-dependent def for overloaded call");
392 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
394 hir::StmtKind::Local(ref local) => {
395 self.walk_local(&local);
398 hir::StmtKind::Item(_) => {
399 // We don't visit nested items in this visitor,
400 // only the fn body we were given.
403 hir::StmtKind::Expr(ref expr) |
404 hir::StmtKind::Semi(ref expr) => {
405 self.consume_expr(&expr);
410 fn walk_local(&mut self, local: &hir::Local) {
411 if let Some(ref expr) = local.init {
412 // Variable declarations with
413 // initializers are considered
414 // "assigns", which is handled by
416 self.walk_expr(&expr);
417 let init_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&expr)));
418 self.walk_irrefutable_pat(init_cmt, &local.pat);
422 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
423 /// depending on its type.
424 fn walk_block(&mut self, blk: &hir::Block) {
425 debug!("walk_block(blk.hir_id={})", blk.hir_id);
427 for stmt in &blk.stmts {
428 self.walk_stmt(stmt);
431 if let Some(ref tail_expr) = blk.expr {
432 self.consume_expr(&tail_expr);
436 fn walk_struct_expr(&mut self,
437 fields: &[hir::Field],
438 opt_with: &Option<P<hir::Expr>>) {
439 // Consume the expressions supplying values for each field.
440 for field in fields {
441 self.consume_expr(&field.expr);
444 let with_expr = match *opt_with {
449 let with_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&with_expr)));
451 // Select just those fields of the `with`
452 // expression that will actually be used
453 match with_cmt.ty.kind {
454 ty::Adt(adt, substs) if adt.is_struct() => {
455 // Consume those fields of the with expression that are needed.
456 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
457 let is_mentioned = fields.iter().any(|f| {
458 self.tcx().field_index(f.hir_id, self.mc.tables) == f_index
461 let cmt_field = self.mc.cat_field(
466 with_field.ty(self.tcx(), substs)
468 self.delegate_consume(&cmt_field);
473 // the base expression should always evaluate to a
474 // struct; however, when EUV is run during typeck, it
475 // may not. This will generate an error earlier in typeck,
476 // so we can just ignore it.
477 if !self.tcx().sess.has_errors() {
480 "with expression doesn't evaluate to a struct");
485 // walk the with expression so that complex expressions
486 // are properly handled.
487 self.walk_expr(with_expr);
490 // Invoke the appropriate delegate calls for anything that gets
491 // consumed or borrowed as part of the automatic adjustment
493 fn walk_adjustment(&mut self, expr: &hir::Expr) {
494 let adjustments = self.mc.tables.expr_adjustments(expr);
495 let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
496 for adjustment in adjustments {
497 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
498 match adjustment.kind {
499 adjustment::Adjust::NeverToAny |
500 adjustment::Adjust::Pointer(_) => {
501 // Creating a closure/fn-pointer or unsizing consumes
502 // the input and stores it into the resulting rvalue.
503 self.delegate_consume(&cmt);
506 adjustment::Adjust::Deref(None) => {}
508 // Autoderefs for overloaded Deref calls in fact reference
509 // their receiver. That is, if we have `(*x)` where `x`
510 // is of type `Rc<T>`, then this in fact is equivalent to
511 // `x.deref()`. Since `deref()` is declared with `&self`,
512 // this is an autoref of `x`.
513 adjustment::Adjust::Deref(Some(ref deref)) => {
514 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
515 self.delegate.borrow(&cmt, bk);
518 adjustment::Adjust::Borrow(ref autoref) => {
519 self.walk_autoref(expr, &cmt, autoref);
522 cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
526 /// Walks the autoref `autoref` applied to the autoderef'd
527 /// `expr`. `cmt_base` is the mem-categorized form of `expr`
528 /// after all relevant autoderefs have occurred.
529 fn walk_autoref(&mut self,
531 cmt_base: &mc::cmt_<'tcx>,
532 autoref: &adjustment::AutoBorrow<'tcx>) {
533 debug!("walk_autoref(expr.hir_id={} cmt_base={:?} autoref={:?})",
539 adjustment::AutoBorrow::Ref(_, m) => {
540 self.delegate.borrow(cmt_base, ty::BorrowKind::from_mutbl(m.into()));
543 adjustment::AutoBorrow::RawPtr(m) => {
544 debug!("walk_autoref: expr.hir_id={} cmt_base={:?}",
549 self.delegate.borrow(cmt_base, ty::BorrowKind::from_mutbl(m));
554 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) {
555 self.walk_pat(discr_cmt.clone(), &arm.pat);
557 if let Some(hir::Guard::If(ref e)) = arm.guard {
561 self.consume_expr(&arm.body);
564 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
565 /// let binding, and *not* a match arm or nested pat.)
566 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
567 self.walk_pat(cmt_discr, pat);
571 /// The core driver for walking a pattern
572 fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
573 debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat);
575 let tcx = self.tcx();
576 let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
577 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| {
578 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
580 "walk_pat: binding cmt_pat={:?} pat={:?}",
584 if let Some(&bm) = mc.tables.pat_binding_modes().get(pat.hir_id) {
585 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
587 // pat_ty: the type of the binding being produced.
588 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
589 debug!("walk_pat: pat_ty={:?}", pat_ty);
591 // Each match binding is effectively an assignment to the
592 // binding being produced.
593 let def = Res::Local(canonical_id);
594 if let Ok(ref binding_cmt) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
595 delegate.mutate(binding_cmt);
598 // It is also a borrow or copy/move of the value being matched.
600 ty::BindByReference(m) => {
601 let bk = ty::BorrowKind::from_mutbl(m);
602 delegate.borrow(&cmt_pat, bk);
604 ty::BindByValue(..) => {
605 let mode = copy_or_move(mc, param_env, &cmt_pat);
606 debug!("walk_pat binding consuming pat");
607 delegate.consume(&cmt_pat, mode);
611 tcx.sess.delay_span_bug(pat.span, "missing binding mode");
617 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
618 debug!("walk_captures({:?})", closure_expr);
620 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
621 if let Some(upvars) = self.tcx().upvars(closure_def_id) {
622 for &var_id in upvars.keys() {
623 let upvar_id = ty::UpvarId {
624 var_path: ty::UpvarPath { hir_id: var_id },
625 closure_expr_id: closure_def_id.to_local(),
627 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
628 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.hir_id,
631 match upvar_capture {
632 ty::UpvarCapture::ByValue => {
633 let mode = copy_or_move(&self.mc, self.param_env, &cmt_var);
634 self.delegate.consume(&cmt_var, mode);
636 ty::UpvarCapture::ByRef(upvar_borrow) => {
637 self.delegate.borrow(&cmt_var, upvar_borrow.kind);
644 fn cat_captured_var(&mut self,
645 closure_hir_id: hir::HirId,
648 -> mc::McResult<mc::cmt_<'tcx>> {
649 // Create the cmt for the variable being borrowed, from the
650 // perspective of the creator (parent) of the closure.
651 let var_ty = self.mc.node_ty(var_id)?;
652 self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
656 fn copy_or_move<'a, 'tcx>(
657 mc: &mc::MemCategorizationContext<'a, 'tcx>,
658 param_env: ty::ParamEnv<'tcx>,
659 cmt: &mc::cmt_<'tcx>,
661 if !mc.type_is_copy_modulo_regions(param_env, cmt.ty, cmt.span) {