]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/expr_use_visitor.rs
Make hir ProjectionKind more precise
[rust.git] / src / librustc_typeck / expr_use_visitor.rs
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.
4
5 pub use self::ConsumeMode::*;
6
7 // Export these here so that Clippy can use them.
8 pub use mc::{PlaceBase, PlaceWithHirId, Projection};
9
10 use rustc_hir as hir;
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::ty::{self, adjustment, TyCtxt};
17 use rustc_target::abi::VariantIdx;
18
19 use crate::mem_categorization as mc;
20 use rustc_span::Span;
21
22 ///////////////////////////////////////////////////////////////////////////
23 // The Delegate trait
24
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.
30     fn consume(&mut self, place_with_id: &mc::PlaceWithHirId<'tcx>, mode: ConsumeMode);
31
32     // The value found at `place` is being borrowed with kind `bk`.
33     fn borrow(&mut self, place_with_id: &mc::PlaceWithHirId<'tcx>, bk: ty::BorrowKind);
34
35     // The path at `place_with_id` is being assigned to.
36     fn mutate(&mut self, assignee_place: &mc::PlaceWithHirId<'tcx>);
37 }
38
39 #[derive(Copy, Clone, PartialEq, Debug)]
40 pub enum ConsumeMode {
41     Copy, // reference to x where x has a type that copies
42     Move, // reference to x where x has a type that moves
43 }
44
45 #[derive(Copy, Clone, PartialEq, Debug)]
46 pub enum MutateMode {
47     Init,
48     JustWrite,    // x = y
49     WriteAndRead, // x += y
50 }
51
52 ///////////////////////////////////////////////////////////////////////////
53 // The ExprUseVisitor type
54 //
55 // This is the code that actually walks the tree.
56 pub struct ExprUseVisitor<'a, 'tcx> {
57     mc: mc::MemCategorizationContext<'a, 'tcx>,
58     delegate: &'a mut dyn Delegate<'tcx>,
59 }
60
61 // If the MC results in an error, it's because the type check
62 // failed (or will fail, when the error is uncovered and reported
63 // during writeback). In this case, we just ignore this part of the
64 // code.
65 //
66 // Note that this macro appears similar to try!(), but, unlike try!(),
67 // it does not propagate the error.
68 macro_rules! return_if_err {
69     ($inp: expr) => {
70         match $inp {
71             Ok(v) => v,
72             Err(()) => {
73                 debug!("mc reported err");
74                 return;
75             }
76         }
77     };
78 }
79
80 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
81     /// Creates the ExprUseVisitor, configuring it with the various options provided:
82     ///
83     /// - `delegate` -- who receives the callbacks
84     /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
85     /// - `tables` --- typeck results for the code being analyzed
86     pub fn new(
87         delegate: &'a mut (dyn Delegate<'tcx> + 'a),
88         infcx: &'a InferCtxt<'a, 'tcx>,
89         body_owner: LocalDefId,
90         param_env: ty::ParamEnv<'tcx>,
91         tables: &'a ty::TypeckTables<'tcx>,
92     ) -> Self {
93         ExprUseVisitor {
94             mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, tables),
95             delegate,
96         }
97     }
98
99     pub fn consume_body(&mut self, body: &hir::Body<'_>) {
100         debug!("consume_body(body={:?})", body);
101
102         for param in body.params {
103             let param_ty = return_if_err!(self.mc.pat_ty_adjusted(&param.pat));
104             debug!("consume_body: param_ty = {:?}", param_ty);
105
106             let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
107
108             self.walk_irrefutable_pat(&param_place, &param.pat);
109         }
110
111         self.consume_expr(&body.value);
112     }
113
114     fn tcx(&self) -> TyCtxt<'tcx> {
115         self.mc.tcx()
116     }
117
118     fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>) {
119         debug!("delegate_consume(place_with_id={:?})", place_with_id);
120
121         let mode = copy_or_move(&self.mc, place_with_id);
122         self.delegate.consume(place_with_id, mode);
123     }
124
125     fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
126         for expr in exprs {
127             self.consume_expr(&expr);
128         }
129     }
130
131     pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
132         debug!("consume_expr(expr={:?})", expr);
133
134         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
135         self.delegate_consume(&place_with_id);
136         self.walk_expr(expr);
137     }
138
139     fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
140         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
141         self.delegate.mutate(&place_with_id);
142         self.walk_expr(expr);
143     }
144
145     fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
146         debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
147
148         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
149         self.delegate.borrow(&place_with_id, bk);
150
151         self.walk_expr(expr)
152     }
153
154     fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
155         self.walk_expr(expr)
156     }
157
158     pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
159         debug!("walk_expr(expr={:?})", expr);
160
161         self.walk_adjustment(expr);
162
163         match expr.kind {
164             hir::ExprKind::Path(_) => {}
165
166             hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
167
168             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
169                 // *base
170                 self.select_from_expr(base);
171             }
172
173             hir::ExprKind::Field(ref base, _) => {
174                 // base.f
175                 self.select_from_expr(base);
176             }
177
178             hir::ExprKind::Index(ref lhs, ref rhs) => {
179                 // lhs[rhs]
180                 self.select_from_expr(lhs);
181                 self.consume_expr(rhs);
182             }
183
184             hir::ExprKind::Call(ref callee, ref args) => {
185                 // callee(args)
186                 self.consume_expr(callee);
187                 self.consume_exprs(args);
188             }
189
190             hir::ExprKind::MethodCall(.., ref args, _) => {
191                 // callee.m(args)
192                 self.consume_exprs(args);
193             }
194
195             hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
196                 self.walk_struct_expr(fields, opt_with);
197             }
198
199             hir::ExprKind::Tup(ref exprs) => {
200                 self.consume_exprs(exprs);
201             }
202
203             hir::ExprKind::Match(ref discr, arms, _) => {
204                 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
205                 self.borrow_expr(&discr, ty::ImmBorrow);
206
207                 // treatment of the discriminant is handled while walking the arms.
208                 for arm in arms {
209                     self.walk_arm(&discr_place, arm);
210                 }
211             }
212
213             hir::ExprKind::Array(ref exprs) => {
214                 self.consume_exprs(exprs);
215             }
216
217             hir::ExprKind::AddrOf(_, m, ref base) => {
218                 // &base
219                 // make sure that the thing we are pointing out stays valid
220                 // for the lifetime `scope_r` of the resulting ptr:
221                 let bk = ty::BorrowKind::from_mutbl(m);
222                 self.borrow_expr(&base, bk);
223             }
224
225             hir::ExprKind::InlineAsm(ref asm) => {
226                 for op in asm.operands {
227                     match op {
228                         hir::InlineAsmOperand::In { expr, .. }
229                         | hir::InlineAsmOperand::Const { expr, .. }
230                         | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
231                         hir::InlineAsmOperand::Out { expr, .. } => {
232                             if let Some(expr) = expr {
233                                 self.mutate_expr(expr);
234                             }
235                         }
236                         hir::InlineAsmOperand::InOut { expr, .. } => {
237                             self.mutate_expr(expr);
238                         }
239                         hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
240                             self.consume_expr(in_expr);
241                             if let Some(out_expr) = out_expr {
242                                 self.mutate_expr(out_expr);
243                             }
244                         }
245                     }
246                 }
247             }
248
249             hir::ExprKind::LlvmInlineAsm(ref ia) => {
250                 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
251                     if o.is_indirect {
252                         self.consume_expr(output);
253                     } else {
254                         self.mutate_expr(output);
255                     }
256                 }
257                 self.consume_exprs(&ia.inputs_exprs);
258             }
259
260             hir::ExprKind::Continue(..) | hir::ExprKind::Lit(..) | hir::ExprKind::Err => {}
261
262             hir::ExprKind::Loop(ref blk, _, _) => {
263                 self.walk_block(blk);
264             }
265
266             hir::ExprKind::Unary(_, ref lhs) => {
267                 self.consume_expr(lhs);
268             }
269
270             hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
271                 self.consume_expr(lhs);
272                 self.consume_expr(rhs);
273             }
274
275             hir::ExprKind::Block(ref blk, _) => {
276                 self.walk_block(blk);
277             }
278
279             hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
280                 if let Some(ref expr) = *opt_expr {
281                     self.consume_expr(expr);
282                 }
283             }
284
285             hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
286                 self.mutate_expr(lhs);
287                 self.consume_expr(rhs);
288             }
289
290             hir::ExprKind::Cast(ref base, _) => {
291                 self.consume_expr(base);
292             }
293
294             hir::ExprKind::DropTemps(ref expr) => {
295                 self.consume_expr(expr);
296             }
297
298             hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
299                 if self.mc.tables.is_method_call(expr) {
300                     self.consume_expr(lhs);
301                 } else {
302                     self.mutate_expr(lhs);
303                 }
304                 self.consume_expr(rhs);
305             }
306
307             hir::ExprKind::Repeat(ref base, _) => {
308                 self.consume_expr(base);
309             }
310
311             hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
312                 self.walk_captures(expr, fn_decl_span);
313             }
314
315             hir::ExprKind::Box(ref base) => {
316                 self.consume_expr(base);
317             }
318
319             hir::ExprKind::Yield(ref value, _) => {
320                 self.consume_expr(value);
321             }
322         }
323     }
324
325     fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
326         match stmt.kind {
327             hir::StmtKind::Local(ref local) => {
328                 self.walk_local(&local);
329             }
330
331             hir::StmtKind::Item(_) => {
332                 // We don't visit nested items in this visitor,
333                 // only the fn body we were given.
334             }
335
336             hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
337                 self.consume_expr(&expr);
338             }
339         }
340     }
341
342     fn walk_local(&mut self, local: &hir::Local<'_>) {
343         if let Some(ref expr) = local.init {
344             // Variable declarations with
345             // initializers are considered
346             // "assigns", which is handled by
347             // `walk_pat`:
348             self.walk_expr(&expr);
349             let init_place = return_if_err!(self.mc.cat_expr(&expr));
350             self.walk_irrefutable_pat(&init_place, &local.pat);
351         }
352     }
353
354     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
355     /// depending on its type.
356     fn walk_block(&mut self, blk: &hir::Block<'_>) {
357         debug!("walk_block(blk.hir_id={})", blk.hir_id);
358
359         for stmt in blk.stmts {
360             self.walk_stmt(stmt);
361         }
362
363         if let Some(ref tail_expr) = blk.expr {
364             self.consume_expr(&tail_expr);
365         }
366     }
367
368     fn walk_struct_expr(
369         &mut self,
370         fields: &[hir::Field<'_>],
371         opt_with: &Option<&'hir hir::Expr<'_>>,
372     ) {
373         // Consume the expressions supplying values for each field.
374         for field in fields {
375             self.consume_expr(&field.expr);
376         }
377
378         let with_expr = match *opt_with {
379             Some(ref w) => &**w,
380             None => {
381                 return;
382             }
383         };
384
385         let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
386
387         // Select just those fields of the `with`
388         // expression that will actually be used
389         match with_place.place.ty().kind {
390             ty::Adt(adt, substs) if adt.is_struct() => {
391                 // Consume those fields of the with expression that are needed.
392                 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
393                     let is_mentioned = fields
394                         .iter()
395                         .any(|f| self.tcx().field_index(f.hir_id, self.mc.tables) == f_index);
396                     if !is_mentioned {
397                         let field_place = self.mc.cat_projection(
398                             &*with_expr,
399                             with_place.clone(),
400                             with_field.ty(self.tcx(), substs),
401                             mc::ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
402                         );
403                         self.delegate_consume(&field_place);
404                     }
405                 }
406             }
407             _ => {
408                 // the base expression should always evaluate to a
409                 // struct; however, when EUV is run during typeck, it
410                 // may not. This will generate an error earlier in typeck,
411                 // so we can just ignore it.
412                 if !self.tcx().sess.has_errors() {
413                     span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
414                 }
415             }
416         }
417
418         // walk the with expression so that complex expressions
419         // are properly handled.
420         self.walk_expr(with_expr);
421     }
422
423     // Invoke the appropriate delegate calls for anything that gets
424     // consumed or borrowed as part of the automatic adjustment
425     // process.
426     fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
427         let adjustments = self.mc.tables.expr_adjustments(expr);
428         let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
429         for adjustment in adjustments {
430             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
431             match adjustment.kind {
432                 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
433                     // Creating a closure/fn-pointer or unsizing consumes
434                     // the input and stores it into the resulting rvalue.
435                     self.delegate_consume(&place_with_id);
436                 }
437
438                 adjustment::Adjust::Deref(None) => {}
439
440                 // Autoderefs for overloaded Deref calls in fact reference
441                 // their receiver. That is, if we have `(*x)` where `x`
442                 // is of type `Rc<T>`, then this in fact is equivalent to
443                 // `x.deref()`. Since `deref()` is declared with `&self`,
444                 // this is an autoref of `x`.
445                 adjustment::Adjust::Deref(Some(ref deref)) => {
446                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
447                     self.delegate.borrow(&place_with_id, bk);
448                 }
449
450                 adjustment::Adjust::Borrow(ref autoref) => {
451                     self.walk_autoref(expr, &place_with_id, autoref);
452                 }
453             }
454             place_with_id =
455                 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
456         }
457     }
458
459     /// Walks the autoref `autoref` applied to the autoderef'd
460     /// `expr`. `base_place` is the mem-categorized form of `expr`
461     /// after all relevant autoderefs have occurred.
462     fn walk_autoref(
463         &mut self,
464         expr: &hir::Expr<'_>,
465         base_place: &mc::PlaceWithHirId<'tcx>,
466         autoref: &adjustment::AutoBorrow<'tcx>,
467     ) {
468         debug!(
469             "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
470             expr.hir_id, base_place, autoref
471         );
472
473         match *autoref {
474             adjustment::AutoBorrow::Ref(_, m) => {
475                 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
476             }
477
478             adjustment::AutoBorrow::RawPtr(m) => {
479                 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
480
481                 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
482             }
483         }
484     }
485
486     fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
487         self.walk_pat(discr_place, &arm.pat);
488
489         if let Some(hir::Guard::If(ref e)) = arm.guard {
490             self.consume_expr(e)
491         }
492
493         self.consume_expr(&arm.body);
494     }
495
496     /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
497     /// let binding, and *not* a match arm or nested pat.)
498     fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
499         self.walk_pat(discr_place, pat);
500     }
501
502     /// The core driver for walking a pattern
503     fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
504         debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
505
506         let tcx = self.tcx();
507         let ExprUseVisitor { ref mc, ref mut delegate } = *self;
508         return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
509             if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
510                 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
511                 if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) {
512                     debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
513
514                     // pat_ty: the type of the binding being produced.
515                     let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
516                     debug!("walk_pat: pat_ty={:?}", pat_ty);
517
518                     // Each match binding is effectively an assignment to the
519                     // binding being produced.
520                     let def = Res::Local(canonical_id);
521                     if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
522                         delegate.mutate(binding_place);
523                     }
524
525                     // It is also a borrow or copy/move of the value being matched.
526                     match bm {
527                         ty::BindByReference(m) => {
528                             let bk = ty::BorrowKind::from_mutbl(m);
529                             delegate.borrow(place, bk);
530                         }
531                         ty::BindByValue(..) => {
532                             let mode = copy_or_move(mc, place);
533                             debug!("walk_pat binding consuming pat");
534                             delegate.consume(place, mode);
535                         }
536                     }
537                 }
538             }
539         }));
540     }
541
542     fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) {
543         debug!("walk_captures({:?})", closure_expr);
544
545         let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
546         if let Some(upvars) = self.tcx().upvars_mentioned(closure_def_id) {
547             for &var_id in upvars.keys() {
548                 let upvar_id = ty::UpvarId {
549                     var_path: ty::UpvarPath { hir_id: var_id },
550                     closure_expr_id: closure_def_id,
551                 };
552                 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
553                 let captured_place = return_if_err!(self.cat_captured_var(
554                     closure_expr.hir_id,
555                     fn_decl_span,
556                     var_id,
557                 ));
558                 match upvar_capture {
559                     ty::UpvarCapture::ByValue => {
560                         let mode = copy_or_move(&self.mc, &captured_place);
561                         self.delegate.consume(&captured_place, mode);
562                     }
563                     ty::UpvarCapture::ByRef(upvar_borrow) => {
564                         self.delegate.borrow(&captured_place, upvar_borrow.kind);
565                     }
566                 }
567             }
568         }
569     }
570
571     fn cat_captured_var(
572         &mut self,
573         closure_hir_id: hir::HirId,
574         closure_span: Span,
575         var_id: hir::HirId,
576     ) -> mc::McResult<mc::PlaceWithHirId<'tcx>> {
577         // Create the place for the variable being borrowed, from the
578         // perspective of the creator (parent) of the closure.
579         let var_ty = self.mc.node_ty(var_id)?;
580         self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
581     }
582 }
583
584 fn copy_or_move<'a, 'tcx>(
585     mc: &mc::MemCategorizationContext<'a, 'tcx>,
586     place_with_id: &PlaceWithHirId<'tcx>,
587 ) -> ConsumeMode {
588     if !mc.type_is_copy_modulo_regions(
589         place_with_id.place.ty(),
590         mc.tcx().hir().span(place_with_id.hir_id),
591     ) {
592         Move
593     } else {
594         Copy
595     }
596 }