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