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