]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
Improve some compiletest documentation
[rust.git] / src / librustc / middle / 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::LoanCause::*;
6 pub use self::ConsumeMode::*;
7 pub use self::MoveReason::*;
8 pub use self::MatchMode::*;
9 use self::TrackMatchMode::*;
10 use self::OverloadedCallType::*;
11
12 use crate::hir::def::Def;
13 use crate::hir::def_id::DefId;
14 use crate::infer::InferCtxt;
15 use crate::middle::mem_categorization as mc;
16 use crate::middle::region;
17 use crate::ty::{self, TyCtxt, adjustment};
18
19 use crate::hir::{self, PatKind};
20 use rustc_data_structures::sync::Lrc;
21 use std::rc::Rc;
22 use syntax::ptr::P;
23 use syntax_pos::Span;
24 use crate::util::nodemap::ItemLocalSet;
25
26 ///////////////////////////////////////////////////////////////////////////
27 // The Delegate trait
28
29 /// This trait defines the callbacks you can expect to receive when
30 /// employing the ExprUseVisitor.
31 pub trait Delegate<'tcx> {
32     // The value found at `cmt` is either copied or moved, depending
33     // on mode.
34     fn consume(&mut self,
35                consume_id: hir::HirId,
36                consume_span: Span,
37                cmt: &mc::cmt_<'tcx>,
38                mode: ConsumeMode);
39
40     // The value found at `cmt` has been determined to match the
41     // pattern binding `matched_pat`, and its subparts are being
42     // copied or moved depending on `mode`.  Note that `matched_pat`
43     // is called on all variant/structs in the pattern (i.e., the
44     // interior nodes of the pattern's tree structure) while
45     // consume_pat is called on the binding identifiers in the pattern
46     // (which are leaves of the pattern's tree structure).
47     //
48     // Note that variants/structs and identifiers are disjoint; thus
49     // `matched_pat` and `consume_pat` are never both called on the
50     // same input pattern structure (though of `consume_pat` can be
51     // called on a subpart of an input passed to `matched_pat).
52     fn matched_pat(&mut self,
53                    matched_pat: &hir::Pat,
54                    cmt: &mc::cmt_<'tcx>,
55                    mode: MatchMode);
56
57     // The value found at `cmt` is either copied or moved via the
58     // pattern binding `consume_pat`, depending on mode.
59     fn consume_pat(&mut self,
60                    consume_pat: &hir::Pat,
61                    cmt: &mc::cmt_<'tcx>,
62                    mode: ConsumeMode);
63
64     // The value found at `borrow` is being borrowed at the point
65     // `borrow_id` for the region `loan_region` with kind `bk`.
66     fn borrow(&mut self,
67               borrow_id: hir::HirId,
68               borrow_span: Span,
69               cmt: &mc::cmt_<'tcx>,
70               loan_region: ty::Region<'tcx>,
71               bk: ty::BorrowKind,
72               loan_cause: LoanCause);
73
74     // The local variable `id` is declared but not initialized.
75     fn decl_without_init(&mut self,
76                          id: hir::HirId,
77                          span: Span);
78
79     // The path at `cmt` is being assigned to.
80     fn mutate(&mut self,
81               assignment_id: hir::HirId,
82               assignment_span: Span,
83               assignee_cmt: &mc::cmt_<'tcx>,
84               mode: MutateMode);
85
86     // A nested closure or generator - only one layer deep.
87     fn nested_body(&mut self, _body_id: hir::BodyId) {}
88 }
89
90 #[derive(Copy, Clone, PartialEq, Debug)]
91 pub enum LoanCause {
92     ClosureCapture(Span),
93     AddrOf,
94     AutoRef,
95     AutoUnsafe,
96     RefBinding,
97     OverloadedOperator,
98     ClosureInvocation,
99     ForLoop,
100     MatchDiscriminant
101 }
102
103 #[derive(Copy, Clone, PartialEq, Debug)]
104 pub enum ConsumeMode {
105     Copy,                // reference to x where x has a type that copies
106     Move(MoveReason),    // reference to x where x has a type that moves
107 }
108
109 #[derive(Copy, Clone, PartialEq, Debug)]
110 pub enum MoveReason {
111     DirectRefMove,
112     PatBindingMove,
113     CaptureMove,
114 }
115
116 #[derive(Copy, Clone, PartialEq, Debug)]
117 pub enum MatchMode {
118     NonBindingMatch,
119     BorrowingMatch,
120     CopyingMatch,
121     MovingMatch,
122 }
123
124 #[derive(Copy, Clone, PartialEq, Debug)]
125 enum TrackMatchMode {
126     Unknown,
127     Definite(MatchMode),
128     Conflicting,
129 }
130
131 impl TrackMatchMode {
132     // Builds up the whole match mode for a pattern from its constituent
133     // parts.  The lattice looks like this:
134     //
135     //          Conflicting
136     //            /     \
137     //           /       \
138     //      Borrowing   Moving
139     //           \       /
140     //            \     /
141     //            Copying
142     //               |
143     //          NonBinding
144     //               |
145     //            Unknown
146     //
147     // examples:
148     //
149     // * `(_, some_int)` pattern is Copying, since
150     //   NonBinding + Copying => Copying
151     //
152     // * `(some_int, some_box)` pattern is Moving, since
153     //   Copying + Moving => Moving
154     //
155     // * `(ref x, some_box)` pattern is Conflicting, since
156     //   Borrowing + Moving => Conflicting
157     //
158     // Note that the `Unknown` and `Conflicting` states are
159     // represented separately from the other more interesting
160     // `Definite` states, which simplifies logic here somewhat.
161     fn lub(&mut self, mode: MatchMode) {
162         *self = match (*self, mode) {
163             // Note that clause order below is very significant.
164             (Unknown, new) => Definite(new),
165             (Definite(old), new) if old == new => Definite(old),
166
167             (Definite(old), NonBindingMatch) => Definite(old),
168             (Definite(NonBindingMatch), new) => Definite(new),
169
170             (Definite(old), CopyingMatch) => Definite(old),
171             (Definite(CopyingMatch), new) => Definite(new),
172
173             (Definite(_), _) => Conflicting,
174             (Conflicting, _) => *self,
175         };
176     }
177
178     fn match_mode(&self) -> MatchMode {
179         match *self {
180             Unknown => NonBindingMatch,
181             Definite(mode) => mode,
182             Conflicting => {
183                 // Conservatively return MovingMatch to let the
184                 // compiler continue to make progress.
185                 MovingMatch
186             }
187         }
188     }
189 }
190
191 #[derive(Copy, Clone, PartialEq, Debug)]
192 pub enum MutateMode {
193     Init,
194     JustWrite,    // x = y
195     WriteAndRead, // x += y
196 }
197
198 #[derive(Copy, Clone)]
199 enum OverloadedCallType {
200     FnOverloadedCall,
201     FnMutOverloadedCall,
202     FnOnceOverloadedCall,
203 }
204
205 impl OverloadedCallType {
206     fn from_trait_id(tcx: TyCtxt<'_, '_, '_>, trait_id: DefId) -> OverloadedCallType {
207         for &(maybe_function_trait, overloaded_call_type) in &[
208             (tcx.lang_items().fn_once_trait(), FnOnceOverloadedCall),
209             (tcx.lang_items().fn_mut_trait(), FnMutOverloadedCall),
210             (tcx.lang_items().fn_trait(), FnOverloadedCall)
211         ] {
212             match maybe_function_trait {
213                 Some(function_trait) if function_trait == trait_id => {
214                     return overloaded_call_type
215                 }
216                 _ => continue,
217             }
218         }
219
220         bug!("overloaded call didn't map to known function trait")
221     }
222
223     fn from_method_id(tcx: TyCtxt<'_, '_, '_>, method_id: DefId) -> OverloadedCallType {
224         let method = tcx.associated_item(method_id);
225         OverloadedCallType::from_trait_id(tcx, method.container.id())
226     }
227 }
228
229 ///////////////////////////////////////////////////////////////////////////
230 // The ExprUseVisitor type
231 //
232 // This is the code that actually walks the tree.
233 pub struct ExprUseVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
234     mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
235     delegate: &'a mut dyn Delegate<'tcx>,
236     param_env: ty::ParamEnv<'tcx>,
237 }
238
239 // If the MC results in an error, it's because the type check
240 // failed (or will fail, when the error is uncovered and reported
241 // during writeback). In this case, we just ignore this part of the
242 // code.
243 //
244 // Note that this macro appears similar to try!(), but, unlike try!(),
245 // it does not propagate the error.
246 macro_rules! return_if_err {
247     ($inp: expr) => (
248         match $inp {
249             Ok(v) => v,
250             Err(()) => {
251                 debug!("mc reported err");
252                 return
253             }
254         }
255     )
256 }
257
258 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx, 'tcx> {
259     /// Creates the ExprUseVisitor, configuring it with the various options provided:
260     ///
261     /// - `delegate` -- who receives the callbacks
262     /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
263     /// - `region_scope_tree` --- region scope tree for the code being analyzed
264     /// - `tables` --- typeck results for the code being analyzed
265     /// - `rvalue_promotable_map` --- if you care about rvalue promotion, then provide
266     ///   the map here (it can be computed with `tcx.rvalue_promotable_map(def_id)`).
267     ///   `None` means that rvalues will be given more conservative lifetimes.
268     ///
269     /// See also `with_infer`, which is used *during* typeck.
270     pub fn new(delegate: &'a mut (dyn Delegate<'tcx>+'a),
271                tcx: TyCtxt<'a, 'tcx, 'tcx>,
272                param_env: ty::ParamEnv<'tcx>,
273                region_scope_tree: &'a region::ScopeTree,
274                tables: &'a ty::TypeckTables<'tcx>,
275                rvalue_promotable_map: Option<Lrc<ItemLocalSet>>)
276                -> Self
277     {
278         ExprUseVisitor {
279             mc: mc::MemCategorizationContext::new(tcx,
280                                                   region_scope_tree,
281                                                   tables,
282                                                   rvalue_promotable_map),
283             delegate,
284             param_env,
285         }
286     }
287 }
288
289 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
290     pub fn with_infer(delegate: &'a mut (dyn Delegate<'tcx>+'a),
291                       infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
292                       param_env: ty::ParamEnv<'tcx>,
293                       region_scope_tree: &'a region::ScopeTree,
294                       tables: &'a ty::TypeckTables<'tcx>)
295                       -> Self
296     {
297         ExprUseVisitor {
298             mc: mc::MemCategorizationContext::with_infer(infcx, region_scope_tree, tables),
299             delegate,
300             param_env,
301         }
302     }
303
304     pub fn consume_body(&mut self, body: &hir::Body) {
305         debug!("consume_body(body={:?})", body);
306
307         for arg in &body.arguments {
308             let arg_ty = return_if_err!(self.mc.pat_ty_adjusted(&arg.pat));
309             debug!("consume_body: arg_ty = {:?}", arg_ty);
310
311             let fn_body_scope_r =
312                 self.tcx().mk_region(ty::ReScope(
313                     region::Scope {
314                         id: body.value.hir_id.local_id,
315                         data: region::ScopeData::Node
316                 }));
317             let arg_cmt = Rc::new(self.mc.cat_rvalue(
318                 arg.hir_id,
319                 arg.pat.span,
320                 fn_body_scope_r, // Args live only as long as the fn body.
321                 arg_ty));
322
323             self.walk_irrefutable_pat(arg_cmt, &arg.pat);
324         }
325
326         self.consume_expr(&body.value);
327     }
328
329     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
330         self.mc.tcx
331     }
332
333     fn delegate_consume(&mut self,
334                         consume_id: hir::HirId,
335                         consume_span: Span,
336                         cmt: &mc::cmt_<'tcx>) {
337         debug!("delegate_consume(consume_id={}, cmt={:?})",
338                consume_id, cmt);
339
340         let mode = copy_or_move(&self.mc, self.param_env, cmt, DirectRefMove);
341         self.delegate.consume(consume_id, consume_span, cmt, mode);
342     }
343
344     fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
345         for expr in exprs {
346             self.consume_expr(&expr);
347         }
348     }
349
350     pub fn consume_expr(&mut self, expr: &hir::Expr) {
351         debug!("consume_expr(expr={:?})", expr);
352
353         let cmt = return_if_err!(self.mc.cat_expr(expr));
354         self.delegate_consume(expr.hir_id, expr.span, &cmt);
355         self.walk_expr(expr);
356     }
357
358     fn mutate_expr(&mut self,
359                    span: Span,
360                    assignment_expr: &hir::Expr,
361                    expr: &hir::Expr,
362                    mode: MutateMode) {
363         let cmt = return_if_err!(self.mc.cat_expr(expr));
364         self.delegate.mutate(assignment_expr.hir_id, span, &cmt, mode);
365         self.walk_expr(expr);
366     }
367
368     fn borrow_expr(&mut self,
369                    expr: &hir::Expr,
370                    r: ty::Region<'tcx>,
371                    bk: ty::BorrowKind,
372                    cause: LoanCause) {
373         debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
374                expr, r, bk);
375
376         let cmt = return_if_err!(self.mc.cat_expr(expr));
377         self.delegate.borrow(expr.hir_id, expr.span, &cmt, r, bk, cause);
378
379         self.walk_expr(expr)
380     }
381
382     fn select_from_expr(&mut self, expr: &hir::Expr) {
383         self.walk_expr(expr)
384     }
385
386     pub fn walk_expr(&mut self, expr: &hir::Expr) {
387         debug!("walk_expr(expr={:?})", expr);
388
389         self.walk_adjustment(expr);
390
391         match expr.node {
392             hir::ExprKind::Path(_) => { }
393
394             hir::ExprKind::Type(ref subexpr, _) => {
395                 self.walk_expr(&subexpr)
396             }
397
398             hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base
399                 self.select_from_expr(&base);
400             }
401
402             hir::ExprKind::Field(ref base, _) => { // base.f
403                 self.select_from_expr(&base);
404             }
405
406             hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs]
407                 self.select_from_expr(&lhs);
408                 self.consume_expr(&rhs);
409             }
410
411             hir::ExprKind::Call(ref callee, ref args) => { // callee(args)
412                 self.walk_callee(expr, &callee);
413                 self.consume_exprs(args);
414             }
415
416             hir::ExprKind::MethodCall(.., ref args) => { // callee.m(args)
417                 self.consume_exprs(args);
418             }
419
420             hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
421                 self.walk_struct_expr(fields, opt_with);
422             }
423
424             hir::ExprKind::Tup(ref exprs) => {
425                 self.consume_exprs(exprs);
426             }
427
428             hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
429                 self.consume_expr(&cond_expr);
430                 self.walk_expr(&then_expr);
431                 if let Some(ref else_expr) = *opt_else_expr {
432                     self.consume_expr(&else_expr);
433                 }
434             }
435
436             hir::ExprKind::Match(ref discr, ref arms, _) => {
437                 let discr_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&discr)));
438                 let r = self.tcx().types.re_empty;
439                 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
440
441                 // treatment of the discriminant is handled while walking the arms.
442                 for arm in arms {
443                     let mode = self.arm_move_mode(discr_cmt.clone(), arm);
444                     let mode = mode.match_mode();
445                     self.walk_arm(discr_cmt.clone(), arm, mode);
446                 }
447             }
448
449             hir::ExprKind::Array(ref exprs) => {
450                 self.consume_exprs(exprs);
451             }
452
453             hir::ExprKind::AddrOf(m, ref base) => {   // &base
454                 // make sure that the thing we are pointing out stays valid
455                 // for the lifetime `scope_r` of the resulting ptr:
456                 let expr_ty = return_if_err!(self.mc.expr_ty(expr));
457                 if let ty::Ref(r, _, _) = expr_ty.sty {
458                     let bk = ty::BorrowKind::from_mutbl(m);
459                     self.borrow_expr(&base, r, bk, AddrOf);
460                 }
461             }
462
463             hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => {
464                 for (o, output) in ia.outputs.iter().zip(outputs) {
465                     if o.is_indirect {
466                         self.consume_expr(output);
467                     } else {
468                         self.mutate_expr(
469                             output.span,
470                             expr,
471                             output,
472                             if o.is_rw {
473                                 MutateMode::WriteAndRead
474                             } else {
475                                 MutateMode::JustWrite
476                             },
477                         );
478                     }
479                 }
480                 self.consume_exprs(inputs);
481             }
482
483             hir::ExprKind::Continue(..) |
484             hir::ExprKind::Lit(..) |
485             hir::ExprKind::Err => {}
486
487             hir::ExprKind::Loop(ref blk, _, _) => {
488                 self.walk_block(&blk);
489             }
490
491             hir::ExprKind::While(ref cond_expr, ref blk, _) => {
492                 self.consume_expr(&cond_expr);
493                 self.walk_block(&blk);
494             }
495
496             hir::ExprKind::Unary(_, ref lhs) => {
497                 self.consume_expr(&lhs);
498             }
499
500             hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
501                 self.consume_expr(&lhs);
502                 self.consume_expr(&rhs);
503             }
504
505             hir::ExprKind::Block(ref blk, _) => {
506                 self.walk_block(&blk);
507             }
508
509             hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
510                 if let Some(ref expr) = *opt_expr {
511                     self.consume_expr(&expr);
512                 }
513             }
514
515             hir::ExprKind::Assign(ref lhs, ref rhs) => {
516                 self.mutate_expr(expr.span, expr, &lhs, MutateMode::JustWrite);
517                 self.consume_expr(&rhs);
518             }
519
520             hir::ExprKind::Cast(ref base, _) => {
521                 self.consume_expr(&base);
522             }
523
524             hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
525                 if self.mc.tables.is_method_call(expr) {
526                     self.consume_expr(lhs);
527                 } else {
528                     self.mutate_expr(expr.span, expr, &lhs, MutateMode::WriteAndRead);
529                 }
530                 self.consume_expr(&rhs);
531             }
532
533             hir::ExprKind::Repeat(ref base, _) => {
534                 self.consume_expr(&base);
535             }
536
537             hir::ExprKind::Closure(_, _, body_id, fn_decl_span, _) => {
538                 self.delegate.nested_body(body_id);
539                 self.walk_captures(expr, fn_decl_span);
540             }
541
542             hir::ExprKind::Box(ref base) => {
543                 self.consume_expr(&base);
544             }
545
546             hir::ExprKind::Yield(ref value) => {
547                 self.consume_expr(&value);
548             }
549         }
550     }
551
552     fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
553         let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
554         debug!("walk_callee: callee={:?} callee_ty={:?}",
555                callee, callee_ty);
556         match callee_ty.sty {
557             ty::FnDef(..) | ty::FnPtr(_) => {
558                 self.consume_expr(callee);
559             }
560             ty::Error => { }
561             _ => {
562                 if let Some(def) = self.mc.tables.type_dependent_defs().get(call.hir_id) {
563                     let def_id = def.def_id();
564                     let call_scope = region::Scope {
565                         id: call.hir_id.local_id,
566                         data: region::ScopeData::Node
567                     };
568                     match OverloadedCallType::from_method_id(self.tcx(), def_id) {
569                         FnMutOverloadedCall => {
570                             let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
571                             self.borrow_expr(callee,
572                                             call_scope_r,
573                                             ty::MutBorrow,
574                                             ClosureInvocation);
575                         }
576                         FnOverloadedCall => {
577                             let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
578                             self.borrow_expr(callee,
579                                             call_scope_r,
580                                             ty::ImmBorrow,
581                                             ClosureInvocation);
582                         }
583                         FnOnceOverloadedCall => self.consume_expr(callee),
584                     }
585                 } else {
586                     self.tcx().sess.delay_span_bug(call.span,
587                                                    "no type-dependent def for overloaded call");
588                 }
589             }
590         }
591     }
592
593     fn walk_stmt(&mut self, stmt: &hir::Stmt) {
594         match stmt.node {
595             hir::StmtKind::Local(ref local) => {
596                 self.walk_local(&local);
597             }
598
599             hir::StmtKind::Item(_) => {
600                 // we don't visit nested items in this visitor,
601                 // only the fn body we were given.
602             }
603
604             hir::StmtKind::Expr(ref expr) |
605             hir::StmtKind::Semi(ref expr) => {
606                 self.consume_expr(&expr);
607             }
608         }
609     }
610
611     fn walk_local(&mut self, local: &hir::Local) {
612         match local.init {
613             None => {
614                 local.pat.each_binding(|_, hir_id, span, _| {
615                     self.delegate.decl_without_init(hir_id, span);
616                 })
617             }
618
619             Some(ref expr) => {
620                 // Variable declarations with
621                 // initializers are considered
622                 // "assigns", which is handled by
623                 // `walk_pat`:
624                 self.walk_expr(&expr);
625                 let init_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&expr)));
626                 self.walk_irrefutable_pat(init_cmt, &local.pat);
627             }
628         }
629     }
630
631     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
632     /// depending on its type.
633     fn walk_block(&mut self, blk: &hir::Block) {
634         debug!("walk_block(blk.hir_id={})", blk.hir_id);
635
636         for stmt in &blk.stmts {
637             self.walk_stmt(stmt);
638         }
639
640         if let Some(ref tail_expr) = blk.expr {
641             self.consume_expr(&tail_expr);
642         }
643     }
644
645     fn walk_struct_expr(&mut self,
646                         fields: &[hir::Field],
647                         opt_with: &Option<P<hir::Expr>>) {
648         // Consume the expressions supplying values for each field.
649         for field in fields {
650             self.consume_expr(&field.expr);
651         }
652
653         let with_expr = match *opt_with {
654             Some(ref w) => &**w,
655             None => { return; }
656         };
657
658         let with_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&with_expr)));
659
660         // Select just those fields of the `with`
661         // expression that will actually be used
662         match with_cmt.ty.sty {
663             ty::Adt(adt, substs) if adt.is_struct() => {
664                 // Consume those fields of the with expression that are needed.
665                 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
666                     let is_mentioned = fields.iter().any(|f| {
667                         self.tcx().field_index(f.hir_id, self.mc.tables) == f_index
668                     });
669                     if !is_mentioned {
670                         let cmt_field = self.mc.cat_field(
671                             &*with_expr,
672                             with_cmt.clone(),
673                             f_index,
674                             with_field.ident,
675                             with_field.ty(self.tcx(), substs)
676                         );
677                         self.delegate_consume(with_expr.hir_id, with_expr.span, &cmt_field);
678                     }
679                 }
680             }
681             _ => {
682                 // the base expression should always evaluate to a
683                 // struct; however, when EUV is run during typeck, it
684                 // may not. This will generate an error earlier in typeck,
685                 // so we can just ignore it.
686                 if !self.tcx().sess.has_errors() {
687                     span_bug!(
688                         with_expr.span,
689                         "with expression doesn't evaluate to a struct");
690                 }
691             }
692         }
693
694         // walk the with expression so that complex expressions
695         // are properly handled.
696         self.walk_expr(with_expr);
697     }
698
699     // Invoke the appropriate delegate calls for anything that gets
700     // consumed or borrowed as part of the automatic adjustment
701     // process.
702     fn walk_adjustment(&mut self, expr: &hir::Expr) {
703         let adjustments = self.mc.tables.expr_adjustments(expr);
704         let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
705         for adjustment in adjustments {
706             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
707             match adjustment.kind {
708                 adjustment::Adjust::NeverToAny |
709                 adjustment::Adjust::ReifyFnPointer |
710                 adjustment::Adjust::UnsafeFnPointer |
711                 adjustment::Adjust::ClosureFnPointer |
712                 adjustment::Adjust::MutToConstPointer |
713                 adjustment::Adjust::Unsize => {
714                     // Creating a closure/fn-pointer or unsizing consumes
715                     // the input and stores it into the resulting rvalue.
716                     self.delegate_consume(expr.hir_id, expr.span, &cmt);
717                 }
718
719                 adjustment::Adjust::Deref(None) => {}
720
721                 // Autoderefs for overloaded Deref calls in fact reference
722                 // their receiver. That is, if we have `(*x)` where `x`
723                 // is of type `Rc<T>`, then this in fact is equivalent to
724                 // `x.deref()`. Since `deref()` is declared with `&self`,
725                 // this is an autoref of `x`.
726                 adjustment::Adjust::Deref(Some(ref deref)) => {
727                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
728                     self.delegate.borrow(expr.hir_id, expr.span, &cmt, deref.region, bk, AutoRef);
729                 }
730
731                 adjustment::Adjust::Borrow(ref autoref) => {
732                     self.walk_autoref(expr, &cmt, autoref);
733                 }
734             }
735             cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
736         }
737     }
738
739     /// Walks the autoref `autoref` applied to the autoderef'd
740     /// `expr`. `cmt_base` is the mem-categorized form of `expr`
741     /// after all relevant autoderefs have occurred.
742     fn walk_autoref(&mut self,
743                     expr: &hir::Expr,
744                     cmt_base: &mc::cmt_<'tcx>,
745                     autoref: &adjustment::AutoBorrow<'tcx>) {
746         debug!("walk_autoref(expr.hir_id={} cmt_base={:?} autoref={:?})",
747                expr.hir_id,
748                cmt_base,
749                autoref);
750
751         match *autoref {
752             adjustment::AutoBorrow::Ref(r, m) => {
753                 self.delegate.borrow(expr.hir_id,
754                                      expr.span,
755                                      cmt_base,
756                                      r,
757                                      ty::BorrowKind::from_mutbl(m.into()),
758                                      AutoRef);
759             }
760
761             adjustment::AutoBorrow::RawPtr(m) => {
762                 debug!("walk_autoref: expr.hir_id={} cmt_base={:?}",
763                        expr.hir_id,
764                        cmt_base);
765
766                 // Converting from a &T to *T (or &mut T to *mut T) is
767                 // treated as borrowing it for the enclosing temporary
768                 // scope.
769                 let r = self.tcx().mk_region(ty::ReScope(
770                     region::Scope {
771                         id: expr.hir_id.local_id,
772                         data: region::ScopeData::Node
773                     }));
774
775                 self.delegate.borrow(expr.hir_id,
776                                      expr.span,
777                                      cmt_base,
778                                      r,
779                                      ty::BorrowKind::from_mutbl(m),
780                                      AutoUnsafe);
781             }
782         }
783     }
784
785     fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
786         let mut mode = Unknown;
787         for pat in &arm.pats {
788             self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
789         }
790         mode
791     }
792
793     fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
794         for pat in &arm.pats {
795             self.walk_pat(discr_cmt.clone(), &pat, mode);
796         }
797
798         if let Some(hir::Guard::If(ref e)) = arm.guard {
799             self.consume_expr(e)
800         }
801
802         self.consume_expr(&arm.body);
803     }
804
805     /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
806     /// let binding, and *not* a match arm or nested pat.)
807     fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
808         let mut mode = Unknown;
809         self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
810         let mode = mode.match_mode();
811         self.walk_pat(cmt_discr, pat, mode);
812     }
813
814     /// Identifies any bindings within `pat` and accumulates within
815     /// `mode` whether the overall pattern/match structure is a move,
816     /// copy, or borrow.
817     fn determine_pat_move_mode(&mut self,
818                                cmt_discr: mc::cmt<'tcx>,
819                                pat: &hir::Pat,
820                                mode: &mut TrackMatchMode) {
821         debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr, pat);
822
823         return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
824             if let PatKind::Binding(..) = pat.node {
825                 let bm = *self.mc.tables.pat_binding_modes()
826                                         .get(pat.hir_id)
827                                         .expect("missing binding mode");
828                 match bm {
829                     ty::BindByReference(..) =>
830                         mode.lub(BorrowingMatch),
831                     ty::BindByValue(..) => {
832                         match copy_or_move(&self.mc, self.param_env, &cmt_pat, PatBindingMove) {
833                             Copy => mode.lub(CopyingMatch),
834                             Move(..) => mode.lub(MovingMatch),
835                         }
836                     }
837                 }
838             }
839         }));
840     }
841
842     /// The core driver for walking a pattern; `match_mode` must be
843     /// established up front, e.g., via `determine_pat_move_mode` (see
844     /// also `walk_irrefutable_pat` for patterns that stand alone).
845     fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
846         debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat);
847
848         let tcx = self.tcx();
849         let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
850         return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| {
851             if let PatKind::Binding(_, canonical_id, ..) = pat.node {
852                 debug!(
853                     "walk_pat: binding cmt_pat={:?} pat={:?} match_mode={:?}",
854                     cmt_pat,
855                     pat,
856                     match_mode,
857                 );
858                 if let Some(&bm) = mc.tables.pat_binding_modes().get(pat.hir_id) {
859                     debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
860
861                     // pat_ty: the type of the binding being produced.
862                     let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
863                     debug!("walk_pat: pat_ty={:?}", pat_ty);
864
865                     // Each match binding is effectively an assignment to the
866                     // binding being produced.
867                     let def = Def::Local(mc.tcx.hir().hir_to_node_id(canonical_id));
868                     if let Ok(ref binding_cmt) = mc.cat_def(pat.hir_id, pat.span, pat_ty, def) {
869                         delegate.mutate(pat.hir_id, pat.span, binding_cmt, MutateMode::Init);
870                     }
871
872                     // It is also a borrow or copy/move of the value being matched.
873                     match bm {
874                         ty::BindByReference(m) => {
875                             if let ty::Ref(r, _, _) = pat_ty.sty {
876                                 let bk = ty::BorrowKind::from_mutbl(m);
877                                 delegate.borrow(pat.hir_id, pat.span, &cmt_pat, r, bk, RefBinding);
878                             }
879                         }
880                         ty::BindByValue(..) => {
881                             let mode = copy_or_move(mc, param_env, &cmt_pat, PatBindingMove);
882                             debug!("walk_pat binding consuming pat");
883                             delegate.consume_pat(pat, &cmt_pat, mode);
884                         }
885                     }
886                 } else {
887                     tcx.sess.delay_span_bug(pat.span, "missing binding mode");
888                 }
889             }
890         }));
891
892         // Do a second pass over the pattern, calling `matched_pat` on
893         // the interior nodes (enum variants and structs), as opposed
894         // to the above loop's visit of than the bindings that form
895         // the leaves of the pattern tree structure.
896         return_if_err!(mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
897             let qpath = match pat.node {
898                 PatKind::Path(ref qpath) |
899                 PatKind::TupleStruct(ref qpath, ..) |
900                 PatKind::Struct(ref qpath, ..) => qpath,
901                 _ => return
902             };
903             let def = mc.tables.qpath_def(qpath, pat.hir_id);
904             match def {
905                 Def::Variant(variant_did) |
906                 Def::VariantCtor(variant_did, ..) => {
907                     let downcast_cmt = mc.cat_downcast_if_needed(pat, cmt_pat, variant_did);
908
909                     debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
910                     delegate.matched_pat(pat, &downcast_cmt, match_mode);
911                 }
912                 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
913                 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
914                     debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
915                     delegate.matched_pat(pat, &cmt_pat, match_mode);
916                 }
917                 _ => {}
918             }
919         }));
920     }
921
922     fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
923         debug!("walk_captures({:?})", closure_expr);
924
925         let closure_def_id = self.tcx().hir().local_def_id_from_hir_id(closure_expr.hir_id);
926         self.tcx().with_freevars(closure_expr.hir_id, |freevars| {
927             for freevar in freevars {
928                 let var_hir_id = self.tcx().hir().node_to_hir_id(freevar.var_id());
929                 let upvar_id = ty::UpvarId {
930                     var_path: ty::UpvarPath { hir_id: var_hir_id },
931                     closure_expr_id: closure_def_id.to_local(),
932                 };
933                 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
934                 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.hir_id,
935                                                                    fn_decl_span,
936                                                                    freevar));
937                 match upvar_capture {
938                     ty::UpvarCapture::ByValue => {
939                         let mode = copy_or_move(&self.mc,
940                                                 self.param_env,
941                                                 &cmt_var,
942                                                 CaptureMove);
943                         self.delegate.consume(closure_expr.hir_id, freevar.span, &cmt_var, mode);
944                     }
945                     ty::UpvarCapture::ByRef(upvar_borrow) => {
946                         self.delegate.borrow(closure_expr.hir_id,
947                                              fn_decl_span,
948                                              &cmt_var,
949                                              upvar_borrow.region,
950                                              upvar_borrow.kind,
951                                              ClosureCapture(freevar.span));
952                     }
953                 }
954             }
955         });
956     }
957
958     fn cat_captured_var(&mut self,
959                         closure_hir_id: hir::HirId,
960                         closure_span: Span,
961                         upvar: &hir::Freevar)
962                         -> mc::McResult<mc::cmt_<'tcx>> {
963         // Create the cmt for the variable being borrowed, from the
964         // caller's perspective
965         let var_hir_id = self.tcx().hir().node_to_hir_id(upvar.var_id());
966         let var_ty = self.mc.node_ty(var_hir_id)?;
967         self.mc.cat_def(closure_hir_id, closure_span, var_ty, upvar.def)
968     }
969 }
970
971 fn copy_or_move<'a, 'gcx, 'tcx>(mc: &mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
972                                 param_env: ty::ParamEnv<'tcx>,
973                                 cmt: &mc::cmt_<'tcx>,
974                                 move_reason: MoveReason)
975                                 -> ConsumeMode
976 {
977     if !mc.type_is_copy_modulo_regions(param_env, cmt.ty, cmt.span) {
978         Move(move_reason)
979     } else {
980         Copy
981     }
982 }