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;
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
29 // on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
31 // The parameter `diag_expr_id` indicates the HIR id that ought to be used for
32 // diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
33 // id will be the id of the expression `expr` but the place itself will have
34 // the id of the binding in the pattern `pat`.
37 place_with_id: &PlaceWithHirId<'tcx>,
38 diag_expr_id: hir::HirId,
42 // The value found at `place` is being borrowed with kind `bk`.
43 // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
46 place_with_id: &PlaceWithHirId<'tcx>,
47 diag_expr_id: hir::HirId,
51 // The path at `assignee_place` is being assigned to.
52 // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
53 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
56 #[derive(Copy, Clone, PartialEq, Debug)]
57 pub enum ConsumeMode {
58 Copy, // reference to x where x has a type that copies
59 Move, // reference to x where x has a type that moves
62 #[derive(Copy, Clone, PartialEq, Debug)]
66 WriteAndRead, // x += y
69 ///////////////////////////////////////////////////////////////////////////
70 // The ExprUseVisitor type
72 // This is the code that actually walks the tree.
73 pub struct ExprUseVisitor<'a, 'tcx> {
74 mc: mc::MemCategorizationContext<'a, 'tcx>,
75 body_owner: LocalDefId,
76 delegate: &'a mut dyn Delegate<'tcx>,
79 // If the MC results in an error, it's because the type check
80 // failed (or will fail, when the error is uncovered and reported
81 // during writeback). In this case, we just ignore this part of the
84 // Note that this macro appears similar to try!(), but, unlike try!(),
85 // it does not propagate the error.
86 macro_rules! return_if_err {
91 debug!("mc reported err");
98 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
99 /// Creates the ExprUseVisitor, configuring it with the various options provided:
101 /// - `delegate` -- who receives the callbacks
102 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
103 /// - `typeck_results` --- typeck results for the code being analyzed
105 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
106 infcx: &'a InferCtxt<'a, 'tcx>,
107 body_owner: LocalDefId,
108 param_env: ty::ParamEnv<'tcx>,
109 typeck_results: &'a ty::TypeckResults<'tcx>,
112 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
118 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
119 debug!("consume_body(body={:?})", body);
121 for param in body.params {
122 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
123 debug!("consume_body: param_ty = {:?}", param_ty);
125 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
127 self.walk_irrefutable_pat(¶m_place, ¶m.pat);
130 self.consume_expr(&body.value);
133 fn tcx(&self) -> TyCtxt<'tcx> {
137 fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
138 debug!("delegate_consume(place_with_id={:?})", place_with_id);
140 let mode = copy_or_move(&self.mc, place_with_id);
141 self.delegate.consume(place_with_id, diag_expr_id, mode);
144 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
146 self.consume_expr(&expr);
150 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
151 debug!("consume_expr(expr={:?})", expr);
153 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
154 self.delegate_consume(&place_with_id, place_with_id.hir_id);
155 self.walk_expr(expr);
158 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
159 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
160 self.delegate.mutate(&place_with_id, place_with_id.hir_id);
161 self.walk_expr(expr);
164 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
165 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
167 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
168 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
173 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
177 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
178 debug!("walk_expr(expr={:?})", expr);
180 self.walk_adjustment(expr);
183 hir::ExprKind::Path(_) => {}
185 hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
187 hir::ExprKind::Unary(hir::UnOp::Deref, ref base) => {
189 self.select_from_expr(base);
192 hir::ExprKind::Field(ref base, _) => {
194 self.select_from_expr(base);
197 hir::ExprKind::Index(ref lhs, ref rhs) => {
199 self.select_from_expr(lhs);
200 self.consume_expr(rhs);
203 hir::ExprKind::Call(ref callee, ref args) => {
205 self.consume_expr(callee);
206 self.consume_exprs(args);
209 hir::ExprKind::MethodCall(.., ref args, _) => {
211 self.consume_exprs(args);
214 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
215 self.walk_struct_expr(fields, opt_with);
218 hir::ExprKind::Tup(ref exprs) => {
219 self.consume_exprs(exprs);
222 hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
223 self.consume_expr(&cond_expr);
224 self.consume_expr(&then_expr);
225 if let Some(ref else_expr) = *opt_else_expr {
226 self.consume_expr(&else_expr);
230 hir::ExprKind::Match(ref discr, arms, _) => {
231 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
232 self.borrow_expr(&discr, ty::ImmBorrow);
234 // treatment of the discriminant is handled while walking the arms.
236 self.walk_arm(&discr_place, arm);
240 hir::ExprKind::Array(ref exprs) => {
241 self.consume_exprs(exprs);
244 hir::ExprKind::AddrOf(_, m, ref base) => {
246 // make sure that the thing we are pointing out stays valid
247 // for the lifetime `scope_r` of the resulting ptr:
248 let bk = ty::BorrowKind::from_mutbl(m);
249 self.borrow_expr(&base, bk);
252 hir::ExprKind::InlineAsm(ref asm) => {
253 for (op, _op_sp) in asm.operands {
255 hir::InlineAsmOperand::In { expr, .. }
256 | hir::InlineAsmOperand::Const { expr, .. }
257 | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
258 hir::InlineAsmOperand::Out { expr, .. } => {
259 if let Some(expr) = expr {
260 self.mutate_expr(expr);
263 hir::InlineAsmOperand::InOut { expr, .. } => {
264 self.mutate_expr(expr);
266 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
267 self.consume_expr(in_expr);
268 if let Some(out_expr) = out_expr {
269 self.mutate_expr(out_expr);
276 hir::ExprKind::LlvmInlineAsm(ref ia) => {
277 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
279 self.consume_expr(output);
281 self.mutate_expr(output);
284 self.consume_exprs(&ia.inputs_exprs);
287 hir::ExprKind::Continue(..)
288 | hir::ExprKind::Lit(..)
289 | hir::ExprKind::ConstBlock(..)
290 | hir::ExprKind::Err => {}
292 hir::ExprKind::Loop(ref blk, ..) => {
293 self.walk_block(blk);
296 hir::ExprKind::Unary(_, ref lhs) => {
297 self.consume_expr(lhs);
300 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
301 self.consume_expr(lhs);
302 self.consume_expr(rhs);
305 hir::ExprKind::Block(ref blk, _) => {
306 self.walk_block(blk);
309 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
310 if let Some(ref expr) = *opt_expr {
311 self.consume_expr(expr);
315 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
316 self.mutate_expr(lhs);
317 self.consume_expr(rhs);
320 hir::ExprKind::Cast(ref base, _) => {
321 self.consume_expr(base);
324 hir::ExprKind::DropTemps(ref expr) => {
325 self.consume_expr(expr);
328 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
329 if self.mc.typeck_results.is_method_call(expr) {
330 self.consume_expr(lhs);
332 self.mutate_expr(lhs);
334 self.consume_expr(rhs);
337 hir::ExprKind::Repeat(ref base, _) => {
338 self.consume_expr(base);
341 hir::ExprKind::Closure(..) => {
342 self.walk_captures(expr);
345 hir::ExprKind::Box(ref base) => {
346 self.consume_expr(base);
349 hir::ExprKind::Yield(ref value, _) => {
350 self.consume_expr(value);
355 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
357 hir::StmtKind::Local(ref local) => {
358 self.walk_local(&local);
361 hir::StmtKind::Item(_) => {
362 // We don't visit nested items in this visitor,
363 // only the fn body we were given.
366 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
367 self.consume_expr(&expr);
372 fn walk_local(&mut self, local: &hir::Local<'_>) {
373 if let Some(ref expr) = local.init {
374 // Variable declarations with
375 // initializers are considered
376 // "assigns", which is handled by
378 self.walk_expr(&expr);
379 let init_place = return_if_err!(self.mc.cat_expr(&expr));
380 self.walk_irrefutable_pat(&init_place, &local.pat);
384 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
385 /// depending on its type.
386 fn walk_block(&mut self, blk: &hir::Block<'_>) {
387 debug!("walk_block(blk.hir_id={})", blk.hir_id);
389 for stmt in blk.stmts {
390 self.walk_stmt(stmt);
393 if let Some(ref tail_expr) = blk.expr {
394 self.consume_expr(&tail_expr);
400 fields: &[hir::Field<'_>],
401 opt_with: &Option<&'hir hir::Expr<'_>>,
403 // Consume the expressions supplying values for each field.
404 for field in fields {
405 self.consume_expr(&field.expr);
408 let with_expr = match *opt_with {
415 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
417 // Select just those fields of the `with`
418 // expression that will actually be used
419 match with_place.place.ty().kind() {
420 ty::Adt(adt, substs) if adt.is_struct() => {
421 // Consume those fields of the with expression that are needed.
422 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
423 let is_mentioned = fields.iter().any(|f| {
424 self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
427 let field_place = self.mc.cat_projection(
430 with_field.ty(self.tcx(), substs),
431 ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
433 self.delegate_consume(&field_place, field_place.hir_id);
438 // the base expression should always evaluate to a
439 // struct; however, when EUV is run during typeck, it
440 // may not. This will generate an error earlier in typeck,
441 // so we can just ignore it.
442 if !self.tcx().sess.has_errors() {
443 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
448 // walk the with expression so that complex expressions
449 // are properly handled.
450 self.walk_expr(with_expr);
453 // Invoke the appropriate delegate calls for anything that gets
454 // consumed or borrowed as part of the automatic adjustment
456 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
457 let adjustments = self.mc.typeck_results.expr_adjustments(expr);
458 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
459 for adjustment in adjustments {
460 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
461 match adjustment.kind {
462 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
463 // Creating a closure/fn-pointer or unsizing consumes
464 // the input and stores it into the resulting rvalue.
465 self.delegate_consume(&place_with_id, place_with_id.hir_id);
468 adjustment::Adjust::Deref(None) => {}
470 // Autoderefs for overloaded Deref calls in fact reference
471 // their receiver. That is, if we have `(*x)` where `x`
472 // is of type `Rc<T>`, then this in fact is equivalent to
473 // `x.deref()`. Since `deref()` is declared with `&self`,
474 // this is an autoref of `x`.
475 adjustment::Adjust::Deref(Some(ref deref)) => {
476 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
477 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
480 adjustment::Adjust::Borrow(ref autoref) => {
481 self.walk_autoref(expr, &place_with_id, autoref);
485 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &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: &PlaceWithHirId<'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(
508 ty::BorrowKind::from_mutbl(m.into()),
512 adjustment::AutoBorrow::RawPtr(m) => {
513 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
515 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
520 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
521 self.walk_pat(discr_place, &arm.pat);
523 if let Some(hir::Guard::If(ref e)) = arm.guard {
527 self.consume_expr(&arm.body);
530 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
531 /// let binding, and *not* a match arm or nested pat.)
532 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
533 self.walk_pat(discr_place, pat);
536 /// The core driver for walking a pattern
537 fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
538 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
540 let tcx = self.tcx();
541 let ExprUseVisitor { ref mc, body_owner: _, ref mut delegate } = *self;
542 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
543 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
544 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
546 mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
548 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
550 // pat_ty: the type of the binding being produced.
551 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
552 debug!("walk_pat: pat_ty={:?}", pat_ty);
554 // Each match binding is effectively an assignment to the
555 // binding being produced.
556 let def = Res::Local(canonical_id);
557 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
558 delegate.mutate(binding_place, binding_place.hir_id);
561 // It is also a borrow or copy/move of the value being matched.
562 // In a cases of pattern like `let pat = upvar`, don't use the span
563 // of the pattern, as this just looks confusing, instead use the span
564 // of the discriminant.
566 ty::BindByReference(m) => {
567 let bk = ty::BorrowKind::from_mutbl(m);
568 delegate.borrow(place, discr_place.hir_id, bk);
570 ty::BindByValue(..) => {
571 let mode = copy_or_move(mc, &place);
572 debug!("walk_pat binding consuming pat");
573 delegate.consume(place, discr_place.hir_id, mode);
581 /// Handle the case where the current body contains a closure.
583 /// When the current body being handled is a closure, then we must make sure that
584 /// - The parent closure only captures Places from the nested closure that are not local to it.
586 /// In the following example the closures `c` only captures `p.x`` even though `incr`
587 /// is a capture of the nested closure
589 /// ```rust,ignore(cannot-test-this-because-pseduo-code)
593 /// let nested = || p.x += incr;
597 /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
598 /// closure as the DefId.
599 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>) {
600 debug!("walk_captures({:?})", closure_expr);
602 let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id).to_def_id();
603 let upvars = self.tcx().upvars_mentioned(self.body_owner);
605 // For purposes of this function, generator and closures are equivalent.
606 let body_owner_is_closure = matches!(
607 self.tcx().type_of(self.body_owner.to_def_id()).kind(),
608 ty::Closure(..) | ty::Generator(..)
611 if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
613 for (var_hir_id, min_list) in min_captures.iter() {
614 if upvars.map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id)) {
615 // The nested closure might be capturing the current (enclosing) closure's local variables.
616 // We check if the root variable is ever mentioned within the enclosing closure, if not
617 // then for the current body (if it's a closure) these aren't captures, we will ignore them.
620 for captured_place in min_list {
621 let place = &captured_place.place;
622 let capture_info = captured_place.info;
624 let place_base = if body_owner_is_closure {
625 // Mark the place to be captured by the enclosing closure
626 PlaceBase::Upvar(ty::UpvarId::new(*var_hir_id, self.body_owner))
628 // If the body owner isn't a closure then the variable must
629 // be a local variable
630 PlaceBase::Local(*var_hir_id)
632 let place_with_id = PlaceWithHirId::new(
633 capture_info.path_expr_id.unwrap_or(closure_expr.hir_id),
636 place.projections.clone(),
639 match capture_info.capture_kind {
640 ty::UpvarCapture::ByValue(_) => {
641 let mode = copy_or_move(&self.mc, &place_with_id);
642 self.delegate.consume(&place_with_id, place_with_id.hir_id, mode);
644 ty::UpvarCapture::ByRef(upvar_borrow) => {
645 self.delegate.borrow(
647 place_with_id.hir_id,
658 fn copy_or_move<'a, 'tcx>(
659 mc: &mc::MemCategorizationContext<'a, 'tcx>,
660 place_with_id: &PlaceWithHirId<'tcx>,
662 if !mc.type_is_copy_modulo_regions(
663 place_with_id.place.ty(),
664 mc.tcx().hir().span(place_with_id.hir_id),