]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
Rollup merge of #31054 - steveklabnik:a11y, r=alexcrichton
[rust.git] / src / librustc / middle / expr_use_visitor.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A different sort of visitor for walking fn bodies.  Unlike the
12 //! normal visitor, which just walks the entire body in one shot, the
13 //! `ExprUseVisitor` determines how expressions are being used.
14
15 pub use self::LoanCause::*;
16 pub use self::ConsumeMode::*;
17 pub use self::MoveReason::*;
18 pub use self::MatchMode::*;
19 use self::TrackMatchMode::*;
20 use self::OverloadedCallType::*;
21
22 use middle::pat_util;
23 use middle::def::Def;
24 use middle::def_id::{DefId};
25 use middle::infer;
26 use middle::mem_categorization as mc;
27 use middle::ty;
28 use middle::ty::adjustment;
29
30 use rustc_front::hir;
31
32 use syntax::ast;
33 use syntax::ptr::P;
34 use syntax::codemap::Span;
35
36 ///////////////////////////////////////////////////////////////////////////
37 // The Delegate trait
38
39 /// This trait defines the callbacks you can expect to receive when
40 /// employing the ExprUseVisitor.
41 pub trait Delegate<'tcx> {
42     // The value found at `cmt` is either copied or moved, depending
43     // on mode.
44     fn consume(&mut self,
45                consume_id: ast::NodeId,
46                consume_span: Span,
47                cmt: mc::cmt<'tcx>,
48                mode: ConsumeMode);
49
50     // The value found at `cmt` has been determined to match the
51     // pattern binding `matched_pat`, and its subparts are being
52     // copied or moved depending on `mode`.  Note that `matched_pat`
53     // is called on all variant/structs in the pattern (i.e., the
54     // interior nodes of the pattern's tree structure) while
55     // consume_pat is called on the binding identifiers in the pattern
56     // (which are leaves of the pattern's tree structure).
57     //
58     // Note that variants/structs and identifiers are disjoint; thus
59     // `matched_pat` and `consume_pat` are never both called on the
60     // same input pattern structure (though of `consume_pat` can be
61     // called on a subpart of an input passed to `matched_pat).
62     fn matched_pat(&mut self,
63                    matched_pat: &hir::Pat,
64                    cmt: mc::cmt<'tcx>,
65                    mode: MatchMode);
66
67     // The value found at `cmt` is either copied or moved via the
68     // pattern binding `consume_pat`, depending on mode.
69     fn consume_pat(&mut self,
70                    consume_pat: &hir::Pat,
71                    cmt: mc::cmt<'tcx>,
72                    mode: ConsumeMode);
73
74     // The value found at `borrow` is being borrowed at the point
75     // `borrow_id` for the region `loan_region` with kind `bk`.
76     fn borrow(&mut self,
77               borrow_id: ast::NodeId,
78               borrow_span: Span,
79               cmt: mc::cmt<'tcx>,
80               loan_region: ty::Region,
81               bk: ty::BorrowKind,
82               loan_cause: LoanCause);
83
84     // The local variable `id` is declared but not initialized.
85     fn decl_without_init(&mut self,
86                          id: ast::NodeId,
87                          span: Span);
88
89     // The path at `cmt` is being assigned to.
90     fn mutate(&mut self,
91               assignment_id: ast::NodeId,
92               assignment_span: Span,
93               assignee_cmt: mc::cmt<'tcx>,
94               mode: MutateMode);
95 }
96
97 #[derive(Copy, Clone, PartialEq, Debug)]
98 pub enum LoanCause {
99     ClosureCapture(Span),
100     AddrOf,
101     AutoRef,
102     AutoUnsafe,
103     RefBinding,
104     OverloadedOperator,
105     ClosureInvocation,
106     ForLoop,
107     MatchDiscriminant
108 }
109
110 #[derive(Copy, Clone, PartialEq, Debug)]
111 pub enum ConsumeMode {
112     Copy,                // reference to x where x has a type that copies
113     Move(MoveReason),    // reference to x where x has a type that moves
114 }
115
116 #[derive(Copy, Clone, PartialEq, Debug)]
117 pub enum MoveReason {
118     DirectRefMove,
119     PatBindingMove,
120     CaptureMove,
121 }
122
123 #[derive(Copy, Clone, PartialEq, Debug)]
124 pub enum MatchMode {
125     NonBindingMatch,
126     BorrowingMatch,
127     CopyingMatch,
128     MovingMatch,
129 }
130
131 #[derive(Copy, Clone, PartialEq, Debug)]
132 enum TrackMatchMode {
133     Unknown,
134     Definite(MatchMode),
135     Conflicting,
136 }
137
138 impl TrackMatchMode {
139     // Builds up the whole match mode for a pattern from its constituent
140     // parts.  The lattice looks like this:
141     //
142     //          Conflicting
143     //            /     \
144     //           /       \
145     //      Borrowing   Moving
146     //           \       /
147     //            \     /
148     //            Copying
149     //               |
150     //          NonBinding
151     //               |
152     //            Unknown
153     //
154     // examples:
155     //
156     // * `(_, some_int)` pattern is Copying, since
157     //   NonBinding + Copying => Copying
158     //
159     // * `(some_int, some_box)` pattern is Moving, since
160     //   Copying + Moving => Moving
161     //
162     // * `(ref x, some_box)` pattern is Conflicting, since
163     //   Borrowing + Moving => Conflicting
164     //
165     // Note that the `Unknown` and `Conflicting` states are
166     // represented separately from the other more interesting
167     // `Definite` states, which simplifies logic here somewhat.
168     fn lub(&mut self, mode: MatchMode) {
169         *self = match (*self, mode) {
170             // Note that clause order below is very significant.
171             (Unknown, new) => Definite(new),
172             (Definite(old), new) if old == new => Definite(old),
173
174             (Definite(old), NonBindingMatch) => Definite(old),
175             (Definite(NonBindingMatch), new) => Definite(new),
176
177             (Definite(old), CopyingMatch) => Definite(old),
178             (Definite(CopyingMatch), new) => Definite(new),
179
180             (Definite(_), _) => Conflicting,
181             (Conflicting, _) => *self,
182         };
183     }
184
185     fn match_mode(&self) -> MatchMode {
186         match *self {
187             Unknown => NonBindingMatch,
188             Definite(mode) => mode,
189             Conflicting => {
190                 // Conservatively return MovingMatch to let the
191                 // compiler continue to make progress.
192                 MovingMatch
193             }
194         }
195     }
196 }
197
198 #[derive(Copy, Clone, PartialEq, Debug)]
199 pub enum MutateMode {
200     Init,
201     JustWrite,    // x = y
202     WriteAndRead, // x += y
203 }
204
205 #[derive(Copy, Clone)]
206 enum OverloadedCallType {
207     FnOverloadedCall,
208     FnMutOverloadedCall,
209     FnOnceOverloadedCall,
210 }
211
212 impl OverloadedCallType {
213     fn from_trait_id(tcx: &ty::ctxt, trait_id: DefId)
214                      -> OverloadedCallType {
215         for &(maybe_function_trait, overloaded_call_type) in &[
216             (tcx.lang_items.fn_once_trait(), FnOnceOverloadedCall),
217             (tcx.lang_items.fn_mut_trait(), FnMutOverloadedCall),
218             (tcx.lang_items.fn_trait(), FnOverloadedCall)
219         ] {
220             match maybe_function_trait {
221                 Some(function_trait) if function_trait == trait_id => {
222                     return overloaded_call_type
223                 }
224                 _ => continue,
225             }
226         }
227
228         tcx.sess.bug("overloaded call didn't map to known function trait")
229     }
230
231     fn from_method_id(tcx: &ty::ctxt, method_id: DefId)
232                       -> OverloadedCallType {
233         let method = tcx.impl_or_trait_item(method_id);
234         OverloadedCallType::from_trait_id(tcx, method.container().id())
235     }
236 }
237
238 ///////////////////////////////////////////////////////////////////////////
239 // The ExprUseVisitor type
240 //
241 // This is the code that actually walks the tree. Like
242 // mem_categorization, it requires a TYPER, which is a type that
243 // supplies types from the tree. After type checking is complete, you
244 // can just use the tcx as the typer.
245 pub struct ExprUseVisitor<'d, 't, 'a: 't, 'tcx:'a+'d> {
246     typer: &'t infer::InferCtxt<'a, 'tcx>,
247     mc: mc::MemCategorizationContext<'t, 'a, 'tcx>,
248     delegate: &'d mut Delegate<'tcx>,
249 }
250
251 // If the TYPER results in an error, it's because the type check
252 // failed (or will fail, when the error is uncovered and reported
253 // during writeback). In this case, we just ignore this part of the
254 // code.
255 //
256 // Note that this macro appears similar to try!(), but, unlike try!(),
257 // it does not propagate the error.
258 macro_rules! return_if_err {
259     ($inp: expr) => (
260         match $inp {
261             Ok(v) => v,
262             Err(()) => {
263                 debug!("mc reported err");
264                 return
265             }
266         }
267     )
268 }
269
270 /// Whether the elements of an overloaded operation are passed by value or by reference
271 enum PassArgs {
272     ByValue,
273     ByRef,
274 }
275
276 impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> {
277     pub fn new(delegate: &'d mut (Delegate<'tcx>+'d),
278                typer: &'t infer::InferCtxt<'a, 'tcx>)
279                -> ExprUseVisitor<'d,'t,'a,'tcx> where 'tcx:'a+'d
280     {
281         let mc: mc::MemCategorizationContext<'t, 'a, 'tcx> =
282             mc::MemCategorizationContext::new(typer);
283         ExprUseVisitor { typer: typer, mc: mc, delegate: delegate }
284     }
285
286     pub fn walk_fn(&mut self,
287                    decl: &hir::FnDecl,
288                    body: &hir::Block) {
289         self.walk_arg_patterns(decl, body);
290         self.walk_block(body);
291     }
292
293     fn walk_arg_patterns(&mut self,
294                          decl: &hir::FnDecl,
295                          body: &hir::Block) {
296         for arg in &decl.inputs {
297             let arg_ty = return_if_err!(self.typer.node_ty(arg.pat.id));
298
299             let fn_body_scope = self.tcx().region_maps.node_extent(body.id);
300             let arg_cmt = self.mc.cat_rvalue(
301                 arg.id,
302                 arg.pat.span,
303                 ty::ReScope(fn_body_scope), // Args live only as long as the fn body.
304                 arg_ty);
305
306             self.walk_irrefutable_pat(arg_cmt, &*arg.pat);
307         }
308     }
309
310     fn tcx(&self) -> &'t ty::ctxt<'tcx> {
311         self.typer.tcx
312     }
313
314     fn delegate_consume(&mut self,
315                         consume_id: ast::NodeId,
316                         consume_span: Span,
317                         cmt: mc::cmt<'tcx>) {
318         debug!("delegate_consume(consume_id={}, cmt={:?})",
319                consume_id, cmt);
320
321         let mode = copy_or_move(self.typer, &cmt, DirectRefMove);
322         self.delegate.consume(consume_id, consume_span, cmt, mode);
323     }
324
325     fn consume_exprs(&mut self, exprs: &[P<hir::Expr>]) {
326         for expr in exprs {
327             self.consume_expr(&**expr);
328         }
329     }
330
331     pub fn consume_expr(&mut self, expr: &hir::Expr) {
332         debug!("consume_expr(expr={:?})", expr);
333
334         let cmt = return_if_err!(self.mc.cat_expr(expr));
335         self.delegate_consume(expr.id, expr.span, cmt);
336         self.walk_expr(expr);
337     }
338
339     fn mutate_expr(&mut self,
340                    assignment_expr: &hir::Expr,
341                    expr: &hir::Expr,
342                    mode: MutateMode) {
343         let cmt = return_if_err!(self.mc.cat_expr(expr));
344         self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
345         self.walk_expr(expr);
346     }
347
348     fn borrow_expr(&mut self,
349                    expr: &hir::Expr,
350                    r: ty::Region,
351                    bk: ty::BorrowKind,
352                    cause: LoanCause) {
353         debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
354                expr, r, bk);
355
356         let cmt = return_if_err!(self.mc.cat_expr(expr));
357         self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
358
359         self.walk_expr(expr)
360     }
361
362     fn select_from_expr(&mut self, expr: &hir::Expr) {
363         self.walk_expr(expr)
364     }
365
366     pub fn walk_expr(&mut self, expr: &hir::Expr) {
367         debug!("walk_expr(expr={:?})", expr);
368
369         self.walk_adjustment(expr);
370
371         match expr.node {
372             hir::ExprPath(..) => { }
373
374             hir::ExprType(ref subexpr, _) => {
375                 self.walk_expr(&**subexpr)
376             }
377
378             hir::ExprUnary(hir::UnDeref, ref base) => {      // *base
379                 if !self.walk_overloaded_operator(expr, &**base, Vec::new(), PassArgs::ByRef) {
380                     self.select_from_expr(&**base);
381                 }
382             }
383
384             hir::ExprField(ref base, _) => {         // base.f
385                 self.select_from_expr(&**base);
386             }
387
388             hir::ExprTupField(ref base, _) => {         // base.<n>
389                 self.select_from_expr(&**base);
390             }
391
392             hir::ExprIndex(ref lhs, ref rhs) => {       // lhs[rhs]
393                 if !self.walk_overloaded_operator(expr,
394                                                   &**lhs,
395                                                   vec![&**rhs],
396                                                   PassArgs::ByValue) {
397                     self.select_from_expr(&**lhs);
398                     self.consume_expr(&**rhs);
399                 }
400             }
401
402             hir::ExprRange(ref start, ref end) => {
403                 start.as_ref().map(|e| self.consume_expr(&**e));
404                 end.as_ref().map(|e| self.consume_expr(&**e));
405             }
406
407             hir::ExprCall(ref callee, ref args) => {    // callee(args)
408                 self.walk_callee(expr, &**callee);
409                 self.consume_exprs(args);
410             }
411
412             hir::ExprMethodCall(_, _, ref args) => { // callee.m(args)
413                 self.consume_exprs(args);
414             }
415
416             hir::ExprStruct(_, ref fields, ref opt_with) => {
417                 self.walk_struct_expr(expr, fields, opt_with);
418             }
419
420             hir::ExprTup(ref exprs) => {
421                 self.consume_exprs(exprs);
422             }
423
424             hir::ExprIf(ref cond_expr, ref then_blk, ref opt_else_expr) => {
425                 self.consume_expr(&**cond_expr);
426                 self.walk_block(&**then_blk);
427                 if let Some(ref else_expr) = *opt_else_expr {
428                     self.consume_expr(&**else_expr);
429                 }
430             }
431
432             hir::ExprMatch(ref discr, ref arms, _) => {
433                 let discr_cmt = return_if_err!(self.mc.cat_expr(&**discr));
434                 self.borrow_expr(&**discr, ty::ReEmpty, ty::ImmBorrow, MatchDiscriminant);
435
436                 // treatment of the discriminant is handled while walking the arms.
437                 for arm in arms {
438                     let mode = self.arm_move_mode(discr_cmt.clone(), arm);
439                     let mode = mode.match_mode();
440                     self.walk_arm(discr_cmt.clone(), arm, mode);
441                 }
442             }
443
444             hir::ExprVec(ref exprs) => {
445                 self.consume_exprs(exprs);
446             }
447
448             hir::ExprAddrOf(m, ref base) => {   // &base
449                 // make sure that the thing we are pointing out stays valid
450                 // for the lifetime `scope_r` of the resulting ptr:
451                 let expr_ty = return_if_err!(self.typer.node_ty(expr.id));
452                 if let ty::TyRef(&r, _) = expr_ty.sty {
453                     let bk = ty::BorrowKind::from_mutbl(m);
454                     self.borrow_expr(&**base, r, bk, AddrOf);
455                 }
456             }
457
458             hir::ExprInlineAsm(ref ia) => {
459                 for &(_, ref input) in &ia.inputs {
460                     self.consume_expr(&**input);
461                 }
462
463                 for output in &ia.outputs {
464                     if output.is_indirect {
465                         self.consume_expr(&*output.expr);
466                     } else {
467                         self.mutate_expr(expr, &*output.expr,
468                                          if output.is_rw {
469                                              MutateMode::WriteAndRead
470                                          } else {
471                                              MutateMode::JustWrite
472                                          });
473                     }
474                 }
475             }
476
477             hir::ExprBreak(..) |
478             hir::ExprAgain(..) |
479             hir::ExprLit(..) => {}
480
481             hir::ExprLoop(ref blk, _) => {
482                 self.walk_block(&**blk);
483             }
484
485             hir::ExprWhile(ref cond_expr, ref blk, _) => {
486                 self.consume_expr(&**cond_expr);
487                 self.walk_block(&**blk);
488             }
489
490             hir::ExprUnary(op, ref lhs) => {
491                 let pass_args = if ::rustc_front::util::is_by_value_unop(op) {
492                     PassArgs::ByValue
493                 } else {
494                     PassArgs::ByRef
495                 };
496
497                 if !self.walk_overloaded_operator(expr, &**lhs, Vec::new(), pass_args) {
498                     self.consume_expr(&**lhs);
499                 }
500             }
501
502             hir::ExprBinary(op, ref lhs, ref rhs) => {
503                 let pass_args = if ::rustc_front::util::is_by_value_binop(op.node) {
504                     PassArgs::ByValue
505                 } else {
506                     PassArgs::ByRef
507                 };
508
509                 if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs], pass_args) {
510                     self.consume_expr(&**lhs);
511                     self.consume_expr(&**rhs);
512                 }
513             }
514
515             hir::ExprBlock(ref blk) => {
516                 self.walk_block(&**blk);
517             }
518
519             hir::ExprRet(ref opt_expr) => {
520                 if let Some(ref expr) = *opt_expr {
521                     self.consume_expr(&**expr);
522                 }
523             }
524
525             hir::ExprAssign(ref lhs, ref rhs) => {
526                 self.mutate_expr(expr, &**lhs, MutateMode::JustWrite);
527                 self.consume_expr(&**rhs);
528             }
529
530             hir::ExprCast(ref base, _) => {
531                 self.consume_expr(&**base);
532             }
533
534             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
535                 // NB All our assignment operations take the RHS by value
536                 assert!(::rustc_front::util::is_by_value_binop(op.node));
537
538                 if !self.walk_overloaded_operator(expr, lhs, vec![rhs], PassArgs::ByValue) {
539                     self.mutate_expr(expr, &**lhs, MutateMode::WriteAndRead);
540                     self.consume_expr(&**rhs);
541                 }
542             }
543
544             hir::ExprRepeat(ref base, ref count) => {
545                 self.consume_expr(&**base);
546                 self.consume_expr(&**count);
547             }
548
549             hir::ExprClosure(..) => {
550                 self.walk_captures(expr)
551             }
552
553             hir::ExprBox(ref base) => {
554                 self.consume_expr(&**base);
555             }
556         }
557     }
558
559     fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
560         let callee_ty = return_if_err!(self.typer.expr_ty_adjusted(callee));
561         debug!("walk_callee: callee={:?} callee_ty={:?}",
562                callee, callee_ty);
563         let call_scope = self.tcx().region_maps.node_extent(call.id);
564         match callee_ty.sty {
565             ty::TyBareFn(..) => {
566                 self.consume_expr(callee);
567             }
568             ty::TyError => { }
569             _ => {
570                 let overloaded_call_type =
571                     match self.typer.node_method_id(ty::MethodCall::expr(call.id)) {
572                         Some(method_id) => {
573                             OverloadedCallType::from_method_id(self.tcx(), method_id)
574                         }
575                         None => {
576                             self.tcx().sess.span_bug(
577                                 callee.span,
578                                 &format!("unexpected callee type {}", callee_ty))
579                         }
580                     };
581                 match overloaded_call_type {
582                     FnMutOverloadedCall => {
583                         self.borrow_expr(callee,
584                                          ty::ReScope(call_scope),
585                                          ty::MutBorrow,
586                                          ClosureInvocation);
587                     }
588                     FnOverloadedCall => {
589                         self.borrow_expr(callee,
590                                          ty::ReScope(call_scope),
591                                          ty::ImmBorrow,
592                                          ClosureInvocation);
593                     }
594                     FnOnceOverloadedCall => self.consume_expr(callee),
595                 }
596             }
597         }
598     }
599
600     fn walk_stmt(&mut self, stmt: &hir::Stmt) {
601         match stmt.node {
602             hir::StmtDecl(ref decl, _) => {
603                 match decl.node {
604                     hir::DeclLocal(ref local) => {
605                         self.walk_local(&**local);
606                     }
607
608                     hir::DeclItem(_) => {
609                         // we don't visit nested items in this visitor,
610                         // only the fn body we were given.
611                     }
612                 }
613             }
614
615             hir::StmtExpr(ref expr, _) |
616             hir::StmtSemi(ref expr, _) => {
617                 self.consume_expr(&**expr);
618             }
619         }
620     }
621
622     fn walk_local(&mut self, local: &hir::Local) {
623         match local.init {
624             None => {
625                 let delegate = &mut self.delegate;
626                 pat_util::pat_bindings(&self.typer.tcx.def_map, &*local.pat,
627                                        |_, id, span, _| {
628                     delegate.decl_without_init(id, span);
629                 })
630             }
631
632             Some(ref expr) => {
633                 // Variable declarations with
634                 // initializers are considered
635                 // "assigns", which is handled by
636                 // `walk_pat`:
637                 self.walk_expr(&**expr);
638                 let init_cmt = return_if_err!(self.mc.cat_expr(&**expr));
639                 self.walk_irrefutable_pat(init_cmt, &*local.pat);
640             }
641         }
642     }
643
644     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
645     /// depending on its type.
646     fn walk_block(&mut self, blk: &hir::Block) {
647         debug!("walk_block(blk.id={})", blk.id);
648
649         for stmt in &blk.stmts {
650             self.walk_stmt(stmt);
651         }
652
653         if let Some(ref tail_expr) = blk.expr {
654             self.consume_expr(&**tail_expr);
655         }
656     }
657
658     fn walk_struct_expr(&mut self,
659                         _expr: &hir::Expr,
660                         fields: &[hir::Field],
661                         opt_with: &Option<P<hir::Expr>>) {
662         // Consume the expressions supplying values for each field.
663         for field in fields {
664             self.consume_expr(&*field.expr);
665         }
666
667         let with_expr = match *opt_with {
668             Some(ref w) => &**w,
669             None => { return; }
670         };
671
672         let with_cmt = return_if_err!(self.mc.cat_expr(&*with_expr));
673
674         // Select just those fields of the `with`
675         // expression that will actually be used
676         if let ty::TyStruct(def, substs) = with_cmt.ty.sty {
677             // Consume those fields of the with expression that are needed.
678             for with_field in &def.struct_variant().fields {
679                 if !contains_field_named(with_field, fields) {
680                     let cmt_field = self.mc.cat_field(
681                         &*with_expr,
682                         with_cmt.clone(),
683                         with_field.name,
684                         with_field.ty(self.tcx(), substs)
685                     );
686                     self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
687                 }
688             }
689         } else {
690             // the base expression should always evaluate to a
691             // struct; however, when EUV is run during typeck, it
692             // may not. This will generate an error earlier in typeck,
693             // so we can just ignore it.
694             if !self.tcx().sess.has_errors() {
695                 self.tcx().sess.span_bug(
696                     with_expr.span,
697                     "with expression doesn't evaluate to a struct");
698             }
699         };
700
701         // walk the with expression so that complex expressions
702         // are properly handled.
703         self.walk_expr(with_expr);
704
705         fn contains_field_named(field: ty::FieldDef,
706                                 fields: &[hir::Field])
707                                 -> bool
708         {
709             fields.iter().any(
710                 |f| f.name.node == field.name)
711         }
712     }
713
714     // Invoke the appropriate delegate calls for anything that gets
715     // consumed or borrowed as part of the automatic adjustment
716     // process.
717     fn walk_adjustment(&mut self, expr: &hir::Expr) {
718         let typer = self.typer;
719         //NOTE(@jroesch): mixed RefCell borrow causes crash
720         let adj = typer.adjustments().get(&expr.id).map(|x| x.clone());
721         if let Some(adjustment) = adj {
722             match adjustment {
723                 adjustment::AdjustReifyFnPointer |
724                 adjustment::AdjustUnsafeFnPointer => {
725                     // Creating a closure/fn-pointer or unsizing consumes
726                     // the input and stores it into the resulting rvalue.
727                     debug!("walk_adjustment(AdjustReifyFnPointer|AdjustUnsafeFnPointer)");
728                     let cmt_unadjusted =
729                         return_if_err!(self.mc.cat_expr_unadjusted(expr));
730                     self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
731                 }
732                 adjustment::AdjustDerefRef(ref adj) => {
733                     self.walk_autoderefref(expr, adj);
734                 }
735             }
736         }
737     }
738
739     /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
740     /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
741     /// `deref()` is declared with `&self`, this is an autoref of `x`.
742     fn walk_autoderefs(&mut self,
743                        expr: &hir::Expr,
744                        autoderefs: usize) {
745         debug!("walk_autoderefs expr={:?} autoderefs={}", expr, autoderefs);
746
747         for i in 0..autoderefs {
748             let deref_id = ty::MethodCall::autoderef(expr.id, i as u32);
749             match self.typer.node_method_ty(deref_id) {
750                 None => {}
751                 Some(method_ty) => {
752                     let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
753
754                     // the method call infrastructure should have
755                     // replaced all late-bound regions with variables:
756                     let self_ty = method_ty.fn_sig().input(0);
757                     let self_ty = self.tcx().no_late_bound_regions(&self_ty).unwrap();
758
759                     let (m, r) = match self_ty.sty {
760                         ty::TyRef(r, ref m) => (m.mutbl, r),
761                         _ => self.tcx().sess.span_bug(expr.span,
762                                 &format!("bad overloaded deref type {:?}",
763                                     method_ty))
764                     };
765                     let bk = ty::BorrowKind::from_mutbl(m);
766                     self.delegate.borrow(expr.id, expr.span, cmt,
767                                          *r, bk, AutoRef);
768                 }
769             }
770         }
771     }
772
773     fn walk_autoderefref(&mut self,
774                          expr: &hir::Expr,
775                          adj: &adjustment::AutoDerefRef<'tcx>) {
776         debug!("walk_autoderefref expr={:?} adj={:?}",
777                expr,
778                adj);
779
780         self.walk_autoderefs(expr, adj.autoderefs);
781
782         let cmt_derefd =
783             return_if_err!(self.mc.cat_expr_autoderefd(expr, adj.autoderefs));
784
785         let cmt_refd =
786             self.walk_autoref(expr, cmt_derefd, adj.autoref);
787
788         if adj.unsize.is_some() {
789             // Unsizing consumes the thin pointer and produces a fat one.
790             self.delegate_consume(expr.id, expr.span, cmt_refd);
791         }
792     }
793
794
795     /// Walks the autoref `opt_autoref` applied to the autoderef'd
796     /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
797     /// after all relevant autoderefs have occurred. Because AutoRefs
798     /// can be recursive, this function is recursive: it first walks
799     /// deeply all the way down the autoref chain, and then processes
800     /// the autorefs on the way out. At each point, it returns the
801     /// `cmt` for the rvalue that will be produced by introduced an
802     /// autoref.
803     fn walk_autoref(&mut self,
804                     expr: &hir::Expr,
805                     cmt_base: mc::cmt<'tcx>,
806                     opt_autoref: Option<adjustment::AutoRef<'tcx>>)
807                     -> mc::cmt<'tcx>
808     {
809         debug!("walk_autoref(expr.id={} cmt_derefd={:?} opt_autoref={:?})",
810                expr.id,
811                cmt_base,
812                opt_autoref);
813
814         let cmt_base_ty = cmt_base.ty;
815
816         let autoref = match opt_autoref {
817             Some(ref autoref) => autoref,
818             None => {
819                 // No AutoRef.
820                 return cmt_base;
821             }
822         };
823
824         match *autoref {
825             adjustment::AutoPtr(r, m) => {
826                 self.delegate.borrow(expr.id,
827                                      expr.span,
828                                      cmt_base,
829                                      *r,
830                                      ty::BorrowKind::from_mutbl(m),
831                                      AutoRef);
832             }
833
834             adjustment::AutoUnsafe(m) => {
835                 debug!("walk_autoref: expr.id={} cmt_base={:?}",
836                        expr.id,
837                        cmt_base);
838
839                 // Converting from a &T to *T (or &mut T to *mut T) is
840                 // treated as borrowing it for the enclosing temporary
841                 // scope.
842                 let r = ty::ReScope(self.tcx().region_maps.node_extent(expr.id));
843
844                 self.delegate.borrow(expr.id,
845                                      expr.span,
846                                      cmt_base,
847                                      r,
848                                      ty::BorrowKind::from_mutbl(m),
849                                      AutoUnsafe);
850             }
851         }
852
853         // Construct the categorization for the result of the autoref.
854         // This is always an rvalue, since we are producing a new
855         // (temporary) indirection.
856
857         let adj_ty = cmt_base_ty.adjust_for_autoref(self.tcx(), opt_autoref);
858
859         self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
860     }
861
862
863     // When this returns true, it means that the expression *is* a
864     // method-call (i.e. via the operator-overload).  This true result
865     // also implies that walk_overloaded_operator already took care of
866     // recursively processing the input arguments, and thus the caller
867     // should not do so.
868     fn walk_overloaded_operator(&mut self,
869                                 expr: &hir::Expr,
870                                 receiver: &hir::Expr,
871                                 rhs: Vec<&hir::Expr>,
872                                 pass_args: PassArgs)
873                                 -> bool
874     {
875         if !self.typer.is_method_call(expr.id) {
876             return false;
877         }
878
879         match pass_args {
880             PassArgs::ByValue => {
881                 self.consume_expr(receiver);
882                 for &arg in &rhs {
883                     self.consume_expr(arg);
884                 }
885
886                 return true;
887             },
888             PassArgs::ByRef => {},
889         }
890
891         self.walk_expr(receiver);
892
893         // Arguments (but not receivers) to overloaded operator
894         // methods are implicitly autoref'd which sadly does not use
895         // adjustments, so we must hardcode the borrow here.
896
897         let r = ty::ReScope(self.tcx().region_maps.node_extent(expr.id));
898         let bk = ty::ImmBorrow;
899
900         for &arg in &rhs {
901             self.borrow_expr(arg, r, bk, OverloadedOperator);
902         }
903         return true;
904     }
905
906     fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
907         let mut mode = Unknown;
908         for pat in &arm.pats {
909             self.determine_pat_move_mode(discr_cmt.clone(), &**pat, &mut mode);
910         }
911         mode
912     }
913
914     fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
915         for pat in &arm.pats {
916             self.walk_pat(discr_cmt.clone(), &**pat, mode);
917         }
918
919         if let Some(ref guard) = arm.guard {
920             self.consume_expr(&**guard);
921         }
922
923         self.consume_expr(&*arm.body);
924     }
925
926     /// Walks a pat that occurs in isolation (i.e. top-level of fn
927     /// arg or let binding.  *Not* a match arm or nested pat.)
928     fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
929         let mut mode = Unknown;
930         self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
931         let mode = mode.match_mode();
932         self.walk_pat(cmt_discr, pat, mode);
933     }
934
935     /// Identifies any bindings within `pat` and accumulates within
936     /// `mode` whether the overall pattern/match structure is a move,
937     /// copy, or borrow.
938     fn determine_pat_move_mode(&mut self,
939                                cmt_discr: mc::cmt<'tcx>,
940                                pat: &hir::Pat,
941                                mode: &mut TrackMatchMode) {
942         debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
943                pat);
944         return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
945             let tcx = self.tcx();
946             let def_map = &self.tcx().def_map;
947             if pat_util::pat_is_binding(&def_map.borrow(), pat) {
948                 match pat.node {
949                     hir::PatIdent(hir::BindByRef(_), _, _) =>
950                         mode.lub(BorrowingMatch),
951                     hir::PatIdent(hir::BindByValue(_), _, _) => {
952                         match copy_or_move(self.typer, &cmt_pat, PatBindingMove) {
953                             Copy => mode.lub(CopyingMatch),
954                             Move(_) => mode.lub(MovingMatch),
955                         }
956                     }
957                     _ => {
958                         tcx.sess.span_bug(
959                             pat.span,
960                             "binding pattern not an identifier");
961                     }
962                 }
963             }
964         }));
965     }
966
967     /// The core driver for walking a pattern; `match_mode` must be
968     /// established up front, e.g. via `determine_pat_move_mode` (see
969     /// also `walk_irrefutable_pat` for patterns that stand alone).
970     fn walk_pat(&mut self,
971                 cmt_discr: mc::cmt<'tcx>,
972                 pat: &hir::Pat,
973                 match_mode: MatchMode) {
974         debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr,
975                pat);
976
977         let mc = &self.mc;
978         let typer = self.typer;
979         let def_map = &self.tcx().def_map;
980         let delegate = &mut self.delegate;
981         return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
982             if pat_util::pat_is_binding(&def_map.borrow(), pat) {
983                 let tcx = typer.tcx;
984
985                 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}",
986                        cmt_pat,
987                        pat,
988                        match_mode);
989
990                 // pat_ty: the type of the binding being produced.
991                 let pat_ty = return_if_err!(typer.node_ty(pat.id));
992
993                 // Each match binding is effectively an assignment to the
994                 // binding being produced.
995                 let def = def_map.borrow().get(&pat.id).unwrap().full_def();
996                 match mc.cat_def(pat.id, pat.span, pat_ty, def) {
997                     Ok(binding_cmt) => {
998                         delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
999                     }
1000                     Err(_) => { }
1001                 }
1002
1003                 // It is also a borrow or copy/move of the value being matched.
1004                 match pat.node {
1005                     hir::PatIdent(hir::BindByRef(m), _, _) => {
1006                         if let ty::TyRef(&r, _) = pat_ty.sty {
1007                             let bk = ty::BorrowKind::from_mutbl(m);
1008                             delegate.borrow(pat.id, pat.span, cmt_pat,
1009                                             r, bk, RefBinding);
1010                         }
1011                     }
1012                     hir::PatIdent(hir::BindByValue(_), _, _) => {
1013                         let mode = copy_or_move(typer, &cmt_pat, PatBindingMove);
1014                         debug!("walk_pat binding consuming pat");
1015                         delegate.consume_pat(pat, cmt_pat, mode);
1016                     }
1017                     _ => {
1018                         tcx.sess.span_bug(
1019                             pat.span,
1020                             "binding pattern not an identifier");
1021                     }
1022                 }
1023             } else {
1024                 match pat.node {
1025                     hir::PatVec(_, Some(ref slice_pat), _) => {
1026                         // The `slice_pat` here creates a slice into
1027                         // the original vector.  This is effectively a
1028                         // borrow of the elements of the vector being
1029                         // matched.
1030
1031                         let (slice_cmt, slice_mutbl, slice_r) =
1032                             return_if_err!(mc.cat_slice_pattern(cmt_pat, &**slice_pat));
1033
1034                         // Note: We declare here that the borrow
1035                         // occurs upon entering the `[...]`
1036                         // pattern. This implies that something like
1037                         // `[a; b]` where `a` is a move is illegal,
1038                         // because the borrow is already in effect.
1039                         // In fact such a move would be safe-ish, but
1040                         // it effectively *requires* that we use the
1041                         // nulling out semantics to indicate when a
1042                         // value has been moved, which we are trying
1043                         // to move away from.  Otherwise, how can we
1044                         // indicate that the first element in the
1045                         // vector has been moved?  Eventually, we
1046                         // could perhaps modify this rule to permit
1047                         // `[..a, b]` where `b` is a move, because in
1048                         // that case we can adjust the length of the
1049                         // original vec accordingly, but we'd have to
1050                         // make trans do the right thing, and it would
1051                         // only work for `Box<[T]>`s. It seems simpler
1052                         // to just require that people call
1053                         // `vec.pop()` or `vec.unshift()`.
1054                         let slice_bk = ty::BorrowKind::from_mutbl(slice_mutbl);
1055                         delegate.borrow(pat.id, pat.span,
1056                                         slice_cmt, slice_r,
1057                                         slice_bk, RefBinding);
1058                     }
1059                     _ => { }
1060                 }
1061             }
1062         }));
1063
1064         // Do a second pass over the pattern, calling `matched_pat` on
1065         // the interior nodes (enum variants and structs), as opposed
1066         // to the above loop's visit of than the bindings that form
1067         // the leaves of the pattern tree structure.
1068         return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
1069             let def_map = def_map.borrow();
1070             let tcx = typer.tcx;
1071
1072             match pat.node {
1073                 hir::PatEnum(_, _) | hir::PatQPath(..) |
1074                 hir::PatIdent(_, _, None) | hir::PatStruct(..) => {
1075                     match def_map.get(&pat.id).map(|d| d.full_def()) {
1076                         None => {
1077                             // no definition found: pat is not a
1078                             // struct or enum pattern.
1079                         }
1080
1081                         Some(Def::Variant(enum_did, variant_did)) => {
1082                             let downcast_cmt =
1083                                 if tcx.lookup_adt_def(enum_did).is_univariant() {
1084                                     cmt_pat
1085                                 } else {
1086                                     let cmt_pat_ty = cmt_pat.ty;
1087                                     mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
1088                                 };
1089
1090                             debug!("variant downcast_cmt={:?} pat={:?}",
1091                                    downcast_cmt,
1092                                    pat);
1093
1094                             delegate.matched_pat(pat, downcast_cmt, match_mode);
1095                         }
1096
1097                         Some(Def::Struct(..)) | Some(Def::TyAlias(..)) => {
1098                             // A struct (in either the value or type
1099                             // namespace; we encounter the former on
1100                             // e.g. patterns for unit structs).
1101
1102                             debug!("struct cmt_pat={:?} pat={:?}",
1103                                    cmt_pat,
1104                                    pat);
1105
1106                             delegate.matched_pat(pat, cmt_pat, match_mode);
1107                         }
1108
1109                         Some(Def::Const(..)) |
1110                         Some(Def::AssociatedConst(..)) |
1111                         Some(Def::Local(..)) => {
1112                             // This is a leaf (i.e. identifier binding
1113                             // or constant value to match); thus no
1114                             // `matched_pat` call.
1115                         }
1116
1117                         Some(def) => {
1118                             // An enum type should never be in a pattern.
1119                             // Remaining cases are e.g. Def::Fn, to
1120                             // which identifiers within patterns
1121                             // should not resolve. However, we do
1122                             // encouter this when using the
1123                             // expr-use-visitor during typeck. So just
1124                             // ignore it, an error should have been
1125                             // reported.
1126
1127                             if !tcx.sess.has_errors() {
1128                                 let msg = format!("Pattern has unexpected def: {:?} and type {:?}",
1129                                                   def,
1130                                                   cmt_pat.ty);
1131                                 tcx.sess.span_bug(pat.span, &msg[..])
1132                             }
1133                         }
1134                     }
1135                 }
1136
1137                 hir::PatIdent(_, _, Some(_)) => {
1138                     // Do nothing; this is a binding (not an enum
1139                     // variant or struct), and the cat_pattern call
1140                     // will visit the substructure recursively.
1141                 }
1142
1143                 hir::PatWild | hir::PatTup(..) | hir::PatBox(..) |
1144                 hir::PatRegion(..) | hir::PatLit(..) | hir::PatRange(..) |
1145                 hir::PatVec(..) => {
1146                     // Similarly, each of these cases does not
1147                     // correspond to an enum variant or struct, so we
1148                     // do not do any `matched_pat` calls for these
1149                     // cases either.
1150                 }
1151             }
1152         }));
1153     }
1154
1155     fn walk_captures(&mut self, closure_expr: &hir::Expr) {
1156         debug!("walk_captures({:?})", closure_expr);
1157
1158         self.tcx().with_freevars(closure_expr.id, |freevars| {
1159             for freevar in freevars {
1160                 let id_var = freevar.def.var_id();
1161                 let upvar_id = ty::UpvarId { var_id: id_var,
1162                                              closure_expr_id: closure_expr.id };
1163                 let upvar_capture = self.typer.upvar_capture(upvar_id).unwrap();
1164                 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1165                                                                    closure_expr.span,
1166                                                                    freevar.def));
1167                 match upvar_capture {
1168                     ty::UpvarCapture::ByValue => {
1169                         let mode = copy_or_move(self.typer, &cmt_var, CaptureMove);
1170                         self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
1171                     }
1172                     ty::UpvarCapture::ByRef(upvar_borrow) => {
1173                         self.delegate.borrow(closure_expr.id,
1174                                              closure_expr.span,
1175                                              cmt_var,
1176                                              upvar_borrow.region,
1177                                              upvar_borrow.kind,
1178                                              ClosureCapture(freevar.span));
1179                     }
1180                 }
1181             }
1182         });
1183     }
1184
1185     fn cat_captured_var(&mut self,
1186                         closure_id: ast::NodeId,
1187                         closure_span: Span,
1188                         upvar_def: Def)
1189                         -> mc::McResult<mc::cmt<'tcx>> {
1190         // Create the cmt for the variable being borrowed, from the
1191         // caller's perspective
1192         let var_id = upvar_def.var_id();
1193         let var_ty = try!(self.typer.node_ty(var_id));
1194         self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
1195     }
1196 }
1197
1198 fn copy_or_move<'a, 'tcx>(typer: &infer::InferCtxt<'a, 'tcx>,
1199                       cmt: &mc::cmt<'tcx>,
1200                       move_reason: MoveReason)
1201                       -> ConsumeMode
1202 {
1203     if typer.type_moves_by_default(cmt.ty, cmt.span) {
1204         Move(move_reason)
1205     } else {
1206         Copy
1207     }
1208 }