1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A different sort of visitor for walking fn bodies.  Unlike the
//! normal visitor, which just walks the entire body in one shot, the
//! `ExprUseVisitor` determines how expressions are being used.

pub use self::MutateMode::*;
pub use self::LoanCause::*;
pub use self::ConsumeMode::*;
pub use self::MoveReason::*;
pub use self::MatchMode::*;
use self::TrackMatchMode::*;
use self::OverloadedCallType::*;

use middle::{def, region, pat_util};
use middle::mem_categorization as mc;
use middle::mem_categorization::Typer;
use middle::ty::{self};
use middle::ty::{MethodCall, MethodObject, MethodTraitObject};
use middle::ty::{MethodOrigin, MethodParam, MethodTypeParam};
use middle::ty::{MethodStatic, MethodStaticClosure};
use util::ppaux::Repr;

use syntax::{ast, ast_util};
use syntax::ptr::P;
use syntax::codemap::Span;

///////////////////////////////////////////////////////////////////////////
// The Delegate trait

/// This trait defines the callbacks you can expect to receive when
/// employing the ExprUseVisitor.
pub trait Delegate<'tcx> {
    // The value found at `cmt` is either copied or moved, depending
    // on mode.
    fn consume(&mut self,
               consume_id: ast::NodeId,
               consume_span: Span,
               cmt: mc::cmt<'tcx>,
               mode: ConsumeMode);

    // The value found at `cmt` has been determined to match the
    // pattern binding `matched_pat`, and its subparts are being
    // copied or moved depending on `mode`.  Note that `matched_pat`
    // is called on all variant/structs in the pattern (i.e., the
    // interior nodes of the pattern's tree structure) while
    // consume_pat is called on the binding identifiers in the pattern
    // (which are leaves of the pattern's tree structure).
    //
    // Note that variants/structs and identifiers are disjoint; thus
    // `matched_pat` and `consume_pat` are never both called on the
    // same input pattern structure (though of `consume_pat` can be
    // called on a subpart of an input passed to `matched_pat).
    fn matched_pat(&mut self,
                   matched_pat: &ast::Pat,
                   cmt: mc::cmt<'tcx>,
                   mode: MatchMode);

    // The value found at `cmt` is either copied or moved via the
    // pattern binding `consume_pat`, depending on mode.
    fn consume_pat(&mut self,
                   consume_pat: &ast::Pat,
                   cmt: mc::cmt<'tcx>,
                   mode: ConsumeMode);

    // The value found at `borrow` is being borrowed at the point
    // `borrow_id` for the region `loan_region` with kind `bk`.
    fn borrow(&mut self,
              borrow_id: ast::NodeId,
              borrow_span: Span,
              cmt: mc::cmt<'tcx>,
              loan_region: ty::Region,
              bk: ty::BorrowKind,
              loan_cause: LoanCause);

    // The local variable `id` is declared but not initialized.
    fn decl_without_init(&mut self,
                         id: ast::NodeId,
                         span: Span);

    // The path at `cmt` is being assigned to.
    fn mutate(&mut self,
              assignment_id: ast::NodeId,
              assignment_span: Span,
              assignee_cmt: mc::cmt<'tcx>,
              mode: MutateMode);
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum LoanCause {
    ClosureCapture(Span),
    AddrOf,
    AutoRef,
    AutoUnsafe,
    RefBinding,
    OverloadedOperator,
    ClosureInvocation,
    ForLoop,
    MatchDiscriminant
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ConsumeMode {
    Copy,                // reference to x where x has a type that copies
    Move(MoveReason),    // reference to x where x has a type that moves
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MoveReason {
    DirectRefMove,
    PatBindingMove,
    CaptureMove,
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MatchMode {
    NonBindingMatch,
    BorrowingMatch,
    CopyingMatch,
    MovingMatch,
}

#[derive(Copy, Clone, PartialEq, Debug)]
enum TrackMatchMode {
    Unknown,
    Definite(MatchMode),
    Conflicting,
}

impl TrackMatchMode {
    // Builds up the whole match mode for a pattern from its constituent
    // parts.  The lattice looks like this:
    //
    //          Conflicting
    //            /     \
    //           /       \
    //      Borrowing   Moving
    //           \       /
    //            \     /
    //            Copying
    //               |
    //          NonBinding
    //               |
    //            Unknown
    //
    // examples:
    //
    // * `(_, some_int)` pattern is Copying, since
    //   NonBinding + Copying => Copying
    //
    // * `(some_int, some_box)` pattern is Moving, since
    //   Copying + Moving => Moving
    //
    // * `(ref x, some_box)` pattern is Conflicting, since
    //   Borrowing + Moving => Conflicting
    //
    // Note that the `Unknown` and `Conflicting` states are
    // represented separately from the other more interesting
    // `Definite` states, which simplifies logic here somewhat.
    fn lub(&mut self, mode: MatchMode) {
        *self = match (*self, mode) {
            // Note that clause order below is very significant.
            (Unknown, new) => Definite(new),
            (Definite(old), new) if old == new => Definite(old),

            (Definite(old), NonBindingMatch) => Definite(old),
            (Definite(NonBindingMatch), new) => Definite(new),

            (Definite(old), CopyingMatch) => Definite(old),
            (Definite(CopyingMatch), new) => Definite(new),

            (Definite(_), _) => Conflicting,
            (Conflicting, _) => *self,
        };
    }

    fn match_mode(&self) -> MatchMode {
        match *self {
            Unknown => NonBindingMatch,
            Definite(mode) => mode,
            Conflicting => {
                // Conservatively return MovingMatch to let the
                // compiler continue to make progress.
                MovingMatch
            }
        }
    }
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MutateMode {
    Init,
    JustWrite,    // x = y
    WriteAndRead, // x += y
}

#[derive(Copy, Clone)]
enum OverloadedCallType {
    FnOverloadedCall,
    FnMutOverloadedCall,
    FnOnceOverloadedCall,
}

impl OverloadedCallType {
    fn from_trait_id(tcx: &ty::ctxt, trait_id: ast::DefId)
                     -> OverloadedCallType {
        for &(maybe_function_trait, overloaded_call_type) in [
            (tcx.lang_items.fn_once_trait(), FnOnceOverloadedCall),
            (tcx.lang_items.fn_mut_trait(), FnMutOverloadedCall),
            (tcx.lang_items.fn_trait(), FnOverloadedCall)
        ].iter() {
            match maybe_function_trait {
                Some(function_trait) if function_trait == trait_id => {
                    return overloaded_call_type
                }
                _ => continue,
            }
        }

        tcx.sess.bug("overloaded call didn't map to known function trait")
    }

    fn from_method_id(tcx: &ty::ctxt, method_id: ast::DefId)
                      -> OverloadedCallType {
        let method_descriptor = match ty::impl_or_trait_item(tcx, method_id) {
            ty::MethodTraitItem(ref method_descriptor) => {
                (*method_descriptor).clone()
            }
            ty::TypeTraitItem(_) => {
                tcx.sess.bug("overloaded call method wasn't in method map")
            }
        };
        let impl_id = match method_descriptor.container {
            ty::TraitContainer(_) => {
                tcx.sess.bug("statically resolved overloaded call method \
                              belonged to a trait?!")
            }
            ty::ImplContainer(impl_id) => impl_id,
        };
        let trait_ref = match ty::impl_trait_ref(tcx, impl_id) {
            None => {
                tcx.sess.bug("statically resolved overloaded call impl \
                              didn't implement a trait?!")
            }
            Some(ref trait_ref) => (*trait_ref).clone(),
        };
        OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
    }

    fn from_closure(tcx: &ty::ctxt, closure_did: ast::DefId)
                    -> OverloadedCallType {
        let trait_did =
            tcx.closure_kinds
               .borrow()
               .get(&closure_did)
               .expect("OverloadedCallType::from_closure: didn't find closure id")
               .trait_did(tcx);
        OverloadedCallType::from_trait_id(tcx, trait_did)
    }

    fn from_method_origin(tcx: &ty::ctxt, origin: &MethodOrigin)
                          -> OverloadedCallType {
        match *origin {
            MethodStatic(def_id) => {
                OverloadedCallType::from_method_id(tcx, def_id)
            }
            MethodStaticClosure(def_id) => {
                OverloadedCallType::from_closure(tcx, def_id)
            }
            MethodTypeParam(MethodParam { ref trait_ref, .. }) |
            MethodTraitObject(MethodObject { ref trait_ref, .. }) => {
                OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////////
// The ExprUseVisitor type
//
// This is the code that actually walks the tree. Like
// mem_categorization, it requires a TYPER, which is a type that
// supplies types from the tree. After type checking is complete, you
// can just use the tcx as the typer.

pub struct ExprUseVisitor<'d,'t,'tcx:'t,TYPER:'t> {
    typer: &'t TYPER,
    mc: mc::MemCategorizationContext<'t,TYPER>,
    delegate: &'d mut (Delegate<'tcx>+'d),
}

// If the TYPER results in an error, it's because the type check
// failed (or will fail, when the error is uncovered and reported
// during writeback). In this case, we just ignore this part of the
// code.
//
// Note that this macro appears similar to try!(), but, unlike try!(),
// it does not propagate the error.
macro_rules! return_if_err {
    ($inp: expr) => (
        match $inp {
            Ok(v) => v,
            Err(()) => return
        }
    )
}

/// Whether the elements of an overloaded operation are passed by value or by reference
enum PassArgs {
    ByValue,
    ByRef,
}

impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> {
    pub fn new(delegate: &'d mut Delegate<'tcx>,
               typer: &'t TYPER)
               -> ExprUseVisitor<'d,'t,'tcx,TYPER> {
        ExprUseVisitor {
            typer: typer,
            mc: mc::MemCategorizationContext::new(typer),
            delegate: delegate,
        }
    }

    pub fn walk_fn(&mut self,
                   decl: &ast::FnDecl,
                   body: &ast::Block) {
        self.walk_arg_patterns(decl, body);
        self.walk_block(body);
    }

    fn walk_arg_patterns(&mut self,
                         decl: &ast::FnDecl,
                         body: &ast::Block) {
        for arg in &decl.inputs {
            let arg_ty = return_if_err!(self.typer.node_ty(arg.pat.id));

            let fn_body_scope = region::CodeExtent::from_node_id(body.id);
            let arg_cmt = self.mc.cat_rvalue(
                arg.id,
                arg.pat.span,
                ty::ReScope(fn_body_scope), // Args live only as long as the fn body.
                arg_ty);

            self.walk_irrefutable_pat(arg_cmt, &*arg.pat);
        }
    }

    fn tcx(&self) -> &'t ty::ctxt<'tcx> {
        self.typer.tcx()
    }

    fn delegate_consume(&mut self,
                        consume_id: ast::NodeId,
                        consume_span: Span,
                        cmt: mc::cmt<'tcx>) {
        debug!("delegate_consume(consume_id={}, cmt={})",
               consume_id, cmt.repr(self.tcx()));

        let mode = copy_or_move(self.typer, &cmt, DirectRefMove);
        self.delegate.consume(consume_id, consume_span, cmt, mode);
    }

    fn consume_exprs(&mut self, exprs: &Vec<P<ast::Expr>>) {
        for expr in exprs {
            self.consume_expr(&**expr);
        }
    }

    pub fn consume_expr(&mut self, expr: &ast::Expr) {
        debug!("consume_expr(expr={})", expr.repr(self.tcx()));

        let cmt = return_if_err!(self.mc.cat_expr(expr));
        self.delegate_consume(expr.id, expr.span, cmt);
        self.walk_expr(expr);
    }

    fn mutate_expr(&mut self,
                   assignment_expr: &ast::Expr,
                   expr: &ast::Expr,
                   mode: MutateMode) {
        let cmt = return_if_err!(self.mc.cat_expr(expr));
        self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
        self.walk_expr(expr);
    }

    fn borrow_expr(&mut self,
                   expr: &ast::Expr,
                   r: ty::Region,
                   bk: ty::BorrowKind,
                   cause: LoanCause) {
        debug!("borrow_expr(expr={}, r={}, bk={})",
               expr.repr(self.tcx()), r.repr(self.tcx()), bk.repr(self.tcx()));

        let cmt = return_if_err!(self.mc.cat_expr(expr));
        self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);

        // Note: Unlike consume, we can ignore ExprParen. cat_expr
        // already skips over them, and walk will uncover any
        // attachments or whatever.
        self.walk_expr(expr)
    }

    fn select_from_expr(&mut self, expr: &ast::Expr) {
        self.walk_expr(expr)
    }

    pub fn walk_expr(&mut self, expr: &ast::Expr) {
        debug!("walk_expr(expr={})", expr.repr(self.tcx()));

        self.walk_adjustment(expr);

        match expr.node {
            ast::ExprParen(ref subexpr) => {
                self.walk_expr(&**subexpr)
            }

            ast::ExprPath(..) => { }

            ast::ExprUnary(ast::UnDeref, ref base) => {      // *base
                if !self.walk_overloaded_operator(expr, &**base, Vec::new(), PassArgs::ByRef) {
                    self.select_from_expr(&**base);
                }
            }

            ast::ExprField(ref base, _) => {         // base.f
                self.select_from_expr(&**base);
            }

            ast::ExprTupField(ref base, _) => {         // base.<n>
                self.select_from_expr(&**base);
            }

            ast::ExprIndex(ref lhs, ref rhs) => {       // lhs[rhs]
                if !self.walk_overloaded_operator(expr,
                                                  &**lhs,
                                                  vec![&**rhs],
                                                  PassArgs::ByValue) {
                    self.select_from_expr(&**lhs);
                    self.consume_expr(&**rhs);
                }
            }

            ast::ExprRange(ref start, ref end) => {
                start.as_ref().map(|e| self.consume_expr(&**e));
                end.as_ref().map(|e| self.consume_expr(&**e));
            }

            ast::ExprCall(ref callee, ref args) => {    // callee(args)
                self.walk_callee(expr, &**callee);
                self.consume_exprs(args);
            }

            ast::ExprMethodCall(_, _, ref args) => { // callee.m(args)
                self.consume_exprs(args);
            }

            ast::ExprStruct(_, ref fields, ref opt_with) => {
                self.walk_struct_expr(expr, fields, opt_with);
            }

            ast::ExprTup(ref exprs) => {
                self.consume_exprs(exprs);
            }

            ast::ExprIf(ref cond_expr, ref then_blk, ref opt_else_expr) => {
                self.consume_expr(&**cond_expr);
                self.walk_block(&**then_blk);
                if let Some(ref else_expr) = *opt_else_expr {
                    self.consume_expr(&**else_expr);
                }
            }

            ast::ExprIfLet(..) => {
                self.tcx().sess.span_bug(expr.span, "non-desugared ExprIfLet");
            }

            ast::ExprMatch(ref discr, ref arms, _) => {
                let discr_cmt = return_if_err!(self.mc.cat_expr(&**discr));
                self.borrow_expr(&**discr, ty::ReEmpty, ty::ImmBorrow, MatchDiscriminant);

                // treatment of the discriminant is handled while walking the arms.
                for arm in arms {
                    let mode = self.arm_move_mode(discr_cmt.clone(), arm);
                    let mode = mode.match_mode();
                    self.walk_arm(discr_cmt.clone(), arm, mode);
                }
            }

            ast::ExprVec(ref exprs) => {
                self.consume_exprs(exprs);
            }

            ast::ExprAddrOf(m, ref base) => {   // &base
                // make sure that the thing we are pointing out stays valid
                // for the lifetime `scope_r` of the resulting ptr:
                let expr_ty = return_if_err!(self.typer.node_ty(expr.id));
                let r = ty::ty_region(self.tcx(), expr.span, expr_ty);
                let bk = ty::BorrowKind::from_mutbl(m);
                self.borrow_expr(&**base, r, bk, AddrOf);
            }

            ast::ExprInlineAsm(ref ia) => {
                for &(_, ref input) in &ia.inputs {
                    self.consume_expr(&**input);
                }

                for &(_, ref output, is_rw) in &ia.outputs {
                    self.mutate_expr(expr, &**output,
                                           if is_rw { WriteAndRead } else { JustWrite });
                }
            }

            ast::ExprBreak(..) |
            ast::ExprAgain(..) |
            ast::ExprLit(..) => {}

            ast::ExprLoop(ref blk, _) => {
                self.walk_block(&**blk);
            }

            ast::ExprWhile(ref cond_expr, ref blk, _) => {
                self.consume_expr(&**cond_expr);
                self.walk_block(&**blk);
            }

            ast::ExprWhileLet(..) => {
                self.tcx().sess.span_bug(expr.span, "non-desugared ExprWhileLet");
            }

            ast::ExprForLoop(..) => {
                self.tcx().sess.span_bug(expr.span, "non-desugared ExprForLoop");
            }

            ast::ExprUnary(op, ref lhs) => {
                let pass_args = if ast_util::is_by_value_unop(op) {
                    PassArgs::ByValue
                } else {
                    PassArgs::ByRef
                };

                if !self.walk_overloaded_operator(expr, &**lhs, Vec::new(), pass_args) {
                    self.consume_expr(&**lhs);
                }
            }

            ast::ExprBinary(op, ref lhs, ref rhs) => {
                let pass_args = if ast_util::is_by_value_binop(op.node) {
                    PassArgs::ByValue
                } else {
                    PassArgs::ByRef
                };

                if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs], pass_args) {
                    self.consume_expr(&**lhs);
                    self.consume_expr(&**rhs);
                }
            }

            ast::ExprBlock(ref blk) => {
                self.walk_block(&**blk);
            }

            ast::ExprRet(ref opt_expr) => {
                if let Some(ref expr) = *opt_expr {
                    self.consume_expr(&**expr);
                }
            }

            ast::ExprAssign(ref lhs, ref rhs) => {
                self.mutate_expr(expr, &**lhs, JustWrite);
                self.consume_expr(&**rhs);
            }

            ast::ExprCast(ref base, _) => {
                self.consume_expr(&**base);
            }

            ast::ExprAssignOp(_, ref lhs, ref rhs) => {
                // This will have to change if/when we support
                // overloaded operators for `+=` and so forth.
                self.mutate_expr(expr, &**lhs, WriteAndRead);
                self.consume_expr(&**rhs);
            }

            ast::ExprRepeat(ref base, ref count) => {
                self.consume_expr(&**base);
                self.consume_expr(&**count);
            }

            ast::ExprClosure(..) => {
                self.walk_captures(expr)
            }

            ast::ExprBox(ref place, ref base) => {
                match *place {
                    Some(ref place) => self.consume_expr(&**place),
                    None => {}
                }
                self.consume_expr(&**base);
            }

            ast::ExprMac(..) => {
                self.tcx().sess.span_bug(
                    expr.span,
                    "macro expression remains after expansion");
            }
        }
    }

    fn walk_callee(&mut self, call: &ast::Expr, callee: &ast::Expr) {
        let callee_ty = return_if_err!(self.typer.expr_ty_adjusted(callee));
        debug!("walk_callee: callee={} callee_ty={}",
               callee.repr(self.tcx()), callee_ty.repr(self.tcx()));
        let call_scope = region::CodeExtent::from_node_id(call.id);
        match callee_ty.sty {
            ty::ty_bare_fn(..) => {
                self.consume_expr(callee);
            }
            ty::ty_err => { }
            _ => {
                let overloaded_call_type =
                    match self.typer.node_method_origin(MethodCall::expr(call.id)) {
                        Some(method_origin) => {
                            OverloadedCallType::from_method_origin(
                                self.tcx(),
                                &method_origin)
                        }
                        None => {
                            self.tcx().sess.span_bug(
                                callee.span,
                                &format!("unexpected callee type {}", callee_ty.repr(self.tcx())))
                        }
                    };
                match overloaded_call_type {
                    FnMutOverloadedCall => {
                        self.borrow_expr(callee,
                                         ty::ReScope(call_scope),
                                         ty::MutBorrow,
                                         ClosureInvocation);
                    }
                    FnOverloadedCall => {
                        self.borrow_expr(callee,
                                         ty::ReScope(call_scope),
                                         ty::ImmBorrow,
                                         ClosureInvocation);
                    }
                    FnOnceOverloadedCall => self.consume_expr(callee),
                }
            }
        }
    }

    fn walk_stmt(&mut self, stmt: &ast::Stmt) {
        match stmt.node {
            ast::StmtDecl(ref decl, _) => {
                match decl.node {
                    ast::DeclLocal(ref local) => {
                        self.walk_local(&**local);
                    }

                    ast::DeclItem(_) => {
                        // we don't visit nested items in this visitor,
                        // only the fn body we were given.
                    }
                }
            }

            ast::StmtExpr(ref expr, _) |
            ast::StmtSemi(ref expr, _) => {
                self.consume_expr(&**expr);
            }

            ast::StmtMac(..) => {
                self.tcx().sess.span_bug(stmt.span, "unexpanded stmt macro");
            }
        }
    }

    fn walk_local(&mut self, local: &ast::Local) {
        match local.init {
            None => {
                let delegate = &mut self.delegate;
                pat_util::pat_bindings(&self.typer.tcx().def_map, &*local.pat,
                                       |_, id, span, _| {
                    delegate.decl_without_init(id, span);
                })
            }

            Some(ref expr) => {
                // Variable declarations with
                // initializers are considered
                // "assigns", which is handled by
                // `walk_pat`:
                self.walk_expr(&**expr);
                let init_cmt = return_if_err!(self.mc.cat_expr(&**expr));
                self.walk_irrefutable_pat(init_cmt, &*local.pat);
            }
        }
    }

    /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
    /// depending on its type.
    fn walk_block(&mut self, blk: &ast::Block) {
        debug!("walk_block(blk.id={})", blk.id);

        for stmt in &blk.stmts {
            self.walk_stmt(&**stmt);
        }

        if let Some(ref tail_expr) = blk.expr {
            self.consume_expr(&**tail_expr);
        }
    }

    fn walk_struct_expr(&mut self,
                        _expr: &ast::Expr,
                        fields: &Vec<ast::Field>,
                        opt_with: &Option<P<ast::Expr>>) {
        // Consume the expressions supplying values for each field.
        for field in fields {
            self.consume_expr(&*field.expr);
        }

        let with_expr = match *opt_with {
            Some(ref w) => &**w,
            None => { return; }
        };

        let with_cmt = return_if_err!(self.mc.cat_expr(&*with_expr));

        // Select just those fields of the `with`
        // expression that will actually be used
        let with_fields = match with_cmt.ty.sty {
            ty::ty_struct(did, substs) => {
                ty::struct_fields(self.tcx(), did, substs)
            }
            _ => {
                // the base expression should always evaluate to a
                // struct; however, when EUV is run during typeck, it
                // may not. This will generate an error earlier in typeck,
                // so we can just ignore it.
                if !self.tcx().sess.has_errors() {
                    self.tcx().sess.span_bug(
                        with_expr.span,
                        "with expression doesn't evaluate to a struct");
                }
                assert!(self.tcx().sess.has_errors());
                vec!()
            }
        };

        // Consume those fields of the with expression that are needed.
        for with_field in &with_fields {
            if !contains_field_named(with_field, fields) {
                let cmt_field = self.mc.cat_field(&*with_expr,
                                                  with_cmt.clone(),
                                                  with_field.name,
                                                  with_field.mt.ty);
                self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
            }
        }

        // walk the with expression so that complex expressions
        // are properly handled.
        self.walk_expr(with_expr);

        fn contains_field_named(field: &ty::field,
                                fields: &Vec<ast::Field>)
                                -> bool
        {
            fields.iter().any(
                |f| f.ident.node.name == field.name)
        }
    }

    // Invoke the appropriate delegate calls for anything that gets
    // consumed or borrowed as part of the automatic adjustment
    // process.
    fn walk_adjustment(&mut self, expr: &ast::Expr) {
        let typer = self.typer;
        if let Some(adjustment) = typer.adjustments().borrow().get(&expr.id) {
            match *adjustment {
                ty::AdjustReifyFnPointer |
                ty::AdjustUnsafeFnPointer => {
                    // Creating a closure/fn-pointer or unsizing consumes
                    // the input and stores it into the resulting rvalue.
                    debug!("walk_adjustment(AdjustReifyFnPointer|AdjustUnsafeFnPointer)");
                    let cmt_unadjusted =
                        return_if_err!(self.mc.cat_expr_unadjusted(expr));
                    self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
                }
                ty::AdjustDerefRef(ref adj) => {
                    self.walk_autoderefref(expr, adj);
                }
            }
        }
    }

    /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
    /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
    /// `deref()` is declared with `&self`, this is an autoref of `x`.
    fn walk_autoderefs(&mut self,
                       expr: &ast::Expr,
                       autoderefs: usize) {
        debug!("walk_autoderefs expr={} autoderefs={}", expr.repr(self.tcx()), autoderefs);

        for i in 0..autoderefs {
            let deref_id = ty::MethodCall::autoderef(expr.id, i as u32);
            match self.typer.node_method_ty(deref_id) {
                None => {}
                Some(method_ty) => {
                    let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));

                    // the method call infrastructure should have
                    // replaced all late-bound regions with variables:
                    let self_ty = ty::ty_fn_sig(method_ty).input(0);
                    let self_ty = ty::no_late_bound_regions(self.tcx(), &self_ty).unwrap();

                    let (m, r) = match self_ty.sty {
                        ty::ty_rptr(r, ref m) => (m.mutbl, r),
                        _ => self.tcx().sess.span_bug(expr.span,
                                &format!("bad overloaded deref type {}",
                                    method_ty.repr(self.tcx())))
                    };
                    let bk = ty::BorrowKind::from_mutbl(m);
                    self.delegate.borrow(expr.id, expr.span, cmt,
                                         *r, bk, AutoRef);
                }
            }
        }
    }

    fn walk_autoderefref(&mut self,
                         expr: &ast::Expr,
                         adj: &ty::AutoDerefRef<'tcx>) {
        debug!("walk_autoderefref expr={} adj={}",
               expr.repr(self.tcx()),
               adj.repr(self.tcx()));

        self.walk_autoderefs(expr, adj.autoderefs);

        let cmt_derefd =
            return_if_err!(self.mc.cat_expr_autoderefd(expr, adj.autoderefs));

        let cmt_refd =
            self.walk_autoref(expr, cmt_derefd, adj.autoref);

        if adj.unsize.is_some() {
            // Unsizing consumes the thin pointer and produces a fat one.
            self.delegate_consume(expr.id, expr.span, cmt_refd);
        }
    }


    /// Walks the autoref `opt_autoref` applied to the autoderef'd
    /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
    /// after all relevant autoderefs have occurred. Because AutoRefs
    /// can be recursive, this function is recursive: it first walks
    /// deeply all the way down the autoref chain, and then processes
    /// the autorefs on the way out. At each point, it returns the
    /// `cmt` for the rvalue that will be produced by introduced an
    /// autoref.
    fn walk_autoref(&mut self,
                    expr: &ast::Expr,
                    cmt_base: mc::cmt<'tcx>,
                    opt_autoref: Option<ty::AutoRef<'tcx>>)
                    -> mc::cmt<'tcx>
    {
        debug!("walk_autoref(expr.id={} cmt_derefd={} opt_autoref={:?})",
               expr.id,
               cmt_base.repr(self.tcx()),
               opt_autoref);

        let cmt_base_ty = cmt_base.ty;

        let autoref = match opt_autoref {
            Some(ref autoref) => autoref,
            None => {
                // No AutoRef.
                return cmt_base;
            }
        };

        debug!("walk_autoref: expr.id={} cmt_base={}",
               expr.id,
               cmt_base.repr(self.tcx()));

        match *autoref {
            ty::AutoPtr(r, m) => {
                self.delegate.borrow(expr.id,
                                     expr.span,
                                     cmt_base,
                                     *r,
                                     ty::BorrowKind::from_mutbl(m),
                                     AutoRef);
            }

            ty::AutoUnsafe(m) => {
                debug!("walk_autoref: expr.id={} cmt_base={}",
                       expr.id,
                       cmt_base.repr(self.tcx()));

                // Converting from a &T to *T (or &mut T to *mut T) is
                // treated as borrowing it for the enclosing temporary
                // scope.
                let r = ty::ReScope(region::CodeExtent::from_node_id(expr.id));

                self.delegate.borrow(expr.id,
                                     expr.span,
                                     cmt_base,
                                     r,
                                     ty::BorrowKind::from_mutbl(m),
                                     AutoUnsafe);
            }
        }

        // Construct the categorization for the result of the autoref.
        // This is always an rvalue, since we are producing a new
        // (temporary) indirection.

        let adj_ty =
            ty::adjust_ty_for_autoref(self.tcx(),
                                      cmt_base_ty,
                                      opt_autoref);

        self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
    }


    // When this returns true, it means that the expression *is* a
    // method-call (i.e. via the operator-overload).  This true result
    // also implies that walk_overloaded_operator already took care of
    // recursively processing the input arguments, and thus the caller
    // should not do so.
    fn walk_overloaded_operator(&mut self,
                                expr: &ast::Expr,
                                receiver: &ast::Expr,
                                rhs: Vec<&ast::Expr>,
                                pass_args: PassArgs)
                                -> bool
    {
        if !self.typer.is_method_call(expr.id) {
            return false;
        }

        match pass_args {
            PassArgs::ByValue => {
                self.consume_expr(receiver);
                for &arg in &rhs {
                    self.consume_expr(arg);
                }

                return true;
            },
            PassArgs::ByRef => {},
        }

        self.walk_expr(receiver);

        // Arguments (but not receivers) to overloaded operator
        // methods are implicitly autoref'd which sadly does not use
        // adjustments, so we must hardcode the borrow here.

        let r = ty::ReScope(region::CodeExtent::from_node_id(expr.id));
        let bk = ty::ImmBorrow;

        for &arg in &rhs {
            self.borrow_expr(arg, r, bk, OverloadedOperator);
        }
        return true;
    }

    fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &ast::Arm) -> TrackMatchMode {
        let mut mode = Unknown;
        for pat in &arm.pats {
            self.determine_pat_move_mode(discr_cmt.clone(), &**pat, &mut mode);
        }
        mode
    }

    fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &ast::Arm, mode: MatchMode) {
        for pat in &arm.pats {
            self.walk_pat(discr_cmt.clone(), &**pat, mode);
        }

        if let Some(ref guard) = arm.guard {
            self.consume_expr(&**guard);
        }

        self.consume_expr(&*arm.body);
    }

    /// Walks an pat that occurs in isolation (i.e. top-level of fn
    /// arg or let binding.  *Not* a match arm or nested pat.)
    fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &ast::Pat) {
        let mut mode = Unknown;
        self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
        let mode = mode.match_mode();
        self.walk_pat(cmt_discr, pat, mode);
    }

    /// Identifies any bindings within `pat` and accumulates within
    /// `mode` whether the overall pattern/match structure is a move,
    /// copy, or borrow.
    fn determine_pat_move_mode(&mut self,
                               cmt_discr: mc::cmt<'tcx>,
                               pat: &ast::Pat,
                               mode: &mut TrackMatchMode) {
        debug!("determine_pat_move_mode cmt_discr={} pat={}", cmt_discr.repr(self.tcx()),
               pat.repr(self.tcx()));
        return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
            let tcx = self.tcx();
            let def_map = &self.tcx().def_map;
            if pat_util::pat_is_binding(def_map, pat) {
                match pat.node {
                    ast::PatIdent(ast::BindByRef(_), _, _) =>
                        mode.lub(BorrowingMatch),
                    ast::PatIdent(ast::BindByValue(_), _, _) => {
                        match copy_or_move(self.typer, &cmt_pat, PatBindingMove) {
                            Copy => mode.lub(CopyingMatch),
                            Move(_) => mode.lub(MovingMatch),
                        }
                    }
                    _ => {
                        tcx.sess.span_bug(
                            pat.span,
                            "binding pattern not an identifier");
                    }
                }
            }
        }));
    }

    /// The core driver for walking a pattern; `match_mode` must be
    /// established up front, e.g. via `determine_pat_move_mode` (see
    /// also `walk_irrefutable_pat` for patterns that stand alone).
    fn walk_pat(&mut self,
                cmt_discr: mc::cmt<'tcx>,
                pat: &ast::Pat,
                match_mode: MatchMode) {
        debug!("walk_pat cmt_discr={} pat={}", cmt_discr.repr(self.tcx()),
               pat.repr(self.tcx()));

        let mc = &self.mc;
        let typer = self.typer;
        let def_map = &self.tcx().def_map;
        let delegate = &mut self.delegate;
        return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
            if pat_util::pat_is_binding(def_map, pat) {
                let tcx = typer.tcx();

                debug!("binding cmt_pat={} pat={} match_mode={:?}",
                       cmt_pat.repr(tcx),
                       pat.repr(tcx),
                       match_mode);

                // pat_ty: the type of the binding being produced.
                let pat_ty = return_if_err!(typer.node_ty(pat.id));

                // Each match binding is effectively an assignment to the
                // binding being produced.
                let def = def_map.borrow().get(&pat.id).unwrap().full_def();
                match mc.cat_def(pat.id, pat.span, pat_ty, def) {
                    Ok(binding_cmt) => {
                        delegate.mutate(pat.id, pat.span, binding_cmt, Init);
                    }
                    Err(_) => { }
                }

                // It is also a borrow or copy/move of the value being matched.
                match pat.node {
                    ast::PatIdent(ast::BindByRef(m), _, _) => {
                        let (r, bk) = {
                            (ty::ty_region(tcx, pat.span, pat_ty),
                             ty::BorrowKind::from_mutbl(m))
                        };
                        delegate.borrow(pat.id, pat.span, cmt_pat,
                                             r, bk, RefBinding);
                    }
                    ast::PatIdent(ast::BindByValue(_), _, _) => {
                        let mode = copy_or_move(typer, &cmt_pat, PatBindingMove);
                        debug!("walk_pat binding consuming pat");
                        delegate.consume_pat(pat, cmt_pat, mode);
                    }
                    _ => {
                        tcx.sess.span_bug(
                            pat.span,
                            "binding pattern not an identifier");
                    }
                }
            } else {
                match pat.node {
                    ast::PatVec(_, Some(ref slice_pat), _) => {
                        // The `slice_pat` here creates a slice into
                        // the original vector.  This is effectively a
                        // borrow of the elements of the vector being
                        // matched.

                        let (slice_cmt, slice_mutbl, slice_r) =
                            return_if_err!(mc.cat_slice_pattern(cmt_pat, &**slice_pat));

                        // Note: We declare here that the borrow
                        // occurs upon entering the `[...]`
                        // pattern. This implies that something like
                        // `[a; b]` where `a` is a move is illegal,
                        // because the borrow is already in effect.
                        // In fact such a move would be safe-ish, but
                        // it effectively *requires* that we use the
                        // nulling out semantics to indicate when a
                        // value has been moved, which we are trying
                        // to move away from.  Otherwise, how can we
                        // indicate that the first element in the
                        // vector has been moved?  Eventually, we
                        // could perhaps modify this rule to permit
                        // `[..a, b]` where `b` is a move, because in
                        // that case we can adjust the length of the
                        // original vec accordingly, but we'd have to
                        // make trans do the right thing, and it would
                        // only work for `~` vectors. It seems simpler
                        // to just require that people call
                        // `vec.pop()` or `vec.unshift()`.
                        let slice_bk = ty::BorrowKind::from_mutbl(slice_mutbl);
                        delegate.borrow(pat.id, pat.span,
                                        slice_cmt, slice_r,
                                        slice_bk, RefBinding);
                    }
                    _ => { }
                }
            }
        }));

        // Do a second pass over the pattern, calling `matched_pat` on
        // the interior nodes (enum variants and structs), as opposed
        // to the above loop's visit of than the bindings that form
        // the leaves of the pattern tree structure.
        return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
            let def_map = def_map.borrow();
            let tcx = typer.tcx();

            match pat.node {
                ast::PatEnum(_, _) | ast::PatIdent(_, _, None) | ast::PatStruct(..) => {
                    match def_map.get(&pat.id).map(|d| d.full_def()) {
                        None => {
                            // no definition found: pat is not a
                            // struct or enum pattern.
                        }

                        Some(def::DefVariant(enum_did, variant_did, _is_struct)) => {
                            let downcast_cmt =
                                if ty::enum_is_univariant(tcx, enum_did) {
                                    cmt_pat
                                } else {
                                    let cmt_pat_ty = cmt_pat.ty;
                                    mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
                                };

                            debug!("variant downcast_cmt={} pat={}",
                                   downcast_cmt.repr(tcx),
                                   pat.repr(tcx));

                            delegate.matched_pat(pat, downcast_cmt, match_mode);
                        }

                        Some(def::DefStruct(..)) | Some(def::DefTy(_, false)) => {
                            // A struct (in either the value or type
                            // namespace; we encounter the former on
                            // e.g. patterns for unit structs).

                            debug!("struct cmt_pat={} pat={}",
                                   cmt_pat.repr(tcx),
                                   pat.repr(tcx));

                            delegate.matched_pat(pat, cmt_pat, match_mode);
                        }

                        Some(def::DefConst(..)) |
                        Some(def::DefLocal(..)) => {
                            // This is a leaf (i.e. identifier binding
                            // or constant value to match); thus no
                            // `matched_pat` call.
                        }

                        Some(def @ def::DefTy(_, true)) => {
                            // An enum's type -- should never be in a
                            // pattern.

                            if !tcx.sess.has_errors() {
                                let msg = format!("Pattern has unexpected type: {:?} and type {}",
                                                  def,
                                                  cmt_pat.ty.repr(tcx));
                                tcx.sess.span_bug(pat.span, &msg)
                            }
                        }

                        Some(def) => {
                            // Remaining cases are e.g. DefFn, to
                            // which identifiers within patterns
                            // should not resolve. However, we do
                            // encouter this when using the
                            // expr-use-visitor during typeck. So just
                            // ignore it, an error should have been
                            // reported.

                            if !tcx.sess.has_errors() {
                                let msg = format!("Pattern has unexpected def: {:?} and type {}",
                                                  def,
                                                  cmt_pat.ty.repr(tcx));
                                tcx.sess.span_bug(pat.span, &msg[..])
                            }
                        }
                    }
                }

                ast::PatIdent(_, _, Some(_)) => {
                    // Do nothing; this is a binding (not a enum
                    // variant or struct), and the cat_pattern call
                    // will visit the substructure recursively.
                }

                ast::PatWild(_) | ast::PatTup(..) | ast::PatBox(..) |
                ast::PatRegion(..) | ast::PatLit(..) | ast::PatRange(..) |
                ast::PatVec(..) | ast::PatMac(..) => {
                    // Similarly, each of these cases does not
                    // correspond to a enum variant or struct, so we
                    // do not do any `matched_pat` calls for these
                    // cases either.
                }
            }
        }));
    }

    fn walk_captures(&mut self, closure_expr: &ast::Expr) {
        debug!("walk_captures({})", closure_expr.repr(self.tcx()));

        ty::with_freevars(self.tcx(), closure_expr.id, |freevars| {
            for freevar in freevars {
                let id_var = freevar.def.def_id().node;
                let upvar_id = ty::UpvarId { var_id: id_var,
                                             closure_expr_id: closure_expr.id };
                let upvar_capture = self.typer.upvar_capture(upvar_id).unwrap();
                let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
                                                                   closure_expr.span,
                                                                   freevar.def));
                match upvar_capture {
                    ty::UpvarCapture::ByValue => {
                        let mode = copy_or_move(self.typer, &cmt_var, CaptureMove);
                        self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
                    }
                    ty::UpvarCapture::ByRef(upvar_borrow) => {
                        self.delegate.borrow(closure_expr.id,
                                             closure_expr.span,
                                             cmt_var,
                                             upvar_borrow.region,
                                             upvar_borrow.kind,
                                             ClosureCapture(freevar.span));
                    }
                }
            }
        });
    }

    fn cat_captured_var(&mut self,
                        closure_id: ast::NodeId,
                        closure_span: Span,
                        upvar_def: def::Def)
                        -> mc::McResult<mc::cmt<'tcx>> {
        // Create the cmt for the variable being borrowed, from the
        // caller's perspective
        let var_id = upvar_def.def_id().node;
        let var_ty = try!(self.typer.node_ty(var_id));
        self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
    }
}

fn copy_or_move<'tcx>(typer: &mc::Typer<'tcx>,
                      cmt: &mc::cmt<'tcx>,
                      move_reason: MoveReason)
                      -> ConsumeMode
{
    if typer.type_moves_by_default(cmt.span, cmt.ty) {
        Move(move_reason)
    } else {
        Copy
    }
}