]> git.proxmox.com Git - rustc.git/blob - src/librustc/middle/expr_use_visitor.rs
Imported Upstream version 1.0.0~beta.3
[rustc.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::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::*;
22
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;
31
32 use syntax::{ast, ast_util};
33 use syntax::ptr::P;
34 use syntax::codemap::Span;
35
36 ///////////////////////////////////////////////////////////////////////////
37 // The Delegate trait
38
39 /// This trait defines the callbacks you can expect to receive when
40 /// employing the ExprUseVisitor.
41 pub trait Delegate<'tcx> {
42 // The value found at `cmt` is either copied or moved, depending
43 // on mode.
44 fn consume(&mut self,
45 consume_id: ast::NodeId,
46 consume_span: Span,
47 cmt: mc::cmt<'tcx>,
48 mode: ConsumeMode);
49
50 // The value found at `cmt` has been determined to match the
51 // pattern binding `matched_pat`, and its subparts are being
52 // copied or moved depending on `mode`. Note that `matched_pat`
53 // is called on all variant/structs in the pattern (i.e., the
54 // interior nodes of the pattern's tree structure) while
55 // consume_pat is called on the binding identifiers in the pattern
56 // (which are leaves of the pattern's tree structure).
57 //
58 // Note that variants/structs and identifiers are disjoint; thus
59 // `matched_pat` and `consume_pat` are never both called on the
60 // same input pattern structure (though of `consume_pat` can be
61 // called on a subpart of an input passed to `matched_pat).
62 fn matched_pat(&mut self,
63 matched_pat: &ast::Pat,
64 cmt: mc::cmt<'tcx>,
65 mode: MatchMode);
66
67 // The value found at `cmt` is either copied or moved via the
68 // pattern binding `consume_pat`, depending on mode.
69 fn consume_pat(&mut self,
70 consume_pat: &ast::Pat,
71 cmt: mc::cmt<'tcx>,
72 mode: ConsumeMode);
73
74 // The value found at `borrow` is being borrowed at the point
75 // `borrow_id` for the region `loan_region` with kind `bk`.
76 fn borrow(&mut self,
77 borrow_id: ast::NodeId,
78 borrow_span: Span,
79 cmt: mc::cmt<'tcx>,
80 loan_region: ty::Region,
81 bk: ty::BorrowKind,
82 loan_cause: LoanCause);
83
84 // The local variable `id` is declared but not initialized.
85 fn decl_without_init(&mut self,
86 id: ast::NodeId,
87 span: Span);
88
89 // The path at `cmt` is being assigned to.
90 fn mutate(&mut self,
91 assignment_id: ast::NodeId,
92 assignment_span: Span,
93 assignee_cmt: mc::cmt<'tcx>,
94 mode: MutateMode);
95 }
96
97 #[derive(Copy, Clone, PartialEq, Debug)]
98 pub enum LoanCause {
99 ClosureCapture(Span),
100 AddrOf,
101 AutoRef,
102 AutoUnsafe,
103 RefBinding,
104 OverloadedOperator,
105 ClosureInvocation,
106 ForLoop,
107 MatchDiscriminant
108 }
109
110 #[derive(Copy, Clone, PartialEq, Debug)]
111 pub enum ConsumeMode {
112 Copy, // reference to x where x has a type that copies
113 Move(MoveReason), // reference to x where x has a type that moves
114 }
115
116 #[derive(Copy, Clone, PartialEq, Debug)]
117 pub enum MoveReason {
118 DirectRefMove,
119 PatBindingMove,
120 CaptureMove,
121 }
122
123 #[derive(Copy, Clone, PartialEq, Debug)]
124 pub enum MatchMode {
125 NonBindingMatch,
126 BorrowingMatch,
127 CopyingMatch,
128 MovingMatch,
129 }
130
131 #[derive(Copy, Clone, PartialEq, Debug)]
132 enum TrackMatchMode {
133 Unknown,
134 Definite(MatchMode),
135 Conflicting,
136 }
137
138 impl TrackMatchMode {
139 // Builds up the whole match mode for a pattern from its constituent
140 // parts. The lattice looks like this:
141 //
142 // Conflicting
143 // / \
144 // / \
145 // Borrowing Moving
146 // \ /
147 // \ /
148 // Copying
149 // |
150 // NonBinding
151 // |
152 // Unknown
153 //
154 // examples:
155 //
156 // * `(_, some_int)` pattern is Copying, since
157 // NonBinding + Copying => Copying
158 //
159 // * `(some_int, some_box)` pattern is Moving, since
160 // Copying + Moving => Moving
161 //
162 // * `(ref x, some_box)` pattern is Conflicting, since
163 // Borrowing + Moving => Conflicting
164 //
165 // Note that the `Unknown` and `Conflicting` states are
166 // represented separately from the other more interesting
167 // `Definite` states, which simplifies logic here somewhat.
168 fn lub(&mut self, mode: MatchMode) {
169 *self = match (*self, mode) {
170 // Note that clause order below is very significant.
171 (Unknown, new) => Definite(new),
172 (Definite(old), new) if old == new => Definite(old),
173
174 (Definite(old), NonBindingMatch) => Definite(old),
175 (Definite(NonBindingMatch), new) => Definite(new),
176
177 (Definite(old), CopyingMatch) => Definite(old),
178 (Definite(CopyingMatch), new) => Definite(new),
179
180 (Definite(_), _) => Conflicting,
181 (Conflicting, _) => *self,
182 };
183 }
184
185 fn match_mode(&self) -> MatchMode {
186 match *self {
187 Unknown => NonBindingMatch,
188 Definite(mode) => mode,
189 Conflicting => {
190 // Conservatively return MovingMatch to let the
191 // compiler continue to make progress.
192 MovingMatch
193 }
194 }
195 }
196 }
197
198 #[derive(Copy, Clone, PartialEq, Debug)]
199 pub enum MutateMode {
200 Init,
201 JustWrite, // x = y
202 WriteAndRead, // x += y
203 }
204
205 #[derive(Copy, Clone)]
206 enum OverloadedCallType {
207 FnOverloadedCall,
208 FnMutOverloadedCall,
209 FnOnceOverloadedCall,
210 }
211
212 impl OverloadedCallType {
213 fn from_trait_id(tcx: &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)
219 ].iter() {
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 tcx.sess.bug("overloaded call didn't map to known function trait")
229 }
230
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()
236 }
237 ty::TypeTraitItem(_) => {
238 tcx.sess.bug("overloaded call method wasn't in method map")
239 }
240 };
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?!")
245 }
246 ty::ImplContainer(impl_id) => impl_id,
247 };
248 let trait_ref = match ty::impl_trait_ref(tcx, impl_id) {
249 None => {
250 tcx.sess.bug("statically resolved overloaded call impl \
251 didn't implement a trait?!")
252 }
253 Some(ref trait_ref) => (*trait_ref).clone(),
254 };
255 OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
256 }
257
258 fn from_closure(tcx: &ty::ctxt, closure_did: ast::DefId)
259 -> OverloadedCallType {
260 let trait_did =
261 tcx.closure_kinds
262 .borrow()
263 .get(&closure_did)
264 .expect("OverloadedCallType::from_closure: didn't find closure id")
265 .trait_did(tcx);
266 OverloadedCallType::from_trait_id(tcx, trait_did)
267 }
268
269 fn from_method_origin(tcx: &ty::ctxt, origin: &MethodOrigin)
270 -> OverloadedCallType {
271 match *origin {
272 MethodStatic(def_id) => {
273 OverloadedCallType::from_method_id(tcx, def_id)
274 }
275 MethodStaticClosure(def_id) => {
276 OverloadedCallType::from_closure(tcx, def_id)
277 }
278 MethodTypeParam(MethodParam { ref trait_ref, .. }) |
279 MethodTraitObject(MethodObject { ref trait_ref, .. }) => {
280 OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
281 }
282 }
283 }
284 }
285
286 ///////////////////////////////////////////////////////////////////////////
287 // The ExprUseVisitor type
288 //
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.
293
294 pub struct ExprUseVisitor<'d,'t,'tcx:'t,TYPER:'t> {
295 typer: &'t TYPER,
296 mc: mc::MemCategorizationContext<'t,TYPER>,
297 delegate: &'d mut (Delegate<'tcx>+'d),
298 }
299
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
303 // code.
304 //
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 {
308 ($inp: expr) => (
309 match $inp {
310 Ok(v) => v,
311 Err(()) => return
312 }
313 )
314 }
315
316 /// Whether the elements of an overloaded operation are passed by value or by reference
317 enum PassArgs {
318 ByValue,
319 ByRef,
320 }
321
322 impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> {
323 pub fn new(delegate: &'d mut Delegate<'tcx>,
324 typer: &'t TYPER)
325 -> ExprUseVisitor<'d,'t,'tcx,TYPER> {
326 ExprUseVisitor {
327 typer: typer,
328 mc: mc::MemCategorizationContext::new(typer),
329 delegate: delegate,
330 }
331 }
332
333 pub fn walk_fn(&mut self,
334 decl: &ast::FnDecl,
335 body: &ast::Block) {
336 self.walk_arg_patterns(decl, body);
337 self.walk_block(body);
338 }
339
340 fn walk_arg_patterns(&mut self,
341 decl: &ast::FnDecl,
342 body: &ast::Block) {
343 for arg in &decl.inputs {
344 let arg_ty = return_if_err!(self.typer.node_ty(arg.pat.id));
345
346 let fn_body_scope = region::CodeExtent::from_node_id(body.id);
347 let arg_cmt = self.mc.cat_rvalue(
348 arg.id,
349 arg.pat.span,
350 ty::ReScope(fn_body_scope), // Args live only as long as the fn body.
351 arg_ty);
352
353 self.walk_irrefutable_pat(arg_cmt, &*arg.pat);
354 }
355 }
356
357 fn tcx(&self) -> &'t ty::ctxt<'tcx> {
358 self.typer.tcx()
359 }
360
361 fn delegate_consume(&mut self,
362 consume_id: ast::NodeId,
363 consume_span: Span,
364 cmt: mc::cmt<'tcx>) {
365 debug!("delegate_consume(consume_id={}, cmt={})",
366 consume_id, cmt.repr(self.tcx()));
367
368 let mode = copy_or_move(self.typer, &cmt, DirectRefMove);
369 self.delegate.consume(consume_id, consume_span, cmt, mode);
370 }
371
372 fn consume_exprs(&mut self, exprs: &Vec<P<ast::Expr>>) {
373 for expr in exprs {
374 self.consume_expr(&**expr);
375 }
376 }
377
378 pub fn consume_expr(&mut self, expr: &ast::Expr) {
379 debug!("consume_expr(expr={})", expr.repr(self.tcx()));
380
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);
384 }
385
386 fn mutate_expr(&mut self,
387 assignment_expr: &ast::Expr,
388 expr: &ast::Expr,
389 mode: MutateMode) {
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);
393 }
394
395 fn borrow_expr(&mut self,
396 expr: &ast::Expr,
397 r: ty::Region,
398 bk: ty::BorrowKind,
399 cause: LoanCause) {
400 debug!("borrow_expr(expr={}, r={}, bk={})",
401 expr.repr(self.tcx()), r.repr(self.tcx()), bk.repr(self.tcx()));
402
403 let cmt = return_if_err!(self.mc.cat_expr(expr));
404 self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
405
406 // Note: Unlike consume, we can ignore ExprParen. cat_expr
407 // already skips over them, and walk will uncover any
408 // attachments or whatever.
409 self.walk_expr(expr)
410 }
411
412 fn select_from_expr(&mut self, expr: &ast::Expr) {
413 self.walk_expr(expr)
414 }
415
416 pub fn walk_expr(&mut self, expr: &ast::Expr) {
417 debug!("walk_expr(expr={})", expr.repr(self.tcx()));
418
419 self.walk_adjustment(expr);
420
421 match expr.node {
422 ast::ExprParen(ref subexpr) => {
423 self.walk_expr(&**subexpr)
424 }
425
426 ast::ExprPath(..) => { }
427
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);
431 }
432 }
433
434 ast::ExprField(ref base, _) => { // base.f
435 self.select_from_expr(&**base);
436 }
437
438 ast::ExprTupField(ref base, _) => { // base.<n>
439 self.select_from_expr(&**base);
440 }
441
442 ast::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs]
443 if !self.walk_overloaded_operator(expr,
444 &**lhs,
445 vec![&**rhs],
446 PassArgs::ByValue) {
447 self.select_from_expr(&**lhs);
448 self.consume_expr(&**rhs);
449 }
450 }
451
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));
455 }
456
457 ast::ExprCall(ref callee, ref args) => { // callee(args)
458 self.walk_callee(expr, &**callee);
459 self.consume_exprs(args);
460 }
461
462 ast::ExprMethodCall(_, _, ref args) => { // callee.m(args)
463 self.consume_exprs(args);
464 }
465
466 ast::ExprStruct(_, ref fields, ref opt_with) => {
467 self.walk_struct_expr(expr, fields, opt_with);
468 }
469
470 ast::ExprTup(ref exprs) => {
471 self.consume_exprs(exprs);
472 }
473
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);
479 }
480 }
481
482 ast::ExprIfLet(..) => {
483 self.tcx().sess.span_bug(expr.span, "non-desugared ExprIfLet");
484 }
485
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);
489
490 // treatment of the discriminant is handled while walking the arms.
491 for arm in 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);
495 }
496 }
497
498 ast::ExprVec(ref exprs) => {
499 self.consume_exprs(exprs);
500 }
501
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);
509 }
510
511 ast::ExprInlineAsm(ref ia) => {
512 for &(_, ref input) in &ia.inputs {
513 self.consume_expr(&**input);
514 }
515
516 for &(_, ref output, is_rw) in &ia.outputs {
517 self.mutate_expr(expr, &**output,
518 if is_rw { WriteAndRead } else { JustWrite });
519 }
520 }
521
522 ast::ExprBreak(..) |
523 ast::ExprAgain(..) |
524 ast::ExprLit(..) => {}
525
526 ast::ExprLoop(ref blk, _) => {
527 self.walk_block(&**blk);
528 }
529
530 ast::ExprWhile(ref cond_expr, ref blk, _) => {
531 self.consume_expr(&**cond_expr);
532 self.walk_block(&**blk);
533 }
534
535 ast::ExprWhileLet(..) => {
536 self.tcx().sess.span_bug(expr.span, "non-desugared ExprWhileLet");
537 }
538
539 ast::ExprForLoop(..) => {
540 self.tcx().sess.span_bug(expr.span, "non-desugared ExprForLoop");
541 }
542
543 ast::ExprUnary(op, ref lhs) => {
544 let pass_args = if ast_util::is_by_value_unop(op) {
545 PassArgs::ByValue
546 } else {
547 PassArgs::ByRef
548 };
549
550 if !self.walk_overloaded_operator(expr, &**lhs, Vec::new(), pass_args) {
551 self.consume_expr(&**lhs);
552 }
553 }
554
555 ast::ExprBinary(op, ref lhs, ref rhs) => {
556 let pass_args = if ast_util::is_by_value_binop(op.node) {
557 PassArgs::ByValue
558 } else {
559 PassArgs::ByRef
560 };
561
562 if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs], pass_args) {
563 self.consume_expr(&**lhs);
564 self.consume_expr(&**rhs);
565 }
566 }
567
568 ast::ExprBlock(ref blk) => {
569 self.walk_block(&**blk);
570 }
571
572 ast::ExprRet(ref opt_expr) => {
573 if let Some(ref expr) = *opt_expr {
574 self.consume_expr(&**expr);
575 }
576 }
577
578 ast::ExprAssign(ref lhs, ref rhs) => {
579 self.mutate_expr(expr, &**lhs, JustWrite);
580 self.consume_expr(&**rhs);
581 }
582
583 ast::ExprCast(ref base, _) => {
584 self.consume_expr(&**base);
585 }
586
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);
592 }
593
594 ast::ExprRepeat(ref base, ref count) => {
595 self.consume_expr(&**base);
596 self.consume_expr(&**count);
597 }
598
599 ast::ExprClosure(..) => {
600 self.walk_captures(expr)
601 }
602
603 ast::ExprBox(ref place, ref base) => {
604 match *place {
605 Some(ref place) => self.consume_expr(&**place),
606 None => {}
607 }
608 self.consume_expr(&**base);
609 }
610
611 ast::ExprMac(..) => {
612 self.tcx().sess.span_bug(
613 expr.span,
614 "macro expression remains after expansion");
615 }
616 }
617 }
618
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);
627 }
628 ty::ty_err => { }
629 _ => {
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(
634 self.tcx(),
635 &method_origin)
636 }
637 None => {
638 self.tcx().sess.span_bug(
639 callee.span,
640 &format!("unexpected callee type {}", callee_ty.repr(self.tcx())))
641 }
642 };
643 match overloaded_call_type {
644 FnMutOverloadedCall => {
645 self.borrow_expr(callee,
646 ty::ReScope(call_scope),
647 ty::MutBorrow,
648 ClosureInvocation);
649 }
650 FnOverloadedCall => {
651 self.borrow_expr(callee,
652 ty::ReScope(call_scope),
653 ty::ImmBorrow,
654 ClosureInvocation);
655 }
656 FnOnceOverloadedCall => self.consume_expr(callee),
657 }
658 }
659 }
660 }
661
662 fn walk_stmt(&mut self, stmt: &ast::Stmt) {
663 match stmt.node {
664 ast::StmtDecl(ref decl, _) => {
665 match decl.node {
666 ast::DeclLocal(ref local) => {
667 self.walk_local(&**local);
668 }
669
670 ast::DeclItem(_) => {
671 // we don't visit nested items in this visitor,
672 // only the fn body we were given.
673 }
674 }
675 }
676
677 ast::StmtExpr(ref expr, _) |
678 ast::StmtSemi(ref expr, _) => {
679 self.consume_expr(&**expr);
680 }
681
682 ast::StmtMac(..) => {
683 self.tcx().sess.span_bug(stmt.span, "unexpanded stmt macro");
684 }
685 }
686 }
687
688 fn walk_local(&mut self, local: &ast::Local) {
689 match local.init {
690 None => {
691 let delegate = &mut self.delegate;
692 pat_util::pat_bindings(&self.typer.tcx().def_map, &*local.pat,
693 |_, id, span, _| {
694 delegate.decl_without_init(id, span);
695 })
696 }
697
698 Some(ref expr) => {
699 // Variable declarations with
700 // initializers are considered
701 // "assigns", which is handled by
702 // `walk_pat`:
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);
706 }
707 }
708 }
709
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);
714
715 for stmt in &blk.stmts {
716 self.walk_stmt(&**stmt);
717 }
718
719 if let Some(ref tail_expr) = blk.expr {
720 self.consume_expr(&**tail_expr);
721 }
722 }
723
724 fn walk_struct_expr(&mut self,
725 _expr: &ast::Expr,
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);
731 }
732
733 let with_expr = match *opt_with {
734 Some(ref w) => &**w,
735 None => { return; }
736 };
737
738 let with_cmt = return_if_err!(self.mc.cat_expr(&*with_expr));
739
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)
745 }
746 _ => {
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(
753 with_expr.span,
754 "with expression doesn't evaluate to a struct");
755 }
756 assert!(self.tcx().sess.has_errors());
757 vec!()
758 }
759 };
760
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,
765 with_cmt.clone(),
766 with_field.name,
767 with_field.mt.ty);
768 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
769 }
770 }
771
772 // walk the with expression so that complex expressions
773 // are properly handled.
774 self.walk_expr(with_expr);
775
776 fn contains_field_named(field: &ty::field,
777 fields: &Vec<ast::Field>)
778 -> bool
779 {
780 fields.iter().any(
781 |f| f.ident.node.name == field.name)
782 }
783 }
784
785 // Invoke the appropriate delegate calls for anything that gets
786 // consumed or borrowed as part of the automatic adjustment
787 // process.
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) {
791 match *adjustment {
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)");
797 let cmt_unadjusted =
798 return_if_err!(self.mc.cat_expr_unadjusted(expr));
799 self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
800 }
801 ty::AdjustDerefRef(ref adj) => {
802 self.walk_autoderefref(expr, adj);
803 }
804 }
805 }
806 }
807
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,
812 expr: &ast::Expr,
813 autoderefs: usize) {
814 debug!("walk_autoderefs expr={} autoderefs={}", expr.repr(self.tcx()), autoderefs);
815
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) {
819 None => {}
820 Some(method_ty) => {
821 let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
822
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();
827
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())))
833 };
834 let bk = ty::BorrowKind::from_mutbl(m);
835 self.delegate.borrow(expr.id, expr.span, cmt,
836 *r, bk, AutoRef);
837 }
838 }
839 }
840 }
841
842 fn walk_autoderefref(&mut self,
843 expr: &ast::Expr,
844 adj: &ty::AutoDerefRef<'tcx>) {
845 debug!("walk_autoderefref expr={} adj={}",
846 expr.repr(self.tcx()),
847 adj.repr(self.tcx()));
848
849 self.walk_autoderefs(expr, adj.autoderefs);
850
851 let cmt_derefd =
852 return_if_err!(self.mc.cat_expr_autoderefd(expr, adj.autoderefs));
853
854 let cmt_refd =
855 self.walk_autoref(expr, cmt_derefd, adj.autoref);
856
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);
860 }
861 }
862
863
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
871 /// autoref.
872 fn walk_autoref(&mut self,
873 expr: &ast::Expr,
874 cmt_base: mc::cmt<'tcx>,
875 opt_autoref: Option<ty::AutoRef<'tcx>>)
876 -> mc::cmt<'tcx>
877 {
878 debug!("walk_autoref(expr.id={} cmt_derefd={} opt_autoref={:?})",
879 expr.id,
880 cmt_base.repr(self.tcx()),
881 opt_autoref);
882
883 let cmt_base_ty = cmt_base.ty;
884
885 let autoref = match opt_autoref {
886 Some(ref autoref) => autoref,
887 None => {
888 // No AutoRef.
889 return cmt_base;
890 }
891 };
892
893 debug!("walk_autoref: expr.id={} cmt_base={}",
894 expr.id,
895 cmt_base.repr(self.tcx()));
896
897 match *autoref {
898 ty::AutoPtr(r, m) => {
899 self.delegate.borrow(expr.id,
900 expr.span,
901 cmt_base,
902 *r,
903 ty::BorrowKind::from_mutbl(m),
904 AutoRef);
905 }
906
907 ty::AutoUnsafe(m) => {
908 debug!("walk_autoref: expr.id={} cmt_base={}",
909 expr.id,
910 cmt_base.repr(self.tcx()));
911
912 // Converting from a &T to *T (or &mut T to *mut T) is
913 // treated as borrowing it for the enclosing temporary
914 // scope.
915 let r = ty::ReScope(region::CodeExtent::from_node_id(expr.id));
916
917 self.delegate.borrow(expr.id,
918 expr.span,
919 cmt_base,
920 r,
921 ty::BorrowKind::from_mutbl(m),
922 AutoUnsafe);
923 }
924 }
925
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.
929
930 let adj_ty =
931 ty::adjust_ty_for_autoref(self.tcx(),
932 cmt_base_ty,
933 opt_autoref);
934
935 self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
936 }
937
938
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
943 // should not do so.
944 fn walk_overloaded_operator(&mut self,
945 expr: &ast::Expr,
946 receiver: &ast::Expr,
947 rhs: Vec<&ast::Expr>,
948 pass_args: PassArgs)
949 -> bool
950 {
951 if !self.typer.is_method_call(expr.id) {
952 return false;
953 }
954
955 match pass_args {
956 PassArgs::ByValue => {
957 self.consume_expr(receiver);
958 for &arg in &rhs {
959 self.consume_expr(arg);
960 }
961
962 return true;
963 },
964 PassArgs::ByRef => {},
965 }
966
967 self.walk_expr(receiver);
968
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.
972
973 let r = ty::ReScope(region::CodeExtent::from_node_id(expr.id));
974 let bk = ty::ImmBorrow;
975
976 for &arg in &rhs {
977 self.borrow_expr(arg, r, bk, OverloadedOperator);
978 }
979 return true;
980 }
981
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);
986 }
987 mode
988 }
989
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);
993 }
994
995 if let Some(ref guard) = arm.guard {
996 self.consume_expr(&**guard);
997 }
998
999 self.consume_expr(&*arm.body);
1000 }
1001
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);
1009 }
1010
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>,
1016 pat: &ast::Pat,
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) {
1024 match pat.node {
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),
1031 }
1032 }
1033 _ => {
1034 tcx.sess.span_bug(
1035 pat.span,
1036 "binding pattern not an identifier");
1037 }
1038 }
1039 }
1040 }));
1041 }
1042
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>,
1048 pat: &ast::Pat,
1049 match_mode: MatchMode) {
1050 debug!("walk_pat cmt_discr={} pat={}", cmt_discr.repr(self.tcx()),
1051 pat.repr(self.tcx()));
1052
1053 let mc = &self.mc;
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();
1060
1061 debug!("binding cmt_pat={} pat={} match_mode={:?}",
1062 cmt_pat.repr(tcx),
1063 pat.repr(tcx),
1064 match_mode);
1065
1066 // pat_ty: the type of the binding being produced.
1067 let pat_ty = return_if_err!(typer.node_ty(pat.id));
1068
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);
1075 }
1076 Err(_) => { }
1077 }
1078
1079 // It is also a borrow or copy/move of the value being matched.
1080 match pat.node {
1081 ast::PatIdent(ast::BindByRef(m), _, _) => {
1082 let (r, bk) = {
1083 (ty::ty_region(tcx, pat.span, pat_ty),
1084 ty::BorrowKind::from_mutbl(m))
1085 };
1086 delegate.borrow(pat.id, pat.span, cmt_pat,
1087 r, bk, RefBinding);
1088 }
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);
1093 }
1094 _ => {
1095 tcx.sess.span_bug(
1096 pat.span,
1097 "binding pattern not an identifier");
1098 }
1099 }
1100 } else {
1101 match pat.node {
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
1106 // matched.
1107
1108 let (slice_cmt, slice_mutbl, slice_r) =
1109 return_if_err!(mc.cat_slice_pattern(cmt_pat, &**slice_pat));
1110
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,
1133 slice_cmt, slice_r,
1134 slice_bk, RefBinding);
1135 }
1136 _ => { }
1137 }
1138 }
1139 }));
1140
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();
1148
1149 match pat.node {
1150 ast::PatEnum(_, _) | ast::PatIdent(_, _, None) | ast::PatStruct(..) => {
1151 match def_map.get(&pat.id).map(|d| d.full_def()) {
1152 None => {
1153 // no definition found: pat is not a
1154 // struct or enum pattern.
1155 }
1156
1157 Some(def::DefVariant(enum_did, variant_did, _is_struct)) => {
1158 let downcast_cmt =
1159 if ty::enum_is_univariant(tcx, enum_did) {
1160 cmt_pat
1161 } else {
1162 let cmt_pat_ty = cmt_pat.ty;
1163 mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
1164 };
1165
1166 debug!("variant downcast_cmt={} pat={}",
1167 downcast_cmt.repr(tcx),
1168 pat.repr(tcx));
1169
1170 delegate.matched_pat(pat, downcast_cmt, match_mode);
1171 }
1172
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).
1177
1178 debug!("struct cmt_pat={} pat={}",
1179 cmt_pat.repr(tcx),
1180 pat.repr(tcx));
1181
1182 delegate.matched_pat(pat, cmt_pat, match_mode);
1183 }
1184
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.
1190 }
1191
1192 Some(def @ def::DefTy(_, true)) => {
1193 // An enum's type -- should never be in a
1194 // pattern.
1195
1196 if !tcx.sess.has_errors() {
1197 let msg = format!("Pattern has unexpected type: {:?} and type {}",
1198 def,
1199 cmt_pat.ty.repr(tcx));
1200 tcx.sess.span_bug(pat.span, &msg)
1201 }
1202 }
1203
1204 Some(def) => {
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
1211 // reported.
1212
1213 if !tcx.sess.has_errors() {
1214 let msg = format!("Pattern has unexpected def: {:?} and type {}",
1215 def,
1216 cmt_pat.ty.repr(tcx));
1217 tcx.sess.span_bug(pat.span, &msg[..])
1218 }
1219 }
1220 }
1221 }
1222
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.
1227 }
1228
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
1235 // cases either.
1236 }
1237 }
1238 }));
1239 }
1240
1241 fn walk_captures(&mut self, closure_expr: &ast::Expr) {
1242 debug!("walk_captures({})", closure_expr.repr(self.tcx()));
1243
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,
1251 closure_expr.span,
1252 freevar.def));
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);
1257 }
1258 ty::UpvarCapture::ByRef(upvar_borrow) => {
1259 self.delegate.borrow(closure_expr.id,
1260 closure_expr.span,
1261 cmt_var,
1262 upvar_borrow.region,
1263 upvar_borrow.kind,
1264 ClosureCapture(freevar.span));
1265 }
1266 }
1267 }
1268 });
1269 }
1270
1271 fn cat_captured_var(&mut self,
1272 closure_id: ast::NodeId,
1273 closure_span: Span,
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)
1281 }
1282 }
1283
1284 fn copy_or_move<'tcx>(typer: &mc::Typer<'tcx>,
1285 cmt: &mc::cmt<'tcx>,
1286 move_reason: MoveReason)
1287 -> ConsumeMode
1288 {
1289 if typer.type_moves_by_default(cmt.span, cmt.ty) {
1290 Move(move_reason)
1291 } else {
1292 Copy
1293 }
1294 }