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