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