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.
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.
15 pub use self::MutateMode::*;
16 pub use self::LoanCause::*;
17 pub use self::ConsumeMode::*;
18 pub use self::MoveReason::*;
19 pub use self::MatchMode::*;
20 use self::TrackMatchMode::*;
21 use self::OverloadedCallType::*;
23 use middle::{def, region, pat_util};
24 use middle::mem_categorization as mc;
25 use middle::mem_categorization::Typer;
26 use middle::ty::{mod, Ty};
27 use middle::typeck::{MethodCall, MethodObject, MethodTraitObject};
28 use middle::typeck::{MethodOrigin, MethodParam, MethodTypeParam};
29 use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure};
31 use util::ppaux::Repr;
35 use syntax::codemap::Span;
37 ///////////////////////////////////////////////////////////////////////////
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
46 consume_id: ast::NodeId,
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).
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: &ast::Pat,
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: &ast::Pat,
75 // The value found at `borrow` is being borrowed at the point
76 // `borrow_id` for the region `loan_region` with kind `bk`.
78 borrow_id: ast::NodeId,
81 loan_region: ty::Region,
83 loan_cause: LoanCause);
85 // The local variable `id` is declared but not initialized.
86 fn decl_without_init(&mut self,
90 // The path at `cmt` is being assigned to.
92 assignment_id: ast::NodeId,
93 assignment_span: Span,
94 assignee_cmt: mc::cmt<'tcx>,
98 #[deriving(PartialEq, Show)]
100 ClosureCapture(Span),
110 #[deriving(PartialEq, Show)]
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
116 #[deriving(PartialEq,Show)]
117 pub enum MoveReason {
123 #[deriving(PartialEq,Show)]
131 #[deriving(PartialEq,Show)]
132 enum TrackMatchMode<T> {
133 Unknown, Definite(MatchMode), Conflicting,
136 impl<T> TrackMatchMode<T> {
137 // Builds up the whole match mode for a pattern from its constituent
138 // parts. The lattice looks like this:
154 // * `(_, some_int)` pattern is Copying, since
155 // NonBinding + Copying => Copying
157 // * `(some_int, some_box)` pattern is Moving, since
158 // Copying + Moving => Moving
160 // * `(ref x, some_box)` pattern is Conflicting, since
161 // Borrowing + Moving => Conflicting
163 // Note that the `Unknown` and `Conflicting` states are
164 // represented separately from the other more interesting
165 // `Definite` states, which simplifies logic here somewhat.
166 fn lub(&mut self, mode: MatchMode) {
167 *self = match (*self, mode) {
168 // Note that clause order below is very significant.
169 (Unknown, new) => Definite(new),
170 (Definite(old), new) if old == new => Definite(old),
172 (Definite(old), NonBindingMatch) => Definite(old),
173 (Definite(NonBindingMatch), new) => Definite(new),
175 (Definite(old), CopyingMatch) => Definite(old),
176 (Definite(CopyingMatch), new) => Definite(new),
178 (Definite(_), _) => Conflicting,
179 (Conflicting, _) => *self,
183 fn match_mode(&self) -> MatchMode {
185 Unknown => NonBindingMatch,
186 Definite(mode) => mode,
188 // Conservatively return MovingMatch to let the
189 // compiler continue to make progress.
196 #[deriving(PartialEq,Show)]
197 pub enum MutateMode {
200 WriteAndRead, // x += y
203 enum OverloadedCallType {
206 FnOnceOverloadedCall,
209 impl OverloadedCallType {
210 fn from_trait_id(tcx: &ty::ctxt, trait_id: ast::DefId)
211 -> OverloadedCallType {
212 for &(maybe_function_trait, overloaded_call_type) in [
213 (tcx.lang_items.fn_once_trait(), FnOnceOverloadedCall),
214 (tcx.lang_items.fn_mut_trait(), FnMutOverloadedCall),
215 (tcx.lang_items.fn_trait(), FnOverloadedCall)
217 match maybe_function_trait {
218 Some(function_trait) if function_trait == trait_id => {
219 return overloaded_call_type
225 tcx.sess.bug("overloaded call didn't map to known function trait")
228 fn from_method_id(tcx: &ty::ctxt, method_id: ast::DefId)
229 -> OverloadedCallType {
230 let method_descriptor = match ty::impl_or_trait_item(tcx, method_id) {
231 ty::MethodTraitItem(ref method_descriptor) => {
232 (*method_descriptor).clone()
234 ty::TypeTraitItem(_) => {
235 tcx.sess.bug("overloaded call method wasn't in method map")
238 let impl_id = match method_descriptor.container {
239 ty::TraitContainer(_) => {
240 tcx.sess.bug("statically resolved overloaded call method \
241 belonged to a trait?!")
243 ty::ImplContainer(impl_id) => impl_id,
245 let trait_ref = match ty::impl_trait_ref(tcx, impl_id) {
247 tcx.sess.bug("statically resolved overloaded call impl \
248 didn't implement a trait?!")
250 Some(ref trait_ref) => (*trait_ref).clone(),
252 OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
255 fn from_unboxed_closure(tcx: &ty::ctxt, closure_did: ast::DefId)
256 -> OverloadedCallType {
261 .expect("OverloadedCallType::from_unboxed_closure: didn't \
265 OverloadedCallType::from_trait_id(tcx, trait_did)
268 fn from_method_origin(tcx: &ty::ctxt, origin: &MethodOrigin)
269 -> OverloadedCallType {
271 MethodStatic(def_id) => {
272 OverloadedCallType::from_method_id(tcx, def_id)
274 MethodStaticUnboxedClosure(def_id) => {
275 OverloadedCallType::from_unboxed_closure(tcx, def_id)
277 MethodTypeParam(MethodParam { ref trait_ref, .. }) |
278 MethodTraitObject(MethodObject { ref trait_ref, .. }) => {
279 OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
285 ///////////////////////////////////////////////////////////////////////////
286 // The ExprUseVisitor type
288 // This is the code that actually walks the tree. Like
289 // mem_categorization, it requires a TYPER, which is a type that
290 // supplies types from the tree. After type checking is complete, you
291 // can just use the tcx as the typer.
293 pub struct ExprUseVisitor<'d,'t,'tcx,TYPER:'t> {
295 mc: mc::MemCategorizationContext<'t,TYPER>,
296 delegate: &'d mut Delegate<'tcx>+'d,
299 // If the TYPER results in an error, it's because the type check
300 // failed (or will fail, when the error is uncovered and reported
301 // during writeback). In this case, we just ignore this part of the
304 // Note that this macro appears similar to try!(), but, unlike try!(),
305 // it does not propagate the error.
306 macro_rules! return_if_err(
315 impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> {
316 pub fn new(delegate: &'d mut Delegate<'tcx>,
318 -> ExprUseVisitor<'d,'t,'tcx,TYPER> {
319 ExprUseVisitor { typer: typer,
320 mc: mc::MemCategorizationContext::new(typer),
324 pub fn walk_fn(&mut self,
327 self.walk_arg_patterns(decl, body);
328 self.walk_block(body);
331 fn walk_arg_patterns(&mut self,
334 for arg in decl.inputs.iter() {
335 let arg_ty = return_if_err!(self.typer.node_ty(arg.pat.id));
337 let fn_body_scope = region::CodeExtent::from_node_id(body.id);
338 let arg_cmt = self.mc.cat_rvalue(
341 ty::ReScope(fn_body_scope), // Args live only as long as the fn body.
344 self.walk_irrefutable_pat(arg_cmt, &*arg.pat);
348 fn tcx(&self) -> &'t ty::ctxt<'tcx> {
352 fn delegate_consume(&mut self,
353 consume_id: ast::NodeId,
355 cmt: mc::cmt<'tcx>) {
356 let mode = copy_or_move(self.tcx(), cmt.ty, DirectRefMove);
357 self.delegate.consume(consume_id, consume_span, cmt, mode);
360 fn consume_exprs(&mut self, exprs: &Vec<P<ast::Expr>>) {
361 for expr in exprs.iter() {
362 self.consume_expr(&**expr);
366 pub fn consume_expr(&mut self, expr: &ast::Expr) {
367 debug!("consume_expr(expr={})", expr.repr(self.tcx()));
369 let cmt = return_if_err!(self.mc.cat_expr(expr));
370 self.delegate_consume(expr.id, expr.span, cmt);
371 self.walk_expr(expr);
374 fn mutate_expr(&mut self,
375 assignment_expr: &ast::Expr,
378 let cmt = return_if_err!(self.mc.cat_expr(expr));
379 self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
380 self.walk_expr(expr);
383 fn borrow_expr(&mut self,
388 debug!("borrow_expr(expr={}, r={}, bk={})",
389 expr.repr(self.tcx()), r.repr(self.tcx()), bk.repr(self.tcx()));
391 let cmt = return_if_err!(self.mc.cat_expr(expr));
392 self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
394 // Note: Unlike consume, we can ignore ExprParen. cat_expr
395 // already skips over them, and walk will uncover any
396 // attachments or whatever.
400 fn select_from_expr(&mut self, expr: &ast::Expr) {
404 pub fn walk_expr(&mut self, expr: &ast::Expr) {
405 debug!("walk_expr(expr={})", expr.repr(self.tcx()));
407 self.walk_adjustment(expr);
410 ast::ExprParen(ref subexpr) => {
411 self.walk_expr(&**subexpr)
414 ast::ExprPath(..) => { }
416 ast::ExprUnary(ast::UnDeref, ref base) => { // *base
417 if !self.walk_overloaded_operator(expr, &**base, Vec::new()) {
418 self.select_from_expr(&**base);
422 ast::ExprField(ref base, _) => { // base.f
423 self.select_from_expr(&**base);
426 ast::ExprTupField(ref base, _) => { // base.<n>
427 self.select_from_expr(&**base);
430 ast::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs]
431 if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs]) {
432 self.select_from_expr(&**lhs);
433 self.consume_expr(&**rhs);
437 ast::ExprSlice(ref base, ref start, ref end, _) => { // base[start..end]
438 let args = match (start, end) {
439 (&Some(ref e1), &Some(ref e2)) => vec![&**e1, &**e2],
440 (&Some(ref e), &None) => vec![&**e],
441 (&None, &Some(ref e)) => vec![&**e],
442 (&None, &None) => Vec::new()
444 let overloaded = self.walk_overloaded_operator(expr, &**base, args);
448 ast::ExprCall(ref callee, ref args) => { // callee(args)
449 self.walk_callee(expr, &**callee);
450 self.consume_exprs(args);
453 ast::ExprMethodCall(_, _, ref args) => { // callee.m(args)
454 self.consume_exprs(args);
457 ast::ExprStruct(_, ref fields, ref opt_with) => {
458 self.walk_struct_expr(expr, fields, opt_with);
461 ast::ExprTup(ref exprs) => {
462 self.consume_exprs(exprs);
465 ast::ExprIf(ref cond_expr, ref then_blk, ref opt_else_expr) => {
466 self.consume_expr(&**cond_expr);
467 self.walk_block(&**then_blk);
468 for else_expr in opt_else_expr.iter() {
469 self.consume_expr(&**else_expr);
473 ast::ExprIfLet(..) => {
474 self.tcx().sess.span_bug(expr.span, "non-desugared ExprIfLet");
477 ast::ExprMatch(ref discr, ref arms, _) => {
478 let discr_cmt = return_if_err!(self.mc.cat_expr(&**discr));
479 self.borrow_expr(&**discr, ty::ReEmpty, ty::ImmBorrow, MatchDiscriminant);
481 // treatment of the discriminant is handled while walking the arms.
482 for arm in arms.iter() {
483 let mode = self.arm_move_mode(discr_cmt.clone(), arm);
484 let mode = mode.match_mode();
485 self.walk_arm(discr_cmt.clone(), arm, mode);
489 ast::ExprVec(ref exprs) => {
490 self.consume_exprs(exprs);
493 ast::ExprAddrOf(m, ref base) => { // &base
494 // make sure that the thing we are pointing out stays valid
495 // for the lifetime `scope_r` of the resulting ptr:
496 let expr_ty = ty::expr_ty(self.tcx(), expr);
497 let r = ty::ty_region(self.tcx(), expr.span, expr_ty);
498 let bk = ty::BorrowKind::from_mutbl(m);
499 self.borrow_expr(&**base, r, bk, AddrOf);
502 ast::ExprInlineAsm(ref ia) => {
503 for &(_, ref input) in ia.inputs.iter() {
504 self.consume_expr(&**input);
507 for &(_, ref output, is_rw) in ia.outputs.iter() {
508 self.mutate_expr(expr, &**output,
509 if is_rw { WriteAndRead } else { JustWrite });
515 ast::ExprLit(..) => {}
517 ast::ExprLoop(ref blk, _) => {
518 self.walk_block(&**blk);
521 ast::ExprWhile(ref cond_expr, ref blk, _) => {
522 self.consume_expr(&**cond_expr);
523 self.walk_block(&**blk);
526 ast::ExprWhileLet(..) => {
527 self.tcx().sess.span_bug(expr.span, "non-desugared ExprWhileLet");
530 ast::ExprForLoop(ref pat, ref head, ref blk, _) => {
531 // The pattern lives as long as the block.
532 debug!("walk_expr for loop case: blk id={}", blk.id);
533 self.consume_expr(&**head);
535 // Fetch the type of the value that the iteration yields to
536 // produce the pattern's categorized mutable type.
537 let pattern_type = return_if_err!(self.typer.node_ty(pat.id));
538 let blk_scope = region::CodeExtent::from_node_id(blk.id);
539 let pat_cmt = self.mc.cat_rvalue(pat.id,
541 ty::ReScope(blk_scope),
543 self.walk_irrefutable_pat(pat_cmt, &**pat);
545 self.walk_block(&**blk);
548 ast::ExprUnary(_, ref lhs) => {
549 if !self.walk_overloaded_operator(expr, &**lhs, Vec::new()) {
550 self.consume_expr(&**lhs);
554 ast::ExprBinary(_, ref lhs, ref rhs) => {
555 if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs]) {
556 self.consume_expr(&**lhs);
557 self.consume_expr(&**rhs);
561 ast::ExprBlock(ref blk) => {
562 self.walk_block(&**blk);
565 ast::ExprRet(ref opt_expr) => {
566 for expr in opt_expr.iter() {
567 self.consume_expr(&**expr);
571 ast::ExprAssign(ref lhs, ref rhs) => {
572 self.mutate_expr(expr, &**lhs, JustWrite);
573 self.consume_expr(&**rhs);
576 ast::ExprCast(ref base, _) => {
577 self.consume_expr(&**base);
580 ast::ExprAssignOp(_, ref lhs, ref rhs) => {
581 // This will have to change if/when we support
582 // overloaded operators for `+=` and so forth.
583 self.mutate_expr(expr, &**lhs, WriteAndRead);
584 self.consume_expr(&**rhs);
587 ast::ExprRepeat(ref base, ref count) => {
588 self.consume_expr(&**base);
589 self.consume_expr(&**count);
592 ast::ExprClosure(..) |
593 ast::ExprProc(..) => {
594 self.walk_captures(expr)
597 ast::ExprBox(ref place, ref base) => {
598 self.consume_expr(&**place);
599 self.consume_expr(&**base);
602 ast::ExprMac(..) => {
603 self.tcx().sess.span_bug(
605 "macro expression remains after expansion");
610 fn walk_callee(&mut self, call: &ast::Expr, callee: &ast::Expr) {
611 let callee_ty = ty::expr_ty_adjusted(self.tcx(), callee);
612 debug!("walk_callee: callee={} callee_ty={}",
613 callee.repr(self.tcx()), callee_ty.repr(self.tcx()));
614 let call_scope = region::CodeExtent::from_node_id(call.id);
615 match callee_ty.sty {
616 ty::ty_bare_fn(..) => {
617 self.consume_expr(callee);
619 ty::ty_closure(ref f) => {
622 self.borrow_expr(callee,
623 ty::ReScope(call_scope),
628 self.consume_expr(callee);
633 let overloaded_call_type =
637 .get(&MethodCall::expr(call.id)) {
638 Some(ref method_callee) => {
639 OverloadedCallType::from_method_origin(
641 &method_callee.origin)
644 self.tcx().sess.span_bug(
646 format!("unexpected callee type {}",
647 callee_ty.repr(self.tcx())).as_slice())
650 match overloaded_call_type {
651 FnMutOverloadedCall => {
652 self.borrow_expr(callee,
653 ty::ReScope(call_scope),
657 FnOverloadedCall => {
658 self.borrow_expr(callee,
659 ty::ReScope(call_scope),
663 FnOnceOverloadedCall => self.consume_expr(callee),
669 fn walk_stmt(&mut self, stmt: &ast::Stmt) {
671 ast::StmtDecl(ref decl, _) => {
673 ast::DeclLocal(ref local) => {
674 self.walk_local(&**local);
677 ast::DeclItem(_) => {
678 // we don't visit nested items in this visitor,
679 // only the fn body we were given.
684 ast::StmtExpr(ref expr, _) |
685 ast::StmtSemi(ref expr, _) => {
686 self.consume_expr(&**expr);
689 ast::StmtMac(..) => {
690 self.tcx().sess.span_bug(stmt.span, "unexpanded stmt macro");
695 fn walk_local(&mut self, local: &ast::Local) {
698 let delegate = &mut self.delegate;
699 pat_util::pat_bindings(&self.typer.tcx().def_map, &*local.pat,
701 delegate.decl_without_init(id, span);
706 // Variable declarations with
707 // initializers are considered
708 // "assigns", which is handled by
710 self.walk_expr(&**expr);
711 let init_cmt = return_if_err!(self.mc.cat_expr(&**expr));
712 self.walk_irrefutable_pat(init_cmt, &*local.pat);
717 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
718 /// depending on its type.
719 fn walk_block(&mut self, blk: &ast::Block) {
720 debug!("walk_block(blk.id={})", blk.id);
722 for stmt in blk.stmts.iter() {
723 self.walk_stmt(&**stmt);
726 for tail_expr in blk.expr.iter() {
727 self.consume_expr(&**tail_expr);
731 fn walk_struct_expr(&mut self,
733 fields: &Vec<ast::Field>,
734 opt_with: &Option<P<ast::Expr>>) {
735 // Consume the expressions supplying values for each field.
736 for field in fields.iter() {
737 self.consume_expr(&*field.expr);
740 let with_expr = match *opt_with {
745 let with_cmt = return_if_err!(self.mc.cat_expr(&*with_expr));
747 // Select just those fields of the `with`
748 // expression that will actually be used
749 let with_fields = match with_cmt.ty.sty {
750 ty::ty_struct(did, ref substs) => {
751 ty::struct_fields(self.tcx(), did, substs)
754 self.tcx().sess.span_bug(
756 "with expression doesn't evaluate to a struct");
760 // Consume those fields of the with expression that are needed.
761 for with_field in with_fields.iter() {
762 if !contains_field_named(with_field, fields) {
763 let cmt_field = self.mc.cat_field(&*with_expr,
767 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
771 // walk the with expression so that complex expressions
772 // are properly handled.
773 self.walk_expr(with_expr);
775 fn contains_field_named(field: &ty::field,
776 fields: &Vec<ast::Field>)
780 |f| f.ident.node.name == field.name)
784 // Invoke the appropriate delegate calls for anything that gets
785 // consumed or borrowed as part of the automatic adjustment
787 fn walk_adjustment(&mut self, expr: &ast::Expr) {
788 let typer = self.typer;
789 match typer.adjustments().borrow().get(&expr.id) {
791 Some(adjustment) => {
793 ty::AdjustAddEnv(..) => {
794 // Creating a closure consumes the input and stores it
795 // into the resulting rvalue.
796 debug!("walk_adjustment(AutoAddEnv)");
798 return_if_err!(self.mc.cat_expr_unadjusted(expr));
799 self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
801 ty::AdjustDerefRef(ty::AutoDerefRef {
802 autoref: ref opt_autoref,
805 self.walk_autoderefs(expr, n);
810 self.walk_autoref(expr, r, n);
819 /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
820 /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
821 /// `deref()` is declared with `&self`, this is an autoref of `x`.
822 fn walk_autoderefs(&mut self,
825 debug!("walk_autoderefs expr={} autoderefs={}", expr.repr(self.tcx()), autoderefs);
827 for i in range(0, autoderefs) {
828 let deref_id = typeck::MethodCall::autoderef(expr.id, i);
829 match self.typer.node_method_ty(deref_id) {
832 let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
833 let self_ty = ty::ty_fn_args(method_ty)[0];
834 let (m, r) = match self_ty.sty {
835 ty::ty_rptr(r, ref m) => (m.mutbl, r),
836 _ => self.tcx().sess.span_bug(expr.span,
837 format!("bad overloaded deref type {}",
838 method_ty.repr(self.tcx())).as_slice())
840 let bk = ty::BorrowKind::from_mutbl(m);
841 self.delegate.borrow(expr.id, expr.span, cmt,
848 fn walk_autoref(&mut self,
850 autoref: &ty::AutoRef,
852 debug!("walk_autoref expr={}", expr.repr(self.tcx()));
854 // Match for unique trait coercions first, since we don't need the
855 // call to cat_expr_autoderefd.
857 ty::AutoUnsizeUniq(ty::UnsizeVtable(..)) |
858 ty::AutoUnsize(ty::UnsizeVtable(..)) => {
859 assert!(n == 1, format!("Expected exactly 1 deref with Uniq \
860 AutoRefs, found: {}", n));
862 return_if_err!(self.mc.cat_expr_unadjusted(expr));
863 self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
869 let cmt_derefd = return_if_err!(
870 self.mc.cat_expr_autoderefd(expr, n));
871 debug!("walk_adjustment: cmt_derefd={}",
872 cmt_derefd.repr(self.tcx()));
875 ty::AutoPtr(r, m, _) => {
876 self.delegate.borrow(expr.id,
880 ty::BorrowKind::from_mutbl(m),
883 ty::AutoUnsizeUniq(_) | ty::AutoUnsize(_) | ty::AutoUnsafe(..) => {}
887 fn walk_overloaded_operator(&mut self,
889 receiver: &ast::Expr,
890 rhs: Vec<&ast::Expr>)
893 if !self.typer.is_method_call(expr.id) {
897 self.walk_expr(receiver);
899 // Arguments (but not receivers) to overloaded operator
900 // methods are implicitly autoref'd which sadly does not use
901 // adjustments, so we must hardcode the borrow here.
903 let r = ty::ReScope(region::CodeExtent::from_node_id(expr.id));
904 let bk = ty::ImmBorrow;
906 for &arg in rhs.iter() {
907 self.borrow_expr(arg, r, bk, OverloadedOperator);
912 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &ast::Arm) -> TrackMatchMode<Span> {
913 let mut mode = Unknown;
914 for pat in arm.pats.iter() {
915 self.determine_pat_move_mode(discr_cmt.clone(), &**pat, &mut mode);
920 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &ast::Arm, mode: MatchMode) {
921 for pat in arm.pats.iter() {
922 self.walk_pat(discr_cmt.clone(), &**pat, mode);
925 for guard in arm.guard.iter() {
926 self.consume_expr(&**guard);
929 self.consume_expr(&*arm.body);
932 /// Walks an pat that occurs in isolation (i.e. top-level of fn
933 /// arg or let binding. *Not* a match arm or nested pat.)
934 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &ast::Pat) {
935 let mut mode = Unknown;
936 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
937 let mode = mode.match_mode();
938 self.walk_pat(cmt_discr, pat, mode);
941 /// Identifies any bindings within `pat` and accumulates within
942 /// `mode` whether the overall pattern/match structure is a move,
944 fn determine_pat_move_mode(&mut self,
945 cmt_discr: mc::cmt<'tcx>,
947 mode: &mut TrackMatchMode<Span>) {
948 debug!("determine_pat_move_mode cmt_discr={} pat={}", cmt_discr.repr(self.tcx()),
949 pat.repr(self.tcx()));
950 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
951 let tcx = self.typer.tcx();
952 let def_map = &self.typer.tcx().def_map;
953 if pat_util::pat_is_binding(def_map, pat) {
955 ast::PatIdent(ast::BindByRef(_), _, _) =>
956 mode.lub(BorrowingMatch),
957 ast::PatIdent(ast::BindByValue(_), _, _) => {
958 match copy_or_move(tcx, cmt_pat.ty, PatBindingMove) {
959 Copy => mode.lub(CopyingMatch),
960 Move(_) => mode.lub(MovingMatch),
966 "binding pattern not an identifier");
973 /// The core driver for walking a pattern; `match_mode` must be
974 /// established up front, e.g. via `determine_pat_move_mode` (see
975 /// also `walk_irrefutable_pat` for patterns that stand alone).
976 fn walk_pat(&mut self,
977 cmt_discr: mc::cmt<'tcx>,
979 match_mode: MatchMode) {
980 debug!("walk_pat cmt_discr={} pat={}", cmt_discr.repr(self.tcx()),
981 pat.repr(self.tcx()));
984 let typer = self.typer;
985 let tcx = typer.tcx();
986 let def_map = &self.typer.tcx().def_map;
987 let delegate = &mut self.delegate;
989 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
990 if pat_util::pat_is_binding(def_map, pat) {
991 let tcx = typer.tcx();
993 debug!("binding cmt_pat={} pat={} match_mode={}",
998 // pat_ty: the type of the binding being produced.
999 let pat_ty = return_if_err!(typer.node_ty(pat.id));
1001 // Each match binding is effectively an assignment to the
1002 // binding being produced.
1003 let def = def_map.borrow()[pat.id].clone();
1004 match mc.cat_def(pat.id, pat.span, pat_ty, def) {
1005 Ok(binding_cmt) => {
1006 delegate.mutate(pat.id, pat.span, binding_cmt, Init);
1011 // It is also a borrow or copy/move of the value being matched.
1013 ast::PatIdent(ast::BindByRef(m), _, _) => {
1015 (ty::ty_region(tcx, pat.span, pat_ty),
1016 ty::BorrowKind::from_mutbl(m))
1018 delegate.borrow(pat.id, pat.span, cmt_pat,
1021 ast::PatIdent(ast::BindByValue(_), _, _) => {
1022 let mode = copy_or_move(typer.tcx(), cmt_pat.ty, PatBindingMove);
1023 debug!("walk_pat binding consuming pat");
1024 delegate.consume_pat(pat, cmt_pat, mode);
1027 typer.tcx().sess.span_bug(
1029 "binding pattern not an identifier");
1034 ast::PatVec(_, Some(ref slice_pat), _) => {
1035 // The `slice_pat` here creates a slice into
1036 // the original vector. This is effectively a
1037 // borrow of the elements of the vector being
1040 let (slice_cmt, slice_mutbl, slice_r) = {
1041 match mc.cat_slice_pattern(cmt_pat, &**slice_pat) {
1044 tcx.sess.span_bug(slice_pat.span,
1050 // Note: We declare here that the borrow
1051 // occurs upon entering the `[...]`
1052 // pattern. This implies that something like
1053 // `[a, ..b]` where `a` is a move is illegal,
1054 // because the borrow is already in effect.
1055 // In fact such a move would be safe-ish, but
1056 // it effectively *requires* that we use the
1057 // nulling out semantics to indicate when a
1058 // value has been moved, which we are trying
1059 // to move away from. Otherwise, how can we
1060 // indicate that the first element in the
1061 // vector has been moved? Eventually, we
1062 // could perhaps modify this rule to permit
1063 // `[..a, b]` where `b` is a move, because in
1064 // that case we can adjust the length of the
1065 // original vec accordingly, but we'd have to
1066 // make trans do the right thing, and it would
1067 // only work for `~` vectors. It seems simpler
1068 // to just require that people call
1069 // `vec.pop()` or `vec.unshift()`.
1070 let slice_bk = ty::BorrowKind::from_mutbl(slice_mutbl);
1071 delegate.borrow(pat.id, pat.span,
1073 slice_bk, RefBinding);
1080 // Do a second pass over the pattern, calling `matched_pat` on
1081 // the interior nodes (enum variants and structs), as opposed
1082 // to the above loop's visit of than the bindings that form
1083 // the leaves of the pattern tree structure.
1084 return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
1085 let def_map = def_map.borrow();
1086 let tcx = typer.tcx();
1089 ast::PatEnum(_, _) | ast::PatIdent(_, _, None) | ast::PatStruct(..) => {
1090 match def_map.get(&pat.id) {
1092 // no definition found: pat is not a
1093 // struct or enum pattern.
1096 Some(&def::DefVariant(enum_did, variant_did, _is_struct)) => {
1098 if ty::enum_is_univariant(tcx, enum_did) {
1101 let cmt_pat_ty = cmt_pat.ty;
1102 mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
1105 debug!("variant downcast_cmt={} pat={}",
1106 downcast_cmt.repr(tcx),
1109 delegate.matched_pat(pat, downcast_cmt, match_mode);
1112 Some(&def::DefStruct(..)) | Some(&def::DefTy(_, false)) => {
1113 // A struct (in either the value or type
1114 // namespace; we encounter the former on
1115 // e.g. patterns for unit structs).
1117 debug!("struct cmt_pat={} pat={}",
1121 delegate.matched_pat(pat, cmt_pat, match_mode);
1124 Some(&def::DefConst(..)) |
1125 Some(&def::DefLocal(..)) => {
1126 // This is a leaf (i.e. identifier binding
1127 // or constant value to match); thus no
1128 // `matched_pat` call.
1131 Some(def @ &def::DefTy(_, true)) => {
1132 // An enum's type -- should never be in a
1135 let msg = format!("Pattern has unexpected type: {}", def);
1136 tcx.sess.span_bug(pat.span, msg.as_slice())
1140 // Remaining cases are e.g. DefFn, to
1141 // which identifiers within patterns
1142 // should not resolve.
1144 let msg = format!("Pattern has unexpected def: {}", def);
1145 tcx.sess.span_bug(pat.span, msg.as_slice())
1150 ast::PatIdent(_, _, Some(_)) => {
1151 // Do nothing; this is a binding (not a enum
1152 // variant or struct), and the cat_pattern call
1153 // will visit the substructure recursively.
1156 ast::PatWild(_) | ast::PatTup(..) | ast::PatBox(..) |
1157 ast::PatRegion(..) | ast::PatLit(..) | ast::PatRange(..) |
1158 ast::PatVec(..) | ast::PatMac(..) => {
1159 // Similarly, each of these cases does not
1160 // correspond to a enum variant or struct, so we
1161 // do not do any `matched_pat` calls for these
1168 fn walk_captures(&mut self, closure_expr: &ast::Expr) {
1169 debug!("walk_captures({})", closure_expr.repr(self.tcx()));
1171 let tcx = self.typer.tcx();
1172 ty::with_freevars(tcx, closure_expr.id, |freevars| {
1173 match self.tcx().capture_mode(closure_expr.id) {
1174 ast::CaptureByRef => {
1175 self.walk_by_ref_captures(closure_expr, freevars);
1177 ast::CaptureByValue => {
1178 self.walk_by_value_captures(closure_expr, freevars);
1184 fn walk_by_ref_captures(&mut self,
1185 closure_expr: &ast::Expr,
1186 freevars: &[ty::Freevar]) {
1187 for freevar in freevars.iter() {
1188 let id_var = freevar.def.def_id().node;
1189 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1193 // Lookup the kind of borrow the callee requires, as
1194 // inferred by regionbk
1195 let upvar_id = ty::UpvarId { var_id: id_var,
1196 closure_expr_id: closure_expr.id };
1197 let upvar_borrow = self.tcx().upvar_borrow_map.borrow()[upvar_id].clone();
1199 self.delegate.borrow(closure_expr.id,
1202 upvar_borrow.region,
1204 ClosureCapture(freevar.span));
1208 fn walk_by_value_captures(&mut self,
1209 closure_expr: &ast::Expr,
1210 freevars: &[ty::Freevar]) {
1211 for freevar in freevars.iter() {
1212 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1215 let mode = copy_or_move(self.tcx(), cmt_var.ty, CaptureMove);
1216 self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
1220 fn cat_captured_var(&mut self,
1221 closure_id: ast::NodeId,
1223 upvar_def: def::Def)
1224 -> mc::McResult<mc::cmt<'tcx>> {
1225 // Create the cmt for the variable being borrowed, from the
1226 // caller's perspective
1227 let var_id = upvar_def.def_id().node;
1228 let var_ty = try!(self.typer.node_ty(var_id));
1229 self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
1233 fn copy_or_move<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>,
1234 move_reason: MoveReason) -> ConsumeMode {
1235 if ty::type_moves_by_default(tcx, ty) { Move(move_reason) } else { Copy }