]> git.lizzy.rs Git - rust.git/commitdiff
Change `&` pat to only work with &T, and `&mut` with &mut T.
authorHuon Wilson <dbau.pp+github@gmail.com>
Fri, 5 Dec 2014 23:56:25 +0000 (15:56 -0800)
committerHuon Wilson <dbau.pp+github@gmail.com>
Mon, 5 Jan 2015 05:14:17 +0000 (16:14 +1100)
This implements RFC 179 by making the pattern `&<pat>` require matching
against a variable of type `&T`, and introducing the pattern `&mut
<pat>` which only works with variables of type `&mut T`.

The pattern `&mut x` currently parses as `&(mut x)` i.e. a pattern match
through a `&T` or a `&mut T` that binds the variable `x` to have type
`T` and to be mutable. This should be rewritten as follows, for example,

    for &mut x in slice.iter() {

becomes

    for &x in slice.iter() {
        let mut x = x;

Due to this, this is a

[breaking-change]

Closes #20496.

19 files changed:
src/doc/reference.md
src/libcore/str/mod.rs
src/librustc/middle/cfg/construct.rs
src/librustc/middle/check_match.rs
src/librustc/middle/mem_categorization.rs
src/librustc_trans/trans/_match.rs
src/librustc_trans/trans/debuginfo.rs
src/librustc_typeck/check/_match.rs
src/librustdoc/clean/mod.rs
src/libsyntax/ast.rs
src/libsyntax/ast_util.rs
src/libsyntax/ext/deriving/generic/mod.rs
src/libsyntax/fold.rs
src/libsyntax/parse/parser.rs
src/libsyntax/print/pprust.rs
src/libsyntax/visit.rs
src/libtest/stats.rs
src/test/compile-fail/mut-pattern-internal-mutability.rs [new file with mode: 0644]
src/test/compile-fail/mut-pattern-mismatched.rs [new file with mode: 0644]

index d7930285260523858d4164b846cf9a82f39a78cc..0d3f9430bd67729eea66d13e657b305b604f4297 100644 (file)
@@ -3484,8 +3484,9 @@ fn main() {
 
 ```
 
-Patterns can also dereference pointers by using the `&`, `box` symbols,
-as appropriate. For example, these two matches on `x: &int` are equivalent:
+Patterns can also dereference pointers by using the `&`, `&mut` and `box`
+symbols, as appropriate. For example, these two matches on `x: &int` are
+equivalent:
 
 ```
 # let x = &3i;
index d069744f8da54f109bba4c957240999bbbfa8258..b497e9733bc9e41f9a855eff953534aa4c2e7dab 100644 (file)
@@ -230,7 +230,7 @@ fn only_ascii(&self) -> bool { false }
 impl<'a> CharEq for &'a [char] {
     #[inline]
     fn matches(&mut self, c: char) -> bool {
-        self.iter().any(|&mut m| m.matches(c))
+        self.iter().any(|&m| { let mut m = m; m.matches(c) })
     }
 
     #[inline]
index de81f307c4d7cfb5286672806ee9f29f784e7a8c..3c672d0fdb6fa01057a9d69af99c66ed51c8be7b 100644 (file)
@@ -119,7 +119,7 @@ fn pat(&mut self, pat: &ast::Pat, pred: CFGIndex) -> CFGIndex {
             }
 
             ast::PatBox(ref subpat) |
-            ast::PatRegion(ref subpat) |
+            ast::PatRegion(ref subpat, _) |
             ast::PatIdent(_, _, Some(ref subpat)) => {
                 let subpat_exit = self.pat(&**subpat, pred);
                 self.add_node(pat.id, &[subpat_exit])
index 2d9284846acf349060192a44454f7945c536ad9b..f2b9ecb5ec4322aa8af50c7a0d780aad0bee7682 100644 (file)
@@ -473,7 +473,7 @@ fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
             }
         }
 
-        ty::ty_rptr(_, ty::mt { ty, .. }) => {
+        ty::ty_rptr(_, ty::mt { ty, mutbl }) => {
             match ty.sty {
                ty::ty_vec(_, Some(n)) => match ctor {
                     &Single => {
@@ -493,7 +493,7 @@ fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
 
                 _ => {
                     assert_eq!(pats_len, 1);
-                    ast::PatRegion(pats.nth(0).unwrap())
+                    ast::PatRegion(pats.nth(0).unwrap(), mutbl)
                 }
             }
         }
@@ -860,7 +860,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
         ast::PatTup(ref args) =>
             Some(args.iter().map(|p| &**p).collect()),
 
-        ast::PatBox(ref inner) | ast::PatRegion(ref inner) =>
+        ast::PatBox(ref inner) | ast::PatRegion(ref inner, _) =>
             Some(vec![&**inner]),
 
         ast::PatLit(ref expr) => {
index 31c3ca4199febfa27dea50422c9caa64d6a00405..f600086fc5e62328d38a4fff431ebe284a5f549a 100644 (file)
@@ -1262,8 +1262,10 @@ fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &ast::Pat, op: &mut F)
             }
           }
 
-          ast::PatBox(ref subpat) | ast::PatRegion(ref subpat) => {
-            // @p1, ~p1, ref p1
+          ast::PatBox(ref subpat) | ast::PatRegion(ref subpat, _) => {
+            // box p1, &p1, &mut p1.  we can ignore the mutability of
+            // PatRegion since that information is already contained
+            // in the type.
             let subcmt = try!(self.cat_deref(pat, cmt, 0, false));
               try!(self.cat_pattern_(subcmt, &**subpat, op));
           }
index 50cbe664b90798d07853a7b8a7647e02fcaca572..fed0931cab71d52f071ed5429356ce99ed19fbd9 100644 (file)
@@ -683,7 +683,7 @@ fn any_uniq_pat(m: &[Match], col: uint) -> bool {
 }
 
 fn any_region_pat(m: &[Match], col: uint) -> bool {
-    any_pat!(m, col, ast::PatRegion(_))
+    any_pat!(m, col, ast::PatRegion(..))
 }
 
 fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: uint) -> bool {
@@ -1725,7 +1725,7 @@ fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             let llbox = Load(bcx, val);
             bcx = bind_irrefutable_pat(bcx, &**inner, llbox, cleanup_scope);
         }
-        ast::PatRegion(ref inner) => {
+        ast::PatRegion(ref inner, _) => {
             let loaded_val = Load(bcx, val);
             bcx = bind_irrefutable_pat(bcx, &**inner, loaded_val, cleanup_scope);
         }
index 916fcbfe13ef77df022583d3acf82788b4ee20ee..0789be956429ccce0d8a31c0547b7ec32ab81eb7 100644 (file)
@@ -3472,7 +3472,7 @@ fn walk_pattern(cx: &CrateContext,
                 }
             }
 
-            ast::PatBox(ref sub_pat) | ast::PatRegion(ref sub_pat) => {
+            ast::PatBox(ref sub_pat) | ast::PatRegion(ref sub_pat, _) => {
                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
                 walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
             }
index d8b410abf84492056bb9d57b9790eb5531cba866..1efff9d41f1ba9a36ebefad7d7046d4c901e01ed 100644 (file)
@@ -146,12 +146,16 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>,
                 check_pat(pcx, &**inner, tcx.types.err);
             }
         }
-        ast::PatRegion(ref inner) => {
+        ast::PatRegion(ref inner, mutbl) => {
             let inner_ty = fcx.infcx().next_ty_var();
 
-            let mutbl =
+            // SNAP c894171 remove this `if`-`else` entirely after next snapshot
+            let mutbl = if mutbl == ast::MutImmutable {
                 ty::deref(fcx.infcx().shallow_resolve(expected), true)
-                .map_or(ast::MutImmutable, |mt| mt.mutbl);
+                    .map_or(ast::MutImmutable, |mt| mt.mutbl)
+            } else {
+                mutbl
+            };
 
             let mt = ty::mt { ty: inner_ty, mutbl: mutbl };
             let region = fcx.infcx().next_region_var(infer::PatternRegion(pat.span));
index f4d0bb79d88d6b74268d4448d90eb5d16d44ed55..6a4337a664b785e6f1288822f06e6a7a621a508e 100644 (file)
@@ -2235,7 +2235,7 @@ fn name_from_pat(p: &ast::Pat) -> String {
         PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
                                             .collect::<Vec<String>>().connect(", ")),
         PatBox(ref p) => name_from_pat(&**p),
-        PatRegion(ref p) => name_from_pat(&**p),
+        PatRegion(ref p, _) => name_from_pat(&**p),
         PatLit(..) => {
             warn!("tried to get argument name from PatLit, \
                   which is silly in function arguments");
index a33ee44be89684a65654bffaebfc2bd2061991ee..d61b7a17a930d86db48711b539854b1f6eac37f7 100644 (file)
@@ -556,7 +556,7 @@ pub enum Pat_ {
     PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
     PatTup(Vec<P<Pat>>),
     PatBox(P<Pat>),
-    PatRegion(P<Pat>), // reference pattern
+    PatRegion(P<Pat>, Mutability), // reference pattern
     PatLit(P<Expr>),
     PatRange(P<Expr>, P<Expr>),
     /// [a, b, ..i, y, z] is represented as:
index 4026da6cf8e478ed48e90eeb026f1b2ca3111133..5e03afec16cf8709e1e5a92a047e87d39ef9a6b5 100644 (file)
@@ -633,7 +633,7 @@ fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
             PatEnum(_, Some(ref s)) | PatTup(ref s) => {
                 s.iter().all(|p| walk_pat_(&**p, it))
             }
-            PatBox(ref s) | PatRegion(ref s) => {
+            PatBox(ref s) | PatRegion(ref s, _) => {
                 walk_pat_(&**s, it)
             }
             PatVec(ref before, ref slice, ref after) => {
index 8863de8757bf7ffb22abddccbb66b71301a59235..d522c346fa0ee523053dacd09182e1c7d24b6d3b 100644 (file)
@@ -940,7 +940,7 @@ fn build_enum_match_tuple(
                                                                          &**variant,
                                                                          self_arg_name,
                                                                          ast::MutImmutable);
-                    (cx.pat(sp, ast::PatRegion(p)), idents)
+                    (cx.pat(sp, ast::PatRegion(p, ast::MutImmutable)), idents)
                 };
 
                 // A single arm has form (&VariantK, &VariantK, ...) => BodyK
index 3d3068f6868c6a3c5c850a542e8a2445e5f55f1b..03a4f9046b5492af99aaba821e9cc52464db813b 100644 (file)
@@ -1267,7 +1267,7 @@ pub fn noop_fold_pat<T: Folder>(p: P<Pat>, folder: &mut T) -> P<Pat> {
             }
             PatTup(elts) => PatTup(elts.move_map(|x| folder.fold_pat(x))),
             PatBox(inner) => PatBox(folder.fold_pat(inner)),
-            PatRegion(inner) => PatRegion(folder.fold_pat(inner)),
+            PatRegion(inner, mutbl) => PatRegion(folder.fold_pat(inner), mutbl),
             PatRange(e1, e2) => {
                 PatRange(folder.fold_expr(e1), folder.fold_expr(e2))
             },
index 37ac86a33242e54e26ec80233add9c034ccf902f..d9183ef0c49f569ed3cd9ddaddc7226df9f017c4 100644 (file)
@@ -3357,11 +3357,16 @@ pub fn parse_pat(&mut self) -> P<Pat> {
             })
           }
           token::BinOp(token::And) | token::AndAnd => {
-            // parse &pat
+            // parse &pat and &mut pat
             let lo = self.span.lo;
             self.expect_and();
+            let mutability = if self.eat_keyword(keywords::Mut) {
+                ast::MutMutable
+            } else {
+                ast::MutImmutable
+            };
             let sub = self.parse_pat();
-            pat = PatRegion(sub);
+            pat = PatRegion(sub, mutability);
             hi = self.last_span.hi;
             return P(ast::Pat {
                 id: ast::DUMMY_NODE_ID,
index 9702c79719c64ac62b20dd53fb3e8af0972d411d..9b2ee9de3584e9515b7352653b4a6a2b5534dc85 100644 (file)
@@ -2092,8 +2092,11 @@ pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
                 try!(word(&mut self.s, "box "));
                 try!(self.print_pat(&**inner));
             }
-            ast::PatRegion(ref inner) => {
+            ast::PatRegion(ref inner, mutbl) => {
                 try!(word(&mut self.s, "&"));
+                if mutbl == ast::MutMutable {
+                    try!(word(&mut self.s, "mut "));
+                }
                 try!(self.print_pat(&**inner));
             }
             ast::PatLit(ref e) => try!(self.print_expr(&**e)),
index ec6b2cfa5c39624fa8610e1b53df0512c0eb6f6c..99701ec9710037e18b98cbde7a9b5da0d72dcacf 100644 (file)
@@ -519,7 +519,7 @@ pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) {
             }
         }
         PatBox(ref subpattern) |
-        PatRegion(ref subpattern) => {
+        PatRegion(ref subpattern, _) => {
             visitor.visit_pat(&**subpattern)
         }
         PatIdent(_, ref pth1, ref optional_subpattern) => {
index 35af0e763d7dd0711d8b3bfa8020c7fffcaed900..c42cf4d055166972ece3231ea1e359bda483ad87 100644 (file)
@@ -169,7 +169,8 @@ impl<T: FloatMath + FromPrimitive> Stats<T> for [T] {
     fn sum(&self) -> T {
         let mut partials = vec![];
 
-        for &mut x in self.iter() {
+        for &x in self.iter() {
+            let mut x = x;
             let mut j = 0;
             // This inner loop applies `hi`/`lo` summation to each
             // partial so that the list of partial sums remains exact.
diff --git a/src/test/compile-fail/mut-pattern-internal-mutability.rs b/src/test/compile-fail/mut-pattern-internal-mutability.rs
new file mode 100644 (file)
index 0000000..05c6c4a
--- /dev/null
@@ -0,0 +1,24 @@
+// Copyright 2015 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.
+
+fn main() {
+    let foo = &mut 1i;
+
+    let &mut x = foo;
+    x += 1; //~ ERROR re-assignment of immutable variable
+
+    // explicitly mut-ify internals
+    let &mut mut x = foo;
+    x += 1;
+
+    // check borrowing is detected successfully
+    let &mut ref x = foo;
+    *foo += 1; //~ ERROR cannot assign to `*foo` because it is borrowed
+}
diff --git a/src/test/compile-fail/mut-pattern-mismatched.rs b/src/test/compile-fail/mut-pattern-mismatched.rs
new file mode 100644 (file)
index 0000000..74e6141
--- /dev/null
@@ -0,0 +1,26 @@
+// 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.
+
+fn main() {
+    let foo = &mut 1i;
+
+    // (separate lines to ensure the spans are accurate)
+
+    // SNAP c894171 uncomment this after the next snapshot
+    // NOTE(stage0) just in case tidy doesn't check SNAP's in tests
+    // let &_ // ~ ERROR expected `&mut int`, found `&_`
+    //    = foo;
+    let &mut _ = foo;
+
+    let bar = &1i;
+    let &_ = bar;
+    let &mut _ //~ ERROR expected `&int`, found `&mut _`
+         = bar;
+}