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
::{self}
;
27 use middle
::ty
::{MethodCall, MethodObject, MethodTraitObject}
;
28 use middle
::ty
::{MethodOrigin, MethodParam, MethodTypeParam}
;
29 use middle
::ty
::{MethodStatic, MethodStaticClosure}
;
30 use util
::ppaux
::Repr
;
32 use syntax
::{ast, ast_util}
;
34 use syntax
::codemap
::Span
;
36 ///////////////////////////////////////////////////////////////////////////
39 /// This trait defines the callbacks you can expect to receive when
40 /// employing the ExprUseVisitor.
41 pub trait Delegate
<'tcx
> {
42 // The value found at `cmt` is either copied or moved, depending
45 consume_id
: ast
::NodeId
,
50 // The value found at `cmt` has been determined to match the
51 // pattern binding `matched_pat`, and its subparts are being
52 // copied or moved depending on `mode`. Note that `matched_pat`
53 // is called on all variant/structs in the pattern (i.e., the
54 // interior nodes of the pattern's tree structure) while
55 // consume_pat is called on the binding identifiers in the pattern
56 // (which are leaves of the pattern's tree structure).
58 // Note that variants/structs and identifiers are disjoint; thus
59 // `matched_pat` and `consume_pat` are never both called on the
60 // same input pattern structure (though of `consume_pat` can be
61 // called on a subpart of an input passed to `matched_pat).
62 fn matched_pat(&mut self,
63 matched_pat
: &ast
::Pat
,
67 // The value found at `cmt` is either copied or moved via the
68 // pattern binding `consume_pat`, depending on mode.
69 fn consume_pat(&mut self,
70 consume_pat
: &ast
::Pat
,
74 // The value found at `borrow` is being borrowed at the point
75 // `borrow_id` for the region `loan_region` with kind `bk`.
77 borrow_id
: ast
::NodeId
,
80 loan_region
: ty
::Region
,
82 loan_cause
: LoanCause
);
84 // The local variable `id` is declared but not initialized.
85 fn decl_without_init(&mut self,
89 // The path at `cmt` is being assigned to.
91 assignment_id
: ast
::NodeId
,
92 assignment_span
: Span
,
93 assignee_cmt
: mc
::cmt
<'tcx
>,
97 #[derive(Copy, Clone, PartialEq, Debug)]
110 #[derive(Copy, Clone, PartialEq, Debug)]
111 pub enum ConsumeMode
{
112 Copy
, // reference to x where x has a type that copies
113 Move(MoveReason
), // reference to x where x has a type that moves
116 #[derive(Copy, Clone, PartialEq, Debug)]
117 pub enum MoveReason
{
123 #[derive(Copy, Clone, PartialEq, Debug)]
131 #[derive(Copy, Clone, PartialEq, Debug)]
132 enum TrackMatchMode
{
138 impl TrackMatchMode
{
139 // Builds up the whole match mode for a pattern from its constituent
140 // parts. The lattice looks like this:
156 // * `(_, some_int)` pattern is Copying, since
157 // NonBinding + Copying => Copying
159 // * `(some_int, some_box)` pattern is Moving, since
160 // Copying + Moving => Moving
162 // * `(ref x, some_box)` pattern is Conflicting, since
163 // Borrowing + Moving => Conflicting
165 // Note that the `Unknown` and `Conflicting` states are
166 // represented separately from the other more interesting
167 // `Definite` states, which simplifies logic here somewhat.
168 fn lub(&mut self, mode
: MatchMode
) {
169 *self = match (*self, mode
) {
170 // Note that clause order below is very significant.
171 (Unknown
, new
) => Definite(new
),
172 (Definite(old
), new
) if old
== new
=> Definite(old
),
174 (Definite(old
), NonBindingMatch
) => Definite(old
),
175 (Definite(NonBindingMatch
), new
) => Definite(new
),
177 (Definite(old
), CopyingMatch
) => Definite(old
),
178 (Definite(CopyingMatch
), new
) => Definite(new
),
180 (Definite(_
), _
) => Conflicting
,
181 (Conflicting
, _
) => *self,
185 fn match_mode(&self) -> MatchMode
{
187 Unknown
=> NonBindingMatch
,
188 Definite(mode
) => mode
,
190 // Conservatively return MovingMatch to let the
191 // compiler continue to make progress.
198 #[derive(Copy, Clone, PartialEq, Debug)]
199 pub enum MutateMode
{
202 WriteAndRead
, // x += y
205 #[derive(Copy, Clone)]
206 enum OverloadedCallType
{
209 FnOnceOverloadedCall
,
212 impl OverloadedCallType
{
213 fn from_trait_id(tcx
: &ty
::ctxt
, trait_id
: ast
::DefId
)
214 -> OverloadedCallType
{
215 for &(maybe_function_trait
, overloaded_call_type
) in [
216 (tcx
.lang_items
.fn_once_trait(), FnOnceOverloadedCall
),
217 (tcx
.lang_items
.fn_mut_trait(), FnMutOverloadedCall
),
218 (tcx
.lang_items
.fn_trait(), FnOverloadedCall
)
220 match maybe_function_trait
{
221 Some(function_trait
) if function_trait
== trait_id
=> {
222 return overloaded_call_type
228 tcx
.sess
.bug("overloaded call didn't map to known function trait")
231 fn from_method_id(tcx
: &ty
::ctxt
, method_id
: ast
::DefId
)
232 -> OverloadedCallType
{
233 let method_descriptor
= match ty
::impl_or_trait_item(tcx
, method_id
) {
234 ty
::MethodTraitItem(ref method_descriptor
) => {
235 (*method_descriptor
).clone()
237 ty
::TypeTraitItem(_
) => {
238 tcx
.sess
.bug("overloaded call method wasn't in method map")
241 let impl_id
= match method_descriptor
.container
{
242 ty
::TraitContainer(_
) => {
243 tcx
.sess
.bug("statically resolved overloaded call method \
244 belonged to a trait?!")
246 ty
::ImplContainer(impl_id
) => impl_id
,
248 let trait_ref
= match ty
::impl_trait_ref(tcx
, impl_id
) {
250 tcx
.sess
.bug("statically resolved overloaded call impl \
251 didn't implement a trait?!")
253 Some(ref trait_ref
) => (*trait_ref
).clone(),
255 OverloadedCallType
::from_trait_id(tcx
, trait_ref
.def_id
)
258 fn from_closure(tcx
: &ty
::ctxt
, closure_did
: ast
::DefId
)
259 -> OverloadedCallType
{
264 .expect("OverloadedCallType::from_closure: didn't find closure id")
266 OverloadedCallType
::from_trait_id(tcx
, trait_did
)
269 fn from_method_origin(tcx
: &ty
::ctxt
, origin
: &MethodOrigin
)
270 -> OverloadedCallType
{
272 MethodStatic(def_id
) => {
273 OverloadedCallType
::from_method_id(tcx
, def_id
)
275 MethodStaticClosure(def_id
) => {
276 OverloadedCallType
::from_closure(tcx
, def_id
)
278 MethodTypeParam(MethodParam { ref trait_ref, .. }
) |
279 MethodTraitObject(MethodObject { ref trait_ref, .. }
) => {
280 OverloadedCallType
::from_trait_id(tcx
, trait_ref
.def_id
)
286 ///////////////////////////////////////////////////////////////////////////
287 // The ExprUseVisitor type
289 // This is the code that actually walks the tree. Like
290 // mem_categorization, it requires a TYPER, which is a type that
291 // supplies types from the tree. After type checking is complete, you
292 // can just use the tcx as the typer.
294 pub struct ExprUseVisitor
<'d
,'t
,'tcx
:'t
,TYPER
:'t
> {
296 mc
: mc
::MemCategorizationContext
<'t
,TYPER
>,
297 delegate
: &'d
mut (Delegate
<'tcx
>+'d
),
300 // If the TYPER results in an error, it's because the type check
301 // failed (or will fail, when the error is uncovered and reported
302 // during writeback). In this case, we just ignore this part of the
305 // Note that this macro appears similar to try!(), but, unlike try!(),
306 // it does not propagate the error.
307 macro_rules
! return_if_err
{
316 /// Whether the elements of an overloaded operation are passed by value or by reference
322 impl<'d
,'t
,'tcx
,TYPER
:mc
::Typer
<'tcx
>> ExprUseVisitor
<'d
,'t
,'tcx
,TYPER
> {
323 pub fn new(delegate
: &'d
mut Delegate
<'tcx
>,
325 -> ExprUseVisitor
<'d
,'t
,'tcx
,TYPER
> {
328 mc
: mc
::MemCategorizationContext
::new(typer
),
333 pub fn walk_fn(&mut self,
336 self.walk_arg_patterns(decl
, body
);
337 self.walk_block(body
);
340 fn walk_arg_patterns(&mut self,
343 for arg
in &decl
.inputs
{
344 let arg_ty
= return_if_err
!(self.typer
.node_ty(arg
.pat
.id
));
346 let fn_body_scope
= region
::CodeExtent
::from_node_id(body
.id
);
347 let arg_cmt
= self.mc
.cat_rvalue(
350 ty
::ReScope(fn_body_scope
), // Args live only as long as the fn body.
353 self.walk_irrefutable_pat(arg_cmt
, &*arg
.pat
);
357 fn tcx(&self) -> &'t ty
::ctxt
<'tcx
> {
361 fn delegate_consume(&mut self,
362 consume_id
: ast
::NodeId
,
364 cmt
: mc
::cmt
<'tcx
>) {
365 debug
!("delegate_consume(consume_id={}, cmt={})",
366 consume_id
, cmt
.repr(self.tcx()));
368 let mode
= copy_or_move(self.typer
, &cmt
, DirectRefMove
);
369 self.delegate
.consume(consume_id
, consume_span
, cmt
, mode
);
372 fn consume_exprs(&mut self, exprs
: &Vec
<P
<ast
::Expr
>>) {
374 self.consume_expr(&**expr
);
378 pub fn consume_expr(&mut self, expr
: &ast
::Expr
) {
379 debug
!("consume_expr(expr={})", expr
.repr(self.tcx()));
381 let cmt
= return_if_err
!(self.mc
.cat_expr(expr
));
382 self.delegate_consume(expr
.id
, expr
.span
, cmt
);
383 self.walk_expr(expr
);
386 fn mutate_expr(&mut self,
387 assignment_expr
: &ast
::Expr
,
390 let cmt
= return_if_err
!(self.mc
.cat_expr(expr
));
391 self.delegate
.mutate(assignment_expr
.id
, assignment_expr
.span
, cmt
, mode
);
392 self.walk_expr(expr
);
395 fn borrow_expr(&mut self,
400 debug
!("borrow_expr(expr={}, r={}, bk={})",
401 expr
.repr(self.tcx()), r
.repr(self.tcx()), bk
.repr(self.tcx()));
403 let cmt
= return_if_err
!(self.mc
.cat_expr(expr
));
404 self.delegate
.borrow(expr
.id
, expr
.span
, cmt
, r
, bk
, cause
);
406 // Note: Unlike consume, we can ignore ExprParen. cat_expr
407 // already skips over them, and walk will uncover any
408 // attachments or whatever.
412 fn select_from_expr(&mut self, expr
: &ast
::Expr
) {
416 pub fn walk_expr(&mut self, expr
: &ast
::Expr
) {
417 debug
!("walk_expr(expr={})", expr
.repr(self.tcx()));
419 self.walk_adjustment(expr
);
422 ast
::ExprParen(ref subexpr
) => {
423 self.walk_expr(&**subexpr
)
426 ast
::ExprPath(..) => { }
428 ast
::ExprUnary(ast
::UnDeref
, ref base
) => { // *base
429 if !self.walk_overloaded_operator(expr
, &**base
, Vec
::new(), PassArgs
::ByRef
) {
430 self.select_from_expr(&**base
);
434 ast
::ExprField(ref base
, _
) => { // base.f
435 self.select_from_expr(&**base
);
438 ast
::ExprTupField(ref base
, _
) => { // base.<n>
439 self.select_from_expr(&**base
);
442 ast
::ExprIndex(ref lhs
, ref rhs
) => { // lhs[rhs]
443 if !self.walk_overloaded_operator(expr
,
447 self.select_from_expr(&**lhs
);
448 self.consume_expr(&**rhs
);
452 ast
::ExprRange(ref start
, ref end
) => {
453 start
.as_ref().map(|e
| self.consume_expr(&**e
));
454 end
.as_ref().map(|e
| self.consume_expr(&**e
));
457 ast
::ExprCall(ref callee
, ref args
) => { // callee(args)
458 self.walk_callee(expr
, &**callee
);
459 self.consume_exprs(args
);
462 ast
::ExprMethodCall(_
, _
, ref args
) => { // callee.m(args)
463 self.consume_exprs(args
);
466 ast
::ExprStruct(_
, ref fields
, ref opt_with
) => {
467 self.walk_struct_expr(expr
, fields
, opt_with
);
470 ast
::ExprTup(ref exprs
) => {
471 self.consume_exprs(exprs
);
474 ast
::ExprIf(ref cond_expr
, ref then_blk
, ref opt_else_expr
) => {
475 self.consume_expr(&**cond_expr
);
476 self.walk_block(&**then_blk
);
477 if let Some(ref else_expr
) = *opt_else_expr
{
478 self.consume_expr(&**else_expr
);
482 ast
::ExprIfLet(..) => {
483 self.tcx().sess
.span_bug(expr
.span
, "non-desugared ExprIfLet");
486 ast
::ExprMatch(ref discr
, ref arms
, _
) => {
487 let discr_cmt
= return_if_err
!(self.mc
.cat_expr(&**discr
));
488 self.borrow_expr(&**discr
, ty
::ReEmpty
, ty
::ImmBorrow
, MatchDiscriminant
);
490 // treatment of the discriminant is handled while walking the arms.
492 let mode
= self.arm_move_mode(discr_cmt
.clone(), arm
);
493 let mode
= mode
.match_mode();
494 self.walk_arm(discr_cmt
.clone(), arm
, mode
);
498 ast
::ExprVec(ref exprs
) => {
499 self.consume_exprs(exprs
);
502 ast
::ExprAddrOf(m
, ref base
) => { // &base
503 // make sure that the thing we are pointing out stays valid
504 // for the lifetime `scope_r` of the resulting ptr:
505 let expr_ty
= return_if_err
!(self.typer
.node_ty(expr
.id
));
506 let r
= ty
::ty_region(self.tcx(), expr
.span
, expr_ty
);
507 let bk
= ty
::BorrowKind
::from_mutbl(m
);
508 self.borrow_expr(&**base
, r
, bk
, AddrOf
);
511 ast
::ExprInlineAsm(ref ia
) => {
512 for &(_
, ref input
) in &ia
.inputs
{
513 self.consume_expr(&**input
);
516 for &(_
, ref output
, is_rw
) in &ia
.outputs
{
517 self.mutate_expr(expr
, &**output
,
518 if is_rw { WriteAndRead }
else { JustWrite }
);
524 ast
::ExprLit(..) => {}
526 ast
::ExprLoop(ref blk
, _
) => {
527 self.walk_block(&**blk
);
530 ast
::ExprWhile(ref cond_expr
, ref blk
, _
) => {
531 self.consume_expr(&**cond_expr
);
532 self.walk_block(&**blk
);
535 ast
::ExprWhileLet(..) => {
536 self.tcx().sess
.span_bug(expr
.span
, "non-desugared ExprWhileLet");
539 ast
::ExprForLoop(..) => {
540 self.tcx().sess
.span_bug(expr
.span
, "non-desugared ExprForLoop");
543 ast
::ExprUnary(op
, ref lhs
) => {
544 let pass_args
= if ast_util
::is_by_value_unop(op
) {
550 if !self.walk_overloaded_operator(expr
, &**lhs
, Vec
::new(), pass_args
) {
551 self.consume_expr(&**lhs
);
555 ast
::ExprBinary(op
, ref lhs
, ref rhs
) => {
556 let pass_args
= if ast_util
::is_by_value_binop(op
.node
) {
562 if !self.walk_overloaded_operator(expr
, &**lhs
, vec
![&**rhs
], pass_args
) {
563 self.consume_expr(&**lhs
);
564 self.consume_expr(&**rhs
);
568 ast
::ExprBlock(ref blk
) => {
569 self.walk_block(&**blk
);
572 ast
::ExprRet(ref opt_expr
) => {
573 if let Some(ref expr
) = *opt_expr
{
574 self.consume_expr(&**expr
);
578 ast
::ExprAssign(ref lhs
, ref rhs
) => {
579 self.mutate_expr(expr
, &**lhs
, JustWrite
);
580 self.consume_expr(&**rhs
);
583 ast
::ExprCast(ref base
, _
) => {
584 self.consume_expr(&**base
);
587 ast
::ExprAssignOp(_
, ref lhs
, ref rhs
) => {
588 // This will have to change if/when we support
589 // overloaded operators for `+=` and so forth.
590 self.mutate_expr(expr
, &**lhs
, WriteAndRead
);
591 self.consume_expr(&**rhs
);
594 ast
::ExprRepeat(ref base
, ref count
) => {
595 self.consume_expr(&**base
);
596 self.consume_expr(&**count
);
599 ast
::ExprClosure(..) => {
600 self.walk_captures(expr
)
603 ast
::ExprBox(ref place
, ref base
) => {
605 Some(ref place
) => self.consume_expr(&**place
),
608 self.consume_expr(&**base
);
611 ast
::ExprMac(..) => {
612 self.tcx().sess
.span_bug(
614 "macro expression remains after expansion");
619 fn walk_callee(&mut self, call
: &ast
::Expr
, callee
: &ast
::Expr
) {
620 let callee_ty
= return_if_err
!(self.typer
.expr_ty_adjusted(callee
));
621 debug
!("walk_callee: callee={} callee_ty={}",
622 callee
.repr(self.tcx()), callee_ty
.repr(self.tcx()));
623 let call_scope
= region
::CodeExtent
::from_node_id(call
.id
);
624 match callee_ty
.sty
{
625 ty
::ty_bare_fn(..) => {
626 self.consume_expr(callee
);
630 let overloaded_call_type
=
631 match self.typer
.node_method_origin(MethodCall
::expr(call
.id
)) {
632 Some(method_origin
) => {
633 OverloadedCallType
::from_method_origin(
638 self.tcx().sess
.span_bug(
640 &format
!("unexpected callee type {}", callee_ty
.repr(self.tcx())))
643 match overloaded_call_type
{
644 FnMutOverloadedCall
=> {
645 self.borrow_expr(callee
,
646 ty
::ReScope(call_scope
),
650 FnOverloadedCall
=> {
651 self.borrow_expr(callee
,
652 ty
::ReScope(call_scope
),
656 FnOnceOverloadedCall
=> self.consume_expr(callee
),
662 fn walk_stmt(&mut self, stmt
: &ast
::Stmt
) {
664 ast
::StmtDecl(ref decl
, _
) => {
666 ast
::DeclLocal(ref local
) => {
667 self.walk_local(&**local
);
670 ast
::DeclItem(_
) => {
671 // we don't visit nested items in this visitor,
672 // only the fn body we were given.
677 ast
::StmtExpr(ref expr
, _
) |
678 ast
::StmtSemi(ref expr
, _
) => {
679 self.consume_expr(&**expr
);
682 ast
::StmtMac(..) => {
683 self.tcx().sess
.span_bug(stmt
.span
, "unexpanded stmt macro");
688 fn walk_local(&mut self, local
: &ast
::Local
) {
691 let delegate
= &mut self.delegate
;
692 pat_util
::pat_bindings(&self.typer
.tcx().def_map
, &*local
.pat
,
694 delegate
.decl_without_init(id
, span
);
699 // Variable declarations with
700 // initializers are considered
701 // "assigns", which is handled by
703 self.walk_expr(&**expr
);
704 let init_cmt
= return_if_err
!(self.mc
.cat_expr(&**expr
));
705 self.walk_irrefutable_pat(init_cmt
, &*local
.pat
);
710 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
711 /// depending on its type.
712 fn walk_block(&mut self, blk
: &ast
::Block
) {
713 debug
!("walk_block(blk.id={})", blk
.id
);
715 for stmt
in &blk
.stmts
{
716 self.walk_stmt(&**stmt
);
719 if let Some(ref tail_expr
) = blk
.expr
{
720 self.consume_expr(&**tail_expr
);
724 fn walk_struct_expr(&mut self,
726 fields
: &Vec
<ast
::Field
>,
727 opt_with
: &Option
<P
<ast
::Expr
>>) {
728 // Consume the expressions supplying values for each field.
729 for field
in fields
{
730 self.consume_expr(&*field
.expr
);
733 let with_expr
= match *opt_with
{
738 let with_cmt
= return_if_err
!(self.mc
.cat_expr(&*with_expr
));
740 // Select just those fields of the `with`
741 // expression that will actually be used
742 let with_fields
= match with_cmt
.ty
.sty
{
743 ty
::ty_struct(did
, substs
) => {
744 ty
::struct_fields(self.tcx(), did
, substs
)
747 // the base expression should always evaluate to a
748 // struct; however, when EUV is run during typeck, it
749 // may not. This will generate an error earlier in typeck,
750 // so we can just ignore it.
751 if !self.tcx().sess
.has_errors() {
752 self.tcx().sess
.span_bug(
754 "with expression doesn't evaluate to a struct");
756 assert
!(self.tcx().sess
.has_errors());
761 // Consume those fields of the with expression that are needed.
762 for with_field
in &with_fields
{
763 if !contains_field_named(with_field
, fields
) {
764 let cmt_field
= self.mc
.cat_field(&*with_expr
,
768 self.delegate_consume(with_expr
.id
, with_expr
.span
, cmt_field
);
772 // walk the with expression so that complex expressions
773 // are properly handled.
774 self.walk_expr(with_expr
);
776 fn contains_field_named(field
: &ty
::field
,
777 fields
: &Vec
<ast
::Field
>)
781 |f
| f
.ident
.node
.name
== field
.name
)
785 // Invoke the appropriate delegate calls for anything that gets
786 // consumed or borrowed as part of the automatic adjustment
788 fn walk_adjustment(&mut self, expr
: &ast
::Expr
) {
789 let typer
= self.typer
;
790 if let Some(adjustment
) = typer
.adjustments().borrow().get(&expr
.id
) {
792 ty
::AdjustReifyFnPointer
|
793 ty
::AdjustUnsafeFnPointer
=> {
794 // Creating a closure/fn-pointer or unsizing consumes
795 // the input and stores it into the resulting rvalue.
796 debug
!("walk_adjustment(AdjustReifyFnPointer|AdjustUnsafeFnPointer)");
798 return_if_err
!(self.mc
.cat_expr_unadjusted(expr
));
799 self.delegate_consume(expr
.id
, expr
.span
, cmt_unadjusted
);
801 ty
::AdjustDerefRef(ref adj
) => {
802 self.walk_autoderefref(expr
, adj
);
808 /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
809 /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
810 /// `deref()` is declared with `&self`, this is an autoref of `x`.
811 fn walk_autoderefs(&mut self,
814 debug
!("walk_autoderefs expr={} autoderefs={}", expr
.repr(self.tcx()), autoderefs
);
816 for i
in 0..autoderefs
{
817 let deref_id
= ty
::MethodCall
::autoderef(expr
.id
, i
as u32);
818 match self.typer
.node_method_ty(deref_id
) {
821 let cmt
= return_if_err
!(self.mc
.cat_expr_autoderefd(expr
, i
));
823 // the method call infrastructure should have
824 // replaced all late-bound regions with variables:
825 let self_ty
= ty
::ty_fn_sig(method_ty
).input(0);
826 let self_ty
= ty
::no_late_bound_regions(self.tcx(), &self_ty
).unwrap();
828 let (m
, r
) = match self_ty
.sty
{
829 ty
::ty_rptr(r
, ref m
) => (m
.mutbl
, r
),
830 _
=> self.tcx().sess
.span_bug(expr
.span
,
831 &format
!("bad overloaded deref type {}",
832 method_ty
.repr(self.tcx())))
834 let bk
= ty
::BorrowKind
::from_mutbl(m
);
835 self.delegate
.borrow(expr
.id
, expr
.span
, cmt
,
842 fn walk_autoderefref(&mut self,
844 adj
: &ty
::AutoDerefRef
<'tcx
>) {
845 debug
!("walk_autoderefref expr={} adj={}",
846 expr
.repr(self.tcx()),
847 adj
.repr(self.tcx()));
849 self.walk_autoderefs(expr
, adj
.autoderefs
);
852 return_if_err
!(self.mc
.cat_expr_autoderefd(expr
, adj
.autoderefs
));
855 self.walk_autoref(expr
, cmt_derefd
, adj
.autoref
);
857 if adj
.unsize
.is_some() {
858 // Unsizing consumes the thin pointer and produces a fat one.
859 self.delegate_consume(expr
.id
, expr
.span
, cmt_refd
);
864 /// Walks the autoref `opt_autoref` applied to the autoderef'd
865 /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
866 /// after all relevant autoderefs have occurred. Because AutoRefs
867 /// can be recursive, this function is recursive: it first walks
868 /// deeply all the way down the autoref chain, and then processes
869 /// the autorefs on the way out. At each point, it returns the
870 /// `cmt` for the rvalue that will be produced by introduced an
872 fn walk_autoref(&mut self,
874 cmt_base
: mc
::cmt
<'tcx
>,
875 opt_autoref
: Option
<ty
::AutoRef
<'tcx
>>)
878 debug
!("walk_autoref(expr.id={} cmt_derefd={} opt_autoref={:?})",
880 cmt_base
.repr(self.tcx()),
883 let cmt_base_ty
= cmt_base
.ty
;
885 let autoref
= match opt_autoref
{
886 Some(ref autoref
) => autoref
,
893 debug
!("walk_autoref: expr.id={} cmt_base={}",
895 cmt_base
.repr(self.tcx()));
898 ty
::AutoPtr(r
, m
) => {
899 self.delegate
.borrow(expr
.id
,
903 ty
::BorrowKind
::from_mutbl(m
),
907 ty
::AutoUnsafe(m
) => {
908 debug
!("walk_autoref: expr.id={} cmt_base={}",
910 cmt_base
.repr(self.tcx()));
912 // Converting from a &T to *T (or &mut T to *mut T) is
913 // treated as borrowing it for the enclosing temporary
915 let r
= ty
::ReScope(region
::CodeExtent
::from_node_id(expr
.id
));
917 self.delegate
.borrow(expr
.id
,
921 ty
::BorrowKind
::from_mutbl(m
),
926 // Construct the categorization for the result of the autoref.
927 // This is always an rvalue, since we are producing a new
928 // (temporary) indirection.
931 ty
::adjust_ty_for_autoref(self.tcx(),
935 self.mc
.cat_rvalue_node(expr
.id
, expr
.span
, adj_ty
)
939 // When this returns true, it means that the expression *is* a
940 // method-call (i.e. via the operator-overload). This true result
941 // also implies that walk_overloaded_operator already took care of
942 // recursively processing the input arguments, and thus the caller
944 fn walk_overloaded_operator(&mut self,
946 receiver
: &ast
::Expr
,
947 rhs
: Vec
<&ast
::Expr
>,
951 if !self.typer
.is_method_call(expr
.id
) {
956 PassArgs
::ByValue
=> {
957 self.consume_expr(receiver
);
959 self.consume_expr(arg
);
964 PassArgs
::ByRef
=> {}
,
967 self.walk_expr(receiver
);
969 // Arguments (but not receivers) to overloaded operator
970 // methods are implicitly autoref'd which sadly does not use
971 // adjustments, so we must hardcode the borrow here.
973 let r
= ty
::ReScope(region
::CodeExtent
::from_node_id(expr
.id
));
974 let bk
= ty
::ImmBorrow
;
977 self.borrow_expr(arg
, r
, bk
, OverloadedOperator
);
982 fn arm_move_mode(&mut self, discr_cmt
: mc
::cmt
<'tcx
>, arm
: &ast
::Arm
) -> TrackMatchMode
{
983 let mut mode
= Unknown
;
984 for pat
in &arm
.pats
{
985 self.determine_pat_move_mode(discr_cmt
.clone(), &**pat
, &mut mode
);
990 fn walk_arm(&mut self, discr_cmt
: mc
::cmt
<'tcx
>, arm
: &ast
::Arm
, mode
: MatchMode
) {
991 for pat
in &arm
.pats
{
992 self.walk_pat(discr_cmt
.clone(), &**pat
, mode
);
995 if let Some(ref guard
) = arm
.guard
{
996 self.consume_expr(&**guard
);
999 self.consume_expr(&*arm
.body
);
1002 /// Walks an pat that occurs in isolation (i.e. top-level of fn
1003 /// arg or let binding. *Not* a match arm or nested pat.)
1004 fn walk_irrefutable_pat(&mut self, cmt_discr
: mc
::cmt
<'tcx
>, pat
: &ast
::Pat
) {
1005 let mut mode
= Unknown
;
1006 self.determine_pat_move_mode(cmt_discr
.clone(), pat
, &mut mode
);
1007 let mode
= mode
.match_mode();
1008 self.walk_pat(cmt_discr
, pat
, mode
);
1011 /// Identifies any bindings within `pat` and accumulates within
1012 /// `mode` whether the overall pattern/match structure is a move,
1013 /// copy, or borrow.
1014 fn determine_pat_move_mode(&mut self,
1015 cmt_discr
: mc
::cmt
<'tcx
>,
1017 mode
: &mut TrackMatchMode
) {
1018 debug
!("determine_pat_move_mode cmt_discr={} pat={}", cmt_discr
.repr(self.tcx()),
1019 pat
.repr(self.tcx()));
1020 return_if_err
!(self.mc
.cat_pattern(cmt_discr
, pat
, |_mc
, cmt_pat
, pat
| {
1021 let tcx
= self.tcx();
1022 let def_map
= &self.tcx().def_map
;
1023 if pat_util
::pat_is_binding(def_map
, pat
) {
1025 ast
::PatIdent(ast
::BindByRef(_
), _
, _
) =>
1026 mode
.lub(BorrowingMatch
),
1027 ast
::PatIdent(ast
::BindByValue(_
), _
, _
) => {
1028 match copy_or_move(self.typer
, &cmt_pat
, PatBindingMove
) {
1029 Copy
=> mode
.lub(CopyingMatch
),
1030 Move(_
) => mode
.lub(MovingMatch
),
1036 "binding pattern not an identifier");
1043 /// The core driver for walking a pattern; `match_mode` must be
1044 /// established up front, e.g. via `determine_pat_move_mode` (see
1045 /// also `walk_irrefutable_pat` for patterns that stand alone).
1046 fn walk_pat(&mut self,
1047 cmt_discr
: mc
::cmt
<'tcx
>,
1049 match_mode
: MatchMode
) {
1050 debug
!("walk_pat cmt_discr={} pat={}", cmt_discr
.repr(self.tcx()),
1051 pat
.repr(self.tcx()));
1054 let typer
= self.typer
;
1055 let def_map
= &self.tcx().def_map
;
1056 let delegate
= &mut self.delegate
;
1057 return_if_err
!(mc
.cat_pattern(cmt_discr
.clone(), pat
, |mc
, cmt_pat
, pat
| {
1058 if pat_util
::pat_is_binding(def_map
, pat
) {
1059 let tcx
= typer
.tcx();
1061 debug
!("binding cmt_pat={} pat={} match_mode={:?}",
1066 // pat_ty: the type of the binding being produced.
1067 let pat_ty
= return_if_err
!(typer
.node_ty(pat
.id
));
1069 // Each match binding is effectively an assignment to the
1070 // binding being produced.
1071 let def
= def_map
.borrow().get(&pat
.id
).unwrap().full_def();
1072 match mc
.cat_def(pat
.id
, pat
.span
, pat_ty
, def
) {
1073 Ok(binding_cmt
) => {
1074 delegate
.mutate(pat
.id
, pat
.span
, binding_cmt
, Init
);
1079 // It is also a borrow or copy/move of the value being matched.
1081 ast
::PatIdent(ast
::BindByRef(m
), _
, _
) => {
1083 (ty
::ty_region(tcx
, pat
.span
, pat_ty
),
1084 ty
::BorrowKind
::from_mutbl(m
))
1086 delegate
.borrow(pat
.id
, pat
.span
, cmt_pat
,
1089 ast
::PatIdent(ast
::BindByValue(_
), _
, _
) => {
1090 let mode
= copy_or_move(typer
, &cmt_pat
, PatBindingMove
);
1091 debug
!("walk_pat binding consuming pat");
1092 delegate
.consume_pat(pat
, cmt_pat
, mode
);
1097 "binding pattern not an identifier");
1102 ast
::PatVec(_
, Some(ref slice_pat
), _
) => {
1103 // The `slice_pat` here creates a slice into
1104 // the original vector. This is effectively a
1105 // borrow of the elements of the vector being
1108 let (slice_cmt
, slice_mutbl
, slice_r
) =
1109 return_if_err
!(mc
.cat_slice_pattern(cmt_pat
, &**slice_pat
));
1111 // Note: We declare here that the borrow
1112 // occurs upon entering the `[...]`
1113 // pattern. This implies that something like
1114 // `[a; b]` where `a` is a move is illegal,
1115 // because the borrow is already in effect.
1116 // In fact such a move would be safe-ish, but
1117 // it effectively *requires* that we use the
1118 // nulling out semantics to indicate when a
1119 // value has been moved, which we are trying
1120 // to move away from. Otherwise, how can we
1121 // indicate that the first element in the
1122 // vector has been moved? Eventually, we
1123 // could perhaps modify this rule to permit
1124 // `[..a, b]` where `b` is a move, because in
1125 // that case we can adjust the length of the
1126 // original vec accordingly, but we'd have to
1127 // make trans do the right thing, and it would
1128 // only work for `~` vectors. It seems simpler
1129 // to just require that people call
1130 // `vec.pop()` or `vec.unshift()`.
1131 let slice_bk
= ty
::BorrowKind
::from_mutbl(slice_mutbl
);
1132 delegate
.borrow(pat
.id
, pat
.span
,
1134 slice_bk
, RefBinding
);
1141 // Do a second pass over the pattern, calling `matched_pat` on
1142 // the interior nodes (enum variants and structs), as opposed
1143 // to the above loop's visit of than the bindings that form
1144 // the leaves of the pattern tree structure.
1145 return_if_err
!(mc
.cat_pattern(cmt_discr
, pat
, |mc
, cmt_pat
, pat
| {
1146 let def_map
= def_map
.borrow();
1147 let tcx
= typer
.tcx();
1150 ast
::PatEnum(_
, _
) | ast
::PatIdent(_
, _
, None
) | ast
::PatStruct(..) => {
1151 match def_map
.get(&pat
.id
).map(|d
| d
.full_def()) {
1153 // no definition found: pat is not a
1154 // struct or enum pattern.
1157 Some(def
::DefVariant(enum_did
, variant_did
, _is_struct
)) => {
1159 if ty
::enum_is_univariant(tcx
, enum_did
) {
1162 let cmt_pat_ty
= cmt_pat
.ty
;
1163 mc
.cat_downcast(pat
, cmt_pat
, cmt_pat_ty
, variant_did
)
1166 debug
!("variant downcast_cmt={} pat={}",
1167 downcast_cmt
.repr(tcx
),
1170 delegate
.matched_pat(pat
, downcast_cmt
, match_mode
);
1173 Some(def
::DefStruct(..)) | Some(def
::DefTy(_
, false)) => {
1174 // A struct (in either the value or type
1175 // namespace; we encounter the former on
1176 // e.g. patterns for unit structs).
1178 debug
!("struct cmt_pat={} pat={}",
1182 delegate
.matched_pat(pat
, cmt_pat
, match_mode
);
1185 Some(def
::DefConst(..)) |
1186 Some(def
::DefLocal(..)) => {
1187 // This is a leaf (i.e. identifier binding
1188 // or constant value to match); thus no
1189 // `matched_pat` call.
1192 Some(def @ def
::DefTy(_
, true)) => {
1193 // An enum's type -- should never be in a
1196 if !tcx
.sess
.has_errors() {
1197 let msg
= format
!("Pattern has unexpected type: {:?} and type {}",
1199 cmt_pat
.ty
.repr(tcx
));
1200 tcx
.sess
.span_bug(pat
.span
, &msg
)
1205 // Remaining cases are e.g. DefFn, to
1206 // which identifiers within patterns
1207 // should not resolve. However, we do
1208 // encouter this when using the
1209 // expr-use-visitor during typeck. So just
1210 // ignore it, an error should have been
1213 if !tcx
.sess
.has_errors() {
1214 let msg
= format
!("Pattern has unexpected def: {:?} and type {}",
1216 cmt_pat
.ty
.repr(tcx
));
1217 tcx
.sess
.span_bug(pat
.span
, &msg
[..])
1223 ast
::PatIdent(_
, _
, Some(_
)) => {
1224 // Do nothing; this is a binding (not a enum
1225 // variant or struct), and the cat_pattern call
1226 // will visit the substructure recursively.
1229 ast
::PatWild(_
) | ast
::PatTup(..) | ast
::PatBox(..) |
1230 ast
::PatRegion(..) | ast
::PatLit(..) | ast
::PatRange(..) |
1231 ast
::PatVec(..) | ast
::PatMac(..) => {
1232 // Similarly, each of these cases does not
1233 // correspond to a enum variant or struct, so we
1234 // do not do any `matched_pat` calls for these
1241 fn walk_captures(&mut self, closure_expr
: &ast
::Expr
) {
1242 debug
!("walk_captures({})", closure_expr
.repr(self.tcx()));
1244 ty
::with_freevars(self.tcx(), closure_expr
.id
, |freevars
| {
1245 for freevar
in freevars
{
1246 let id_var
= freevar
.def
.def_id().node
;
1247 let upvar_id
= ty
::UpvarId
{ var_id
: id_var
,
1248 closure_expr_id
: closure_expr
.id
};
1249 let upvar_capture
= self.typer
.upvar_capture(upvar_id
).unwrap();
1250 let cmt_var
= return_if_err
!(self.cat_captured_var(closure_expr
.id
,
1253 match upvar_capture
{
1254 ty
::UpvarCapture
::ByValue
=> {
1255 let mode
= copy_or_move(self.typer
, &cmt_var
, CaptureMove
);
1256 self.delegate
.consume(closure_expr
.id
, freevar
.span
, cmt_var
, mode
);
1258 ty
::UpvarCapture
::ByRef(upvar_borrow
) => {
1259 self.delegate
.borrow(closure_expr
.id
,
1262 upvar_borrow
.region
,
1264 ClosureCapture(freevar
.span
));
1271 fn cat_captured_var(&mut self,
1272 closure_id
: ast
::NodeId
,
1274 upvar_def
: def
::Def
)
1275 -> mc
::McResult
<mc
::cmt
<'tcx
>> {
1276 // Create the cmt for the variable being borrowed, from the
1277 // caller's perspective
1278 let var_id
= upvar_def
.def_id().node
;
1279 let var_ty
= try
!(self.typer
.node_ty(var_id
));
1280 self.mc
.cat_def(closure_id
, closure_span
, var_ty
, upvar_def
)
1284 fn copy_or_move
<'tcx
>(typer
: &mc
::Typer
<'tcx
>,
1285 cmt
: &mc
::cmt
<'tcx
>,
1286 move_reason
: MoveReason
)
1289 if typer
.type_moves_by_default(cmt
.span
, cmt
.ty
) {