From d3c831ba4a4a2284f73e4f9147aa4900cab56815 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Mon, 7 Apr 2014 22:32:49 +1000 Subject: [PATCH 01/28] std: use a `match` in `assert_eq!` to extend the lifetime of the args. This enables assert_eq!(foo.collect::>().as_slice(), &[1,2,3,4]); to work, by extending the lifetime of the .as_slice() rvalue. --- src/libstd/macros.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index fbb48f2ebcb26..9d06e38dd8e9c 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -117,13 +117,15 @@ macro_rules! assert( #[macro_export] macro_rules! assert_eq( ($given:expr , $expected:expr) => ({ - let given_val = &($given); - let expected_val = &($expected); - // check both directions of equality.... - if !((*given_val == *expected_val) && - (*expected_val == *given_val)) { - fail!("assertion failed: `(left == right) && (right == left)` \ - (left: `{}`, right: `{}`)", *given_val, *expected_val) + match (&($given), &($expected)) { + (given_val, expected_val) => { + // check both directions of equality.... + if !((*given_val == *expected_val) && + (*expected_val == *given_val)) { + fail!("assertion failed: `(left == right) && (right == left)` \ + (left: `{}`, right: `{}`)", *given_val, *expected_val) + } + } } }) ) From 4b9a7a2588798ab4ffaa4805397fa428348d6a2a Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Sat, 5 Apr 2014 16:45:42 +1100 Subject: [PATCH 02/28] collections: replace all ~[T] with Vec. --- src/libcollections/bitv.rs | 67 ++++++++++----------- src/libcollections/btree.rs | 58 +++++++++--------- src/libcollections/deque.rs | 7 +-- src/libcollections/dlist.rs | 40 ++++++------- src/libcollections/enum_set.rs | 32 +++++----- src/libcollections/hashmap.rs | 22 +++---- src/libcollections/lib.rs | 2 + src/libcollections/lru_cache.rs | 8 +-- src/libcollections/priority_queue.rs | 90 ++++++++++++++-------------- src/libcollections/ringbuf.rs | 45 +++++++------- src/libcollections/smallintmap.rs | 20 +++---- src/libcollections/treemap.rs | 30 +++++----- src/libcollections/trie.rs | 4 +- 13 files changed, 212 insertions(+), 213 deletions(-) diff --git a/src/libcollections/bitv.rs b/src/libcollections/bitv.rs index 510e8908427c0..cdcc05bf72983 100644 --- a/src/libcollections/bitv.rs +++ b/src/libcollections/bitv.rs @@ -111,7 +111,7 @@ impl SmallBitv { #[deriving(Clone)] struct BigBitv { - storage: ~[uint] + storage: Vec } /** @@ -131,7 +131,7 @@ fn big_mask(nbits: uint, elem: uint) -> uint { } impl BigBitv { - pub fn new(storage: ~[uint]) -> BigBitv { + pub fn new(storage: Vec) -> BigBitv { BigBitv {storage: storage} } @@ -193,7 +193,7 @@ impl BigBitv { pub fn get(&self, i: uint) -> bool { let w = i / uint::BITS; let b = i % uint::BITS; - let x = 1 & self.storage[w] >> b; + let x = 1 & self.storage.get(w) >> b; x == 1 } @@ -202,15 +202,15 @@ impl BigBitv { let w = i / uint::BITS; let b = i % uint::BITS; let flag = 1 << b; - self.storage[w] = if x { self.storage[w] | flag } - else { self.storage[w] & !flag }; + *self.storage.get_mut(w) = if x { *self.storage.get(w) | flag } + else { *self.storage.get(w) & !flag }; } #[inline] pub fn equals(&self, b: &BigBitv, nbits: uint) -> bool { for (i, elt) in b.storage.iter().enumerate() { let mask = big_mask(nbits, i); - if mask & self.storage[i] != mask & *elt { + if mask & *self.storage.get(i) != mask & *elt { return false; } } @@ -278,13 +278,13 @@ impl Bitv { let s = if init { if exact { - slice::from_elem(nelems, !0u) + Vec::from_elem(nelems, !0u) } else { - let mut v = slice::from_elem(nelems-1, !0u); + let mut v = Vec::from_elem(nelems-1, !0u); v.push((1< ~[uint] { - slice::from_fn(self.nbits, |x| self.init_to_vec(x)) + pub fn to_vec(&self) -> Vec { + Vec::from_fn(self.nbits, |x| self.init_to_vec(x)) } /** @@ -461,7 +461,7 @@ impl Bitv { * size of the `Bitv` is not a multiple of 8 then trailing bits * will be filled-in with false/0 */ - pub fn to_bytes(&self) -> ~[u8] { + pub fn to_bytes(&self) -> Vec { fn bit (bitv: &Bitv, byte: uint, bit: uint) -> u8 { let offset = byte * 8 + bit; if offset >= bitv.nbits { @@ -473,7 +473,7 @@ impl Bitv { let len = self.nbits/8 + if self.nbits % 8 == 0 { 0 } else { 1 }; - slice::from_fn(len, |i| + Vec::from_fn(len, |i| bit(self, i, 0) | bit(self, i, 1) | bit(self, i, 2) | @@ -486,10 +486,10 @@ impl Bitv { } /** - * Transform `self` into a `[bool]` by turning each bit into a `bool`. + * Transform `self` into a `Vec` by turning each bit into a `bool`. */ - pub fn to_bools(&self) -> ~[bool] { - slice::from_fn(self.nbits, |i| self[i]) + pub fn to_bools(&self) -> Vec { + Vec::from_fn(self.nbits, |i| self[i]) } /** @@ -659,7 +659,7 @@ pub struct BitvSet { impl BitvSet { /// Creates a new bit vector set with initially no contents pub fn new() -> BitvSet { - BitvSet{ size: 0, bitv: BigBitv::new(~[0]) } + BitvSet{ size: 0, bitv: BigBitv::new(vec!(0)) } } /// Creates a new bit vector set from the given bit vector @@ -673,7 +673,7 @@ impl BitvSet { match rep { Big(b) => BitvSet{ size: size, bitv: b }, Small(SmallBitv{bits}) => - BitvSet{ size: size, bitv: BigBitv{ storage: ~[bits] } }, + BitvSet{ size: size, bitv: BigBitv{ storage: vec!(bits) } }, } } @@ -705,9 +705,9 @@ impl BitvSet { self.bitv.storage.grow(other.capacity() / uint::BITS, &0); } for (i, &w) in other.bitv.storage.iter().enumerate() { - let old = self.bitv.storage[i]; + let old = *self.bitv.storage.get(i); let new = f(old, w); - self.bitv.storage[i] = new; + *self.bitv.storage.get_mut(i) = new; self.size += nbits(new) - nbits(old); } } @@ -863,7 +863,7 @@ impl MutableSet for BitvSet { // Attempt to truncate our storage let mut i = self.bitv.storage.len(); - while i > 1 && self.bitv.storage[i - 1] == 0 { + while i > 1 && *self.bitv.storage.get(i - 1) == 0 { i -= 1; } self.bitv.storage.truncate(i); @@ -878,12 +878,12 @@ impl BitvSet { /// w1, w2) where the bit location is the number of bits offset so far, /// and w1/w2 are the words coming from the two vectors self, other. fn commons<'a>(&'a self, other: &'a BitvSet) - -> Map<'static, ((uint, &'a uint), &'a ~[uint]), (uint, uint, uint), - Zip>, Repeat<&'a ~[uint]>>> { + -> Map<'static, ((uint, &'a uint), &'a Vec), (uint, uint, uint), + Zip>, Repeat<&'a Vec>>> { let min = cmp::min(self.bitv.storage.len(), other.bitv.storage.len()); self.bitv.storage.slice(0, min).iter().enumerate() .zip(Repeat::new(&other.bitv.storage)) - .map(|((i, &w), o_store)| (i * uint::BITS, w, o_store[i])) + .map(|((i, &w), o_store)| (i * uint::BITS, w, *o_store.get(i))) } /// Visits each word in `self` or `other` that extends beyond the other. This @@ -946,7 +946,6 @@ mod tests { use bitv; use std::uint; - use std::slice; use rand; use rand::Rng; @@ -964,8 +963,8 @@ mod tests { #[test] fn test_0_elements() { let act = Bitv::new(0u, false); - let exp = slice::from_elem::(0u, false); - assert!(act.eq_vec(exp)); + let exp = Vec::from_elem(0u, false); + assert!(act.eq_vec(exp.as_slice())); } #[test] @@ -1299,12 +1298,12 @@ mod tests { fn test_to_bytes() { let mut bv = Bitv::new(3, true); bv.set(1, false); - assert_eq!(bv.to_bytes(), ~[0b10100000]); + assert_eq!(bv.to_bytes(), vec!(0b10100000)); let mut bv = Bitv::new(9, false); bv.set(2, true); bv.set(8, true); - assert_eq!(bv.to_bytes(), ~[0b00100000, 0b10000000]); + assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000)); } #[test] @@ -1315,7 +1314,7 @@ mod tests { #[test] fn test_to_bools() { - let bools = ~[false, false, true, false, false, true, true, false]; + let bools = vec!(false, false, true, false, false, true, true, false); assert_eq!(from_bytes([0b00100110]).to_bools(), bools); } @@ -1334,8 +1333,8 @@ mod tests { let bools = [true, false, true, true]; let bitv = BitvSet::from_bitv(from_bools(bools)); - let idxs: ~[uint] = bitv.iter().collect(); - assert_eq!(idxs, ~[0, 2, 3]); + let idxs: Vec = bitv.iter().collect(); + assert_eq!(idxs, vec!(0, 2, 3)); } #[test] @@ -1579,7 +1578,7 @@ mod tests { #[bench] fn bench_big_bitv_small(b: &mut BenchHarness) { let mut r = rng(); - let mut bitv = BigBitv::new(~[0]); + let mut bitv = BigBitv::new(vec!(0)); b.iter(|| { bitv.set((r.next_u32() as uint) % uint::BITS, true); &bitv @@ -1589,7 +1588,7 @@ mod tests { #[bench] fn bench_big_bitv_big(b: &mut BenchHarness) { let mut r = rng(); - let mut storage = ~[]; + let mut storage = vec!(); storage.grow(BENCH_BITS / uint::BITS, &0u); let mut bitv = BigBitv::new(storage); b.iter(|| { diff --git a/src/libcollections/btree.rs b/src/libcollections/btree.rs index b516997b81e77..c317ed926f668 100644 --- a/src/libcollections/btree.rs +++ b/src/libcollections/btree.rs @@ -35,7 +35,7 @@ impl BTree { ///The lower bound applies to every node except the root node. pub fn new(k: K, v: V, lb: uint) -> BTree { BTree { - root: Node::new_leaf(~[LeafElt::new(k, v)]), + root: Node::new_leaf(vec!(LeafElt::new(k, v))), len: 1, lower_bound: lb, upper_bound: 2 * lb @@ -135,12 +135,12 @@ enum Node { //Node functions/methods impl Node { ///Creates a new leaf node given a vector of elements. - fn new_leaf(vec: ~[LeafElt]) -> Node { + fn new_leaf(vec: Vec>) -> Node { LeafNode(Leaf::new(vec)) } ///Creates a new branch node given a vector of an elements and a pointer to a rightmost child. - fn new_branch(vec: ~[BranchElt], right: ~Node) -> Node { + fn new_branch(vec: Vec>, right: ~Node) -> Node { BranchNode(Branch::new(vec, right)) } @@ -264,19 +264,19 @@ impl fmt::Show for Node { //A leaf is a vector with elements that contain no children. A leaf also //does not contain a rightmost child. struct Leaf { - elts: ~[LeafElt] + elts: Vec> } //Vector of values with children, plus a rightmost child (greater than all) struct Branch { - elts: ~[BranchElt], + elts: Vec>, rightmost_child: ~Node } impl Leaf { ///Creates a new Leaf from a vector of LeafElts. - fn new(vec: ~[LeafElt]) -> Leaf { + fn new(vec: Vec>) -> Leaf { Leaf { elts: vec } @@ -292,14 +292,14 @@ impl Leaf { midpoint = 0; } loop { - let order = self.elts[midpoint].key.cmp(&k); + let order = self.elts.get(midpoint).key.cmp(&k); match order { Equal => { return None; } Greater => { if midpoint > 0 { - if self.elts[midpoint - 1].key.cmp(&k) == Less { + if self.elts.get(midpoint - 1).key.cmp(&k) == Less { return Some(midpoint); } else { @@ -315,7 +315,7 @@ impl Leaf { } Less => { if midpoint + 1 < self.elts.len() { - if self.elts[midpoint + 1].key.cmp(&k) == Greater { + if self.elts.get(midpoint + 1).key.cmp(&k) == Greater { return Some(midpoint); } else { @@ -375,9 +375,9 @@ impl Leaf { let (left_leaf, right_leaf) = self.elts.partition(|le| le.key.cmp(&midpoint.key.clone()) == Less); - let branch_return = Node::new_branch(~[BranchElt::new(midpoint.key.clone(), + let branch_return = Node::new_branch(vec!(BranchElt::new(midpoint.key.clone(), midpoint.value.clone(), - ~Node::new_leaf(left_leaf))], + ~Node::new_leaf(left_leaf))), ~Node::new_leaf(right_leaf)); return (branch_return, true); } @@ -415,7 +415,7 @@ impl TotalOrd for Leaf { if self.elts.len() < other.elts.len() { return Less; } - self.elts[0].cmp(&other.elts[0]) + self.elts.get(0).cmp(other.elts.get(0)) } } @@ -434,7 +434,7 @@ impl fmt::Show for Leaf { impl Branch { ///Creates a new Branch from a vector of BranchElts and a rightmost child (a node). - fn new(vec: ~[BranchElt], right: ~Node) -> Branch { + fn new(vec: Vec>, right: ~Node) -> Branch { Branch { elts: vec, rightmost_child: right @@ -449,14 +449,14 @@ impl Branch { midpoint = 0u; } loop { - let order = self.elts[midpoint].key.cmp(&k); + let order = self.elts.get(midpoint).key.cmp(&k); match order { Equal => { return None; } Greater => { if midpoint > 0 { - if self.elts[midpoint - 1].key.cmp(&k) == Less { + if self.elts.get(midpoint - 1).key.cmp(&k) == Less { return Some(midpoint); } else { @@ -472,7 +472,7 @@ impl Branch { } Less => { if midpoint + 1 < self.elts.len() { - if self.elts[midpoint + 1].key.cmp(&k) == Greater { + if self.elts.get(midpoint + 1).key.cmp(&k) == Greater { return Some(midpoint); } else { @@ -527,7 +527,7 @@ impl Branch { outcome = new_outcome.val1(); } else { - let new_outcome = self.clone().elts[index.unwrap()].left.insert(k.clone(), + let new_outcome = self.elts.get(index.unwrap()).left.clone().insert(k.clone(), v.clone(), ub.clone()); new_branch = new_outcome.clone().val0(); @@ -543,7 +543,7 @@ impl Branch { self.rightmost_child = ~new_branch.clone(); } else { - self.elts[index.unwrap()].left = ~new_branch.clone(); + self.elts.get_mut(index.unwrap()).left = ~new_branch.clone(); } return (Node::new_branch(self.clone().elts, self.clone().rightmost_child), @@ -564,7 +564,7 @@ impl Branch { self.rightmost_child = ~new_branch; } else { - self.elts[index.unwrap()].left = ~new_branch; + self.elts.get_mut(index.unwrap()).left = ~new_branch; } return (Node::new_branch(self.clone().elts, self.clone().rightmost_child), @@ -573,7 +573,7 @@ impl Branch { //If we have a new branch node, attempt to insert it into the tree //as with the key-value pair, then check to see if the node is overfull. BranchNode(branch) => { - let new_elt = branch.clone().elts[0]; + let new_elt = branch.elts.get(0).clone(); let new_elt_index = self.bsearch_branch(new_elt.clone().key); match new_elt_index { None => { @@ -587,7 +587,7 @@ impl Branch { self.rightmost_child = branch.clone().rightmost_child; } else { - self.elts[new_elt_index.unwrap() + 1].left = + self.elts.get_mut(new_elt_index.unwrap() + 1).left = branch.clone().rightmost_child; } } @@ -602,10 +602,10 @@ impl Branch { midpoint.key.cmp(&le.key) == Greater); new_branch = Node::new_branch( - ~[BranchElt::new(midpoint.clone().key, + vec!(BranchElt::new(midpoint.clone().key, midpoint.clone().value, ~Node::new_branch(new_left, - midpoint.clone().left))], + midpoint.clone().left))), ~Node::new_branch(new_right, self.clone().rightmost_child)); return (new_branch, true); } @@ -644,7 +644,7 @@ impl TotalOrd for Branch { if self.elts.len() < other.elts.len() { return Less; } - self.elts[0].cmp(&other.elts[0]) + self.elts.get(0).cmp(other.elts.get(0)) } } @@ -787,7 +787,7 @@ mod test_btree { let leaf_elt_1 = LeafElt::new(1, ~"aaa"); let leaf_elt_2 = LeafElt::new(2, ~"bbb"); let leaf_elt_3 = LeafElt::new(3, ~"ccc"); - let n = Node::new_leaf(~[leaf_elt_1, leaf_elt_2, leaf_elt_3]); + let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3)); let b = BTree::new_with_node_len(n, 3, 2); //println!("{}", b.clone().insert(4, ~"ddd").to_str()); assert!(b.insert(4, ~"ddd").root.is_leaf()); @@ -799,7 +799,7 @@ mod test_btree { let leaf_elt_2 = LeafElt::new(2, ~"bbb"); let leaf_elt_3 = LeafElt::new(3, ~"ccc"); let leaf_elt_4 = LeafElt::new(4, ~"ddd"); - let n = Node::new_leaf(~[leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4]); + let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4)); let b = BTree::new_with_node_len(n, 3, 2); //println!("{}", b.clone().insert(5, ~"eee").to_str()); assert!(!b.insert(5, ~"eee").root.is_leaf()); @@ -811,7 +811,7 @@ mod test_btree { let leaf_elt_2 = LeafElt::new(2, ~"bbb"); let leaf_elt_3 = LeafElt::new(3, ~"ccc"); let leaf_elt_4 = LeafElt::new(4, ~"ddd"); - let n = Node::new_leaf(~[leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4]); + let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4)); let mut b = BTree::new_with_node_len(n, 3, 2); b = b.clone().insert(5, ~"eee"); b = b.clone().insert(6, ~"fff"); @@ -840,7 +840,7 @@ mod test_btree { let leaf_elt_2 = LeafElt::new(2, ~"bbb"); let leaf_elt_3 = LeafElt::new(4, ~"ccc"); let leaf_elt_4 = LeafElt::new(5, ~"ddd"); - let n = Node::new_leaf(~[leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4]); + let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4)); let b = BTree::new_with_node_len(n, 3, 2); assert_eq!(Some(2), b.root.bsearch_node(3)); } @@ -851,7 +851,7 @@ mod test_btree { let leaf_elt_2 = LeafElt::new(2, ~"bbb"); let leaf_elt_3 = LeafElt::new(4, ~"ccc"); let leaf_elt_4 = LeafElt::new(5, ~"ddd"); - let n = Node::new_leaf(~[leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4]); + let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4)); let b = BTree::new_with_node_len(n, 3, 2); assert_eq!(Some(4), b.root.bsearch_node(800)); } diff --git a/src/libcollections/deque.rs b/src/libcollections/deque.rs index def8f4f356113..24d3e2c617ce8 100644 --- a/src/libcollections/deque.rs +++ b/src/libcollections/deque.rs @@ -44,7 +44,6 @@ pub mod bench { extern crate test; use self::test::BenchHarness; use std::container::MutableMap; - use std::slice; use rand; use rand::Rng; @@ -90,18 +89,18 @@ pub mod bench { bh: &mut BenchHarness) { // setup let mut rng = rand::weak_rng(); - let mut keys = slice::from_fn(n, |_| rng.gen::() % n); + let mut keys = Vec::from_fn(n, |_| rng.gen::() % n); for k in keys.iter() { map.insert(*k, 1); } - rng.shuffle(keys); + rng.shuffle(keys.as_mut_slice()); // measure let mut i = 0; bh.iter(|| { - map.find(&(keys[i])); + map.find(keys.get(i)); i = (i + 1) % n; }) } diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index 1c3a01a355d3c..3c1c7a3a88642 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -739,12 +739,12 @@ mod tests { check_links(&m); } - let v = ~[1,2,3,4,5]; - let u = ~[9,8,1,2,3,4,5]; - let mut m = list_from(v); - m.append(list_from(u)); + let v = vec![1,2,3,4,5]; + let u = vec![9,8,1,2,3,4,5]; + let mut m = list_from(v.as_slice()); + m.append(list_from(u.as_slice())); check_links(&m); - let sum = v + u; + let sum = v.append(u.as_slice()); assert_eq!(sum.len(), m.len()); for elt in sum.move_iter() { assert_eq!(m.pop_front(), Some(elt)) @@ -763,12 +763,12 @@ mod tests { check_links(&m); } - let v = ~[1,2,3,4,5]; - let u = ~[9,8,1,2,3,4,5]; - let mut m = list_from(v); - m.prepend(list_from(u)); + let v = vec![1,2,3,4,5]; + let u = vec![9,8,1,2,3,4,5]; + let mut m = list_from(v.as_slice()); + m.prepend(list_from(u.as_slice())); check_links(&m); - let sum = u + v; + let sum = u.append(v.as_slice()); assert_eq!(sum.len(), m.len()); for elt in sum.move_iter() { assert_eq!(m.pop_front(), Some(elt)) @@ -783,11 +783,11 @@ mod tests { n.rotate_forward(); check_links(&n); assert_eq!(n.len(), 0); - let v = ~[1,2,3,4,5]; - let mut m = list_from(v); + let v = vec![1,2,3,4,5]; + let mut m = list_from(v.as_slice()); m.rotate_backward(); check_links(&m); m.rotate_forward(); check_links(&m); - assert_eq!(v.iter().collect::<~[&int]>(), m.iter().collect()); + assert_eq!(v.iter().collect::>(), m.iter().collect()); m.rotate_forward(); check_links(&m); m.rotate_forward(); check_links(&m); m.pop_front(); check_links(&m); @@ -795,7 +795,7 @@ mod tests { m.rotate_backward(); check_links(&m); m.push_front(9); check_links(&m); m.rotate_forward(); check_links(&m); - assert_eq!(~[3,9,5,1,2], m.move_iter().collect()); + assert_eq!(vec![3,9,5,1,2], m.move_iter().collect()); } #[test] @@ -925,7 +925,7 @@ mod tests { } check_links(&m); assert_eq!(m.len(), 3 + len * 2); - assert_eq!(m.move_iter().collect::<~[int]>(), ~[-2,0,1,2,3,4,5,6,7,8,9,0,1]); + assert_eq!(m.move_iter().collect::>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]); } #[test] @@ -936,8 +936,8 @@ mod tests { m.merge(n, |a, b| a <= b); assert_eq!(m.len(), len); check_links(&m); - let res = m.move_iter().collect::<~[int]>(); - assert_eq!(res, ~[-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]); + let res = m.move_iter().collect::>(); + assert_eq!(res, vec![-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]); } #[test] @@ -952,7 +952,7 @@ mod tests { m.push_back(4); m.insert_ordered(3); check_links(&m); - assert_eq!(~[2,3,4], m.move_iter().collect::<~[int]>()); + assert_eq!(vec![2,3,4], m.move_iter().collect::>()); } #[test] @@ -974,7 +974,7 @@ mod tests { let n = list_from([1,2,3]); spawn(proc() { check_links(&n); - assert_eq!(~[&1,&2,&3], n.iter().collect::<~[&int]>()); + assert_eq!(&[&1,&2,&3], n.iter().collect::>().as_slice()); }); } @@ -1047,7 +1047,7 @@ mod tests { #[cfg(test)] fn fuzz_test(sz: int) { let mut m: DList = DList::new(); - let mut v = ~[]; + let mut v = vec![]; for i in range(0, sz) { check_links(&m); let r: u8 = rand::random(); diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index 83ba09ac68b6c..8249faad19a08 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -246,24 +246,24 @@ mod test { fn test_iterator() { let mut e1: EnumSet = EnumSet::empty(); - let elems: ~[Foo] = e1.iter().collect(); - assert_eq!(~[], elems) + let elems: Vec = e1.iter().collect(); + assert!(elems.is_empty()) e1.add(A); - let elems: ~[Foo] = e1.iter().collect(); - assert_eq!(~[A], elems) + let elems = e1.iter().collect(); + assert_eq!(vec![A], elems) e1.add(C); - let elems: ~[Foo] = e1.iter().collect(); - assert_eq!(~[A,C], elems) + let elems = e1.iter().collect(); + assert_eq!(vec![A,C], elems) e1.add(C); - let elems: ~[Foo] = e1.iter().collect(); - assert_eq!(~[A,C], elems) + let elems = e1.iter().collect(); + assert_eq!(vec![A,C], elems) e1.add(B); - let elems: ~[Foo] = e1.iter().collect(); - assert_eq!(~[A,B,C], elems) + let elems = e1.iter().collect(); + assert_eq!(vec![A,B,C], elems) } /////////////////////////////////////////////////////////////////////////// @@ -280,15 +280,15 @@ mod test { e2.add(C); let e_union = e1 | e2; - let elems: ~[Foo] = e_union.iter().collect(); - assert_eq!(~[A,B,C], elems) + let elems = e_union.iter().collect(); + assert_eq!(vec![A,B,C], elems) let e_intersection = e1 & e2; - let elems: ~[Foo] = e_intersection.iter().collect(); - assert_eq!(~[C], elems) + let elems = e_intersection.iter().collect(); + assert_eq!(vec![C], elems) let e_subtract = e1 - e2; - let elems: ~[Foo] = e_subtract.iter().collect(); - assert_eq!(~[A], elems) + let elems = e_subtract.iter().collect(); + assert_eq!(vec![A], elems) } } diff --git a/src/libcollections/hashmap.rs b/src/libcollections/hashmap.rs index 8090b2cea8c6e..dadf92a58e029 100644 --- a/src/libcollections/hashmap.rs +++ b/src/libcollections/hashmap.rs @@ -81,7 +81,7 @@ mod table { /// You can kind of think of this module/data structure as a safe wrapper /// around just the "table" part of the hashtable. It enforces some /// invariants at the type level and employs some performance trickery, - /// but in general is just a tricked out `~[Option]`. + /// but in general is just a tricked out `Vec>`. /// /// FIXME(cgaebel): /// @@ -1833,8 +1833,8 @@ mod test_map { hm }; - let v = hm.move_iter().collect::<~[(char, int)]>(); - assert!([('a', 1), ('b', 2)] == v || [('b', 2), ('a', 1)] == v); + let v = hm.move_iter().collect::>(); + assert!([('a', 1), ('b', 2)] == v.as_slice() || [('b', 2), ('a', 1)] == v.as_slice()); } #[test] @@ -1856,9 +1856,9 @@ mod test_map { #[test] fn test_keys() { - let vec = ~[(1, 'a'), (2, 'b'), (3, 'c')]; + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; let map = vec.move_iter().collect::>(); - let keys = map.keys().map(|&k| k).collect::<~[int]>(); + let keys = map.keys().map(|&k| k).collect::>(); assert_eq!(keys.len(), 3); assert!(keys.contains(&1)); assert!(keys.contains(&2)); @@ -1867,9 +1867,9 @@ mod test_map { #[test] fn test_values() { - let vec = ~[(1, 'a'), (2, 'b'), (3, 'c')]; + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; let map = vec.move_iter().collect::>(); - let values = map.values().map(|&v| v).collect::<~[char]>(); + let values = map.values().map(|&v| v).collect::>(); assert_eq!(values.len(), 3); assert!(values.contains(&'a')); assert!(values.contains(&'b')); @@ -1942,7 +1942,7 @@ mod test_map { #[test] fn test_from_iter() { - let xs = ~[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; + let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; let map: HashMap = xs.iter().map(|&x| x).collect(); @@ -2133,7 +2133,7 @@ mod test_set { #[test] fn test_from_iter() { - let xs = ~[1, 2, 3, 4, 5, 6, 7, 8, 9]; + let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let set: HashSet = xs.iter().map(|&x| x).collect(); @@ -2153,8 +2153,8 @@ mod test_set { hs }; - let v = hs.move_iter().collect::<~[char]>(); - assert!(['a', 'b'] == v || ['b', 'a'] == v); + let v = hs.move_iter().collect::>(); + assert!(['a', 'b'] == v.as_slice() || ['b', 'a'] == v.as_slice()); } #[test] diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index ef5289ae373d8..2121e129c3523 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -22,6 +22,8 @@ #![feature(macro_rules, managed_boxes, default_type_params, phase)] +#![deny(deprecated_owned_vector)] + extern crate rand; #[cfg(test)] extern crate test; diff --git a/src/libcollections/lru_cache.rs b/src/libcollections/lru_cache.rs index bd40d18394555..87b1fee1d27d9 100644 --- a/src/libcollections/lru_cache.rs +++ b/src/libcollections/lru_cache.rs @@ -294,10 +294,10 @@ mod tests { #[test] fn test_put_update() { - let mut cache: LruCache<~str, ~[u8]> = LruCache::new(1); - cache.put(~"1", ~[10, 10]); - cache.put(~"1", ~[10, 19]); - assert_opt_eq(cache.get(&~"1"), ~[10, 19]); + let mut cache: LruCache<~str, Vec> = LruCache::new(1); + cache.put(~"1", vec![10, 10]); + cache.put(~"1", vec![10, 19]); + assert_opt_eq(cache.get(&~"1"), vec![10, 19]); assert_eq!(cache.len(), 1); } diff --git a/src/libcollections/priority_queue.rs b/src/libcollections/priority_queue.rs index a13785104abd5..2ebbf65b9e5d1 100644 --- a/src/libcollections/priority_queue.rs +++ b/src/libcollections/priority_queue.rs @@ -19,7 +19,7 @@ use std::slice; /// A priority queue implemented with a binary heap #[deriving(Clone)] pub struct PriorityQueue { - data: ~[T], + data: Vec, } impl Container for PriorityQueue { @@ -40,7 +40,7 @@ impl PriorityQueue { } /// Returns the greatest item in the queue - fails if empty - pub fn top<'a>(&'a self) -> &'a T { &self.data[0] } + pub fn top<'a>(&'a self) -> &'a T { self.data.get(0) } /// Returns the greatest item in the queue - None if empty pub fn maybe_top<'a>(&'a self) -> Option<&'a T> { @@ -64,7 +64,7 @@ impl PriorityQueue { pub fn pop(&mut self) -> T { let mut item = self.data.pop().unwrap(); if !self.is_empty() { - swap(&mut item, &mut self.data[0]); + swap(&mut item, self.data.get_mut(0)); self.siftdown(0); } item @@ -84,8 +84,8 @@ impl PriorityQueue { /// Optimized version of a push followed by a pop pub fn push_pop(&mut self, mut item: T) -> T { - if !self.is_empty() && self.data[0] > item { - swap(&mut item, &mut self.data[0]); + if !self.is_empty() && *self.top() > item { + swap(&mut item, self.data.get_mut(0)); self.siftdown(0); } item @@ -93,37 +93,37 @@ impl PriorityQueue { /// Optimized version of a pop followed by a push - fails if empty pub fn replace(&mut self, mut item: T) -> T { - swap(&mut item, &mut self.data[0]); + swap(&mut item, self.data.get_mut(0)); self.siftdown(0); item } /// Consume the PriorityQueue and return the underlying vector - pub fn to_vec(self) -> ~[T] { let PriorityQueue{data: v} = self; v } + pub fn to_vec(self) -> Vec { let PriorityQueue{data: v} = self; v } /// Consume the PriorityQueue and return a vector in sorted /// (ascending) order - pub fn to_sorted_vec(self) -> ~[T] { + pub fn to_sorted_vec(self) -> Vec { let mut q = self; let mut end = q.len(); while end > 1 { end -= 1; - q.data.swap(0, end); + q.data.as_mut_slice().swap(0, end); q.siftdown_range(0, end) } q.to_vec() } /// Create an empty PriorityQueue - pub fn new() -> PriorityQueue { PriorityQueue{data: ~[],} } + pub fn new() -> PriorityQueue { PriorityQueue{data: vec!(),} } /// Create an empty PriorityQueue with capacity `capacity` pub fn with_capacity(capacity: uint) -> PriorityQueue { - PriorityQueue { data: slice::with_capacity(capacity) } + PriorityQueue { data: Vec::with_capacity(capacity) } } /// Create a PriorityQueue from a vector (heapify) - pub fn from_vec(xs: ~[T]) -> PriorityQueue { + pub fn from_vec(xs: Vec) -> PriorityQueue { let mut q = PriorityQueue{data: xs,}; let mut n = q.len() / 2; while n > 0 { @@ -140,40 +140,40 @@ impl PriorityQueue { // compared to using swaps, which involves twice as many moves. fn siftup(&mut self, start: uint, mut pos: uint) { unsafe { - let new = replace(&mut self.data[pos], init()); + let new = replace(self.data.get_mut(pos), init()); while pos > start { let parent = (pos - 1) >> 1; - if new > self.data[parent] { - let x = replace(&mut self.data[parent], init()); - move_val_init(&mut self.data[pos], x); + if new > *self.data.get(parent) { + let x = replace(self.data.get_mut(parent), init()); + move_val_init(self.data.get_mut(pos), x); pos = parent; continue } break } - move_val_init(&mut self.data[pos], new); + move_val_init(self.data.get_mut(pos), new); } } fn siftdown_range(&mut self, mut pos: uint, end: uint) { unsafe { let start = pos; - let new = replace(&mut self.data[pos], init()); + let new = replace(self.data.get_mut(pos), init()); let mut child = 2 * pos + 1; while child < end { let right = child + 1; - if right < end && !(self.data[child] > self.data[right]) { + if right < end && !(*self.data.get(child) > *self.data.get(right)) { child = right; } - let x = replace(&mut self.data[child], init()); - move_val_init(&mut self.data[pos], x); + let x = replace(self.data.get_mut(child), init()); + move_val_init(self.data.get_mut(pos), x); pos = child; child = 2 * pos + 1; } - move_val_init(&mut self.data[pos], new); + move_val_init(self.data.get_mut(pos), new); self.siftup(start, pos); } } @@ -224,8 +224,8 @@ mod tests { #[test] fn test_iterator() { - let data = ~[5, 9, 3]; - let iterout = ~[9, 5, 3]; + let data = vec!(5, 9, 3); + let iterout = [9, 5, 3]; let pq = PriorityQueue::from_vec(data); let mut i = 0; for el in pq.iter() { @@ -236,7 +236,7 @@ mod tests { #[test] fn test_top_and_pop() { - let data = ~[2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1]; + let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1); let mut sorted = data.clone(); sorted.sort(); let mut heap = PriorityQueue::from_vec(data); @@ -248,7 +248,7 @@ mod tests { #[test] fn test_push() { - let mut heap = PriorityQueue::from_vec(~[2, 4, 9]); + let mut heap = PriorityQueue::from_vec(vec!(2, 4, 9)); assert_eq!(heap.len(), 3); assert!(*heap.top() == 9); heap.push(11); @@ -270,7 +270,7 @@ mod tests { #[test] fn test_push_unique() { - let mut heap = PriorityQueue::from_vec(~[~2, ~4, ~9]); + let mut heap = PriorityQueue::from_vec(vec!(~2, ~4, ~9)); assert_eq!(heap.len(), 3); assert!(*heap.top() == ~9); heap.push(~11); @@ -292,7 +292,7 @@ mod tests { #[test] fn test_push_pop() { - let mut heap = PriorityQueue::from_vec(~[5, 5, 2, 1, 3]); + let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3)); assert_eq!(heap.len(), 5); assert_eq!(heap.push_pop(6), 6); assert_eq!(heap.len(), 5); @@ -306,7 +306,7 @@ mod tests { #[test] fn test_replace() { - let mut heap = PriorityQueue::from_vec(~[5, 5, 2, 1, 3]); + let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3)); assert_eq!(heap.len(), 5); assert_eq!(heap.replace(6), 5); assert_eq!(heap.len(), 5); @@ -318,7 +318,7 @@ mod tests { assert_eq!(heap.len(), 5); } - fn check_to_vec(mut data: ~[int]) { + fn check_to_vec(mut data: Vec) { let heap = PriorityQueue::from_vec(data.clone()); let mut v = heap.clone().to_vec(); v.sort(); @@ -330,19 +330,19 @@ mod tests { #[test] fn test_to_vec() { - check_to_vec(~[]); - check_to_vec(~[5]); - check_to_vec(~[3, 2]); - check_to_vec(~[2, 3]); - check_to_vec(~[5, 1, 2]); - check_to_vec(~[1, 100, 2, 3]); - check_to_vec(~[1, 3, 5, 7, 9, 2, 4, 6, 8, 0]); - check_to_vec(~[2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1]); - check_to_vec(~[9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0]); - check_to_vec(~[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); - check_to_vec(~[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]); - check_to_vec(~[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2]); - check_to_vec(~[5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]); + check_to_vec(vec!()); + check_to_vec(vec!(5)); + check_to_vec(vec!(3, 2)); + check_to_vec(vec!(2, 3)); + check_to_vec(vec!(5, 1, 2)); + check_to_vec(vec!(1, 100, 2, 3)); + check_to_vec(vec!(1, 3, 5, 7, 9, 2, 4, 6, 8, 0)); + check_to_vec(vec!(2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1)); + check_to_vec(vec!(9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0)); + check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); + check_to_vec(vec!(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)); + check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2)); + check_to_vec(vec!(5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1)); } #[test] @@ -380,9 +380,9 @@ mod tests { #[test] fn test_from_iter() { - let xs = ~[9u, 8, 7, 6, 5, 4, 3, 2, 1]; + let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1); - let mut q: PriorityQueue = xs.rev_iter().map(|&x| x).collect(); + let mut q: PriorityQueue = xs.as_slice().rev_iter().map(|&x| x).collect(); for &x in xs.iter() { assert_eq!(q.pop(), x); diff --git a/src/libcollections/ringbuf.rs b/src/libcollections/ringbuf.rs index 705e0f7d3d486..c61fcd0c76bbd 100644 --- a/src/libcollections/ringbuf.rs +++ b/src/libcollections/ringbuf.rs @@ -14,7 +14,6 @@ //! collections::deque::Deque`. use std::cmp; -use std::slice; use std::iter::{Rev, RandomAccessIterator}; use deque::Deque; @@ -27,7 +26,7 @@ static MINIMUM_CAPACITY: uint = 2u; pub struct RingBuf { nelts: uint, lo: uint, - elts: ~[Option] + elts: Vec> } impl Container for RingBuf { @@ -67,7 +66,7 @@ impl Deque for RingBuf { /// Remove and return the first element in the RingBuf, or None if it is empty fn pop_front(&mut self) -> Option { - let result = self.elts[self.lo].take(); + let result = self.elts.get_mut(self.lo).take(); if result.is_some() { self.lo = (self.lo + 1u) % self.elts.len(); self.nelts -= 1u; @@ -80,7 +79,7 @@ impl Deque for RingBuf { if self.nelts > 0 { self.nelts -= 1; let hi = self.raw_index(self.nelts); - self.elts[hi].take() + self.elts.get_mut(hi).take() } else { None } @@ -94,7 +93,7 @@ impl Deque for RingBuf { if self.lo == 0u { self.lo = self.elts.len() - 1u; } else { self.lo -= 1u; } - self.elts[self.lo] = Some(t); + *self.elts.get_mut(self.lo) = Some(t); self.nelts += 1u; } @@ -104,7 +103,7 @@ impl Deque for RingBuf { grow(self.nelts, &mut self.lo, &mut self.elts); } let hi = self.raw_index(self.nelts); - self.elts[hi] = Some(t); + *self.elts.get_mut(hi) = Some(t); self.nelts += 1u; } } @@ -118,7 +117,7 @@ impl RingBuf { /// Create an empty RingBuf with space for at least `n` elements. pub fn with_capacity(n: uint) -> RingBuf { RingBuf{nelts: 0, lo: 0, - elts: slice::from_fn(cmp::max(MINIMUM_CAPACITY, n), |_| None)} + elts: Vec::from_fn(cmp::max(MINIMUM_CAPACITY, n), |_| None)} } /// Retrieve an element in the RingBuf by index @@ -126,7 +125,7 @@ impl RingBuf { /// Fails if there is no element with the given index pub fn get<'a>(&'a self, i: uint) -> &'a T { let idx = self.raw_index(i); - match self.elts[idx] { + match *self.elts.get(idx) { None => fail!(), Some(ref v) => v } @@ -137,7 +136,7 @@ impl RingBuf { /// Fails if there is no element with the given index pub fn get_mut<'a>(&'a mut self, i: uint) -> &'a mut T { let idx = self.raw_index(i); - match self.elts[idx] { + match *self.elts.get_mut(idx) { None => fail!(), Some(ref mut v) => v } @@ -153,7 +152,7 @@ impl RingBuf { assert!(j < self.len()); let ri = self.raw_index(i); let rj = self.raw_index(j); - self.elts.swap(ri, rj); + self.elts.as_mut_slice().swap(ri, rj); } /// Return index in underlying vec for a given logical element index @@ -188,7 +187,7 @@ impl RingBuf { /// Front-to-back iterator. pub fn iter<'a>(&'a self) -> Items<'a, T> { - Items{index: 0, rindex: self.nelts, lo: self.lo, elts: self.elts} + Items{index: 0, rindex: self.nelts, lo: self.lo, elts: self.elts.as_slice()} } /// Back-to-front iterator. @@ -333,7 +332,7 @@ impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {} /// Grow is only called on full elts, so nelts is also len(elts), unlike /// elsewhere. -fn grow(nelts: uint, loptr: &mut uint, elts: &mut ~[Option]) { +fn grow(nelts: uint, loptr: &mut uint, elts: &mut Vec>) { assert_eq!(nelts, elts.len()); let lo = *loptr; let newlen = nelts * 2; @@ -356,11 +355,11 @@ fn grow(nelts: uint, loptr: &mut uint, elts: &mut ~[Option]) { assert!(newlen - nelts/2 >= nelts); if lo <= (nelts - lo) { // A for i in range(0u, lo) { - elts.swap(i, nelts + i); + elts.as_mut_slice().swap(i, nelts + i); } } else { // B for i in range(lo, nelts) { - elts.swap(i, newlen - nelts + i); + elts.as_mut_slice().swap(i, newlen - nelts + i); } *loptr += newlen - nelts; } @@ -671,7 +670,7 @@ mod tests { let mut d: RingBuf = range(0, 5).collect(); d.pop_front(); d.swap(0, 3); - assert_eq!(d.iter().map(|&x|x).collect::<~[int]>(), ~[4, 2, 3, 1]); + assert_eq!(d.iter().map(|&x|x).collect::>(), vec!(4, 2, 3, 1)); } #[test] @@ -683,12 +682,12 @@ mod tests { for i in range(0, 5) { d.push_back(i); } - assert_eq!(d.iter().collect::<~[&int]>(), ~[&0,&1,&2,&3,&4]); + assert_eq!(d.iter().collect::>().as_slice(), &[&0,&1,&2,&3,&4]); for i in range(6, 9) { d.push_front(i); } - assert_eq!(d.iter().collect::<~[&int]>(), ~[&8,&7,&6,&0,&1,&2,&3,&4]); + assert_eq!(d.iter().collect::>().as_slice(), &[&8,&7,&6,&0,&1,&2,&3,&4]); let mut it = d.iter(); let mut len = d.len(); @@ -708,12 +707,12 @@ mod tests { for i in range(0, 5) { d.push_back(i); } - assert_eq!(d.rev_iter().collect::<~[&int]>(), ~[&4,&3,&2,&1,&0]); + assert_eq!(d.rev_iter().collect::>().as_slice(), &[&4,&3,&2,&1,&0]); for i in range(6, 9) { d.push_front(i); } - assert_eq!(d.rev_iter().collect::<~[&int]>(), ~[&4,&3,&2,&1,&0,&6,&7,&8]); + assert_eq!(d.rev_iter().collect::>().as_slice(), &[&4,&3,&2,&1,&0,&6,&7,&8]); } #[test] @@ -727,8 +726,8 @@ mod tests { assert_eq!(d.pop_front(), Some(1)); d.push_back(4); - assert_eq!(d.mut_rev_iter().map(|x| *x).collect::<~[int]>(), - ~[4, 3, 2]); + assert_eq!(d.mut_rev_iter().map(|x| *x).collect::>(), + vec!(4, 3, 2)); } #[test] @@ -780,9 +779,9 @@ mod tests { #[test] fn test_from_iter() { use std::iter; - let v = ~[1,2,3,4,5,6,7]; + let v = vec!(1,2,3,4,5,6,7); let deq: RingBuf = v.iter().map(|&x| x).collect(); - let u: ~[int] = deq.iter().map(|&x| x).collect(); + let u: Vec = deq.iter().map(|&x| x).collect(); assert_eq!(u, v); let mut seq = iter::count(0u, 2).take(256); diff --git a/src/libcollections/smallintmap.rs b/src/libcollections/smallintmap.rs index bd4f85aa81a78..4485987b15b40 100644 --- a/src/libcollections/smallintmap.rs +++ b/src/libcollections/smallintmap.rs @@ -17,11 +17,11 @@ use std::iter::{Enumerate, FilterMap, Rev}; use std::mem::replace; -use std::slice; +use std::{vec, slice}; #[allow(missing_doc)] pub struct SmallIntMap { - v: ~[Option], + v: Vec>, } impl Container for SmallIntMap { @@ -45,7 +45,7 @@ impl Map for SmallIntMap { /// Return a reference to the value corresponding to the key fn find<'a>(&'a self, key: &uint) -> Option<&'a V> { if *key < self.v.len() { - match self.v[*key] { + match *self.v.get(*key) { Some(ref value) => Some(value), None => None } @@ -59,7 +59,7 @@ impl MutableMap for SmallIntMap { /// Return a mutable reference to the value corresponding to the key fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> { if *key < self.v.len() { - match self.v[*key] { + match *self.v.get_mut(*key) { Some(ref mut value) => Some(value), None => None } @@ -77,7 +77,7 @@ impl MutableMap for SmallIntMap { if len <= key { self.v.grow_fn(key - len + 1, |_| None); } - self.v[key] = Some(value); + *self.v.get_mut(key) = Some(value); !exists } @@ -104,17 +104,17 @@ impl MutableMap for SmallIntMap { if *key >= self.v.len() { return None; } - self.v[*key].take() + self.v.get_mut(*key).take() } } impl SmallIntMap { /// Create an empty SmallIntMap - pub fn new() -> SmallIntMap { SmallIntMap{v: ~[]} } + pub fn new() -> SmallIntMap { SmallIntMap{v: vec!()} } /// Create an empty SmallIntMap with capacity `capacity` pub fn with_capacity(capacity: uint) -> SmallIntMap { - SmallIntMap { v: slice::with_capacity(capacity) } + SmallIntMap { v: Vec::with_capacity(capacity) } } pub fn get<'a>(&'a self, key: &uint) -> &'a V { @@ -158,9 +158,9 @@ impl SmallIntMap { /// Empties the hash map, moving all values into the specified closure pub fn move_iter(&mut self) -> FilterMap<(uint, Option), (uint, V), - Enumerate>>> + Enumerate>>> { - let values = replace(&mut self.v, ~[]); + let values = replace(&mut self.v, vec!()); values.move_iter().enumerate().filter_map(|(i, v)| { v.map(|v| (i, v)) }) diff --git a/src/libcollections/treemap.rs b/src/libcollections/treemap.rs index 0a5e653f8ebd6..1846ca0013e86 100644 --- a/src/libcollections/treemap.rs +++ b/src/libcollections/treemap.rs @@ -139,7 +139,7 @@ impl TreeMap { /// Requires that it be frozen (immutable). pub fn iter<'a>(&'a self) -> Entries<'a, K, V> { Entries { - stack: ~[], + stack: vec!(), node: deref(&self.root), remaining_min: self.length, remaining_max: self.length @@ -156,7 +156,7 @@ impl TreeMap { /// map, with the values being mutable. pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, K, V> { MutEntries { - stack: ~[], + stack: vec!(), node: mut_deref(&mut self.root), remaining_min: self.length, remaining_max: self.length @@ -173,8 +173,8 @@ impl TreeMap { pub fn move_iter(self) -> MoveEntries { let TreeMap { root: root, length: length } = self; let stk = match root { - None => ~[], - Some(~tn) => ~[tn] + None => vec!(), + Some(~tn) => vec!(tn) }; MoveEntries { stack: stk, @@ -222,7 +222,7 @@ impl TreeMap { /// `traverse_left`/`traverse_right`/`traverse_complete`. fn iter_for_traversal<'a>(&'a self) -> Entries<'a, K, V> { Entries { - stack: ~[], + stack: vec!(), node: deref(&self.root), remaining_min: 0, remaining_max: self.length @@ -245,7 +245,7 @@ impl TreeMap { /// `traverse_left`/`traverse_right`/`traverse_complete`. fn mut_iter_for_traversal<'a>(&'a mut self) -> MutEntries<'a, K, V> { MutEntries { - stack: ~[], + stack: vec!(), node: mut_deref(&mut self.root), remaining_min: 0, remaining_max: self.length @@ -273,7 +273,7 @@ impl TreeMap { /// Lazy forward iterator over a map pub struct Entries<'a, K, V> { - stack: ~[&'a TreeNode], + stack: Vec<&'a TreeNode>, // See the comment on MutEntries; this is just to allow // code-sharing (for this immutable-values iterator it *could* very // well be Option<&'a TreeNode>). @@ -290,7 +290,7 @@ pub struct RevEntries<'a, K, V> { /// Lazy forward iterator over a map that allows for the mutation of /// the values. pub struct MutEntries<'a, K, V> { - stack: ~[&'a mut TreeNode], + stack: Vec<&'a mut TreeNode>, // Unfortunately, we require some unsafe-ness to get around the // fact that we would be storing a reference *into* one of the // nodes in the stack. @@ -482,7 +482,7 @@ fn mut_deref(x: &mut Option<~TreeNode>) -> *mut TreeNode { /// Lazy forward iterator over a map that consumes the map while iterating pub struct MoveEntries { - stack: ~[TreeNode], + stack: Vec>, remaining: uint } @@ -1143,9 +1143,9 @@ mod test_treemap { #[test] fn test_rand_int() { let mut map: TreeMap = TreeMap::new(); - let mut ctrl = ~[]; + let mut ctrl = vec![]; - check_equal(ctrl, &map); + check_equal(ctrl.as_slice(), &map); assert!(map.find(&5).is_none()); let mut rng: rand::IsaacRng = rand::SeedableRng::from_seed(&[42]); @@ -1158,7 +1158,7 @@ mod test_treemap { assert!(map.insert(k, v)); ctrl.push((k, v)); check_structure(&map); - check_equal(ctrl, &map); + check_equal(ctrl.as_slice(), &map); } } @@ -1167,7 +1167,7 @@ mod test_treemap { let (key, _) = ctrl.remove(r).unwrap(); assert!(map.remove(&key)); check_structure(&map); - check_equal(ctrl, &map); + check_equal(ctrl.as_slice(), &map); } } } @@ -1414,7 +1414,7 @@ mod test_treemap { #[test] fn test_from_iter() { - let xs = ~[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; + let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; let map: TreeMap = xs.iter().map(|&x| x).collect(); @@ -1725,7 +1725,7 @@ mod test_set { #[test] fn test_from_iter() { - let xs = ~[1, 2, 3, 4, 5, 6, 7, 8, 9]; + let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let set: TreeSet = xs.iter().map(|&x| x).collect(); diff --git a/src/libcollections/trie.rs b/src/libcollections/trie.rs index 8b83e65838697..5c290d56da39a 100644 --- a/src/libcollections/trie.rs +++ b/src/libcollections/trie.rs @@ -774,7 +774,7 @@ mod test_map { #[test] fn test_from_iter() { - let xs = ~[(1u, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; + let xs = vec![(1u, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; let map: TrieMap = xs.iter().map(|&x| x).collect(); @@ -1042,7 +1042,7 @@ mod test_set { #[test] fn test_from_iter() { - let xs = ~[9u, 8, 7, 6, 5, 4, 3, 2, 1]; + let xs = vec![9u, 8, 7, 6, 5, 4, 3, 2, 1]; let set: TrieSet = xs.iter().map(|&x| x).collect(); From 43e8ace76b01820032679f276f3e298b92288ad6 Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Thu, 27 Mar 2014 13:43:01 +0100 Subject: [PATCH 03/28] debuginfo: Improve source code position assignment for inlined functions. This commit makes sure that code inlined from other functions isn't assigned the source position of the call site, since this leads to undesired behavior when setting line breakpoints (issue #12886) --- src/librustc/middle/trans/debuginfo.rs | 36 +++++++++++++++----------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 8a7f30ee2c42d..6f6484ae1a596 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -533,21 +533,26 @@ pub fn create_argument_metadata(bcx: &Block, arg: &ast::Arg) { pub fn set_source_location(fcx: &FunctionContext, node_id: ast::NodeId, span: Span) { - if fn_should_be_ignored(fcx) { - return; - } - - let cx = fcx.ccx; + match fcx.debug_context { + DebugInfoDisabled => return, + FunctionWithoutDebugInfo => { + set_debug_location(fcx.ccx, UnknownLocation); + return; + } + FunctionDebugContext(~ref function_debug_context) => { + let cx = fcx.ccx; - debug!("set_source_location: {}", cx.sess().codemap().span_to_str(span)); + debug!("set_source_location: {}", cx.sess().codemap().span_to_str(span)); - if fcx.debug_context.get_ref(cx, span).source_locations_enabled.get() { - let loc = span_start(cx, span); - let scope = scope_metadata(fcx, node_id, span); + if function_debug_context.source_locations_enabled.get() { + let loc = span_start(cx, span); + let scope = scope_metadata(fcx, node_id, span); - set_debug_location(cx, DebugLocation::new(scope, loc.line, loc.col.to_uint())); - } else { - set_debug_location(cx, UnknownLocation); + set_debug_location(cx, DebugLocation::new(scope, loc.line, loc.col.to_uint())); + } else { + set_debug_location(cx, UnknownLocation); + } + } } } @@ -590,6 +595,10 @@ pub fn create_function_debug_context(cx: &CrateContext, return DebugInfoDisabled; } + // Clear the debug location so we don't assign them in the function prelude. Do this here + // already, in case we do an early exit from this function. + set_debug_location(cx, UnknownLocation); + if fn_ast_id == -1 { return FunctionWithoutDebugInfo; } @@ -740,9 +749,6 @@ pub fn create_function_debug_context(cx: &CrateContext, fn_metadata, &mut *fn_debug_context.scope_map.borrow_mut()); - // Clear the debug location so we don't assign them in the function prelude - set_debug_location(cx, UnknownLocation); - return FunctionDebugContext(fn_debug_context); fn get_function_signature(cx: &CrateContext, From c26d25466d93cefea6cf81ec3f0e64200a7150be Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Thu, 27 Mar 2014 15:47:13 +0100 Subject: [PATCH 04/28] debuginfo: Implement discriminator type metadata re-use. An optimization for sharing the type metadata of generic enum discriminators between monomorphized instances (fixes issue #12840) --- src/librustc/middle/trans/debuginfo.rs | 68 +++++++++++++++++++------- 1 file changed, 51 insertions(+), 17 deletions(-) diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 6f6484ae1a596..c2828b333edd1 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -130,6 +130,7 @@ use driver::session::{FullDebugInfo, LimitedDebugInfo, NoDebugInfo}; use lib::llvm::llvm; use lib::llvm::{ModuleRef, ContextRef, ValueRef}; use lib::llvm::debuginfo::*; +use metadata::csearch; use middle::trans::adt; use middle::trans::common::*; use middle::trans::datum::{Datum, Lvalue}; @@ -178,6 +179,7 @@ pub struct CrateDebugContext { current_debug_location: Cell, created_files: RefCell>, created_types: RefCell>, + created_enum_disr_types: RefCell>, namespace_map: RefCell , @NamespaceTreeNode>>, // This collection is used to assert that composite types (structs, enums, ...) have their // members only set once: @@ -196,6 +198,7 @@ impl CrateDebugContext { current_debug_location: Cell::new(UnknownLocation), created_files: RefCell::new(HashMap::new()), created_types: RefCell::new(HashMap::new()), + created_enum_disr_types: RefCell::new(HashMap::new()), namespace_map: RefCell::new(HashMap::new()), composite_types_completed: RefCell::new(HashSet::new()), }; @@ -1542,24 +1545,45 @@ fn prepare_enum_metadata(cx: &CrateContext, .collect(); let discriminant_type_metadata = |inttype| { - let discriminant_llvm_type = adt::ll_inttype(cx, inttype); - let (discriminant_size, discriminant_align) = size_and_align_of(cx, discriminant_llvm_type); - let discriminant_base_type_metadata = type_metadata(cx, adt::ty_of_inttype(inttype), - codemap::DUMMY_SP); - enum_name.with_c_str(|enum_name| { - unsafe { - llvm::LLVMDIBuilderCreateEnumerationType( - DIB(cx), - containing_scope, - enum_name, - file_metadata, - loc.line as c_uint, - bytes_to_bits(discriminant_size), - bytes_to_bits(discriminant_align), - create_DIArray(DIB(cx), enumerators_metadata.as_slice()), - discriminant_base_type_metadata) + // We can reuse the type of the discriminant for all monomorphized instances of an enum + // because it doesn't depend on any type parameters. The def_id, uniquely identifying the + // enum's polytype acts as key in this cache. + let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types + .borrow() + .find_copy(&enum_def_id); + match cached_discriminant_type_metadata { + Some(discriminant_type_metadata) => discriminant_type_metadata, + None => { + let discriminant_llvm_type = adt::ll_inttype(cx, inttype); + let (discriminant_size, discriminant_align) = + size_and_align_of(cx, discriminant_llvm_type); + let discriminant_base_type_metadata = type_metadata(cx, + adt::ty_of_inttype(inttype), + codemap::DUMMY_SP); + let discriminant_name = get_enum_discriminant_name(cx, enum_def_id); + + let discriminant_type_metadata = discriminant_name.get().with_c_str(|name| { + unsafe { + llvm::LLVMDIBuilderCreateEnumerationType( + DIB(cx), + containing_scope, + name, + file_metadata, + loc.line as c_uint, + bytes_to_bits(discriminant_size), + bytes_to_bits(discriminant_align), + create_DIArray(DIB(cx), enumerators_metadata.as_slice()), + discriminant_base_type_metadata) + } + }); + + debug_context(cx).created_enum_disr_types + .borrow_mut() + .insert(enum_def_id, discriminant_type_metadata); + + discriminant_type_metadata } - }) + } }; let type_rep = adt::represent_type(cx, enum_type); @@ -1648,6 +1672,16 @@ fn prepare_enum_metadata(cx: &CrateContext, } } }; + + fn get_enum_discriminant_name(cx: &CrateContext, def_id: ast::DefId) -> token::InternedString { + let name = if def_id.krate == ast::LOCAL_CRATE { + cx.tcx.map.get_path_elem(def_id.node).name() + } else { + csearch::get_item_path(&cx.tcx, def_id).last().unwrap().name() + }; + + token::get_name(name) + } } enum MemberOffset { From 5099b8c863150675450631347436b7d220f4efd3 Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Thu, 10 Apr 2014 10:25:13 +0200 Subject: [PATCH 05/28] debuginfo: Don't create debuginfo for statics inlined from other crates. Fixes issue #13213, that is linker errors when the inlined static has been optimized out of the exporting crate. --- src/librustc/middle/trans/debuginfo.rs | 7 +++++++ src/test/auxiliary/issue13213aux.rs | 27 ++++++++++++++++++++++++++ src/test/debug-info/issue13213.rs | 26 +++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 src/test/auxiliary/issue13213aux.rs create mode 100644 src/test/debug-info/issue13213.rs diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index c2828b333edd1..8ea2065509bb8 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -293,6 +293,13 @@ pub fn create_global_var_metadata(cx: &CrateContext, return; } + // Don't create debuginfo for globals inlined from other crates. The other crate should already + // contain debuginfo for it. More importantly, the global might not even exist in un-inlined + // form anywhere which would lead to a linker errors. + if cx.external_srcs.borrow().contains_key(&node_id) { + return; + } + let var_item = cx.tcx.map.get(node_id); let (ident, span) = match var_item { diff --git a/src/test/auxiliary/issue13213aux.rs b/src/test/auxiliary/issue13213aux.rs new file mode 100644 index 0000000000000..23cf49fb1d8da --- /dev/null +++ b/src/test/auxiliary/issue13213aux.rs @@ -0,0 +1,27 @@ +// Copyright 2013-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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![crate_type = "lib"] +// compile-flags:-g + +pub use private::P; + +pub struct S { + p: P, +} + +mod private { + pub struct P { + p: i32, + } + pub static THREE: P = P { p: 3 }; +} + +pub static A: S = S { p: private::THREE }; \ No newline at end of file diff --git a/src/test/debug-info/issue13213.rs b/src/test/debug-info/issue13213.rs new file mode 100644 index 0000000000000..e60643eb3f402 --- /dev/null +++ b/src/test/debug-info/issue13213.rs @@ -0,0 +1,26 @@ +// Copyright 2013-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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// ignore-android: FIXME(#10381) + +// aux-build:issue13213aux.rs +extern crate issue13213aux; + +// compile-flags:-g + +// This tests make sure that we get no linker error when using a completely inlined static. Some +// statics that are marked with AvailableExternallyLinkage in the importing crate, may actually not +// be available because they have been optimized out from the exporting crate. +fn main() { + let b: issue13213aux::S = issue13213aux::A; + zzz(); +} + +fn zzz() {()} \ No newline at end of file From 81350327790fa7bfacb7c32603ca61eb0004b5b2 Mon Sep 17 00:00:00 2001 From: Kevin Ballard Date: Wed, 9 Apr 2014 12:24:12 -0700 Subject: [PATCH 06/28] Remove references to @Trait from a compiler error message --- src/librustc/middle/typeck/astconv.rs | 5 ++--- src/test/compile-fail/issue-5883.rs | 8 +++++--- src/test/compile-fail/regions-trait-2.rs | 2 +- src/test/compile-fail/trait-bounds-not-on-bare-trait.rs | 3 ++- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc/middle/typeck/astconv.rs index 82be783616888..2119419e0b1e5 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc/middle/typeck/astconv.rs @@ -572,9 +572,8 @@ pub fn ast_ty_to_ty( let path_str = path_to_str(path); tcx.sess.span_err( ast_ty.span, - format!("reference to trait `{}` where a type is expected; \ - try `@{}`, `~{}`, or `&{}`", - path_str, path_str, path_str, path_str)); + format!("reference to trait `{name}` where a type is expected; \ + try `~{name}` or `&{name}`", name=path_str)); ty::mk_err() } ast::DefTy(did) | ast::DefStruct(did) => { diff --git a/src/test/compile-fail/issue-5883.rs b/src/test/compile-fail/issue-5883.rs index 621510cea99e4..5a7eb75d90d4c 100644 --- a/src/test/compile-fail/issue-5883.rs +++ b/src/test/compile-fail/issue-5883.rs @@ -11,13 +11,15 @@ trait A {} struct Struct { - r: A //~ ERROR reference to trait `A` where a type is expected + r: A //~ ERROR reference to trait `A` where a type is expected; try `~A` or `&A` } -fn new_struct(r: A) -> Struct { //~ ERROR reference to trait `A` where a type is expected +fn new_struct(r: A) -> Struct { + //~^ ERROR reference to trait `A` where a type is expected; try `~A` or `&A` Struct { r: r } } trait Curve {} -enum E {X(Curve)} //~ ERROR reference to trait `Curve` where a type is expected +enum E {X(Curve)} +//~^ ERROR reference to trait `Curve` where a type is expected; try `~Curve` or `&Curve` fn main() {} diff --git a/src/test/compile-fail/regions-trait-2.rs b/src/test/compile-fail/regions-trait-2.rs index 5b1f6b241d25c..92c1849c15b83 100644 --- a/src/test/compile-fail/regions-trait-2.rs +++ b/src/test/compile-fail/regions-trait-2.rs @@ -29,7 +29,7 @@ fn make_gc() -> @get_ctxt { let ctxt = ctxt { v: 22u }; let hc = has_ctxt { c: &ctxt }; return @hc as @get_ctxt; - //^~ ERROR source contains reference + //~^ ERROR source contains reference } fn main() { diff --git a/src/test/compile-fail/trait-bounds-not-on-bare-trait.rs b/src/test/compile-fail/trait-bounds-not-on-bare-trait.rs index d7c98ec4e9d24..50e55ad295ecb 100644 --- a/src/test/compile-fail/trait-bounds-not-on-bare-trait.rs +++ b/src/test/compile-fail/trait-bounds-not-on-bare-trait.rs @@ -13,7 +13,8 @@ trait Foo { // This should emit the less confusing error, not the more confusing one. -fn foo(_x: Foo:Send) { //~ERROR reference to trait `Foo` where a type is expected +fn foo(_x: Foo:Send) { + //~^ERROR reference to trait `Foo` where a type is expected; try `~Foo` or `&Foo` } fn main() { } From 342e8b59be97c28be38d54bec10e511ae17da129 Mon Sep 17 00:00:00 2001 From: Eduard Bopp Date: Wed, 9 Apr 2014 20:16:44 +0200 Subject: [PATCH 07/28] Fix outdated lint warning about inner attribute It suggested adding a semicolon instead of the new syntax using an exclamation mark. --- src/librustc/middle/lint.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 22182d7e87e13..24dea77c17019 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -1063,7 +1063,7 @@ fn check_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) { if name.equiv(crate_attr) { let msg = match attr.node.style { ast::AttrOuter => "crate-level attribute should be an inner attribute: \ - add semicolon at end", + add an exclamation mark: #![foo]", ast::AttrInner => "crate-level attribute should be in the root module", }; cx.span_lint(AttributeUsage, attr.span, msg); From a65411e4f7b5df78e34dcaf8061d4641f4b56412 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Wed, 9 Apr 2014 11:43:33 +1000 Subject: [PATCH 08/28] std,serialize: remove some internal uses of ~[]. These are all private uses of ~[], so can easily & non-controversially be replaced with Vec. --- src/libserialize/ebml.rs | 5 ++--- src/libstd/io/extensions.rs | 10 +++++----- src/libstd/io/signal.rs | 5 +++-- src/libstd/local_data.rs | 11 ++++++----- src/libstd/repr.rs | 17 +++++++++-------- src/libstd/rt/at_exit_imp.rs | 7 ++++--- src/libstd/sync/deque.rs | 16 ++++++++-------- src/libstd/sync/mpmc_bounded_queue.rs | 12 ++++++------ 8 files changed, 43 insertions(+), 40 deletions(-) diff --git a/src/libserialize/ebml.rs b/src/libserialize/ebml.rs index a6356e34af30d..d753922f7f426 100644 --- a/src/libserialize/ebml.rs +++ b/src/libserialize/ebml.rs @@ -636,7 +636,7 @@ pub mod writer { // ebml writing pub struct Encoder<'a, W> { pub writer: &'a mut W, - size_positions: ~[uint], + size_positions: Vec, } fn write_sized_vuint(w: &mut W, n: uint, size: uint) -> EncodeResult { @@ -668,10 +668,9 @@ pub mod writer { } pub fn Encoder<'a, W: Writer + Seek>(w: &'a mut W) -> Encoder<'a, W> { - let size_positions: ~[uint] = ~[]; Encoder { writer: w, - size_positions: size_positions, + size_positions: vec!(), } } diff --git a/src/libstd/io/extensions.rs b/src/libstd/io/extensions.rs index f87f4a69f17a6..e1eaa2792bf31 100644 --- a/src/libstd/io/extensions.rs +++ b/src/libstd/io/extensions.rs @@ -21,7 +21,7 @@ use option::{Option, Some, None}; use result::{Ok, Err}; use io; use io::{IoError, IoResult, Reader}; -use slice::{OwnedVector, ImmutableVector}; +use slice::{OwnedVector, ImmutableVector, Vector}; use ptr::RawPtr; /// An iterator that reads a single byte on each iteration, @@ -88,7 +88,7 @@ pub fn u64_to_le_bytes(n: u64, size: uint, f: |v: &[u8]| -> T) -> T { 8u => f(unsafe { transmute::(to_le64(n as i64)) }), _ => { - let mut bytes: ~[u8] = ~[]; + let mut bytes = vec!(); let mut i = size; let mut n = n; while i > 0u { @@ -96,7 +96,7 @@ pub fn u64_to_le_bytes(n: u64, size: uint, f: |v: &[u8]| -> T) -> T { n >>= 8_u64; i -= 1u; } - f(bytes) + f(bytes.as_slice()) } } } @@ -127,14 +127,14 @@ pub fn u64_to_be_bytes(n: u64, size: uint, f: |v: &[u8]| -> T) -> T { 4u => f(unsafe { transmute::(to_be32(n as i32)) }), 8u => f(unsafe { transmute::(to_be64(n as i64)) }), _ => { - let mut bytes: ~[u8] = ~[]; + let mut bytes = vec!(); let mut i = size; while i > 0u { let shift = ((i - 1u) * 8u) as u64; bytes.push((n >> shift) as u8); i -= 1u; } - f(bytes) + f(bytes.as_slice()) } } } diff --git a/src/libstd/io/signal.rs b/src/libstd/io/signal.rs index 6762e7c6a76ef..00b2e4f2307d8 100644 --- a/src/libstd/io/signal.rs +++ b/src/libstd/io/signal.rs @@ -29,6 +29,7 @@ use option::{Some, None}; use result::{Ok, Err}; use rt::rtio::{IoFactory, LocalIo, RtioSignal}; use slice::{ImmutableVector, OwnedVector}; +use vec::Vec; /// Signals that can be sent and received #[repr(int)] @@ -80,7 +81,7 @@ pub enum Signum { /// ``` pub struct Listener { /// A map from signums to handles to keep the handles in memory - handles: ~[(Signum, ~RtioSignal:Send)], + handles: Vec<(Signum, ~RtioSignal:Send)>, /// This is where all the handles send signums, which are received by /// the clients from the receiver. tx: Sender, @@ -99,7 +100,7 @@ impl Listener { Listener { tx: tx, rx: rx, - handles: ~[], + handles: vec!(), } } diff --git a/src/libstd/local_data.rs b/src/libstd/local_data.rs index c555fb58db89a..c76e079432ae1 100644 --- a/src/libstd/local_data.rs +++ b/src/libstd/local_data.rs @@ -47,6 +47,7 @@ use mem::replace; use option::{None, Option, Some}; use rt::task::{Task, LocalStorage}; use slice::{ImmutableVector, MutableVector, OwnedVector}; +use vec::Vec; /** * Indexes a task-local data slot. This pointer is used for comparison to @@ -89,7 +90,7 @@ impl LocalData for T {} // n.b. If TLS is used heavily in future, this could be made more efficient with // a proper map. #[doc(hidden)] -pub type Map = ~[Option<(*u8, TLSValue, LoanState)>]; +pub type Map = Vec>; type TLSValue = ~LocalData:Send; // Gets the map from the runtime. Lazily initialises if not done so already. @@ -106,7 +107,7 @@ unsafe fn get_local_map() -> &mut Map { // If this is the first time we've accessed TLS, perform similar // actions to the oldsched way of doing things. &LocalStorage(ref mut slot) => { - *slot = Some(~[]); + *slot = Some(vec!()); match *slot { Some(ref mut map_ptr) => { return map_ptr } None => abort() @@ -237,7 +238,7 @@ fn get_with { let ret; let mut return_loan = false; - match map[i] { + match *map.get_mut(i) { Some((_, ref data, ref mut loan)) => { match (state, *loan) { (_, NoLoan) => { @@ -271,7 +272,7 @@ fn get_with { *loan = NoLoan; } None => abort() } @@ -331,7 +332,7 @@ pub fn set(key: Key, data: T) { // we're not actually sending it to other schedulers or anything. let data: ~LocalData:Send = unsafe { cast::transmute(data) }; match insertion_position(map, keyval) { - Some(i) => { map[i] = Some((keyval, data, NoLoan)); } + Some(i) => { *map.get_mut(i) = Some((keyval, data, NoLoan)); } None => { map.push(Some((keyval, data, NoLoan))); } } } diff --git a/src/libstd/repr.rs b/src/libstd/repr.rs index e12e0234d9650..7205edee611c1 100644 --- a/src/libstd/repr.rs +++ b/src/libstd/repr.rs @@ -31,6 +31,7 @@ use to_str::ToStr; use slice::{Vector, OwnedVector}; use intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc}; use raw; +use vec::Vec; macro_rules! try( ($me:expr, $e:expr) => ( match $e { @@ -102,8 +103,8 @@ enum VariantState { pub struct ReprVisitor<'a> { ptr: *u8, - ptr_stk: ~[*u8], - var_stk: ~[VariantState], + ptr_stk: Vec<*u8>, + var_stk: Vec, writer: &'a mut io::Writer, last_err: Option, } @@ -112,8 +113,8 @@ pub fn ReprVisitor<'a>(ptr: *u8, writer: &'a mut io::Writer) -> ReprVisitor<'a> { ReprVisitor { ptr: ptr, - ptr_stk: ~[], - var_stk: ~[], + ptr_stk: vec!(), + var_stk: vec!(), writer: writer, last_err: None, } @@ -154,8 +155,8 @@ impl<'a> ReprVisitor<'a> { // issues we have to recreate it here. let u = ReprVisitor { ptr: ptr, - ptr_stk: ~[], - var_stk: ~[], + ptr_stk: vec!(), + var_stk: vec!(), writer: ::cast::transmute_copy(&self.writer), last_err: None, }; @@ -505,7 +506,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { _offset: uint, inner: *TyDesc) -> bool { - match self.var_stk[self.var_stk.len() - 1] { + match *self.var_stk.get(self.var_stk.len() - 1) { Matched => { if i != 0 { try!(self, self.writer.write(", ".as_bytes())); @@ -523,7 +524,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { _disr_val: Disr, n_fields: uint, _name: &str) -> bool { - match self.var_stk[self.var_stk.len() - 1] { + match *self.var_stk.get(self.var_stk.len() - 1) { Matched => { if n_fields > 0 { try!(self, self.writer.write([')' as u8])); diff --git a/src/libstd/rt/at_exit_imp.rs b/src/libstd/rt/at_exit_imp.rs index 4be9c8a84acd3..67b8b40b47e6e 100644 --- a/src/libstd/rt/at_exit_imp.rs +++ b/src/libstd/rt/at_exit_imp.rs @@ -20,8 +20,9 @@ use option::{Some, None}; use ptr::RawPtr; use unstable::sync::Exclusive; use slice::OwnedVector; +use vec::Vec; -type Queue = Exclusive<~[proc():Send]>; +type Queue = Exclusive>; // You'll note that these variables are *not* atomic, and this is done on // purpose. This module is designed to have init() called *once* in a @@ -35,7 +36,7 @@ pub fn init() { unsafe { rtassert!(!RUNNING); rtassert!(QUEUE.is_null()); - let state: ~Queue = ~Exclusive::new(~[]); + let state: ~Queue = ~Exclusive::new(vec!()); QUEUE = cast::transmute(state); } } @@ -61,7 +62,7 @@ pub fn run() { QUEUE = 0 as *mut Queue; let mut vec = None; state.with(|arr| { - vec = Some(mem::replace(arr, ~[])); + vec = Some(mem::replace(arr, vec!())); }); vec.take_unwrap() }; diff --git a/src/libstd/sync/deque.rs b/src/libstd/sync/deque.rs index d01c89878ded9..8beadce21604e 100644 --- a/src/libstd/sync/deque.rs +++ b/src/libstd/sync/deque.rs @@ -62,6 +62,7 @@ use sync::arc::UnsafeArc; use sync::atomics::{AtomicInt, AtomicPtr, SeqCst}; use unstable::sync::Exclusive; use slice::{OwnedVector, ImmutableVector}; +use vec::Vec; // Once the queue is less than 1/K full, then it will be downsized. Note that // the deque requires that this number be less than 2. @@ -116,14 +117,14 @@ pub enum Stolen { /// will only use this structure when allocating a new buffer or deallocating a /// previous one. pub struct BufferPool { - pool: Exclusive<~[~Buffer]>, + pool: Exclusive>>, } /// An internal buffer used by the chase-lev deque. This structure is actually /// implemented as a circular buffer, and is used as the intermediate storage of /// the data in the deque. /// -/// This type is implemented with *T instead of ~[T] for two reasons: +/// This type is implemented with *T instead of Vec for two reasons: /// /// 1. There is nothing safe about using this buffer. This easily allows the /// same value to be read twice in to rust, and there is nothing to @@ -132,7 +133,7 @@ pub struct BufferPool { /// destructors for values in this buffer (on drop) because the bounds /// are defined by the deque it's owned by. /// -/// 2. We can certainly avoid bounds checks using *T instead of ~[T], although +/// 2. We can certainly avoid bounds checks using *T instead of Vec, although /// LLVM is probably pretty good at doing this already. struct Buffer { storage: *T, @@ -143,7 +144,7 @@ impl BufferPool { /// Allocates a new buffer pool which in turn can be used to allocate new /// deques. pub fn new() -> BufferPool { - BufferPool { pool: Exclusive::new(~[]) } + BufferPool { pool: Exclusive::new(vec!()) } } /// Allocates a new work-stealing deque which will send/receiving memory to @@ -494,7 +495,7 @@ mod tests { } } }) - }).collect::<~[Thread<()>]>(); + }).collect::>>(); while remaining.load(SeqCst) > 0 { match w.pop() { @@ -525,7 +526,7 @@ mod tests { Thread::start(proc() { stampede(w, s, 4, 10000); }) - }).collect::<~[Thread<()>]>(); + }).collect::>>(); for thread in threads.move_iter() { thread.join(); @@ -556,7 +557,7 @@ mod tests { } } }) - }).collect::<~[Thread<()>]>(); + }).collect::>>(); let mut rng = rand::task_rng(); let mut expected = 0; @@ -658,4 +659,3 @@ mod tests { } } } - diff --git a/src/libstd/sync/mpmc_bounded_queue.rs b/src/libstd/sync/mpmc_bounded_queue.rs index 12c05c0d61cea..b392cc8ff9a70 100644 --- a/src/libstd/sync/mpmc_bounded_queue.rs +++ b/src/libstd/sync/mpmc_bounded_queue.rs @@ -35,7 +35,7 @@ use num::next_power_of_two; use option::{Option, Some, None}; use sync::arc::UnsafeArc; use sync::atomics::{AtomicUint,Relaxed,Release,Acquire}; -use slice; +use vec::Vec; struct Node { sequence: AtomicUint, @@ -44,7 +44,7 @@ struct Node { struct State { pad0: [u8, ..64], - buffer: ~[Node], + buffer: Vec>, mask: uint, pad1: [u8, ..64], enqueue_pos: AtomicUint, @@ -69,7 +69,7 @@ impl State { } else { capacity }; - let buffer = slice::from_fn(capacity, |i| { + let buffer = Vec::from_fn(capacity, |i| { Node { sequence:AtomicUint::new(i), value: None } }); State{ @@ -88,7 +88,7 @@ impl State { let mask = self.mask; let mut pos = self.enqueue_pos.load(Relaxed); loop { - let node = &mut self.buffer[pos & mask]; + let node = self.buffer.get_mut(pos & mask); let seq = node.sequence.load(Acquire); let diff: int = seq as int - pos as int; @@ -114,7 +114,7 @@ impl State { let mask = self.mask; let mut pos = self.dequeue_pos.load(Relaxed); loop { - let node = &mut self.buffer[pos & mask]; + let node = self.buffer.get_mut(pos & mask); let seq = node.sequence.load(Acquire); let diff: int = seq as int - (pos + 1) as int; if diff == 0 { @@ -186,7 +186,7 @@ mod tests { }); } - let mut completion_rxs = ~[]; + let mut completion_rxs = vec![]; for _ in range(0, nthreads) { let (tx, rx) = channel(); completion_rxs.push(rx); From 301594917fca62ffa1ca4589ac398c3196427547 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Wed, 9 Apr 2014 11:45:20 +1000 Subject: [PATCH 09/28] std,native,green,rustuv: make readdir return `Vec`. Replacing `~[]`. This also makes the `walk_dir` iterator use a `Vec` internally. --- src/libnative/io/file_unix.rs | 7 +++---- src/libnative/io/file_win32.rs | 6 +++--- src/libnative/io/mod.rs | 2 +- src/librustuv/file.rs | 4 ++-- src/librustuv/uvio.rs | 2 +- src/libstd/io/fs.rs | 4 ++-- src/libstd/rt/rtio.rs | 3 ++- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/libnative/io/file_unix.rs b/src/libnative/io/file_unix.rs index 56460166b48a4..5446ab2950e44 100644 --- a/src/libnative/io/file_unix.rs +++ b/src/libnative/io/file_unix.rs @@ -340,11 +340,11 @@ pub fn mkdir(p: &CString, mode: io::FilePermission) -> IoResult<()> { })) } -pub fn readdir(p: &CString) -> IoResult<~[Path]> { +pub fn readdir(p: &CString) -> IoResult> { use libc::{dirent_t}; use libc::{opendir, readdir_r, closedir}; - fn prune(root: &CString, dirs: ~[Path]) -> ~[Path] { + fn prune(root: &CString, dirs: Vec) -> Vec { let root = unsafe { CString::new(root.with_ref(|p| p), false) }; let root = Path::new(root); @@ -365,7 +365,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> { let dir_ptr = p.with_ref(|buf| unsafe { opendir(buf) }); if dir_ptr as uint != 0 { - let mut paths = ~[]; + let mut paths = vec!(); let mut entry_ptr = 0 as *mut dirent_t; while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } { if entry_ptr.is_null() { break } @@ -571,4 +571,3 @@ mod tests { } } } - diff --git a/src/libnative/io/file_win32.rs b/src/libnative/io/file_win32.rs index 3e8ee55df94fc..8090042f090c9 100644 --- a/src/libnative/io/file_win32.rs +++ b/src/libnative/io/file_win32.rs @@ -323,10 +323,10 @@ pub fn mkdir(p: &CString, _mode: io::FilePermission) -> IoResult<()> { }) } -pub fn readdir(p: &CString) -> IoResult<~[Path]> { +pub fn readdir(p: &CString) -> IoResult> { use rt::global_heap::malloc_raw; - fn prune(root: &CString, dirs: ~[Path]) -> ~[Path] { + fn prune(root: &CString, dirs: Vec) -> Vec { let root = unsafe { CString::new(root.with_ref(|p| p), false) }; let root = Path::new(root); @@ -346,7 +346,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> { let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint); let find_handle = libc::FindFirstFileW(path_ptr, wfd_ptr as libc::HANDLE); if find_handle as libc::c_int != libc::INVALID_HANDLE_VALUE { - let mut paths = ~[]; + let mut paths = vec!(); let mut more_files = 1 as libc::c_int; while more_files != 0 { let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr as *c_void); diff --git a/src/libnative/io/mod.rs b/src/libnative/io/mod.rs index ffca0dbe3dc60..cc432555abb92 100644 --- a/src/libnative/io/mod.rs +++ b/src/libnative/io/mod.rs @@ -217,7 +217,7 @@ impl rtio::IoFactory for IoFactory { fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()> { file::rename(path, to) } - fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult<~[Path]> { + fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult> { file::readdir(path) } fn fs_lstat(&mut self, path: &CString) -> IoResult { diff --git a/src/librustuv/file.rs b/src/librustuv/file.rs index acb7a8184dd07..69be32a60211d 100644 --- a/src/librustuv/file.rs +++ b/src/librustuv/file.rs @@ -152,13 +152,13 @@ impl FsRequest { } pub fn readdir(loop_: &Loop, path: &CString, flags: c_int) - -> Result<~[Path], UvError> + -> Result, UvError> { execute(|req, cb| unsafe { uvll::uv_fs_readdir(loop_.handle, req, path.with_ref(|p| p), flags, cb) }).map(|req| unsafe { - let mut paths = ~[]; + let mut paths = vec!(); let path = CString::new(path.with_ref(|p| p), false); let parent = Path::new(path); let _ = c_str::from_c_multistring(req.get_ptr() as *libc::c_char, diff --git a/src/librustuv/uvio.rs b/src/librustuv/uvio.rs index 424849bbf0eab..55456bb548e91 100644 --- a/src/librustuv/uvio.rs +++ b/src/librustuv/uvio.rs @@ -234,7 +234,7 @@ impl IoFactory for UvIoFactory { r.map_err(uv_error_to_io_error) } fn fs_readdir(&mut self, path: &CString, flags: c_int) - -> Result<~[Path], IoError> + -> Result, IoError> { let r = FsRequest::readdir(&self.loop_, path, flags); r.map_err(uv_error_to_io_error) diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index 2fea002d4197f..b8a58c5cf1040 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -483,7 +483,7 @@ pub fn rmdir(path: &Path) -> IoResult<()> { /// Will return an error if the provided `from` doesn't exist, the process lacks /// permissions to view the contents or if the `path` points at a non-directory /// file -pub fn readdir(path: &Path) -> IoResult<~[Path]> { +pub fn readdir(path: &Path) -> IoResult> { LocalIo::maybe_raise(|io| { io.fs_readdir(&path.to_c_str(), 0) }) @@ -498,7 +498,7 @@ pub fn walk_dir(path: &Path) -> IoResult { /// An iterator which walks over a directory pub struct Directories { - stack: ~[Path], + stack: Vec, } impl Iterator for Directories { diff --git a/src/libstd/rt/rtio.rs b/src/libstd/rt/rtio.rs index 1750e685627d8..cc8356d2b9a04 100644 --- a/src/libstd/rt/rtio.rs +++ b/src/libstd/rt/rtio.rs @@ -20,6 +20,7 @@ use path::Path; use result::Err; use rt::local::Local; use rt::task::Task; +use vec::Vec; use ai = io::net::addrinfo; use io; @@ -168,7 +169,7 @@ pub trait IoFactory { fn fs_rmdir(&mut self, path: &CString) -> IoResult<()>; fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()>; fn fs_readdir(&mut self, path: &CString, flags: c_int) -> - IoResult<~[Path]>; + IoResult>; fn fs_lstat(&mut self, path: &CString) -> IoResult; fn fs_chown(&mut self, path: &CString, uid: int, gid: int) -> IoResult<()>; From 1403b35be70d30fccdf68378b3555d1ce74e852b Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Wed, 9 Apr 2014 11:46:49 +1000 Subject: [PATCH 10/28] std,syntax: make std::fmt::parse use `Vec`s. --- src/libstd/fmt/parse.rs | 116 ++++++++++++++++++------------------ src/libsyntax/ext/format.rs | 8 +-- 2 files changed, 62 insertions(+), 62 deletions(-) diff --git a/src/libstd/fmt/parse.rs b/src/libstd/fmt/parse.rs index 4752f3a75f473..36ffb8572378f 100644 --- a/src/libstd/fmt/parse.rs +++ b/src/libstd/fmt/parse.rs @@ -131,13 +131,13 @@ pub enum Method<'a> { /// /// The final element of this enum is the default "other" case which is /// always required to be specified. - Plural(Option, ~[PluralArm<'a>], ~[Piece<'a>]), + Plural(Option, Vec>, Vec>), /// A select method selects over a string. Each arm is a different string /// which can be selected for. /// /// As with `Plural`, a default "other" case is required as well. - Select(~[SelectArm<'a>], ~[Piece<'a>]), + Select(Vec>, Vec>), } /// A selector for what pluralization a plural method should take @@ -156,7 +156,7 @@ pub struct PluralArm<'a> { /// literal. pub selector: PluralSelector, /// Array of pieces which are the format of this arm - pub result: ~[Piece<'a>], + pub result: Vec>, } /// Enum of the 5 CLDR plural keywords. There is one more, "other", but that @@ -184,7 +184,7 @@ pub struct SelectArm<'a> { /// String selector which guards this arm pub selector: &'a str, /// Array of pieces which are the format of this arm - pub result: ~[Piece<'a>], + pub result: Vec>, } /// The parser structure for interpreting the input format string. This is @@ -198,7 +198,7 @@ pub struct Parser<'a> { cur: str::CharOffsets<'a>, depth: uint, /// Error messages accumulated during parsing - pub errors: ~[~str], + pub errors: Vec<~str>, } impl<'a> Iterator> for Parser<'a> { @@ -236,7 +236,7 @@ impl<'a> Parser<'a> { input: s, cur: s.char_indices(), depth: 0, - errors: ~[], + errors: vec!(), } } @@ -463,7 +463,7 @@ impl<'a> Parser<'a> { /// Parses a 'select' statement (after the initial 'select' word) fn select(&mut self) -> ~Method<'a> { let mut other = None; - let mut arms = ~[]; + let mut arms = vec!(); // Consume arms one at a time loop { self.ws(); @@ -496,7 +496,7 @@ impl<'a> Parser<'a> { Some(arm) => { arm } None => { self.err("`select` statement must provide an `other` case"); - ~[] + vec!() } }; ~Select(arms, other) @@ -506,7 +506,7 @@ impl<'a> Parser<'a> { fn plural(&mut self) -> ~Method<'a> { let mut offset = None; let mut other = None; - let mut arms = ~[]; + let mut arms = vec!(); // First, attempt to parse the 'offset:' field. We know the set of // selector words which can appear in plural arms, and the only ones @@ -594,7 +594,7 @@ impl<'a> Parser<'a> { Some(arm) => { arm } None => { self.err("`plural` statement must provide an `other` case"); - ~[] + vec!() } }; ~Plural(offset, arms, other) @@ -684,9 +684,9 @@ mod tests { use super::*; use prelude::*; - fn same(fmt: &'static str, p: ~[Piece<'static>]) { + fn same(fmt: &'static str, p: &[Piece<'static>]) { let mut parser = Parser::new(fmt); - assert!(p == parser.collect()); + assert!(p == parser.collect::>>().as_slice()); } fn fmtdflt() -> FormatSpec<'static> { @@ -708,12 +708,12 @@ mod tests { #[test] fn simple() { - same("asdf", ~[String("asdf")]); - same("a\\{b", ~[String("a"), String("{b")]); - same("a\\#b", ~[String("a"), String("#b")]); - same("a\\}b", ~[String("a"), String("}b")]); - same("a\\}", ~[String("a"), String("}")]); - same("\\}", ~[String("}")]); + same("asdf", [String("asdf")]); + same("a\\{b", [String("a"), String("{b")]); + same("a\\#b", [String("a"), String("#b")]); + same("a\\}b", [String("a"), String("}b")]); + same("a\\}", [String("a"), String("}")]); + same("\\}", [String("}")]); } #[test] fn invalid01() { musterr("{") } @@ -725,7 +725,7 @@ mod tests { #[test] fn format_nothing() { - same("{}", ~[Argument(Argument { + same("{}", [Argument(Argument { position: ArgumentNext, format: fmtdflt(), method: None, @@ -733,7 +733,7 @@ mod tests { } #[test] fn format_position() { - same("{3}", ~[Argument(Argument { + same("{3}", [Argument(Argument { position: ArgumentIs(3), format: fmtdflt(), method: None, @@ -741,7 +741,7 @@ mod tests { } #[test] fn format_position_nothing_else() { - same("{3:}", ~[Argument(Argument { + same("{3:}", [Argument(Argument { position: ArgumentIs(3), format: fmtdflt(), method: None, @@ -749,7 +749,7 @@ mod tests { } #[test] fn format_type() { - same("{3:a}", ~[Argument(Argument { + same("{3:a}", [Argument(Argument { position: ArgumentIs(3), format: FormatSpec { fill: None, @@ -764,7 +764,7 @@ mod tests { } #[test] fn format_align_fill() { - same("{3:>}", ~[Argument(Argument { + same("{3:>}", [Argument(Argument { position: ArgumentIs(3), format: FormatSpec { fill: None, @@ -776,7 +776,7 @@ mod tests { }, method: None, })]); - same("{3:0<}", ~[Argument(Argument { + same("{3:0<}", [Argument(Argument { position: ArgumentIs(3), format: FormatSpec { fill: Some('0'), @@ -788,7 +788,7 @@ mod tests { }, method: None, })]); - same("{3:* Context<'a, 'b> { } } } - self.verify_pieces(arm.result); + self.verify_pieces(arm.result.as_slice()); } - self.verify_pieces(*default); + self.verify_pieces(default.as_slice()); } parse::Select(ref arms, ref default) => { self.verify_arg_type(pos, String); @@ -258,9 +258,9 @@ impl<'a, 'b> Context<'a, 'b> { self.ecx.span_err(self.fmtsp, "empty selector in `select`"); } - self.verify_pieces(arm.result); + self.verify_pieces(arm.result.as_slice()); } - self.verify_pieces(*default); + self.verify_pieces(default.as_slice()); } } self.nest_level -= 1; From 8ec16e1e66354199fff519fb9380bcd749e33d2f Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Wed, 9 Apr 2014 18:36:19 +1000 Subject: [PATCH 11/28] green: de-~[]. --- src/libgreen/basic.rs | 20 ++++++++++---------- src/libgreen/lib.rs | 32 +++++++++++++++++++------------- src/libgreen/sched.rs | 12 ++++++------ src/libgreen/stack.rs | 4 ++-- 4 files changed, 37 insertions(+), 31 deletions(-) diff --git a/src/libgreen/basic.rs b/src/libgreen/basic.rs index 62b6f71ae9c6b..2877768dd8bfe 100644 --- a/src/libgreen/basic.rs +++ b/src/libgreen/basic.rs @@ -27,11 +27,11 @@ pub fn event_loop() -> ~EventLoop:Send { } struct BasicLoop { - work: ~[proc():Send], // pending work + work: Vec, // pending work idle: Option<*mut BasicPausable>, // only one is allowed - remotes: ~[(uint, ~Callback:Send)], + remotes: Vec<(uint, ~Callback:Send)>, next_remote: uint, - messages: Exclusive<~[Message]>, + messages: Exclusive>, } enum Message { RunRemote(uint), RemoveRemote(uint) } @@ -39,18 +39,18 @@ enum Message { RunRemote(uint), RemoveRemote(uint) } impl BasicLoop { fn new() -> BasicLoop { BasicLoop { - work: ~[], + work: vec![], idle: None, next_remote: 0, - remotes: ~[], - messages: Exclusive::new(~[]), + remotes: vec![], + messages: Exclusive::new(vec![]), } } /// Process everything in the work queue (continually) fn work(&mut self) { while self.work.len() > 0 { - for work in replace(&mut self.work, ~[]).move_iter() { + for work in replace(&mut self.work, vec![]).move_iter() { work(); } } @@ -60,7 +60,7 @@ impl BasicLoop { let messages = unsafe { self.messages.with(|messages| { if messages.len() > 0 { - Some(replace(messages, ~[])) + Some(replace(messages, vec![])) } else { None } @@ -165,12 +165,12 @@ impl EventLoop for BasicLoop { } struct BasicRemote { - queue: Exclusive<~[Message]>, + queue: Exclusive>, id: uint, } impl BasicRemote { - fn new(queue: Exclusive<~[Message]>, id: uint) -> BasicRemote { + fn new(queue: Exclusive>, id: uint) -> BasicRemote { BasicRemote { queue: queue, id: id } } } diff --git a/src/libgreen/lib.rs b/src/libgreen/lib.rs index e4a9641efd1b7..820627b6b7d13 100644 --- a/src/libgreen/lib.rs +++ b/src/libgreen/lib.rs @@ -195,6 +195,7 @@ // NB this does *not* include globs, please keep it that way. #![feature(macro_rules, phase)] #![allow(visible_private_types)] +#![deny(deprecated_owned_vector)] #[cfg(test)] #[phase(syntax, link)] extern crate log; #[cfg(test)] extern crate rustuv; @@ -209,7 +210,6 @@ use std::rt; use std::sync::atomics::{SeqCst, AtomicUint, INIT_ATOMIC_UINT}; use std::sync::deque; use std::task::TaskOpts; -use std::slice; use std::sync::arc::UnsafeArc; use sched::{Shutdown, Scheduler, SchedHandle, TaskFromFriend, NewNeighbor}; @@ -318,9 +318,9 @@ impl PoolConfig { /// used to keep the pool alive and also reap the status from the pool. pub struct SchedPool { id: uint, - threads: ~[Thread<()>], - handles: ~[SchedHandle], - stealers: ~[deque::Stealer<~task::GreenTask>], + threads: Vec>, + handles: Vec, + stealers: Vec>, next_friend: uint, stack_pool: StackPool, deque_pool: deque::BufferPool<~task::GreenTask>, @@ -356,9 +356,9 @@ impl SchedPool { // The pool of schedulers that will be returned from this function let (p, state) = TaskState::new(); let mut pool = SchedPool { - threads: ~[], - handles: ~[], - stealers: ~[], + threads: vec![], + handles: vec![], + stealers: vec![], id: unsafe { POOL_ID.fetch_add(1, SeqCst) }, sleepers: SleeperList::new(), stack_pool: StackPool::new(), @@ -371,8 +371,14 @@ impl SchedPool { // Create a work queue for each scheduler, ntimes. Create an extra // for the main thread if that flag is set. We won't steal from it. - let arr = slice::from_fn(nscheds, |_| pool.deque_pool.deque()); - let (workers, stealers) = slice::unzip(arr.move_iter()); + let mut workers = Vec::with_capacity(nscheds); + let mut stealers = Vec::with_capacity(nscheds); + + for _ in range(0, nscheds) { + let (w, s) = pool.deque_pool.deque(); + workers.push(w); + stealers.push(s); + } pool.stealers = stealers; // Now that we've got all our work queues, create one scheduler per @@ -420,7 +426,7 @@ impl SchedPool { } // Jettison the task away! - self.handles[idx].send(TaskFromFriend(task)); + self.handles.get_mut(idx).send(TaskFromFriend(task)); } /// Spawns a new scheduler into this M:N pool. A handle is returned to the @@ -466,7 +472,7 @@ impl SchedPool { /// This only waits for all tasks in *this pool* of schedulers to exit, any /// native tasks or extern pools will not be waited on pub fn shutdown(mut self) { - self.stealers = ~[]; + self.stealers = vec![]; // Wait for everyone to exit. We may have reached a 0-task count // multiple times in the past, meaning there could be several buffered @@ -478,10 +484,10 @@ impl SchedPool { } // Now that everyone's gone, tell everything to shut down. - for mut handle in replace(&mut self.handles, ~[]).move_iter() { + for mut handle in replace(&mut self.handles, vec![]).move_iter() { handle.send(Shutdown); } - for thread in replace(&mut self.threads, ~[]).move_iter() { + for thread in replace(&mut self.threads, vec![]).move_iter() { thread.join(); } } diff --git a/src/libgreen/sched.rs b/src/libgreen/sched.rs index 036d02655f9f0..9971dfee82815 100644 --- a/src/libgreen/sched.rs +++ b/src/libgreen/sched.rs @@ -49,7 +49,7 @@ pub struct Scheduler { work_queue: deque::Worker<~GreenTask>, /// Work queues for the other schedulers. These are created by /// cloning the core work queues. - work_queues: ~[deque::Stealer<~GreenTask>], + work_queues: Vec>, /// The queue of incoming messages from other schedulers. /// These are enqueued by SchedHandles after which a remote callback /// is triggered to handle the message. @@ -125,7 +125,7 @@ impl Scheduler { pub fn new(pool_id: uint, event_loop: ~EventLoop:Send, work_queue: deque::Worker<~GreenTask>, - work_queues: ~[deque::Stealer<~GreenTask>], + work_queues: Vec>, sleeper_list: SleeperList, state: TaskState) -> Scheduler { @@ -138,7 +138,7 @@ impl Scheduler { pub fn new_special(pool_id: uint, event_loop: ~EventLoop:Send, work_queue: deque::Worker<~GreenTask>, - work_queues: ~[deque::Stealer<~GreenTask>], + work_queues: Vec>, sleeper_list: SleeperList, run_anything: bool, friend: Option, @@ -502,7 +502,7 @@ impl Scheduler { let len = work_queues.len(); let start_index = self.rng.gen_range(0, len); for index in range(0, len).map(|i| (i + start_index) % len) { - match work_queues[index].steal() { + match work_queues.get_mut(index).steal() { deque::Data(task) => { rtdebug!("found task by stealing"); return Some(task) @@ -1137,7 +1137,7 @@ mod test { let mut pool = BufferPool::new(); let (normal_worker, normal_stealer) = pool.deque(); let (special_worker, special_stealer) = pool.deque(); - let queues = ~[normal_stealer, special_stealer]; + let queues = vec![normal_stealer, special_stealer]; let (_p, state) = TaskState::new(); // Our normal scheduler @@ -1326,7 +1326,7 @@ mod test { #[test] fn multithreading() { run(proc() { - let mut rxs = ~[]; + let mut rxs = vec![]; for _ in range(0, 10) { let (tx, rx) = channel(); spawn(proc() { diff --git a/src/libgreen/stack.rs b/src/libgreen/stack.rs index b8ab4d5f8c1fe..1f06ba379f0fa 100644 --- a/src/libgreen/stack.rs +++ b/src/libgreen/stack.rs @@ -126,13 +126,13 @@ impl Drop for Stack { pub struct StackPool { // Ideally this would be some datastructure that preserved ordering on // Stack.min_size. - stacks: ~[Stack], + stacks: Vec, } impl StackPool { pub fn new() -> StackPool { StackPool { - stacks: ~[], + stacks: vec![], } } From 32cf4a188c220d1d36a153af19ede1eb43cace05 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Wed, 9 Apr 2014 19:41:44 +1000 Subject: [PATCH 12/28] native: remove some internal ~[]. --- src/libnative/io/timer_other.rs | 12 ++++++------ src/libnative/io/timer_timerfd.rs | 12 ++++++------ src/libnative/io/timer_win32.rs | 6 +++--- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/libnative/io/timer_other.rs b/src/libnative/io/timer_other.rs index 13f1ea6319a46..569b4cbb258e0 100644 --- a/src/libnative/io/timer_other.rs +++ b/src/libnative/io/timer_other.rs @@ -102,11 +102,11 @@ fn helper(input: libc::c_int, messages: Receiver) { // active timers are those which are able to be selected upon (and it's a // sorted list, and dead timers are those which have expired, but ownership // hasn't yet been transferred back to the timer itself. - let mut active: ~[~Inner] = ~[]; - let mut dead = ~[]; + let mut active: Vec<~Inner> = vec![]; + let mut dead = vec![]; // inserts a timer into an array of timers (sorted by firing time) - fn insert(t: ~Inner, active: &mut ~[~Inner]) { + fn insert(t: ~Inner, active: &mut Vec<~Inner>) { match active.iter().position(|tm| tm.target > t.target) { Some(pos) => { active.insert(pos, t); } None => { active.push(t); } @@ -114,7 +114,7 @@ fn helper(input: libc::c_int, messages: Receiver) { } // signals the first requests in the queue, possible re-enqueueing it. - fn signal(active: &mut ~[~Inner], dead: &mut ~[(uint, ~Inner)]) { + fn signal(active: &mut Vec<~Inner>, dead: &mut Vec<(uint, ~Inner)>) { let mut timer = match active.shift() { Some(timer) => timer, None => return }; @@ -137,7 +137,7 @@ fn helper(input: libc::c_int, messages: Receiver) { let now = now(); // If this request has already expired, then signal it and go // through another iteration - if active[0].target <= now { + if active.get(0).target <= now { signal(&mut active, &mut dead); continue; } @@ -145,7 +145,7 @@ fn helper(input: libc::c_int, messages: Receiver) { // The actual timeout listed in the requests array is an // absolute date, so here we translate the absolute time to a // relative time. - let tm = active[0].target - now; + let tm = active.get(0).target - now; timeout.tv_sec = (tm / 1000) as libc::time_t; timeout.tv_usec = ((tm % 1000) * 1000) as libc::suseconds_t; &timeout as *libc::timeval diff --git a/src/libnative/io/timer_timerfd.rs b/src/libnative/io/timer_timerfd.rs index 25dbdc1e1a5cd..d37a39fc30e8d 100644 --- a/src/libnative/io/timer_timerfd.rs +++ b/src/libnative/io/timer_timerfd.rs @@ -76,7 +76,7 @@ fn helper(input: libc::c_int, messages: Receiver) { add(efd, input); let events: [imp::epoll_event, ..16] = unsafe { mem::init() }; - let mut list: ~[(libc::c_int, Sender<()>, bool)] = ~[]; + let mut list: Vec<(libc::c_int, Sender<()>, bool)> = vec![]; 'outer: loop { let n = match unsafe { imp::epoll_wait(efd, events.as_ptr(), @@ -104,9 +104,9 @@ fn helper(input: libc::c_int, messages: Receiver) { // times? let _ = FileDesc::new(fd, false).inner_read(bits).unwrap(); let (remove, i) = { - match list.bsearch(|&(f, _, _)| f.cmp(&fd)) { + match list.as_slice().bsearch(|&(f, _, _)| f.cmp(&fd)) { Some(i) => { - let (_, ref c, oneshot) = list[i]; + let (_, ref c, oneshot) = *list.get(i); (!c.try_send(()) || oneshot, i) } None => fail!("fd not active: {}", fd), @@ -128,9 +128,9 @@ fn helper(input: libc::c_int, messages: Receiver) { // If we haven't previously seen the file descriptor, then // we need to add it to the epoll set. - match list.bsearch(|&(f, _, _)| f.cmp(&fd)) { + match list.as_slice().bsearch(|&(f, _, _)| f.cmp(&fd)) { Some(i) => { - drop(mem::replace(&mut list[i], (fd, chan, one))); + drop(mem::replace(list.get_mut(i), (fd, chan, one))); } None => { match list.iter().position(|&(f, _, _)| f >= fd) { @@ -150,7 +150,7 @@ fn helper(input: libc::c_int, messages: Receiver) { } Data(RemoveTimer(fd, chan)) => { - match list.bsearch(|&(f, _, _)| f.cmp(&fd)) { + match list.as_slice().bsearch(|&(f, _, _)| f.cmp(&fd)) { Some(i) => { drop(list.remove(i)); del(efd, fd); diff --git a/src/libnative/io/timer_win32.rs b/src/libnative/io/timer_win32.rs index 278a5a73a36bd..8b7592783da04 100644 --- a/src/libnative/io/timer_win32.rs +++ b/src/libnative/io/timer_win32.rs @@ -40,8 +40,8 @@ pub enum Req { } fn helper(input: libc::HANDLE, messages: Receiver) { - let mut objs = ~[input]; - let mut chans = ~[]; + let mut objs = vec![input]; + let mut chans = vec![]; 'outer: loop { let idx = unsafe { @@ -78,7 +78,7 @@ fn helper(input: libc::HANDLE, messages: Receiver) { } } else { let remove = { - match &chans[idx as uint - 1] { + match chans.get(idx as uint - 1) { &(ref c, oneshot) => !c.try_send(()) || oneshot } }; From 6e63b12f5f1c4974bcb90455b01146938f73f328 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Wed, 9 Apr 2014 20:02:26 +1000 Subject: [PATCH 13/28] Remove some internal ~[] from several libraries. Some straggling instances of `~[]` across a few different libs. Also, remove some public ones from workcache. --- src/compiletest/runtest.rs | 2 +- src/libflate/lib.rs | 4 ++-- src/libgetopts/lib.rs | 2 +- src/libglob/lib.rs | 12 +++++++----- src/librustc/metadata/creader.rs | 4 ++-- src/librustdoc/html/markdown.rs | 6 +++--- src/librustdoc/html/render.rs | 8 ++++---- src/librustdoc/markdown.rs | 4 ++-- src/librustuv/access.rs | 4 ++-- src/libtest/stats.rs | 8 ++++---- src/libworkcache/lib.rs | 9 +++++---- src/test/bench/shootout-binarytrees.rs | 2 +- 12 files changed, 34 insertions(+), 31 deletions(-) diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index b290bd2838ab3..c605596b9629e 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -451,7 +451,7 @@ fn run_debuginfo_test(config: &config, props: &TestProps, testfile: &Path) { let options_to_remove = [~"-O", ~"-g", ~"--debuginfo"]; let new_options = split_maybe_args(options).move_iter() .filter(|x| !options_to_remove.contains(x)) - .collect::<~[~str]>() + .collect::>() .connect(" "); Some(new_options) } diff --git a/src/libflate/lib.rs b/src/libflate/lib.rs index 753a3120c2157..ea5ffb9965a0f 100644 --- a/src/libflate/lib.rs +++ b/src/libflate/lib.rs @@ -117,13 +117,13 @@ mod tests { words.push(r.gen_vec::(range)); } for _ in range(0, 20) { - let mut input = ~[]; + let mut input = vec![]; for _ in range(0, 2000) { input.push_all(r.choose(words.as_slice()).as_slice()); } debug!("de/inflate of {} bytes of random word-sequences", input.len()); - let cmp = deflate_bytes(input).expect("deflation failed"); + let cmp = deflate_bytes(input.as_slice()).expect("deflation failed"); let out = inflate_bytes(cmp.as_slice()).expect("inflation failed"); debug!("{} bytes deflated to {} ({:.1f}% size)", input.len(), cmp.len(), diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 9d4f2e2f8f082..52fbcc0cb1cab 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -53,7 +53,7 @@ //! //! let program = args[0].clone(); //! -//! let opts = ~[ +//! let opts = [ //! optopt("o", "", "set output file name", "NAME"), //! optflag("h", "help", "print this help menu") //! ]; diff --git a/src/libglob/lib.rs b/src/libglob/lib.rs index d19924da5beda..ca1fd2b560ec8 100644 --- a/src/libglob/lib.rs +++ b/src/libglob/lib.rs @@ -31,6 +31,8 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")] +#![deny(deprecated_owned_vector)] + use std::cell::Cell; use std::{cmp, os, path}; use std::io::fs; @@ -245,26 +247,26 @@ impl Pattern { */ pub fn new(pattern: &str) -> Pattern { - let chars = pattern.chars().collect::<~[_]>(); + let chars = pattern.chars().collect::>(); let mut tokens = Vec::new(); let mut i = 0; while i < chars.len() { - match chars[i] { + match *chars.get(i) { '?' => { tokens.push(AnyChar); i += 1; } '*' => { // *, **, ***, ****, ... are all equivalent - while i < chars.len() && chars[i] == '*' { + while i < chars.len() && *chars.get(i) == '*' { i += 1; } tokens.push(AnySequence); } '[' => { - if i <= chars.len() - 4 && chars[i + 1] == '!' { + if i <= chars.len() - 4 && *chars.get(i + 1) == '!' { match chars.slice_from(i + 3).position_elem(&']') { None => (), Some(j) => { @@ -276,7 +278,7 @@ impl Pattern { } } } - else if i <= chars.len() - 3 && chars[i + 1] != '!' { + else if i <= chars.len() - 3 && *chars.get(i + 1) != '!' { match chars.slice_from(i + 2).position_elem(&']') { None => (), Some(j) => { diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 50c22f6bf1bba..b57ab8d0f2fc8 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -190,7 +190,7 @@ fn visit_item(e: &Env, i: &ast::Item) { } else { None }) - .collect::<~[&ast::Attribute]>(); + .collect::>(); for m in link_args.iter() { match m.value_str() { Some(linkarg) => e.sess.cstore.add_used_link_args(linkarg.get()), @@ -205,7 +205,7 @@ fn visit_item(e: &Env, i: &ast::Item) { } else { None }) - .collect::<~[&ast::Attribute]>(); + .collect::>(); for m in link_args.iter() { match m.meta_item_list() { Some(items) => { diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 61f2075fcce65..788b2a5e6cd32 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -133,7 +133,7 @@ pub fn render(w: &mut io::Writer, s: &str, print_toc: bool) -> fmt::Result { slice::raw::buf_as_slice((*text).data, (*text).size as uint, |text| { let text = str::from_utf8(text).unwrap(); let mut lines = text.lines().filter(|l| stripped_filtered_line(*l).is_none()); - let text = lines.collect::<~[&str]>().connect("\n"); + let text = lines.collect::>().connect("\n"); let buf = buf { data: text.as_bytes().as_ptr(), @@ -186,7 +186,7 @@ pub fn render(w: &mut io::Writer, s: &str, print_toc: bool) -> fmt::Result { Some(s) => s.to_lower().into_str(), None => s.to_owned() } - }).collect::<~[~str]>().connect("-"); + }).collect::>().connect("-"); let opaque = unsafe {&mut *(opaque as *mut my_opaque)}; @@ -285,7 +285,7 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) { let tests = &mut *(opaque as *mut ::test::Collector); let text = str::from_utf8(text).unwrap(); let mut lines = text.lines().map(|l| stripped_filtered_line(l).unwrap_or(l)); - let text = lines.collect::<~[&str]>().connect("\n"); + let text = lines.collect::>().connect("\n"); tests.add_test(text, should_fail, no_run, ignore); }) } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 3ed4ece514ad0..9e5c8f05c5008 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1205,8 +1205,8 @@ fn item_trait(w: &mut Writer, it: &clean::Item, it.name.get_ref().as_slice(), t.generics, parents)); - let required = t.methods.iter().filter(|m| m.is_req()).collect::<~[&clean::TraitMethod]>(); - let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<~[&clean::TraitMethod]>(); + let required = t.methods.iter().filter(|m| m.is_req()).collect::>(); + let provided = t.methods.iter().filter(|m| !m.is_req()).collect::>(); if t.methods.len() == 0 { try!(write!(w, "\\{ \\}")); @@ -1502,11 +1502,11 @@ fn render_methods(w: &mut Writer, it: &clean::Item) -> fmt::Result { let mut non_trait = v.iter().filter(|p| { p.ref0().trait_.is_none() }); - let non_trait = non_trait.collect::<~[&(clean::Impl, Option<~str>)]>(); + let non_trait = non_trait.collect::)>>(); let mut traits = v.iter().filter(|p| { p.ref0().trait_.is_some() }); - let traits = traits.collect::<~[&(clean::Impl, Option<~str>)]>(); + let traits = traits.collect::)>>(); if non_trait.len() > 0 { try!(write!(w, "

Methods

")); diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index be91279844209..be1a17e3e3143 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -161,12 +161,12 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int } /// Run any tests/code examples in the markdown file `input`. -pub fn test(input: &str, libs: HashSet, mut test_args: ~[~str]) -> int { +pub fn test(input: &str, libs: HashSet, mut test_args: Vec<~str>) -> int { let input_str = load_or_return!(input, 1, 2); let mut collector = Collector::new(input.to_owned(), libs, true, true); find_testable_code(input_str, &mut collector); test_args.unshift(~"rustdoctest"); - testing::test_main(test_args, collector.tests); + testing::test_main(test_args.as_slice(), collector.tests); 0 } diff --git a/src/librustuv/access.rs b/src/librustuv/access.rs index 0d2550d4ebda2..3ea58a71cfe3c 100644 --- a/src/librustuv/access.rs +++ b/src/librustuv/access.rs @@ -31,7 +31,7 @@ pub struct Guard<'a> { } struct Inner { - queue: ~[BlockedTask], + queue: Vec, held: bool, } @@ -39,7 +39,7 @@ impl Access { pub fn new() -> Access { Access { inner: UnsafeArc::new(Inner { - queue: ~[], + queue: vec![], held: false, }) } diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index d04aa4082c45c..f6c138b8c669d 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -170,14 +170,14 @@ impl<'a> Stats for &'a [f64] { // FIXME #11059 handle NaN, inf and overflow #[allow(deprecated_owned_vector)] fn sum(self) -> f64 { - let mut partials : ~[f64] = ~[]; + let mut partials = vec![]; for &mut x in self.iter() { let mut j = 0; // This inner loop applies `hi`/`lo` summation to each // partial so that the list of partial sums remains exact. for i in range(0, partials.len()) { - let mut y = partials[i]; + let mut y = *partials.get(i); if num::abs(x) < num::abs(y) { mem::swap(&mut x, &mut y); } @@ -186,7 +186,7 @@ impl<'a> Stats for &'a [f64] { let hi = x + y; let lo = y - (hi - x); if lo != 0f64 { - partials[j] = lo; + *partials.get_mut(j) = lo; j += 1; } x = hi; @@ -194,7 +194,7 @@ impl<'a> Stats for &'a [f64] { if j >= partials.len() { partials.push(x); } else { - partials[j] = x; + *partials.get_mut(j) = x; partials.truncate(j+1); } } diff --git a/src/libworkcache/lib.rs b/src/libworkcache/lib.rs index 748ca378e4d53..623488ac6129d 100644 --- a/src/libworkcache/lib.rs +++ b/src/libworkcache/lib.rs @@ -17,6 +17,7 @@ html_root_url = "http://static.rust-lang.org/doc/master")] #![feature(phase)] #![allow(visible_private_types)] +#![deny(deprecated_owned_vector)] #[phase(syntax, link)] extern crate log; extern crate serialize; @@ -319,8 +320,8 @@ impl Exec { } // returns pairs of (kind, name) - pub fn lookup_discovered_inputs(&self) -> ~[(~str, ~str)] { - let mut rs = ~[]; + pub fn lookup_discovered_inputs(&self) -> Vec<(~str, ~str)> { + let mut rs = vec![]; let WorkMap(ref discovered_inputs) = self.discovered_inputs; for (k, v) in discovered_inputs.iter() { let KindMap(ref vmap) = *v; @@ -341,8 +342,8 @@ impl<'a> Prep<'a> { } } - pub fn lookup_declared_inputs(&self) -> ~[~str] { - let mut rs = ~[]; + pub fn lookup_declared_inputs(&self) -> Vec<~str> { + let mut rs = vec![]; let WorkMap(ref declared_inputs) = self.declared_inputs; for (_, v) in declared_inputs.iter() { let KindMap(ref vmap) = *v; diff --git a/src/test/bench/shootout-binarytrees.rs b/src/test/bench/shootout-binarytrees.rs index 62b01779ac25a..49184e188ebb6 100644 --- a/src/test/bench/shootout-binarytrees.rs +++ b/src/test/bench/shootout-binarytrees.rs @@ -76,7 +76,7 @@ fn main() { format!("{}\t trees of depth {}\t check: {}", iterations * 2, depth, chk) }) - }).collect::<~[Future<~str>]>(); + }).collect::>>(); for message in messages.mut_iter() { println!("{}", *message.get_ref()); From b99482801fd09f33c70329bc72fc6efebd7cd3b5 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 8 Apr 2014 22:54:06 -0700 Subject: [PATCH 14/28] Stop using transmute_mut in RefCell This is supposedly undefined behavior now that Unsafe exists, so we'll use Cell instead. --- src/libstd/cell.rs | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/src/libstd/cell.rs b/src/libstd/cell.rs index 40c6c3ebccf0b..ec064f4f5ec73 100644 --- a/src/libstd/cell.rs +++ b/src/libstd/cell.rs @@ -10,7 +10,6 @@ //! Types dealing with dynamic mutability -use cast; use clone::Clone; use cmp::Eq; use fmt; @@ -70,7 +69,7 @@ impl fmt::Show for Cell { /// A mutable memory location with dynamically checked borrow rules pub struct RefCell { value: Unsafe, - borrow: BorrowFlag, + borrow: Cell, nocopy: marker::NoCopy, noshare: marker::NoShare, } @@ -86,22 +85,18 @@ impl RefCell { pub fn new(value: T) -> RefCell { RefCell { value: Unsafe::new(value), + borrow: Cell::new(UNUSED), nocopy: marker::NoCopy, noshare: marker::NoShare, - borrow: UNUSED, } } /// Consumes the `RefCell`, returning the wrapped value. pub fn unwrap(self) -> T { - assert!(self.borrow == UNUSED); + assert!(self.borrow.get() == UNUSED); unsafe{self.value.unwrap()} } - unsafe fn as_mut<'a>(&'a self) -> &'a mut RefCell { - cast::transmute_mut(self) - } - /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple @@ -109,10 +104,10 @@ impl RefCell { /// /// Returns `None` if the value is currently mutably borrowed. pub fn try_borrow<'a>(&'a self) -> Option> { - match self.borrow { + match self.borrow.get() { WRITING => None, - _ => { - unsafe { self.as_mut().borrow += 1; } + borrow => { + self.borrow.set(borrow + 1); Some(Ref { parent: self }) } } @@ -140,11 +135,10 @@ impl RefCell { /// /// Returns `None` if the value is currently borrowed. pub fn try_borrow_mut<'a>(&'a self) -> Option> { - match self.borrow { - UNUSED => unsafe { - let mut_self = self.as_mut(); - mut_self.borrow = WRITING; - Some(RefMut { parent: mut_self }) + match self.borrow.get() { + UNUSED => { + self.borrow.set(WRITING); + Some(RefMut { parent: self }) }, _ => None } @@ -186,8 +180,9 @@ pub struct Ref<'b, T> { #[unsafe_destructor] impl<'b, T> Drop for Ref<'b, T> { fn drop(&mut self) { - assert!(self.parent.borrow != WRITING && self.parent.borrow != UNUSED); - unsafe { self.parent.as_mut().borrow -= 1; } + let borrow = self.parent.borrow.get(); + assert!(borrow != WRITING && borrow != UNUSED); + self.parent.borrow.set(borrow - 1); } } @@ -200,14 +195,15 @@ impl<'b, T> Deref for Ref<'b, T> { /// Wraps a mutable borrowed reference to a value in a `RefCell` box. pub struct RefMut<'b, T> { - parent: &'b mut RefCell + parent: &'b RefCell } #[unsafe_destructor] impl<'b, T> Drop for RefMut<'b, T> { fn drop(&mut self) { - assert!(self.parent.borrow == WRITING); - self.parent.borrow = UNUSED; + let borrow = self.parent.borrow.get(); + assert!(borrow == WRITING); + self.parent.borrow.set(UNUSED); } } From a70f8d9cf3619aed475874c1b27595e0c86e627e Mon Sep 17 00:00:00 2001 From: OGINO Masanori Date: Wed, 9 Apr 2014 13:42:44 +0900 Subject: [PATCH 15/28] Remove an unnecessary file. Signed-off-by: OGINO Masanori --- src/libnative/io/p | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/libnative/io/p diff --git a/src/libnative/io/p b/src/libnative/io/p deleted file mode 100644 index e69de29bb2d1d..0000000000000 From da25539c1ab295ec40261109557dd4526923928c Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Tue, 8 Apr 2014 22:07:15 +0200 Subject: [PATCH 16/28] Generalized the pretty-print entry points to support `-o `. --- src/librustc/driver/driver.rs | 20 +++++++++++++++---- src/librustc/lib.rs | 2 +- .../run-make/pretty-print-to-file/Makefile | 5 +++++ .../run-make/pretty-print-to-file/input.pp | 13 ++++++++++++ .../run-make/pretty-print-to-file/input.rs | 15 ++++++++++++++ 5 files changed, 50 insertions(+), 5 deletions(-) create mode 100644 src/test/run-make/pretty-print-to-file/Makefile create mode 100644 src/test/run-make/pretty-print-to-file/input.pp create mode 100644 src/test/run-make/pretty-print-to-file/input.rs diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 8a593d5f92a2a..1b3653c6948a6 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -664,7 +664,8 @@ impl pprust::PpAnn for TypedAnnotation { pub fn pretty_print_input(sess: Session, cfg: ast::CrateConfig, input: &Input, - ppm: PpMode) { + ppm: PpMode, + ofile: Option) { let krate = phase_1_parse_input(&sess, cfg, input); let id = link::find_crate_id(krate.attrs.as_slice(), input.filestem()); @@ -682,6 +683,17 @@ pub fn pretty_print_input(sess: Session, let src = Vec::from_slice(sess.codemap().get_filemap(src_name).src.as_bytes()); let mut rdr = MemReader::new(src); + let out = match ofile { + None => ~io::stdout() as ~Writer, + Some(p) => { + let r = io::File::create(&p); + match r { + Ok(w) => ~w as ~Writer, + Err(e) => fail!("print-print failed to open {} due to {}", + p.display(), e), + } + } + }; match ppm { PpmIdentified | PpmExpandedIdentified => { pprust::print_crate(sess.codemap(), @@ -689,7 +701,7 @@ pub fn pretty_print_input(sess: Session, &krate, src_name, &mut rdr, - ~io::stdout(), + out, &IdentifiedAnnotation, is_expanded) } @@ -704,7 +716,7 @@ pub fn pretty_print_input(sess: Session, &krate, src_name, &mut rdr, - ~io::stdout(), + out, &annotation, is_expanded) } @@ -714,7 +726,7 @@ pub fn pretty_print_input(sess: Session, &krate, src_name, &mut rdr, - ~io::stdout(), + out, &pprust::NoAnn, is_expanded) } diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index 3f72be673e0a0..20f9e868c30e1 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -293,7 +293,7 @@ pub fn run_compiler(args: &[~str]) { }); match pretty { Some::(ppm) => { - d::pretty_print_input(sess, cfg, &input, ppm); + d::pretty_print_input(sess, cfg, &input, ppm, ofile); return; } None:: => {/* continue */ } diff --git a/src/test/run-make/pretty-print-to-file/Makefile b/src/test/run-make/pretty-print-to-file/Makefile new file mode 100644 index 0000000000000..1c1242ada8a6d --- /dev/null +++ b/src/test/run-make/pretty-print-to-file/Makefile @@ -0,0 +1,5 @@ +-include ../tools.mk + +all: + $(RUSTC) -o $(TMPDIR)/input.out --pretty=normal input.rs + diff -u $(TMPDIR)/input.out input.pp diff --git a/src/test/run-make/pretty-print-to-file/input.pp b/src/test/run-make/pretty-print-to-file/input.pp new file mode 100644 index 0000000000000..a6dd6b6778ed0 --- /dev/null +++ b/src/test/run-make/pretty-print-to-file/input.pp @@ -0,0 +1,13 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + + +#[crate_type = "lib"] +pub fn foo() -> i32 { 45 } diff --git a/src/test/run-make/pretty-print-to-file/input.rs b/src/test/run-make/pretty-print-to-file/input.rs new file mode 100644 index 0000000000000..8e3ec36318749 --- /dev/null +++ b/src/test/run-make/pretty-print-to-file/input.rs @@ -0,0 +1,15 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[crate_type="lib"] + +pub fn +foo() -> i32 +{ 45 } From 6d6d4c987faeec2242e58527f4bb8073083918a3 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 8 Apr 2014 11:38:18 -0700 Subject: [PATCH 17/28] test: Add a test for #7663 I think that the test case from this issue has become out of date with resolve changes in the past 9 months, and it's not entirely clear to me what the original bug was. Regardless, it seems like tricky resolve behavior, so tests were added to make sure things resolved correctly and warnings were correctly reported. Closes #7663 --- src/test/compile-fail/issue-7663.rs | 56 ++++++++++++++++++++++++++++ src/test/run-pass/issue-7663.rs | 57 +++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 src/test/compile-fail/issue-7663.rs create mode 100644 src/test/run-pass/issue-7663.rs diff --git a/src/test/compile-fail/issue-7663.rs b/src/test/compile-fail/issue-7663.rs new file mode 100644 index 0000000000000..baea483ad982b --- /dev/null +++ b/src/test/compile-fail/issue-7663.rs @@ -0,0 +1,56 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(globs)] +#![deny(unused_imports)] +#![allow(dead_code)] + +mod test1 { + + mod foo { pub fn p() -> int { 1 } } + mod bar { pub fn p() -> int { 2 } } + + pub mod baz { + use test1::foo::*; //~ ERROR: unused import + use test1::bar::*; + + pub fn my_main() { assert!(p() == 2); } + } +} + +mod test2 { + + mod foo { pub fn p() -> int { 1 } } + mod bar { pub fn p() -> int { 2 } } + + pub mod baz { + use test2::foo::p; //~ ERROR: unused import + use test2::bar::p; + + pub fn my_main() { assert!(p() == 2); } + } +} + +mod test3 { + + mod foo { pub fn p() -> int { 1 } } + mod bar { pub fn p() -> int { 2 } } + + pub mod baz { + use test3::foo::*; //~ ERROR: unused import + use test3::bar::p; + + pub fn my_main() { assert!(p() == 2); } + } +} + +fn main() { +} + diff --git a/src/test/run-pass/issue-7663.rs b/src/test/run-pass/issue-7663.rs new file mode 100644 index 0000000000000..baf37e314173d --- /dev/null +++ b/src/test/run-pass/issue-7663.rs @@ -0,0 +1,57 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(globs)] +#![allow(unused_imports, dead_code)] + +mod test1 { + + mod foo { pub fn p() -> int { 1 } } + mod bar { pub fn p() -> int { 2 } } + + pub mod baz { + use test1::foo::*; + use test1::bar::*; + + pub fn my_main() { assert!(p() == 2); } + } +} + +mod test2 { + + mod foo { pub fn p() -> int { 1 } } + mod bar { pub fn p() -> int { 2 } } + + pub mod baz { + use test2::foo::p; + use test2::bar::p; + + pub fn my_main() { assert!(p() == 2); } + } +} + +mod test3 { + + mod foo { pub fn p() -> int { 1 } } + mod bar { pub fn p() -> int { 2 } } + + pub mod baz { + use test3::foo::*; + use test3::bar::p; + + pub fn my_main() { assert!(p() == 2); } + } +} + +fn main() { + test1::baz::my_main(); + test2::baz::my_main(); + test3::baz::my_main(); +} From dd00bf37910058d3509a7a709de7b98ca11de091 Mon Sep 17 00:00:00 2001 From: Kang Seonghoon Date: Wed, 9 Apr 2014 02:45:53 +0900 Subject: [PATCH 18/28] mk: Add a dummy CFG_COMPILER_HOST_TRIPLE to rustdoc invocation. Otherwise it will prohibit `make compiler-docs` on Windows. --- mk/docs.mk | 1 + 1 file changed, 1 insertion(+) diff --git a/mk/docs.mk b/mk/docs.mk index fab828571cd4f..ddc3b175d1015 100644 --- a/mk/docs.mk +++ b/mk/docs.mk @@ -269,6 +269,7 @@ LIB_DOC_DEP_$(1) = $$(CRATEFILE_$(1)) $$(RSINPUTS_$(1)) endif $(2) += doc/$(1)/index.html +doc/$(1)/index.html: CFG_COMPILER_HOST_TRIPLE = $(CFG_TARGET) doc/$(1)/index.html: $$(LIB_DOC_DEP_$(1)) @$$(call E, rustdoc $$@) $$(Q)$$(RUSTDOC) --cfg dox --cfg stage2 $$< From 34ece7ad718469b4634d5eadd91d078d95bbd6c5 Mon Sep 17 00:00:00 2001 From: Kang Seonghoon Date: Wed, 9 Apr 2014 02:47:52 +0900 Subject: [PATCH 19/28] rustdoc: Clean the `initSearch` routine up. --- src/librustdoc/html/static/main.js | 82 ++++++++++++++---------------- 1 file changed, 39 insertions(+), 43 deletions(-) diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index ffdf67e56cf7f..1904ab27d17d9 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -137,8 +137,6 @@ val = valLower, typeFilter = query.type, results = [], - aa = 0, - bb = 0, split = valLower.split("::"); //remove empty keywords @@ -150,16 +148,16 @@ } // quoted values mean literal search - bb = searchWords.length; + var nSearchWords = searchWords.length; if ((val.charAt(0) === "\"" || val.charAt(0) === "'") && val.charAt(val.length - 1) === val.charAt(0)) { val = val.substr(1, val.length - 2); - for (aa = 0; aa < bb; aa += 1) { - if (searchWords[aa] === val) { + for (var i = 0; i < nSearchWords; i += 1) { + if (searchWords[i] === val) { // filter type: ... queries - if (!typeFilter || typeFilter === searchIndex[aa].ty) { - results.push([aa, -1]); + if (!typeFilter || typeFilter === searchIndex[i].ty) { + results.push({id: i, index: -1}); } } if (results.length === max) { @@ -170,14 +168,14 @@ // gather matching search results up to a certain maximum val = val.replace(/\_/g, ""); for (var i = 0; i < split.length; i++) { - for (aa = 0; aa < bb; aa += 1) { - if (searchWords[aa].indexOf(split[i]) > -1 || - searchWords[aa].indexOf(val) > -1 || - searchWords[aa].replace(/_/g, "").indexOf(val) > -1) + for (var j = 0; j < nSearchWords; j += 1) { + if (searchWords[j].indexOf(split[i]) > -1 || + searchWords[j].indexOf(val) > -1 || + searchWords[j].replace(/_/g, "").indexOf(val) > -1) { // filter type: ... queries - if (!typeFilter || typeFilter === searchIndex[aa].ty) { - results.push([aa, searchWords[aa].replace(/_/g, "").indexOf(val)]); + if (!typeFilter || typeFilter === searchIndex[j].ty) { + results.push({id: j, index: searchWords[j].replace(/_/g, "").indexOf(val)}); } } if (results.length === max) { @@ -187,13 +185,12 @@ } } - bb = results.length; - for (aa = 0; aa < bb; aa += 1) { - results[aa].push(searchIndex[results[aa][0]].ty); - results[aa].push(searchIndex[results[aa][0]].path); - results[aa].push(searchIndex[results[aa][0]].name); - results[aa].push(searchIndex[results[aa][0]].parent); - results[aa].push(searchIndex[results[aa][0]].crate); + var nresults = results.length; + for (var i = 0; i < nresults; i += 1) { + results[i].word = searchWords[results[i].id]; + results[i].item = searchIndex[results[i].id] || {}; + results[i].ty = results[i].item.ty; + results[i].path = results[i].item.path; } // if there are no results then return to default and fail if (results.length === 0) { @@ -202,31 +199,31 @@ // sort by exact match results.sort(function search_complete_sort0(aaa, bbb) { - if (searchWords[aaa[0]] === valLower && - searchWords[bbb[0]] !== valLower) { + if (aaa.word === valLower && + bbb.word !== valLower) { return 1; } }); // first sorting attempt // sort by item name length results.sort(function search_complete_sort1(aaa, bbb) { - if (searchWords[aaa[0]].length > searchWords[bbb[0]].length) { + if (aaa.word.length > bbb.word.length) { return 1; } }); // second sorting attempt // sort by item name results.sort(function search_complete_sort1(aaa, bbb) { - if (searchWords[aaa[0]].length === searchWords[bbb[0]].length && - searchWords[aaa[0]] > searchWords[bbb[0]]) { + if (aaa.word.length === bbb.word.length && + aaa.word > bbb.word) { return 1; } }); // third sorting attempt // sort by index of keyword in item name - if (results[0][1] !== -1) { + if (results[0].index !== -1) { results.sort(function search_complete_sort1(aaa, bbb) { - if (aaa[1] > bbb[1] && bbb[1] === 0) { + if (aaa.index > bbb.index && bbb.index === 0) { return 1; } }); @@ -234,38 +231,38 @@ // fourth sorting attempt // sort by type results.sort(function search_complete_sort3(aaa, bbb) { - if (searchWords[aaa[0]] === searchWords[bbb[0]] && - aaa[2] > bbb[2]) { + if (aaa.word === bbb.word && + aaa.ty > bbb.ty) { return 1; } }); // fifth sorting attempt // sort by path results.sort(function search_complete_sort4(aaa, bbb) { - if (searchWords[aaa[0]] === searchWords[bbb[0]] && - aaa[2] === bbb[2] && aaa[3] > bbb[3]) { + if (aaa.word === bbb.word && + aaa.ty === bbb.ty && aaa.path > bbb.path) { return 1; } }); // sixth sorting attempt // remove duplicates, according to the data provided - for (aa = results.length - 1; aa > 0; aa -= 1) { - if (searchWords[results[aa][0]] === searchWords[results[aa - 1][0]] && - results[aa][2] === results[aa - 1][2] && - results[aa][3] === results[aa - 1][3]) + for (var i = results.length - 1; i > 0; i -= 1) { + if (results[i].word === results[i - 1].word && + results[i].ty === results[i - 1].ty && + results[i].path === results[i - 1].path) { - results[aa][0] = -1; + results[i].id = -1; } } for (var i = 0; i < results.length; i++) { var result = results[i], - name = result[4].toLowerCase(), - path = result[3].toLowerCase(), - parent = allPaths[result[6]][result[5]]; + name = result.item.name.toLowerCase(), + path = result.item.path.toLowerCase(), + parent = allPaths[result.item.crate][result.item.parent]; var valid = validateResult(name, path, split, parent); if (!valid) { - result[0] = -1; + result.id = -1; } } return results; @@ -495,8 +492,8 @@ resultIndex = execQuery(query, 20000, index); len = resultIndex.length; for (i = 0; i < len; i += 1) { - if (resultIndex[i][0] > -1) { - obj = searchIndex[resultIndex[i][0]]; + if (resultIndex[i].id > -1) { + obj = searchIndex[resultIndex[i].id]; filterdata.push([obj.name, obj.ty, obj.path, obj.desc]); results.push(obj); } @@ -580,7 +577,6 @@ // Draw a convenient sidebar of known crates if we have a listing if (rootPath == '../') { - console.log('here'); var sidebar = $('.sidebar'); var div = $('
').attr('class', 'block crate'); div.append($('

').text('Crates')); From 85299e360cda49d61b8d9a509319e19bc206c336 Mon Sep 17 00:00:00 2001 From: Kang Seonghoon Date: Wed, 9 Apr 2014 03:25:54 +0900 Subject: [PATCH 20/28] rustdoc: Prune the paths that do not appear in the index. For the full library and compiler docs, the size of `search-index.js` decreases by 13% (18.5% after gzip -9) which is a substantial gain. --- src/librustdoc/html/render.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 9e5c8f05c5008..ff437ff23dce7 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -262,10 +262,11 @@ pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> { cache.stack.push(krate.name.clone()); krate = cache.fold_crate(krate); { + let Cache { search_index: ref mut index, + orphan_methods: ref meths, paths: ref mut paths, ..} = cache; + // Attach all orphan methods to the type's definition if the type // has since been learned. - let Cache { search_index: ref mut index, - orphan_methods: ref meths, paths: ref paths, ..} = cache; for &(ref pid, ref item) in meths.iter() { match paths.find(pid) { Some(&(ref fqp, _)) => { @@ -280,6 +281,18 @@ pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> { None => {} } }; + + // Prune the paths that do not appear in the index. + let mut unseen: HashSet = paths.keys().map(|&id| id).collect(); + for item in index.iter() { + match item.parent { + Some(ref pid) => { unseen.remove(pid); } + None => {} + } + } + for pid in unseen.iter() { + paths.remove(pid); + } } // Publish the search index From ec996737fe5e3f0693f4e92a33a53c2c189f36ba Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 7 Apr 2014 15:40:58 -0700 Subject: [PATCH 21/28] rustc: Remove absolute rpaths Concerns have been raised about using absolute rpaths in #11746, and this is the first step towards not relying on rpaths at all. The only current use case for an absolute rpath is when a non-installed rust builds an executable that then moves from is built location. The relative rpath back to libstd and absolute rpath to the installation directory still remain (CFG_PREFIX). Closes #11746 Rebasing of #12754 --- mk/main.mk | 4 ---- src/librustc/back/rpath.rs | 30 +----------------------------- 2 files changed, 1 insertion(+), 33 deletions(-) diff --git a/mk/main.mk b/mk/main.mk index fa19a4b380ec6..f2bcdbd4bd539 100644 --- a/mk/main.mk +++ b/mk/main.mk @@ -358,7 +358,6 @@ CFGFLAG$(1)_T_$(2)_H_$(3) = stage1 endif endif -ifdef CFG_DISABLE_RPATH ifeq ($$(OSTYPE_$(3)),apple-darwin) RPATH_VAR$(1)_T_$(2)_H_$(3) := \ DYLD_LIBRARY_PATH="$$$$DYLD_LIBRARY_PATH:$$(CURDIR)/$$(HLIB$(1)_H_$(3))" @@ -366,9 +365,6 @@ else RPATH_VAR$(1)_T_$(2)_H_$(3) := \ LD_LIBRARY_PATH="$$$$LD_LIBRARY_PATH:$$(CURDIR)/$$(HLIB$(1)_H_$(3))" endif -else - RPATH_VAR$(1)_T_$(2)_H_$(3) := -endif STAGE$(1)_T_$(2)_H_$(3) := \ $$(Q)$$(RPATH_VAR$(1)_T_$(2)_H_$(3)) \ diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index c47f9893cd2ef..73ccc8871caea 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -87,10 +87,6 @@ fn get_rpaths(os: abi::Os, // crates they depend on. let rel_rpaths = get_rpaths_relative_to_output(os, output, libs); - // Make backup absolute paths to the libraries. Binaries can - // be moved as long as the crates they link against don't move. - let abs_rpaths = get_absolute_rpaths(libs); - // And a final backup rpath to the global library location. let fallback_rpaths = vec!(get_install_prefix_rpath(sysroot, target_triple)); @@ -102,11 +98,9 @@ fn get_rpaths(os: abi::Os, } log_rpaths("relative", rel_rpaths.as_slice()); - log_rpaths("absolute", abs_rpaths.as_slice()); log_rpaths("fallback", fallback_rpaths.as_slice()); let mut rpaths = rel_rpaths; - rpaths.push_all(abs_rpaths.as_slice()); rpaths.push_all(fallback_rpaths.as_slice()); // Remove duplicates @@ -146,17 +140,6 @@ pub fn get_rpath_relative_to_output(os: abi::Os, prefix+"/"+relative.as_str().expect("non-utf8 component in path") } -fn get_absolute_rpaths(libs: &[Path]) -> Vec<~str> { - libs.iter().map(|a| get_absolute_rpath(a)).collect() -} - -pub fn get_absolute_rpath(lib: &Path) -> ~str { - let mut p = os::make_absolute(lib); - p.pop(); - // FIXME (#9639): This needs to handle non-utf8 paths - p.as_str().expect("non-utf8 component in rpath").to_owned() -} - pub fn get_install_prefix_rpath(sysroot: &Path, target_triple: &str) -> ~str { let install_prefix = env!("CFG_PREFIX"); @@ -183,7 +166,7 @@ pub fn minimize_rpaths(rpaths: &[~str]) -> Vec<~str> { mod test { use std::os; - use back::rpath::{get_absolute_rpath, get_install_prefix_rpath}; + use back::rpath::get_install_prefix_rpath; use back::rpath::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output}; use syntax::abi; use metadata::filesearch; @@ -258,15 +241,4 @@ mod test { &Path::new("lib/libstd.so")); assert_eq!(res.as_slice(), "@loader_path/../lib"); } - - #[test] - fn test_get_absolute_rpath() { - let res = get_absolute_rpath(&Path::new("lib/libstd.so")); - let lib = os::make_absolute(&Path::new("lib")); - debug!("test_get_absolute_rpath: {} vs. {}", - res.to_str(), lib.display()); - - // FIXME (#9639): This needs to handle non-utf8 paths - assert_eq!(res.as_slice(), lib.as_str().expect("non-utf8 component in path")); - } } From f9e17e1d336f2988f6cf27db95924dd462f66e0d Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 8 Apr 2014 10:05:18 -0700 Subject: [PATCH 22/28] rustc: Don't rpath to librustrt.dylib This library no longer exists, there's no reason for this rpath to exist any more. --- src/librustc/back/rpath.rs | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 73ccc8871caea..4b54b1f600885 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -42,10 +42,9 @@ pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<~str> { let sysroot = sess.filesearch().sysroot; let output = out_filename; let libs = sess.cstore.get_used_crates(cstore::RequireDynamic); - let libs = libs.move_iter().filter_map(|(_, l)| l.map(|p| p.clone())).collect(); - // We don't currently rpath extern libraries, but we know - // where rustrt is and we know every rust program needs it - let libs = slice::append_one(libs, get_sysroot_absolute_rt_lib(sess)); + let libs = libs.move_iter().filter_map(|(_, l)| { + l.map(|p| p.clone()) + }).collect::<~[_]>(); let rpaths = get_rpaths(os, sysroot, output, libs, sess.opts.target_triple); @@ -53,14 +52,6 @@ pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<~str> { flags } -fn get_sysroot_absolute_rt_lib(sess: &Session) -> Path { - let sysroot = sess.filesearch().sysroot; - let r = filesearch::relative_target_lib_path(sysroot, sess.opts.target_triple); - let mut p = sysroot.join(&r); - p.push(os::dll_filename("rustrt")); - p -} - pub fn rpaths_to_flags(rpaths: &[~str]) -> Vec<~str> { let mut ret = Vec::new(); for rpath in rpaths.iter() { From 25a6b6ef8b4a2852c98585496146ca9d3da37b1b Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 8 Apr 2014 10:06:11 -0700 Subject: [PATCH 23/28] rustc: Add a realpath utility function This is required in rustc to resolve symlinks for utilities such as the sysroot and the rpath values which are encoded into binaries. --- src/librustc/lib.rs | 1 + src/librustc/util/fs.rs | 103 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 src/librustc/util/fs.rs diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index 20f9e868c30e1..b9acd41321520 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -127,6 +127,7 @@ pub mod util { pub mod ppaux; pub mod sha2; pub mod nodemap; + pub mod fs; } pub mod lib { diff --git a/src/librustc/util/fs.rs b/src/librustc/util/fs.rs new file mode 100644 index 0000000000000..c051b8e60cd80 --- /dev/null +++ b/src/librustc/util/fs.rs @@ -0,0 +1,103 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::io; +use std::io::fs; +use std::os; + +/// Returns an absolute path in the filesystem that `path` points to. The +/// returned path does not contain any symlinks in its hierarchy. +pub fn realpath(original: &Path) -> io::IoResult { + static MAX_LINKS_FOLLOWED: uint = 256; + let original = os::make_absolute(original); + + // Right now lstat on windows doesn't work quite well + if cfg!(windows) { + return Ok(original) + } + + let result = original.root_path(); + let mut result = result.expect("make_absolute has no root_path"); + let mut followed = 0; + + for part in original.components() { + result.push(part); + + loop { + if followed == MAX_LINKS_FOLLOWED { + return Err(io::standard_error(io::InvalidInput)) + } + + match fs::lstat(&result) { + Err(..) => break, + Ok(ref stat) if stat.kind != io::TypeSymlink => break, + Ok(..) => { + followed += 1; + let path = try!(fs::readlink(&result)); + result.pop(); + result.push(path); + } + } + } + } + + return Ok(result); +} + +#[cfg(not(windows), test)] +mod test { + use std::io; + use std::io::fs::{File, symlink, mkdir, mkdir_recursive}; + use super::realpath; + use std::io::TempDir; + + #[test] + fn realpath_works() { + let tmpdir = TempDir::new("rustc-fs").unwrap(); + let tmpdir = realpath(tmpdir.path()).unwrap(); + let file = tmpdir.join("test"); + let dir = tmpdir.join("test2"); + let link = dir.join("link"); + let linkdir = tmpdir.join("test3"); + + File::create(&file).unwrap(); + mkdir(&dir, io::UserRWX).unwrap(); + symlink(&file, &link).unwrap(); + symlink(&dir, &linkdir).unwrap(); + + assert!(realpath(&tmpdir).unwrap() == tmpdir); + assert!(realpath(&file).unwrap() == file); + assert!(realpath(&link).unwrap() == file); + assert!(realpath(&linkdir).unwrap() == dir); + assert!(realpath(&linkdir.join("link")).unwrap() == file); + } + + #[test] + fn realpath_works_tricky() { + let tmpdir = TempDir::new("rustc-fs").unwrap(); + let tmpdir = realpath(tmpdir.path()).unwrap(); + + let a = tmpdir.join("a"); + let b = a.join("b"); + let c = b.join("c"); + let d = a.join("d"); + let e = d.join("e"); + let f = a.join("f"); + + mkdir_recursive(&b, io::UserRWX).unwrap(); + mkdir_recursive(&d, io::UserRWX).unwrap(); + File::create(&f).unwrap(); + symlink(&Path::new("../d/e"), &c).unwrap(); + symlink(&Path::new("../f"), &e).unwrap(); + + assert!(realpath(&c).unwrap() == f); + assert!(realpath(&e).unwrap() == f); + } +} From 3f2c55f7d5b5c7717dd12eef4572c52a4e8ff550 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 8 Apr 2014 10:15:46 -0700 Subject: [PATCH 24/28] rustc: Use realpath() for sysroot/rpath When calculating the sysroot, it's more accurate to use realpath() rather than just one readlink() to account for any intermediate symlinks that the rustc binary resolves itself to. For rpath, realpath() is necessary because the rpath must dictate a relative rpath from the destination back to the originally linked library, which works more robustly if there are no symlinks involved. Concretely, any binary generated on OSX into $TMPDIR requires an absolute rpath because the temporary directory is behind a symlink with one layer of indirection. This symlink causes all relative rpaths to fail to resolve. cc #11734 cc #11857 --- src/librustc/back/rpath.rs | 7 ++++--- src/librustc/metadata/filesearch.rs | 17 ++++++----------- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 4b54b1f600885..e455c4ad23ce0 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -12,9 +12,10 @@ use driver::session::Session; use metadata::cstore; use metadata::filesearch; +use util::fs; use collections::HashSet; -use std::{os, slice}; +use std::os; use syntax::abi; fn not_win32(os: abi::Os) -> bool { @@ -121,9 +122,9 @@ pub fn get_rpath_relative_to_output(os: abi::Os, abi::OsWin32 => unreachable!() }; - let mut lib = os::make_absolute(lib); + let mut lib = fs::realpath(&os::make_absolute(lib)).unwrap(); lib.pop(); - let mut output = os::make_absolute(output); + let mut output = fs::realpath(&os::make_absolute(output)).unwrap(); output.pop(); let relative = lib.path_relative_from(&output); let relative = relative.expect("could not create rpath relative to output"); diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index 7a531c5c128bf..f4ea386a2ecad 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -15,6 +15,8 @@ use std::os; use std::io::fs; use collections::HashSet; +use myfs = util::fs; + pub enum FileMatch { FileMatches, FileDoesntMatch } // A module for searching for libraries @@ -156,17 +158,10 @@ fn make_rustpkg_target_lib_path(sysroot: &Path, pub fn get_or_default_sysroot() -> Path { // Follow symlinks. If the resolved path is relative, make it absolute. fn canonicalize(path: Option) -> Option { - path.and_then(|mut path| - match fs::readlink(&path) { - Ok(canon) => { - if canon.is_absolute() { - Some(canon) - } else { - path.pop(); - Some(path.join(canon)) - } - }, - Err(..) => Some(path), + path.and_then(|path| + match myfs::realpath(&path) { + Ok(canon) => Some(canon), + Err(e) => fail!("failed to get realpath: {}", e), }) } From 0bf4e900d421f011d7c68016308aab4998f9084e Mon Sep 17 00:00:00 2001 From: Kasey Carrothers Date: Sun, 6 Apr 2014 18:04:40 -0700 Subject: [PATCH 25/28] Renamed ast::Purity to ast::FnStyle and ast::ImpureFn to ast::NormalFn and updated associated variable and function names. --- src/librustc/metadata/csearch.rs | 2 +- src/librustc/metadata/decoder.rs | 16 ++--- src/librustc/metadata/encoder.rs | 32 +++++----- src/librustc/metadata/tydecode.rs | 14 ++-- src/librustc/metadata/tyencode.rs | 8 +-- src/librustc/middle/effect.rs | 10 +-- src/librustc/middle/resolve.rs | 10 +-- src/librustc/middle/trans/base.rs | 8 +-- src/librustc/middle/trans/consts.rs | 2 +- src/librustc/middle/trans/reflect.rs | 10 +-- src/librustc/middle/ty.rs | 28 ++++---- src/librustc/middle/ty_fold.rs | 4 +- src/librustc/middle/typeck/astconv.rs | 20 +++--- src/librustc/middle/typeck/check/method.rs | 2 +- src/librustc/middle/typeck/check/mod.rs | 64 +++++++++---------- src/librustc/middle/typeck/collect.rs | 16 ++--- src/librustc/middle/typeck/infer/coercion.rs | 2 +- src/librustc/middle/typeck/infer/combine.rs | 12 ++-- .../middle/typeck/infer/error_reporting.rs | 8 +-- src/librustc/middle/typeck/infer/glb.rs | 8 +-- src/librustc/middle/typeck/infer/lub.rs | 8 +-- src/librustc/middle/typeck/infer/sub.rs | 8 +-- src/librustc/middle/typeck/infer/test.rs | 2 +- src/librustc/middle/typeck/mod.rs | 4 +- src/librustc/util/ppaux.rs | 20 +++--- src/librustdoc/clean.rs | 22 +++---- src/librustdoc/doctree.rs | 2 +- src/librustdoc/html/format.rs | 18 +++--- src/librustdoc/html/render.rs | 14 ++-- src/librustdoc/visit_ast.rs | 4 +- src/libsyntax/ast.rs | 22 +++---- src/libsyntax/ast_util.rs | 2 +- src/libsyntax/ext/build.rs | 2 +- src/libsyntax/ext/deriving/generic.rs | 2 +- src/libsyntax/fold.rs | 12 ++-- src/libsyntax/parse/mod.rs | 2 +- src/libsyntax/parse/parser.rs | 46 ++++++------- src/libsyntax/print/pprust.rs | 50 +++++++-------- src/libsyntax/visit.rs | 6 +- .../trait-impl-method-mismatch.rs | 2 +- 40 files changed, 262 insertions(+), 262 deletions(-) diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index 977db296af96b..16068dd939b1d 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -28,7 +28,7 @@ use syntax::parse::token; pub struct StaticMethodInfo { pub ident: ast::Ident, pub def_id: ast::DefId, - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, pub vis: ast::Visibility, } diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 40f0b719f2dcb..28968a6001616 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -330,11 +330,11 @@ fn item_to_def_like(item: ebml::Doc, did: ast::DefId, cnum: ast::CrateNum) MutStatic => DlDef(ast::DefStatic(did, true)), Struct => DlDef(ast::DefStruct(did)), UnsafeFn => DlDef(ast::DefFn(did, ast::UnsafeFn)), - Fn => DlDef(ast::DefFn(did, ast::ImpureFn)), + Fn => DlDef(ast::DefFn(did, ast::NormalFn)), ForeignFn => DlDef(ast::DefFn(did, ast::ExternFn)), StaticMethod | UnsafeStaticMethod => { - let purity = if fam == UnsafeStaticMethod { ast::UnsafeFn } else - { ast::ImpureFn }; + let fn_style = if fam == UnsafeStaticMethod { ast::UnsafeFn } else + { ast::NormalFn }; // def_static_method carries an optional field of its enclosing // trait or enclosing impl (if this is an inherent static method). // So we need to detect whether this is in a trait or not, which @@ -348,7 +348,7 @@ fn item_to_def_like(item: ebml::Doc, did: ast::DefId, cnum: ast::CrateNum) ast::FromImpl(item_reqd_and_translated_parent_item(cnum, item)) }; - DlDef(ast::DefStaticMethod(did, provenance, purity)) + DlDef(ast::DefStaticMethod(did, provenance, fn_style)) } Type | ForeignType => DlDef(ast::DefTy(did)), Mod => DlDef(ast::DefMod(did)), @@ -905,17 +905,17 @@ pub fn get_static_methods_if_impl(intr: Rc, let family = item_family(impl_method_doc); match family { StaticMethod | UnsafeStaticMethod => { - let purity; + let fn_style; match item_family(impl_method_doc) { - StaticMethod => purity = ast::ImpureFn, - UnsafeStaticMethod => purity = ast::UnsafeFn, + StaticMethod => fn_style = ast::NormalFn, + UnsafeStaticMethod => fn_style = ast::UnsafeFn, _ => fail!() } static_impl_methods.push(StaticMethodInfo { ident: item_name(&*intr, impl_method_doc), def_id: item_def_id(impl_method_doc, cdata), - purity: purity, + fn_style: fn_style, vis: item_visibility(impl_method_doc), }); } diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index fcb0e3136a76e..ac62702e59ed1 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -758,12 +758,12 @@ fn encode_method_ty_fields(ecx: &EncodeContext, encode_method_fty(ecx, ebml_w, &method_ty.fty); encode_visibility(ebml_w, method_ty.vis); encode_explicit_self(ebml_w, method_ty.explicit_self); - let purity = method_ty.fty.purity; + let fn_style = method_ty.fty.fn_style; match method_ty.explicit_self { ast::SelfStatic => { - encode_family(ebml_w, purity_static_method_family(purity)); + encode_family(ebml_w, fn_style_static_method_family(fn_style)); } - _ => encode_family(ebml_w, purity_fn_family(purity)) + _ => encode_family(ebml_w, style_fn_family(fn_style)) } encode_provided_source(ebml_w, method_ty.provided_source); } @@ -811,18 +811,18 @@ fn encode_info_for_method(ecx: &EncodeContext, ebml_w.end_tag(); } -fn purity_fn_family(p: Purity) -> char { - match p { +fn style_fn_family(s: FnStyle) -> char { + match s { UnsafeFn => 'u', - ImpureFn => 'f', + NormalFn => 'f', ExternFn => 'e' } } -fn purity_static_method_family(p: Purity) -> char { - match p { +fn fn_style_static_method_family(s: FnStyle) -> char { + match s { UnsafeFn => 'U', - ImpureFn => 'F', + NormalFn => 'F', _ => fail!("extern fn can't be static") } } @@ -911,11 +911,11 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_visibility(ebml_w, vis); ebml_w.end_tag(); } - ItemFn(_, purity, _, ref generics, _) => { + ItemFn(_, fn_style, _, ref generics, _) => { add_to_index(item, ebml_w, index); ebml_w.start_tag(tag_items_data_item); encode_def_id(ebml_w, def_id); - encode_family(ebml_w, purity_fn_family(purity)); + encode_family(ebml_w, style_fn_family(fn_style)); let tps_len = generics.ty_params.len(); encode_bounds_and_type(ebml_w, ecx, &lookup_item_type(tcx, def_id)); encode_name(ebml_w, item.ident.name); @@ -1165,8 +1165,8 @@ fn encode_info_for_item(ecx: &EncodeContext, match method_ty.explicit_self { SelfStatic => { encode_family(ebml_w, - purity_static_method_family( - method_ty.fty.purity)); + fn_style_static_method_family( + method_ty.fty.fn_style)); let tpt = ty::lookup_item_type(tcx, method_def_id); encode_bounds_and_type(ebml_w, ecx, &tpt); @@ -1174,8 +1174,8 @@ fn encode_info_for_item(ecx: &EncodeContext, _ => { encode_family(ebml_w, - purity_fn_family( - method_ty.fty.purity)); + style_fn_family( + method_ty.fty.fn_style)); } } @@ -1227,7 +1227,7 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext, encode_def_id(ebml_w, local_def(nitem.id)); match nitem.node { ForeignItemFn(..) => { - encode_family(ebml_w, purity_fn_family(ImpureFn)); + encode_family(ebml_w, style_fn_family(NormalFn)); encode_bounds_and_type(ebml_w, ecx, &lookup_item_type(ecx.tcx,local_def(nitem.id))); encode_name(ebml_w, nitem.ident.name); diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index 599a1dad33d22..cf40448167028 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -449,12 +449,12 @@ fn parse_hex(st: &mut PState) -> uint { }; } -fn parse_purity(c: char) -> Purity { +fn parse_fn_style(c: char) -> FnStyle { match c { 'u' => UnsafeFn, - 'i' => ImpureFn, + 'n' => NormalFn, 'c' => ExternFn, - _ => fail!("parse_purity: bad purity {}", c) + _ => fail!("parse_fn_style: bad fn_style {}", c) } } @@ -476,13 +476,13 @@ fn parse_onceness(c: char) -> ast::Onceness { fn parse_closure_ty(st: &mut PState, conv: conv_did) -> ty::ClosureTy { let sigil = parse_sigil(st); - let purity = parse_purity(next(st)); + let fn_style = parse_fn_style(next(st)); let onceness = parse_onceness(next(st)); let region = parse_region(st, |x,y| conv(x,y)); let bounds = parse_bounds(st, |x,y| conv(x,y)); let sig = parse_sig(st, |x,y| conv(x,y)); ty::ClosureTy { - purity: purity, + fn_style: fn_style, sigil: sigil, onceness: onceness, region: region, @@ -492,11 +492,11 @@ fn parse_closure_ty(st: &mut PState, conv: conv_did) -> ty::ClosureTy { } fn parse_bare_fn_ty(st: &mut PState, conv: conv_did) -> ty::BareFnTy { - let purity = parse_purity(next(st)); + let fn_style = parse_fn_style(next(st)); let abi = parse_abi_set(st); let sig = parse_sig(st, |x,y| conv(x,y)); ty::BareFnTy { - purity: purity, + fn_style: fn_style, abi: abi, sig: sig } diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index 384c6907aed4f..485b28ca13bea 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -332,9 +332,9 @@ fn enc_sigil(w: &mut MemWriter, sigil: Sigil) { } } -fn enc_purity(w: &mut MemWriter, p: Purity) { +fn enc_fn_style(w: &mut MemWriter, p: FnStyle) { match p { - ImpureFn => mywrite!(w, "i"), + NormalFn => mywrite!(w, "n"), UnsafeFn => mywrite!(w, "u"), ExternFn => mywrite!(w, "c") } @@ -354,14 +354,14 @@ fn enc_onceness(w: &mut MemWriter, o: Onceness) { } pub fn enc_bare_fn_ty(w: &mut MemWriter, cx: &ctxt, ft: &ty::BareFnTy) { - enc_purity(w, ft.purity); + enc_fn_style(w, ft.fn_style); enc_abi(w, ft.abi); enc_fn_sig(w, cx, &ft.sig); } fn enc_closure_ty(w: &mut MemWriter, cx: &ctxt, ft: &ty::ClosureTy) { enc_sigil(w, ft.sigil); - enc_purity(w, ft.purity); + enc_fn_style(w, ft.fn_style); enc_onceness(w, ft.onceness); enc_region(w, cx, ft.region); let bounds = ty::ParamBounds {builtin_bounds: ft.bounds, diff --git a/src/librustc/middle/effect.rs b/src/librustc/middle/effect.rs index 5cec239783eb8..827d07484b739 100644 --- a/src/librustc/middle/effect.rs +++ b/src/librustc/middle/effect.rs @@ -29,8 +29,8 @@ enum UnsafeContext { fn type_is_unsafe_function(ty: ty::t) -> bool { match ty::get(ty).sty { - ty::ty_bare_fn(ref f) => f.purity == ast::UnsafeFn, - ty::ty_closure(ref f) => f.purity == ast::UnsafeFn, + ty::ty_bare_fn(ref f) => f.fn_style == ast::UnsafeFn, + ty::ty_closure(ref f) => f.fn_style == ast::UnsafeFn, _ => false, } } @@ -84,10 +84,10 @@ impl<'a> Visitor<()> for EffectCheckVisitor<'a> { block: &ast::Block, span: Span, node_id: ast::NodeId, _:()) { let (is_item_fn, is_unsafe_fn) = match *fn_kind { - visit::FkItemFn(_, _, purity, _) => - (true, purity == ast::UnsafeFn), + visit::FkItemFn(_, _, fn_style, _) => + (true, fn_style == ast::UnsafeFn), visit::FkMethod(_, _, method) => - (true, method.purity == ast::UnsafeFn), + (true, method.fn_style == ast::UnsafeFn), _ => (false, false), }; diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 143b02f96d22f..95101dc63371a 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -1182,11 +1182,11 @@ impl<'a> Resolver<'a> { (DefStatic(local_def(item.id), mutbl), sp, is_public); parent } - ItemFn(_, purity, _, _, _) => { + ItemFn(_, fn_style, _, _, _) => { let (name_bindings, new_parent) = self.add_child(ident, parent, ForbidDuplicateValues, sp); - let def = DefFn(local_def(item.id), purity); + let def = DefFn(local_def(item.id), fn_style); name_bindings.define_value(def, sp, is_public); new_parent } @@ -1313,7 +1313,7 @@ impl<'a> Resolver<'a> { DefStaticMethod(local_def(method.id), FromImpl(local_def( item.id)), - method.purity) + method.fn_style) } _ => { // Non-static methods become @@ -1364,7 +1364,7 @@ impl<'a> Resolver<'a> { // Static methods become `def_static_method`s. DefStaticMethod(local_def(ty_m.id), FromTrait(local_def(item.id)), - ty_m.purity) + ty_m.fn_style) } _ => { // Non-static methods become `def_method`s. @@ -1869,7 +1869,7 @@ impl<'a> Resolver<'a> { DUMMY_SP); let def = DefFn( static_method_info.def_id, - static_method_info.purity); + static_method_info.fn_style); method_name_bindings.define_value( def, DUMMY_SP, diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 69155f3df8ea0..92b1a60598b7c 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -1554,8 +1554,8 @@ impl<'a> Visitor<()> for TransItemVisitor<'a> { pub fn trans_item(ccx: &CrateContext, item: &ast::Item) { let _icx = push_ctxt("trans_item"); match item.node { - ast::ItemFn(decl, purity, _abi, ref generics, body) => { - if purity == ast::ExternFn { + ast::ItemFn(decl, fn_style, _abi, ref generics, body) => { + if fn_style == ast::ExternFn { let llfndecl = get_item_val(ccx, item.id); foreign::trans_rust_fn_with_foreign_abi( ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id); @@ -1899,8 +1899,8 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { } } - ast::ItemFn(_, purity, _, _, _) => { - let llfn = if purity != ast::ExternFn { + ast::ItemFn(_, fn_style, _, _, _) => { + let llfn = if fn_style != ast::ExternFn { register_fn(ccx, i.span, sym, i.id, ty) } else { foreign::register_rust_fn_with_foreign_abi(ccx, diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index cb16998f736e6..d6156e7c3e64e 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -615,7 +615,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr, let opt_def = cx.tcx().def_map.borrow().find_copy(&e.id); match opt_def { - Some(ast::DefFn(def_id, _purity)) => { + Some(ast::DefFn(def_id, _fn_style)) => { if !ast_util::is_local(def_id) { let ty = csearch::get_type(cx.tcx(), def_id).ty; (base::trans_external_path(cx, def_id, ty), true) diff --git a/src/librustc/middle/trans/reflect.rs b/src/librustc/middle/trans/reflect.rs index 0cfa4f5f6d538..2244c769af1c0 100644 --- a/src/librustc/middle/trans/reflect.rs +++ b/src/librustc/middle/trans/reflect.rs @@ -211,7 +211,7 @@ impl<'a> Reflector<'a> { // FIXME (#2594): fetch constants out of intrinsic // FIXME (#4809): visitor should break out bare fns from other fns ty::ty_closure(ref fty) => { - let pureval = ast_purity_constant(fty.purity); + let pureval = ast_fn_style_constant(fty.fn_style); let sigilval = ast_sigil_constant(fty.sigil); let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u}; let extra = vec!(self.c_uint(pureval), @@ -226,7 +226,7 @@ impl<'a> Reflector<'a> { // FIXME (#2594): fetch constants out of intrinsic:: for the // numbers. ty::ty_bare_fn(ref fty) => { - let pureval = ast_purity_constant(fty.purity); + let pureval = ast_fn_style_constant(fty.fn_style); let sigilval = 0u; let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u}; let extra = vec!(self.c_uint(pureval), @@ -399,10 +399,10 @@ pub fn ast_sigil_constant(sigil: ast::Sigil) -> uint { } } -pub fn ast_purity_constant(purity: ast::Purity) -> uint { - match purity { +pub fn ast_fn_style_constant(fn_style: ast::FnStyle) -> uint { + match fn_style { ast::UnsafeFn => 1u, - ast::ImpureFn => 2u, + ast::NormalFn => 2u, ast::ExternFn => 3u } } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index a250c6c298ba5..aac847c795aeb 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -415,14 +415,14 @@ pub fn type_id(t: t) -> uint { get(t).id } #[deriving(Clone, Eq, TotalEq, Hash)] pub struct BareFnTy { - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, pub abi: abi::Abi, pub sig: FnSig, } #[deriving(Clone, Eq, TotalEq, Hash)] pub struct ClosureTy { - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, pub sigil: ast::Sigil, pub onceness: ast::Onceness, pub region: Region, @@ -791,7 +791,7 @@ pub struct expected_found { #[deriving(Clone, Show)] pub enum type_err { terr_mismatch, - terr_purity_mismatch(expected_found), + terr_fn_style_mismatch(expected_found), terr_onceness_mismatch(expected_found), terr_abi_mismatch(expected_found), terr_mutability, @@ -1397,7 +1397,7 @@ pub fn mk_ctor_fn(cx: &ctxt, let input_args = input_tys.iter().map(|t| *t).collect(); mk_bare_fn(cx, BareFnTy { - purity: ast::ImpureFn, + fn_style: ast::NormalFn, abi: abi::Rust, sig: FnSig { binder_id: binder_id, @@ -2843,7 +2843,7 @@ pub fn adjust_ty(cx: &ctxt, ty::ty_bare_fn(ref b) => { ty::mk_closure( cx, - ty::ClosureTy {purity: b.purity, + ty::ClosureTy {fn_style: b.fn_style, sigil: s, onceness: ast::Many, region: r, @@ -3340,7 +3340,7 @@ pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> ~str { match *err { terr_mismatch => ~"types differ", - terr_purity_mismatch(values) => { + terr_fn_style_mismatch(values) => { format!("expected {} fn but found {} fn", values.expected.to_str(), values.found.to_str()) } @@ -4297,16 +4297,16 @@ pub fn eval_repeat_count(tcx: &T, count_expr: &ast::Expr) -> } } -// Determine what purity to check a nested function under -pub fn determine_inherited_purity(parent: (ast::Purity, ast::NodeId), - child: (ast::Purity, ast::NodeId), +// Determine what the style to check a nested function under +pub fn determine_inherited_style(parent: (ast::FnStyle, ast::NodeId), + child: (ast::FnStyle, ast::NodeId), child_sigil: ast::Sigil) - -> (ast::Purity, ast::NodeId) { + -> (ast::FnStyle, ast::NodeId) { // If the closure is a stack closure and hasn't had some non-standard - // purity inferred for it, then check it under its parent's purity. + // style inferred for it, then check it under its parent's style. // Otherwise, use its own match child_sigil { - ast::BorrowedSigil if child.val0() == ast::ImpureFn => parent, + ast::BorrowedSigil if child.val0() == ast::NormalFn => parent, _ => child } } @@ -4665,12 +4665,12 @@ pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 { } ty_bare_fn(ref b) => { byte!(14); - hash!(b.purity); + hash!(b.fn_style); hash!(b.abi); } ty_closure(ref c) => { byte!(15); - hash!(c.purity); + hash!(c.fn_style); hash!(c.sigil); hash!(c.onceness); hash!(c.bounds); diff --git a/src/librustc/middle/ty_fold.rs b/src/librustc/middle/ty_fold.rs index 8b14741f88145..a0d2318e1d024 100644 --- a/src/librustc/middle/ty_fold.rs +++ b/src/librustc/middle/ty_fold.rs @@ -49,7 +49,7 @@ pub trait TypeFolder { -> ty::BareFnTy { ty::BareFnTy { sig: self.fold_sig(&fty.sig), abi: fty.abi, - purity: fty.purity } + fn_style: fty.fn_style } } fn fold_closure_ty(&mut self, @@ -58,7 +58,7 @@ pub trait TypeFolder { ty::ClosureTy { region: self.fold_region(fty.region), sig: self.fold_sig(&fty.sig), - purity: fty.purity, + fn_style: fty.fn_style, sigil: fty.sigil, onceness: fty.onceness, bounds: fty.bounds, diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc/middle/typeck/astconv.rs index 2119419e0b1e5..d2e98c617a7de 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc/middle/typeck/astconv.rs @@ -523,7 +523,7 @@ pub fn ast_ty_to_ty( tcx.sess.span_err(ast_ty.span, "variadic function must have C calling convention"); } - ty::mk_bare_fn(tcx, ty_of_bare_fn(this, ast_ty.id, bf.purity, + ty::mk_bare_fn(tcx, ty_of_bare_fn(this, ast_ty.id, bf.fn_style, bf.abi, bf.decl)) } ast::TyClosure(ref f) => { @@ -543,7 +543,7 @@ pub fn ast_ty_to_ty( rscope, ast_ty.id, f.sigil, - f.purity, + f.fn_style, f.onceness, bounds, &f.region, @@ -661,24 +661,24 @@ struct SelfInfo { pub fn ty_of_method( this: &AC, id: ast::NodeId, - purity: ast::Purity, + fn_style: ast::FnStyle, untransformed_self_ty: ty::t, explicit_self: ast::ExplicitSelf, decl: &ast::FnDecl) -> ty::BareFnTy { - ty_of_method_or_bare_fn(this, id, purity, abi::Rust, Some(SelfInfo { + ty_of_method_or_bare_fn(this, id, fn_style, abi::Rust, Some(SelfInfo { untransformed_self_ty: untransformed_self_ty, explicit_self: explicit_self }), decl) } pub fn ty_of_bare_fn(this: &AC, id: ast::NodeId, - purity: ast::Purity, abi: abi::Abi, + fn_style: ast::FnStyle, abi: abi::Abi, decl: &ast::FnDecl) -> ty::BareFnTy { - ty_of_method_or_bare_fn(this, id, purity, abi, None, decl) + ty_of_method_or_bare_fn(this, id, fn_style, abi, None, decl) } fn ty_of_method_or_bare_fn(this: &AC, id: ast::NodeId, - purity: ast::Purity, abi: abi::Abi, + fn_style: ast::FnStyle, abi: abi::Abi, opt_self_info: Option, decl: &ast::FnDecl) -> ty::BareFnTy { debug!("ty_of_method_or_bare_fn"); @@ -724,7 +724,7 @@ fn ty_of_method_or_bare_fn(this: &AC, id: ast::NodeId, }; return ty::BareFnTy { - purity: purity, + fn_style: fn_style, abi: abi, sig: ty::FnSig { binder_id: id, @@ -740,7 +740,7 @@ pub fn ty_of_closure( rscope: &RS, id: ast::NodeId, sigil: ast::Sigil, - purity: ast::Purity, + fn_style: ast::FnStyle, onceness: ast::Onceness, bounds: ty::BuiltinBounds, opt_lifetime: &Option, @@ -797,7 +797,7 @@ pub fn ty_of_closure( }; ty::ClosureTy { - purity: purity, + fn_style: fn_style, sigil: sigil, onceness: onceness, region: bound_region, diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index 991e21ffab8b5..611b3653ab3f4 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -1163,7 +1163,7 @@ impl<'a> LookupContext<'a> { let transformed_self_ty = *fn_sig.inputs.get(0); let fty = ty::mk_bare_fn(tcx, ty::BareFnTy { sig: fn_sig, - purity: bare_fn_ty.purity, + fn_style: bare_fn_ty.fn_style, abi: bare_fn_ty.abi.clone(), }); debug!("after replacing bound regions, fty={}", self.ty_to_str(fty)); diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 9e0f3c9faa5ec..bfbac7aaebb1a 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -177,32 +177,32 @@ pub enum FnKind { } #[deriving(Clone)] -pub struct PurityState { +pub struct FnStyleState { pub def: ast::NodeId, - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, from_fn: bool } -impl PurityState { - pub fn function(purity: ast::Purity, def: ast::NodeId) -> PurityState { - PurityState { def: def, purity: purity, from_fn: true } +impl FnStyleState { + pub fn function(fn_style: ast::FnStyle, def: ast::NodeId) -> FnStyleState { + FnStyleState { def: def, fn_style: fn_style, from_fn: true } } - pub fn recurse(&mut self, blk: &ast::Block) -> PurityState { - match self.purity { + pub fn recurse(&mut self, blk: &ast::Block) -> FnStyleState { + match self.fn_style { // If this unsafe, then if the outer function was already marked as // unsafe we shouldn't attribute the unsafe'ness to the block. This // way the block can be warned about instead of ignoring this // extraneous block (functions are never warned about). ast::UnsafeFn if self.from_fn => *self, - purity => { - let (purity, def) = match blk.rules { + fn_style => { + let (fn_style, def) = match blk.rules { ast::UnsafeBlock(..) => (ast::UnsafeFn, blk.id), - ast::DefaultBlock => (purity, self.def), + ast::DefaultBlock => (fn_style, self.def), }; - PurityState{ def: def, - purity: purity, + FnStyleState{ def: def, + fn_style: fn_style, from_fn: false } } } @@ -227,7 +227,7 @@ pub struct FnCtxt<'a> { err_count_on_creation: uint, ret_ty: ty::t, - ps: RefCell, + ps: RefCell, // Sometimes we generate region pointers where the precise region // to use is not known. For example, an expression like `&x.f` @@ -281,7 +281,7 @@ fn blank_fn_ctxt<'a>(ccx: &'a CrateCtxt<'a>, FnCtxt { err_count_on_creation: ccx.tcx.sess.err_count(), ret_ty: rty, - ps: RefCell::new(PurityState::function(ast::ImpureFn, 0)), + ps: RefCell::new(FnStyleState::function(ast::NormalFn, 0)), region_lb: Cell::new(region_bnd), fn_kind: Vanilla, inh: inh, @@ -335,7 +335,7 @@ fn check_bare_fn(ccx: &CrateCtxt, match ty::get(fty).sty { ty::ty_bare_fn(ref fn_ty) => { let inh = Inherited::new(ccx.tcx, param_env); - let fcx = check_fn(ccx, fn_ty.purity, &fn_ty.sig, + let fcx = check_fn(ccx, fn_ty.fn_style, &fn_ty.sig, decl, id, body, Vanilla, &inh); vtable::resolve_in_block(&fcx, body); @@ -415,7 +415,7 @@ impl<'a> Visitor<()> for GatherLocalsVisitor<'a> { } fn check_fn<'a>(ccx: &'a CrateCtxt<'a>, - purity: ast::Purity, + fn_style: ast::FnStyle, fn_sig: &ty::FnSig, decl: &ast::FnDecl, id: ast::NodeId, @@ -456,7 +456,7 @@ fn check_fn<'a>(ccx: &'a CrateCtxt<'a>, let fcx = FnCtxt { err_count_on_creation: err_count_on_creation, ret_ty: ret_ty, - ps: RefCell::new(PurityState::function(purity, id)), + ps: RefCell::new(FnStyleState::function(fn_style, id)), region_lb: Cell::new(body.id), fn_kind: fn_kind, inh: inherited, @@ -2127,7 +2127,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, // fresh bound regions for any bound regions we find in the // expected types so as to avoid capture. // - // Also try to pick up inferred purity and sigil, defaulting + // Also try to pick up inferred style and sigil, defaulting // to impure and block. Note that we only will use those for // block syntax lambdas; that is, lambdas without explicit // sigils. @@ -2136,7 +2136,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, |x| Some((*x).clone())); let error_happened = false; let (expected_sig, - expected_purity, + expected_style, expected_sigil, expected_onceness, expected_bounds) = { @@ -2146,7 +2146,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, replace_late_bound_regions_in_fn_sig( tcx, &cenv.sig, |_| fcx.inh.infcx.fresh_bound_region(expr.id)); - (Some(sig), cenv.purity, cenv.sigil, + (Some(sig), cenv.fn_style, cenv.sigil, cenv.onceness, cenv.bounds) } _ => { @@ -2162,7 +2162,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, } _ => () } - (None, ast::ImpureFn, sigil, + (None, ast::NormalFn, sigil, onceness, bounds) } } @@ -2170,9 +2170,9 @@ fn check_expr_with_unifier(fcx: &FnCtxt, // If the proto is specified, use that, otherwise select a // proto based on inference. - let (sigil, purity) = match ast_sigil_opt { - Some(p) => (p, ast::ImpureFn), - None => (expected_sigil, expected_purity) + let (sigil, fn_style) = match ast_sigil_opt { + Some(p) => (p, ast::NormalFn), + None => (expected_sigil, expected_style) }; // construct the function type @@ -2180,7 +2180,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, fcx.infcx(), expr.id, sigil, - purity, + fn_style, expected_onceness, expected_bounds, &None, @@ -2208,13 +2208,13 @@ fn check_expr_with_unifier(fcx: &FnCtxt, fcx.write_ty(expr.id, fty); - let (inherited_purity, id) = - ty::determine_inherited_purity((fcx.ps.borrow().purity, + let (inherited_style, id) = + ty::determine_inherited_style((fcx.ps.borrow().fn_style, fcx.ps.borrow().def), - (purity, expr.id), + (fn_style, expr.id), sigil); - check_fn(fcx.ccx, inherited_purity, &fty_sig, + check_fn(fcx.ccx, inherited_style, &fty_sig, decl, id, body, fn_kind, fcx.inh); } @@ -3272,8 +3272,8 @@ pub fn check_block_with_expected(fcx: &FnCtxt, expected: Option) { let prev = { let mut fcx_ps = fcx.ps.borrow_mut(); - let purity_state = fcx_ps.recurse(blk); - replace(&mut *fcx_ps, purity_state) + let fn_style_state = fcx_ps.recurse(blk); + replace(&mut *fcx_ps, fn_style_state) }; fcx.with_region_lb(blk.id, || { @@ -4223,7 +4223,7 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &ast::ForeignItem) { } }; let fty = ty::mk_bare_fn(tcx, ty::BareFnTy { - purity: ast::UnsafeFn, + fn_style: ast::UnsafeFn, abi: abi::RustIntrinsic, sig: FnSig {binder_id: it.id, inputs: inputs, diff --git a/src/librustc/middle/typeck/collect.rs b/src/librustc/middle/typeck/collect.rs index 274f88ad4c37d..7e53445147f50 100644 --- a/src/librustc/middle/typeck/collect.rs +++ b/src/librustc/middle/typeck/collect.rs @@ -200,14 +200,14 @@ pub fn ensure_trait_methods(ccx: &CrateCtxt, trait_id: ast::NodeId) { ty_method_of_trait_method( ccx, trait_id, &trait_ty_generics, &m.id, &m.ident, &m.explicit_self, - &m.generics, &m.purity, m.decl) + &m.generics, &m.fn_style, m.decl) } &ast::Provided(ref m) => { ty_method_of_trait_method( ccx, trait_id, &trait_ty_generics, &m.id, &m.ident, &m.explicit_self, - &m.generics, &m.purity, m.decl) + &m.generics, &m.fn_style, m.decl) } }; @@ -376,11 +376,11 @@ pub fn ensure_trait_methods(ccx: &CrateCtxt, trait_id: ast::NodeId) { m_ident: &ast::Ident, m_explicit_self: &ast::ExplicitSelf, m_generics: &ast::Generics, - m_purity: &ast::Purity, + m_fn_style: &ast::FnStyle, m_decl: &ast::FnDecl) -> ty::Method { let trait_self_ty = ty::mk_self(this.tcx, local_def(trait_id)); - let fty = astconv::ty_of_method(this, *m_id, *m_purity, trait_self_ty, + let fty = astconv::ty_of_method(this, *m_id, *m_fn_style, trait_self_ty, *m_explicit_self, m_decl); let num_trait_type_params = trait_generics.type_param_defs().len(); let ty_generics = ty_generics_for_fn_or_method(this, m_generics, @@ -508,7 +508,7 @@ fn convert_methods(ccx: &CrateCtxt, rcvr_generics: &ast::Generics, rcvr_visibility: ast::Visibility) -> ty::Method { - let fty = astconv::ty_of_method(ccx, m.id, m.purity, + let fty = astconv::ty_of_method(ccx, m.id, m.fn_style, untransformed_rcvr_ty, m.explicit_self, m.decl); @@ -818,11 +818,11 @@ pub fn ty_of_item(ccx: &CrateCtxt, it: &ast::Item) tcx.tcache.borrow_mut().insert(local_def(it.id), tpt.clone()); return tpt; } - ast::ItemFn(decl, purity, abi, ref generics, _) => { + ast::ItemFn(decl, fn_style, abi, ref generics, _) => { let ty_generics = ty_generics_for_fn_or_method(ccx, generics, 0); let tofd = astconv::ty_of_bare_fn(ccx, it.id, - purity, + fn_style, abi, decl); let tpt = ty_param_bounds_and_ty { @@ -1029,7 +1029,7 @@ pub fn ty_of_foreign_fn_decl(ccx: &CrateCtxt, ccx.tcx, ty::BareFnTy { abi: abi, - purity: ast::UnsafeFn, + fn_style: ast::UnsafeFn, sig: ty::FnSig {binder_id: def_id.node, inputs: input_tys, output: output_ty, diff --git a/src/librustc/middle/typeck/infer/coercion.rs b/src/librustc/middle/typeck/infer/coercion.rs index 8a1662ca701d3..38ffa2ae50828 100644 --- a/src/librustc/middle/typeck/infer/coercion.rs +++ b/src/librustc/middle/typeck/infer/coercion.rs @@ -385,7 +385,7 @@ impl<'f> Coerce<'f> { debug!("coerce_from_bare_fn(a={}, b={})", a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx)); - if fn_ty_a.abi != abi::Rust || fn_ty_a.purity != ast::ImpureFn { + if fn_ty_a.abi != abi::Rust || fn_ty_a.fn_style != ast::NormalFn { return self.subtype(a, b); } diff --git a/src/librustc/middle/typeck/infer/combine.rs b/src/librustc/middle/typeck/infer/combine.rs index 749c1ee69387c..555aaa90da144 100644 --- a/src/librustc/middle/typeck/infer/combine.rs +++ b/src/librustc/middle/typeck/infer/combine.rs @@ -64,7 +64,7 @@ use util::ppaux::Repr; use std::result; -use syntax::ast::{Onceness, Purity}; +use syntax::ast::{Onceness, FnStyle}; use syntax::ast; use syntax::owned_slice::OwnedSlice; use syntax::abi; @@ -194,10 +194,10 @@ pub trait Combine { fn bare_fn_tys(&self, a: &ty::BareFnTy, b: &ty::BareFnTy) -> cres { - let purity = if_ok!(self.purities(a.purity, b.purity)); + let fn_style = if_ok!(self.fn_styles(a.fn_style, b.fn_style)); let abi = if_ok!(self.abi(a.abi, b.abi)); let sig = if_ok!(self.fn_sigs(&a.sig, &b.sig)); - Ok(ty::BareFnTy {purity: purity, + Ok(ty::BareFnTy {fn_style: fn_style, abi: abi, sig: sig}) } @@ -207,11 +207,11 @@ pub trait Combine { let p = if_ok!(self.sigils(a.sigil, b.sigil)); let r = if_ok!(self.contraregions(a.region, b.region)); - let purity = if_ok!(self.purities(a.purity, b.purity)); + let fn_style = if_ok!(self.fn_styles(a.fn_style, b.fn_style)); let onceness = if_ok!(self.oncenesses(a.onceness, b.onceness)); let bounds = if_ok!(self.bounds(a.bounds, b.bounds)); let sig = if_ok!(self.fn_sigs(&a.sig, &b.sig)); - Ok(ty::ClosureTy {purity: purity, + Ok(ty::ClosureTy {fn_style: fn_style, sigil: p, onceness: onceness, region: r, @@ -246,7 +246,7 @@ pub trait Combine { } } - fn purities(&self, a: Purity, b: Purity) -> cres; + fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres; fn abi(&self, a: abi::Abi, b: abi::Abi) -> cres { if a == b { diff --git a/src/librustc/middle/typeck/infer/error_reporting.rs b/src/librustc/middle/typeck/infer/error_reporting.rs index db66c93086afa..24a6ab338a761 100644 --- a/src/librustc/middle/typeck/infer/error_reporting.rs +++ b/src/librustc/middle/typeck/infer/error_reporting.rs @@ -1102,10 +1102,10 @@ impl<'a> ErrorReportingHelpers for InferCtxt<'a> { output: ast::P, item: ast::P, generics: ast::Generics) { - let (fn_decl, purity, ident) = match item.node { + let (fn_decl, fn_style, ident) = match item.node { // FIXME: handling method - ast::ItemFn(ref fn_decl, ref purity, _, _, _) => { - (fn_decl, purity, item.ident) + ast::ItemFn(ref fn_decl, ref fn_style, _, _, _) => { + (fn_decl, fn_style, item.ident) }, _ => fail!("Expect function or method") @@ -1117,7 +1117,7 @@ impl<'a> ErrorReportingHelpers for InferCtxt<'a> { variadic: fn_decl.variadic }; let suggested_fn = - pprust::fun_to_str(&fd, *purity, ident, None, &generics); + pprust::fun_to_str(&fd, *fn_style, ident, None, &generics); let msg = format!("consider using an explicit lifetime \ parameter as shown: {}", suggested_fn); self.tcx.sess.span_note(item.span, msg); diff --git a/src/librustc/middle/typeck/infer/glb.rs b/src/librustc/middle/typeck/infer/glb.rs index 83fc315bcebc8..ea0d3a1c1d40c 100644 --- a/src/librustc/middle/typeck/infer/glb.rs +++ b/src/librustc/middle/typeck/infer/glb.rs @@ -22,8 +22,8 @@ use middle::typeck::infer::{cres, InferCtxt}; use middle::typeck::infer::{TypeTrace, Subtype}; use middle::typeck::infer::fold_regions_in_sig; use syntax::ast::{Many, Once, MutImmutable, MutMutable}; -use syntax::ast::{ExternFn, ImpureFn, UnsafeFn, NodeId}; -use syntax::ast::{Onceness, Purity}; +use syntax::ast::{ExternFn, NormalFn, UnsafeFn, NodeId}; +use syntax::ast::{Onceness, FnStyle}; use collections::HashMap; use util::common::{indenter}; use util::ppaux::mt_to_str; @@ -81,10 +81,10 @@ impl<'f> Combine for Glb<'f> { Lub(*self.get_ref()).tys(a, b) } - fn purities(&self, a: Purity, b: Purity) -> cres { + fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres { match (a, b) { (ExternFn, _) | (_, ExternFn) => Ok(ExternFn), - (ImpureFn, _) | (_, ImpureFn) => Ok(ImpureFn), + (NormalFn, _) | (_, NormalFn) => Ok(NormalFn), (UnsafeFn, UnsafeFn) => Ok(UnsafeFn) } } diff --git a/src/librustc/middle/typeck/infer/lub.rs b/src/librustc/middle/typeck/infer/lub.rs index 7f48e2333676a..e355d7d48ac23 100644 --- a/src/librustc/middle/typeck/infer/lub.rs +++ b/src/librustc/middle/typeck/infer/lub.rs @@ -23,8 +23,8 @@ use middle::typeck::infer::fold_regions_in_sig; use middle::typeck::infer::{TypeTrace, Subtype}; use collections::HashMap; use syntax::ast::{Many, Once, NodeId}; -use syntax::ast::{ExternFn, ImpureFn, UnsafeFn}; -use syntax::ast::{Onceness, Purity}; +use syntax::ast::{ExternFn, NormalFn, UnsafeFn}; +use syntax::ast::{Onceness, FnStyle}; use util::ppaux::mt_to_str; pub struct Lub<'f>(pub CombineFields<'f>); // least-upper-bound: common supertype @@ -75,10 +75,10 @@ impl<'f> Combine for Lub<'f> { Glb(*self.get_ref()).tys(a, b) } - fn purities(&self, a: Purity, b: Purity) -> cres { + fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres { match (a, b) { (UnsafeFn, _) | (_, UnsafeFn) => Ok(UnsafeFn), - (ImpureFn, _) | (_, ImpureFn) => Ok(ImpureFn), + (NormalFn, _) | (_, NormalFn) => Ok(NormalFn), (ExternFn, ExternFn) => Ok(ExternFn), } } diff --git a/src/librustc/middle/typeck/infer/sub.rs b/src/librustc/middle/typeck/infer/sub.rs index b22e6f4677bd7..95b95380fa3ef 100644 --- a/src/librustc/middle/typeck/infer/sub.rs +++ b/src/librustc/middle/typeck/infer/sub.rs @@ -25,7 +25,7 @@ use middle::typeck::infer::{TypeTrace, Subtype}; use util::common::{indenter}; use util::ppaux::bound_region_to_str; -use syntax::ast::{Onceness, Purity}; +use syntax::ast::{Onceness, FnStyle}; pub struct Sub<'f>(pub CombineFields<'f>); // "subtype", "subregion" etc @@ -87,9 +87,9 @@ impl<'f> Combine for Sub<'f> { } } - fn purities(&self, a: Purity, b: Purity) -> cres { - self.lub().purities(a, b).compare(b, || { - ty::terr_purity_mismatch(expected_found(self, a, b)) + fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres { + self.lub().fn_styles(a, b).compare(b, || { + ty::terr_fn_style_mismatch(expected_found(self, a, b)) }) } diff --git a/src/librustc/middle/typeck/infer/test.rs b/src/librustc/middle/typeck/infer/test.rs index a3f44c9a06906..791cd4f86250d 100644 --- a/src/librustc/middle/typeck/infer/test.rs +++ b/src/librustc/middle/typeck/infer/test.rs @@ -182,7 +182,7 @@ impl Env { let inputs = input_tys.map(|t| {mode: ast::expl(ast::by_copy), ty: *t}); ty::mk_fn(self.tcx, FnTyBase { - meta: FnMeta {purity: ast::ImpureFn, + meta: FnMeta {fn_style: ast::NormalFn, proto: ast::ProtoBare, onceness: ast::Many, region: ty::ReStatic, diff --git a/src/librustc/middle/typeck/mod.rs b/src/librustc/middle/typeck/mod.rs index 446d2ff055cca..f78f0a8f2731f 100644 --- a/src/librustc/middle/typeck/mod.rs +++ b/src/librustc/middle/typeck/mod.rs @@ -357,7 +357,7 @@ fn check_main_fn_ty(ccx: &CrateCtxt, _ => () } let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy { - purity: ast::ImpureFn, + fn_style: ast::NormalFn, abi: abi::Rust, sig: ty::FnSig { binder_id: main_id, @@ -403,7 +403,7 @@ fn check_start_fn_ty(ccx: &CrateCtxt, } let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy { - purity: ast::ImpureFn, + fn_style: ast::NormalFn, abi: abi::Rust, sig: ty::FnSig { binder_id: start_id, diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 155ceadf0d829..e7b925197076a 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -252,7 +252,7 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> ~str { ty_to_str(cx, input) } fn bare_fn_to_str(cx: &ctxt, - purity: ast::Purity, + fn_style: ast::FnStyle, abi: abi::Abi, ident: Option, sig: &ty::FnSig) @@ -263,10 +263,10 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> ~str { format!("extern {} ", abi.to_str()) }; - match purity { - ast::ImpureFn => {} + match fn_style { + ast::NormalFn => {} _ => { - s.push_str(purity.to_str()); + s.push_str(fn_style.to_str()); s.push_char(' '); } }; @@ -305,10 +305,10 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> ~str { } } - match cty.purity { - ast::ImpureFn => {} + match cty.fn_style { + ast::NormalFn => {} _ => { - s.push_str(cty.purity.to_str()); + s.push_str(cty.fn_style.to_str()); s.push_char(' '); } }; @@ -405,7 +405,7 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> ~str { closure_to_str(cx, *f) } ty_bare_fn(ref f) => { - bare_fn_to_str(cx, f.purity, f.abi, None, &f.sig) + bare_fn_to_str(cx, f.fn_style, f.abi, None, &f.sig) } ty_infer(infer_ty) => infer_ty.to_str(), ty_err => ~"[type error]", @@ -812,8 +812,8 @@ impl Repr for ast::Visibility { impl Repr for ty::BareFnTy { fn repr(&self, tcx: &ctxt) -> ~str { - format!("BareFnTy \\{purity: {:?}, abi: {}, sig: {}\\}", - self.purity, + format!("BareFnTy \\{fn_style: {:?}, abi: {}, sig: {}\\}", + self.fn_style, self.abi.to_str(), self.sig.repr(tcx)) } diff --git a/src/librustdoc/clean.rs b/src/librustdoc/clean.rs index e92aec8e25c7c..ce7f167ea1724 100644 --- a/src/librustdoc/clean.rs +++ b/src/librustdoc/clean.rs @@ -356,7 +356,7 @@ impl Clean for ast::Generics { pub struct Method { pub generics: Generics, pub self_: SelfTy, - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, pub decl: FnDecl, } @@ -383,7 +383,7 @@ impl Clean for ast::Method { inner: MethodItem(Method { generics: self.generics.clean(), self_: self.explicit_self.clean(), - purity: self.purity.clone(), + fn_style: self.fn_style.clone(), decl: decl, }), } @@ -392,7 +392,7 @@ impl Clean for ast::Method { #[deriving(Clone, Encodable, Decodable)] pub struct TyMethod { - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, pub decl: FnDecl, pub generics: Generics, pub self_: SelfTy, @@ -419,7 +419,7 @@ impl Clean for ast::TypeMethod { id: self.id, visibility: None, inner: TyMethodItem(TyMethod { - purity: self.purity.clone(), + fn_style: self.fn_style.clone(), decl: decl, self_: self.explicit_self.clean(), generics: self.generics.clean(), @@ -451,7 +451,7 @@ impl Clean for ast::ExplicitSelf { pub struct Function { pub decl: FnDecl, pub generics: Generics, - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, } impl Clean for doctree::Function { @@ -465,7 +465,7 @@ impl Clean for doctree::Function { inner: FunctionItem(Function { decl: self.decl.clean(), generics: self.generics.clean(), - purity: self.purity, + fn_style: self.fn_style, }), } } @@ -478,7 +478,7 @@ pub struct ClosureDecl { pub lifetimes: Vec, pub decl: FnDecl, pub onceness: ast::Onceness, - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, pub bounds: Vec, } @@ -490,7 +490,7 @@ impl Clean for ast::ClosureTy { lifetimes: self.lifetimes.clean().move_iter().collect(), decl: self.decl.clean(), onceness: self.onceness, - purity: self.purity, + fn_style: self.fn_style, bounds: match self.bounds { Some(ref x) => x.clean().move_iter().collect(), None => Vec::new() @@ -960,7 +960,7 @@ impl Clean for doctree::Typedef { #[deriving(Clone, Encodable, Decodable)] pub struct BareFunctionDecl { - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, pub generics: Generics, pub decl: FnDecl, pub abi: ~str, @@ -969,7 +969,7 @@ pub struct BareFunctionDecl { impl Clean for ast::BareFnTy { fn clean(&self) -> BareFunctionDecl { BareFunctionDecl { - purity: self.purity, + fn_style: self.fn_style, generics: Generics { lifetimes: self.lifetimes.clean().move_iter().collect(), type_params: Vec::new(), @@ -1164,7 +1164,7 @@ impl Clean for ast::ForeignItem { ForeignFunctionItem(Function { decl: decl.clean(), generics: generics.clean(), - purity: ast::ExternFn, + fn_style: ast::ExternFn, }) } ast::ForeignItemStatic(ref ty, mutbl) => { diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index 78b1a1388f88c..5104ce81465ba 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -113,7 +113,7 @@ pub struct Function { pub id: NodeId, pub name: Ident, pub vis: ast::Visibility, - pub purity: ast::Purity, + pub fn_style: ast::FnStyle, pub where: Span, pub generics: ast::Generics, } diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 10c155262c31e..a93107a739210 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -29,9 +29,9 @@ use html::render::{cache_key, current_location_key}; /// Helper to render an optional visibility with a space after it (if the /// visibility is preset) pub struct VisSpace(pub Option); -/// Similarly to VisSpace, this structure is used to render a purity with a +/// Similarly to VisSpace, this structure is used to render a function style with a /// space after it. -pub struct PuritySpace(pub ast::Purity); +pub struct FnStyleSpace(pub ast::FnStyle); /// Wrapper struct for properly emitting a method declaration. pub struct Method<'a>(pub &'a clean::SelfTy, pub &'a clean::FnDecl); @@ -41,9 +41,9 @@ impl VisSpace { } } -impl PuritySpace { - pub fn get(&self) -> ast::Purity { - let PuritySpace(v) = *self; v +impl FnStyleSpace { + pub fn get(&self) -> ast::FnStyle { + let FnStyleSpace(v) = *self; v } } @@ -343,7 +343,7 @@ impl fmt::Show for clean::Type { }; write!(f.buf, "{}{}{arrow, select, yes{ -> {ret}} other{}}", - PuritySpace(decl.purity), + FnStyleSpace(decl.fn_style), match decl.sigil { ast::OwnedSigil => format!("proc({})", decl.decl.inputs), ast::BorrowedSigil => format!("{}|{}|", region, decl.decl.inputs), @@ -355,7 +355,7 @@ impl fmt::Show for clean::Type { } clean::BareFunction(ref decl) => { write!(f.buf, "{}{}fn{}{}", - PuritySpace(decl.purity), + FnStyleSpace(decl.fn_style), match decl.abi { ref x if "" == *x => ~"", ref x if "\"Rust\"" == *x => ~"", @@ -472,12 +472,12 @@ impl fmt::Show for VisSpace { } } -impl fmt::Show for PuritySpace { +impl fmt::Show for FnStyleSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get() { ast::UnsafeFn => write!(f.buf, "unsafe "), ast::ExternFn => write!(f.buf, "extern "), - ast::ImpureFn => Ok(()) + ast::NormalFn => Ok(()) } } } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index ff437ff23dce7..2bc4b6e841f55 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -51,7 +51,7 @@ use rustc::util::nodemap::NodeSet; use clean; use doctree; use fold::DocFolder; -use html::format::{VisSpace, Method, PuritySpace}; +use html::format::{VisSpace, Method, FnStyleSpace}; use html::layout; use html::markdown; use html::markdown::Markdown; @@ -1191,10 +1191,10 @@ fn item_module(w: &mut Writer, cx: &Context, fn item_function(w: &mut Writer, it: &clean::Item, f: &clean::Function) -> fmt::Result { - try!(write!(w, "
{vis}{purity}fn \
+    try!(write!(w, "
{vis}{fn_style}fn \
                     {name}{generics}{decl}
", vis = VisSpace(it.visibility), - purity = PuritySpace(f.purity), + fn_style = FnStyleSpace(f.fn_style), name = it.name.get_ref().as_slice(), generics = f.generics, decl = f.decl)); @@ -1305,12 +1305,12 @@ fn item_trait(w: &mut Writer, it: &clean::Item, } fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result { - fn fun(w: &mut Writer, it: &clean::Item, purity: ast::Purity, + fn fun(w: &mut Writer, it: &clean::Item, fn_style: ast::FnStyle, g: &clean::Generics, selfty: &clean::SelfTy, d: &clean::FnDecl) -> fmt::Result { write!(w, "{}fn {name}\ {generics}{decl}", - match purity { + match fn_style { ast::UnsafeFn => "unsafe ", _ => "", }, @@ -1321,10 +1321,10 @@ fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result { } match meth.inner { clean::TyMethodItem(ref m) => { - fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl) + fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl) } clean::MethodItem(ref m) => { - fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl) + fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl) } _ => unreachable!() } diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index a6c1ece6400ed..7de898a50a9e3 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -95,7 +95,7 @@ impl<'a> RustdocVisitor<'a> { } pub fn visit_fn(&mut self, item: &ast::Item, fd: &ast::FnDecl, - purity: &ast::Purity, _abi: &abi::Abi, + fn_style: &ast::FnStyle, _abi: &abi::Abi, gen: &ast::Generics) -> Function { debug!("Visiting fn"); Function { @@ -106,7 +106,7 @@ impl<'a> RustdocVisitor<'a> { name: item.ident, where: item.span, generics: gen.clone(), - purity: *purity, + fn_style: *fn_style, } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 6a5acff3fe04e..1eb034a573ac3 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -210,8 +210,8 @@ pub enum MethodProvenance { #[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Def { - DefFn(DefId, Purity), - DefStaticMethod(/* method */ DefId, MethodProvenance, Purity), + DefFn(DefId, FnStyle), + DefStaticMethod(/* method */ DefId, MethodProvenance, FnStyle), DefSelfTy(/* trait id */ NodeId), DefMod(DefId), DefForeignMod(DefId), @@ -696,7 +696,7 @@ pub struct TypeField { pub struct TypeMethod { pub ident: Ident, pub attrs: Vec, - pub purity: Purity, + pub fn_style: FnStyle, pub decl: P, pub generics: Generics, pub explicit_self: ExplicitSelf, @@ -794,7 +794,7 @@ pub struct ClosureTy { pub sigil: Sigil, pub region: Option, pub lifetimes: Vec, - pub purity: Purity, + pub fn_style: FnStyle, pub onceness: Onceness, pub decl: P, // Optional optvec distinguishes between "fn()" and "fn:()" so we can @@ -806,7 +806,7 @@ pub struct ClosureTy { #[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub struct BareFnTy { - pub purity: Purity, + pub fn_style: FnStyle, pub abi: Abi, pub lifetimes: Vec, pub decl: P @@ -886,16 +886,16 @@ pub struct FnDecl { } #[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] -pub enum Purity { +pub enum FnStyle { UnsafeFn, // declared with "unsafe fn" - ImpureFn, // declared with "fn" + NormalFn, // declared with "fn" ExternFn, // declared with "extern fn" } -impl fmt::Show for Purity { +impl fmt::Show for FnStyle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ImpureFn => "impure".fmt(f), + NormalFn => "normal".fmt(f), UnsafeFn => "unsafe".fmt(f), ExternFn => "extern".fmt(f), } @@ -925,7 +925,7 @@ pub struct Method { pub attrs: Vec, pub generics: Generics, pub explicit_self: ExplicitSelf, - pub purity: Purity, + pub fn_style: FnStyle, pub decl: P, pub body: P, pub id: NodeId, @@ -1119,7 +1119,7 @@ pub struct Item { #[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Item_ { ItemStatic(P, Mutability, @Expr), - ItemFn(P, Purity, Abi, Generics, P), + ItemFn(P, FnStyle, Abi, Generics, P), ItemMod(Mod), ItemForeignMod(ForeignMod), ItemTy(P, Generics), diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index ec9c02ac82a73..558642059969d 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -264,7 +264,7 @@ pub fn trait_method_to_ty_method(method: &TraitMethod) -> TypeMethod { TypeMethod { ident: m.ident, attrs: m.attrs.clone(), - purity: m.purity, + fn_style: m.fn_style, decl: m.decl, generics: m.generics.clone(), explicit_self: m.explicit_self, diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index b7c12cd4fdcae..203edf6590fb7 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -825,7 +825,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { name, Vec::new(), ast::ItemFn(self.fn_decl(inputs, output), - ast::ImpureFn, + ast::NormalFn, abi::Rust, generics, body)) diff --git a/src/libsyntax/ext/deriving/generic.rs b/src/libsyntax/ext/deriving/generic.rs index 1dcb753624d83..8a44caf34a5b4 100644 --- a/src/libsyntax/ext/deriving/generic.rs +++ b/src/libsyntax/ext/deriving/generic.rs @@ -619,7 +619,7 @@ impl<'a> MethodDef<'a> { attrs: attrs, generics: fn_generics, explicit_self: explicit_self, - purity: ast::ImpureFn, + fn_style: ast::NormalFn, decl: fn_decl, body: body_block, id: ast::DUMMY_NODE_ID, diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index e21f14e4a9622..e9e69eabef896 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -158,7 +158,7 @@ pub trait Folder { TyClosure(ref f) => { TyClosure(@ClosureTy { sigil: f.sigil, - purity: f.purity, + fn_style: f.fn_style, region: fold_opt_lifetime(&f.region, self), onceness: f.onceness, bounds: fold_opt_bounds(&f.bounds, self), @@ -169,7 +169,7 @@ pub trait Folder { TyBareFn(ref f) => { TyBareFn(@BareFnTy { lifetimes: f.lifetimes.iter().map(|l| fold_lifetime(l, self)).collect(), - purity: f.purity, + fn_style: f.fn_style, abi: f.abi, decl: self.fold_fn_decl(f.decl) }) @@ -549,10 +549,10 @@ pub fn noop_fold_item_underscore(i: &Item_, folder: &mut T) -> Item_ ItemStatic(t, m, e) => { ItemStatic(folder.fold_ty(t), m, folder.fold_expr(e)) } - ItemFn(decl, purity, abi, ref generics, body) => { + ItemFn(decl, fn_style, abi, ref generics, body) => { ItemFn( folder.fold_fn_decl(decl), - purity, + fn_style, abi, fold_generics(generics, folder), folder.fold_block(body) @@ -603,7 +603,7 @@ pub fn noop_fold_type_method(m: &TypeMethod, fld: &mut T) -> TypeMeth id: fld.new_id(m.id), // Needs to be first, for ast_map. ident: fld.fold_ident(m.ident), attrs: m.attrs.iter().map(|a| fold_attribute_(*a, fld)).collect(), - purity: m.purity, + fn_style: m.fn_style, decl: fld.fold_fn_decl(m.decl), generics: fold_generics(&m.generics, fld), explicit_self: fld.fold_explicit_self(&m.explicit_self), @@ -680,7 +680,7 @@ pub fn noop_fold_method(m: &Method, folder: &mut T) -> @Method { attrs: m.attrs.iter().map(|a| fold_attribute_(*a, folder)).collect(), generics: fold_generics(&m.generics, folder), explicit_self: folder.fold_explicit_self(&m.explicit_self), - purity: m.purity, + fn_style: m.fn_style, decl: folder.fold_fn_decl(m.decl), body: folder.fold_block(m.body), span: folder.new_span(m.span), diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 35f9898ebbbf7..eca9f955d9392 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -657,7 +657,7 @@ mod test { cf: ast::Return, variadic: false }), - ast::ImpureFn, + ast::NormalFn, abi::Rust, ast::Generics{ // no idea on either of these: lifetimes: Vec::new(), diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index c8ea0b6aac283..fe4bd87c4eb18 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -14,7 +14,7 @@ use abi; use ast::{Sigil, BorrowedSigil, ManagedSigil, OwnedSigil}; use ast::{BareFnTy, ClosureTy}; use ast::{RegionTyParamBound, TraitTyParamBound}; -use ast::{Provided, Public, Purity}; +use ast::{Provided, Public, FnStyle}; use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue}; use ast::{BiBitAnd, BiBitOr, BiBitXor, Block}; use ast::{BlockCheckMode, UnBox}; @@ -31,7 +31,7 @@ use ast::{ExprVec, ExprVstore, ExprVstoreSlice}; use ast::{ExprVstoreMutSlice, ExprWhile, ExprForLoop, ExternFn, Field, FnDecl}; use ast::{ExprVstoreUniq, Once, Many}; use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod}; -use ast::{Ident, ImpureFn, Inherited, Item, Item_, ItemStatic}; +use ast::{Ident, NormalFn, Inherited, Item, Item_, ItemStatic}; use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl}; use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_}; use ast::{LitBool, LitFloat, LitFloatUnsuffixed, LitInt, LitChar}; @@ -867,7 +867,7 @@ impl<'a> Parser<'a> { | | | Argument types | | Lifetimes | | - | Purity + | Function Style ABI */ @@ -878,12 +878,12 @@ impl<'a> Parser<'a> { abi::Rust }; - let purity = self.parse_unsafety(); + let fn_style = self.parse_unsafety(); self.expect_keyword(keywords::Fn); let (decl, lifetimes) = self.parse_ty_fn_decl(true); return TyBareFn(@BareFnTy { abi: abi, - purity: purity, + fn_style: fn_style, lifetimes: lifetimes, decl: decl }); @@ -925,7 +925,7 @@ impl<'a> Parser<'a> { TyClosure(@ClosureTy { sigil: OwnedSigil, region: None, - purity: ImpureFn, + fn_style: NormalFn, onceness: Once, bounds: bounds, decl: decl, @@ -945,11 +945,11 @@ impl<'a> Parser<'a> { | | | Argument types | | Lifetimes | Once-ness (a.k.a., affine) - Purity + Function Style */ - let purity = self.parse_unsafety(); + let fn_style = self.parse_unsafety(); let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many}; let lifetimes = if self.eat(&token::LT) { @@ -985,7 +985,7 @@ impl<'a> Parser<'a> { TyClosure(@ClosureTy { sigil: BorrowedSigil, region: region, - purity: purity, + fn_style: fn_style, onceness: onceness, bounds: bounds, decl: decl, @@ -993,11 +993,11 @@ impl<'a> Parser<'a> { }) } - pub fn parse_unsafety(&mut self) -> Purity { + pub fn parse_unsafety(&mut self) -> FnStyle { if self.eat_keyword(keywords::Unsafe) { return UnsafeFn; } else { - return ImpureFn; + return NormalFn; } } @@ -1045,7 +1045,7 @@ impl<'a> Parser<'a> { let vis_span = p.span; let vis = p.parse_visibility(); - let pur = p.parse_fn_purity(); + let style = p.parse_fn_style(); // NB: at the moment, trait methods are public by default; this // could change. let ident = p.parse_ident(); @@ -1071,7 +1071,7 @@ impl<'a> Parser<'a> { Required(TypeMethod { ident: ident, attrs: attrs, - purity: pur, + fn_style: style, decl: d, generics: generics, explicit_self: explicit_self, @@ -1089,7 +1089,7 @@ impl<'a> Parser<'a> { attrs: attrs, generics: generics, explicit_self: explicit_self, - purity: pur, + fn_style: style, decl: d, body: body, id: ast::DUMMY_NODE_ID, @@ -3754,11 +3754,11 @@ impl<'a> Parser<'a> { } // parse an item-position function declaration. - fn parse_item_fn(&mut self, purity: Purity, abi: abi::Abi) -> ItemInfo { + fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo { let (ident, generics) = self.parse_fn_header(); let decl = self.parse_fn_decl(false); let (inner_attrs, body) = self.parse_inner_attrs_and_block(); - (ident, ItemFn(decl, purity, abi, generics, body), Some(inner_attrs)) + (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs)) } // parse a method in a trait impl, starting with `attrs` attributes. @@ -3772,7 +3772,7 @@ impl<'a> Parser<'a> { let lo = self.span.lo; let visa = self.parse_visibility(); - let pur = self.parse_fn_purity(); + let fn_style = self.parse_fn_style(); let ident = self.parse_ident(); let generics = self.parse_generics(); let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| { @@ -3787,7 +3787,7 @@ impl<'a> Parser<'a> { attrs: attrs, generics: generics, explicit_self: explicit_self, - purity: pur, + fn_style: fn_style, decl: decl, body: body, id: ast::DUMMY_NODE_ID, @@ -4169,8 +4169,8 @@ impl<'a> Parser<'a> { let lo = self.span.lo; // Parse obsolete purity. - let purity = self.parse_fn_purity(); - if purity != ImpureFn { + let fn_style = self.parse_fn_style(); + if fn_style != NormalFn { self.obsolete(self.last_span, ObsoleteUnsafeExternFn); } @@ -4208,8 +4208,8 @@ impl<'a> Parser<'a> { } // parse safe/unsafe and fn - fn parse_fn_purity(&mut self) -> Purity { - if self.eat_keyword(keywords::Fn) { ImpureFn } + fn parse_fn_style(&mut self) -> FnStyle { + if self.eat_keyword(keywords::Fn) { NormalFn } else if self.eat_keyword(keywords::Unsafe) { self.expect_keyword(keywords::Fn); UnsafeFn @@ -4540,7 +4540,7 @@ impl<'a> Parser<'a> { // FUNCTION ITEM self.bump(); let (ident, item_, extra_attrs) = - self.parse_item_fn(ImpureFn, abi::Rust); + self.parse_item_fn(NormalFn, abi::Rust); let item = self.mk_item(lo, self.last_span.hi, ident, diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 44e95aa9573c0..b33f76a6047ef 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -186,11 +186,11 @@ pub fn path_to_str(p: &ast::Path) -> ~str { to_str(|s| s.print_path(p, false)) } -pub fn fun_to_str(decl: &ast::FnDecl, purity: ast::Purity, name: ast::Ident, +pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident, opt_explicit_self: Option, generics: &ast::Generics) -> ~str { to_str(|s| { - try!(s.print_fn(decl, Some(purity), abi::Rust, + try!(s.print_fn(decl, Some(fn_style), abi::Rust, name, generics, opt_explicit_self, ast::Inherited)); try!(s.end()); // Close the head box s.end() // Close the outer box @@ -479,7 +479,7 @@ impl<'a> State<'a> { ty_params: OwnedSlice::empty() }; try!(self.print_ty_fn(Some(f.abi), None, &None, - f.purity, ast::Many, f.decl, None, &None, + f.fn_style, ast::Many, f.decl, None, &None, Some(&generics), None)); } ast::TyClosure(f) => { @@ -488,7 +488,7 @@ impl<'a> State<'a> { ty_params: OwnedSlice::empty() }; try!(self.print_ty_fn(None, Some(f.sigil), &f.region, - f.purity, f.onceness, f.decl, None, &f.bounds, + f.fn_style, f.onceness, f.decl, None, &f.bounds, Some(&generics), None)); } ast::TyPath(ref path, ref bounds, _) => { @@ -567,10 +567,10 @@ impl<'a> State<'a> { try!(word(&mut self.s, ";")); try!(self.end()); // end the outer cbox } - ast::ItemFn(decl, purity, abi, ref typarams, body) => { + ast::ItemFn(decl, fn_style, abi, ref typarams, body) => { try!(self.print_fn( decl, - Some(purity), + Some(fn_style), abi, item.ident, typarams, @@ -861,7 +861,7 @@ impl<'a> State<'a> { try!(self.print_ty_fn(None, None, &None, - m.purity, + m.fn_style, ast::Many, m.decl, Some(m.ident), @@ -883,7 +883,7 @@ impl<'a> State<'a> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(meth.span.lo)); try!(self.print_outer_attributes(meth.attrs.as_slice())); - try!(self.print_fn(meth.decl, Some(meth.purity), abi::Rust, + try!(self.print_fn(meth.decl, Some(meth.fn_style), abi::Rust, meth.ident, &meth.generics, Some(meth.explicit_self.node), meth.vis)); try!(word(&mut self.s, " ")); @@ -1708,14 +1708,14 @@ impl<'a> State<'a> { pub fn print_fn(&mut self, decl: &ast::FnDecl, - purity: Option, + fn_style: Option, abi: abi::Abi, name: ast::Ident, generics: &ast::Generics, opt_explicit_self: Option, vis: ast::Visibility) -> IoResult<()> { try!(self.head("")); - try!(self.print_fn_header_info(opt_explicit_self, purity, abi, + try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, ast::Many, None, vis)); try!(self.nbsp()); try!(self.print_ident(name)); @@ -2024,7 +2024,7 @@ impl<'a> State<'a> { opt_abi: Option, opt_sigil: Option, opt_region: &Option, - purity: ast::Purity, + fn_style: ast::FnStyle, onceness: ast::Onceness, decl: &ast::FnDecl, id: Option, @@ -2040,12 +2040,12 @@ impl<'a> State<'a> { try!(word(&mut self.s, "proc")); } else if opt_sigil == Some(ast::BorrowedSigil) { try!(self.print_extern_opt_abi(opt_abi)); - try!(self.print_purity(purity)); + try!(self.print_fn_style(fn_style)); try!(self.print_onceness(onceness)); } else { try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi)); try!(self.print_opt_sigil(opt_sigil)); - try!(self.print_purity(purity)); + try!(self.print_fn_style(fn_style)); try!(self.print_onceness(onceness)); try!(word(&mut self.s, "fn")); } @@ -2294,10 +2294,10 @@ impl<'a> State<'a> { } } - pub fn print_opt_purity(&mut self, - opt_purity: Option) -> IoResult<()> { - match opt_purity { - Some(purity) => self.print_purity(purity), + pub fn print_opt_fn_style(&mut self, + opt_fn_style: Option) -> IoResult<()> { + match opt_fn_style { + Some(fn_style) => self.print_fn_style(fn_style), None => Ok(()) } } @@ -2338,7 +2338,7 @@ impl<'a> State<'a> { pub fn print_fn_header_info(&mut self, _opt_explicit_self: Option, - opt_purity: Option, + opt_fn_style: Option, abi: abi::Abi, onceness: ast::Onceness, opt_sigil: Option, @@ -2349,11 +2349,11 @@ impl<'a> State<'a> { try!(self.word_nbsp("extern")); try!(self.word_nbsp(abi.to_str())); - if opt_purity != Some(ast::ExternFn) { - try!(self.print_opt_purity(opt_purity)); + if opt_fn_style != Some(ast::ExternFn) { + try!(self.print_opt_fn_style(opt_fn_style)); } } else { - try!(self.print_opt_purity(opt_purity)); + try!(self.print_opt_fn_style(opt_fn_style)); } try!(self.print_onceness(onceness)); @@ -2361,9 +2361,9 @@ impl<'a> State<'a> { self.print_opt_sigil(opt_sigil) } - pub fn print_purity(&mut self, p: ast::Purity) -> IoResult<()> { - match p { - ast::ImpureFn => Ok(()), + pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> { + match s { + ast::NormalFn => Ok(()), ast::UnsafeFn => self.word_nbsp("unsafe"), ast::ExternFn => self.word_nbsp("extern") } @@ -2399,7 +2399,7 @@ mod test { variadic: false }; let generics = ast_util::empty_generics(); - assert_eq!(&fun_to_str(&decl, ast::ImpureFn, abba_ident, + assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident, None, &generics), &~"fn abba()"); } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 81e5e2280275f..5b376f4c5feb6 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -29,7 +29,7 @@ use owned_slice::OwnedSlice; pub enum FnKind<'a> { // fn foo() or extern "Abi" fn foo() - FkItemFn(Ident, &'a Generics, Purity, Abi), + FkItemFn(Ident, &'a Generics, FnStyle, Abi), // fn foo(&self) FkMethod(Ident, &'a Generics, &'a Method), @@ -207,8 +207,8 @@ pub fn walk_item>(visitor: &mut V, item: &Item, env: E) visitor.visit_ty(typ, env.clone()); visitor.visit_expr(expr, env); } - ItemFn(declaration, purity, abi, ref generics, body) => { - visitor.visit_fn(&FkItemFn(item.ident, generics, purity, abi), + ItemFn(declaration, fn_style, abi, ref generics, body) => { + visitor.visit_fn(&FkItemFn(item.ident, generics, fn_style, abi), declaration, body, item.span, diff --git a/src/test/compile-fail/trait-impl-method-mismatch.rs b/src/test/compile-fail/trait-impl-method-mismatch.rs index 039f94ec2e768..e64f76bb4cd77 100644 --- a/src/test/compile-fail/trait-impl-method-mismatch.rs +++ b/src/test/compile-fail/trait-impl-method-mismatch.rs @@ -17,7 +17,7 @@ trait Mumbo { impl Mumbo for uint { // Cannot have a larger effect than the trait: unsafe fn jumbo(&self, x: @uint) { *self + *x; } - //~^ ERROR expected impure fn but found unsafe fn + //~^ ERROR expected normal fn but found unsafe fn } fn main() {} From 83d2c0b8a6f6c2ce25fe48b541f176ea88be8d99 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 8 Apr 2014 14:31:25 -0700 Subject: [PATCH 26/28] rustc: Disallow importing through use statements Resolve is currently erroneously allowing imports through private `use` statements in some circumstances, even across module boundaries. For example, this code compiles successfully today: use std::c_str; mod test { use c_str::CString; } This should not be allowed because it was explicitly decided that private `use` statements are purely bringing local names into scope, they are not participating further in name resolution. As a consequence of this patch, this code, while valid today, is now invalid: mod test { use std::c_str; unsafe fn foo() { ::test::c_str::CString::new(0 as *u8, false); } } While plausibly acceptable, I found it to be more consistent if private imports were only considered candidates to resolve the first component in a path, and no others. Closes #12612 --- src/libnative/io/file_win32.rs | 2 +- src/librustc/front/test.rs | 14 ++++++++------ src/librustc/middle/resolve.rs | 22 +++++++++++++++++----- src/test/auxiliary/issue-12612-1.rs | 13 +++++++++++++ src/test/auxiliary/issue-12612-2.rs | 11 +++++++++++ src/test/compile-fail/issue-12612.rs | 24 ++++++++++++++++++++++++ src/test/run-pass/issue-11881.rs | 10 ++++------ src/test/run-pass/issue-12612.rs | 23 +++++++++++++++++++++++ 8 files changed, 101 insertions(+), 18 deletions(-) create mode 100644 src/test/auxiliary/issue-12612-1.rs create mode 100644 src/test/auxiliary/issue-12612-2.rs create mode 100644 src/test/compile-fail/issue-12612.rs create mode 100644 src/test/run-pass/issue-12612.rs diff --git a/src/libnative/io/file_win32.rs b/src/libnative/io/file_win32.rs index 8090042f090c9..de515659bf7ad 100644 --- a/src/libnative/io/file_win32.rs +++ b/src/libnative/io/file_win32.rs @@ -324,7 +324,7 @@ pub fn mkdir(p: &CString, _mode: io::FilePermission) -> IoResult<()> { } pub fn readdir(p: &CString) -> IoResult> { - use rt::global_heap::malloc_raw; + use std::rt::global_heap::malloc_raw; fn prune(root: &CString, dirs: Vec) -> Vec { let root = unsafe { CString::new(root.with_ref(|p| p), false) }; diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index 86d2e039505f1..dff3d8b03bcbf 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -297,20 +297,22 @@ mod __test { fn mk_std(cx: &TestCtxt) -> ast::ViewItem { let id_test = token::str_to_ident("test"); - let vi = if cx.is_test_crate { - ast::ViewItemUse( + let (vi, vis) = if cx.is_test_crate { + (ast::ViewItemUse( vec!(@nospan(ast::ViewPathSimple(id_test, path_node(vec!(id_test)), - ast::DUMMY_NODE_ID)))) + ast::DUMMY_NODE_ID)))), + ast::Public) } else { - ast::ViewItemExternCrate(id_test, + (ast::ViewItemExternCrate(id_test, with_version("test"), - ast::DUMMY_NODE_ID) + ast::DUMMY_NODE_ID), + ast::Inherited) }; ast::ViewItem { node: vi, attrs: Vec::new(), - vis: ast::Inherited, + vis: vis, span: DUMMY_SP } } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 95101dc63371a..cfacf0ee3df97 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -2286,10 +2286,12 @@ impl<'a> Resolver<'a> { } Some(child_name_bindings) => { if child_name_bindings.defined_in_namespace(ValueNS) { + debug!("(resolving single import) found value binding"); value_result = BoundResult(containing_module, *child_name_bindings); } if child_name_bindings.defined_in_namespace(TypeNS) { + debug!("(resolving single import) found type binding"); type_result = BoundResult(containing_module, *child_name_bindings); } @@ -2320,6 +2322,7 @@ impl<'a> Resolver<'a> { .borrow(); match import_resolutions.find(&source.name) { None => { + debug!("(resolving single import) no import"); // The containing module definitely doesn't have an // exported import with the name in question. We can // therefore accurately report that the names are @@ -2353,6 +2356,8 @@ impl<'a> Resolver<'a> { return UnboundResult; } Some(target) => { + debug!("(resolving single import) found \ + import in ns {:?}", namespace); let id = import_resolution.id(namespace); this.used_imports.insert((id, namespace)); return BoundResult(target.target_module, @@ -2396,6 +2401,8 @@ impl<'a> Resolver<'a> { .find_copy(&source.name) { None => {} // Continue. Some(module) => { + debug!("(resolving single import) found external \ + module"); let name_bindings = @Resolver::create_name_bindings_from_module( module); @@ -2669,7 +2676,8 @@ impl<'a> Resolver<'a> { match self.resolve_name_in_module(search_module, name, TypeNS, - name_search_type) { + name_search_type, + false) { Failed => { let segment_name = token::get_ident(name); let module_name = self.module_to_str(search_module); @@ -2977,7 +2985,8 @@ impl<'a> Resolver<'a> { match self.resolve_name_in_module(search_module, name, namespace, - PathSearch) { + PathSearch, + true) { Failed => { // Continue up the search chain. } @@ -3141,7 +3150,8 @@ impl<'a> Resolver<'a> { module_: @Module, name: Ident, namespace: Namespace, - name_search_type: NameSearchType) + name_search_type: NameSearchType, + allow_private_imports: bool) -> ResolveResult<(Target, bool)> { debug!("(resolving name in module) resolving `{}` in `{}`", token::get_ident(name), @@ -3172,7 +3182,9 @@ impl<'a> Resolver<'a> { // Check the list of resolved imports. match module_.import_resolutions.borrow().find(&name.name) { - Some(import_resolution) => { + Some(import_resolution) if allow_private_imports || + import_resolution.is_public.get() => { + if import_resolution.is_public.get() && import_resolution.outstanding_references.get() != 0 { debug!("(resolving name in module) import \ @@ -3193,7 +3205,7 @@ impl<'a> Resolver<'a> { } } } - None => {} // Continue. + Some(..) | None => {} // Continue. } // Finally, search through external children. diff --git a/src/test/auxiliary/issue-12612-1.rs b/src/test/auxiliary/issue-12612-1.rs new file mode 100644 index 0000000000000..a0234c1185a97 --- /dev/null +++ b/src/test/auxiliary/issue-12612-1.rs @@ -0,0 +1,13 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub mod bar { + pub fn foo() {} +} diff --git a/src/test/auxiliary/issue-12612-2.rs b/src/test/auxiliary/issue-12612-2.rs new file mode 100644 index 0000000000000..b4ae4374b2e58 --- /dev/null +++ b/src/test/auxiliary/issue-12612-2.rs @@ -0,0 +1,11 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub fn baz() {} diff --git a/src/test/compile-fail/issue-12612.rs b/src/test/compile-fail/issue-12612.rs new file mode 100644 index 0000000000000..9d6eb42567893 --- /dev/null +++ b/src/test/compile-fail/issue-12612.rs @@ -0,0 +1,24 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// aux-build:issue-12612-1.rs + +extern crate foo = "issue-12612-1"; + +use foo::bar; + +mod test { + use bar::foo; + //~^ ERROR: unresolved import + //~^^ ERROR: failed to resolve import +} + +fn main() {} + diff --git a/src/test/run-pass/issue-11881.rs b/src/test/run-pass/issue-11881.rs index 2bf846fe3419c..7e51c6ad2aebb 100644 --- a/src/test/run-pass/issue-11881.rs +++ b/src/test/run-pass/issue-11881.rs @@ -8,13 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern crate ser = "serialize"; +extern crate serialize; -use serialize = self::ser; - //necessary for deriving(Encodable) -use ser::{Encodable, Encoder}; -use ser::json; -use ser::ebml::writer; +use serialize::{Encodable, Encoder}; +use serialize::json; +use serialize::ebml::writer; use std::io::MemWriter; use std::str::from_utf8_owned; diff --git a/src/test/run-pass/issue-12612.rs b/src/test/run-pass/issue-12612.rs new file mode 100644 index 0000000000000..fcb658036b6b1 --- /dev/null +++ b/src/test/run-pass/issue-12612.rs @@ -0,0 +1,23 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// aux-build:issue-12612-1.rs +// aux-build:issue-12612-2.rs + +extern crate foo = "issue-12612-1"; +extern crate bar = "issue-12612-2"; + +use foo::bar; + +mod test { + use bar::baz; +} + +fn main() {} From df533c6e87f5052667b0c03c918f95b51439fdba Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 8 Apr 2014 15:03:29 -0700 Subject: [PATCH 27/28] rustc: Don't succeed on shadowed nonexistent import Previously resolve was checking the "import resolution" for whether an import had succeeded or not, but this was the same structure filled in by a previous import if a name is shadowed. Instead, this alters resolve to consult the local resolve state (as opposed to the shared one) to test whether an import succeeded or not. Closes #13404 --- src/liblibc/lib.rs | 2 +- src/librustc/middle/resolve.rs | 9 +++++++-- src/test/compile-fail/issue-13404.rs | 21 +++++++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 src/test/compile-fail/issue-13404.rs diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index 6b519fa7b83b7..18e815e9b7c03 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -146,7 +146,7 @@ pub use types::os::arch::c95::{c_ushort, clock_t, ptrdiff_t}; pub use types::os::arch::c95::{size_t, time_t}; pub use types::os::arch::c99::{c_longlong, c_ulonglong, intptr_t}; pub use types::os::arch::c99::{uintptr_t}; -pub use types::os::arch::posix88::{dev_t, dirent_t, ino_t, mode_t}; +pub use types::os::arch::posix88::{dev_t, ino_t, mode_t}; pub use types::os::arch::posix88::{off_t, pid_t, ssize_t}; pub use consts::os::c95::{_IOFBF, _IOLBF, _IONBF, BUFSIZ, EOF}; diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index cfacf0ee3df97..8240068979cbe 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -144,6 +144,12 @@ impl NamespaceResult { _ => false } } + fn is_unbound(&self) -> bool { + match *self { + UnboundResult => true, + _ => false + } + } } enum NameDefinition { @@ -2449,8 +2455,7 @@ impl<'a> Resolver<'a> { } } - if import_resolution.value_target.borrow().is_none() && - import_resolution.type_target.borrow().is_none() { + if value_result.is_unbound() && type_result.is_unbound() { let msg = format!("unresolved import: there is no \ `{}` in `{}`", token::get_ident(source), diff --git a/src/test/compile-fail/issue-13404.rs b/src/test/compile-fail/issue-13404.rs new file mode 100644 index 0000000000000..2ce502ee8dbb3 --- /dev/null +++ b/src/test/compile-fail/issue-13404.rs @@ -0,0 +1,21 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use a::f; +use b::f; +//~^ ERROR: unresolved import +//~^^ ERROR: failed to resolve import + +mod a { pub fn f() {} } +mod b { } + +fn main() { + f(); +} From 1f2c18a0afd55bf3a5319d9e3810ec1ac6b3e1bb Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 8 Apr 2014 15:10:41 -0700 Subject: [PATCH 28/28] rustc: Don't allow priv use to shadow pub use Previously, a private use statement would shadow a public use statement, all of a sudden publicly exporting the privately used item. The correct behavior here is to only shadow the use for the module in question, but for now it just reverts the entire name to private so the pub use doesn't have much effect. The behavior isn't exactly what we want, but this no longer has backwards compatibility hazards. --- src/librustc/middle/resolve.rs | 1 + src/libstd/io/test.rs | 1 - .../resolve-priv-shadowing-pub.rs | 33 +++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/test/compile-fail/resolve-priv-shadowing-pub.rs diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 8240068979cbe..38eab354f2bd8 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -1982,6 +1982,7 @@ impl<'a> Resolver<'a> { // the source of this name is different now resolution.type_id.set(id); resolution.value_id.set(id); + resolution.is_public.set(is_public); } None => { debug!("(building import directive) creating new"); diff --git a/src/libstd/io/test.rs b/src/libstd/io/test.rs index 14b9b5c1e061b..dd874fecc52a5 100644 --- a/src/libstd/io/test.rs +++ b/src/libstd/io/test.rs @@ -39,7 +39,6 @@ macro_rules! iotest ( use io::process::*; use unstable::running_on_valgrind; use str; - use util; fn f() $b diff --git a/src/test/compile-fail/resolve-priv-shadowing-pub.rs b/src/test/compile-fail/resolve-priv-shadowing-pub.rs new file mode 100644 index 0000000000000..0830722f96929 --- /dev/null +++ b/src/test/compile-fail/resolve-priv-shadowing-pub.rs @@ -0,0 +1,33 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +mod a { + pub fn foobar() -> int { 1 } +} + +mod b { + pub fn foobar() -> int { 2 } +} + +mod c { + // Technically the second use shadows the first, but in theory it should + // only be shadowed for this module. The implementation of resolve currently + // doesn't implement this, so this test is ensuring that using "c::foobar" + // is *not* getting b::foobar. Today it's an error, but perhaps one day it + // can correctly get a::foobar instead. + pub use a::foobar; + use b::foobar; +} + +fn main() { + assert_eq!(c::foobar(), 1); + //~^ ERROR: unresolved name `c::foobar` +} +