]> git.lizzy.rs Git - rust.git/commitdiff
Improve the vec![...] macro with UFCS.
authorEduard Burtescu <edy.burt@gmail.com>
Sun, 18 Jan 2015 11:13:23 +0000 (13:13 +0200)
committerEduard Burtescu <edy.burt@gmail.com>
Sun, 18 Jan 2015 11:13:23 +0000 (13:13 +0200)
There are two limitations to the macro that this addresses:
1. the expected type is not propagated, coercions don't trigger
2. references inside element expressions don't outlive the `Vec`

Both of these limitations are caused by the block in the
macro expansion, previously needed to trigger a coercion
from `Box<[T; N]>` to `Box<[T]>`, now possible with UFCS.

src/libcollections/macros.rs
src/test/run-pass/coerce-expect-unsized.rs
src/test/run-pass/vec-macro-rvalue-scope.rs [new file with mode: 0644]

index c078db7d46fb7ec610295d059487a8387a63f5f1..85aedaeb010f127689c8b43053a27b2f40e0e39a 100644 (file)
 #[macro_export]
 #[stable]
 macro_rules! vec {
-    ($x:expr; $y:expr) => ({
-        let xs: $crate::boxed::Box<[_]> = $crate::boxed::Box::new([$x; $y]);
-        $crate::slice::SliceExt::into_vec(xs)
-    });
-    ($($x:expr),*) => ({
-        let xs: $crate::boxed::Box<[_]> = $crate::boxed::Box::new([$($x),*]);
-        $crate::slice::SliceExt::into_vec(xs)
-    });
+    ($x:expr; $y:expr) => (
+        <[_] as $crate::slice::SliceExt>::into_vec(
+            $crate::boxed::Box::new([$x; $y]))
+    );
+    ($($x:expr),*) => (
+        <[_] as $crate::slice::SliceExt>::into_vec(
+            $crate::boxed::Box::new([$($x),*]))
+    );
     ($($x:expr,)*) => (vec![$($x),*])
 }
index f590e6e07283cc208f26e2e63e8aacc22754104d..200d3fd69356b22b68ecdbfd0d8b746f34c12b28 100644 (file)
@@ -33,4 +33,9 @@ pub fn main() {
 
     let _: Box<[int]> = Box::new([1, 2, 3]);
     let _: Box<Fn(int) -> _> = Box::new(|x| (x as u8));
+
+    let _: Vec<Box<Fn(int) -> _>> = vec![
+        Box::new(|x| (x as u8)),
+        box |x| (x as i16 as u8),
+    ];
 }
diff --git a/src/test/run-pass/vec-macro-rvalue-scope.rs b/src/test/run-pass/vec-macro-rvalue-scope.rs
new file mode 100644 (file)
index 0000000..68dedfc
--- /dev/null
@@ -0,0 +1,18 @@
+// 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 one() -> i32 { 1 }
+
+// Make sure the vec![...] macro doesn't introduce hidden rvalue
+// scopes (such as blocks) around the element expressions.
+pub fn main() {
+    assert_eq!(vec![&one(), &one(), &2], vec![&1, &1, &(one()+one())]);
+    assert_eq!(vec![&one(); 2], vec![&1, &one()]);
+}