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