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;
23 ///////////////////////////////////////////////////////////////////////////
26 /// This trait defines the callbacks you can expect to receive when
27 /// employing the ExprUseVisitor.
28 pub trait Delegate<'tcx> {
29 // The value found at `place` is either copied or moved, depending
30 // on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
32 // The parameter `diag_expr_id` indicates the HIR id that ought to be used for
33 // diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
34 // id will be the id of the expression `expr` but the place itself will have
35 // the id of the binding in the pattern `pat`.
38 place_with_id: &PlaceWithHirId<'tcx>,
39 diag_expr_id: hir::HirId,
43 // The value found at `place` is being borrowed with kind `bk`.
44 // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
47 place_with_id: &PlaceWithHirId<'tcx>,
48 diag_expr_id: hir::HirId,
52 // The path at `assignee_place` is being assigned to.
53 // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
54 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
57 #[derive(Copy, Clone, PartialEq, Debug)]
58 pub enum ConsumeMode {
59 Copy, // reference to x where x has a type that copies
60 Move, // reference to x where x has a type that moves
63 #[derive(Copy, Clone, PartialEq, Debug)]
67 WriteAndRead, // x += y
70 ///////////////////////////////////////////////////////////////////////////
71 // The ExprUseVisitor type
73 // This is the code that actually walks the tree.
74 pub struct ExprUseVisitor<'a, 'tcx> {
75 mc: mc::MemCategorizationContext<'a, 'tcx>,
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),
117 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
118 debug!("consume_body(body={:?})", body);
120 for param in body.params {
121 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat));
122 debug!("consume_body: param_ty = {:?}", param_ty);
124 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
126 self.walk_irrefutable_pat(¶m_place, ¶m.pat);
129 self.consume_expr(&body.value);
132 fn tcx(&self) -> TyCtxt<'tcx> {
136 fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
137 debug!("delegate_consume(place_with_id={:?})", place_with_id);
139 let mode = copy_or_move(&self.mc, place_with_id);
140 self.delegate.consume(place_with_id, diag_expr_id, mode);
143 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
145 self.consume_expr(&expr);
149 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
150 debug!("consume_expr(expr={:?})", expr);
152 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
153 self.delegate_consume(&place_with_id, place_with_id.hir_id);
154 self.walk_expr(expr);
157 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
158 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
159 self.delegate.mutate(&place_with_id, place_with_id.hir_id);
160 self.walk_expr(expr);
163 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
164 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
166 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
167 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
172 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
176 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
177 debug!("walk_expr(expr={:?})", expr);
179 self.walk_adjustment(expr);
182 hir::ExprKind::Path(_) => {}
184 hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
186 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
188 self.select_from_expr(base);
191 hir::ExprKind::Field(ref base, _) => {
193 self.select_from_expr(base);
196 hir::ExprKind::Index(ref lhs, ref rhs) => {
198 self.select_from_expr(lhs);
199 self.consume_expr(rhs);
202 hir::ExprKind::Call(ref callee, ref args) => {
204 self.consume_expr(callee);
205 self.consume_exprs(args);
208 hir::ExprKind::MethodCall(.., ref args, _) => {
210 self.consume_exprs(args);
213 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
214 self.walk_struct_expr(fields, opt_with);
217 hir::ExprKind::Tup(ref exprs) => {
218 self.consume_exprs(exprs);
221 hir::ExprKind::Match(ref discr, arms, _) => {
222 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
223 self.borrow_expr(&discr, ty::ImmBorrow);
225 // treatment of the discriminant is handled while walking the arms.
227 self.walk_arm(&discr_place, arm);
231 hir::ExprKind::Array(ref exprs) => {
232 self.consume_exprs(exprs);
235 hir::ExprKind::AddrOf(_, m, ref base) => {
237 // make sure that the thing we are pointing out stays valid
238 // for the lifetime `scope_r` of the resulting ptr:
239 let bk = ty::BorrowKind::from_mutbl(m);
240 self.borrow_expr(&base, bk);
243 hir::ExprKind::InlineAsm(ref asm) => {
244 for op in asm.operands {
246 hir::InlineAsmOperand::In { expr, .. }
247 | hir::InlineAsmOperand::Const { expr, .. }
248 | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
249 hir::InlineAsmOperand::Out { expr, .. } => {
250 if let Some(expr) = expr {
251 self.mutate_expr(expr);
254 hir::InlineAsmOperand::InOut { expr, .. } => {
255 self.mutate_expr(expr);
257 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
258 self.consume_expr(in_expr);
259 if let Some(out_expr) = out_expr {
260 self.mutate_expr(out_expr);
267 hir::ExprKind::LlvmInlineAsm(ref ia) => {
268 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
270 self.consume_expr(output);
272 self.mutate_expr(output);
275 self.consume_exprs(&ia.inputs_exprs);
278 hir::ExprKind::Continue(..)
279 | hir::ExprKind::Lit(..)
280 | hir::ExprKind::ConstBlock(..)
281 | hir::ExprKind::Err => {}
283 hir::ExprKind::Loop(ref blk, _, _) => {
284 self.walk_block(blk);
287 hir::ExprKind::Unary(_, ref lhs) => {
288 self.consume_expr(lhs);
291 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
292 self.consume_expr(lhs);
293 self.consume_expr(rhs);
296 hir::ExprKind::Block(ref blk, _) => {
297 self.walk_block(blk);
300 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
301 if let Some(ref expr) = *opt_expr {
302 self.consume_expr(expr);
306 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
307 self.mutate_expr(lhs);
308 self.consume_expr(rhs);
311 hir::ExprKind::Cast(ref base, _) => {
312 self.consume_expr(base);
315 hir::ExprKind::DropTemps(ref expr) => {
316 self.consume_expr(expr);
319 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
320 if self.mc.typeck_results.is_method_call(expr) {
321 self.consume_expr(lhs);
323 self.mutate_expr(lhs);
325 self.consume_expr(rhs);
328 hir::ExprKind::Repeat(ref base, _) => {
329 self.consume_expr(base);
332 hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
333 self.walk_captures(expr, fn_decl_span);
336 hir::ExprKind::Box(ref base) => {
337 self.consume_expr(base);
340 hir::ExprKind::Yield(ref value, _) => {
341 self.consume_expr(value);
346 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
348 hir::StmtKind::Local(ref local) => {
349 self.walk_local(&local);
352 hir::StmtKind::Item(_) => {
353 // We don't visit nested items in this visitor,
354 // only the fn body we were given.
357 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
358 self.consume_expr(&expr);
363 fn walk_local(&mut self, local: &hir::Local<'_>) {
364 if let Some(ref expr) = local.init {
365 // Variable declarations with
366 // initializers are considered
367 // "assigns", which is handled by
369 self.walk_expr(&expr);
370 let init_place = return_if_err!(self.mc.cat_expr(&expr));
371 self.walk_irrefutable_pat(&init_place, &local.pat);
375 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
376 /// depending on its type.
377 fn walk_block(&mut self, blk: &hir::Block<'_>) {
378 debug!("walk_block(blk.hir_id={})", blk.hir_id);
380 for stmt in blk.stmts {
381 self.walk_stmt(stmt);
384 if let Some(ref tail_expr) = blk.expr {
385 self.consume_expr(&tail_expr);
391 fields: &[hir::Field<'_>],
392 opt_with: &Option<&'hir hir::Expr<'_>>,
394 // Consume the expressions supplying values for each field.
395 for field in fields {
396 self.consume_expr(&field.expr);
399 let with_expr = match *opt_with {
406 let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
408 // Select just those fields of the `with`
409 // expression that will actually be used
410 match with_place.place.ty().kind() {
411 ty::Adt(adt, substs) if adt.is_struct() => {
412 // Consume those fields of the with expression that are needed.
413 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
414 let is_mentioned = fields.iter().any(|f| {
415 self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
418 let field_place = self.mc.cat_projection(
421 with_field.ty(self.tcx(), substs),
422 ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
424 self.delegate_consume(&field_place, field_place.hir_id);
429 // the base expression should always evaluate to a
430 // struct; however, when EUV is run during typeck, it
431 // may not. This will generate an error earlier in typeck,
432 // so we can just ignore it.
433 if !self.tcx().sess.has_errors() {
434 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
439 // walk the with expression so that complex expressions
440 // are properly handled.
441 self.walk_expr(with_expr);
444 // Invoke the appropriate delegate calls for anything that gets
445 // consumed or borrowed as part of the automatic adjustment
447 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
448 let adjustments = self.mc.typeck_results.expr_adjustments(expr);
449 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
450 for adjustment in adjustments {
451 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
452 match adjustment.kind {
453 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
454 // Creating a closure/fn-pointer or unsizing consumes
455 // the input and stores it into the resulting rvalue.
456 self.delegate_consume(&place_with_id, place_with_id.hir_id);
459 adjustment::Adjust::Deref(None) => {}
461 // Autoderefs for overloaded Deref calls in fact reference
462 // their receiver. That is, if we have `(*x)` where `x`
463 // is of type `Rc<T>`, then this in fact is equivalent to
464 // `x.deref()`. Since `deref()` is declared with `&self`,
465 // this is an autoref of `x`.
466 adjustment::Adjust::Deref(Some(ref deref)) => {
467 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
468 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
471 adjustment::Adjust::Borrow(ref autoref) => {
472 self.walk_autoref(expr, &place_with_id, autoref);
476 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
480 /// Walks the autoref `autoref` applied to the autoderef'd
481 /// `expr`. `base_place` is the mem-categorized form of `expr`
482 /// after all relevant autoderefs have occurred.
485 expr: &hir::Expr<'_>,
486 base_place: &PlaceWithHirId<'tcx>,
487 autoref: &adjustment::AutoBorrow<'tcx>,
490 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
491 expr.hir_id, base_place, autoref
495 adjustment::AutoBorrow::Ref(_, m) => {
496 self.delegate.borrow(
499 ty::BorrowKind::from_mutbl(m.into()),
503 adjustment::AutoBorrow::RawPtr(m) => {
504 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
506 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
511 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
512 self.walk_pat(discr_place, &arm.pat);
514 if let Some(hir::Guard::If(ref e)) = arm.guard {
518 self.consume_expr(&arm.body);
521 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
522 /// let binding, and *not* a match arm or nested pat.)
523 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
524 self.walk_pat(discr_place, pat);
527 /// The core driver for walking a pattern
528 fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
529 debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
531 let tcx = self.tcx();
532 let ExprUseVisitor { ref mc, ref mut delegate } = *self;
533 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
534 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
535 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
537 mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
539 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
541 // pat_ty: the type of the binding being produced.
542 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
543 debug!("walk_pat: pat_ty={:?}", pat_ty);
545 // Each match binding is effectively an assignment to the
546 // binding being produced.
547 let def = Res::Local(canonical_id);
548 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
549 delegate.mutate(binding_place, binding_place.hir_id);
552 // It is also a borrow or copy/move of the value being matched.
553 // In a cases of pattern like `let pat = upvar`, don't use the span
554 // of the pattern, as this just looks confusing, instead use the span
555 // of the discriminant.
557 ty::BindByReference(m) => {
558 let bk = ty::BorrowKind::from_mutbl(m);
559 delegate.borrow(place, discr_place.hir_id, bk);
561 ty::BindByValue(..) => {
562 let mode = copy_or_move(mc, &place);
563 debug!("walk_pat binding consuming pat");
564 delegate.consume(place, discr_place.hir_id, 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_mentioned(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,
582 let upvar_capture = self.mc.typeck_results.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, captured_place.hir_id, mode);
593 ty::UpvarCapture::ByRef(upvar_borrow) => {
594 self.delegate.borrow(
596 captured_place.hir_id,
607 closure_hir_id: hir::HirId,
610 ) -> mc::McResult<PlaceWithHirId<'tcx>> {
611 // Create the place for the variable being borrowed, from the
612 // perspective of the creator (parent) of the closure.
613 let var_ty = self.mc.node_ty(var_id)?;
614 self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
618 fn copy_or_move<'a, 'tcx>(
619 mc: &mc::MemCategorizationContext<'a, 'tcx>,
620 place_with_id: &PlaceWithHirId<'tcx>,
622 if !mc.type_is_copy_modulo_regions(
623 place_with_id.place.ty(),
624 mc.tcx().hir().span(place_with_id.hir_id),