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.
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.
12 * A different sort of visitor for walking fn bodies. Unlike the
13 * normal visitor, which just walks the entire body in one shot, the
14 * `ExprUseVisitor` determines how expressions are being used.
17 use middle::mem_categorization as mc;
19 use middle::mem_categorization::Typer;
22 use middle::typeck::{MethodCall, MethodObject, MethodOrigin, MethodParam};
23 use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure};
25 use util::ppaux::Repr;
29 use syntax::codemap::Span;
31 ///////////////////////////////////////////////////////////////////////////
34 /// This trait defines the callbacks you can expect to receive when
35 /// employing the ExprUseVisitor.
37 // The value found at `cmt` is either copied or moved, depending
40 consume_id: ast::NodeId,
45 // The value found at `cmt` is either copied or moved via the
46 // pattern binding `consume_pat`, depending on mode.
47 fn consume_pat(&mut self,
48 consume_pat: &ast::Pat,
52 // The value found at `borrow` is being borrowed at the point
53 // `borrow_id` for the region `loan_region` with kind `bk`.
55 borrow_id: ast::NodeId,
58 loan_region: ty::Region,
60 loan_cause: LoanCause);
62 // The local variable `id` is declared but not initialized.
63 fn decl_without_init(&mut self,
67 // The path at `cmt` is being assigned to.
69 assignment_id: ast::NodeId,
70 assignment_span: Span,
71 assignee_cmt: mc::cmt,
75 #[deriving(PartialEq)]
86 #[deriving(PartialEq,Show)]
87 pub enum ConsumeMode {
88 Copy, // reference to x where x has a type that copies
89 Move(MoveReason), // reference to x where x has a type that moves
92 #[deriving(PartialEq,Show)]
99 #[deriving(PartialEq,Show)]
100 pub enum MutateMode {
103 WriteAndRead, // x += y
106 enum OverloadedCallType {
109 FnOnceOverloadedCall,
112 impl OverloadedCallType {
113 fn from_trait_id(tcx: &ty::ctxt, trait_id: ast::DefId)
114 -> OverloadedCallType {
115 for &(maybe_function_trait, overloaded_call_type) in [
116 (tcx.lang_items.fn_once_trait(), FnOnceOverloadedCall),
117 (tcx.lang_items.fn_mut_trait(), FnMutOverloadedCall),
118 (tcx.lang_items.fn_trait(), FnOverloadedCall)
120 match maybe_function_trait {
121 Some(function_trait) if function_trait == trait_id => {
122 return overloaded_call_type
128 tcx.sess.bug("overloaded call didn't map to known function trait")
131 fn from_method_id(tcx: &ty::ctxt, method_id: ast::DefId)
132 -> OverloadedCallType {
133 let method_descriptor = match ty::impl_or_trait_item(tcx, method_id) {
134 ty::MethodTraitItem(ref method_descriptor) => {
135 (*method_descriptor).clone()
137 ty::TypeTraitItem(_) => {
138 tcx.sess.bug("overloaded call method wasn't in method map")
141 let impl_id = match method_descriptor.container {
142 ty::TraitContainer(_) => {
143 tcx.sess.bug("statically resolved overloaded call method \
144 belonged to a trait?!")
146 ty::ImplContainer(impl_id) => impl_id,
148 let trait_ref = match ty::impl_trait_ref(tcx, impl_id) {
150 tcx.sess.bug("statically resolved overloaded call impl \
151 didn't implement a trait?!")
153 Some(ref trait_ref) => (*trait_ref).clone(),
155 OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
158 fn from_unboxed_closure(tcx: &ty::ctxt, closure_did: ast::DefId)
159 -> OverloadedCallType {
164 .expect("OverloadedCallType::from_unboxed_closure: didn't \
168 OverloadedCallType::from_trait_id(tcx, trait_did)
171 fn from_method_origin(tcx: &ty::ctxt, origin: &MethodOrigin)
172 -> OverloadedCallType {
174 MethodStatic(def_id) => {
175 OverloadedCallType::from_method_id(tcx, def_id)
177 MethodStaticUnboxedClosure(def_id) => {
178 OverloadedCallType::from_unboxed_closure(tcx, def_id)
180 MethodParam(MethodParam { trait_ref: ref trait_ref, .. }) |
181 MethodObject(MethodObject { trait_ref: ref trait_ref, .. }) => {
182 OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
188 ///////////////////////////////////////////////////////////////////////////
189 // The ExprUseVisitor type
191 // This is the code that actually walks the tree. Like
192 // mem_categorization, it requires a TYPER, which is a type that
193 // supplies types from the tree. After type checking is complete, you
194 // can just use the tcx as the typer.
196 pub struct ExprUseVisitor<'d,'t,TYPER:'t> {
198 mc: mc::MemCategorizationContext<'t,TYPER>,
199 delegate: &'d mut Delegate+'d,
202 // If the TYPER results in an error, it's because the type check
203 // failed (or will fail, when the error is uncovered and reported
204 // during writeback). In this case, we just ignore this part of the
207 // Note that this macro appears similar to try!(), but, unlike try!(),
208 // it does not propagate the error.
209 macro_rules! return_if_err(
218 impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,TYPER> {
219 pub fn new(delegate: &'d mut Delegate,
221 -> ExprUseVisitor<'d,'t,TYPER> {
222 ExprUseVisitor { typer: typer,
223 mc: mc::MemCategorizationContext::new(typer),
227 pub fn walk_fn(&mut self,
230 self.walk_arg_patterns(decl, body);
231 self.walk_block(body);
234 fn walk_arg_patterns(&mut self,
237 for arg in decl.inputs.iter() {
238 let arg_ty = return_if_err!(self.typer.node_ty(arg.pat.id));
240 let arg_cmt = self.mc.cat_rvalue(
243 ty::ReScope(body.id), // Args live only as long as the fn body.
246 self.walk_pat(arg_cmt, &*arg.pat);
250 fn tcx(&self) -> &'t ty::ctxt<'tcx> {
254 fn delegate_consume(&mut self,
255 consume_id: ast::NodeId,
258 let mode = copy_or_move(self.tcx(), cmt.ty, DirectRefMove);
259 self.delegate.consume(consume_id, consume_span, cmt, mode);
262 fn consume_exprs(&mut self, exprs: &Vec<P<ast::Expr>>) {
263 for expr in exprs.iter() {
264 self.consume_expr(&**expr);
268 fn consume_expr(&mut self, expr: &ast::Expr) {
269 debug!("consume_expr(expr={})", expr.repr(self.tcx()));
271 let cmt = return_if_err!(self.mc.cat_expr(expr));
272 self.delegate_consume(expr.id, expr.span, cmt);
273 self.walk_expr(expr);
276 fn mutate_expr(&mut self,
277 assignment_expr: &ast::Expr,
280 let cmt = return_if_err!(self.mc.cat_expr(expr));
281 self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
282 self.walk_expr(expr);
285 fn borrow_expr(&mut self,
290 debug!("borrow_expr(expr={}, r={}, bk={})",
291 expr.repr(self.tcx()), r.repr(self.tcx()), bk.repr(self.tcx()));
293 let cmt = return_if_err!(self.mc.cat_expr(expr));
294 self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
296 // Note: Unlike consume, we can ignore ExprParen. cat_expr
297 // already skips over them, and walk will uncover any
298 // attachments or whatever.
302 fn select_from_expr(&mut self, expr: &ast::Expr) {
306 pub fn walk_expr(&mut self, expr: &ast::Expr) {
307 debug!("walk_expr(expr={})", expr.repr(self.tcx()));
309 self.walk_adjustment(expr);
312 ast::ExprParen(ref subexpr) => {
313 self.walk_expr(&**subexpr)
316 ast::ExprPath(..) => { }
318 ast::ExprUnary(ast::UnDeref, ref base) => { // *base
319 if !self.walk_overloaded_operator(expr, &**base, None) {
320 self.select_from_expr(&**base);
324 ast::ExprField(ref base, _, _) => { // base.f
325 self.select_from_expr(&**base);
328 ast::ExprTupField(ref base, _, _) => { // base.<n>
329 self.select_from_expr(&**base);
332 ast::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs]
333 if !self.walk_overloaded_operator(expr, &**lhs, Some(&**rhs)) {
334 self.select_from_expr(&**lhs);
335 self.consume_expr(&**rhs);
339 ast::ExprCall(ref callee, ref args) => { // callee(args)
340 self.walk_callee(expr, &**callee);
341 self.consume_exprs(args);
344 ast::ExprMethodCall(_, _, ref args) => { // callee.m(args)
345 self.consume_exprs(args);
348 ast::ExprStruct(_, ref fields, ref opt_with) => {
349 self.walk_struct_expr(expr, fields, opt_with);
352 ast::ExprTup(ref exprs) => {
353 self.consume_exprs(exprs);
356 ast::ExprIf(ref cond_expr, ref then_blk, ref opt_else_expr) => {
357 self.consume_expr(&**cond_expr);
358 self.walk_block(&**then_blk);
359 for else_expr in opt_else_expr.iter() {
360 self.consume_expr(&**else_expr);
364 ast::ExprMatch(ref discr, ref arms) => {
365 // treatment of the discriminant is handled while
367 self.walk_expr(&**discr);
368 let discr_cmt = return_if_err!(self.mc.cat_expr(&**discr));
369 for arm in arms.iter() {
370 self.walk_arm(discr_cmt.clone(), arm);
374 ast::ExprVec(ref exprs) => {
375 self.consume_exprs(exprs);
378 ast::ExprAddrOf(m, ref base) => { // &base
379 // make sure that the thing we are pointing out stays valid
380 // for the lifetime `scope_r` of the resulting ptr:
381 let expr_ty = ty::expr_ty(self.tcx(), expr);
382 if !ty::type_is_bot(expr_ty) {
383 let r = ty::ty_region(self.tcx(), expr.span, expr_ty);
384 let bk = ty::BorrowKind::from_mutbl(m);
385 self.borrow_expr(&**base, r, bk, AddrOf);
387 self.walk_expr(&**base);
391 ast::ExprInlineAsm(ref ia) => {
392 for &(_, ref input) in ia.inputs.iter() {
393 self.consume_expr(&**input);
396 for &(_, ref output, is_rw) in ia.outputs.iter() {
397 self.mutate_expr(expr, &**output,
398 if is_rw { WriteAndRead } else { JustWrite });
404 ast::ExprLit(..) => {}
406 ast::ExprLoop(ref blk, _) => {
407 self.walk_block(&**blk);
410 ast::ExprWhile(ref cond_expr, ref blk, _) => {
411 self.consume_expr(&**cond_expr);
412 self.walk_block(&**blk);
415 ast::ExprForLoop(ref pat, ref head, ref blk, _) => {
416 // The pattern lives as long as the block.
417 debug!("walk_expr for loop case: blk id={}", blk.id);
418 self.consume_expr(&**head);
420 // Fetch the type of the value that the iteration yields to
421 // produce the pattern's categorized mutable type.
422 let pattern_type = return_if_err!(self.typer.node_ty(pat.id));
423 let pat_cmt = self.mc.cat_rvalue(pat.id,
427 self.walk_pat(pat_cmt, &**pat);
429 self.walk_block(&**blk);
432 ast::ExprUnary(_, ref lhs) => {
433 if !self.walk_overloaded_operator(expr, &**lhs, None) {
434 self.consume_expr(&**lhs);
438 ast::ExprBinary(_, ref lhs, ref rhs) => {
439 if !self.walk_overloaded_operator(expr, &**lhs, Some(&**rhs)) {
440 self.consume_expr(&**lhs);
441 self.consume_expr(&**rhs);
445 ast::ExprBlock(ref blk) => {
446 self.walk_block(&**blk);
449 ast::ExprRet(ref opt_expr) => {
450 for expr in opt_expr.iter() {
451 self.consume_expr(&**expr);
455 ast::ExprAssign(ref lhs, ref rhs) => {
456 self.mutate_expr(expr, &**lhs, JustWrite);
457 self.consume_expr(&**rhs);
460 ast::ExprCast(ref base, _) => {
461 self.consume_expr(&**base);
464 ast::ExprAssignOp(_, ref lhs, ref rhs) => {
465 // This will have to change if/when we support
466 // overloaded operators for `+=` and so forth.
467 self.mutate_expr(expr, &**lhs, WriteAndRead);
468 self.consume_expr(&**rhs);
471 ast::ExprRepeat(ref base, ref count) => {
472 self.consume_expr(&**base);
473 self.consume_expr(&**count);
476 ast::ExprFnBlock(..) |
477 ast::ExprUnboxedFn(..) |
478 ast::ExprProc(..) => {
479 self.walk_captures(expr)
482 ast::ExprBox(ref place, ref base) => {
483 self.consume_expr(&**place);
484 self.consume_expr(&**base);
487 ast::ExprMac(..) => {
488 self.tcx().sess.span_bug(
490 "macro expression remains after expansion");
495 fn walk_callee(&mut self, call: &ast::Expr, callee: &ast::Expr) {
496 let callee_ty = ty::expr_ty_adjusted(self.tcx(), callee);
497 debug!("walk_callee: callee={} callee_ty={}",
498 callee.repr(self.tcx()), callee_ty.repr(self.tcx()));
499 match ty::get(callee_ty).sty {
500 ty::ty_bare_fn(..) => {
501 self.consume_expr(callee);
503 ty::ty_closure(ref f) => {
506 self.borrow_expr(callee,
507 ty::ReScope(call.id),
512 self.consume_expr(callee);
517 let overloaded_call_type =
521 .find(&MethodCall::expr(call.id)) {
522 Some(ref method_callee) => {
523 OverloadedCallType::from_method_origin(
525 &method_callee.origin)
528 self.tcx().sess.span_bug(
530 format!("unexpected callee type {}",
531 callee_ty.repr(self.tcx())).as_slice())
534 match overloaded_call_type {
535 FnMutOverloadedCall => {
536 self.borrow_expr(callee,
537 ty::ReScope(call.id),
541 FnOverloadedCall => {
542 self.borrow_expr(callee,
543 ty::ReScope(call.id),
547 FnOnceOverloadedCall => self.consume_expr(callee),
553 fn walk_stmt(&mut self, stmt: &ast::Stmt) {
555 ast::StmtDecl(ref decl, _) => {
557 ast::DeclLocal(ref local) => {
558 self.walk_local(&**local);
561 ast::DeclItem(_) => {
562 // we don't visit nested items in this visitor,
563 // only the fn body we were given.
568 ast::StmtExpr(ref expr, _) |
569 ast::StmtSemi(ref expr, _) => {
570 self.consume_expr(&**expr);
573 ast::StmtMac(..) => {
574 self.tcx().sess.span_bug(stmt.span, "unexpanded stmt macro");
579 fn walk_local(&mut self, local: &ast::Local) {
582 let delegate = &mut self.delegate;
583 pat_util::pat_bindings(&self.typer.tcx().def_map, &*local.pat,
585 delegate.decl_without_init(id, span);
590 // Variable declarations with
591 // initializers are considered
592 // "assigns", which is handled by
594 self.walk_expr(&**expr);
595 let init_cmt = return_if_err!(self.mc.cat_expr(&**expr));
596 self.walk_pat(init_cmt, &*local.pat);
601 fn walk_block(&mut self, blk: &ast::Block) {
603 * Indicates that the value of `blk` will be consumed,
604 * meaning either copied or moved depending on its type.
607 debug!("walk_block(blk.id={:?})", blk.id);
609 for stmt in blk.stmts.iter() {
610 self.walk_stmt(&**stmt);
613 for tail_expr in blk.expr.iter() {
614 self.consume_expr(&**tail_expr);
618 fn walk_struct_expr(&mut self,
620 fields: &Vec<ast::Field>,
621 opt_with: &Option<P<ast::Expr>>) {
622 // Consume the expressions supplying values for each field.
623 for field in fields.iter() {
624 self.consume_expr(&*field.expr);
627 let with_expr = match *opt_with {
632 let with_cmt = return_if_err!(self.mc.cat_expr(&*with_expr));
634 // Select just those fields of the `with`
635 // expression that will actually be used
636 let with_fields = match ty::get(with_cmt.ty).sty {
637 ty::ty_struct(did, ref substs) => {
638 ty::struct_fields(self.tcx(), did, substs)
641 self.tcx().sess.span_bug(
643 "with expression doesn't evaluate to a struct");
647 // Consume those fields of the with expression that are needed.
648 for with_field in with_fields.iter() {
649 if !contains_field_named(with_field, fields) {
650 let cmt_field = self.mc.cat_field(&*with_expr,
654 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
658 fn contains_field_named(field: &ty::field,
659 fields: &Vec<ast::Field>)
663 |f| f.ident.node.name == field.ident.name)
667 // Invoke the appropriate delegate calls for anything that gets
668 // consumed or borrowed as part of the automatic adjustment
670 fn walk_adjustment(&mut self, expr: &ast::Expr) {
671 let typer = self.typer;
672 match typer.adjustments().borrow().find(&expr.id) {
674 Some(adjustment) => {
676 ty::AutoAddEnv(..) => {
677 // Creating a closure consumes the input and stores it
678 // into the resulting rvalue.
679 debug!("walk_adjustment(AutoAddEnv)");
681 return_if_err!(self.mc.cat_expr_unadjusted(expr));
682 self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
684 ty::AutoDerefRef(ty::AutoDerefRef {
685 autoref: ref opt_autoref,
688 self.walk_autoderefs(expr, n);
693 self.walk_autoref(expr, r, n);
702 fn walk_autoderefs(&mut self,
706 * Autoderefs for overloaded Deref calls in fact reference
707 * their receiver. That is, if we have `(*x)` where `x` is of
708 * type `Rc<T>`, then this in fact is equivalent to
709 * `x.deref()`. Since `deref()` is declared with `&self`, this
710 * is an autoref of `x`.
712 debug!("walk_autoderefs expr={} autoderefs={}", expr.repr(self.tcx()), autoderefs);
714 for i in range(0, autoderefs) {
715 let deref_id = typeck::MethodCall::autoderef(expr.id, i);
716 match self.typer.node_method_ty(deref_id) {
719 let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
720 let self_ty = *ty::ty_fn_args(method_ty).get(0);
721 let (m, r) = match ty::get(self_ty).sty {
722 ty::ty_rptr(r, ref m) => (m.mutbl, r),
723 _ => self.tcx().sess.span_bug(expr.span,
724 format!("bad overloaded deref type {}",
725 method_ty.repr(self.tcx())).as_slice())
727 let bk = ty::BorrowKind::from_mutbl(m);
728 self.delegate.borrow(expr.id, expr.span, cmt,
735 fn walk_autoref(&mut self,
737 autoref: &ty::AutoRef,
739 debug!("walk_autoref expr={}", expr.repr(self.tcx()));
741 // Match for unique trait coercions first, since we don't need the
742 // call to cat_expr_autoderefd.
744 ty::AutoUnsizeUniq(ty::UnsizeVtable(..)) |
745 ty::AutoUnsize(ty::UnsizeVtable(..)) => {
746 assert!(n == 1, format!("Expected exactly 1 deref with Uniq \
747 AutoRefs, found: {}", n));
749 return_if_err!(self.mc.cat_expr_unadjusted(expr));
750 self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
756 let cmt_derefd = return_if_err!(
757 self.mc.cat_expr_autoderefd(expr, n));
758 debug!("walk_adjustment: cmt_derefd={}",
759 cmt_derefd.repr(self.tcx()));
762 ty::AutoPtr(r, m, _) => {
763 self.delegate.borrow(expr.id,
767 ty::BorrowKind::from_mutbl(m),
770 ty::AutoUnsizeUniq(_) | ty::AutoUnsize(_) | ty::AutoUnsafe(..) => {}
774 fn walk_overloaded_operator(&mut self,
776 receiver: &ast::Expr,
777 rhs: Option<&ast::Expr>)
780 if !self.typer.is_method_call(expr.id) {
784 self.walk_expr(receiver);
786 // Arguments (but not receivers) to overloaded operator
787 // methods are implicitly autoref'd which sadly does not use
788 // adjustments, so we must hardcode the borrow here.
790 let r = ty::ReScope(expr.id);
791 let bk = ty::ImmBorrow;
793 for &arg in rhs.iter() {
794 self.borrow_expr(arg, r, bk, OverloadedOperator);
799 fn walk_arm(&mut self, discr_cmt: mc::cmt, arm: &ast::Arm) {
800 for pat in arm.pats.iter() {
801 self.walk_pat(discr_cmt.clone(), &**pat);
804 for guard in arm.guard.iter() {
805 self.consume_expr(&**guard);
808 self.consume_expr(&*arm.body);
811 fn walk_pat(&mut self, cmt_discr: mc::cmt, pat: &ast::Pat) {
812 debug!("walk_pat cmt_discr={} pat={}", cmt_discr.repr(self.tcx()),
813 pat.repr(self.tcx()));
815 let typer = self.typer;
816 let tcx = typer.tcx();
817 let def_map = &self.typer.tcx().def_map;
818 let delegate = &mut self.delegate;
819 return_if_err!(mc.cat_pattern(cmt_discr, &*pat, |mc, cmt_pat, pat| {
820 if pat_util::pat_is_binding(def_map, pat) {
821 let tcx = typer.tcx();
823 debug!("binding cmt_pat={} pat={}",
827 // pat_ty: the type of the binding being produced.
828 let pat_ty = return_if_err!(typer.node_ty(pat.id));
830 // Each match binding is effectively an assignment to the
831 // binding being produced.
832 let def = def_map.borrow().get_copy(&pat.id);
833 match mc.cat_def(pat.id, pat.span, pat_ty, def) {
835 delegate.mutate(pat.id, pat.span, binding_cmt, Init);
840 // It is also a borrow or copy/move of the value being matched.
842 ast::PatIdent(ast::BindByRef(m), _, _) => {
844 (ty::ty_region(tcx, pat.span, pat_ty),
845 ty::BorrowKind::from_mutbl(m))
847 delegate.borrow(pat.id, pat.span, cmt_pat,
850 ast::PatIdent(ast::BindByValue(_), _, _) => {
851 let mode = copy_or_move(typer.tcx(), cmt_pat.ty, PatBindingMove);
852 debug!("walk_pat binding consuming pat");
853 delegate.consume_pat(pat, cmt_pat, mode);
856 typer.tcx().sess.span_bug(
858 "binding pattern not an identifier");
863 ast::PatVec(_, Some(ref slice_pat), _) => {
864 // The `slice_pat` here creates a slice into
865 // the original vector. This is effectively a
866 // borrow of the elements of the vector being
869 let (slice_cmt, slice_mutbl, slice_r) = {
870 match mc.cat_slice_pattern(cmt_pat, &**slice_pat) {
873 tcx.sess.span_bug(slice_pat.span,
879 // Note: We declare here that the borrow
880 // occurs upon entering the `[...]`
881 // pattern. This implies that something like
882 // `[a, ..b]` where `a` is a move is illegal,
883 // because the borrow is already in effect.
884 // In fact such a move would be safe-ish, but
885 // it effectively *requires* that we use the
886 // nulling out semantics to indicate when a
887 // value has been moved, which we are trying
888 // to move away from. Otherwise, how can we
889 // indicate that the first element in the
890 // vector has been moved? Eventually, we
891 // could perhaps modify this rule to permit
892 // `[..a, b]` where `b` is a move, because in
893 // that case we can adjust the length of the
894 // original vec accordingly, but we'd have to
895 // make trans do the right thing, and it would
896 // only work for `~` vectors. It seems simpler
897 // to just require that people call
898 // `vec.pop()` or `vec.unshift()`.
899 let slice_bk = ty::BorrowKind::from_mutbl(slice_mutbl);
900 delegate.borrow(pat.id, pat.span,
902 slice_bk, RefBinding);
910 fn walk_captures(&mut self, closure_expr: &ast::Expr) {
911 debug!("walk_captures({})", closure_expr.repr(self.tcx()));
913 let tcx = self.typer.tcx();
914 ty::with_freevars(tcx, closure_expr.id, |freevars| {
915 match self.tcx().capture_mode(closure_expr.id) {
916 ast::CaptureByRef => {
917 self.walk_by_ref_captures(closure_expr, freevars);
919 ast::CaptureByValue => {
920 self.walk_by_value_captures(closure_expr, freevars);
926 fn walk_by_ref_captures(&mut self,
927 closure_expr: &ast::Expr,
928 freevars: &[ty::Freevar]) {
929 for freevar in freevars.iter() {
930 let id_var = freevar.def.def_id().node;
931 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
935 // Lookup the kind of borrow the callee requires, as
936 // inferred by regionbk
937 let upvar_id = ty::UpvarId { var_id: id_var,
938 closure_expr_id: closure_expr.id };
939 let upvar_borrow = self.tcx().upvar_borrow_map.borrow()
940 .get_copy(&upvar_id);
942 self.delegate.borrow(closure_expr.id,
947 ClosureCapture(freevar.span));
951 fn walk_by_value_captures(&mut self,
952 closure_expr: &ast::Expr,
953 freevars: &[ty::Freevar]) {
954 for freevar in freevars.iter() {
955 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
958 let mode = copy_or_move(self.tcx(), cmt_var.ty, CaptureMove);
959 self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
963 fn cat_captured_var(&mut self,
964 closure_id: ast::NodeId,
967 -> mc::McResult<mc::cmt> {
968 // Create the cmt for the variable being borrowed, from the
969 // caller's perspective
970 let var_id = upvar_def.def_id().node;
971 let var_ty = try!(self.typer.node_ty(var_id));
972 self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
976 fn copy_or_move(tcx: &ty::ctxt, ty: ty::t, move_reason: MoveReason) -> ConsumeMode {
977 if ty::type_moves_by_default(tcx, ty) { Move(move_reason) } else { Copy }