]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
b65046022b7f49b7ca6c0c07cefa6690ef345d74
[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 hir::def::Def;
23 use hir::def_id::DefId;
24 use infer::InferCtxt;
25 use middle::mem_categorization as mc;
26 use middle::region;
27 use ty::{self, TyCtxt, adjustment};
28
29 use hir::{self, PatKind};
30 use rustc_data_structures::sync::Lrc;
31 use syntax::ast;
32 use syntax::ptr::P;
33 use syntax_pos::Span;
34 use util::nodemap::ItemLocalSet;
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<'tcx>,
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: TyCtxt, trait_id: DefId) -> OverloadedCallType {
214         for &(maybe_function_trait, overloaded_call_type) in &[
215             (tcx.lang_items().fn_once_trait(), FnOnceOverloadedCall),
216             (tcx.lang_items().fn_mut_trait(), FnMutOverloadedCall),
217             (tcx.lang_items().fn_trait(), FnOverloadedCall)
218         ] {
219             match maybe_function_trait {
220                 Some(function_trait) if function_trait == trait_id => {
221                     return overloaded_call_type
222                 }
223                 _ => continue,
224             }
225         }
226
227         bug!("overloaded call didn't map to known function trait")
228     }
229
230     fn from_method_id(tcx: TyCtxt, method_id: DefId) -> OverloadedCallType {
231         let method = tcx.associated_item(method_id);
232         OverloadedCallType::from_trait_id(tcx, method.container.id())
233     }
234 }
235
236 ///////////////////////////////////////////////////////////////////////////
237 // The ExprUseVisitor type
238 //
239 // This is the code that actually walks the tree.
240 pub struct ExprUseVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
241     mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
242     delegate: &'a mut Delegate<'tcx>,
243     param_env: ty::ParamEnv<'tcx>,
244 }
245
246 // If the MC results in an error, it's because the type check
247 // failed (or will fail, when the error is uncovered and reported
248 // during writeback). In this case, we just ignore this part of the
249 // code.
250 //
251 // Note that this macro appears similar to try!(), but, unlike try!(),
252 // it does not propagate the error.
253 macro_rules! return_if_err {
254     ($inp: expr) => (
255         match $inp {
256             Ok(v) => v,
257             Err(()) => {
258                 debug!("mc reported err");
259                 return
260             }
261         }
262     )
263 }
264
265 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx, 'tcx> {
266     /// Creates the ExprUseVisitor, configuring it with the various options provided:
267     ///
268     /// - `delegate` -- who receives the callbacks
269     /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
270     /// - `region_scope_tree` --- region scope tree for the code being analyzed
271     /// - `tables` --- typeck results for the code being analyzed
272     /// - `rvalue_promotable_map` --- if you care about rvalue promotion, then provide
273     ///   the map here (it can be computed with `tcx.rvalue_promotable_map(def_id)`).
274     ///   `None` means that rvalues will be given more conservative lifetimes.
275     ///
276     /// See also `with_infer`, which is used *during* typeck.
277     pub fn new(delegate: &'a mut (Delegate<'tcx>+'a),
278                tcx: TyCtxt<'a, 'tcx, 'tcx>,
279                param_env: ty::ParamEnv<'tcx>,
280                region_scope_tree: &'a region::ScopeTree,
281                tables: &'a ty::TypeckTables<'tcx>,
282                rvalue_promotable_map: Option<Lrc<ItemLocalSet>>)
283                -> Self
284     {
285         ExprUseVisitor {
286             mc: mc::MemCategorizationContext::new(tcx,
287                                                   region_scope_tree,
288                                                   tables,
289                                                   rvalue_promotable_map),
290             delegate,
291             param_env,
292         }
293     }
294 }
295
296 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
297     pub fn with_infer(delegate: &'a mut (Delegate<'tcx>+'a),
298                       infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
299                       param_env: ty::ParamEnv<'tcx>,
300                       region_scope_tree: &'a region::ScopeTree,
301                       tables: &'a ty::TypeckTables<'tcx>)
302                       -> Self
303     {
304         ExprUseVisitor {
305             mc: mc::MemCategorizationContext::with_infer(infcx, region_scope_tree, tables),
306             delegate,
307             param_env,
308         }
309     }
310
311     pub fn consume_body(&mut self, body: &hir::Body) {
312         debug!("consume_body(body={:?})", body);
313
314         for arg in &body.arguments {
315             let arg_ty = return_if_err!(self.mc.node_ty(arg.pat.hir_id));
316
317             let fn_body_scope_r =
318                 self.tcx().mk_region(ty::ReScope(region::Scope::Node(body.value.hir_id.local_id)));
319             let arg_cmt = self.mc.cat_rvalue(
320                 arg.id,
321                 arg.pat.span,
322                 fn_body_scope_r, // Args live only as long as the fn body.
323                 arg_ty);
324
325             self.walk_irrefutable_pat(arg_cmt, &arg.pat);
326         }
327
328         self.consume_expr(&body.value);
329     }
330
331     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
332         self.mc.tcx
333     }
334
335     fn delegate_consume(&mut self,
336                         consume_id: ast::NodeId,
337                         consume_span: Span,
338                         cmt: mc::cmt<'tcx>) {
339         debug!("delegate_consume(consume_id={}, cmt={:?})",
340                consume_id, cmt);
341
342         let mode = copy_or_move(&self.mc, self.param_env, &cmt, DirectRefMove);
343         self.delegate.consume(consume_id, consume_span, cmt, mode);
344     }
345
346     fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
347         for expr in exprs {
348             self.consume_expr(&expr);
349         }
350     }
351
352     pub fn consume_expr(&mut self, expr: &hir::Expr) {
353         debug!("consume_expr(expr={:?})", expr);
354
355         let cmt = return_if_err!(self.mc.cat_expr(expr));
356         self.delegate_consume(expr.id, expr.span, cmt);
357         self.walk_expr(expr);
358     }
359
360     fn mutate_expr(&mut self,
361                    assignment_expr: &hir::Expr,
362                    expr: &hir::Expr,
363                    mode: MutateMode) {
364         let cmt = return_if_err!(self.mc.cat_expr(expr));
365         self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
366         self.walk_expr(expr);
367     }
368
369     fn borrow_expr(&mut self,
370                    expr: &hir::Expr,
371                    r: ty::Region<'tcx>,
372                    bk: ty::BorrowKind,
373                    cause: LoanCause) {
374         debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
375                expr, r, bk);
376
377         let cmt = return_if_err!(self.mc.cat_expr(expr));
378         self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
379
380         self.walk_expr(expr)
381     }
382
383     fn select_from_expr(&mut self, expr: &hir::Expr) {
384         self.walk_expr(expr)
385     }
386
387     pub fn walk_expr(&mut self, expr: &hir::Expr) {
388         debug!("walk_expr(expr={:?})", expr);
389
390         self.walk_adjustment(expr);
391
392         match expr.node {
393             hir::ExprPath(_) => { }
394
395             hir::ExprType(ref subexpr, _) => {
396                 self.walk_expr(&subexpr)
397             }
398
399             hir::ExprUnary(hir::UnDeref, ref base) => {      // *base
400                 self.select_from_expr(&base);
401             }
402
403             hir::ExprField(ref base, _) => {         // base.f
404                 self.select_from_expr(&base);
405             }
406
407             hir::ExprTupField(ref base, _) => {         // base.<n>
408                 self.select_from_expr(&base);
409             }
410
411             hir::ExprIndex(ref lhs, ref rhs) => {       // lhs[rhs]
412                 self.select_from_expr(&lhs);
413                 self.consume_expr(&rhs);
414             }
415
416             hir::ExprCall(ref callee, ref args) => {    // callee(args)
417                 self.walk_callee(expr, &callee);
418                 self.consume_exprs(args);
419             }
420
421             hir::ExprMethodCall(.., ref args) => { // callee.m(args)
422                 self.consume_exprs(args);
423             }
424
425             hir::ExprStruct(_, ref fields, ref opt_with) => {
426                 self.walk_struct_expr(fields, opt_with);
427             }
428
429             hir::ExprTup(ref exprs) => {
430                 self.consume_exprs(exprs);
431             }
432
433             hir::ExprIf(ref cond_expr, ref then_expr, ref opt_else_expr) => {
434                 self.consume_expr(&cond_expr);
435                 self.walk_expr(&then_expr);
436                 if let Some(ref else_expr) = *opt_else_expr {
437                     self.consume_expr(&else_expr);
438                 }
439             }
440
441             hir::ExprMatch(ref discr, ref arms, _) => {
442                 let discr_cmt = return_if_err!(self.mc.cat_expr(&discr));
443                 let r = self.tcx().types.re_empty;
444                 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
445
446                 // treatment of the discriminant is handled while walking the arms.
447                 for arm in arms {
448                     let mode = self.arm_move_mode(discr_cmt.clone(), arm);
449                     let mode = mode.match_mode();
450                     self.walk_arm(discr_cmt.clone(), arm, mode);
451                 }
452             }
453
454             hir::ExprArray(ref exprs) => {
455                 self.consume_exprs(exprs);
456             }
457
458             hir::ExprAddrOf(m, ref base) => {   // &base
459                 // make sure that the thing we are pointing out stays valid
460                 // for the lifetime `scope_r` of the resulting ptr:
461                 let expr_ty = return_if_err!(self.mc.expr_ty(expr));
462                 if let ty::TyRef(r, _) = expr_ty.sty {
463                     let bk = ty::BorrowKind::from_mutbl(m);
464                     self.borrow_expr(&base, r, bk, AddrOf);
465                 }
466             }
467
468             hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
469                 for (o, output) in ia.outputs.iter().zip(outputs) {
470                     if o.is_indirect {
471                         self.consume_expr(output);
472                     } else {
473                         self.mutate_expr(expr, output,
474                                          if o.is_rw {
475                                              MutateMode::WriteAndRead
476                                          } else {
477                                              MutateMode::JustWrite
478                                          });
479                     }
480                 }
481                 self.consume_exprs(inputs);
482             }
483
484             hir::ExprAgain(..) |
485             hir::ExprLit(..) => {}
486
487             hir::ExprLoop(ref blk, _, _) => {
488                 self.walk_block(&blk);
489             }
490
491             hir::ExprWhile(ref cond_expr, ref blk, _) => {
492                 self.consume_expr(&cond_expr);
493                 self.walk_block(&blk);
494             }
495
496             hir::ExprUnary(_, ref lhs) => {
497                 self.consume_expr(&lhs);
498             }
499
500             hir::ExprBinary(_, ref lhs, ref rhs) => {
501                 self.consume_expr(&lhs);
502                 self.consume_expr(&rhs);
503             }
504
505             hir::ExprBlock(ref blk) => {
506                 self.walk_block(&blk);
507             }
508
509             hir::ExprBreak(_, ref opt_expr) | hir::ExprRet(ref opt_expr) => {
510                 if let Some(ref expr) = *opt_expr {
511                     self.consume_expr(&expr);
512                 }
513             }
514
515             hir::ExprAssign(ref lhs, ref rhs) => {
516                 self.mutate_expr(expr, &lhs, MutateMode::JustWrite);
517                 self.consume_expr(&rhs);
518             }
519
520             hir::ExprCast(ref base, _) => {
521                 self.consume_expr(&base);
522             }
523
524             hir::ExprAssignOp(_, 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, &lhs, MutateMode::WriteAndRead);
529                 }
530                 self.consume_expr(&rhs);
531             }
532
533             hir::ExprRepeat(ref base, _) => {
534                 self.consume_expr(&base);
535             }
536
537             hir::ExprClosure(.., fn_decl_span, _) => {
538                 self.walk_captures(expr, fn_decl_span)
539             }
540
541             hir::ExprBox(ref base) => {
542                 self.consume_expr(&base);
543             }
544
545             hir::ExprYield(ref value) => {
546                 self.consume_expr(&value);
547             }
548         }
549     }
550
551     fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
552         let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
553         debug!("walk_callee: callee={:?} callee_ty={:?}",
554                callee, callee_ty);
555         match callee_ty.sty {
556             ty::TyFnDef(..) | ty::TyFnPtr(_) => {
557                 self.consume_expr(callee);
558             }
559             ty::TyError => { }
560             _ => {
561                 if let Some(def) = self.mc.tables.type_dependent_defs().get(call.hir_id) {
562                     let def_id = def.def_id();
563                     let call_scope = region::Scope::Node(call.hir_id.local_id);
564                     match OverloadedCallType::from_method_id(self.tcx(), def_id) {
565                         FnMutOverloadedCall => {
566                             let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
567                             self.borrow_expr(callee,
568                                             call_scope_r,
569                                             ty::MutBorrow,
570                                             ClosureInvocation);
571                         }
572                         FnOverloadedCall => {
573                             let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
574                             self.borrow_expr(callee,
575                                             call_scope_r,
576                                             ty::ImmBorrow,
577                                             ClosureInvocation);
578                         }
579                         FnOnceOverloadedCall => self.consume_expr(callee),
580                     }
581                 } else {
582                     self.tcx().sess.delay_span_bug(call.span,
583                                                    "no type-dependent def for overloaded call");
584                 }
585             }
586         }
587     }
588
589     fn walk_stmt(&mut self, stmt: &hir::Stmt) {
590         match stmt.node {
591             hir::StmtDecl(ref decl, _) => {
592                 match decl.node {
593                     hir::DeclLocal(ref local) => {
594                         self.walk_local(&local);
595                     }
596
597                     hir::DeclItem(_) => {
598                         // we don't visit nested items in this visitor,
599                         // only the fn body we were given.
600                     }
601                 }
602             }
603
604             hir::StmtExpr(ref expr, _) |
605             hir::StmtSemi(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                 let delegate = &mut self.delegate;
615                 local.pat.each_binding(|_, id, span, _| {
616                     delegate.decl_without_init(id, span);
617                 })
618             }
619
620             Some(ref expr) => {
621                 // Variable declarations with
622                 // initializers are considered
623                 // "assigns", which is handled by
624                 // `walk_pat`:
625                 self.walk_expr(&expr);
626                 let init_cmt = return_if_err!(self.mc.cat_expr(&expr));
627                 self.walk_irrefutable_pat(init_cmt, &local.pat);
628             }
629         }
630     }
631
632     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
633     /// depending on its type.
634     fn walk_block(&mut self, blk: &hir::Block) {
635         debug!("walk_block(blk.id={})", blk.id);
636
637         for stmt in &blk.stmts {
638             self.walk_stmt(stmt);
639         }
640
641         if let Some(ref tail_expr) = blk.expr {
642             self.consume_expr(&tail_expr);
643         }
644     }
645
646     fn walk_struct_expr(&mut self,
647                         fields: &[hir::Field],
648                         opt_with: &Option<P<hir::Expr>>) {
649         // Consume the expressions supplying values for each field.
650         for field in fields {
651             self.consume_expr(&field.expr);
652         }
653
654         let with_expr = match *opt_with {
655             Some(ref w) => &**w,
656             None => { return; }
657         };
658
659         let with_cmt = return_if_err!(self.mc.cat_expr(&with_expr));
660
661         // Select just those fields of the `with`
662         // expression that will actually be used
663         match with_cmt.ty.sty {
664             ty::TyAdt(adt, substs) if adt.is_struct() => {
665                 // Consume those fields of the with expression that are needed.
666                 for with_field in &adt.non_enum_variant().fields {
667                     if !contains_field_named(with_field, fields) {
668                         let cmt_field = self.mc.cat_field(
669                             &*with_expr,
670                             with_cmt.clone(),
671                             with_field.name,
672                             with_field.ty(self.tcx(), substs)
673                         );
674                         self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
675                     }
676                 }
677             }
678             _ => {
679                 // the base expression should always evaluate to a
680                 // struct; however, when EUV is run during typeck, it
681                 // may not. This will generate an error earlier in typeck,
682                 // so we can just ignore it.
683                 if !self.tcx().sess.has_errors() {
684                     span_bug!(
685                         with_expr.span,
686                         "with expression doesn't evaluate to a struct");
687                 }
688             }
689         }
690
691         // walk the with expression so that complex expressions
692         // are properly handled.
693         self.walk_expr(with_expr);
694
695         fn contains_field_named(field: &ty::FieldDef,
696                                 fields: &[hir::Field])
697                                 -> bool
698         {
699             fields.iter().any(
700                 |f| f.name.node == field.name)
701         }
702     }
703
704     // Invoke the appropriate delegate calls for anything that gets
705     // consumed or borrowed as part of the automatic adjustment
706     // process.
707     fn walk_adjustment(&mut self, expr: &hir::Expr) {
708         let adjustments = self.mc.tables.expr_adjustments(expr);
709         let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
710         for adjustment in adjustments {
711             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
712             match adjustment.kind {
713                 adjustment::Adjust::NeverToAny |
714                 adjustment::Adjust::ReifyFnPointer |
715                 adjustment::Adjust::UnsafeFnPointer |
716                 adjustment::Adjust::ClosureFnPointer |
717                 adjustment::Adjust::MutToConstPointer |
718                 adjustment::Adjust::Unsize => {
719                     // Creating a closure/fn-pointer or unsizing consumes
720                     // the input and stores it into the resulting rvalue.
721                     self.delegate_consume(expr.id, expr.span, cmt.clone());
722                 }
723
724                 adjustment::Adjust::Deref(None) => {}
725
726                 // Autoderefs for overloaded Deref calls in fact reference
727                 // their receiver. That is, if we have `(*x)` where `x`
728                 // is of type `Rc<T>`, then this in fact is equivalent to
729                 // `x.deref()`. Since `deref()` is declared with `&self`,
730                 // this is an autoref of `x`.
731                 adjustment::Adjust::Deref(Some(ref deref)) => {
732                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
733                     self.delegate.borrow(expr.id, expr.span, cmt.clone(),
734                                          deref.region, bk, AutoRef);
735                 }
736
737                 adjustment::Adjust::Borrow(ref autoref) => {
738                     self.walk_autoref(expr, cmt.clone(), autoref);
739                 }
740             }
741             cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
742         }
743     }
744
745     /// Walks the autoref `autoref` applied to the autoderef'd
746     /// `expr`. `cmt_base` is the mem-categorized form of `expr`
747     /// after all relevant autoderefs have occurred.
748     fn walk_autoref(&mut self,
749                     expr: &hir::Expr,
750                     cmt_base: mc::cmt<'tcx>,
751                     autoref: &adjustment::AutoBorrow<'tcx>) {
752         debug!("walk_autoref(expr.id={} cmt_base={:?} autoref={:?})",
753                expr.id,
754                cmt_base,
755                autoref);
756
757         match *autoref {
758             adjustment::AutoBorrow::Ref(r, m) => {
759                 self.delegate.borrow(expr.id,
760                                      expr.span,
761                                      cmt_base,
762                                      r,
763                                      ty::BorrowKind::from_mutbl(m.into()),
764                                      AutoRef);
765             }
766
767             adjustment::AutoBorrow::RawPtr(m) => {
768                 debug!("walk_autoref: expr.id={} cmt_base={:?}",
769                        expr.id,
770                        cmt_base);
771
772                 // Converting from a &T to *T (or &mut T to *mut T) is
773                 // treated as borrowing it for the enclosing temporary
774                 // scope.
775                 let r = self.tcx().mk_region(ty::ReScope(
776                     region::Scope::Node(expr.hir_id.local_id)));
777
778                 self.delegate.borrow(expr.id,
779                                      expr.span,
780                                      cmt_base,
781                                      r,
782                                      ty::BorrowKind::from_mutbl(m),
783                                      AutoUnsafe);
784             }
785         }
786     }
787
788     fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
789         let mut mode = Unknown;
790         for pat in &arm.pats {
791             self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
792         }
793         mode
794     }
795
796     fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
797         for pat in &arm.pats {
798             self.walk_pat(discr_cmt.clone(), &pat, mode);
799         }
800
801         if let Some(ref guard) = arm.guard {
802             self.consume_expr(&guard);
803         }
804
805         self.consume_expr(&arm.body);
806     }
807
808     /// Walks a pat that occurs in isolation (i.e. top-level of fn
809     /// arg or let binding.  *Not* a match arm or nested pat.)
810     fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
811         let mut mode = Unknown;
812         self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
813         let mode = mode.match_mode();
814         self.walk_pat(cmt_discr, pat, mode);
815     }
816
817     /// Identifies any bindings within `pat` and accumulates within
818     /// `mode` whether the overall pattern/match structure is a move,
819     /// copy, or borrow.
820     fn determine_pat_move_mode(&mut self,
821                                cmt_discr: mc::cmt<'tcx>,
822                                pat: &hir::Pat,
823                                mode: &mut TrackMatchMode) {
824         debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
825                pat);
826         return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
827             if let PatKind::Binding(..) = pat.node {
828                 let bm = *self.mc.tables.pat_binding_modes().get(pat.hir_id)
829                                                           .expect("missing binding mode");
830                 match bm {
831                     ty::BindByReference(..) =>
832                         mode.lub(BorrowingMatch),
833                     ty::BindByValue(..) => {
834                         match copy_or_move(&self.mc, self.param_env, &cmt_pat, PatBindingMove) {
835                             Copy => mode.lub(CopyingMatch),
836                             Move(..) => mode.lub(MovingMatch),
837                         }
838                     }
839                 }
840             }
841         }));
842     }
843
844     /// The core driver for walking a pattern; `match_mode` must be
845     /// established up front, e.g. via `determine_pat_move_mode` (see
846     /// also `walk_irrefutable_pat` for patterns that stand alone).
847     fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
848         debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
849
850         let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
851         return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| {
852             if let PatKind::Binding(_, canonical_id, ..) = pat.node {
853                 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
854                 let bm = *mc.tables.pat_binding_modes().get(pat.hir_id)
855                                                      .expect("missing binding mode");
856
857                 // pat_ty: the type of the binding being produced.
858                 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
859
860                 // Each match binding is effectively an assignment to the
861                 // binding being produced.
862                 let def = Def::Local(canonical_id);
863                 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
864                     delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
865                 }
866
867                 // It is also a borrow or copy/move of the value being matched.
868                 match bm {
869                     ty::BindByReference(m) => {
870                         if let ty::TyRef(r, _) = pat_ty.sty {
871                             let bk = ty::BorrowKind::from_mutbl(m);
872                             delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
873                         }
874                     }
875                     ty::BindByValue(..) => {
876                         let mode = copy_or_move(mc, param_env, &cmt_pat, PatBindingMove);
877                         debug!("walk_pat binding consuming pat");
878                         delegate.consume_pat(pat, cmt_pat, mode);
879                     }
880                 }
881             }
882         }));
883
884         // Do a second pass over the pattern, calling `matched_pat` on
885         // the interior nodes (enum variants and structs), as opposed
886         // to the above loop's visit of than the bindings that form
887         // the leaves of the pattern tree structure.
888         return_if_err!(mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
889             let qpath = match pat.node {
890                 PatKind::Path(ref qpath) |
891                 PatKind::TupleStruct(ref qpath, ..) |
892                 PatKind::Struct(ref qpath, ..) => qpath,
893                 _ => return
894             };
895             let def = mc.tables.qpath_def(qpath, pat.hir_id);
896             match def {
897                 Def::Variant(variant_did) |
898                 Def::VariantCtor(variant_did, ..) => {
899                     let downcast_cmt = mc.cat_downcast_if_needed(pat, cmt_pat, variant_did);
900
901                     debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
902                     delegate.matched_pat(pat, downcast_cmt, match_mode);
903                 }
904                 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
905                 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
906                     debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
907                     delegate.matched_pat(pat, cmt_pat, match_mode);
908                 }
909                 _ => {}
910             }
911         }));
912     }
913
914     fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
915         debug!("walk_captures({:?})", closure_expr);
916
917         self.tcx().with_freevars(closure_expr.id, |freevars| {
918             for freevar in freevars {
919                 let var_hir_id = self.tcx().hir.node_to_hir_id(freevar.var_id());
920                 let closure_def_id = self.tcx().hir.local_def_id(closure_expr.id);
921                 let upvar_id = ty::UpvarId {
922                     var_id: var_hir_id,
923                     closure_expr_id: closure_def_id.to_local(),
924                 };
925                 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
926                 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
927                                                                    fn_decl_span,
928                                                                    freevar));
929                 match upvar_capture {
930                     ty::UpvarCapture::ByValue => {
931                         let mode = copy_or_move(&self.mc,
932                                                 self.param_env,
933                                                 &cmt_var,
934                                                 CaptureMove);
935                         self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
936                     }
937                     ty::UpvarCapture::ByRef(upvar_borrow) => {
938                         self.delegate.borrow(closure_expr.id,
939                                              fn_decl_span,
940                                              cmt_var,
941                                              upvar_borrow.region,
942                                              upvar_borrow.kind,
943                                              ClosureCapture(freevar.span));
944                     }
945                 }
946             }
947         });
948     }
949
950     fn cat_captured_var(&mut self,
951                         closure_id: ast::NodeId,
952                         closure_span: Span,
953                         upvar: &hir::Freevar)
954                         -> mc::McResult<mc::cmt<'tcx>> {
955         // Create the cmt for the variable being borrowed, from the
956         // caller's perspective
957         let var_hir_id = self.tcx().hir.node_to_hir_id(upvar.var_id());
958         let var_ty = self.mc.node_ty(var_hir_id)?;
959         self.mc.cat_def(closure_id, closure_span, var_ty, upvar.def)
960     }
961 }
962
963 fn copy_or_move<'a, 'gcx, 'tcx>(mc: &mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
964                                 param_env: ty::ParamEnv<'tcx>,
965                                 cmt: &mc::cmt<'tcx>,
966                                 move_reason: MoveReason)
967                                 -> ConsumeMode
968 {
969     if mc.type_moves_by_default(param_env, cmt.ty, cmt.span) {
970         Move(move_reason)
971     } else {
972         Copy
973     }
974 }