Skip to content

Commit ee87234

Browse files
committed
auto merge of #16458 : pcwalton/rust/borrowck-for-moves, r=nikomatsakis
`for` loop heads. This breaks code like: let x = Some(box 1i); for &a in x.iter() { } Change this code to obey the borrow checking rules. For example: let x = Some(box 1i); for &ref a in x.iter() { } Closes #16205. [breaking-change] r? @nikomatsakis
2 parents e189122 + 7579185 commit ee87234

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

src/librustc/middle/expr_use_visitor.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -399,10 +399,16 @@ impl<'d,'t,TYPER:mc::Typer> ExprUseVisitor<'d,'t,TYPER> {
399399
ast::ExprForLoop(ref pat, ref head, ref blk, _) => {
400400
// The pattern lives as long as the block.
401401
debug!("walk_expr for loop case: blk id={}", blk.id);
402-
self.walk_expr(&**head);
402+
self.consume_expr(&**head);
403403

404-
let head_cmt = return_if_err!(self.mc.cat_expr(&**head));
405-
self.walk_pat(head_cmt, pat.clone());
404+
// Fetch the type of the value that the iteration yields to
405+
// produce the pattern's categorized mutable type.
406+
let pattern_type = ty::node_id_to_type(self.tcx(), pat.id);
407+
let pat_cmt = self.mc.cat_rvalue(pat.id,
408+
pat.span,
409+
ty::ReScope(blk.id),
410+
pattern_type);
411+
self.walk_pat(pat_cmt, pat.clone());
406412

407413
self.walk_block(&**blk);
408414
}
@@ -835,6 +841,7 @@ impl<'d,'t,TYPER:mc::Typer> ExprUseVisitor<'d,'t,TYPER> {
835841
}
836842
ast::PatIdent(ast::BindByValue(_), _, _) => {
837843
let mode = copy_or_move(typer.tcx(), cmt_pat.ty, PatBindingMove);
844+
debug!("walk_pat binding consuming pat");
838845
delegate.consume_pat(pat, cmt_pat, mode);
839846
}
840847
_ => {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
// Issue #16205.
12+
13+
struct Foo {
14+
a: [Box<int>, ..3],
15+
}
16+
17+
fn main() {
18+
let mut y = 1i;
19+
let x = Some(&mut y);
20+
for &a in x.iter() { //~ ERROR cannot move out
21+
}
22+
23+
let f = Foo {
24+
a: [box 3, box 4, box 5],
25+
};
26+
for &a in f.a.iter() { //~ ERROR cannot move out
27+
}
28+
29+
let x = Some(box 1i);
30+
for &a in x.iter() { //~ ERROR cannot move out
31+
}
32+
}
33+

0 commit comments

Comments
 (0)