Skip to content

Commit 23a553a

Browse files
committed
Improve the vec![...] macro with UFCS.
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.
1 parent a833337 commit 23a553a

File tree

3 files changed

+31
-8
lines changed

3 files changed

+31
-8
lines changed

src/libcollections/macros.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@
1212
#[macro_export]
1313
#[stable]
1414
macro_rules! vec {
15-
($x:expr; $y:expr) => ({
16-
let xs: $crate::boxed::Box<[_]> = $crate::boxed::Box::new([$x; $y]);
17-
$crate::slice::SliceExt::into_vec(xs)
18-
});
19-
($($x:expr),*) => ({
20-
let xs: $crate::boxed::Box<[_]> = $crate::boxed::Box::new([$($x),*]);
21-
$crate::slice::SliceExt::into_vec(xs)
22-
});
15+
($x:expr; $y:expr) => (
16+
<[_] as $crate::slice::SliceExt>::into_vec(
17+
$crate::boxed::Box::new([$x; $y]))
18+
);
19+
($($x:expr),*) => (
20+
<[_] as $crate::slice::SliceExt>::into_vec(
21+
$crate::boxed::Box::new([$($x),*]))
22+
);
2323
($($x:expr,)*) => (vec![$($x),*])
2424
}

src/test/run-pass/coerce-expect-unsized.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,9 @@ pub fn main() {
3333

3434
let _: Box<[int]> = Box::new([1, 2, 3]);
3535
let _: Box<Fn(int) -> _> = Box::new(|x| (x as u8));
36+
37+
let _: Vec<Box<Fn(int) -> _>> = vec![
38+
Box::new(|x| (x as u8)),
39+
box |x| (x as i16 as u8),
40+
];
3641
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Copyright 2015 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+
fn one() -> i32 { 1 }
12+
13+
// Make sure the vec![...] macro doesn't introduce hidden rvalue
14+
// scopes (such as blocks) around the element expressions.
15+
pub fn main() {
16+
assert_eq!(vec![&one(), &one(), &2], vec![&1, &1, &(one()+one())]);
17+
assert_eq!(vec![&one(); 2], vec![&1, &one()]);
18+
}

0 commit comments

Comments
 (0)