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